* 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>
This commit is contained in:
@@ -21,13 +21,13 @@ import coreUtilsMod = require('./core-utils.cjs');
|
||||
const { toPosixPath, generateSlugInternal, extractOneLinerFromBody } = coreUtilsMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import phaseIdMod = require('./phase-id.cjs');
|
||||
const { normalizePhaseName, comparePhaseNum, extractPhaseToken, PHASE_NUMBER_TOKEN_SOURCE } = phaseIdMod;
|
||||
const { normalizePhaseName, comparePhaseNum, extractPhaseToken, PHASE_NUMBER_TOKEN_SOURCE, isSentinelPhaseId } = phaseIdMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import phaseLocatorMod = require('./phase-locator.cjs');
|
||||
const { getArchivedPhaseDirs, findPhaseInternal } = phaseLocatorMod;
|
||||
const { getArchivedPhaseDirs, findPhaseInternal, listMilestonePhaseDirs } = phaseLocatorMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import roadmapParserMod = require('./roadmap-parser.cjs');
|
||||
const { extractCurrentMilestone, stripShippedMilestones: _stripShippedMilestones, getMilestoneInfo, getMilestonePhaseFilter, getRoadmapPhaseInternal } = roadmapParserMod;
|
||||
const { extractCurrentMilestone, stripShippedMilestones: _stripShippedMilestones, getMilestoneInfo, getRoadmapPhaseInternal } = roadmapParserMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import modelResolverMod = require('./model-resolver.cjs');
|
||||
const { resolveModelInternal, resolveModelForTier, resolveProviderEscalation, resolveEffortInternal, resolveFastModeInternal, resolveEffortForTier, resolveGranularityInternal, assertValidGranularityOverride } = modelResolverMod;
|
||||
@@ -1565,10 +1565,16 @@ function cmdProgressRender(cwd: string, format: string | undefined, raw: boolean
|
||||
const phases: PhaseProgress[] = [];
|
||||
let totalPlans = 0;
|
||||
let totalSummaries = 0;
|
||||
let phaseScope: string | null = null;
|
||||
|
||||
try {
|
||||
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
const dirs = entries.filter(e => e.isDirectory()).map(e => e.name).sort((a, b) => comparePhaseNum(a, b));
|
||||
// #3185 (ADR-3180 Decision 1): the single owner applies the milestone
|
||||
// window AND the sentinel filter and returns dirs already sorted by
|
||||
// comparePhaseNum. This command previously read the phases directory
|
||||
// directly with neither, which is why `query progress` listed 999.*
|
||||
// backlog directories as current-milestone phases (#3167).
|
||||
const { value: dirs, scope } = listMilestonePhaseDirs(phasesDir, { cwd });
|
||||
phaseScope = scope;
|
||||
|
||||
for (const dir of dirs) {
|
||||
const dm = dir.match(/^(\d+(?:\.\d+)*)-?(.*)/);
|
||||
@@ -1619,6 +1625,9 @@ function cmdProgressRender(cwd: string, format: string | undefined, raw: boolean
|
||||
total_plans: totalPlans,
|
||||
total_summaries: totalSummaries,
|
||||
percent,
|
||||
// #3185 (ADR-3180 Decision 2): the enumeration's scope, so a consumer
|
||||
// can tell a genuinely-empty milestone from one it could not scope.
|
||||
phase_scope: phaseScope,
|
||||
}, raw, undefined);
|
||||
}
|
||||
}
|
||||
@@ -1856,7 +1865,6 @@ function cmdStats(cwd: string, format: string | undefined, raw: boolean): void {
|
||||
const reqPath = planningPaths(cwd).requirements;
|
||||
const statePath = planningPaths(cwd).state;
|
||||
const milestone = getMilestoneInfo(cwd);
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd) as (dir: string) => boolean;
|
||||
|
||||
// Phase & plan stats (reuse progress pattern)
|
||||
const phasesByNumber = new Map<string, {
|
||||
@@ -1868,6 +1876,7 @@ function cmdStats(cwd: string, format: string | undefined, raw: boolean): void {
|
||||
}>();
|
||||
let totalPlans = 0;
|
||||
let totalSummaries = 0;
|
||||
let phaseScope: string | null = null;
|
||||
|
||||
try {
|
||||
const roadmapRaw = platformReadSync(roadmapPath);
|
||||
@@ -1879,6 +1888,12 @@ function cmdStats(cwd: string, format: string | undefined, raw: boolean): void {
|
||||
const headingPattern = /#{2,4}\s*(?:\[[^\]]{1,200}\]\s*)?Phase\s+([\w][\w.-]*)(?:\s*\([^)\n]{0,200}\))?\s*:\s*([^\n]+)/gi;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = headingPattern.exec(roadmapContent)) !== null) {
|
||||
// #3185: the heading seed carried no sentinel filter, so a
|
||||
// `### Phase 999.1:` backlog heading produced a stats row even with no
|
||||
// directory on disk. Uses the canonical predicate (phase-id.cts), not a
|
||||
// local literal — the rule had five copies and three regex variants
|
||||
// before this phase, disagreeing about Phase 0.
|
||||
if (isSentinelPhaseId(match[1])) continue;
|
||||
const key = normalizePhaseName(match[1]);
|
||||
phasesByNumber.set(key, {
|
||||
number: key,
|
||||
@@ -1891,12 +1906,13 @@ function cmdStats(cwd: string, format: string | undefined, raw: boolean): void {
|
||||
} catch { /* intentionally empty */ }
|
||||
|
||||
try {
|
||||
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
const dirs = entries
|
||||
.filter(e => e.isDirectory())
|
||||
.map(e => e.name)
|
||||
.filter(isDirInMilestone)
|
||||
.sort((a, b) => comparePhaseNum(a, b));
|
||||
// #3185 (ADR-3180 Decision 1): route through the single owner. This
|
||||
// previously applied the milestone window but NOT a directory-level
|
||||
// sentinel filter — and getMilestonePhaseFilter degrades to a pass-all
|
||||
// predicate when its heading set is empty, at which point every directory
|
||||
// on disk passed, backlog included (#3167).
|
||||
const { value: dirs, scope } = listMilestonePhaseDirs(phasesDir, { cwd });
|
||||
phaseScope = scope;
|
||||
|
||||
for (const dir of dirs) {
|
||||
// Use extractPhaseToken to correctly parse M-NN-style and code-prefixed dir names.
|
||||
@@ -1991,6 +2007,9 @@ function cmdStats(cwd: string, format: string | undefined, raw: boolean): void {
|
||||
git_commits: gitCommits,
|
||||
git_first_commit_date: gitFirstCommitDate,
|
||||
last_activity: lastActivity,
|
||||
// #3185 (ADR-3180 Decision 2): the enumeration's scope, so a consumer
|
||||
// can tell a genuinely-empty milestone from one it could not scope.
|
||||
phase_scope: phaseScope,
|
||||
};
|
||||
|
||||
if (format === 'table') {
|
||||
|
||||
79
src/init.cts
79
src/init.cts
@@ -79,16 +79,15 @@ const {
|
||||
const { output, error } = io;
|
||||
const { loadConfig, loadConfigResolved } = configLoader;
|
||||
const { resolveModelInternal, resolveGranularityInternal, assertValidGranularityOverride } = modelResolver;
|
||||
const { findPhaseInternal } = phaseLocator;
|
||||
const { findPhaseInternal, listMilestonePhaseDirs } = phaseLocator;
|
||||
const {
|
||||
getRoadmapPhaseInternal,
|
||||
getMilestoneInfo,
|
||||
getMilestonePhaseFilter,
|
||||
stripShippedMilestones,
|
||||
extractCurrentMilestone,
|
||||
} = roadmapParser;
|
||||
const { pathExistsInternal, generateSlugInternal, toPosixPath } = coreUtils;
|
||||
const { escapeRegex, normalizePhaseName, phaseTokenMatches, stripProjectCodePrefix, PHASE_NUMBER_TOKEN_SOURCE, isForeignPrefixedPhaseQuery } = phaseId;
|
||||
const { escapeRegex, normalizePhaseName, phaseTokenMatches, stripProjectCodePrefix, PHASE_NUMBER_TOKEN_SOURCE, isForeignPrefixedPhaseQuery, isSentinelPhaseId } = phaseId;
|
||||
const { pruneOrphanedWorktrees } = worktreeSafety;
|
||||
|
||||
const {
|
||||
@@ -1212,19 +1211,11 @@ function cmdInitNewMilestone(cwd: string, raw: boolean, options: Record<string,
|
||||
const milestone = getMilestoneInfo(cwd) as unknown as Record<string, unknown>;
|
||||
const latestCompleted = getLatestCompletedMilestone(cwd);
|
||||
const phasesDir = path.join(planningDir(cwd), 'phases');
|
||||
let phaseDirCount = 0;
|
||||
|
||||
try {
|
||||
if (fs.existsSync(phasesDir)) {
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd);
|
||||
phaseDirCount = fs
|
||||
.readdirSync(phasesDir, { withFileTypes: true })
|
||||
.filter((entry) => entry.isDirectory() && isDirInMilestone(entry.name))
|
||||
.length;
|
||||
}
|
||||
} catch {
|
||||
/* intentionally empty */
|
||||
}
|
||||
// #3185 (ADR-3180 Decision 1): "how many phase directories belong to the
|
||||
// CURRENT milestone" is exactly the scoped question listMilestonePhaseDirs
|
||||
// owns — routed through it instead of a local readdirSync + hand-rolled
|
||||
// window filter (which also never excluded sentinels, unlike the owner).
|
||||
const phaseDirCount = listMilestonePhaseDirs(phasesDir, { cwd }).value.length;
|
||||
|
||||
const wf = (config.workflow ?? {}) as Record<string, unknown>;
|
||||
|
||||
@@ -2012,7 +2003,8 @@ function cmdInitMilestoneOp(cwd: string, raw: boolean): void {
|
||||
const phasePattern = new RegExp(`#{2,4}\\s*Phase\\s+(${PHASE_NUMBER_TOKEN_SOURCE})(?:\\s*\\([^)\\n]{0,200}\\))?\\s*:`, 'gi');
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = phasePattern.exec(currentSection)) !== null) {
|
||||
if (/^999(?:\.|$)/.test(m[1])) continue;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (isSentinelPhaseId(m[1])) continue;
|
||||
roadmapPhaseNumbers.push(m[1]);
|
||||
}
|
||||
} catch {
|
||||
@@ -2050,8 +2042,12 @@ function cmdInitMilestoneOp(cwd: string, raw: boolean): void {
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
const dirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
|
||||
// #3185 (ADR-3180 Decision 1): the ROADMAP heading scan above found no
|
||||
// current-milestone phase headings — fall back to asking the canonical
|
||||
// owner "which phase directories belong to the current milestone"
|
||||
// directly, instead of a hand-rolled readdirSync over every directory
|
||||
// on disk (which also never excluded sentinels, unlike the owner).
|
||||
const dirs = listMilestonePhaseDirs(phasesDir, { cwd }).value;
|
||||
phaseCount = dirs.length;
|
||||
for (const dir of dirs) {
|
||||
try {
|
||||
@@ -2152,18 +2148,13 @@ function cmdInitManager(cwd: string, raw: boolean): void {
|
||||
const rawContent = fs.readFileSync(paths.roadmap, 'utf-8');
|
||||
const content = extractCurrentMilestone(rawContent, cwd);
|
||||
const phasesDir = paths.phases;
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd);
|
||||
|
||||
const _phaseDirEntries = (() => {
|
||||
try {
|
||||
return fs
|
||||
.readdirSync(phasesDir, { withFileTypes: true })
|
||||
.filter((e) => e.isDirectory())
|
||||
.map((e) => e.name);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
})();
|
||||
// #3185 (ADR-3180 Decision 1): "which phase directories belong to the
|
||||
// CURRENT milestone" is the scoped question listMilestonePhaseDirs owns —
|
||||
// routed through it instead of a hand-rolled readdirSync + a separate
|
||||
// getMilestonePhaseFilter window check (which also never excluded
|
||||
// sentinels, unlike the owner).
|
||||
const _phaseDirEntries = listMilestonePhaseDirs(phasesDir, { cwd }).value;
|
||||
|
||||
const _checkboxStates = new Map<string, boolean>();
|
||||
const _cbPattern = new RegExp(`-\\s*\\[(x| )\\]\\s*.*Phase\\s+(${PHASE_NUMBER_TOKEN_SOURCE})[:\\s]`, 'gi');
|
||||
@@ -2213,8 +2204,7 @@ function cmdInitManager(cwd: string, raw: boolean): void {
|
||||
);
|
||||
|
||||
try {
|
||||
const dirs = _phaseDirEntries.filter(isDirInMilestone);
|
||||
const dirMatch = dirs.find((d) => phaseTokenMatches(d, normalized));
|
||||
const dirMatch = _phaseDirEntries.find((d) => phaseTokenMatches(d, normalized));
|
||||
|
||||
if (dirMatch) {
|
||||
const fullDir = path.join(phasesDir, dirMatch);
|
||||
@@ -2387,7 +2377,8 @@ function cmdInitManager(cwd: string, raw: boolean): void {
|
||||
const recommendedActions: Record<string, unknown>[] = [];
|
||||
for (const phase of phases) {
|
||||
if (phase['disk_status'] === 'complete') continue;
|
||||
if (/^999(?:\.|$)/.test(phase['number'] as string)) continue;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (isSentinelPhaseId(phase['number'])) continue;
|
||||
|
||||
if (phase['disk_status'] === 'executed') {
|
||||
recommendedActions.push({
|
||||
@@ -2455,7 +2446,8 @@ function cmdInitManager(cwd: string, raw: boolean): void {
|
||||
return true;
|
||||
});
|
||||
|
||||
const nonBacklogPhases = phases.filter((p) => !/^999(?:\.|$)/.test(p['number'] as string));
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
const nonBacklogPhases = phases.filter((p) => !isSentinelPhaseId(p['number'] as string));
|
||||
const completedCount = nonBacklogPhases.filter((p) => p['phase_complete'] === true).length;
|
||||
|
||||
const sanitizeFlags = (rawVal: unknown): string => {
|
||||
@@ -2806,21 +2798,16 @@ function cmdInitProgress(cwd: string, raw: boolean, options: Record<string, unkn
|
||||
/* intentionally empty */
|
||||
}
|
||||
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd);
|
||||
const seenPhaseNums = new Set<string>();
|
||||
|
||||
try {
|
||||
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
const dirs = entries
|
||||
.filter((e) => e.isDirectory())
|
||||
.map((e) => e.name)
|
||||
.filter(isDirInMilestone)
|
||||
.sort((a, b) => {
|
||||
const pa = a.match(new RegExp(`^(${PHASE_NUMBER_TOKEN_SOURCE})`, 'i'));
|
||||
const pb = b.match(new RegExp(`^(${PHASE_NUMBER_TOKEN_SOURCE})`, 'i'));
|
||||
if (!pa || !pb) return a.localeCompare(b);
|
||||
return parseInt(pa[1], 10) - parseInt(pb[1], 10);
|
||||
});
|
||||
// #3185 (ADR-3180 Decision 1): "which phase directories belong to the
|
||||
// CURRENT milestone" — routed through the canonical owner instead of a
|
||||
// hand-rolled readdirSync + isDirInMilestone filter + local sort (which
|
||||
// also never excluded sentinels, unlike the owner; the final `phases`
|
||||
// array is re-sorted below anyway, so dropping the local sort here is
|
||||
// behavior-preserving).
|
||||
const dirs = listMilestonePhaseDirs(phasesDir, { cwd }).value;
|
||||
|
||||
for (const dir of dirs) {
|
||||
const dirMatch = dir.match(new RegExp(`^(${PHASE_NUMBER_TOKEN_SOURCE})-?(.*)`, 'i'));
|
||||
|
||||
@@ -26,7 +26,7 @@ import ioMod = require('./io.cjs');
|
||||
const { output, error } = ioMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import phaseIdMod = require('./phase-id.cjs');
|
||||
const { escapeRegex, normalizePhaseName, phaseTokenMatches, PHASE_NUMBER_TOKEN_SOURCE } = phaseIdMod;
|
||||
const { escapeRegex, normalizePhaseName, phaseTokenMatches, PHASE_NUMBER_TOKEN_SOURCE, isSentinelPhaseId } = phaseIdMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import roadmapParserMod = require('./roadmap-parser.cjs');
|
||||
const {
|
||||
@@ -44,6 +44,9 @@ const { extractOneLinerFromBody, countMatchedSummaries } = coreUtilsMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- plan-scan.cjs is an export= CommonJS module
|
||||
import planScanMod = require('./plan-scan.cjs');
|
||||
const { scanPhasePlans } = planScanMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- phase-locator.cjs is an export= CommonJS module
|
||||
import phaseLocatorMod = require('./phase-locator.cjs');
|
||||
const { listMilestonePhaseDirs } = phaseLocatorMod;
|
||||
const { planningPaths } = planningWorkspace;
|
||||
const { extractFrontmatter } = frontmatterMod;
|
||||
const { writeStateMd } = stateMod;
|
||||
@@ -653,8 +656,8 @@ function cmdMilestoneComplete(cwd: string, version: string, options: MilestoneCo
|
||||
// milestone completion. Mirrors the engine-wide sentinel convention
|
||||
// (phase-id getMilestoneFromPhaseId, roadmap-command-router SENTINELS,
|
||||
// the #1445 /^999/ progress filters). (#1580)
|
||||
const major = parseInt(phaseNum, 10);
|
||||
if (major === 0 || major === 999) continue;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this local check already covered both 0 and 999; now delegates to the single canonical owner.
|
||||
if (isSentinelPhaseId(phaseNum)) continue;
|
||||
const normalized = normalizePhaseName(phaseNum);
|
||||
// A phase has disk_status: 'no_directory' when no phase directory
|
||||
// with a matching token exists on disk. Use the same phaseTokenMatches
|
||||
@@ -686,15 +689,14 @@ function cmdMilestoneComplete(cwd: string, version: string, options: MilestoneCo
|
||||
const accomplishments: string[] = [];
|
||||
|
||||
try {
|
||||
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
const dirs = entries
|
||||
.filter((e) => e.isDirectory())
|
||||
.map((e) => e.name)
|
||||
.sort();
|
||||
// #3185 (ADR-3180 Decision 1): "which phase directories belong to the
|
||||
// CURRENT milestone" — routed through the canonical owner (with the
|
||||
// explicit `version` this command already resolved) instead of a
|
||||
// hand-rolled readdirSync + isDirInMilestone filter, which also never
|
||||
// excluded sentinels, unlike the owner.
|
||||
const dirs = listMilestonePhaseDirs(phasesDir, { cwd, versionOverride: version }).value;
|
||||
|
||||
for (const dir of dirs) {
|
||||
if (!isDirInMilestone(dir)) continue;
|
||||
|
||||
phaseCount++;
|
||||
// #3183: canonical plan/summary sets (root+nested, superseded-excluded)
|
||||
// from the single owner, rather than a root-only hand-rolled readdirSync
|
||||
@@ -745,14 +747,10 @@ function cmdMilestoneComplete(cwd: string, version: string, options: MilestoneCo
|
||||
if (options.dryRun) {
|
||||
const phaseDirsToArchive: string[] = [];
|
||||
if (options.archivePhases !== false) {
|
||||
try {
|
||||
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
for (const e of entries) {
|
||||
if (e.isDirectory() && isDirInMilestone(e.name)) {
|
||||
phaseDirsToArchive.push(e.name);
|
||||
}
|
||||
}
|
||||
} catch { /* phasesDir missing — nothing to archive */ }
|
||||
// #3185 (ADR-3180 Decision 1): same routed derivation as the stats loop
|
||||
// above — the dry-run preview must list exactly what the real archive
|
||||
// pass below would move.
|
||||
phaseDirsToArchive.push(...listMilestonePhaseDirs(phasesDir, { cwd, versionOverride: version }).value);
|
||||
}
|
||||
const dryRunResult = {
|
||||
dry_run: true,
|
||||
@@ -876,10 +874,12 @@ function cmdMilestoneComplete(cwd: string, version: string, options: MilestoneCo
|
||||
const phaseArchiveDir = path.join(archiveDir, `${version}-phases`);
|
||||
platformEnsureDir(phaseArchiveDir);
|
||||
|
||||
const phaseEntries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
const phaseDirNames = phaseEntries.filter((e) => e.isDirectory()).map((e) => e.name);
|
||||
// #3185 (ADR-3180 Decision 1): same routed derivation as the stats
|
||||
// loop above — only the CURRENT milestone's phase directories move,
|
||||
// never a sentinel or an out-of-window directory left for a later
|
||||
// milestone.
|
||||
const phaseDirNames = listMilestonePhaseDirs(phasesDir, { cwd, versionOverride: version }).value;
|
||||
for (const dir of phaseDirNames) {
|
||||
if (!isDirInMilestone(dir)) continue;
|
||||
retryRenameSync(path.join(phasesDir, dir), path.join(phaseArchiveDir, dir));
|
||||
archivedCount++;
|
||||
}
|
||||
@@ -949,7 +949,13 @@ function cmdPhasesClear(cwd: string, raw: boolean, args: string[]): void {
|
||||
|
||||
if (fs.existsSync(phasesDir)) {
|
||||
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
const dirs = entries.filter((e) => e.isDirectory() && !/^999(?:\.|$)/.test(e.name));
|
||||
// #3185 (ADR-3180 Decision 1): this carried the FIFTH copy of the
|
||||
// sentinel rule and its THIRD regex variant — `/^999(?:\.|$)/` — which
|
||||
// excluded 999 but NOT 0. Because this is the DESTRUCTIVE path, that
|
||||
// divergence meant a `0-*` directory `roadmap analyze` preserves as a
|
||||
// sentinel was DELETED here. Routed through the canonical predicate so
|
||||
// every reader of "is this a sentinel phase" agrees by construction.
|
||||
const dirs = entries.filter((e) => e.isDirectory() && !isSentinelPhaseId(e.name));
|
||||
|
||||
if (dirs.length > 0 && !confirm) {
|
||||
error(
|
||||
|
||||
@@ -21,6 +21,9 @@
|
||||
*/
|
||||
|
||||
import { findTableWithColumns } from './markdown-table.cjs';
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- phase-id.cjs is an export= CommonJS module
|
||||
import phaseIdMod = require('./phase-id.cjs');
|
||||
const { isSentinelPhaseId } = phaseIdMod;
|
||||
|
||||
/** Result of deriveProgressFromRoadmap. */
|
||||
export interface RoadmapProgress {
|
||||
@@ -90,10 +93,11 @@ export function deriveProgressFromRoadmap(roadmapContent: string): RoadmapProgre
|
||||
const completed = allRows.filter((r) => /^complete$/i.test((r['Status'] ?? '').trim())).length;
|
||||
completedPhases = completed > 0 ? completed : null;
|
||||
|
||||
// Data rows only (exclude 999.x backlog phases). Mirrors init.cts /^999(?:\.|$)/ filter.
|
||||
// Data rows only (exclude sentinel phases 0 and 999.x).
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
const dataRows = allRows.filter((r) => {
|
||||
const phase = (r['Phase'] ?? '').trim();
|
||||
return /^\d/.test(phase) && !/^999\b/.test(phase);
|
||||
return /^\d/.test(phase) && !isSentinelPhaseId(phase);
|
||||
});
|
||||
totalPhases = dataRows.length > 0 ? dataRows.length : null;
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import phaseIdModule = require('./phase-id.cjs');
|
||||
const { normalizePhaseName, phaseTokenMatches, extractPhaseToken } = phaseIdModule;
|
||||
const { normalizePhaseName, phaseTokenMatches, extractPhaseToken, isSentinelPhaseId, comparePhaseNum } = phaseIdModule;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import coreUtilsModule = require('./core-utils.cjs');
|
||||
const { readSubdirectories, getPhaseFileStats, extractCanonicalPlanId, toPosixPath, findUnsummarizedPlans } = coreUtilsModule;
|
||||
@@ -33,6 +33,13 @@ const { extractFrontmatter } = frontmatterModule;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import planDependencyGraphModule = require('./plan-dependency-graph.cjs');
|
||||
const { computeHaltPropagation, buildSummaryFileIndex, isSummaryFileHalted } = planDependencyGraphModule;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import roadmapParserModule = require('./roadmap-parser.cjs');
|
||||
const { getMilestonePhaseFilter } = roadmapParserModule;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import planningScopeMod = require('./planning-scope.cjs');
|
||||
const { SCOPE } = planningScopeMod;
|
||||
type Scope = planningScopeMod.Scope;
|
||||
|
||||
// ─── Phase search types ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -287,6 +294,86 @@ function findPhaseInternal(cwd: string, phase: unknown): PhaseSearchResult | nul
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* #3185 (epic #3180 Phase 3, ADR-3180 Decision 1 row "Phase enumeration"):
|
||||
* the SINGLE canonical owner of "which phase directories belong to the current
|
||||
* milestone". Applies the milestone window AND the sentinel filter, in that
|
||||
* order, and returns the surviving directory names.
|
||||
*
|
||||
* Before this existed the derivation had four independent implementations and
|
||||
* only `cmdRoadmapAnalyze` carried both halves; `cmdProgressRender`,
|
||||
* `cmdStats` and `cmdPhasesList` each carried neither or one.
|
||||
*
|
||||
* TWO THINGS THIS GETS RIGHT THAT A HEADING-SIDE FILTER CANNOT:
|
||||
*
|
||||
* 1. The sentinel test runs against DIRECTORY NAMES and is UNCONDITIONAL.
|
||||
* `getMilestonePhaseFilter` excludes sentinels from its ROADMAP HEADING
|
||||
* set, but when that set is empty it degrades to a literal `() => true`
|
||||
* pass-all predicate and never consults the heading set at all — so its
|
||||
* own sentinel exclusion becomes unreachable exactly when it is needed,
|
||||
* and every directory on disk (backlog included) is reported as a
|
||||
* current-milestone phase. That degrade is the #3167 symptom path.
|
||||
*
|
||||
* 2. The sentinel predicate is the canonical `isSentinelPhaseId`
|
||||
* (`src/phase-id.cts`, SENTINEL_RANGES [0, 999]), not a local literal.
|
||||
* The rule had five copies and three different regexes before this phase,
|
||||
* and they disagreed about Phase 0.
|
||||
*
|
||||
* The pass-all degrade is narrowed MINIMALLY: it stays over-inclusive for
|
||||
* non-sentinel directories, so a project whose window declares no phases
|
||||
* still sees its real phase directories. Only sentinels are refused.
|
||||
*
|
||||
* `scope` distinguishes a REAL empty from a NON-answer (ADR-3180 Decision 2):
|
||||
* an absent `phasesDir` is a real empty (a new project genuinely has no
|
||||
* phases) and inherits the window's scope, whereas a `phasesDir` that exists
|
||||
* but cannot be read is UNREADABLE.
|
||||
*/
|
||||
function listMilestonePhaseDirs(
|
||||
phasesDir: string,
|
||||
opts: {
|
||||
cwd?: string;
|
||||
ws?: string | null;
|
||||
versionOverride?: string | null;
|
||||
phaseIdConvention?: string | null;
|
||||
} = {},
|
||||
): { value: string[]; scope: Scope } {
|
||||
const { cwd, ws = null, versionOverride = null, phaseIdConvention = null } = opts;
|
||||
|
||||
// Without a cwd there is nothing to scope AGAINST — the caller asked for an
|
||||
// unscoped read, which is a real answer (mirrors extractCurrentMilestoneScoped's
|
||||
// row 1). Sentinels are still refused: they are never milestone phases.
|
||||
let inWindow: (dirName: string) => boolean = () => true;
|
||||
let scope: Scope = SCOPE.COMPLETE;
|
||||
if (cwd) {
|
||||
const filter = getMilestonePhaseFilter(cwd, versionOverride, phaseIdConvention, ws);
|
||||
inWindow = filter;
|
||||
scope = filter.scope;
|
||||
}
|
||||
|
||||
// An ABSENT phases dir is a real empty, not a failure: a freshly-created
|
||||
// project genuinely has no phase directories yet. Distinguishing this from
|
||||
// the unreadable case below is the whole point of the scope discriminator.
|
||||
if (!fs.existsSync(phasesDir)) return { value: [], scope };
|
||||
|
||||
let names: string[];
|
||||
try {
|
||||
names = fs.readdirSync(phasesDir, { withFileTypes: true })
|
||||
.filter((e) => e.isDirectory())
|
||||
.map((e) => e.name);
|
||||
} catch {
|
||||
// The directory EXISTS but could not be read (EACCES/EIO). An empty list
|
||||
// here is a NON-answer and must not be reported as "this milestone has no
|
||||
// phases" — that collapse is the defect class this epic removes.
|
||||
return { value: [], scope: SCOPE.UNREADABLE };
|
||||
}
|
||||
|
||||
const value = names
|
||||
.filter((name) => inWindow(name) && !isSentinelPhaseId(name, phaseIdConvention ?? undefined))
|
||||
.sort((a, b) => comparePhaseNum(a, b));
|
||||
|
||||
return { value, scope };
|
||||
}
|
||||
|
||||
function getArchivedPhaseDirs(cwd: string): ArchivedPhaseDir[] {
|
||||
// #2855: same workstream-scoped resolution as findPhaseInternal above, via
|
||||
// the shared listArchiveVersionDirs helper. `phase.list --include-archived`
|
||||
@@ -314,4 +401,5 @@ export = {
|
||||
searchPhaseInDir,
|
||||
findPhaseInternal,
|
||||
getArchivedPhaseDirs,
|
||||
listMilestonePhaseDirs,
|
||||
};
|
||||
|
||||
113
src/phase.cts
113
src/phase.cts
@@ -42,10 +42,10 @@ const {
|
||||
} = phaseIdMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- phase-locator.cjs is an export= CommonJS module
|
||||
import phaseLocatorMod = require('./phase-locator.cjs');
|
||||
const { findPhaseInternal, getArchivedPhaseDirs } = phaseLocatorMod;
|
||||
const { findPhaseInternal, getArchivedPhaseDirs, listMilestonePhaseDirs } = phaseLocatorMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- roadmap-parser.cjs is an export= CommonJS module
|
||||
import roadmapParserMod = require('./roadmap-parser.cjs');
|
||||
const { stripShippedMilestones, extractCurrentMilestone, getMilestonePhaseFilter, currentMilestoneRawRanges, withPhaseSection } = roadmapParserMod;
|
||||
const { stripShippedMilestones, extractCurrentMilestone, currentMilestoneRawRanges, withPhaseSection } = roadmapParserMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- planning-workspace.cjs is an export= CommonJS module
|
||||
import planningWorkspace = require('./planning-workspace.cjs');
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- frontmatter.cjs is an export= CommonJS module
|
||||
@@ -209,26 +209,51 @@ function cmdPhasesList(cwd: string, options: PhaseListOptions, raw: boolean): vo
|
||||
}
|
||||
|
||||
try {
|
||||
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
let dirs: string[] = entries.filter((e) => e.isDirectory()).map((e) => e.name);
|
||||
|
||||
if (includeArchived) {
|
||||
const archived = getArchivedPhaseDirs(cwd);
|
||||
for (const a of archived) {
|
||||
dirs.push(`${a.name} [${a.milestone}]`);
|
||||
}
|
||||
}
|
||||
|
||||
dirs.sort((a, b) => comparePhaseNum(a, b));
|
||||
// #3185 (ADR-3180 Decision 1): only the ENUMERATION routes through the
|
||||
// single owner. The two other modes below ask genuinely DIFFERENT
|
||||
// questions and are exempt by documented reason, never by a file
|
||||
// allowlist (ADR-3180 Decision 4a):
|
||||
//
|
||||
// --phase <n> locating ONE phase by token is phase LOCATION, a
|
||||
// question src/phase-locator.cts already owns via
|
||||
// findPhaseInternal/searchPhaseInDir. Scoping it to
|
||||
// the current milestone would make an out-of-window
|
||||
// phase report "Phase not found".
|
||||
// --include-archived archived directories are BY DEFINITION from other
|
||||
// milestones; filtering them through the CURRENT
|
||||
// milestone window would return nothing at all.
|
||||
//
|
||||
// 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 wants the physical set; only "which phases belong to
|
||||
// this milestone" wants the scoped set.
|
||||
const archivedLabels: string[] = includeArchived
|
||||
? getArchivedPhaseDirs(cwd).map((a) => `${a.name} [${a.milestone}]`)
|
||||
: [];
|
||||
|
||||
let dirs: string[];
|
||||
// #3185 (ADR-3180 Decision 2): the enumeration's scope, so a consumer
|
||||
// can tell a genuinely-empty milestone from one it could not scope. Only
|
||||
// the ENUMERATION path scopes anything; the LOOKUP path below has no
|
||||
// enumeration to report a scope for.
|
||||
let phaseScope: string | null = null;
|
||||
if (phase) {
|
||||
// LOOKUP (b): search the physical set, plus archived when asked.
|
||||
const lookupPool = [...readSubdirectories(phasesDir, true), ...archivedLabels];
|
||||
const normalized = normalizePhaseName(phase);
|
||||
const match = dirs.find((d) => phaseTokenMatches(d, normalized));
|
||||
const match = lookupPool.find((d) => phaseTokenMatches(d, normalized));
|
||||
if (!match) {
|
||||
output({ files: [], count: 0, phase_dir: null, error: 'Phase not found' }, raw, '');
|
||||
return;
|
||||
}
|
||||
dirs = [match];
|
||||
} else {
|
||||
// ENUMERATION (a): milestone-scoped and sentinel-filtered, plus
|
||||
// archived when asked (c).
|
||||
const enumerated = listMilestonePhaseDirs(phasesDir, { cwd });
|
||||
phaseScope = enumerated.scope;
|
||||
dirs = [...enumerated.value, ...archivedLabels];
|
||||
dirs.sort((a, b) => comparePhaseNum(a, b));
|
||||
}
|
||||
|
||||
if (type) {
|
||||
@@ -274,13 +299,18 @@ function cmdPhasesList(cwd: string, options: PhaseListOptions, raw: boolean): vo
|
||||
files,
|
||||
count: files.length,
|
||||
phase_dir: phase ? dirs[0].replace(/^\d+(?:\.\d+)*-?/, '') : null,
|
||||
// #3185 (ADR-3180 Decision 2): the enumeration's scope, so a consumer
|
||||
// can tell a genuinely-empty milestone from one it could not scope.
|
||||
phase_scope: phaseScope,
|
||||
};
|
||||
if (warnings.length) result['warning'] = warnings.join(' | ');
|
||||
output(result, raw, files.join('\n'));
|
||||
return;
|
||||
}
|
||||
|
||||
output({ directories: dirs, count: dirs.length }, raw, dirs.join('\n'));
|
||||
// #3185 (ADR-3180 Decision 2): the enumeration's scope, so a consumer
|
||||
// can tell a genuinely-empty milestone from one it could not scope.
|
||||
output({ directories: dirs, count: dirs.length, phase_scope: phaseScope }, raw, dirs.join('\n'));
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
error('Failed to list phases: ' + msg);
|
||||
@@ -979,11 +1009,13 @@ function cmdPhaseAdd(cwd: string, description: string, raw: boolean, customId?:
|
||||
|
||||
while ((m = headerPattern.exec(content)) !== null) {
|
||||
const num = parseInt(m[1], 10);
|
||||
if (num !== 999) usedPhaseNums.add(num);
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (!isSentinelPhaseId(num)) usedPhaseNums.add(num);
|
||||
}
|
||||
while ((m = bulletPattern.exec(content)) !== null) {
|
||||
const num = parseInt(m[1], 10);
|
||||
if (num !== 999) usedPhaseNums.add(num);
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (!isSentinelPhaseId(num)) usedPhaseNums.add(num);
|
||||
}
|
||||
|
||||
// 3) On-disk phase directories (e.g. phases/11-foo/ with no header yet)
|
||||
@@ -994,7 +1026,8 @@ function cmdPhaseAdd(cwd: string, description: string, raw: boolean, customId?:
|
||||
const match = entry.match(dirNumPattern);
|
||||
if (!match) continue;
|
||||
const num = parseInt(match[1], 10);
|
||||
if (num !== 999) usedPhaseNums.add(num);
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (!isSentinelPhaseId(num)) usedPhaseNums.add(num);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1072,7 +1105,8 @@ function cmdPhaseAddBatch(cwd: string, descriptions: string[], raw: boolean): vo
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = phasePattern.exec(content)) !== null) {
|
||||
const num = parseInt(m[1], 10);
|
||||
if (num === 999) continue;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (isSentinelPhaseId(num)) continue;
|
||||
if (num > maxPhase) maxPhase = num;
|
||||
}
|
||||
const phasesOnDisk = path.join(planningDir(cwd), 'phases');
|
||||
@@ -1082,7 +1116,8 @@ function cmdPhaseAddBatch(cwd: string, descriptions: string[], raw: boolean): vo
|
||||
const match = entry.match(dirNumPattern);
|
||||
if (!match) continue;
|
||||
const num = parseInt(match[1], 10);
|
||||
if (num === 999) continue;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (isSentinelPhaseId(num)) continue;
|
||||
if (num > maxPhase) maxPhase = num;
|
||||
}
|
||||
}
|
||||
@@ -1376,7 +1411,8 @@ function renameIntegerPhases(
|
||||
const m = dir.match(/^(\d+)([A-Z])?(?:\.(\d+))?-(.+)$/i);
|
||||
if (!m) return null;
|
||||
const dirInt = parseInt(m[1], 10);
|
||||
return dirInt > removedInt && dirInt !== 999
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
return dirInt > removedInt && !isSentinelPhaseId(dirInt)
|
||||
? {
|
||||
dir,
|
||||
oldInt: dirInt,
|
||||
@@ -1418,7 +1454,8 @@ function renameIntegerPhases(
|
||||
|
||||
function decrementRoadmapPhaseNumber(raw: string, removedInt: number): string {
|
||||
const num = parseInt(raw, 10);
|
||||
if (!Number.isInteger(num) || num <= removedInt || num === 999) return raw;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (!Number.isInteger(num) || num <= removedInt || isSentinelPhaseId(num)) return raw;
|
||||
return String(num - 1);
|
||||
}
|
||||
|
||||
@@ -1426,13 +1463,15 @@ function decrementRoadmapPhaseToken(raw: string, removedInt: number): string {
|
||||
const match = String(raw).match(/^(\d+)(\.\d+)?$/);
|
||||
if (!match) return raw;
|
||||
const num = parseInt(match[1], 10);
|
||||
if (!Number.isInteger(num) || num <= removedInt || num === 999) return raw;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (!Number.isInteger(num) || num <= removedInt || isSentinelPhaseId(num)) return raw;
|
||||
return `${num - 1}${match[2] || ''}`;
|
||||
}
|
||||
|
||||
function decrementRoadmapPaddedPhaseNumber(raw: string, removedInt: number): string {
|
||||
const num = parseInt(raw, 10);
|
||||
if (!Number.isInteger(num) || num <= removedInt || num === 999) return raw;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (!Number.isInteger(num) || num <= removedInt || isSentinelPhaseId(num)) return raw;
|
||||
return String(num - 1).padStart(raw.length, '0');
|
||||
}
|
||||
|
||||
@@ -1621,7 +1660,8 @@ function updateRoadmapAfterPhaseRemoval(
|
||||
const m = phaseCellShapeRe.exec(row['Phase'] ?? '');
|
||||
if (!m) return false;
|
||||
const num = parseInt(m[1], 10);
|
||||
if (!Number.isInteger(num) || num <= removedInt || num === 999) return false;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (!Number.isInteger(num) || num <= removedInt || isSentinelPhaseId(num)) return false;
|
||||
processedOrdinalRows.add(index);
|
||||
matchedRowIndex = index;
|
||||
return true;
|
||||
@@ -2590,18 +2630,20 @@ function cmdPhaseComplete(cwd: string, phaseNum: string, raw: boolean): void {
|
||||
}
|
||||
|
||||
try {
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd);
|
||||
const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
|
||||
const dirs = entries
|
||||
.filter((e) => e.isDirectory())
|
||||
.map((e) => e.name)
|
||||
.filter(isDirInMilestone)
|
||||
.sort((a, b) => comparePhaseNum(a, b));
|
||||
// #3185 (ADR-3180 Decision 1): "which phase directories belong to
|
||||
// the CURRENT milestone" — routed through the canonical owner
|
||||
// instead of a hand-rolled readdirSync + isDirInMilestone filter
|
||||
// (which also never excluded sentinels on its own, unlike the
|
||||
// owner; the per-directory isSentinelPhaseId check below stays as a
|
||||
// defensive second check against the REGEX-EXTRACTED token, which
|
||||
// is not necessarily identical to the raw directory name).
|
||||
const dirs = listMilestonePhaseDirs(phasesDir, { cwd }).value;
|
||||
|
||||
for (const dir of dirs) {
|
||||
const dm = dir.match(new RegExp(`^(${PHASE_NUMBER_TOKEN_SOURCE})-?(.*)`, 'i'));
|
||||
if (dm) {
|
||||
if (/^999(?:\.|$)/.test(dm[1])) continue;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (isSentinelPhaseId(dm[1])) continue;
|
||||
if (comparePhaseNum(dm[1], phaseNum) > 0) {
|
||||
nextPhaseNum = dm[1];
|
||||
nextPhaseName = dm[2] || null;
|
||||
@@ -2645,9 +2687,8 @@ function cmdPhaseComplete(cwd: string, phaseNum: string, raw: boolean): void {
|
||||
let pm: RegExpExecArray | null;
|
||||
while ((pm = phasePattern.exec(roadmapForPhases)) !== null) {
|
||||
// #2786: skip sentinel phase ids (999.x backlog, 0.x drafts) — stage 1
|
||||
// already skips 999 dirs on disk; stage 2's heading scan must not
|
||||
// advance into backlog headings. Mirrors the /^999(?:\.|$)/ guard
|
||||
// stage 1 uses at line 2536, but via isSentinelPhaseId for both ranges.
|
||||
// already skips sentinel dirs on disk via isSentinelPhaseId (#3185);
|
||||
// stage 2's heading scan must not advance into backlog headings either.
|
||||
if (isSentinelPhaseId(pm[1])) continue;
|
||||
if (comparePhaseNum(pm[1], phaseNum) > 0) {
|
||||
nextPhaseNum = pm[1];
|
||||
|
||||
@@ -28,6 +28,8 @@ const {
|
||||
// #2121: roadmapPhaseLookupSources now lives in phase-id.cjs (single owner of
|
||||
// the lookup-source ordering); imported here rather than defined locally.
|
||||
roadmapPhaseLookupSources,
|
||||
extractPhaseToken,
|
||||
isSentinelPhaseId,
|
||||
} = phaseIdModule;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import planningWorkspace = require('./planning-workspace.cjs');
|
||||
@@ -643,7 +645,8 @@ function findRoadmapBulletPhaseInContent(content: string, phaseNum: unknown, pha
|
||||
function getRoadmapPhaseInternal(cwd: string, phaseNum: unknown): RoadmapPhaseResult | null {
|
||||
if (!phaseNum) return null;
|
||||
const normalizedPhase = stripProjectCodePrefix(phaseNum);
|
||||
if (/^999(?:\.|$)/.test(normalizedPhase)) return null;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (isSentinelPhaseId(normalizedPhase)) return null;
|
||||
// Resolved INSIDE the try for the same reason as getMilestoneInfo below: planningDir
|
||||
// throws a plain Error for an invalid GSD_WORKSTREAM/GSD_PROJECT segment, and resolving
|
||||
// it outside let that escape uncaught, crashing every caller for a malformed workstream
|
||||
@@ -958,7 +961,11 @@ function getMilestonePhaseFilter(cwd: string, versionOverride?: string | null, p
|
||||
for (const h of tokenizeHeadings(roadmap)) {
|
||||
if (h.level < 2 || h.level > 4) continue;
|
||||
const pm = phaseHeadingPattern.exec(h.text);
|
||||
// Exclude 999.x backlog phases from milestone phase set. Mirrors init.cts filter.
|
||||
// #3185: deliberately NOT isSentinelPhaseId here. That predicate treats a
|
||||
// leading 0 as sentinel milestone 0, which would swallow the #2554 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.
|
||||
if (pm && !/^999\b/.test(pm[1])) milestonePhaseNums.add(pm[1]);
|
||||
}
|
||||
// #2199: also count bullet/checkbox phase entries (`- [ ] **Phase N — name**`)
|
||||
@@ -973,6 +980,11 @@ function getMilestonePhaseFilter(cwd: string, versionOverride?: string | null, p
|
||||
const scanner = new RegExp(BULLET_PHASE_LINE_PATTERN.source, 'gim');
|
||||
const roadmapUnfenced = stripFencedCode(roadmap).text;
|
||||
while ((bm = scanner.exec(roadmapUnfenced)) !== null) {
|
||||
// #3185: deliberately NOT isSentinelPhaseId here. That predicate treats a
|
||||
// leading 0 as sentinel milestone 0, which would swallow the #2554 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.
|
||||
if (!/^999\b/.test(bm[1])) milestonePhaseNums.add(bm[1]);
|
||||
}
|
||||
}
|
||||
@@ -1039,6 +1051,20 @@ function getMilestonePhaseFilter(cwd: string, versionOverride?: string | null, p
|
||||
const sm = stripped.match(numericRe);
|
||||
if (sm && normalized.has(normalizePhaseIdSegments(sm[1]).toLowerCase())) return true;
|
||||
}
|
||||
// #3185: last resort — ask the CANONICAL phase-id token extractor. The
|
||||
// three attempts above are all leading-DIGIT or bare-alnum shapes, so none
|
||||
// of them can match a #1324 letter-prefixed-DECIMAL directory
|
||||
// (`P0.0-foundation`) against its own `### Phase P0.0:` heading: numericRe
|
||||
// needs a leading digit, `customMatch` stops at the `.` and yields `P0`,
|
||||
// and stripProjectCodePrefix needs a dash before the digit. The observable
|
||||
// symptom was `stats` reporting such a phase with plans: 0 while its
|
||||
// directory held plan files, because the heading seeded the row but the
|
||||
// directory never folded in. extractPhaseToken is #2121's single owner of
|
||||
// "what is this directory's phase token", so this defers to it rather than
|
||||
// widening a fourth bespoke regex here. Additive: it can only ADMIT a
|
||||
// directory, never exclude one the attempts above already matched.
|
||||
const token = extractPhaseToken(dirName);
|
||||
if (token && normalized.has(normalizePhaseIdSegments(String(token)).toLowerCase())) return true;
|
||||
return false;
|
||||
}
|
||||
(isDirInMilestone as MilestonePhaseFilter).phaseCount = milestonePhaseNums.size;
|
||||
|
||||
@@ -14,7 +14,7 @@ import ioMod = require('./io.cjs');
|
||||
const { output, error } = ioMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import phaseIdMod = require('./phase-id.cjs');
|
||||
const { escapeRegex, normalizePhaseName, phaseMarkdownRegexSource, phaseTokenMatches, stripProjectCodePrefix, OPTIONAL_PHASE_TAG_SOURCE, roadmapPhaseLookupSources } = phaseIdMod;
|
||||
const { escapeRegex, normalizePhaseName, phaseMarkdownRegexSource, phaseTokenMatches, stripProjectCodePrefix, OPTIONAL_PHASE_TAG_SOURCE, roadmapPhaseLookupSources, isSentinelPhaseId } = phaseIdMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import phaseLocatorMod = require('./phase-locator.cjs');
|
||||
const { findPhaseInternal } = phaseLocatorMod;
|
||||
@@ -215,7 +215,8 @@ function searchPhaseInContent(content: string, escapedPhase: string, phaseNum: s
|
||||
* phase resolution as `roadmap.get-phase` — not a milestone-only subset.
|
||||
*/
|
||||
function getRoadmapPhaseWithFallback(cwd: string, phaseNum: string): string | null {
|
||||
if (/^999(?:\.|$)/.test(stripProjectCodePrefix(phaseNum))) return null;
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (isSentinelPhaseId(stripProjectCodePrefix(phaseNum))) return null;
|
||||
const roadmapPath = planningPaths(cwd).roadmap;
|
||||
// Read directly rather than gating on fs.existsSync: existsSync returns false
|
||||
// on EACCES/EIO too, which would mask an UNREADABLE roadmap as "missing" and
|
||||
@@ -247,7 +248,8 @@ function getRoadmapPhaseWithFallback(cwd: string, phaseNum: string): string | nu
|
||||
// ─── cmdRoadmapGetPhase ───────────────────────────────────────────────────────
|
||||
|
||||
function cmdRoadmapGetPhase(cwd: string, phaseNum: string, raw: boolean): void {
|
||||
if (/^999(?:\.|$)/.test(stripProjectCodePrefix(phaseNum))) {
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (isSentinelPhaseId(stripProjectCodePrefix(phaseNum))) {
|
||||
output({ found: false, phase_number: phaseNum }, raw, '');
|
||||
return;
|
||||
}
|
||||
@@ -338,17 +340,21 @@ function cmdRoadmapAnalyze(cwd: string, raw: boolean): void {
|
||||
}> = [];
|
||||
let match: RegExpExecArray | null;
|
||||
|
||||
// Phase 0 (pre-milestone) and Phase 999 (backlog) are sentinels, not real
|
||||
// phases. They legitimately have no directory and must never be surfaced as
|
||||
// current/next phase or counted in phase_count. Mirrors the engine-wide
|
||||
// sentinel convention (phase-id getMilestoneFromPhaseId, roadmap-command-router
|
||||
// SENTINELS, the #1445 /^999/ progress filters). (#1580)
|
||||
const isSentinelPhase = (num: string): boolean => {
|
||||
const major = parseInt(num, 10);
|
||||
return major === 0 || major === 999;
|
||||
};
|
||||
// #3185 (ADR-3180 Decision 1): the local `isSentinelPhase` closure was a
|
||||
// fourth independent copy of the sentinel rule (`parseInt(num,10) === 0 ||
|
||||
// === 999`). Deleted in favour of the canonical `isSentinelPhaseId`
|
||||
// (src/phase-id.cts, SENTINEL_RANGES) so the engine-wide convention #1580
|
||||
// describes has exactly one implementation. Phase 0 (pre-milestone) and
|
||||
// Phase 999 (backlog) are sentinels, not real phases: they legitimately
|
||||
// have no directory and must never be surfaced as current/next phase or
|
||||
// counted in phase_count.
|
||||
|
||||
// Build phase directory lookup once (O(1) readdir instead of O(N) per phase)
|
||||
// #3185 exemption (documented reason, not a file allowlist — ADR-3180
|
||||
// Decision 4a): this is a heading->directory LOOKUP INDEX, not a milestone
|
||||
// enumeration. It must see the PHYSICAL set so a heading already scoped by
|
||||
// extractCurrentMilestoneScoped above can find its directory; filtering it
|
||||
// through listMilestonePhaseDirs would scope the same set twice.
|
||||
const _phaseDirNames = (() => {
|
||||
try {
|
||||
return fs.readdirSync(phasesDir, { withFileTypes: true })
|
||||
@@ -359,7 +365,7 @@ function cmdRoadmapAnalyze(cwd: string, raw: boolean): void {
|
||||
|
||||
while ((match = phasePattern.exec(content)) !== null) {
|
||||
const phaseNum = match[1];
|
||||
if (isSentinelPhase(phaseNum)) continue;
|
||||
if (isSentinelPhaseId(phaseNum)) continue;
|
||||
const phaseName = match[2].replace(/\(INSERTED\)/i, '').trim();
|
||||
|
||||
// Extract goal from the section
|
||||
@@ -476,7 +482,7 @@ function cmdRoadmapAnalyze(cwd: string, raw: boolean): void {
|
||||
checklistPhases.add(checklistMatch[1]);
|
||||
}
|
||||
const detailPhases = new Set(phases.map(p => p.number));
|
||||
const missingDetails = [...checklistPhases].filter(p => !detailPhases.has(p) && !isSentinelPhase(p));
|
||||
const missingDetails = [...checklistPhases].filter(p => !detailPhases.has(p) && !isSentinelPhaseId(p));
|
||||
|
||||
const result = {
|
||||
milestones,
|
||||
|
||||
@@ -16,10 +16,10 @@ import configLoaderMod = require('./config-loader.cjs');
|
||||
const { loadConfig } = configLoaderMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import phaseIdMod = require('./phase-id.cjs');
|
||||
const { escapeRegex, parsePhaseFromProse, PHASE_NUMBER_TOKEN_SOURCE, phaseKeyFromToken, phaseKeyFromDir } = phaseIdMod;
|
||||
const { escapeRegex, parsePhaseFromProse, PHASE_NUMBER_TOKEN_SOURCE, phaseKeyFromToken, phaseKeyFromDir, isSentinelPhaseId } = phaseIdMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import roadmapParserMod = require('./roadmap-parser.cjs');
|
||||
const { getMilestoneInfo, getMilestonePhaseFilter, extractCurrentMilestone, isMilestoneBoundedInRoadmap, hasMilestoneSectioning } = roadmapParserMod;
|
||||
const { getMilestoneInfo, extractCurrentMilestone, isMilestoneBoundedInRoadmap, hasMilestoneSectioning } = roadmapParserMod;
|
||||
import { platformWriteSync, platformReadSync, platformEnsureDir, retryRenameSync, toPosixPath } from './shell-command-projection.cjs';
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import planningWorkspace = require('./planning-workspace.cjs');
|
||||
@@ -34,6 +34,9 @@ import scanPhasePlans = require('./plan-scan.cjs');
|
||||
import planningScopeMod = require('./planning-scope.cjs');
|
||||
const { SCOPE } = planningScopeMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import phaseLocatorMod = require('./phase-locator.cjs');
|
||||
const { listMilestonePhaseDirs } = phaseLocatorMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import stateTransitionMod = require('./state-transition.cjs');
|
||||
const { transitionCore, applyStatePreservation, sliceCurrentPositionSection } = stateTransitionMod;
|
||||
type StateTransitionIntent = stateTransitionMod.StateTransitionIntent;
|
||||
@@ -748,11 +751,14 @@ function cmdStateUpdateProgress(cwd: string, raw: boolean): void {
|
||||
let totalPlans = 0;
|
||||
let totalSummaries = 0;
|
||||
|
||||
if (fs.existsSync(phasesDir)) {
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd) as (dir: string) => boolean;
|
||||
const phaseDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
|
||||
.filter(e => e.isDirectory()).map(e => e.name)
|
||||
.filter(isDirInMilestone);
|
||||
{
|
||||
// #3185 (ADR-3180 Decision 1): "which phase directories belong to the
|
||||
// CURRENT milestone" — routed through the canonical owner instead of a
|
||||
// hand-rolled readdirSync + isDirInMilestone filter (which also never
|
||||
// excluded sentinels, unlike the owner). The owner already handles an
|
||||
// absent phasesDir as a real empty, so the fs.existsSync guard folds
|
||||
// into it.
|
||||
const phaseDirs = listMilestonePhaseDirs(phasesDir, { cwd }).value;
|
||||
for (const dir of phaseDirs) {
|
||||
const { planCount, summaryCount } = scanPhasePlans(path.join(phasesDir, dir));
|
||||
totalPlans += planCount;
|
||||
@@ -1697,10 +1703,11 @@ function buildStateFrontmatter(bodyContent: string, cwd: string | undefined, sto
|
||||
// #3017: scope the milestone filter to the STORED milestone when available,
|
||||
// so a state.* write doesn't auto-derive (and mis-bind) to a different
|
||||
// milestone's heading and clobber the stored value + progress counts.
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd, storedMilestone ?? undefined) as (dir: string) => boolean;
|
||||
const allMatchingDirs = fs.readdirSync(phasesDir, { withFileTypes: true })
|
||||
.filter(e => e.isDirectory()).map(e => e.name)
|
||||
.filter(isDirInMilestone);
|
||||
// #3185 (ADR-3180 Decision 1): "which phase directories belong to the
|
||||
// CURRENT (stored) milestone" — routed through the canonical owner
|
||||
// instead of a hand-rolled readdirSync + isDirInMilestone filter
|
||||
// (which also never excluded sentinels, unlike the owner).
|
||||
const allMatchingDirs = listMilestonePhaseDirs(phasesDir, { cwd, versionOverride: storedMilestone ?? null }).value;
|
||||
|
||||
// Bug #2445: when stale phase dirs from a prior milestone remain in
|
||||
// .planning/phases/ alongside new dirs with the same phase number,
|
||||
@@ -1756,8 +1763,9 @@ function buildStateFrontmatter(bodyContent: string, cwd: string | undefined, sto
|
||||
// Only count tokens that contain at least one digit — excludes
|
||||
// pure-word section headings (Overview, Details) while keeping
|
||||
// numeric phases (01, 05.1) and project-code IDs (PROJ-42).
|
||||
// Also exclude 999.x backlog phases. Mirrors init.cts filter.
|
||||
if (!/\d/.test(m[1]) || /^999\b/.test(m[1])) continue;
|
||||
// Also exclude sentinel phases (0 and 999.x backlog).
|
||||
// #3185: canonical sentinel predicate (SENTINEL_RANGES [0,999]) — this was a local 999-only literal that admitted Phase 0.
|
||||
if (!/\d/.test(m[1]) || isSentinelPhaseId(m[1])) continue;
|
||||
// #1514: retired/folded phases are struck through in the ROADMAP;
|
||||
// exclude them from the denominator (they can never be completed).
|
||||
if (retiredPhaseNums.has(phaseKeyFromToken(m[1]))) continue;
|
||||
@@ -3179,6 +3187,11 @@ function cmdStateRebuild(cwd: string, options: StateRebuildOptions, raw: boolean
|
||||
try {
|
||||
const phasesDir = path.join(planningPaths(cwd).planning, 'phases');
|
||||
if (!fs.existsSync(phasesDir) || !fs.statSync(phasesDir).isDirectory()) return { ok: true, phases: [] };
|
||||
// #3185: deliberately NOT 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 window) is dropped. Scoping this
|
||||
// would make the rebuild silently preserve stale rows.
|
||||
const entries = fs.readdirSync(phasesDir);
|
||||
const records: PhaseInventoryRecord[] = [];
|
||||
for (const entry of entries) {
|
||||
|
||||
22
src/uat.cts
22
src/uat.cts
@@ -21,9 +21,6 @@ const { collectSection, tokenizeHeadings } = markdownSectionizer;
|
||||
import markdownTable = require('./markdown-table.cjs');
|
||||
const { splitTableRow, isDelimiterRow } = markdownTable;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import roadmapParser = require('./roadmap-parser.cjs');
|
||||
const { getMilestonePhaseFilter } = roadmapParser;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import coreUtils = require('./core-utils.cjs');
|
||||
const { toPosixPath } = coreUtils;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
@@ -37,7 +34,7 @@ import phaseIdMod = require('./phase-id.cjs');
|
||||
const { PHASE_NUMBER_TOKEN_SOURCE } = phaseIdMod;
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
import phaseLocator = require('./phase-locator.cjs');
|
||||
const { getArchivedPhaseDirs } = phaseLocator;
|
||||
const { getArchivedPhaseDirs, listMilestonePhaseDirs } = phaseLocator;
|
||||
import { requireSafePath, sanitizeForDisplay } from './security.cjs';
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- config-loader.cjs is an export= CommonJS module
|
||||
import configLoader = require('./config-loader.cjs');
|
||||
@@ -105,21 +102,20 @@ function cmdAuditUat(cwd: string, raw: boolean): void {
|
||||
error('No phases directory found in planning directory');
|
||||
}
|
||||
|
||||
const isDirInMilestone = getMilestonePhaseFilter(cwd);
|
||||
const results: UatFileResult[] = [];
|
||||
|
||||
// Active dirs are milestone-filtered; archived dirs deliberately are NOT.
|
||||
// getMilestonePhaseFilter derives the CURRENT milestone's phase numbers from
|
||||
// ROADMAP.md, and archived phases belong to past milestones by definition — so
|
||||
// applying it to them discards every one and silently reinstates the bug.
|
||||
// listMilestonePhaseDirs derives the CURRENT milestone's phase directories
|
||||
// (window + sentinel filtered) from ROADMAP.md, and archived phases belong
|
||||
// to past milestones by definition — so applying it to them discards every
|
||||
// one and silently reinstates the bug.
|
||||
const scanTargets: { dir: string; phaseDir: string; milestone?: string }[] = [];
|
||||
|
||||
if (hasActivePhases) {
|
||||
const dirs = fs.readdirSync(phasesDir, { withFileTypes: true })
|
||||
.filter(e => e.isDirectory())
|
||||
.map(e => e.name)
|
||||
.filter(isDirInMilestone)
|
||||
.sort();
|
||||
// #3185 (ADR-3180 Decision 1): routed through the canonical owner
|
||||
// instead of a hand-rolled readdirSync + isDirInMilestone filter, which
|
||||
// also never excluded sentinels, unlike the owner.
|
||||
const dirs = listMilestonePhaseDirs(phasesDir, { cwd }).value;
|
||||
for (const dir of dirs) {
|
||||
scanTargets.push({ dir, phaseDir: path.join(phasesDir, dir) });
|
||||
}
|
||||
|
||||
@@ -78,11 +78,26 @@ function workstreamsRoot(cwd: string): string {
|
||||
return path.join(planningRoot(cwd), 'workstreams');
|
||||
}
|
||||
|
||||
function countRoadmapPhases(roadmapPath: string, fallbackCount: number): number {
|
||||
/**
|
||||
* #3185 (ADR-3180 Decision 1): count the phases the CURRENT milestone
|
||||
* declares, not every `Phase` heading in the file.
|
||||
*
|
||||
* This previously matched `^#{2,4}\s+Phase\s+…` across the whole ROADMAP with
|
||||
* no milestone window and no sentinel filter, so it counted 999.* backlog and
|
||||
* Phase 0 headings and spanned every milestone the document had ever had.
|
||||
* `getMilestonePhaseFilter` already computes exactly this number for the
|
||||
* scoped window (`phaseCount`, sentinel-filtered), and `inspectWorkstream` in
|
||||
* this same file already passes a resolved `currentVersion` to it — this
|
||||
* function was the sibling copy that never got the fix.
|
||||
*/
|
||||
function countRoadmapPhases(roadmapPath: string, fallbackCount: number, cwd?: string, ws?: string | null, versionOverride?: string | null): number {
|
||||
try {
|
||||
const roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
|
||||
const matches = roadmapContent.match(/^#{2,4}\s+Phase\s+[\w][\w.-]*/gm);
|
||||
return matches ? matches.length : fallbackCount;
|
||||
if (!fs.existsSync(roadmapPath)) return fallbackCount;
|
||||
if (!cwd) return fallbackCount;
|
||||
const filter = getMilestonePhaseFilter(cwd, versionOverride ?? null, null, ws ?? null);
|
||||
// A pass-all degrade (phaseCount 0) means the window declared no phases —
|
||||
// fall back rather than reporting a confident zero.
|
||||
return filter.phaseCount > 0 ? filter.phaseCount : fallbackCount;
|
||||
} catch {
|
||||
return fallbackCount;
|
||||
}
|
||||
@@ -717,7 +732,7 @@ function inspectWorkstream(cwd: string, name: string, options: InspectWorkstream
|
||||
// declares in its Progress table but never scaffolded — the heading-only
|
||||
// count drops them, even when other headings exist. Union the declared rows
|
||||
// with the phase directories so neither source can silently shrink it.
|
||||
let fallbackPhaseCount = countRoadmapPhases(p.roadmap, phaseDirNames.length);
|
||||
let fallbackPhaseCount = countRoadmapPhases(p.roadmap, phaseDirNames.length, cwd, name, currentVersion);
|
||||
if (!scoped && progressRows.length > 0) {
|
||||
const union = new Set(progressRows.map(row => row.key));
|
||||
for (const entry of phaseFilesCounts) union.add(entry.phaseKey);
|
||||
|
||||
Reference in New Issue
Block a user