Files
msd-core/src/verification.cts
Tom Boucher 9a76ca6783 fix(#1882): distinguish unterminated frontmatter from absent frontmatter (#2712)
* fix(#1882): distinguish unterminated frontmatter from absent frontmatter

extractFrontmatter returned {} both for a document with no frontmatter and for
one whose fence was opened and never closed, so a file truncated mid-write was
byte-identical to a legitimate no-metadata file. Verified live through
`gsd-tools frontmatter get`: both printed {} with exit 0 and nothing on stderr.

Per ADR-1411's "corrupt is not absent" amendment the {} return is preserved
exactly -- no caller may break -- and the cause is surfaced out-of-band as a
deduplicated, unconditional stderr diagnostic. That mechanism lands as a shared
leaf module rather than a per-site copy because three sibling findings in the
same epic need it identically; four hand-rolled copies of one behaviour is the
generative-fix-divergence defect class.

The discriminator is deliberately not "opened but never closed". A Markdown
document whose first line is a thematic break takes that exact branch, so
flagging on the missing fence alone reports corruption on good Markdown -- the
failure mode this class of check has shipped with before. The unterminated
region is instead run through extractFrontmatter's own parser (extracted as
parseYamlRegion so the probe and the real parse can never diverge) and reported
only when it yields at least one key.

Also folds an inline defect found while working: src/config-loader.cts carried
two NUL bytes in the JSDoc added by this epic's Phase 1 (3eb1cede2), making it
the only non-text file under src. file(1) reported it as data and text tools
silently skipped it, defeating the audit rule that says to search the authored
source; tsc passed because the bytes sat inside a comment, so no gate caught it.
It is live on next.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(#1882): pin unterminated-frontmatter detection and its negative space

Covers the discriminator on both sides. The positive rows are the issue's own
repro (LF and CRLF) plus the key-count boundary 0/1/2 around the ">= 1 parsed
key" threshold. The negative rows are the documents that reach the same branch
and must stay silent -- above all a Markdown thematic break at byte 0, which is
how this class of check has previously shipped a false positive on valid
Markdown.

Deduplication is tested on both halves of the composite key: a repeat of the
same (path, cause) is suppressed, a genuine second failure in a different file
is not, and a Windows and POSIX spelling of one path resolve to a single key.
The reset seam is asserted to actually clear -- #2674 is the precedent where a
reset that silently failed to clear made every later dedup assertion a vacuous
pass, and the cases only passed because each happened to pick an unused key, so
every case here uses a path unique to itself.

Assertions are on typed surfaces throughout -- the frozen reason enum and the
dedup-set size -- never on diagnostic prose. The one CLI-level case asserts a
differential between two runs (whether stderr is empty) rather than matching a
message, and is the wired user-reachable surface for this fix. Stream failure is
injected by overriding process.stderr.write and restoring it, never chmod 0o000,
which root bypasses.

Two properties guard the ~50 call sites of the changed function: the new
optional path argument is inert with respect to the parsed value, and LF/CRLF
spellings of a document still parse identically.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#1882): raise the truncation threshold and repair the dedup key

Isolated adversarial review found the one-key discriminator false-positives on
ordinary Markdown: a thematic break above a single labelled line -- `Note:`,
`Author:`, `TODO:`, `See:` -- parses as exactly one key and was reported as
corruption, which is the precise failure the design claimed to prevent and the
changeset promised was fixed. The threshold is now two keys. A file truncated
after exactly one key becomes a false negative; that is the same
precision-over-recall direction already taken at zero keys, and every GSD
artefact this guards carries two or more frontmatter keys.

Three dedup-key defects, each of which could silently swallow a real diagnostic:

- Backslash normalization is removed. A backslash is a legal filename character
  on Linux and macOS, so folding it to a forward slash made two genuinely
  different files share one key. Two spellings of one Windows path may now
  report twice; two distinct files can never silence each other. Lost signal is
  the worse failure.
- The key namespaces are tagged so a file literally named like the unnamed
  digest fallback can no longer collide with a path-less caller whose content
  hashes to that digest -- computable for any predictable content, no brute
  force needed.
- The source identity is computed once rather than hashed twice per emission.

Corrects the previous commit. The two NUL bytes in src/config-loader.cts were
NOT in a JSDoc comment as that message claimed; they were deliberate separators
in the live dedup key, and stripping them degraded it to bare concatenation.
They are restored as escape sequences -- byte-identical runtime string, and the
file is text again so grep can see it. The diagnostic script that misled me
indexed a character-offset string with a byte offset.

Also threads sourcePath through the STATE.md and PLAN.md readers so the two
artefacts epic #1879 is actually about name their file rather than reporting
under a content digest.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(#1882): correct fixtures and assertions left behind by the review fixes

The previous commit changed two behaviours deliberately and the suite still
encoded the old ones, so gsd-test came back red with six failures across both
lanes -- all of them mine.

Fixtures carrying a single frontmatter key no longer clear the two-key
truncation threshold, so the CLI differential and the two path-less dedup cases
were asserting a diagnostic that is now correctly withheld. They now carry two
keys, which is what a real interrupted write of a GSD artefact looks like.

The Windows/POSIX case asserted that two spellings of one path collapse to a
single key -- the exact folding that was removed because it also collapsed
genuinely distinct POSIX files whose names contain a backslash. Inverted to
assert they now report separately, with the reasoning recorded inline so the
trade is not silently reversed later: mild duplicate noise on one Windows path
is acceptable, a swallowed diagnostic is not.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#1882): name the file at every read site, and report each file once

The diagnostic reached only the four frontmatter CLI verbs, so ~47 of 53 call
sites reported a truncated file under an anonymous content digest instead of
naming it. Since naming the file is the whole point -- it is what an operator
can act on -- that was a gap in the deliverable, not a scoping choice. 43 of 53
sites now pass the resolved path.

Closing it surfaced a defect the original design missed. A single truncated
STATE.md is parsed twice in a normal run: once by the read wrapper, which holds
the path, and again by a pure core downstream, which is handed only the string
and cannot know it. Those two parses keyed separately, so one file produced two
diagnostics -- and wiring more sites made the collision more likely, not less.
Every emission now registers both identities the input could be known by and
checks both before writing, so whichever caller arrives first speaks and the
other is suppressed. Distinct files with distinct content still report
separately, which is the property ADR-1411 actually requires; two files whose
truncated content is byte-identical collapse to one report, which stays the
documented limit.

Ten call sites deliberately keep no path. Two are frontmatter's own round-trip
checks during set and merge, where passing a path would report on every write.
The other eight are the state-transition pure cores, which ADR-1769 defines as
(content, intent, deps) -> newContent with injected I/O; threading a path
through them would contradict that recorded decision, so it is surfaced rather
than taken unilaterally. With the widened key they no longer double-report, and
in the normal flow the named parse runs first, so the file is still named.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#1882): inject the STATE.md path into the transition cores

The six state-transition cores parsed STATE.md frontmatter without knowing
which file it came from, so a truncated STATE.md reached the operator as an
anonymous content digest on exactly the artefact epic #1879 is named for.

ADR-1769 section 3 shapes these as (content, intent, deps) -> newContent with
injected deps, and deps is the seam for precisely this: something the core
cannot derive without doing I/O. It already carries roadmapProvider and a
phase-inventory provider on that basis, each documented as injected rather than
imported so the core stays pure and testable without disk access. A resolved
path is data, not I/O, so an optional sourcePath member extends the established
pattern rather than contradicting it, and every existing stub keeps compiling
because the member is optional.

updateCore and reconcileCurrentPosition take no deps and are left alone. With
the widened dedup key they cannot double-report, and in the normal flow the read
wrapper has already named the file by the time they run.

Also regenerates gsd-core/bin/lib/state-transition.cjs. That artifact is tracked
rather than gitignored, unlike most of its siblings, so leaving it stale would
have shipped a runtime without this change to anyone reading the repo without
building. tsc had skipped the re-emit because its incremental build info still
recorded an emit that had since been reverted, so the stale output survived a
clean build; clearing tsconfig.build.tsbuildinfo forced it. The
compiled-artifact-sync gate is what surfaced the drift and now reports all nine
tracked artifacts matching their source.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#1882): stop the widened dedup key from hiding a second file

The previous commit widened the dedup guard so one file parsed twice -- once by
a read wrapper holding the path, once by a pure core holding only the string --
reported once instead of twice. It did that by checking BOTH keys before
emitting, which silently traded one defect for a worse one: two DIFFERENT files
whose truncated content happened to be byte-identical now collided on the shared
content digest, and the second file's diagnostic was swallowed. That is the
over-coarse keying ADR-1411 explicitly forbids, reintroduced while fixing
something else.

The guard now checks only the key matching what the caller actually knows -- a
named read checks its path key, a path-less read checks its digest key -- while
still recording every key the input could later be identified by. The redundant
path-less re-parse of an already-named file stays silent, and two distinct files
always both report.

Verified across all six orderings: same file named-then-anonymous reports once;
two different files with identical content report twice; two different files
with different content report twice; the same path twice reports once; two
path-less parses of identical content report once; two path-less parses of
different content report twice.

The suite caught this -- twenty failures, all in the unusable-input tests that
reuse one truncated fixture across different paths. The local probe written
alongside the broken change did not, because it compared two files with
different content and could therefore only confirm the expected behaviour.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(#1882): count diagnostics emitted, not identities interned

The suite measured the size of the dedup set as a stand-in for "how many
diagnostics were emitted". That held only while one emission recorded exactly
one key. Once an emission began recording every identity the input could later
be matched by -- a path key and a content key for the same file -- the set grew
by two per write and twenty assertions read 2 where they expected 1.

The production behaviour was correct throughout; the proxy was not. Set size
counts identities, which is an implementation detail of the guard. The
behavioural claim these tests exist to make is how many diagnostics an operator
actually saw, so the module now exposes that directly as an emission counter and
the suite asserts on it. The set-size accessor stays for assertions genuinely
about key shape.

The local probe written alongside the change did not catch this because it
counted process.stderr.write calls -- the right thing -- while the suite counted
set growth. Verification now asserts both and requires them to agree, so a
future divergence between the counter and real writes fails immediately rather
than being discovered a bench run later.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(#1882): retire two assertions that outlived the behaviour they described

Both tests encoded assumptions the dedup fix invalidated, and both were caught
by the suite rather than by the probe written alongside the change.

The forged-path case asserted that a file named like the anonymous digest
fallback must not suppress a later path-less report. That premise is gone: an
emission now records every identity its input could be matched by, so ANY named
report of some content silences the anonymous re-parse of that same content --
which is the same-file guard working as intended, and has nothing to do with the
crafted name. The property still worth defending is that a crafted filename can
never silence a real file reported under its own path, so that is what the test
now asserts, with the deliberate suppression documented beside it.

The reset-seam case ended by reading the size of the dedup set and expecting 1.
Set size counts interned identities, not diagnostics written, and one emission
now interns two. It asserts the emission counter for the event and keeps a
weaker set-size check for the interning.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#1882): close the review findings on the discriminator, dry-run and counter

Three orthogonal review passes ran against the final diff. Their findings:

A labelled preamble under a leading rule was still misreported. Raising the key
threshold to two only moved the boundary, because two colon-labelled lines are
as common in ordinary prose as one -- a document opening with a rule over an
Author and a Reviewed-by line, then prose, was called corrupt. Key count alone
cannot separate the two. What does is what follows: a write interrupted part way
through a frontmatter block ends mid-block, so every line of the region is still
frontmatter-shaped, whereas a document merely opening with a rule goes on to
prose. Both conditions are now required, and each closes a false-positive class
the other leaves open. Nested list values and indented continuations stay
frontmatter-shaped, so legitimate truncations are unaffected.

`state rebuild --dry-run` reported a truncated STATE.md anonymously. The write
path is named only because readModifyWriteStateMd parses with the path first;
the dry-run branch reads the file directly and never did. Dry-run is the
read-only mode an operator reaches for first when they suspect corruption, so it
is the one that most needed to name the file. reconcileCurrentPosition takes the
path as an optional argument now and rebuildCore passes it down. That function
was previously left alone on the grounds that a read wrapper always names the
file first -- this is the flow that disproves it.

The emission counter counted write attempts rather than writes, so on a broken
stderr it claimed a diagnostic had reached the operator when nothing had. It is
incremented only after a write that completed, and the broken-stderr test now
asserts the count as well as the return value.

Two documentation defects. The module described a guarantee it does not keep:
one file yields one diagnostic only when the named read comes first. The reverse
ordering emits twice, and that is deliberate -- a path-less caller cannot
identify its file, so suppressing the later named report would also suppress a
genuine second failure in a different file whenever two files share identical
truncated bytes, which ADR-1411 ranks the worse failure. The comment now states
the asymmetric guarantee and a test pins it. Separately, the CONTEXT.md glossary
entry still described backslash normalization that a later commit removed, and
asserted the opposite of what the tests pin; no lint checks prose against code,
so nothing caught it.

Also converts three body-level try/finally blocks to t.after(), per
CONTRIBUTING.md's rule that try/finally belongs only in helpers with no test
context -- the file's own emissionsDuring helper already did this correctly.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(#1882): tell the operator what the truncated-frontmatter warning means

A user who has just seen the new warning is acting, not studying, so this lands
in the How-To quadrant beside the other "if you see X" branches in
debug-a-failed-execution, not in reference or explanation. It gives them what
the warning means for this run, three steps to restore the file, and the fact
that the warning changes no return value or exit code.

It also states the case that matters more than the warning itself: silence does
not prove the file is intact. GSD says nothing when the partial block carries
fewer than two fields or reads as prose, because a Markdown document opening
with a horizontal rule is indistinguishable from one of those. A reader chasing
missing metadata needs to know not to treat quiet as clean. Why that threshold
exists is explanation and deliberately stays out of a how-to.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore(#1882): backfill changeset pr number to 2712

* test(#1882): constrain each branch of the frontmatter-shape check

CI's mutation gate came in at 61.56 against a threshold of 62, and the surviving
mutants were concentrated in isFrontmatterShaped -- the function added last, in
response to review, and the only one never given tests of its own. It was
exercised solely through extractFrontmatter, which covers the composite decision
but leaves each branch of the predicate unconstrained: drop the blank-line
filter, or any one of the three shape alternatives, and every existing assertion
still passed.

Four cases now pin the halves independently. A blank line inside an interrupted
block must not disqualify it, which constrains the filter and its comparison. An
unindented list item and an indented folded-scalar continuation each exercise one
shape alternative that no other case reaches on its own -- the folded line is
neither a key nor a list item, so it is the only input that distinguishes the
indented branch. And two keys followed by prose must stay silent, which is the
negative half: it fails if the predicate is ever mutated to accept everything,
and it is the case that proves key count alone was never sufficient.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(#1882): register the unusable-input suite with the frontmatter mutation shard

The mutation gate reported an identical 61.56 across two runs whose only
difference was four added tests. That is the tell: the tests were never
executed. The frontmatter shard runs a fixed file list in stryker.config.mjs and
scripts/mutation-matrix.cjs, and tests/unusable-input.test.cjs was in neither, so
the entire suite covering the new unterminated-fence branch was invisible to the
gate while passing perfectly well in the normal run.

So the score was not measuring weak tests, it was measuring absent ones: #1882
added mutants to frontmatter.cjs and no test in the shard covered them. Both
lists gain the file; the config already notes they must stay in sync.

This is a registration ripple a new test file carries when it covers a
mutation-tracked module, alongside the .gitignore, eslint, inventory, glossary
and size-baseline ripples a new module carries. Nothing warned about it, which
is why two runs were spent before the identical score gave it away.

Refs #1879

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 16:50:12 -04:00

499 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Verification Status — single queryable home for verification-status routing.
*
* Issue #651: consolidate the pass/gaps_found/human_needed routing that was
* previously scattered across ship.md and execute-phase.md into a single
* tested module. Both workflow files will later consume this module's routing
* table as the single source of truth.
*
* ADR-457 build-at-publish: source in src/verification.cts, compiled to
* gsd-core/bin/lib/verification.cjs (gitignored).
*
* DEFECT.FRONTMATTER-SCALAR-BROAD-GREP fix: status extraction is scoped to
* the leading YAML frontmatter block only. A `status:` line in the body (e.g.
* inside a fenced code block) is ignored — this is the exact failure mode that
* issue #586 / PR #650 identified. The shared extractFrontmatter parser anchors
* its regex at byte 0 of the document, which provides this guarantee.
*
* #2348 staleness signal: whether a *-VERIFICATION.md is stale (a summary newer
* than it) is decided from git commit time when a file is committed AND clean,
* and from filesystem mtime otherwise. mtimes are assigned at checkout time and
* are not preserved by `git clone` / `cp -R`, and any unrelated `touch` /
* reformat / editor-save re-stales a valid report — so a committed phase could
* read `passed` on one machine and `stale` on a fresh clone purely from checkout
* order. Git commit time is content-tied and clone-stable; mtime is retained
* only for uncommitted or working-tree-dirty files, where it is the true
* last-changed signal. Both are real wall-clock change times, so the comparison
* is sound even when one file uses each.
*/
import fs from 'node:fs';
import path from 'node:path';
// eslint-disable-next-line @typescript-eslint/no-require-imports -- io.cjs is an export= CommonJS module
import io = require('./io.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports -- phase-id.cjs is an export= CommonJS module
import phaseId = require('./phase-id.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports -- frontmatter.cjs is an export= CommonJS module
import frontmatterMod = require('./frontmatter.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports -- plan-scan.cjs is an export= CommonJS module
import scanPhasePlans = require('./plan-scan.cjs');
import { execGit } from './shell-command-projection.cjs';
import { formatGsdSlash, resolveRuntime } from './runtime-slash.cjs';
const { output, error } = io;
const { extractPhaseToken } = phaseId;
const { extractFrontmatter } = frontmatterMod;
// ─── Constants ────────────────────────────────────────────────────────────────
/** The set of status values that the gsd-verifier agent emits. */
const VERIFIER_STATUSES: ReadonlyArray<string> = ['passed', 'gaps_found', 'human_needed'];
// ─── Routing table ────────────────────────────────────────────────────────────
interface VerificationRoute {
status: string;
next_action: string;
next_command: string;
}
/**
* Canonical routing table for verification statuses.
*
* This is the single source of truth — ship.md and execute-phase.md will
* later import from here instead of embedding their own message strings.
*
* INTERNAL SENTINELS: 'missing' and 'unknown' are operational states constructed
* internally — the verifier (gsd-verifier.md) never emits them. The verifier only
* emits values in VERIFIER_STATUSES (passed|gaps_found|human_needed). The guard in
* readVerificationStatus excludes 'missing' and 'unknown' from raw-status table
* lookup so they can only be reached via internal construction paths.
*
* For 'gaps_found', next_command is built at call time in readVerificationStatus
* by substituting the phase number — it is NOT stored as a function in the table.
*
* #2617: `next_command` here holds a BARE command name (`execute-phase`), never a
* prefixed one. Every return path projects it through `formatGsdSlash` with the
* caller's runtime, so Codex sees `$gsd-execute-phase` and slash-hyphen runtimes
* see `/gsd-execute-phase`. Storing a prefixed literal is what leaked the
* hard-coded (and deprecated) `/gsd:` colon form to every runtime.
*/
const VERIFICATION_ROUTING_TABLE: Record<string, VerificationRoute> = {
passed: {
status: 'passed',
next_action: 'Verification passed — continue.',
next_command: '',
},
gaps_found: {
status: 'gaps_found',
next_action: 'Gaps found. Plan the fixes, then re-run execute-phase before shipping.',
// next_command is computed at call time; this entry is never returned directly.
next_command: '',
},
human_needed: {
status: 'human_needed',
next_action: "Human verification required. Complete the manual tests in the phase's *-UAT.md, then re-run the verify step until status is passed.",
// #2617: was '' — next_action told the user to "re-run the verify step" but
// named no command, while init.cts's parallel projector emitted
// `verify-work <N>` for this same state. The two surfaces disagreed on
// whether a next command existed at all; init's answer was the useful one,
// and init now delegates here rather than re-deriving it.
next_command: 'verify-work',
},
stale: {
status: 'stale',
next_action: 'Verification is stale. Re-run verify-work before transition.',
next_command: '',
},
// INTERNAL SENTINEL: constructed when no *-VERIFICATION.md file exists or when
// the file has no parseable frontmatter status. Never emitted by the verifier.
missing: {
status: 'missing',
next_action: 'No verification report found — the verify step never completed. Re-run execute-phase.',
next_command: 'execute-phase',
},
// INTERNAL SENTINEL: constructed when the file has a status value not in
// VERIFIER_STATUSES. Never emitted by the verifier.
unknown: {
status: 'unknown',
next_action: '', // filled in dynamically with the raw value
next_command: 'execute-phase',
},
};
/**
* Project a BARE command name (plus optional argument tail) into the surface the
* given runtime actually installs (#2617).
*
* `formatGsdSlash` owns the per-runtime shape (`$gsd-<cmd>` for shell-var
* runtimes like Codex, `/gsd-<cmd>` otherwise) and is idempotent, so passing an
* already-prefixed string is safe. An empty command stays empty — "no next
* command" must not become a bare prefix.
*/
function projectNextCommand(bare: string, runtime: string, tail = ''): string {
if (!bare) return '';
return `${formatGsdSlash(bare, runtime) as string}${tail}`;
}
// ─── Helpers ─────────────────────────────────────────────────────────────────
interface FsLike {
readdirSync(dir: string): string[];
readFileSync(filePath: string, encoding: 'utf-8'): string;
statSync(filePath: string): { mtimeMs: number };
}
interface StaleVerificationInfo {
verificationFile: string;
summaryFile: string;
}
/**
* Resolve the git commit time (epoch-ms) for each of `files` (paths relative to
* `phaseDir`) that is BOTH committed AND clean (its working-tree content matches
* HEAD), keyed by the given relative path. A file that is dirty, untracked,
* uncommitted, or in a non-repo is simply absent — callers then time it by its
* filesystem mtime. Injectable so tests exercise the clock without git. (#2348)
*/
type PhaseCleanCommitTimesFn = (phaseDir: string, files: string[]) => Map<string, number>;
/** Normalize separators to posix (git emits `/`; callers may pass `\` on Windows). */
function toPosix(p: string): string {
return p.replace(/\\/g, '/');
}
/**
* Match a git-emitted (repo-root-relative) path back to the caller's
* phaseDir-relative request by exact match or `/`-bounded suffix — precise
* enough that a root file and a nested `plans/` file can never collide (a plain
* basename match could). Returns the original caller-form file string, or null.
*/
function matchRequestedFile(gitPath: string, requested: string[], requestedPosix: string[]): string | null {
const g = toPosix(gitPath);
for (let i = 0; i < requested.length; i++) {
const want = requestedPosix[i];
if (g === want || g.endsWith('/' + want)) return requested[i];
}
return null;
}
/**
* Parse `git log --format=%ct --name-only` output into file → most-recent commit
* time (ms). Output is reverse-chronological, so a file's FIRST appearance
* top-down is its latest commit. `%ct` headers are pure digits; path lines
* contain a `.` (the `.md` extension) — so the two are unambiguous.
*/
function parseCommitTimes(
stdout: string,
requested: string[],
requestedPosix: string[],
): Map<string, number> {
const out = new Map<string, number>();
let currentCt: number | null = null;
for (const line of stdout.split('\n')) {
if (line.length === 0) continue;
if (/^\d+$/.test(line)) {
currentCt = Number.parseInt(line, 10);
continue;
}
if (currentCt === null) continue;
const rel = matchRequestedFile(line, requested, requestedPosix);
if (rel !== null && !out.has(rel)) out.set(rel, currentCt * 1000);
}
return out;
}
/**
* Default resolver: two bounded git calls per phase (never one-per-file — #2348 /
* "Unbounded Subprocesses"; readVerificationStatus runs per-phase in the
* init/roadmap listing loops, so per-file spawning would fan out to P×(S+1)):
*
* 1. `git log --first-parent --format=%ct --name-only -- <files…>` for commit
* times. `--first-parent` makes merge commits report their (first-parent)
* file lists — plain `--name-only` omits merge diffs, which would silently
* under-date content that landed via a conflict-resolving merge.
* 2. `git diff --name-only HEAD -- <files…>` to drop any file whose working
* tree has diverged from HEAD: a committed-then-edited file must be timed by
* its mtime (the edit), never by its now-stale commit time.
*
* Paths pass after `--` so a dash-prefixed filename cannot be read as a flag. Any
* non-answer (no repo, no commits, missing git) yields an empty map → the caller
* times every file by mtime. Never throws. The per-phase file list is small (a
* verification report + a handful of summaries), so the argv stays far below the
* Windows 32K limit. `execGitFn` is injectable so the two-call error handling is
* unit-testable without spawning git.
*/
type ExecGitFn = typeof execGit;
function defaultPhaseCleanCommitTimesMs(
phaseDir: string,
files: string[],
execGitFn: ExecGitFn = execGit,
): Map<string, number> {
if (files.length === 0) return new Map();
const requestedPosix = files.map(toPosix);
const logRes = execGitFn(['log', '--first-parent', '--format=%ct', '--name-only', '--', ...files], {
cwd: phaseDir,
});
if (logRes.error || logRes.exitCode !== 0 || logRes.stdout.length === 0) return new Map();
const commitTimes = parseCommitTimes(logRes.stdout, files, requestedPosix);
if (commitTimes.size === 0) return commitTimes;
// Drop dirty files (working tree ≠ HEAD) so their mtime is used instead. If the
// dirty-check itself is INCONCLUSIVE (git diff errored / non-zero — as opposed
// to "ran and reported no dirty files"), we cannot prove any file is clean, so
// fail SAFE: discard the commit times and let every file fall back to mtime,
// the same direction as a git-log failure. Trusting possibly-stale commit times
// here would silently mask a real edit (false "not stale"). (#2348)
const diffRes = execGitFn(['diff', '--name-only', 'HEAD', '--', ...files], { cwd: phaseDir });
if (diffRes.error || diffRes.exitCode !== 0) return new Map();
for (const line of diffRes.stdout.split('\n')) {
if (line.length === 0) continue;
const rel = matchRequestedFile(line, files, requestedPosix);
if (rel !== null) commitTimes.delete(rel);
}
return commitTimes;
}
/**
* Build a 'missing' result from the routing table.
* Used for two early-return paths: no *-VERIFICATION.md file found, and
* file present but no parseable frontmatter status.
*/
function missingResult(runtime: string, phaseArg: string): VerificationStatusResult {
const route = VERIFICATION_ROUTING_TABLE['missing'];
return {
status: route.status,
next_action: route.next_action,
next_command: projectNextCommand(route.next_command, runtime, phaseArg),
};
}
// ─── Public API ───────────────────────────────────────────────────────────────
interface ReadVerificationStatusOptions {
fs?: FsLike;
/** Injectable per-phase clean-commit-time resolver for the staleness clock (#2348). */
phaseCleanCommitTimesMs?: PhaseCleanCommitTimesFn;
/**
* Runtime whose command surface `next_command` is projected into (#2617).
* Callers that have a cwd should pass `resolveRuntime(cwd)`. Defaults to
* `'claude'`, which yields the canonical `/gsd-<cmd>` hyphen form — never the
* deprecated `/gsd:` colon form this field used to hard-code.
*/
runtime?: string;
/**
* Phase number appended to the routed command (#2617). Defaults to the token
* parsed from `phaseDir`, but only when that token is unambiguously numeric.
* Callers that already know the number pass it explicitly — `init` reaches
* this with `phaseDir` unresolved in some branches.
*/
phaseNumber?: string;
}
interface VerificationStatusResult {
status: string;
next_action: string;
next_command: string;
}
function findStaleVerificationSummary(
phaseDir: string,
fsImpl: FsLike = fs,
phaseCleanCommitTimesMs: PhaseCleanCommitTimesFn = defaultPhaseCleanCommitTimesMs,
): StaleVerificationInfo | null {
// FS errors (TOCTOU: a SUMMARY listed by scanPhasePlans then removed before statSync;
// unreadable dir; broken symlink; file->dir swap) must degrade to "not stale" rather
// than throw uncaught into callers that are NOT under the planning lock
// (init.manager / init.progress / uat-predicate). Mirrors readVerificationStatus's
// no-throw contract; `fsImpl` threads the same injectable-fs seam for parity/testing.
// (Review B1 on #1548.)
try {
const phaseFiles = fsImpl.readdirSync(phaseDir);
const verificationFile = phaseFiles.filter((f) => f.endsWith('-VERIFICATION.md')).sort()[0];
if (!verificationFile) return null;
const summaryFiles = (scanPhasePlans(phaseDir) as { summaryFiles: string[] }).summaryFiles
.slice()
.sort();
// No summary can be newer than the verification → never stale. Return before
// touching git so a phase with no summaries costs zero subprocesses. (#2348)
if (summaryFiles.length === 0) return null;
// Each file's effective "last changed" time = its commit time when committed
// AND clean (content-tied and clone-stable), else its filesystem mtime (the
// uncommitted working-tree edit). Both are real wall-clock change times, so
// comparing a clean file's commit time against a dirty file's mtime is sound.
// One resolver call = two git subprocesses for the whole phase. (#2348)
const cleanCommitMs = phaseCleanCommitTimesMs(phaseDir, [verificationFile, ...summaryFiles]);
const effectiveTimeMs = (file: string): number =>
cleanCommitMs.has(file)
? (cleanCommitMs.get(file) as number)
: fsImpl.statSync(path.join(phaseDir, file)).mtimeMs;
const verificationTimeMs = effectiveTimeMs(verificationFile);
for (const summaryFile of summaryFiles) {
// The caller only needs whether the phase is stale, not which summary —
// the first stale summary (in sorted order) is enough. Short-circuit.
if (effectiveTimeMs(summaryFile) > verificationTimeMs) {
return { verificationFile, summaryFile };
}
}
return null;
} catch {
return null;
}
}
/**
* Read the verification status from the first `*-VERIFICATION.md` file in
* phaseDir and return the routing result.
*
* Behavior:
* 1. Find the first file matching `*-VERIFICATION.md` (sorted, take first).
* If none → status 'missing'.
* 2. Extract `status` from FRONTMATTER ONLY via the shared extractFrontmatter
* parser (DEFECT.FRONTMATTER-SCALAR-BROAD-GREP fix — parser anchors at byte 0).
* If no frontmatter block or no `status` key → status 'missing'.
* 3. Map to routing table. Unknown non-empty value → status 'unknown'.
*
* @param phaseDir - Absolute path to the phase directory.
* @param opts - Options. `opts.fs` allows test injection (defaults to node:fs).
* `opts.runtime` selects the command surface `next_command` is
* projected into (#2617).
*/
function readVerificationStatus(
phaseDir: string,
opts: ReadVerificationStatusOptions = {},
): VerificationStatusResult {
const fsImpl: FsLike = opts.fs ?? fs;
const phaseCleanCommitTimesMs: PhaseCleanCommitTimesFn =
opts.phaseCleanCommitTimesMs ?? defaultPhaseCleanCommitTimesMs;
const runtime = opts.runtime ?? 'claude';
// Phase token for the gaps_found command
const baseName = path.basename(phaseDir);
const phaseToken = extractPhaseToken(baseName);
const derivedPhaseNumber = phaseToken.length > 0 ? phaseToken : baseName;
// #2617: the phase number becomes a COMMAND ARGUMENT, so it is appended only
// when it is unambiguously one. extractPhaseToken also returns project-code
// forms (`PROJ-07`), which are indistinguishable by shape from an ordinary
// directory name — `gsd-651-parent` yields `gsd-651` — and emitting
// `execute-phase gsd-651` is worse than emitting no argument at all. Callers
// that already know the number (init) pass it explicitly and always get it.
const phaseArgSource = opts.phaseNumber ?? (/^\d+(\.\d+)*$/.test(derivedPhaseNumber) ? derivedPhaseNumber : '');
const phaseArg = phaseArgSource ? ` ${phaseArgSource}` : '';
// 1. Find *-VERIFICATION.md
let verificationFile: string | null = null;
try {
const entries = fsImpl.readdirSync(phaseDir);
const candidates = entries.filter((f) => f.endsWith('-VERIFICATION.md')).sort();
verificationFile = candidates.length > 0 ? candidates[0] : null;
} catch {
// Directory unreadable → treat as missing
verificationFile = null;
}
if (!verificationFile) {
return missingResult(runtime, phaseArg);
}
// 2. Read and parse frontmatter using the shared parser.
// extractFrontmatter anchors at byte 0, so body `status:` lines are ignored.
const filePath = path.join(phaseDir, verificationFile);
let rawStatus: string | null = null;
try {
const content = fsImpl.readFileSync(filePath, 'utf-8');
const fm = extractFrontmatter(content, filePath);
const statusVal = fm['status'];
// status is always a scalar string in a well-formed VERIFICATION.md frontmatter;
// only accept string values — arrays and objects are not valid status values.
if (typeof statusVal === 'string') {
const trimmed = statusVal.trim();
rawStatus = trimmed.length > 0 ? trimmed : null;
}
} catch {
rawStatus = null;
}
if (!rawStatus) {
return missingResult(runtime, phaseArg);
}
// gaps_found takes priority over stale — gap closure is the correct next
// step regardless of whether summaries are newer than the verification file.
if (rawStatus === 'gaps_found') {
const entry = VERIFICATION_ROUTING_TABLE['gaps_found'];
return {
status: entry.status,
next_action: entry.next_action,
next_command: projectNextCommand('plan-phase', runtime, `${phaseArg} --gaps`),
};
}
const staleVerification = findStaleVerificationSummary(phaseDir, fsImpl, phaseCleanCommitTimesMs);
if (staleVerification) {
const entry = VERIFICATION_ROUTING_TABLE['stale'];
return {
status: entry.status,
next_action: entry.next_action,
next_command: projectNextCommand('verify-work', runtime, phaseArg),
};
}
// 3. Route — exclude internal sentinels from raw-file lookup (they are
// constructed internally above, never written by the verifier).
if (
rawStatus in VERIFICATION_ROUTING_TABLE &&
rawStatus !== 'missing' &&
rawStatus !== 'unknown' &&
rawStatus !== 'stale' &&
rawStatus !== 'gaps_found'
) {
const entry = VERIFICATION_ROUTING_TABLE[rawStatus];
return {
status: entry.status,
next_action: entry.next_action,
next_command: projectNextCommand(entry.next_command, runtime, phaseArg),
};
}
// Unknown value
const unknownRoute = VERIFICATION_ROUTING_TABLE['unknown'];
return {
status: unknownRoute.status,
next_action: `Unexpected verification status '${rawStatus}'. Re-run execute-phase verification.`,
next_command: projectNextCommand(unknownRoute.next_command, runtime, phaseArg),
};
}
/**
* CLI command handler: resolve phaseDir against cwd, call readVerificationStatus,
* emit via io.output().
*
* @param cwd - Current working directory (used to resolve phaseDirArg).
* @param phaseDirArg - Phase directory path (absolute or relative to cwd).
* @param raw - Whether to emit raw (non-JSON) output.
*/
function cmdVerificationStatus(cwd: string, phaseDirArg: string | undefined, raw: boolean): void {
if (!phaseDirArg) {
error('phase directory required for verification.status');
return;
}
const phaseDir = path.resolve(cwd, phaseDirArg);
const result = readVerificationStatus(phaseDir, { runtime: resolveRuntime(cwd) });
output(result, raw);
}
export = {
VERIFIER_STATUSES,
VERIFICATION_ROUTING_TABLE,
defaultPhaseCleanCommitTimesMs,
findStaleVerificationSummary,
readVerificationStatus,
cmdVerificationStatus,
};