fix(#3707): degrade the fold for every UAT gap class, and stop line endings hiding rows from the audit and the acceptance gate (#3903)

* test(#3707): failing-first coverage for reverting the fence-shortfall fold shield

Pins the post-revert contract: a phase whose only gap is a fence shortfall must
degrade the fold and withhold the milestone percentages, like every other gap class.

Five of the eight rows are CONTROLS that pass before the change, and they carry more
weight than the failing row. The failure mode of this revert is degrading TOO MUCH:
a revert that sets foldScope outside the headingsSeen > 0 branch would withhold every
percentage in the project, and only the no-gap control catches that. Another control
catches a revert that collapses the two scopes into one and loses the distinction
between what a phase reports and what the fold folds -- uat.scope must stay TRUNCATED
for every gap either way, which it already is.

The row that pinned the shielded behavior is rewritten rather than deleted. Deleting
a test because the behavior it asserts is being reversed leaves the reversal
unguarded.

* fix(#3707): degrade the fold for every UAT gap class, reverting the fence-shortfall shield

Maintainer decision. The two orthogonal engines split on this during #3707 and
neither filed it as blocking, so it shipped in the shape the engine that raised the
objection endorsed after verifying seven fixtures. The call has now gone the other
way, restoring the fail-safe direction chosen twice already on this issue.

The shield exempted one gap class from the fold's teeth. It could not do that
safely: shortfallBlocks is a single tally incremented at exactly one site and spans
BOTH a harmless fenced documentation sample AND a genuinely fence-straddled
result: blocked row. Exempting it therefore could not exempt only the harmless case
-- it also published a milestone percentage over a real, unread outstanding row.
SCOPE.TRUNCATED means the scan could not SEE part of the evidence, which is exactly
that case.

scope and foldScope now agree: every gap class degrades both. The accepted
over-report documented in uat.cts is unchanged and still documented there; what
changed is only that it no longer buys an exemption from the fold.

The comment block above it argued FOR the shield and is rewritten, because a
comment defending behavior the code no longer has is worse than no comment.
shortfallBlocks leaves this function's destructure but is untouched upstream, where
audit-uat still consumes it.

* fix(#3707): correct the caller comment, add the changeset, and name what the order tests guard

Review found a SECOND comment still documenting the removed shield -- the caller's,
beside the worstScope fold, stating that foldScope differs from scope for exactly
one case which must not raise phase_scope_degraded or withhold the milestone's
percentages. That is now the opposite of what the code does. I rewrote the
buildUatRows comment in the previous commit and asserted in its message that a
comment defending behavior the code no longer has is worse than no comment, then
left exactly that one standing a few hundred lines away.

The change had no changeset. It is user-visible: a milestone's percentage goes from
published to withheld whenever any phase has a fence-shortfall-only gap. PR gates
hard-fail a user-facing code diff without one.

The two scopes are now identical at every return site. They are NOT collapsed --
that would change the return shape and the caller on what is meant to be a
one-condition revert, and the seam is worth keeping if the distinction is ever
wanted again -- but the declaration now says plainly that they agree by decision
rather than by accident, so a reader does not have to re-derive it.

The two order-independence tests were renamed. foldScope is monotonic with no reset
path, so file order is structurally irrelevant and those rows could never have
failed for the ordering reason their names promised. They do guard something real --
a multi-file phase degrading when any one file has a shortfall-only gap -- so they
now say that instead.

* test(#3707): failing-first coverage for the lone-CR UAT false-clean

The parser splits on newline only, and the heading tokenizer agrees with it, so a
lone carriage return is not a line boundary anywhere in it. CommonMark treats a lone
CR as a line ending, so such a row renders to a human reader while being invisible
to BOTH sides of the parser's symmetry invariant: no item, no shortfall, no
headingsSeen. A phase hiding a result: blocked row this way reports 100 percent with
zero diagnostics.

Found by the security review of the fold-shield revert. It is the one false-clean
class that revert does not reach, and it is the same bug class this issue exists to
fix -- an unreadable row reported as clean.

Nine rows. The LF control is what proves this is a separator defect rather than a
content defect: identical bodies, one separator apart, and only one of them hides
the row. CRLF and CR-inside-a-fence controls guard the coming normalization against
double-counting or tearing content that legitimately contains a carriage return.
Two further manifestations turned up while writing them: a leading CR breaks
column-0 anchoring of the first heading, and an all-CR document flags a shortfall it
cannot attribute to any row.

* fix(#3707): treat a lone carriage return as a line ending in the UAT parser

A lone CR was not a line boundary anywhere in the parser -- it split on newline
only, and the heading tokenizer agreed with it. CommonMark treats a lone CR as a
line ending, so such a row rendered to a human reader while being invisible to BOTH
sides of the parser's symmetry invariant: no item, no shortfall, no headingsSeen. A
phase hiding a result: blocked row that way reported 100 percent with zero
diagnostics.

Line endings are now normalized once at document ingress -- CRLF and lone CR both to
newline -- at the two independent entry points, rather than teaching each split site
about CR. Every downstream scan, offset and span therefore reads one convention.
That single-frame property is deliberate: this issue already cost a HIGH when two
scans read the same document through different frames.

MY OWN END-TO-END TEST WAS WRONG and is replaced rather than weakened. It asserted
that a lone-CR document must withhold its percentage, which reasons from the
pre-fix symptom: after the fix the row is not hidden, it is surfaced, and this
module deliberately keeps visible outstanding UAT work separate from completion
percentages -- only unreadable evidence degrades scope. The success of the fix is
what made the assertion false. The implementing agent refused to satisfy both it and
the architecture and asked instead of bending either; it was right.

What replaces it is a stronger contract: a lone-CR document and its LF twin, built
from one source, must produce identical audit output -- scope, percent, every
unresolved row by identity, and the diagnostic set. That is what 'a line-ending
convention must not change what the audit reports' actually means, and it carries a
non-vacuity check so it cannot pass with both sides empty.

shortfallBlocks keeps being returned, now documented as currently unconsumed. An
earlier reviewer told me audit-uat still consumed it and I passed that on as an
instruction; it was wrong, and it was caught by checking rather than by me.

* fix(#3707): normalize at the document read boundary, not at two call sites

The lone-CR fix was half-applied and both review engines caught it independently.
cmdAuditUat has four document ingresses, not the two I normalized: VERIFICATION.md
and deferred-items.md still handed raw text to newline-only splitters, and the
frontmatter extract in the UAT loop read raw content while its parser read
normalized -- one audit entry mixing the two frames the fix exists to unify.
Measured: a phase written twice from one source gave total_files 2 / total_items 4
under LF and results [] / total_items 0 under lone CR, with zero diagnostics.

Normalizing two call sites and declaring it done is exactly why two were missed, so
this moves it to the read boundary: every document now enters through a helper that
normalizes, in audit-uat, in planning-inspect's readDocument, and in the shared
verification-status read. Future parsers downstream get normalized text by
construction rather than because someone remembered.

That last seam also fixes an under-reporting case of the same root: a lone-CR
VERIFICATION.md saying status: passed was read as missing, telling the user a verify
step that had completed never ran.

The parity test's load-bearing assertion is now marked as such. Four of its five
equality checks still pass with the bug present -- only the unresolved-row identity
differs -- so trimming that one as redundant would make the row vacuous.

Second changeset added: the CR fix is user-visible independently of the fold revert,
and one fragment covering both would have described neither.

* test(#3707): failing-first coverage for the U+2028 and duplicate-result false-cleans

Two more of the same class, both found by the security review of this branch and
both reproduced before writing a line.

normalizeLineEndings folds only carriage returns, but a JS /m anchor also treats
U+2028 and U+2029 as line terminators while split on newline does not. That is the
identical asymmetry the carriage-return bug exploited, one separator over, and worse
in one respect: these are not CommonMark line endings, so a reader still sees the
column-0 result: blocked that the tool discards. Measured: a scalar-internal
result: pass placed after U+2028 wins over the real blocked line and the row
disappears with no gap raised.

Separately, and independent of any separator, a block with two column-0 result:
lines resolves to the first with no ambiguity signalled. Prepending result: pass to
a block therefore deletes an outstanding row silently; reversing the order surfaces
it. Order deciding meaning is the defect, so the pair of rows pins the contract as
ambiguity-is-a-gap rather than last-one-wins, leaving the fix room to implement the
gap sensibly.

Four controls: an ordinary marker in the same position (proving separator not
content), legitimate U+2028 inside prose that must not be torn, a single result line,
and a result line inside a fence that must not count as a second occurrence.

* fix(#3707): scan result lines by split, not by a multiline anchor

Two more false-cleans from the security review, both closed by the same change.

A JS /m anchor treats U+2028 and U+2029 as line terminators while split on newline
does not. A scalar-internal result: pass placed after one of those separators
therefore matched as a line start and beat the real column-0 result: blocked, and
the row vanished at 100 percent with no gap. Worse than the carriage-return case in
one respect: these are not CommonMark line endings, so a reader still saw the
blocked row the tool discarded.

Separately, the non-global match returned the leftmost hit, so a block with two
column-0 result: lines silently resolved to the first. Prepending result: pass
deleted an outstanding row; reversing the order surfaced it. Order deciding meaning
was the defect.

Both close by scanning lines produced by split rather than by anchoring a regex
inside the whole document: each line is tested on its own, and a count other than
exactly one is reported as a parse gap instead of resolved to either candidate.

I asked for U+2028 to be folded in normalizeLineEndings and that was wrong. Folding
is length-preserving, so it would have made the U+2028 fixture byte-identical to the
genuine two-result-line fixture -- while one requires a confident item and the other
requires an ambiguity gap. No implementation can satisfy both once the distinguishing
character is erased. The agent proved that and deviated rather than forcing it, which
is why normalizeLineEndings still folds only carriage returns, now with a comment
saying why.

* fix(#3707): bound the ambiguity scan at the next heading-shaped line

The split-based result scan regressed four pre-existing #3078/#3707 guards, each
off by exactly one gap.

My diagnosis was wrong. I read the off-by-one as double counting -- zero-result
blocks taking both the new path and the pre-existing one -- and said to change the
ambiguity condition from not-equal-one to greater-than-one. The agent checked and
refused: the zero path was never duplicated. The real cause is double ATTRIBUTION.
A block is sliced to the next TOKENIZED heading, so when the next row is untokenized
-- hidden by a straddling fence, or indented and already counted by the shortfall
scan -- that row's own result: line is absorbed into the previous block. The scan
then saw two result lines across what are really two rows and raised a second,
redundant gap on top of the one already counted elsewhere.

Had the greater-than-one change gone in, the counts would have matched while the
double attribution stayed. That is the compensating-adjustment failure I had asked
it to refuse, and it did.

The scan is now bounded at the first following heading-shaped line, either indent
class, so a genuine same-block ambiguity is untouched while spillover from a row
counted elsewhere is excluded.

* fix(#3707): keep the U+2028 immunity, revert the ambiguity detection

The ambiguity half of this change regressed the suite twice and is coming out.

Attempt one double-attributed: a block is sliced to the next TOKENIZED heading, so
when the real next row is untokenized its result: line was absorbed into the
previous block and raised a second gap on a row already counted elsewhere. Four
guards broke.

Attempt two bounded the scan at the next heading-shaped line and broke thirty. An
indented ### N. inside a block scalar is legitimate scalar CONTENT, not a heading,
and truncating there defeats every #3078 guard that exists to stop scalar bodies
being read as rows. Telling a genuinely hidden indented row apart from indented
scalar text is a classification countUnattributedIndentedRows already owns; a raw
regex does not have that information.

What survives is the half that is sound and was never implicated in either
regression: the result scan tests each line produced by split rather than anchoring
a regex with the multiline flag over the whole block. split never treats U+2028 or
U+2029 as a delimiter, so those separators can no longer manufacture a line start
and steal a row. Everything else returns to first-match-wins, byte-identical to
origin/next.

The two tests pinning ambiguity-as-a-gap are removed with it, since the contract is
no longer implemented here. The defect they described is real, pre-existing and
independent of any separator -- result: pass before result: blocked silently deletes
an outstanding row -- and it needs its own change with a scalar-aware counter rather
than being wedged into a branch already carrying three fixes.

* fix(#3707): correct the shared-seam rationale and restore U+2028 trailing text

The revert left a stale rationale in core-utils, justifying the decision not to fold
U+2028 by claiming uat.cts must tell a fake line start apart from a real second
column-0 result: declaration that gets flagged as ambiguous. Nothing flags ambiguity
any more; that behavior was reverted and the same file says so a few lines away. The
decision is still right, the stated reason was false.

This is the third stale comment this branch has shipped and had to fix, and the worst
placed of them: core-utils is a shared leaf that every future document consumer will
read for guidance. Rewritten to the true reason -- the scan tests each split line
individually rather than anchoring over the block, so an exotic separator cannot
manufacture a line start and folding is unnecessary.

Also a real behavior delta I had not noticed. Dropping the multiline flag left the
pattern's trailing .*$ in place, and dot never matches U+2028, so a genuine column-0
result: blocked whose TRAILING text contained one stopped parsing entirely -- a
visible parse gap rather than a false clean, so fail-safe, but a regression against
origin/next that nothing pinned. The trailing portion now matches any character and
a test pins it by identity against its plain-LF twin.

Plus the JSDoc orphaned when normalizeLineEndings moved to core-utils, and the
changeset, which described neither the separator fix nor planning-inspect surfacing
lone-CR rows.

* fix(#3707): harden the acceptance gate, which had both halves of the same bug

uat-predicate is a SECOND, independent UAT parser, and it is the one that decides
phase uat-passed. It read raw bytes and anchored a multiline regex over unsplit
text -- exactly the two defects this branch closed one module away in uat.cts.

The consequence is worse than the audit surface it mirrors. Measured on identical
bytes: a U+2028 scalar injection made the gate return passed true while planning
inspect reported the same row as blocked and outstanding. The hardened surface and
the gate disagreed, and the gate was the permissive one -- so a phase could be
accepted over a row the audit could see and the gate could not.

Both raw reads now go through the shared normalize seam and both scans test lines
produced by split rather than anchoring over the document. First-match-wins,
matching uat.cts; no ambiguity counting is reintroduced. Tests assert the AGREEMENT
between the two surfaces rather than each separately, because divergence is the
defect.

Also finishes the same root cause one module over: phase complete's advisory
pre-scan read raw bytes, so a lone-CR VERIFICATION.md lost its human_needed or
gaps_found warning -- the fix verification.cts already got on this branch.

And narrows the core-utils rationale I reworded last commit, which claimed consumers
already avoid multiline anchors. uat.cts still has five over unsplit text. That is
the fourth comment on this branch to assert something the code does not do, so it
now states only what is true of core-utils itself.

* fix(#3707): give structure and attribution different line frames, normalize the close audit

Two more from review, and the first was a regression I introduced one commit
earlier.

Converting the gate's heading scan to split-then-match removed a detection
origin/next had: a ### N. heading delimited by U+2028 was found by the old multiline
scan and was not found after. So hardening the result scan quietly weakened the
heading scan, and the gate stopped blocking on rows origin/next blocked -- the
permissive direction, on the surface that decides acceptance.

The insight I had missed is that the two scans need DIFFERENT frames. Heading
detection is structure: there is no distinction to preserve, so it splits on newline
or either exotic separator and finds a heading however it is delimited. The result
scan is attribution: the newline-only frame is exactly what stops a scalar-internal
result: from being read as a column-0 line, so it stays. One frame applied uniformly
was the error.

Second, a THIRD unnormalized parser family: the milestone-close audit read every
artifact raw. A lone-CR VERIFICATION.md degraded to status unknown and was skipped,
and deferred entries vanished outright -- measured as three items requiring
decisions under LF and one under CR, on identical bytes. All nine scanner reads now
normalize; six of them had the identical defect beyond the three review named. The
acknowledge path stays deliberately raw, since it splices by byte offset, and now
says so.

Also pins the cross-newline result: divergence, and replaces three raw U+2028
literals in test source with escapes. A raw separator in a fixture is one formatter
away from becoming an ordinary-character control that still passes -- vacuous in the
only test pinning the separator fix.

* fix(#3707): share one frame between the acknowledge writer and the audit reader

Normalizing the audit scanners left the writer and the reader on different frames.
cmdAuditAcknowledge derives its stored snapshot values from raw content -- correct
for the SPLICE, which rewrites by byte offset -- but scanUatGaps and
scanContextQuestions now recompute those same values from normalized content. For a
lone-CR artifact the two can never match, so an acknowledgement never suppresses its
item and it resurfaces on every audit: acknowledge became a silent no-op.

Fail-safe in direction, since the item stays visible rather than being wrongly
suppressed, but it is the writer and reader disagreeing about what a line is -- the
exact class this branch exists to eliminate, and the fourth instance of it here.

The derive functions now read a normalized copy while the splice keeps raw bytes and
raw offsets, so both sides share one frame and the byte-offset rewrite is untouched.
Round trip pinned for lone-CR and LF, with an existing LF marker asserted still
recognised so the change cannot silently invalidate acknowledgements already in
users' files.

Also tightens an assertion that pinned this branch's own heading fix with a proxy:
notStrictEqual against 'passed' also passes on 'pass', which IS a passing token, so
it could not have caught a regression attributing a passing result to the recovered
heading. It now pins the exact token.

* chore(#3707): backfill changeset pr numbers

Both fragments still carried the pr: 0 placeholder, which failed changeset-lint and
docs-lint on PR 3903. The review had flagged the backfill as pending and I opened
the PR without doing it.

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-08-26 20:17:35 -04:00
committed by GitHub
parent 6b7df61938
commit 4e8927b0b9
13 changed files with 1522 additions and 96 deletions

View File

@@ -18,6 +18,9 @@ import { platformReadSync } from './shell-command-projection.cjs';
import { collectSection } from './markdown-sectionizer.cjs';
import { splitLines } from './text-lines.cjs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import coreUtils = require('./core-utils.cjs');
const { normalizeLineEndings } = coreUtils;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import planningWorkspace = require('./planning-workspace.cjs');
const { planningDir, quickDirFrom } = planningWorkspace;
// eslint-disable-next-line @typescript-eslint/no-require-imports
@@ -449,8 +452,16 @@ function scanDebugSessions(planDir: string): ScanOutcome<DebugSessionItem> {
continue;
}
const content = platformReadSync(safeFilePath);
if (content === null) continue;
// #3078-CR MEDIUM 2 (security review follow-up): normalize a lone-CR
// document at this read boundary, same seam as `src/uat.cts`'s
// `readNormalizedDocument` — `platformReadSync` performs no line-ending
// normalization itself, and extractFrontmatter/status-derivation below
// degrade a lone-CR file's frontmatter to `unknown`, which every scan
// in this module treats as "not open" (fail-open, the permissive
// direction) rather than a real parse gap.
const rawContent = platformReadSync(safeFilePath);
if (rawContent === null) continue;
const content = normalizeLineEndings(rawContent);
const fm = extractFrontmatter(content, safeFilePath);
const status = ((fm.status as string) || 'unknown').toLowerCase();
@@ -570,10 +581,14 @@ function scanQuickTasks(planDir: string): ScanOutcome<QuickTaskItem> {
} catch {
continue;
}
const content = platformReadSync(safeSum);
if (content === null) {
// #3078-CR MEDIUM 2: same normalize-at-read-boundary fix as the other
// scans in this module — see the comment above `scanDebugSessions`'s
// read.
const rawContent = platformReadSync(safeSum);
if (rawContent === null) {
status = 'unreadable';
} else {
const content = normalizeLineEndings(rawContent);
fm = extractFrontmatter(content, safeSum);
status = ((fm.status as string) || 'unknown').toLowerCase();
}
@@ -648,8 +663,16 @@ function scanThreads(planDir: string): ScanOutcome<ThreadItem> {
continue;
}
const content = platformReadSync(safeFilePath);
if (content === null) continue;
// #3078-CR MEDIUM 2 (security review follow-up): normalize a lone-CR
// document at this read boundary, same seam as `src/uat.cts`'s
// `readNormalizedDocument` — `platformReadSync` performs no line-ending
// normalization itself, and extractFrontmatter/status-derivation below
// degrade a lone-CR file's frontmatter to `unknown`, which every scan
// in this module treats as "not open" (fail-open, the permissive
// direction) rather than a real parse gap.
const rawContent = platformReadSync(safeFilePath);
if (rawContent === null) continue;
const content = normalizeLineEndings(rawContent);
const fm = extractFrontmatter(content, safeFilePath);
const status = deriveThreadStatus(fm, content);
@@ -723,8 +746,16 @@ function scanTodos(planDir: string): ScanOutcome<TodoItem> {
continue;
}
const content = platformReadSync(safeFilePath);
if (content === null) continue;
// #3078-CR MEDIUM 2 (security review follow-up): normalize a lone-CR
// document at this read boundary, same seam as `src/uat.cts`'s
// `readNormalizedDocument` — `platformReadSync` performs no line-ending
// normalization itself, and extractFrontmatter/status-derivation below
// degrade a lone-CR file's frontmatter to `unknown`, which every scan
// in this module treats as "not open" (fail-open, the permissive
// direction) rather than a real parse gap.
const rawContent = platformReadSync(safeFilePath);
if (rawContent === null) continue;
const content = normalizeLineEndings(rawContent);
const fm = extractFrontmatter(content, safeFilePath);
@@ -796,8 +827,16 @@ function scanSeeds(planDir: string): ScanOutcome<SeedItem> {
continue;
}
const content = platformReadSync(safeFilePath);
if (content === null) continue;
// #3078-CR MEDIUM 2 (security review follow-up): normalize a lone-CR
// document at this read boundary, same seam as `src/uat.cts`'s
// `readNormalizedDocument` — `platformReadSync` performs no line-ending
// normalization itself, and extractFrontmatter/status-derivation below
// degrade a lone-CR file's frontmatter to `unknown`, which every scan
// in this module treats as "not open" (fail-open, the permissive
// direction) rather than a real parse gap.
const rawContent = platformReadSync(safeFilePath);
if (rawContent === null) continue;
const content = normalizeLineEndings(rawContent);
const fm = extractFrontmatter(content, safeFilePath);
const status = ((fm.status as string) || 'dormant').toLowerCase();
@@ -970,8 +1009,16 @@ function scanUatGaps(planDir: string, cwd: string): ScanOutcome<UatGapItem> {
continue;
}
const content = platformReadSync(safeFilePath);
if (content === null) continue;
// #3078-CR MEDIUM 2 (security review follow-up): normalize a lone-CR
// document at this read boundary, same seam as `src/uat.cts`'s
// `readNormalizedDocument` — `platformReadSync` performs no line-ending
// normalization itself, and extractFrontmatter/status-derivation below
// degrade a lone-CR file's frontmatter to `unknown`, which every scan
// in this module treats as "not open" (fail-open, the permissive
// direction) rather than a real parse gap.
const rawContent = platformReadSync(safeFilePath);
if (rawContent === null) continue;
const content = normalizeLineEndings(rawContent);
const fm = extractFrontmatter(content, safeFilePath);
const status = ((fm.status as string) || 'unknown').toLowerCase();
@@ -1045,8 +1092,16 @@ function scanVerificationGaps(planDir: string, cwd: string): ScanOutcome<Verific
continue;
}
const content = platformReadSync(safeFilePath);
if (content === null) continue;
// #3078-CR MEDIUM 2 (security review follow-up): normalize a lone-CR
// document at this read boundary, same seam as `src/uat.cts`'s
// `readNormalizedDocument` — `platformReadSync` performs no line-ending
// normalization itself, and extractFrontmatter/status-derivation below
// degrade a lone-CR file's frontmatter to `unknown`, which every scan
// in this module treats as "not open" (fail-open, the permissive
// direction) rather than a real parse gap.
const rawContent = platformReadSync(safeFilePath);
if (rawContent === null) continue;
const content = normalizeLineEndings(rawContent);
const fm = extractFrontmatter(content, safeFilePath);
const status = ((fm.status as string) || 'unknown').toLowerCase();
@@ -1106,8 +1161,16 @@ function scanContextQuestions(planDir: string, cwd: string): ScanOutcome<Context
continue;
}
const content = platformReadSync(safeFilePath);
if (content === null) continue;
// #3078-CR MEDIUM 2 (security review follow-up): normalize a lone-CR
// document at this read boundary, same seam as `src/uat.cts`'s
// `readNormalizedDocument` — `platformReadSync` performs no line-ending
// normalization itself, and extractFrontmatter/status-derivation below
// degrade a lone-CR file's frontmatter to `unknown`, which every scan
// in this module treats as "not open" (fail-open, the permissive
// direction) rather than a real parse gap.
const rawContent = platformReadSync(safeFilePath);
if (rawContent === null) continue;
const content = normalizeLineEndings(rawContent);
const fm = extractFrontmatter(content, safeFilePath);
const questions = deriveOpenQuestions(content, fm);
@@ -1194,8 +1257,14 @@ function scanDeferredItems(planDir: string, cwd: string): ScanOutcome<DeferredIt
continue;
}
const content = platformReadSync(safeFilePath);
if (content === null) continue;
// #3078-CR MEDIUM 2: normalize at this read boundary too —
// `parseDeferredItemsWithStatus` performs no normalization of its own
// (unlike `src/uat.cts`'s callers, which route through
// `readNormalizedDocument`), so a lone-CR `deferred-items.md` was read as
// one unbroken line and every entry in it silently vanished.
const rawContent = platformReadSync(safeFilePath);
if (rawContent === null) continue;
const content = normalizeLineEndings(rawContent);
for (const item of uat.parseDeferredItemsWithStatus(content)) {
const rawStatus = (item.status || '').toLowerCase();
@@ -1541,6 +1610,21 @@ function cmdAuditAcknowledge(cwd: string, args: string[], raw: boolean): void {
const planDir = planningDir(cwd);
const markerBase = { milestone: milestone as string, at };
// #3078-CR MEDIUM 2: every `fs.readFileSync` in this function (below, and
// in the flat-category branch further down) is DELIBERATELY left raw,
// unlike `auditOpenArtifacts`'s scan reads (which now route through
// `normalizeLineEndings`). This function splices frontmatter into the
// EXISTING content and writes the result back via `platformWriteSync` /
// `uat.acknowledgeDeferredItem` — both `spliceFrontmatter` and
// `acknowledgeDeferredItem` locate and rewrite a specific byte span
// (frontmatter block / matched deferred-item text) in the file exactly as
// it exists on disk. Normalizing first would rewrite the file's line
// endings as a side effect of an unrelated acknowledge operation, and a
// splice computed against normalized text can land at the wrong offset
// when written back over the RAW (un-normalized) original. The snapshot
// VALUE computed below IS normalized (on a separate in-memory copy, never
// the spliced one) so it agrees with the scanner's frame — see the comment
// at `normalizedContent` further down.
// ── The four phase-scoped categories: --phase --file [--archived-milestone] ──
const PHASE_SCOPED = new Set(['uat_gaps', 'verification_gaps', 'context_questions', 'deferred_items']);
if (PHASE_SCOPED.has(category as string)) {
@@ -1576,6 +1660,15 @@ function cmdAuditAcknowledge(cwd: string, args: string[], raw: boolean): void {
const content = fs.readFileSync(safeFilePath, 'utf-8');
const fm = extractFrontmatter(content, safeFilePath);
// Mixed-frame fix (security review, 4th instance on this branch): the
// splice above and below stays keyed to RAW `content` (raw byte offsets
// must not shift), but `scanUatGaps`/`scanContextQuestions` now derive
// their comparison values from `normalizeLineEndings`d content. Deriving
// the snapshot here from raw `content` would make a lone-CR file's
// stored value permanently disagree with what the scanner recomputes —
// `audit acknowledge` would be a silent no-op for lone-CR artifacts. Feed
// the derive functions a normalized COPY; never splice from it.
const normalizedContent = normalizeLineEndings(content);
let snapshotKey: string;
let currentValue: string;
if (category === 'uat_gaps') {
@@ -1583,7 +1676,7 @@ function cmdAuditAcknowledge(cwd: string, args: string[], raw: boolean): void {
// pending scenarios added under the same status — snapshot the
// composite `deriveUatGapSnapshotValue` instead (see its doc comment).
snapshotKey = 'gap_snapshot';
currentValue = deriveUatGapSnapshotValue(((fm.status as string) || 'unknown').toLowerCase(), content);
currentValue = deriveUatGapSnapshotValue(((fm.status as string) || 'unknown').toLowerCase(), normalizedContent);
} else if (category === 'verification_gaps') {
snapshotKey = 'status';
currentValue = ((fm.status as string) || 'unknown').toLowerCase();
@@ -1592,7 +1685,7 @@ function cmdAuditAcknowledge(cwd: string, args: string[], raw: boolean): void {
// question set, not just its count (see `deriveOpenQuestionsDigest`'s
// doc comment).
snapshotKey = 'questions_digest';
currentValue = deriveOpenQuestionsDigest(deriveOpenQuestions(content, fm));
currentValue = deriveOpenQuestionsDigest(deriveOpenQuestions(normalizedContent, fm));
}
fm.audit_acknowledged = { ...markerBase, [snapshotKey]: currentValue };
const newContent = spliceFrontmatter(content, fm);

View File

@@ -41,6 +41,56 @@ import planningWorkspace = require('./planning-workspace.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
import shellCommandProjection = require('./shell-command-projection.cjs');
// ─── Line-ending normalization ─────────────────────────────────────────────────
/**
* Normalize every line ending in `content` to a bare `\n`, ONCE — the shared
* seam every document-READ boundary in this codebase should route through
* (#3707-CR follow-up MAJOR).
*
* CommonMark treats a lone CR (no paired LF) as a line ending — such a
* document RENDERS as separate lines to a human reader — but a parser that
* splits/tokenizes/scans on `\n` alone treats a lone-CR-separated document as
* ONE unbroken line, hiding every row boundary in it. `src/uat.cts` originally
* carried this exact fix as a PRIVATE, unexported function applied inside two
* of its own parse functions (`parseUatItemsWithStats`, `parseCurrentTest`) —
* which is why two OTHER read sites in the same module (`cmdAuditUat`'s
* VERIFICATION and deferred-items.md ingresses) were missed: normalizing
* per-parser means every new parser must remember to call it. Promoted here,
* to the shared leaf module every document consumer can reach without a new
* dependency edge, so normalization can be applied at the READ boundary
* instead — every current and future parser fed from a boundary that calls
* this gets normalized text by construction.
*
* `/\r\n?/g` is deliberately ONE alternation, not two separate replaces: a
* two-pass `replace(/\r\n/g,'\n').replace(/\r/g,'\n')` is equivalent here
* because the first pass already consumes every CRLF pair before the second
* pass ever runs, but a single regex avoids relying on pass ORDER and matches
* greedily left-to-right in one scan, so a CRLF is always consumed as ONE
* unit (never left as a stray trailing `\r` after the `\n` half is matched
* first) and a lone CR — including one immediately followed by nothing, i.e.
* at EOF, or by another lone CR — is still replaced.
*
* This is deliberately NOT a length-preserving transform (CRLF, two UTF-16
* units, becomes LF, one), so any offsets a caller computes must be compared
* only against THIS normalized string, never against the original raw text.
*
* U+2028 LINE SEPARATOR / U+2029 PARAGRAPH SEPARATOR (#3078-CR) are
* DELIBERATELY NOT folded here, unlike `\r`/`\r\n`. Folding is unnecessary:
* `String.prototype.split('\n')` never treats U+2028/U+2029 as a delimiter,
* so an exotic separator can never manufacture a fake line start for a
* consumer that scans lines produced by `split('\n')`, rather than anchoring
* a multiline (`/m`) regex directly over unsplit text. Only the latter
* pattern is vulnerable to the ECMA-262 LineTerminator set including these
* two code points. This module performs no line-anchored matching of its
* own; a caller that scans lines should split first and match per-line
* rather than anchor `/m` over unsplit text — this comment makes no claim
* about whether any particular caller currently does so.
*/
function normalizeLineEndings(content: string): string {
return content.replace(/\r\n?/g, '\n');
}
// ─── Path helpers ────────────────────────────────────────────────────────────
/**
@@ -459,6 +509,7 @@ function findOrphanSummaries(planFiles: string[], summaryFiles: string[]): strin
export = {
toPosixPath,
normalizeLineEndings,
detectSubRepos,
extractOneLinerFromBody,
pathExistsInternal,

View File

@@ -36,7 +36,7 @@ import coreUtilsMod = require('./core-utils.cjs');
// drift and no parity test needed to police one.
const {
toPosixPath, generateSlugInternal, readSubdirectories, extractCanonicalPlanId,
findUnsummarizedPlans,
findUnsummarizedPlans, normalizeLineEndings,
} = coreUtilsMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports -- phase-id.cjs is an export= CommonJS module
import phaseIdMod = require('./phase-id.cjs');
@@ -2407,7 +2407,12 @@ function cmdPhaseComplete(cwd: string, phaseNum: string, raw: boolean): void {
phaseFullDirBaseName,
)) {
const verificationFilePath = path.join(phaseFullDir, file);
const content = fs.readFileSync(verificationFilePath, 'utf-8');
// #3707-CR follow-up MINOR: normalize line endings at this read boundary
// (same fix as src/verification.cts's readVerificationStatus) so a
// lone-CR VERIFICATION.md's `---\r...\r---` frontmatter fence still
// matches extractFrontmatter's byte-0 check instead of silently
// dropping the human_needed/gaps_found advisory warning below.
const content = normalizeLineEndings(fs.readFileSync(verificationFilePath, 'utf-8'));
// #1159 (Defect A): read ONLY the frontmatter `status` key to avoid false positives
// from historical metadata in the file body (e.g. `previous_status: gaps_found`).
// A full-text regex like /status: gaps_found/ matches the substring inside

View File

@@ -89,6 +89,9 @@ const { collectSection, iterateBullets } = markdownSectionizer;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import markdownTable = require('./markdown-table.cjs');
const { parseMarkdownTable, matchTableSchema } = markdownTable;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import coreUtilsMod = require('./core-utils.cjs');
const { normalizeLineEndings } = coreUtilsMod;
/**
* The wire schema version. A consumer MUST reject any value other than this
@@ -263,7 +266,16 @@ function readDocument(filePath: string, root: string): { text: string | null; ex
}
try {
return { text: fs.readFileSync(filePath, 'utf-8'), exists: true, readable: true };
// #3707-CR follow-up MAJOR: normalize line endings HERE, at this module's
// one shared document-read seam, so a lone-CR document (CommonMark line
// ending; a document using it renders as separate lines to a human
// reader) is normalized by construction for every current and future
// caller of `readDocument` (`buildRequirements`, `buildUatRows`, the
// ROADMAP.md read above) — not only the ones a parser author remembered
// to fix individually. Mirrors `src/uat.cts`'s `readNormalizedDocument`,
// the equivalent boundary for `cmdAuditUat`; both now delegate to the
// same `normalizeLineEndings` in `core-utils.cts`.
return { text: normalizeLineEndings(fs.readFileSync(filePath, 'utf-8')), exists: true, readable: true };
} catch {
return { text: null, exists: true, readable: false };
}
@@ -803,6 +815,13 @@ function buildPlanRows(phaseDir: string, diagnostics: Diagnostic[], planningRoot
// ─── UAT ──────────────────────────────────────────────────────────────────────
// `scope` and `foldScope` are, by decision, identical at every return site in
// this function as of #3078 round-8 — they are not accidentally in sync. The
// two-field shape is kept anyway because it lets `scope` (the row's own
// honest answer) and `foldScope` (what the caller folds into the milestone)
// diverge again later without a signature change, should some future gap
// class need to be reported on the row but exempted from the fold, or vice
// versa. If you find yourself "simplifying" this to one field, don't.
function buildUatRows(
phasesDir: string,
phaseDirName: string,
@@ -889,23 +908,18 @@ function buildUatRows(
// fold raises `phase_scope_degraded` AND, via `phaseScope`/`makeFraction`,
// withholds BOTH progress percentages for the WHOLE milestone.
//
// Those teeth cannot bite on `shortfallBlocks`: that is the subset of
// `headingsSeen` produced by the fence-suppression shortfall scan, the ONE
// gap class `src/uat.cts` documents as an ACCEPTED OVER-REPORT — a
// closed-fence documentation sample written with literal digits is provably
// indistinguishable from a genuinely fence-straddled row (fence-closedness
// is identical in both), so the scan deliberately over-reports. A COMPLETED
// phase is terminal: nobody reopens its UAT file, so a shortfall-only
// over-report there would withhold the project's percentages in every
// future audit FOREVER over a paragraph of prose. Reported-and-dismissible
// is the right shape for it; silent is not, and neither is permanent.
//
// Every OTHER gap class (a block with no `result:` line, an unattributed
// indented row, an unterminated fence) has no such false-positive story and
// still degrades the fold, as does the unreadable-FILE case above — which
// is what `SCOPE.TRUNCATED` means per src/planning-scope.cts: the scan
// could not SEE part of the evidence.
const { items: fileItems, headingsSeen, shortfallBlocks } = parseUatItemsWithStats(doc.text);
// The two now agree: EVERY gap class degrades both, including the
// fence-suppression shortfall. `shortfallBlocks` is not exempted here
// because it is a single tally incremented at ONE site in the scan and
// spans BOTH a harmless closed-fence documentation sample AND a genuinely
// fence-straddled `result: blocked` row — exempting the tally cannot
// exempt only the harmless case, it also publishes a milestone percentage
// over a real unread outstanding row. `SCOPE.TRUNCATED` means the scan
// could not SEE part of the evidence (src/planning-scope.cts), which is
// exactly the fence-straddled case. The accepted over-report itself is
// unchanged and still documented at src/uat.cts; what changed is only
// that it no longer buys an exemption from the fold.
const { items: fileItems, headingsSeen } = parseUatItemsWithStats(doc.text);
items.push(...fileItems);
if (headingsSeen > 0) {
diagnostics.push({
@@ -914,7 +928,7 @@ function buildUatRows(
detail: `UAT document has ${headingsSeen} test block(s) with no parseable result; unresolved is not a complete answer.`,
});
scope = SCOPE.TRUNCATED;
if (headingsSeen > shortfallBlocks) foldScope = SCOPE.TRUNCATED;
foldScope = SCOPE.TRUNCATED;
}
}
return { items, scope, foldScope };
@@ -1226,13 +1240,15 @@ function buildPlanningInspect(cwd: string): Record<string, unknown> {
const phaseId = token ? token[1] : null;
const { goal, dependencies } = buildPhaseGoalAndDependencies(cwd, roadmapDoc, phaseId, phase.dir, diagnostics);
// `uat.foldScope`, NOT `uat.scope` (#3078 round-8). The two differ for
// exactly one case: a UAT document whose ONLY parse gap is the
// fence-suppression shortfall, `src/uat.cts`'s documented ACCEPTED
// OVER-REPORT class. That still reports honestly on the row itself
// (`uat.scope === "truncated"` plus the `uat_unreadable` diagnostic below),
// but it must not raise `phase_scope_degraded` and must not withhold the
// milestone's percentages — see `buildUatRows` for the full rationale.
// `uat.foldScope`, NOT `uat.scope` (#3078 round-8). The two currently
// agree at every call site — see `buildUatRows` for why the field is
// still kept separate — so folding either one here produces the same
// result today. `foldScope` is used because it is the field with teeth:
// it is what `worstScope` folds into the phase's overall scope, and a
// non-COMPLETE result here raises `phase_scope_degraded` and, via
// `makeFraction`, withholds the milestone's percentages. A phase whose
// UAT document could not be fully read must not contribute an
// affirmative completion to the milestone.
const folded = worstScope(phase.scope, plans.scope, uat.foldScope, goal.scope, dependencies.scope);
if (folded !== SCOPE.COMPLETE) {
diagnostics.push({

View File

@@ -25,6 +25,9 @@ const { readVerificationStatus } = verification;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import phaseIdMod = require('./phase-id.cjs');
const { scopeToPhase } = phaseIdMod;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import coreUtils = require('./core-utils.cjs');
const { normalizeLineEndings } = coreUtils;
// ─── Types ────────────────────────────────────────────────────────────────────
@@ -156,34 +159,64 @@ function analyzeMarkdown(raw: string): { unterminatedFence: boolean; unterminate
function parseUatResultItems(cleanContent: string): Array<{ test: number; name: string; result: string }> {
const items: Array<{ test: number; name: string; result: string }> = [];
// Find all ### N. Name headings (line-anchored)
const headingPattern = /^###\s*(\d+)\.\s*(.+)$/gm;
const headings: Array<{ index: number; test: number; name: string }> = [];
let hMatch: RegExpExecArray | null;
while ((hMatch = headingPattern.exec(cleanContent)) !== null) {
headings.push({
index: hMatch.index + hMatch[0].length,
test: parseInt(hMatch[1], 10),
name: hMatch[2].trim(),
});
// Find all ### N. Name headings.
// #3078-CR MEDIUM (security review follow-up): STRUCTURE and ATTRIBUTION
// need different split frames. This is a STRUCTURE scan — finding where a
// heading block begins — and there is no attribution distinction to
// preserve, so split on any of `\n`, U+2028, U+2029: a heading delimited by
// an exotic line separator (origin/next's `/m`-anchored scan found these;
// a naive `split('\n')`-only port silently stopped finding them, making the
// gate MORE permissive than origin/next) is found exactly like a
// `\n`-delimited one. Contrast the `result:` scan below, which is an
// ATTRIBUTION scan and must NOT do this.
const HEADING_LINE_RE = /^###\s*(\d+)\.\s*(.+)$/;
const headings: Array<{ index: number; lineStart: number; test: number; name: string }> = [];
{
// All three separators are exactly one UTF-16 code unit, so the
// `line.length + 1` offset arithmetic below stays valid regardless of
// which separator terminated a given line.
const lines = cleanContent.split(/[\n\u2028\u2029]/);
let offset = 0;
for (const line of lines) {
const hMatch = line.match(HEADING_LINE_RE);
if (hMatch) {
headings.push({
index: offset + hMatch[0].length,
lineStart: offset,
test: parseInt(hMatch[1], 10),
name: hMatch[2].trim(),
});
}
offset += line.length + 1; // +1 for the separator consumed by split
}
}
for (let i = 0; i < headings.length; i++) {
const h = headings[i];
const blockStart = h.index;
// More precise: find next heading's position in the original string
// We'll slice from current heading end to the position just before next heading's "###"
const nextHeadingMatch = i + 1 < headings.length
? cleanContent.lastIndexOf('\n###', headings[i + 1].index)
: -1;
const blockContent = nextHeadingMatch >= blockStart
? cleanContent.slice(blockStart, nextHeadingMatch)
// A block spans until the START of the next heading's line (tracked
// directly from the same split-frame scan above), not a re-search for a
// literal '\n###' over unsplit text -- the latter would silently miss a
// next heading delimited by U+2028/U+2029 instead of '\n' and swallow
// every subsequent block into this one.
const blockContent = i + 1 < headings.length
? cleanContent.slice(blockStart, headings[i + 1].lineStart)
: cleanContent.slice(blockStart);
// Column-0 anchored result line: /^result:[ \t]*\[?([\w-]+)\]?/mi
// Column-0 result line, split-then-match (#3078-CR MEDIUM — same fix as
// the heading scan above): test each already-split line individually
// against a single-line (no `/m` anchor) pattern instead of anchoring
// over unsplit `blockContent`, so a `result:`-shaped line reachable only
// via a U+2028/U+2029 separator inside an `expected: |` scalar body can
// never register as a fake column-0 match. FIRST MATCH WINS — no
// ambiguity counting, matching src/uat.cts's contract.
// Uses [ \t]* (not \s*) so the captured value must sit on the SAME line as result:.
// A result: key with the value on a subsequent line yields no match → 'missing' (blocker).
const resultMatch = /^result:[ \t]*\[?([\w-]+)\]?/mi.exec(blockContent);
const RESULT_LINE_RE = /^result:[ \t]*\[?([\w-]+)\]?/i;
const resultMatch = blockContent
.split('\n')
.map((line) => line.match(RESULT_LINE_RE))
.find((m): m is RegExpMatchArray => m !== null) ?? null;
if (resultMatch) {
items.push({
test: h.test,
@@ -265,7 +298,11 @@ function evaluateUatPassed(
const uatFilePath = path.join(phaseFullDir, file);
let raw = '';
try {
raw = fs.readFileSync(uatFilePath, 'utf-8');
// #3078-CR MEDIUM: normalize line endings at the read boundary — the
// same seam src/uat.cts and src/verification.cts route through — so a
// lone-CR *-UAT.md is not read as one unbroken line by the column-0
// scans below.
raw = normalizeLineEndings(fs.readFileSync(uatFilePath, 'utf-8'));
} catch {
blockers.push(`${file}: could not read file`);
continue;
@@ -317,7 +354,8 @@ function evaluateUatPassed(
const verificationFilePath = path.join(phaseFullDir, file);
let raw = '';
try {
raw = fs.readFileSync(verificationFilePath, 'utf-8');
// #3078-CR MEDIUM: same read-boundary normalization as the UAT loop above.
raw = normalizeLineEndings(fs.readFileSync(verificationFilePath, 'utf-8'));
} catch {
blockers.push(`${file}: could not read verification file`);
continue;

View File

@@ -22,7 +22,7 @@ import markdownTable = require('./markdown-table.cjs');
const { splitTableRow, isDelimiterRow } = markdownTable;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import coreUtils = require('./core-utils.cjs');
const { toPosixPath } = coreUtils;
const { toPosixPath, normalizeLineEndings } = coreUtils;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import planningWorkspace = require('./planning-workspace.cjs');
const { planningDir } = planningWorkspace;
@@ -114,6 +114,25 @@ function selectPhaseUatFiles(files: string[], phaseDirName: string): string[] {
return scopeToPhase(files.filter((f) => f.includes('-UAT') && f.endsWith('.md')), phaseDirName);
}
/**
* The ONE read boundary for every document `cmdAuditUat` scans off disk
* (#3707-CR follow-up MAJOR). Wraps `fs.readFileSync` +
* `normalizeLineEndings` in a single seam so a lone-CR-separated
* `*-UAT.md`, `*-VERIFICATION.md`, or `deferred-items.md` is normalized BY
* CONSTRUCTION before it reaches ANY downstream parser — current
* (`parseUatItemsWithStats`, `parseVerificationItems`, `parseDeferredItems`)
* or future. Fixing this per-parser was the original (#3707-CR) MEDIUM fix's
* mistake: two of the four ingresses in this function were normalized by
* editing their own parsers directly, and the other two (VERIFICATION,
* deferred-items.md) were missed precisely because nothing forced a new call
* site to remember the step. Routing every read through this function
* removes that failure mode: a parser added later needs no line-ending logic
* of its own, because the text it receives is already normalized.
*/
function readNormalizedDocument(filePath: string): string {
return normalizeLineEndings(fs.readFileSync(filePath, 'utf-8'));
}
function cmdAuditUat(cwd: string, raw: boolean): void {
const phasesDir = path.join(planningDir(cwd), 'phases');
const hasActivePhases = fs.existsSync(phasesDir);
@@ -174,7 +193,7 @@ function cmdAuditUat(cwd: string, raw: boolean): void {
// the reason scopeToPhase has no unfiltered fallback.
for (const file of selectPhaseUatFiles(files, dir)) {
const uatFilePath = path.join(phaseDir, file);
const content = fs.readFileSync(uatFilePath, 'utf-8');
const content = readNormalizedDocument(uatFilePath);
const { items, headingsSeen } = parseUatItemsWithStats(content);
const status = (extractFrontmatter(content, uatFilePath).status as string || 'unknown');
// `parse_gap` means the file contained `### N.` test blocks that
@@ -235,7 +254,7 @@ function cmdAuditUat(cwd: string, raw: boolean): void {
// for the same reason as the UAT loop above.
for (const file of scopeToPhase(files.filter(f => f.includes('-VERIFICATION') && f.endsWith('.md')), dir)) {
const verificationFilePath = path.join(phaseDir, file);
const content = fs.readFileSync(verificationFilePath, 'utf-8');
const content = readNormalizedDocument(verificationFilePath);
const status = extractFrontmatter(content, verificationFilePath).status as string || 'unknown';
if (status === 'human_needed' || status === 'gaps_found') {
const items = parseVerificationItems(content, status, verificationFilePath);
@@ -263,7 +282,7 @@ function cmdAuditUat(cwd: string, raw: boolean): void {
// required.
const deferredFile = 'deferred-items.md';
if (files.includes(deferredFile)) {
const content = fs.readFileSync(path.join(phaseDir, deferredFile), 'utf-8');
const content = readNormalizedDocument(path.join(phaseDir, deferredFile));
const items = parseDeferredItems(content);
if (items.length > 0) {
results.push({
@@ -364,6 +383,13 @@ function cmdRenderCheckpoint(cwd: string, options: { file?: string } = {}, raw:
// ─── parseCurrentTest ─────────────────────────────────────────────────────────
function parseCurrentTest(content: string): CurrentTest {
// #3707-CR: this is the render-checkpoint path's own independent ingress
// into `tokenizeHeadings` (via the `parseFirstPendingTest` fallback below),
// separate from `parseUatItemsWithStats`'s. Normalize here too, ONCE, so a
// lone-CR document cannot hide its first pending row from this path either
// — see `normalizeLineEndings` for why.
content = normalizeLineEndings(content);
// Use the seam to locate the ## Current Test section (ADR-1372 T5).
// HTML-comment stripping within the section body is UAT-specific, so we keep
// the comment removal caller-side after extracting the body.
@@ -1220,10 +1246,21 @@ function countUnattributedIndentedRows(surface: string): number {
* Reported separately so a consumer that must decide whether to WITHHOLD a
* derived number — as opposed to merely REPORT the gap — can tell "a row I
* definitely could not read" from "a row I possibly mis-counted".
* `src/planning-inspect.cts`'s `buildUatRows` is that consumer; `cmdAuditUat`
* is not, and still gates `parse_gap` on the total.
*
* #3707-CR: `src/planning-inspect.cts`'s `buildUatRows` does NOT destructure
* this field (verified — it and `cmdAuditUat` both consume only `items` and
* `headingsSeen`), correcting an earlier stated instruction that it did.
* `shortfallBlocks` currently has NO production consumer outside this
* function's own computation. It is retained on the return value anyway,
* deliberately, as part of this function's published stats contract — tests
* assert on the full `{ items, headingsSeen, shortfallBlocks }` shape, and
* dropping a returned field is a wider, unrelated change than a line-ending
* fix warrants. A future consumer that needs to distinguish an
* accepted-over-report shortfall from the rest of `headingsSeen` (the
* original design intent above) can still do so.
*/
function parseUatItemsWithStats(content: string): { items: UatItem[]; headingsSeen: number; shortfallBlocks: number } {
content = normalizeLineEndings(content);
const items: UatItem[] = [];
let headingsSeen = 0;
let shortfallBlocks = 0;
@@ -1422,7 +1459,45 @@ function parseUatItemsWithStats(content: string): { items: UatItem[]; headingsSe
// doing so previously changed `categorizeItem`'s classification for
// shapes origin/next categorized differently (an unpinned behavior
// change, not something the blocker required).
const resultLineMatch = fenceStrippedBlock.match(/^result:\s*\[?(\w+)\]?.*$/im);
// #3078-CR defect A fix, split-then-match scan: the previous `.match()`
// against `/^result:.../im` ran a MULTILINE regex anchor directly over
// unsplit block text. ECMA-262's LineTerminator set for `^`/`$` under
// `/m` includes U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR, but
// `content.split('\n')` and this module's own heading tokenizer do NOT
// treat either as a boundary. A `result:`-shaped line inside an
// `expected: |` scalar body, sitting immediately after one of these
// separators instead of an ordinary character, was therefore read as a
// genuine line start by the regex engine even though it is not
// `\n`-delimited from anything — it is exactly as much "one line" to
// every other consumer as the ordinary-character control case.
// Splitting on `\n` FIRST and testing each already-split line against a
// single-line (`/im`-anchor-free) pattern fixes this: a line is never
// split by U+2028/U+2029 (`String.prototype.split` matches only its
// literal separator argument, never the wider ECMA-262 LineTerminator
// set), so a `result:`-shaped line reachable only via one of those
// separators can never register as its own split line — the split view
// and the regex view are back in agreement, by construction, exactly the
// way `splitLines` module is documented to be immune to the sibling `\r`
// bug.
//
// FIRST MATCH WINS (byte-identical to origin/next otherwise): a block
// with more than one column-0 `result:` line resolves to the FIRST one
// encountered, same as the pre-existing `.match()` behaviour without
// `/g` — this is deliberately NOT an ambiguity/parse-gap case (that
// variant was tried and reverted: its boundary-truncation heuristic
// mistook an indented `### N.` living inside a legitimate block scalar
// for a heading boundary, corrupting every scalar/indent guard in this
// module — see tests/uat.test.cjs's #3078 scalar guard family).
// Trailing text is matched with `[^]*` rather than `.*` (final review
// MINOR 1): `.` never matches U+2028/U+2029, so a column-0 `result:`
// line whose trailing text contains one of those separators would
// otherwise never reach `$`, and the whole line would fail to match —
// an unpinned regression against origin/next, which parses it.
const RESULT_LINE_RE = /^result:\s*\[?(\w+)\]?[^]*$/i;
const resultLineMatch = fenceStrippedBlock
.split('\n')
.map((line) => line.match(RESULT_LINE_RE))
.find((m): m is RegExpMatchArray => m !== null);
if (!resultLineMatch) {
headingsSeen += 1;
continue;

View File

@@ -37,6 +37,8 @@ import phaseId = require('./phase-id.cjs');
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');
// eslint-disable-next-line @typescript-eslint/no-require-imports -- core-utils.cjs is an export= CommonJS module
import coreUtilsMod = require('./core-utils.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports -- planning-scope.cjs is an export= CommonJS module
import planningScopeMod = require('./planning-scope.cjs');
import { execGit } from './shell-command-projection.cjs';
@@ -45,6 +47,7 @@ import { formatGsdSlash, resolveRuntime } from './runtime-slash.cjs';
const { output, error } = io;
const { extractPhaseToken, scopeToPhase } = phaseId;
const { extractFrontmatter } = frontmatterMod;
const { normalizeLineEndings } = coreUtilsMod;
const { SCOPE } = planningScopeMod;
type Scope = planningScopeMod.Scope;
@@ -650,7 +653,17 @@ function readVerificationStatus(
const filePath = path.join(phaseDir, verificationFile);
let rawStatus: string | null = null;
try {
const content = fsImpl.readFileSync(filePath, 'utf-8');
// #3707-CR follow-up MINOR 1: normalize line endings at this read
// boundary — this function's own `readFileSync` is the equivalent seam
// `planning.inspect`'s `buildUatRows`/`readDocument` route through for
// UAT/REQUIREMENTS documents, but `readVerificationStatus` had no such
// normalization of its own. A lone-CR VERIFICATION.md's `---\r...\r---`
// frontmatter fence never matched `extractFrontmatter`'s byte-0
// `---\n`/`---\r\n` check, so `status: passed` was read as absent and
// this function reported 'missing' — under-reporting a completed
// verification as if the step never ran, the fail-safe direction but the
// same root cause as the false-clean class fixed elsewhere in #3707-CR.
const content = normalizeLineEndings(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;