Files
msd-core/scripts/lint-phase-enumeration-drift.cjs
Tom Boucher 636ec92107 refactor(#3185): phase enumeration has one owner and a decidable scope (#3222)
* test(#3185): failing-first phase-enumeration single-owner suite

Covers the enumeration rows with direct code evidence: 999.* backlog dirs
listed by progress/stats, the phase-0 sentinel divergence, the #1324
letter-prefixed-decimal negative space, and the destructive-path find —
cmdPhasesClear carries a fifth sentinel copy (/^999(?:\.|$)/) that excludes
999 but not 0, so a 0-* directory roadmap.analyze preserves is deleted there.

Also covers the pass-all degrade, which is where the defect actually lives:
when the milestone window declares no phases the filter becomes a literal
() => true and its heading-side sentinel exclusion is unreachable. A fixture
carrying phase headings keeps the filter active and never reaches that path.

Named for the derivation, not a module: the suite drives commands, phase,
milestone, workstream-inventory and state, and both the phase and
phase-locator buckets are already at the per-module test-file cap.

Committed alone so the remote runner records the failure before the fix.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QELmgcSwcNBgbUs3kzJeqG

* refactor(#3185): phase enumeration has one owner and a decidable scope

Adds phase-locator.cts::listMilestonePhaseDirs as the single canonical owner
of "which phase directories belong to the current milestone". It applies the
milestone window AND the sentinel filter and returns a ScopedResult, so a
caller can tell a genuinely-empty milestone from an enumeration that could
not be scoped.

The sentinel test now runs against DIRECTORY NAMES and is unconditional.
getMilestonePhaseFilter excludes sentinels from its ROADMAP heading set, but
degrades to a literal () => true pass-all predicate when that set is empty --
at which point the heading set is never consulted and its sentinel exclusion
is unreachable exactly when it is needed. That degrade is the #3167 path, and
it is why stats already used the filter and still listed backlog directories.
The narrowing is sentinel-only: pass-all stays over-inclusive otherwise.

Sentinel copies deleted, canonical isSentinelPhaseId adopted:
  - cmdRoadmapAnalyze's local closure (parseInt === 0 || === 999), 2 call sites
  - cmdPhasesClear's /^999(?:\.|$)/ -- the DESTRUCTIVE path, which excluded
    999 but not 0, so a 0-* directory roadmap.analyze preserves was deleted

cmdStats also seeded rows from ROADMAP headings with no sentinel filter, so a
999 heading produced a row with no directory; that seed is filtered now.

cmdPhasesList routes only its ENUMERATION. --phase lookup searches the
physical set (scoping it would report an out-of-window phase as not found) and
--include-archived still merges archived dirs (they are by definition from
other milestones). Both exempt by documented reason, never a file allowlist.

Fixed inline, found while building: isDirInMilestone could not match a #1324
letter-prefixed-decimal directory (P0.0-foundation) to its own Phase P0.0
heading, so stats reported the phase with plans: 0 while its directory held
plan files. Defers to phase-id's extractPhaseToken rather than widening a
fourth bespoke regex; additive, so it can only admit directories.

Refs #3180. Closes #3185.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QELmgcSwcNBgbUs3kzJeqG

* refactor(#3185): route the last two enumeration re-derivations

workstream-inventory countRoadmapPhases counted every `Phase` heading across
the whole ROADMAP -- no window, no sentinel filter -- so it counted 999.*
backlog and Phase 0 and spanned every milestone the document ever had. Its own
caller already resolved a currentVersion and passed it to getMilestonePhaseFilter
elsewhere in the same file; this was the sibling copy that never got the fix.

state.cts phaseInventoryProvider enumerated phase dirs with its own
/^(\d+)-(.+)$/ convention regex and neither filter, so a rebuilt STATE.md
inventory carried backlog and sentinel directories as current-milestone phases.
A non-COMPLETE enumeration scope now throws to the outer catch as a real scan
failure rather than reporting a confident undercount, mirroring the per-phase
scanPhasePlans contract beside it.

Refs #3180 #3185.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QELmgcSwcNBgbUs3kzJeqG

* refactor(#3185): consolidate 23 sentinel re-derivations onto one predicate

The whole-repo drift guard (ADR-3180 Decision 4a, no file allowlist) found the
sentinel rule re-implemented 23 times across 8 modules, in three regex variants
plus four integer-comparison forms. Most tested 999 only, so Phase 0 slipped
through them while roadmap.analyze and the engine-wide convention (#1580) both
treat 0 and 999 alike. That disagreement is the defect class this epic removes.

All 23 now call phase-id's isSentinelPhaseId (SENTINEL_RANGES [0,999]). Sites:
init recommended-actions and backlog counts, milestone phase scan, the
phase-lifecycle progress table, phase.cts used-number collection and the four
renumber-on-remove guards, roadmap-parser's heading and bullet milestone
counts, roadmap get-phase fallbacks, and state's heading denominator.

Excluding Phase 0 at these sites is a deliberate behavior change and the point
of the consolidation — several carried comments already saying 0 should be
excluded while the literal beside them caught only 999.

Adds scripts/lint-phase-enumeration-drift.cjs, wired into lint:ci. It scans the
whole src/ tree with no file allowlist and reports both shapes: an independent
phases-dir enumeration, and an independent sentinel literal. Exemptions are
function-scoped with a written reason. The guard is comment-aware — its first
pass flagged JSDoc and a comment documenting that the code below uses the
canonical owner, which would have trained readers to exempt prose.

Refs #3180 #3185.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QELmgcSwcNBgbUs3kzJeqG

* refactor(#3185): resolve every phases-dir enumeration; drift guard reports zero

Per-site triage of the 31 remaining whole-repo guard hits, applying the rule
generalized from #3183's Amendment 1: a LOOKUP, DIAGNOSTIC, ARCHIVAL or
MUTATION pass wants the physical set; only "which phases belong to this
milestone" wants the scoped set.

Routed (10): init new-milestone phase_dir_count, init milestone-op fallback
count, init manager, init progress, milestone complete stats/dry-run/archive
move, phase complete's next-phase scan, state update-progress, state
frontmatter stats, and uat audit's active set.

Exempt with a written function-scoped reason (never a file allowlist): the
audit/UAT/verification sweeps that deliberately scan every directory to report
gaps, phase create/insert/rename/renumber mutations, single-phase lookups,
roadmap-upgrade's cross-milestone migration, cmdPhasesClear's whole-tree
destructive pass, and the reads that list a phase dir's FILES rather than
enumerating the phases dir at all.

Latent defects fixed by the routing: sentinel directories leaked into
cmdInitNewMilestone's phase_dir_count, cmdMilestoneComplete's stats, dry-run
AND ARCHIVE MOVE, cmdStateUpdateProgress, buildStateFrontmatter and
cmdAuditUat's active set — every one of those hand-rolled an isDirInMilestone
filter with no sentinel exclusion, so `milestone complete` was archiving
backlog directories.

scripts/lint-phase-enumeration-drift.cjs now reports 0 re-derivations and
npm run lint:ci is green.

Refs #3180 #3185.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QELmgcSwcNBgbUs3kzJeqG

* docs(#3185): document milestone-scoped enumeration and record ADR Amendment 3

Changeset fragment (Changed), CLI-TOOLS/COMMANDS/USER-GUIDE updates for the
scoped output of progress, stats, phases list, phases clear and milestone
complete, the CONTEXT.md Phase Locator glossary entry naming
listMilestonePhaseDirs, and ADR-3180 Amendment 3.

Amendment 3 records: the SCOPE contract held unchanged; the declared deviation
from Decision 1's provisional signature (the window needs cwd/ws, which the
locked roadmapContent parameter cannot supply); the copy count being a lower
bound for the third consecutive phase (4 scoped vs 54 found); the load-bearing
finding that the sentinel exclusion sat on the heading set and was unreachable
under the pass-all degrade; the two destructive-path defects; and the
generalized exemption rule.

Refs #3180 #3185.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QELmgcSwcNBgbUs3kzJeqG

* fix(#3185): wire scope to consumers; revert two wrong routings the suite caught

Review + remote runner findings, all fixed:

The three consumers computed the enumeration scope and threw it away, so
TRUNCATED/UNSCOPED/UNREADABLE collapsed into the same output as COMPLETE --
reproducing this epic's own output-identical-failure defect one layer up.
progress, stats and phases list now emit phase_scope (null on the phases list
--phase lookup path, which performs no enumeration).

Two routings were wrong and the suite proved it:

roadmap-parser's two milestone phase-count scans are reverted to the 999-only
literal. isSentinelPhaseId is BROADER than what it replaced: its legacy branch
runs /^0*(\d+)/ over "00.1", which backtracks to capture 0, so it read #2554's
decimal phase ids as sentinel milestone 0 and stopped counting them.

state.cts phaseInventoryProvider is reverted to the physical disk scan.
`state rebuild` is a RECONCILIATION pass -- scoping it made it throw on healthy
trees whose fixture resolves no window, swallowed the raw readdirSync fault
message #3057 B1 requires verbatim, and stopped it dropping orphan STATE.md
rows, which is the job.

Both are now function-scoped guard exemptions with written reasons, not
silent reverts. This is the consolidation trap named in the epic: a canonical
rule can cover MORE than the copy it replaces, and only real inputs show it.

Adds phases list coverage, a scope-branch test, and a drift-guard unit suite;
backports comment-awareness to the milestone-window and plan-count guards so
all three siblings share one false-positive profile; names #3161 alongside
#3167 in Amendment 3's subsumption record.

Refs #3180 #3185.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QELmgcSwcNBgbUs3kzJeqG

* fix(#3185): correct isSentinelPhaseId's decimal-zero misclassification

An isolated security review caught this branch committing the epic's own sin:
the over-broad predicate was worked around at ONE call site and left live at
the destructive ones.

isSentinelPhaseId's legacy branch ran /^0*(\d+)/, which backtracks so any id
whose leading digit run is all zeros before a non-digit captures 0 -- "0.1",
"00.1" and "0.2554" all read as sentinel milestone 0. Two pinned contracts
disagree with that: #2554 requires "00.1" to be counted as a real phase, and
the 999 icebox is a whole reserved milestone so "999.1" must stay sentinel.

The rule is asymmetric and now says so explicitly: 999 is sentinel with or
without a decimal part; 0 is sentinel only when bare. A decimal phase under
either is a real phase for 0 and reserved for 999, because 999 reserves a
MILESTONE while 0 reserves a PHASE.

Fixing the owner lets the earlier workaround go: getMilestonePhaseFilter's two
scans route through isSentinelPhaseId again and the guard exemption that
existed only to accommodate the defect is deleted. The state.cts cmdStateRebuild
exemption stays -- that one is a genuine reconciliation-wants-the-physical-set
case.

Also corrects tests/adr-612-bracket-grammar.test.cjs, which asserted
isSentinelPhaseId('0.1') === true and so had encoded the defect as expected
behavior.

Refs #3180 #3185.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QELmgcSwcNBgbUs3kzJeqG

* fix(#3185): keep isSentinelPhaseId's semantics — 0.x is layered, not wrong

Reverts the previous commit. The remote suite failed six tests proving it
wrong, and the reason is the sharpest finding of this phase.

An isolated security review observed that isSentinelPhaseId reads 0.1 and 00.1
as sentinel milestone 0 and judged that a defect against #2554. Correcting the
canonical predicate broke #2949. Both contracts are pinned and both are right,
because they ask different questions:

  #2554  is this dir part of the current milestone's phase SET?  -> count 00.1
  #2949  must this phase COMPLETE before the milestone closes?   -> 0.x sentinel

No single global predicate answers both. isSentinelPhaseId keeps its semantics
(0.x IS a sentinel, #2949), and the milestone-window layer keeps a narrower
999-only rule (#2554) as a function-scoped guard exemption with a written
reason — not a second silent copy.

That corrects how Decision 1 reads: "one owner per derivation" governs who
computes an answer, not how many questions share it. An over-broad canonical
rule is as much a defect as a divergent copy and fails worse, because it looks
like consolidation. Recorded in Amendment 3 as the lesson for Phases 4 and 5.

Where a review's inference about intent conflicts with a pinned contract, the
pinned contract wins; the finding is adjudicated, not fixed.

The boundary tables in the enumeration suite are corrected to assert 0.x IS a
sentinel, with the layering explained.

Refs #3180 #3185.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QELmgcSwcNBgbUs3kzJeqG

* chore(#3185): set changeset fragment pr to 3222

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QELmgcSwcNBgbUs3kzJeqG

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 14:22:10 -04:00

458 lines
25 KiB
JavaScript

#!/usr/bin/env node
'use strict';
/**
* Anti-divergence drift guard for the PHASE-ENUMERATION seam (epic #3180,
* issue #3185, ADR-3180 Decision 1 row "Phase enumeration").
*
* `src/phase-locator.cts` is the SINGLE canonical owner of "which phase
* directories belong to the current milestone" — `listMilestonePhaseDirs`.
* `src/phase-id.cts` is the SINGLE canonical owner of "is this phase id a
* reserved sentinel (Phase 0 / Phase 999.x)" — `isSentinelPhaseId` /
* `SENTINEL_RANGES`. Before these existed the derivation had four
* independent implementations, and the sentinel rule had five copies across
* three different regexes that disagreed about Phase 0 (see
* `listMilestonePhaseDirs`'s own doc comment). Every other module that
* hand-rolls a `readdirSync` over the phases directory, or hand-rolls a
* `999`-shaped sentinel test, is a re-derivation that can silently drift
* from one of these two owners — the same generative-fix-divergence class
* `lint-plan-count-drift.cjs` and `lint-milestone-window-drift.cjs` exist to
* remove, now applied to the phase-enumeration seam.
*
* Per ADR-3180 Decision 4(a) this guard discovers call sites by SCANNING THE
* WHOLE `src/` TREE, not by consulting an allowlist of known files — an
* allowlist only measures re-derivations in files someone remembered to
* list. Exemptions below are FUNCTION-SCOPED with a written reason, never a
* bare file allowlist, mirroring `lint-plan-count-drift.cjs`'s and
* `lint-milestone-window-drift.cjs`'s precedent.
*
* TWO INDEPENDENT DETECTORS. A line matching EITHER is a violation:
*
* DETECTOR 1 (enumeration): a single source line carrying BOTH
* (a) `readdirSync`, AND
* (b) a phases-directory token — the identifier `phasesDir`, or a
* quoted/backticked `'phases'` string.
* This is the shape every consumer used before routing through the owner.
*
* DETECTOR 2 (sentinel): a single source line carrying a sentinel-range
* literal outside the owner —
* - a bare `999` inside a regex literal or a quoted/backticked string
* (e.g. `/^999\b/`, `/^999(?:\.|$)/`, `'999'`), OR
* - a numeric comparison against 999 (`=== 999`, `== 999`, `!== 999`),
* or a bare reference to `SENTINEL_RANGES` outside its owner.
* Deliberately NARROW, mirroring the sibling guards' token discipline: the
* `999` must be a STANDALONE digit run (no digit immediately before or
* after it, inside the literal or right after the comparison operator), so
* unrelated arithmetic (`total + 1999`, `=== 9990`) never fires — only a
* line that actually spells the reserved sentinel value fires.
*
* Owner files (exempt by construction — each not only DEFINES its half of
* the grammar but composes it at internal call sites that are the canonical
* implementation, not copies of it):
* - `src/phase-locator.cts` — defines `listMilestonePhaseDirs`, the
* enumeration owner, and legitimately calls `readdirSync` on the phases
* dir inside it.
* - `src/phase-id.cts` — defines `isSentinelPhaseId` and
* `SENTINEL_RANGES`, the sentinel owner.
*
* FUNCTION-SCOPED EXEMPTIONS (per ADR-3180 Decision 4(a) — a written reason,
* never a bare file allowlist, so an unrelated re-derivation added anywhere
* ELSE in these same files is still caught). Generalizing #3183's rule ("a
* diagnostic about file NAMING wants the physical set; only a question about
* outstanding WORK wants the live set"): a LOOKUP, DIAGNOSTIC or ARCHIVAL
* pass wants the physical set; only "which phases belong to this milestone"
* wants the scoped set.
* - `src/roadmap.cts` `cmdRoadmapAnalyze`: builds `_phaseDirNames` as a
* heading->directory LOOKUP INDEX, not a milestone enumeration. It must
* see the PHYSICAL set so a heading already scoped by
* `extractCurrentMilestoneScoped` can find its directory; filtering it
* through the owner would scope the same set twice.
* - `src/verify.cts` `collectDiskPhases`: a DRIFT DIAGNOSTIC comparing
* what is on disk against what the ROADMAP declares. It wants the
* physical set by definition — scoping it would make the diagnostic
* unable to see the very drift it exists to report.
* - `src/verify.cts` `cmdValidateHealth`: a project-wide HEALTH-CHECK sweep
* (config drift, phase-directory naming, duplicate-directory collisions,
* unsummarized-plan detection) — same "sweep everything, report gaps"
* shape as `collectDiskPhases` and the `audit.cts` scanners; it must see
* every phase directory regardless of milestone window to catch a
* naming/duplicate defect wherever it lives.
* - `src/verify.cts` `cmdVerifySchemaDrift`: resolves ONE caller-supplied
* `phase` argument to its directory (falling back to an exact-name
* match) — a single-phase LOOKUP, not a current-milestone enumeration.
* - `src/init.cts` `detectHasPriorPhases`: answers "has this project EVER
* completed a phase", explicitly excluding the current one. A history
* probe across all milestones, not a current-milestone enumeration.
* - `src/init.cts` `detectUiPhaseActive`: its `readdirSync` targets a
* SINGLE already-resolved phase directory's own FILES
* (`phases/<dirName>`) to check for a `*-UI-SPEC.md` file — not the
* phases directory itself. It never enumerates which phases exist at
* all, so it is not this derivation, only shaped like it textually.
* - `src/init.cts` `cmdInitMilestoneOp`: `diskPhaseDirs` is a heading->
* directory LOOKUP INDEX (same role as `cmdRoadmapAnalyze`'s
* `_phaseDirNames` below) — the ROADMAP heading scan just above it
* already scopes `roadmapPhaseNumbers` to the current milestone, so this
* map must see the PHYSICAL set to resolve each heading's phase number
* to its actual directory name; scoping it again would look up inside
* an already-scoped set for no benefit. Its sibling readdirSync (the
* no-ROADMAP-headings-found fallback, where there is no heading scope
* to look inside) is a real current-milestone enumeration and is routed
* through the owner, not exempted.
* - `src/milestone.cts` `archivePhaseDirectories`: archival MOVES the
* physical set. Scoping it would silently leave out-of-window
* directories behind in the live tree.
* - `src/milestone.cts` `cmdMilestoneComplete`: its one remaining
* unrouted readdirSync (`phaseDirEntries`, the unstarted-phase guard)
* is a token-match LOOKUP against ROADMAP headings already scoped by
* `sliceMilestoneWindow`/`extractCurrentMilestone` above it — same
* "physical set feeds an already-scoped lookup" shape as
* `cmdRoadmapAnalyze`'s `_phaseDirNames`. Its three OTHER former
* readdirSync call sites (the stats aggregation, the dry-run archive
* preview, and the real archive-move loop) all genuinely asked "which
* phases belong to the current milestone" and are routed through the
* owner with the resolved `version` as `versionOverride`.
* - `src/milestone.cts` `cmdPhasesClear`: a destructive CLEAR that must
* remove every live phase directory except sentinels, regardless of
* milestone window — `new-milestone` runs this to wipe the ENTIRE
* phases tree before starting fresh, not just the outgoing milestone's
* slice. Scoping it to one milestone's window would silently leave
* out-of-window directories behind instead of clearing/archiving them.
* - `src/phase.cts` `cmdPhasesList`: its `--phase <n>` lookup and
* `--include-archived` merge are phase LOCATION and archive
* enumeration, not current-milestone enumeration; both legitimately
* read the physical set. Its ENUMERATION path routes through the owner.
* - `src/roadmap-parser.cts` `getMilestonePhaseFilter`: its two heading/
* bullet scans that seed `milestonePhaseNums` deliberately use the local
* `999`-only literal, NOT `isSentinelPhaseId`. That canonical predicate
* additionally treats a leading `0` as sentinel milestone 0 (via its
* `/^0*(\d+)/` backtrack), which would swallow #2554's decimal phase ids
* ("00.1" is a real phase, not milestone 0). This scan asks a narrower
* question — "which phase ids does this milestone's window declare" —
* where only the 999 icebox range is excluded.
* - `src/state.cts` `cmdStateValidate` ("Gate 1: Validate STATE.md against
* filesystem"): resolves ONE directory — the disk match for STATE.md's
* own `Current Phase` field — by prefix, a single-phase LOOKUP, not an
* enumeration of the current milestone's phase set.
* - `src/state.cts` `cmdStateSync` ("Gate 2: Sync STATE.md from filesystem
* ground truth"): a ground-truth RECONCILIATION pass, same family as
* `collectDiskPhases` below — it deliberately scans every phase
* directory on disk (minus #1514 retired-phase exclusion) so STATE.md's
* rewritten counters reflect the true disk state, not a re-derivation of
* "which phases belong to the current milestone" the way its sibling
* `buildStateFrontmatter` computes (that one IS routed through the
* owner, scoped to the stored milestone, because it exists specifically
* to answer the milestone-scoped question at STATE.md construction
* time).
* - `src/state.cts` `cmdStateRebuild`: its nested `phaseInventoryProvider`
* deliberately does NOT route through `listMilestonePhaseDirs`. `state
* rebuild` is a RECONCILIATION pass against ground truth — it must see
* every phase directory on disk so an orphan STATE.md row for a phase
* that no longer exists (or sits outside the current milestone window) is
* dropped. Scoping this enumeration would make the rebuild silently
* preserve stale rows instead of dropping them, and a non-`readdirSync`-
* shaped owner call also cannot propagate the original fault message the
* #3057 B1 contract requires to surface verbatim.
* - `src/phase.cts` `cmdPhaseNextDecimal`: computes the next free decimal
* sub-phase id (e.g. `2.3`) by scanning EVERY on-disk directory and the
* WHOLE ROADMAP (not milestone-scoped) for existing `2.N` ids — an id
* collision it must avoid can come from any milestone, so it needs the
* physical set, matching the CREATE-adjacent exemption category.
* - `src/phase.cts` `cmdPhasePlanIndex`: resolves ONE caller-supplied
* `phase` id to its directory — a single-phase LOCATION lookup, not an
* enumeration of the current milestone's phase set.
* - `src/phase.cts` `cmdPhaseInsert`: the same next-free-decimal-id scan as
* `cmdPhaseNextDecimal` (id collisions can come from any milestone),
* immediately followed by creating the new phase directory — a CREATE
* operation, physical set by definition.
* - `src/phase.cts` `renameDecimalPhases`, `renameIntegerPhases`: RENAME
* mutations. Each `readdirSync` targets a SINGLE just-renamed phase
* directory's own FILES (`phasesDir/newDirName`) to rename the files
* inside it to match — not an enumeration of the phases directory at
* all; only shaped like one because `phasesDir` is a substring of the
* joined path.
* - `src/audit.cts` `scanUatGaps`, `scanVerificationGaps`,
* `scanContextQuestions`, `scanDeferredItems`: the pre-milestone-close
* audit gate (`gsd-tools.cjs audit-open`, called by `/gsd:complete-
* milestone`'s pre-close gate). Each deliberately SWEEPS EVERY phase
* directory on disk to report open UAT/VERIFICATION/CONTEXT/deferred-item
* gaps — the audit's whole purpose is catching stragglers before a
* milestone closes, so scoping it to the current milestone's window
* would hide exactly the drift (e.g. a still-open item in a phase that
* somehow fell outside the window) it exists to surface.
* - `src/roadmap-upgrade.cts` `computeMigrationPlan`: a legacy-id-to-
* milestone-prefixed-id MIGRATION. It must see and rename EVERY existing
* phase directory across every milestone in one pass (a legacy phase
* number can legitimately collide across milestones — that ambiguity is
* exactly what the migration resolves) — the physical set by definition.
* - `src/smart-entry.cts` `detectVerifyFailed`: resolves ONE phase — the
* current phase from STATE.md, falling back to the highest-numbered
* directory when STATE.md has none — to check its own verify/UAT
* artifacts. A single-phase LOOKUP (with an explicit fallback rule of
* its own), not a current-milestone enumeration.
* - `src/commands.cts` `cmdHistoryDigest`: explicitly builds `allPhaseDirs`
* as archived-milestone dirs (via `getArchivedPhaseDirs`) PLUS every
* live phase directory, to produce a project-wide historical digest
* spanning every milestone ever shipped — the union is a strict
* superset of any one milestone's window by design; scoping the live
* half would silently drop history the digest exists to preserve.
*
* The tree-walk / root-confinement / regex-literal-tokenizer / sanitizer
* machinery is SHARED with the sibling drift guards via
* `scripts/lib/drift-scan.cjs` (ADR-3180 Decision 4) — see that module for
* the `isInsideRoot` case-sensitivity note, the `walk` symlink-confinement
* rationale, and the `readRegexLiteralAt` ReDoS-avoidance rationale.
* `readStringLiteralAt` below is the same style, written locally for
* quoted/backticked strings, mirroring `lint-milestone-window-drift.cjs`'s
* own local copy (not shared — each guard's literal-bearing shape differs).
*
* KNOWN, ACCEPTED limits of a per-line textual scan (same tradeoff the
* sibling drift guards document): a re-derivation whose detector tokens are
* split across two DIFFERENT lines with no single line carrying both is not
* caught by this narrow shape. That is left to code review and the design's
* identity tests, not this regex.
*/
const path = require('node:path');
const driftScan = require('./lib/drift-scan.cjs');
const { readRegexLiteralAt, MAX_REGEX_LITERAL_LEN, sanitizeForReport, scanTree } = driftScan;
// (1a) The enumeration primitive itself.
const READDIR_SYNC_RE = /readdirSync/;
// (1b1) The phases-directory identifier every routed call site used to bind
// its `readdirSync` target to.
const PHASES_DIR_ID_RE = /\bphasesDir\b/;
// (1b2) A quoted/backticked `'phases'` string — the other shape a phases-dir
// path segment takes at a call site that builds the path inline instead of
// through a `phasesDir` local.
const PHASES_STRING_RE = /['"`]phases['"`]/;
// (2b) A numeric comparison against the sentinel value, or a bare reference
// to the owner's exported range constant used outside the owner. The digit
// run is anchored on both sides (`\b`, and no digit can precede it inside
// the `\s*` gap immediately after the operator) so `=== 9990` / `=== 19999`
// never fire — only the standalone value `999` does.
const SENTINEL_COMPARISON_RE = /(?:===|==|!==)\s*999\b|\bSENTINEL_RANGES\b/;
// A standalone `999` inside an already-located literal's text: no digit
// immediately before or after, so `1999`/`9990`/`19999` inside a string or
// regex literal never fire — only the literal spelling of the reserved
// sentinel value does.
const STANDALONE_999_RE = /(?<!\d)999(?!\d)/;
// Authored TypeScript source only (the generated bin/lib/*.cjs mirror it).
const SCAN_DIRS = ['src'];
const SCAN_EXT = new Set(['.cts', '.ts', '.mts']);
// The two canonical owners; each defines and internally composes its half
// of the grammar and is exempt by construction (see header comment).
const OWNER_FILES = new Set([
path.join('src', 'phase-locator.cts'),
path.join('src', 'phase-id.cts'),
]);
// Per ADR-3180 Decision 4(a): NOT a bare file allowlist — each entry below
// is scoped to the SPECIFIC function asking a documented, DIFFERENT
// question, so an unrelated re-derivation added anywhere else in these same
// files is still caught. Mirrors `lint-plan-count-drift.cjs`'s and
// `lint-milestone-window-drift.cjs`'s FUNCTION_SCOPED_EXEMPTIONS mechanism.
// See the header comment for the full written reason behind each entry.
const FUNCTION_SCOPED_EXEMPTIONS = new Map([
[path.join('src', 'roadmap.cts'), new Set(['cmdRoadmapAnalyze'])],
[path.join('src', 'verify.cts'), new Set(['collectDiskPhases', 'cmdValidateHealth', 'cmdVerifySchemaDrift'])],
[path.join('src', 'init.cts'), new Set(['detectHasPriorPhases', 'detectUiPhaseActive', 'cmdInitMilestoneOp'])],
[path.join('src', 'milestone.cts'), new Set(['archivePhaseDirectories', 'cmdMilestoneComplete', 'cmdPhasesClear'])],
[path.join('src', 'phase.cts'), new Set(['cmdPhasesList', 'cmdPhaseNextDecimal', 'cmdPhasePlanIndex', 'cmdPhaseInsert', 'renameDecimalPhases', 'renameIntegerPhases'])],
[path.join('src', 'audit.cts'), new Set(['scanUatGaps', 'scanVerificationGaps', 'scanContextQuestions', 'scanDeferredItems'])],
[path.join('src', 'commands.cts'), new Set(['cmdHistoryDigest'])],
[path.join('src', 'state.cts'), new Set(['cmdStateValidate', 'cmdStateSync', 'cmdStateRebuild'])],
[path.join('src', 'roadmap-upgrade.cts'), new Set(['computeMigrationPlan'])],
[path.join('src', 'smart-entry.cts'), new Set(['detectVerifyFailed'])],
[path.join('src', 'roadmap-parser.cts'), new Set(['getMilestonePhaseFilter'])],
]);
// Optional `export ` modifier, mirroring the sibling guards' function
// tracker — only a column-0 top-level `function` declaration updates the
// current-function tracker; a nested/arrow function does not reset it,
// matching every FUNCTION_SCOPED_EXEMPTIONS entry above (all top-level
// `function` declarations).
const TOP_LEVEL_FUNCTION_RE = /^(?:export\s+)?function\s+([A-Za-z0-9_]+)\s*\(/;
/**
* Read the quoted or backtick-delimited string/template literal starting at
* `line[start]` (which must be `'`, `"`, or `` ` ``). Returns `{ text, end }`
* — `text` includes both delimiters, `end` is the index one past the literal
* — or null if no matching close quote is found within MAX_REGEX_LITERAL_LEN
* characters. Same single left-to-right, no-backtracking, escape-aware style
* as the shared `readRegexLiteralAt` (`\x` escapes consume both characters,
* so an escaped quote never terminates the literal early) — written locally,
* mirroring `lint-milestone-window-drift.cjs`'s own copy (not shared — each
* guard's literal-bearing shape differs).
*/
function readStringLiteralAt(line, start) {
const quote = line[start];
if (quote !== "'" && quote !== '"' && quote !== '`') return null;
const limit = Math.min(line.length, start + MAX_REGEX_LITERAL_LEN);
for (let i = start + 1; i < limit; i++) {
const ch = line[i];
if (ch === '\\') {
i++; // escape consumes the next character, whatever it is
continue;
}
if (ch === '\r' || ch === '\n') return null; // a literal cannot span lines in this per-line scan
if (ch === quote) return { text: line.slice(start, i + 1), end: i + 1 };
}
return null;
}
/**
* True when `line` contains a regex-literal or quoted/backtick-string
* literal whose text carries a STANDALONE `999` (see STANDALONE_999_RE).
*/
function hasSentinelLiteral(line) {
for (let i = 0; i < line.length; i++) {
const ch = line[i];
let literal = null;
if (ch === '/') literal = readRegexLiteralAt(line, i);
else if (ch === "'" || ch === '"' || ch === '`') literal = readStringLiteralAt(line, i);
if (!literal) continue;
if (STANDALONE_999_RE.test(literal.text)) return true;
i = literal.end - 1; // resume scanning just past this literal
}
return false;
}
/**
* The first literal (regex OR quoted/backtick string) on `line` whose text
* contains a STANDALONE `999` or the exact `'phases'` token — the "smoking
* gun" fragment worth reporting, mirroring `extractFragment`'s role in
* `lint-milestone-window-drift.cjs`. Falls back to a bounded, trimmed slice
* of the raw line when neither is inside a located literal (the
* `phasesDir` identifier / `SENTINEL_RANGES` / bare numeric-comparison
* shapes never are).
*/
function extractFragment(line) {
for (let i = 0; i < line.length; i++) {
const ch = line[i];
let literal = null;
if (ch === '/') literal = readRegexLiteralAt(line, i);
else if (ch === "'" || ch === '"' || ch === '`') literal = readStringLiteralAt(line, i);
if (!literal) continue;
if (STANDALONE_999_RE.test(literal.text) || /^['"`]phases['"`]$/.test(literal.text)) return literal.text;
i = literal.end - 1; // resume scanning just past this literal
}
return line.trim().slice(0, MAX_REGEX_LITERAL_LEN);
}
/**
* Strip comment text from a line before detection. A guard that fires on a
* COMMENT — including a comment documenting that the code below uses the
* canonical owner — reports prose as drift and trains readers to add
* exemptions for documentation. Handles the three shapes that appear in this
* codebase: a whole-line block-comment continuation (`*` or `/*` leading), a
* `//` line comment, and a trailing `//` after code.
*
* Deliberately simple and conservative: it does not attempt full block-comment
* state tracking across lines (this is a per-line scan, same tradeoff the
* sibling guards document). A `//` inside a string literal would be stripped
* early — accepted, because the effect is to UNDER-report on a pathological
* line, never to over-report prose as drift.
*/
function stripComments(line) {
const trimmed = line.trim();
// Whole-line block comment or JSDoc continuation.
if (trimmed.startsWith('*') || trimmed.startsWith('/*') || trimmed.startsWith('//')) return '';
// Trailing line comment after code.
const idx = line.indexOf('//');
return idx === -1 ? line : line.slice(0, idx);
}
/**
* Pure: find every unsanctioned phase-enumeration re-derivation in `text`.
* `relPath` is the repo-relative path, used both to report file:line and to
* apply the narrow, function-scoped exemptions above.
* Returns [{ line, found }].
*/
function findPhaseEnumerationDrift(text, relPath) {
const out = [];
const lines = text.split('\n');
const exemptFunctions = FUNCTION_SCOPED_EXEMPTIONS.get(relPath) || null;
let currentFunction = null;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const fnMatch = TOP_LEVEL_FUNCTION_RE.exec(line);
if (fnMatch) currentFunction = fnMatch[1];
const code = stripComments(line);
if (!code.trim()) continue;
const isEnumerationDrift = READDIR_SYNC_RE.test(code) && (PHASES_DIR_ID_RE.test(code) || PHASES_STRING_RE.test(code));
const isSentinelDrift = SENTINEL_COMPARISON_RE.test(code) || hasSentinelLiteral(code);
if (!isEnumerationDrift && !isSentinelDrift) continue;
if (exemptFunctions && exemptFunctions.has(currentFunction)) continue;
out.push({ line: i + 1, found: extractFragment(line) });
}
return out;
}
/**
* Scan the authored source tree and return every unsanctioned re-derivation,
* each annotated with the repo-relative file path.
*/
function scanRepo(root) {
return scanTree({
root,
scanDirs: SCAN_DIRS,
scanExt: SCAN_EXT,
onFile(rel, text) {
// `rel` is already the REAL (canonical) path (scanTree resolves
// symlinks before calling onFile), so this comparison — and
// FUNCTION_SCOPED_EXEMPTIONS above, also keyed on `rel` — match
// consistently regardless of which symlink reached the file.
if (OWNER_FILES.has(rel)) return [];
return findPhaseEnumerationDrift(text, rel).map((d) => ({ file: rel, ...d }));
},
});
}
function main() {
const root = path.join(__dirname, '..');
const violations = scanRepo(root);
if (violations.length === 0) {
process.stdout.write('ok phase-enumeration-drift: no unsanctioned phase-enumeration re-derivations outside phase-locator.cts / phase-id.cts\n');
return;
}
process.stderr.write('phase-enumeration-drift: independent re-derivation(s) of phase enumeration found.\n');
process.stderr.write('Use src/phase-locator.cjs `listMilestonePhaseDirs` instead of re-deriving a phases-directory\n');
process.stderr.write('readdirSync, and src/phase-id.cjs `isSentinelPhaseId` instead of re-deriving a `999` sentinel test:\n');
for (const d of violations) {
// `d.file` is exactly as attacker-controlled as `d.found`: a repo can
// legally track a filename containing control bytes / bidi overrides,
// and it is a fork-PR-authored value reaching a CI log the same way the
// matched literal does — sanitize it at the same reporting boundary.
process.stderr.write(` ${sanitizeForReport(d.file)}:${d.line} ${sanitizeForReport(d.found)}\n`);
}
process.exitCode = 1;
}
if (require.main === module) main();
module.exports = {
findPhaseEnumerationDrift,
scanRepo,
READDIR_SYNC_RE,
PHASES_DIR_ID_RE,
PHASES_STRING_RE,
SENTINEL_COMPARISON_RE,
STANDALONE_999_RE,
OWNER_FILES,
FUNCTION_SCOPED_EXEMPTIONS,
readStringLiteralAt,
hasSentinelLiteral,
extractFragment,
stripComments,
};