Files
msd-core/src/phase-locator.cts
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

406 lines
17 KiB
TypeScript

/**
* Phase Locator — Phase-directory search and location
*
* ADR-857 rollout phase 2d: extracted from core.cts (issue #881).
* Owns active-phase discovery against the `.planning/phases/` tree
* (`searchPhaseInDir`, `findPhaseInternal`) and archived-phase-dir
* enumeration (`getArchivedPhaseDirs`), matching phase ids/tokens against
* the filesystem. Behaviour is preserved byte-for-behaviour from the prior
* location; only the module boundary moved. The core.cjs re-export spine
* was retired in epic #1267; callers import phase-locator helpers directly.
*
* Dependencies (leaf modules only — no loadConfig):
* - node:fs / node:path (stdlib)
* - ./phase-id.cjs (normalizePhaseName, phaseTokenMatches, extractPhaseToken)
* - ./core-utils.cjs (readSubdirectories, getPhaseFileStats, extractCanonicalPlanId, toPosixPath)
* - ./planning-workspace.cjs (planningDir)
*/
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, 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;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import planningWorkspace = require('./planning-workspace.cjs');
const { planningDir } = planningWorkspace;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import frontmatterModule = require('./frontmatter.cjs');
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 ───────────────────────────────────────────────────────
interface PhaseSearchResult {
found: boolean;
directory: string;
phase_number: string;
phase_name: string | null;
phase_slug: string | null;
plans: string[];
summaries: string[];
incomplete_plans: string[];
has_research: boolean;
has_context: boolean;
has_verification: boolean;
has_reviews: boolean;
archived?: string;
ambiguous_matches?: string[];
/**
* #2830: plan filenames (from `plans`) whose own SUMMARY declares
* `status: halted` — a designed stop, not an ordinary completion.
*/
halted_plans: string[];
/**
* #2830: plan filename -> the halted plan id(s) (canonical, e.g. "01-02")
* transitively blocking it, for every entry in `incomplete_plans` that is
* blocked by an upstream halt. A plan filename absent from this map is not
* blocked (either not incomplete, or incomplete with no halted upstream).
*/
blocked_by: Record<string, string[]>;
/**
* #2830: the runnable-only view — `incomplete_plans` filtered to exclude
* anything present as a key in `blocked_by`. `incomplete_plans` itself
* keeps its pre-#2830 meaning ("no matching SUMMARY yet") unchanged.
*/
runnable_plans: string[];
}
/**
* #2830: parse a plan file's `depends_on` frontmatter. Returns [] — never
* throws — on a missing/unreadable/malformed plan or absent field, matching
* this primitive's existing fail-safe posture (a plan directory this
* primitive can otherwise read must never throw here).
*/
function parsePlanDependsOn(phaseDir: string, planFile: string): string[] {
try {
const planPath = path.join(phaseDir, planFile);
const content = fs.readFileSync(planPath, 'utf-8');
const fm = extractFrontmatter(content, planPath);
const fmDeps = fm['depends_on'];
if (Array.isArray(fmDeps)) return fmDeps.map(String);
if (typeof fmDeps === 'string' && fmDeps.trim() !== '') return [fmDeps];
return [];
} catch {
return [];
}
}
interface ArchivedPhaseDir {
name: string;
milestone: string;
basePath: string;
fullPath: string;
}
interface ArchiveVersionDir {
version: string;
archivePath: string;
}
// ─── Phase search helpers ─────────────────────────────────────────────────────
/**
* #2855: single source of truth for resolving and enumerating a project's
* (or, when a workstream is active, that workstream's OWN) archived-milestone
* directories — `<planningDir(cwd)>/milestones/vX.Y-phases/`. Both
* `findPhaseInternal`'s archive fallback and `getArchivedPhaseDirs` used to
* carry independent copies of this resolve-then-enumerate logic, which is
* exactly the shape that let the original #2855 bug (hardcoded root path)
* exist in one copy and not the other. Sharing this seam means a future
* change to how the archive tree is located only needs to happen once.
* Most-recent-milestone-first order (reverse-sorted directory names).
* Never throws: an absent/unreadable milestones/ dir yields [].
*/
function listArchiveVersionDirs(cwd: string): ArchiveVersionDir[] {
const milestonesDir = path.join(planningDir(cwd), 'milestones');
if (!fs.existsSync(milestonesDir)) return [];
try {
const milestoneEntries = fs.readdirSync(milestonesDir, { withFileTypes: true });
return milestoneEntries
.filter(e => e.isDirectory() && /^v[\d.]+-phases$/.test(e.name))
.map(e => e.name)
.sort()
.reverse()
.map(archiveName => ({
version: archiveName.match(/^(v[\d.]+)-phases$/)![1],
archivePath: path.join(milestonesDir, archiveName),
}));
} catch {
return [];
}
}
function searchPhaseInDir(baseDir: string, relBase: string, normalized: string): PhaseSearchResult | null {
try {
const dirs = readSubdirectories(baseDir, true);
const matches = dirs.filter(d => phaseTokenMatches(d, normalized));
if (matches.length === 0) return null;
// #2237: fail loud when multiple directories match the same bare phase
// number — this happens when unrelated projects share a .planning/phases/
// tree. Silently taking the first match risks cross-project file writes.
if (matches.length > 1) {
return {
found: false,
directory: '',
phase_number: normalized,
phase_name: null,
phase_slug: null,
plans: [],
summaries: [],
incomplete_plans: [],
has_research: false,
has_context: false,
has_verification: false,
has_reviews: false,
ambiguous_matches: matches,
halted_plans: [],
blocked_by: {},
runnable_plans: [],
};
}
const match = matches[0];
const phaseToken = extractPhaseToken(match);
const phaseNumber = phaseToken || normalized;
const afterToken = match.slice(phaseToken ? phaseToken.length : 0).replace(/^-/, '');
const phaseName = afterToken || null;
const phaseDir = path.join(baseDir, match);
const { plans: unsortedPlans, summaries: unsortedSummaries, hasResearch, hasContext, hasVerification, hasReviews } = getPhaseFileStats(phaseDir);
const plans = unsortedPlans.sort();
const summaries = unsortedSummaries.sort();
// #3183 (ADR-3180 Decision 2): the summary→plan pairing used to be a
// bespoke rule local to this function (a third pairing rule alongside
// scanPhasePlans's completion check and countMatchedSummaries). Routed
// through the canonical core-utils.findUnsummarizedPlans instead, which
// shares its `summaryCandidates` matching rule with countMatchedSummaries
// so the count and this named list can never disagree.
const incompletePlans = findUnsummarizedPlans(plans, summaries);
// #2830: reverse lookup from a completed plan's id (exact or canonical) to
// its actual summary filename. Shared builder (also used by phase.cts's
// cmdPhasePlanIndex) so the two can never disagree about which summary
// belongs to which plan.
const summaryFileByPlanId = buildSummaryFileIndex(summaries, extractCanonicalPlanId);
// #2830: this primitive previously never parsed depends_on at all — see
// src/plan-dependency-graph.cts's file header. Build the same
// PlanHaltNode[] shape phase.cts's cmdPhasePlanIndex builds (id resolution
// mirrors its planMap/canonicalToId pattern) and hand it to the ONE
// shared halt-propagation traversal so this reader and the wave-grouping
// reader can never diverge on the halt rule again.
const planIds = plans.map(p => p.replace('-PLAN.md', '').replace('PLAN.md', ''));
const planIdByLower = new Map(planIds.map(id => [id.toLowerCase(), id]));
const canonicalToPlanId = new Map(
plans.map((p, i) => [extractCanonicalPlanId(p).toLowerCase(), planIds[i]]),
);
const haltNodes = plans.map((p, i) => {
const planId = planIds[i];
const canonical = extractCanonicalPlanId(p);
const summaryFile = summaryFileByPlanId.get(planId) ?? summaryFileByPlanId.get(canonical);
const halted = summaryFile !== undefined && isSummaryFileHalted(path.join(phaseDir, summaryFile));
const resolvedDependsOn = parsePlanDependsOn(phaseDir, p)
.map((dep) => {
const lower = dep.toLowerCase();
return planIdByLower.get(lower) ?? canonicalToPlanId.get(lower) ?? null;
})
.filter((id): id is string => id !== null);
return { id: planId, resolvedDependsOn, halted };
});
const { blockedBy } = computeHaltPropagation(haltNodes);
const haltedPlans = plans.filter((_, i) => haltNodes[i].halted);
const incompletePlanSet = new Set(incompletePlans);
const blockedByFiles: Record<string, string[]> = {};
const runnablePlans: string[] = [];
for (let i = 0; i < plans.length; i++) {
const p = plans[i];
if (!incompletePlanSet.has(p)) continue;
const causes = blockedBy.get(planIds[i]) ?? [];
if (causes.length > 0) {
blockedByFiles[p] = causes;
} else {
runnablePlans.push(p);
}
}
return {
found: true,
directory: toPosixPath(path.join(relBase, match)),
phase_number: phaseNumber,
phase_name: phaseName,
phase_slug: phaseName ? phaseName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : null,
plans,
summaries,
incomplete_plans: incompletePlans,
has_research: hasResearch,
has_context: hasContext,
has_verification: hasVerification,
has_reviews: hasReviews,
halted_plans: haltedPlans,
blocked_by: blockedByFiles,
runnable_plans: runnablePlans,
};
} catch {
return null;
}
}
function findPhaseInternal(cwd: string, phase: unknown): PhaseSearchResult | null {
if (!phase) return null;
const phasesDir = path.join(planningDir(cwd), 'phases');
const normalized = normalizePhaseName(phase);
const relPhasesDir = toPosixPath(path.relative(cwd, phasesDir));
const current = searchPhaseInDir(phasesDir, relPhasesDir, normalized);
if (current) return current;
// #2855: scope the archived-milestone fallback to the SAME workstream as the
// active-phase search above (planningDir(cwd) resolves GSD_WORKSTREAM/GSD_PROJECT
// the identical way both places), not the hardcoded project-root tree. Archived
// phases genuinely live under a workstream's own `.planning/workstreams/<ws>/
// milestones/` — that is where archivePhaseDirectories (milestone.cts) writes
// them via the same planningDir(cwd) resolution. Hardcoding root here let a
// pending workstream phase resolve to an unrelated workstream's (or a flat-mode
// project's) archived phase that merely shares a phase number. Shared with
// getArchivedPhaseDirs via listArchiveVersionDirs (see its doc comment).
for (const { version, archivePath } of listArchiveVersionDirs(cwd)) {
const relBase = toPosixPath(path.relative(cwd, archivePath));
const result = searchPhaseInDir(archivePath, relBase, normalized);
if (result) {
result.archived = version;
return result;
}
}
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`
// (the primary non-init consumer) must not leak a different workstream's
// archive either.
const results: ArchivedPhaseDir[] = [];
for (const { version, archivePath } of listArchiveVersionDirs(cwd)) {
const dirs = readSubdirectories(archivePath, true);
for (const dir of dirs) {
results.push({
name: dir,
milestone: version,
basePath: toPosixPath(path.relative(cwd, archivePath)),
fullPath: path.join(archivePath, dir),
});
}
}
return results;
}
export = {
searchPhaseInDir,
findPhaseInternal,
getArchivedPhaseDirs,
listMilestonePhaseDirs,
};