* fix(#3458): scan archived milestone phases in the four audit-open scanners `query audit-open` resolved exactly one phase root, `.planning/phases/`. When a milestone closes its phase directories move to `.planning/milestones/v<X.Y>-phases/`, so an item still unresolved at that moment — the `[R]/[A]/[C]` prompt accepts "accept" and "carry forward", not only "resolve" — became invisible to the v1.1 pre-close audit and every audit after it. The window in which an unresolved item is visible to this gate was exactly one milestone wide, and nothing announced when it closed. Reproduced before fixing, with byte-identical artifacts in the two layouts and the active layout as the control: active → has_open_items=true deferred=1 uat_gaps=1 total=2 archived → has_open_items=false deferred=0 uat_gaps=0 total=0 `scanDeferredItems`' own doc comment names this as the thing it was built to prevent — "phase directories archive to `milestones/vX.Y-phases/` (#1871) and the entry leaves the live tree having never been triaged" — while the implementation eleven lines below cannot read that path. It catches an entry at its own milestone close and goes blind at precisely the transition the comment describes. This is not cosmetic under-reporting. `auditOpenArtifacts` sums all nine category counts into `counts.total` and returns `has_open_items: counts.total > 0`, so four blind scanners can flip the gate's headline boolean and let `/gsd-complete-milestone` assert a clean close it never verified. In a fully-archived project `.planning/phases/` may not exist at all, and the scanners' `if (!fs.existsSync(phasesDir)) return []` produced a value indistinguishable from "nothing is open". ## One enumeration, not four The four scanners each hand-rolled the same active-only walk. They now share `listAuditPhaseTargets(planDir, cwd)`, which yields both roots — the shape of fix epic #3473's B2 asks for, and the reason the fix is one seam rather than four edits. Three properties are load-bearing: * the ACTIVE enumeration is unchanged — still a raw `readdirSync`, NOT `listMilestonePhaseDirs`. These scanners are deliberately not milestone-filtered today, and switching would silently add window and sentinel filtering: a behavior change belonging to #3372, not here. * a missing or unreadable active root skips that half instead of returning early. That early return WAS the bug in a fully-archived project. * archived dirs are deliberately NOT milestone-filtered, per the comment `src/uat.cts` already carries: archived phases belong to past milestones by definition, so applying the current-milestone filter discards every one and silently reinstates this bug. Each item now carries `archived_milestone` when it comes from a closed milestone, matching how the sibling module already labels archived results — without it an operator triaging `[R]/[A]/[C]` cannot tell a live item from one carried over. Additive: no existing test or doc asserted an exact key set. `scripts/lint-phase-enumeration-drift.cjs`'s exemption list for this file drops from the four scanner names to the single helper, since that is now the only place the enumeration lives. ## Tests Written failing-first and confirmed red for the right reason before the fix, all four driven through the real `audit-open` CLI rather than private functions: archived-only (was 0/0/0/0 with `has_open_items=false`, now 1/1/1/1 true), mixed active+archived (was 1/1/1/1 — the archived half dropped — now 2/2/2/2), active-only unchanged, and an all-resolved archived phase contributing 0. That last one passed vacuously before the fix, because the archived path was not reached at all; it was re-verified as genuinely discriminating afterward by flipping one archived item to unresolved and watching the count rise. Closes #3458 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3458): restore the scan_error sentinel and show archive provenance Adversarial review found one BLOCKER that the previous revision introduced, which a green remote-runner suite did not catch because nothing in the tree asserts `scan_error` at all. ## The regression Consolidating four hand-rolled walks into `listAuditPhaseTargets` swallowed the active-root `readdirSync` throw in a bare `catch {}`. Pre-fix each scanner returned `[{scan_error: true, …}]`; after, each returned `[]`. Measured with `.planning/phases` created as a FILE (so `existsSync` passes and `readdirSync` throws ENOTDIR): before this fix: uat_gaps/verification_gaps/context_questions/deferred_items each `[{"scan_error":true,…}]` the regression: each `[]` `complete-milestone.md` re-runs `audit-open --json` and reads those counts, so a machine consumer could no longer tell "I/O failed" from "verified clean" — the exact conflation this issue exists to remove, reintroduced on the failure path. `listAuditPhaseTargets` now reports `activeUnreadable` and each scanner pushes the sentinel shape recovered verbatim from `origin/next`, not reinvented. The docstring claiming the active enumeration was "UNCHANGED" was false while that sentinel was missing, and is corrected to state what is actually preserved. An unreadable ARCHIVED root deliberately gets NO sentinel: there was no archived read before, so there is no consumer contract to preserve, and adding one would conflate the ordinary "no milestones archived yet" state with a real I/O failure. ## The operator could not see the archive `formatAuditReport` is the surface the gate actually shows a human — `complete-milestone.md` runs it without `--json` — and it never rendered `archived_milestone`. With `01-alpha` in both roots the identical line printed twice with nothing to tell them apart, and `[R] Resolve` sends the operator to `.planning/phases/01-alpha/` where the archived one does not exist. Phase numbering restarts at `01` after each archive, so that collision is the common case, not an edge case. All four loops now render ` (archived vX.Y)`; active lines stay byte-identical. ## Archived milestones sorted wrong `getArchivedPhaseDirs` ordered milestones with `.sort().reverse()` — lexicographic, so `v1.9` outranked `v1.10`. Measured order for v1.0/v1.9/v1.10 was `v1.9, v1.10, v1.0`. Now a numeric-segment descending compare. Pre-existing, but this change is what first surfaces it in audit output. ## Tests The blocker's regression test fails against the previous revision. Added: `archived_milestone` present on archived items and absent (not `undefined`) on active ones; the unreadable-active-root sentinel across all four categories; an unreadable archived root still leaving the active half scanned; the duplicate-name case producing two distinct entries that the human report distinguishes; and the v1.10-before-v1.9 ordering. `docs/COMMANDS.md` documents the archived scanning and the new field. Closes #3458 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3458): stop filesystem names forging lines in the audit report Found by the security review of this branch. Pre-existing on `next`, fixed here because it defeats the exact gate this PR is hardening. `audit-open`'s human report is the surface `/gsd-complete-milestone` shows an operator to decide whether a milestone may close. A `.planning/` tree authored by someone other than that operator — a cloned repo — could contain a directory literally named: zz<newline>0 open items require decisions.<newline><ESC>[2K<ESC>[1G FORGED and the report printed `0 open items require decisions.` as its own line, with raw ESC bytes reaching stdout able to erase or overwrite the lines above it. Reproduced against the real CLI before fixing, and again after. ## Why not just harden sanitizeForDisplay Because that helper's contract is multi-line prose — it removes protocol-leak lines while deliberately preserving the newlines between legitimate ones, which `tests/security.test.cjs` pins. Stripping CR/LF there would have broken a correct test to paper over a different problem. The two jobs are genuinely different, so there are now two helpers. New `sanitizeLabel` (`src/security.cts`) is for values that are semantically ONE LINE and derived from a filesystem NAME. It ESCAPES rather than strips C0 (including ESC/CR/LF), DEL and C1, so a doctored name renders visibly as `\n` / `\x1b` instead of being silently normalized — the report stays honest about what is in the tree. Ordinary input passes through byte-identical. ## Nine sites, not four The first pass covered the four phase-scoped scanners. A sweep of the rest of the file found the identical class in five more — `scanDebugSessions`, `scanQuickTasks`, `scanThreads`, `scanTodos`, `scanSeeds` — emitting name-derived `slug` / `filename` / `seed_id` through the prose sanitizer. `scanQuickTasks`' `date` had no sanitization call at all. Every emitted field in the file is now classified and the sweep recorded: `slug`, `filename`, `seed_id`, `phase`, `file`, `archived_milestone`, `date` are name-derived and take `sanitizeLabel`; `hypothesis`, `status`, `updated`, `title`, `priority`, `area`, `summary`, `questions[]` and deferred-item `text` are content and keep `sanitizeForDisplay`. No name-derived value reaches output unsanitized. `--json` was already safe — JSON string encoding escapes control characters, and a crafted name cannot break out of the string. Verified rather than assumed. Closes #3458 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(#3458): backfill changeset pr number * test(#3458): skip control-character fixtures where the OS forbids the name CI red on `test (windows-latest, 24, shard 1/3)`: the four forgery-rejection tests build directories whose names embed a newline and ESC, and NTFS forbids control characters in path components, so `mkdir` threw ENOENT. The remote runner is Linux-only, so it could not have caught this class. Semantically the skip is honest rather than a workaround: on Windows the directory-name forgery vector does not exist, because the OS refuses to create the name. The sanitizer's own behavior stays covered there by the `sanitizeLabel` unit tests, which are pure string tests with no filesystem calls — verified. Uses the repo's established capability-probe convention (`tests/adr-index-gate.test.cjs`'s `trySymlink`), which `t.skip()`s on the real errno rather than branching on `process.platform`, and whose comment gives the reason: a bare `return` "would silently report a PASS ... and hide the gap this guard exists to close". A skipped test is visibly skipped. Swept every test added on this branch for names Windows would reject or POSIX path assumptions; these four were the only ones. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(#3458): make [A] Acknowledge actually suppress, without overwriting a verdict Making archived phases visible exposed the other half of the problem: an item unresolved at a milestone close now resurfaces at every later close forever, because `[A] Acknowledge` wrote a prose block to STATE.md that `auditOpenArtifacts` never reads. `verified_closeout` became unreachable and the gate degraded to a mandatory `[A]` every time. ## The prompt does not change `[A] Acknowledge all` already promises "document as deferred and proceed with close". It documented but never deferred. This makes `[A]` do what it says. `[R]` and `[C]` stay abort paths. No "carry forward" option is invented — an item that is not acknowledged simply keeps surfacing, which is the default. ## The marker lives inside the artifact Not a ledger. The audit mints no ids and has no stable identity — `phase` is a token that collides across directories, `file` for deferred items is a constant, and identity otherwise degrades to the item's own prose after a lossy sanitizer. Any ledger must re-derive that key every close, so a reworded item silently un-suppresses or, worse, mis-suppresses a different one. Storing the acknowledgment next to the thing it suppresses makes that class of bug structurally impossible, and it is the pattern `src/uat.cts` already argues for with `deferred-items.md`'s in-place `status: resolved`. ## The marker is verdict-preserving and self-invalidating `status:` is never overwritten — writing `resolved` into an unresolved UAT would be a lie in the artifact of record, and the disclosure has to be additive. audit_acknowledged: milestone: v1.0 at: 2026-08-15 status: gaps_found # snapshot of what was true when acknowledged Suppression applies ONLY while the snapshot still matches reality: `status` for seven categories, `question_count` for context questions, and for deferred items a new per-entry `status: acknowledged` distinct from `resolved`, which keeps meaning "actually fixed". Change the artifact and the acknowledgment stops applying, so the item comes back on its own. That is what makes re-opening answer itself with no extra state, and it fails in the safe direction: a stale acknowledgment can never hide a NEW problem. A malformed marker is treated as absent — a bad marker must never silence an item. The check is ONE shared `isAuditItemAcknowledged`, not nine copies. This file has already been through that defect family twice in this PR. ## Observable, not silent `audit-open --json` now reports an `acknowledged` count beside `counts`, so a reviewer can tell a close that is clean because things were fixed from one that is clean because things were silenced. ## Writer New `audit-open acknowledge` verb snapshots current state itself, so the marker is never hand-authored from workflow prose — the gap that left the STATE.md block with no writer, no schema and two conflicting formats. Writes route through the existing path-confinement seam. ## Two deliberate limits, failing closed Heading-delimited deferred entries (#3457) are REFUSED with `unsupported_heading_shape` rather than edited, because mapping a heading entry back to its exact source span is not safely derivable when headless and heading entries interleave in one file. A loud refusal beats a mis-targeted write. A quick task with no summary gets one created to carry the marker, since there is otherwise nowhere to put it. ## Tests Self-invalidation is the important one and is covered per category: acknowledge, then change the status or question count, and the item resurfaces. Also malformed markers not suppressing, `status:` byte-unchanged after acknowledging, the writer refusing a path outside the project, and the four original #3458 scenarios unchanged. Closes #3458 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(#3458): wire [A] to the acknowledge verb and converge the disclosure table Consumer side of the suppression seam. ## The workflow stops hand-authoring the mechanism `[A]` now calls `audit-open acknowledge` once per open item, then writes the STATE.md `## Deferred Items` table as before. The table stays as a human-readable disclosure; it is no longer the mechanism. That closes the gap where the block had no writer, no schema and no reader — the marker is now written by the tool, which snapshots current state itself. The `[R]` / `[A]` / `[C]` prompt is unchanged, `[C]` still means "Cancel — exit without closing", and no carry-forward option is invented. The all-clear branch now distinguishes a close that is clean because items were FIXED from one that is clean because they were ACKNOWLEDGED, using the `acknowledged.total` count, and carries that into the MILESTONES.md disclosure line beside the existing override count. A clean close that was bought with acknowledgments should say so. ## Format drift resolved Two incompatible `## Deferred Items` shapes shipped simultaneously — 3 columns in the workflow, 4 in the template, with different body lines. Converged on one 5-column shape carrying the source Milestone, since archived items now appear and the archived-milestone disambiguator was previously discarded at write time. The workflow enumerates the categories instead of trailing off in `...`. ## Ack fragment bookkeeping `complete-milestone.md` grows 6,764 bytes (31,228 → 37,992; cap 61,440), covered by a new `tests/emitted-drift-acks/3458-*.json`. `2962-zsh-nomatch-for-glob-portability.json`'s `complete-milestone.md` entry is REMOVED — the no-duplicate-path rule hard-blocks two sources naming one path. That entry is spent: the nullglob shim it acknowledges is present in both `origin/next` and the CI emitted baseline `fd2b97a5`, so its ripple is already absorbed and it can never clear anything again — verified directly, not assumed, and the gate's own message directs deleting spent entries. Its other three files' entries are untouched. `scripts/sync-runtime-launcher.cjs` wanted to rewrite `explore.md` as well — pre-existing drift unrelated to this change, reverted. `complete-milestone.md` still carries exactly one canonical preamble. Docs cover the verb's real flag surface, the marker's verdict-preserving and self-invalidating behavior, and the new `acknowledged` count. A second `Added` changeset covers the verb, since the existing `Fixed` fragment describes only the archived-phase scanning. Closes #3458 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3458): close three blockers in the acknowledgment seam Adversarial review of the seam. Three BLOCKERs, one of which disproves a safety claim I published in the PR body, the changeset and the docs. ## The claim was false; the code is fixed rather than the claim softened I wrote that "a stale acknowledgment can never hide a NEW problem". It could. `context_questions` snapshotted only the question COUNT, so replacing two acknowledged questions with two brand-new blockers kept the item suppressed. `uat_gaps` snapshotted only `status`, so adding five more pending scenarios (`open_scenario_count` 1→6) kept it suppressed. The snapshot now identifies CONTENT, not size: a digest of the whole question set, and a status + open-scenario-count composite. Any edit invalidates. The other seven categories were checked and their single tracked dimension is already the whole story. Both disproofs now resurface the item. ## Writing to the wrong line, and reporting success `acknowledgeDeferredItem` built an unanchored regex and exec'd it over the whole file while match-selection and the ambiguity guard ran over the section body only, so the write landed at the first match ANYWHERE. A file with `# Notes` holding `- Fix the parser` above a `## Deferred Items` section holding the same bullet: the CLI exited 0 saying `acknowledged: true`, injected `status: acknowledged` under `# Notes`, and re-audit still reported the entry open. It corrupted unrelated content, suppressed nothing, and claimed success — and since `--file` is unconstrained the same path could inject into a UAT or VERIFICATION body. Matching is now anchored to the selected section, and the matched span is re-verified against the selected entry before any write; a mismatch refuses with `match_verification_failed` rather than writing. ## Acknowledging todos hid the ones never shown `scanTodos` capped at five files and then checked acknowledgment. With seven todos, acknowledging the five that were LISTED drove `todos: 0`, `has_open_items: false`, and items six and seven never appeared in any later scan. The workflow's own "repeat until no todos items" remedy terminates after one pass. Pre-feature this was unreachable because the count was pinned at five. That is silent over-suppression — the exact direction this PR exists to remove. Acknowledged items are now filtered BEFORE the display cap, so unacknowledged todos beyond it still drive the count. ## The [A] branch could not fail closed Every acknowledge call sat in a `cmd | while read` pipeline with no status accumulation, so any refusal was discarded and the close proceeded as `override_closeout`. Separately, `io.output` swaps payloads over 50000 chars for an `@file:<path>` sentinel — every `jq` would then fail, every loop body run zero times, nothing be suppressed, and the close happen anyway. Both closed: failures accumulate across all invocations and halt before close, and the sentinel is dereferenced using the same pattern `verify_readiness` already uses for `INIT_MANAGER`. Quoting was verified sound by the review and is left alone. ## Also Suppression is now visible in the human report, not only `--json` — the "clean because fixed vs clean because silenced" distinction was promised for the surface an operator actually reads. The CRLF-preservation branches in the writer were dead: every `.md` write goes through `_normalizeMd`, which normalizes line endings and blank lines whatever the writer does. Deleted and documented rather than left as code that cannot run. ## Why these shipped The review named it exactly: there was no coverage for `unsupported_heading_shape`, `ambiguous`, `not_found`, duplicate-text mis-targeting, todos beyond the cap, or CRLF. All are now tested, alongside both snapshot disproofs and the mixed-section fixture. Closes #3458 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(#3458): align the items-open footer wording with its assertion Remote runner red on one test: the items-open footer must match `/previously acknowledged item/i`. The disclosure was NOT missing — the items-open branch already printed "N additional items previously acknowledged and still suppressed." The word order simply did not match the regex the test in the same change asserts. A wording mismatch between my own test and my own implementation, not a behavior gap. Reworded to "N previously acknowledged items also suppressed above the M open items", which satisfies the assertion and states the relationship between the two counts more plainly than the original did. Swept `formatAuditReport` for other branches that could skip the tally: the only early return is the all-clear path, which already discloses it. `scan_error` sentinels are filtered per category and excluded from `counts.total`, so an all-error project falls through to that same branch. No inconsistency remains. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3458): splice by carried span, digest the untruncated question set Security review of the writer. Both findings are the same shape, and both are cases where an earlier fix of mine was incomplete in the same direction: a value derived for DISPLAY was reused for an IDENTITY or LOCATION decision. ## Writing to the wrong entry, again The previous fix anchored matching to the `## Deferred Items` SECTION but still re-found the entry inside it with an unanchored regex, so the write landed at the first SUBSTRING occurrence rather than the entry's own span. The `match_verification_failed` guard could not catch it, because the mis-targeted span is byte-identical to the target. Probe-confirmed, in a cloned repo's own artifact: - CRITICAL unfixed auth bypass see also: - minor typo - minor typo Acknowledging "minor typo" appended `status: acknowledged` into the CRITICAL entry, suppressing it at every future close, while the typo stayed open — exit 0, `"acknowledged": true`. A variant where the target text appears inside unrelated prose split that line mid-sentence, acknowledged nothing, and still exited 0, so the workflow's `ACK_FAILURES` halt never fired. Fixed structurally rather than with a better regex: `splitGapsEntriesWithSpans` carries each entry's own character span out of the splitter, and the write splices by that recorded span. The location is already known at selection time — re-deriving it by searching was the entire defect class. Added as a sibling so `splitGapsEntries`' three existing callers are untouched. With index-splicing, `match_verification_failed` becomes a genuine independent cross-check instead of a guard that could never fire. ## The digest was blind past the third question `deriveOpenQuestions` truncated to three questions, and clamped each to 200 chars, BEFORE the digest hashed it — so the snapshot could not see the fourth and later. Ship three innocuous questions, acknowledge, then add real blockers, and they are permanently invisible: measured `open=0, acknowledged=1`, report "All artifact types clear." That is the same self-invalidation property this digest was added to guarantee one revision ago. The digest now covers the untruncated list; truncation is display-only. Found while fixing it: the previous digest joined on a literal raw NUL byte embedded in the source — collisions are constructible, and reachable through attacker-controlled YAML `\x00` escapes. Verified both ways. Replaced with a length-prefixed encoding so no two question sets can collide by concatenation. ## Sweep Because this is the third incomplete fix on this seam, every identity and location derivation was swept for the display-vs-identity confusion: uat_gaps uses status plus a full-content count, the other seven categories use a scalar status or presence, the deferred `--text` identity is never truncated, and all five flat categories resolve their file by path rather than by content search. No further instances. Closes #3458 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(#3458): correct two assertions that over-reached the measured behavior Remote runner red on two of the F1 tests. The source is correct — reproduced both fixtures against the built CLI — and both failures were bugs in the assertions I wrote. `src/` is untouched by this commit. The first is worth recording. It computed the CRITICAL entry's block as content.slice(content.indexOf('- CRITICAL'), content.indexOf('- minor typo')) and `indexOf` found the FIRST SUBSTRING occurrence, which lives inside that entry's own continuation line ` see also: - minor typo`. The block was truncated mid-line, so the assertion could never match. The test committed the exact first-substring-match mistake it exists to catch, one revision after that mistake was fixed in the source. The second asserted `deferred_items === 0` after acknowledging the typo entry, but the decoy `- Note: reference - minor typo elsewhere, ignore` is itself an open entry and was never acknowledged, so the correct count is 1. It now also asserts WHICH item remains open — that is what actually proves the right entry was suppressed, and the original assertion would have passed even if both had been silenced. Both now derive their expectations from measured CLI output. A comment records that the write seam normalizes markdown (`_normalizeMd` inserts a blank line before a list item following a non-list line) so the inserted line is not later mistaken for a regression; that is repo-wide behavior for every `.md` write through the single write projection, not something this change should diverge from. Root cause of both: the previous two dispatches verified behavior with direct CLI probes but never executed the test file, so assertions could over-reach what had actually been measured. Every other assertion added in those two commits has since been re-derived from real output; no further mismatches. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: sim <sim@local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1669 lines
75 KiB
TypeScript
1669 lines
75 KiB
TypeScript
/**
|
||
* UAT Audit — Cross-phase UAT/VERIFICATION scanner
|
||
*
|
||
* Reads all *-UAT.md and *-VERIFICATION.md files across all phases.
|
||
* Extracts non-passing items. Returns structured JSON for workflow consumption.
|
||
*
|
||
* ADR-457 build-at-publish: the hand-written bin/lib/uat.cjs collapsed
|
||
* to a TypeScript source of truth. Behaviour is preserved byte-for-behaviour
|
||
* from the prior hand-written .cjs; only strict types are added.
|
||
*/
|
||
|
||
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||
import io = require('./io.cjs');
|
||
const { output, error } = io;
|
||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||
import markdownSectionizer = require('./markdown-sectionizer.cjs');
|
||
const { collectSection, tokenizeHeadings } = markdownSectionizer;
|
||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||
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;
|
||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||
import planningWorkspace = require('./planning-workspace.cjs');
|
||
const { planningDir } = planningWorkspace;
|
||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||
import frontmatter = require('./frontmatter.cjs');
|
||
const { extractFrontmatter } = frontmatter;
|
||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||
import phaseIdMod = require('./phase-id.cjs');
|
||
const { PHASE_NUMBER_TOKEN_SOURCE, scopeToPhase } = phaseIdMod;
|
||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||
import phaseLocator = require('./phase-locator.cjs');
|
||
const { getArchivedPhaseDirs, listMilestonePhaseDirs } = phaseLocator;
|
||
import { requireSafePath, sanitizeForDisplay } from './security.cjs';
|
||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- config-loader.cjs is an export= CommonJS module
|
||
import configLoader = require('./config-loader.cjs');
|
||
const { loadConfig } = configLoader;
|
||
|
||
// ─── Types ────────────────────────────────────────────────────────────────────
|
||
|
||
type UatResult = string;
|
||
type UatCategory = 'server_blocked' | 'device_needed' | 'build_needed' | 'third_party' | 'blocked' | 'skipped_unresolved' | 'pending' | 'human_uat' | 'unknown' | 'deferred';
|
||
|
||
interface UatItem {
|
||
test?: number;
|
||
name: string;
|
||
expected?: string;
|
||
result: UatResult;
|
||
category: UatCategory;
|
||
reason?: string;
|
||
blocked_by?: string;
|
||
}
|
||
|
||
interface UatFileResult {
|
||
phase: string;
|
||
phase_dir: string;
|
||
file: string;
|
||
file_path: string;
|
||
type: 'uat' | 'verification' | 'deferred';
|
||
status: string;
|
||
/**
|
||
* Milestone version whose archive this phase dir was read from
|
||
* (`.planning/milestones/<version>-phases/`), or undefined for a phase still
|
||
* in the active `.planning/phases/` tree. Lets a consumer label provenance
|
||
* instead of presenting archived and in-flight work identically.
|
||
*/
|
||
archived_milestone?: string;
|
||
items: UatItem[];
|
||
}
|
||
|
||
interface CurrentTest {
|
||
complete: boolean;
|
||
number?: number;
|
||
name?: string;
|
||
expected?: string;
|
||
}
|
||
|
||
// ─── cmdAuditUat ─────────────────────────────────────────────────────────────
|
||
|
||
function cmdAuditUat(cwd: string, raw: boolean): void {
|
||
const phasesDir = path.join(planningDir(cwd), 'phases');
|
||
const hasActivePhases = fs.existsSync(phasesDir);
|
||
|
||
// #2766: on milestone completion `milestone.cts` MOVES each phase dir into
|
||
// `.planning/milestones/<version>-phases/` (archive-by-default since #1871),
|
||
// leaving `.planning/phases/` empty or absent. Scanning only the active tree
|
||
// meant a partly-archived project silently omitted the archived phases, and a
|
||
// fully-archived one hard-errored with "No phases directory found" —
|
||
// indistinguishable from a broken install. Outstanding UAT items do not stop
|
||
// mattering when a milestone closes: a deferred human-UAT scenario or a
|
||
// `skipped` live-stack test is exactly what gets archived still-open.
|
||
//
|
||
// Reuses the canonical `getArchivedPhaseDirs` seam (phase-locator.cts), which
|
||
// `findPhaseInternal` already uses for this same fallback, so the archive
|
||
// layout convention stays owned by one module.
|
||
const archivedDirs = getArchivedPhaseDirs(cwd);
|
||
if (!hasActivePhases && archivedDirs.length === 0) {
|
||
error('No phases directory found in planning directory');
|
||
}
|
||
|
||
const results: UatFileResult[] = [];
|
||
|
||
// Active dirs are milestone-filtered; archived dirs deliberately are NOT.
|
||
// listMilestonePhaseDirs derives the CURRENT milestone's phase directories
|
||
// (window + sentinel filtered) from ROADMAP.md, and archived phases belong
|
||
// to past milestones by definition — so applying it to them discards every
|
||
// one and silently reinstates the bug.
|
||
const scanTargets: { dir: string; phaseDir: string; milestone?: string }[] = [];
|
||
|
||
if (hasActivePhases) {
|
||
// #3185 (ADR-3180 Decision 1): routed through the canonical owner
|
||
// instead of a hand-rolled readdirSync + isDirInMilestone filter, which
|
||
// also never excluded sentinels, unlike the owner.
|
||
const dirs = listMilestonePhaseDirs(phasesDir, { cwd }).value;
|
||
for (const dir of dirs) {
|
||
scanTargets.push({ dir, phaseDir: path.join(phasesDir, dir) });
|
||
}
|
||
}
|
||
|
||
for (const archived of archivedDirs) {
|
||
scanTargets.push({
|
||
dir: archived.name,
|
||
phaseDir: archived.fullPath,
|
||
milestone: archived.milestone,
|
||
});
|
||
}
|
||
|
||
for (const { dir, phaseDir, milestone } of scanTargets) {
|
||
const phaseMatch = dir.match(new RegExp(`^(${PHASE_NUMBER_TOKEN_SOURCE})`, 'i'));
|
||
const phaseNum = phaseMatch ? phaseMatch[1] : dir;
|
||
const files = fs.readdirSync(phaseDir);
|
||
|
||
// Process UAT files — scoped to THIS phase's own token (#3511) via
|
||
// scopeToPhase, so a stray, cross-phase, or ad-hoc file cannot be reported
|
||
// under this phase's audit-uat entry. A phase whose own UAT file is
|
||
// genuinely absent scopes to empty and contributes nothing — correct, and
|
||
// the reason scopeToPhase has no unfiltered fallback.
|
||
for (const file of scopeToPhase(files.filter(f => f.includes('-UAT') && f.endsWith('.md')), dir)) {
|
||
const uatFilePath = path.join(phaseDir, file);
|
||
const content = fs.readFileSync(uatFilePath, 'utf-8');
|
||
const items = parseUatItems(content);
|
||
if (items.length > 0) {
|
||
results.push({
|
||
phase: phaseNum,
|
||
phase_dir: dir,
|
||
file,
|
||
file_path: toPosixPath(path.relative(cwd, path.join(phaseDir, file))),
|
||
type: 'uat',
|
||
status: (extractFrontmatter(content, uatFilePath).status as string || 'unknown'),
|
||
archived_milestone: milestone,
|
||
items,
|
||
});
|
||
}
|
||
}
|
||
|
||
// Process VERIFICATION files — scoped to THIS phase's own token (#3511)
|
||
// 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 status = extractFrontmatter(content, verificationFilePath).status as string || 'unknown';
|
||
if (status === 'human_needed' || status === 'gaps_found') {
|
||
const items = parseVerificationItems(content, status, verificationFilePath);
|
||
if (items.length > 0) {
|
||
results.push({
|
||
phase: phaseNum,
|
||
phase_dir: dir,
|
||
file,
|
||
file_path: toPosixPath(path.relative(cwd, path.join(phaseDir, file))),
|
||
type: 'verification',
|
||
status,
|
||
archived_milestone: milestone,
|
||
items,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
// Process deferred-items.md (#2287) — the SCOPE BOUNDARY convention
|
||
// (agents/gsd-executor.md) has the executor log out-of-scope discoveries
|
||
// to this file; nothing previously read it back. Surface every
|
||
// UNRESOLVED entry (see parseDeferredItems for the resolved/unresolved
|
||
// parsing rule) as a 'deferred'-typed result, keeping deferred-items.md
|
||
// itself the single source of truth — no duplicate pending-todo entry
|
||
// required.
|
||
const deferredFile = 'deferred-items.md';
|
||
if (files.includes(deferredFile)) {
|
||
const content = fs.readFileSync(path.join(phaseDir, deferredFile), 'utf-8');
|
||
const items = parseDeferredItems(content);
|
||
if (items.length > 0) {
|
||
results.push({
|
||
phase: phaseNum,
|
||
phase_dir: dir,
|
||
file: deferredFile,
|
||
file_path: toPosixPath(path.relative(cwd, path.join(phaseDir, deferredFile))),
|
||
type: 'deferred',
|
||
status: 'unresolved',
|
||
archived_milestone: milestone,
|
||
items,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
// Compute summary
|
||
const summary: {
|
||
total_files: number;
|
||
total_items: number;
|
||
by_category: Record<string, number>;
|
||
by_phase: Record<string, number>;
|
||
} = {
|
||
total_files: results.length,
|
||
total_items: results.reduce((sum, r) => sum + r.items.length, 0),
|
||
by_category: {},
|
||
by_phase: {},
|
||
};
|
||
|
||
for (const r of results) {
|
||
if (!summary.by_phase[r.phase]) summary.by_phase[r.phase] = 0;
|
||
for (const item of r.items) {
|
||
summary.by_phase[r.phase]++;
|
||
const cat = item.category || 'unknown';
|
||
summary.by_category[cat] = (summary.by_category[cat] || 0) + 1;
|
||
}
|
||
}
|
||
|
||
output({ results, summary }, raw, undefined);
|
||
}
|
||
|
||
// ─── cmdRenderCheckpoint ──────────────────────────────────────────────────────
|
||
|
||
function cmdRenderCheckpoint(cwd: string, options: { file?: string } = {}, raw: boolean): void {
|
||
const filePath = options.file;
|
||
if (!filePath) {
|
||
error('UAT file required: use uat render-checkpoint --file <path>');
|
||
}
|
||
|
||
const resolvedPath = requireSafePath(filePath, cwd, 'UAT file', { allowAbsolute: true });
|
||
if (!fs.existsSync(resolvedPath)) {
|
||
error(`UAT file not found: ${filePath}`);
|
||
}
|
||
|
||
const content = fs.readFileSync(resolvedPath, 'utf-8');
|
||
const currentTest = parseCurrentTest(content);
|
||
|
||
if (currentTest.complete) {
|
||
error('UAT session is already complete; no pending checkpoint to render');
|
||
}
|
||
|
||
const config = loadConfig(cwd);
|
||
const responseLanguage = typeof config.response_language === 'string' ? config.response_language : undefined;
|
||
const checkpoint = buildCheckpoint(currentTest as Required<Omit<CurrentTest, 'complete'>> & { complete: false }, responseLanguage);
|
||
output({
|
||
file_path: toPosixPath(path.relative(cwd, resolvedPath)),
|
||
test_number: currentTest.number,
|
||
test_name: currentTest.name,
|
||
checkpoint,
|
||
}, raw, checkpoint);
|
||
}
|
||
|
||
// ─── parseCurrentTest ─────────────────────────────────────────────────────────
|
||
|
||
function parseCurrentTest(content: string): CurrentTest {
|
||
// 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.
|
||
const currentTestSection = collectSection(
|
||
content,
|
||
(h) => /^current\s+test$/i.test(h.text) && h.level === 2,
|
||
{ levelBounded: true },
|
||
);
|
||
if (!currentTestSection) {
|
||
error('UAT file is missing a Current Test section');
|
||
}
|
||
|
||
// Remove any leading HTML comment block (UAT-specific document structure)
|
||
const rawBody = currentTestSection!.body.replace(/^<!--[\s\S]*?-->\s*\n?/, '');
|
||
const section = rawBody.trimEnd();
|
||
if (!section.trim()) {
|
||
error('Current Test section is empty');
|
||
}
|
||
|
||
if (/\[testing complete\]/i.test(section)) {
|
||
return { complete: true };
|
||
}
|
||
|
||
const numberMatch = section.match(/^number:\s*(\d+)\s*$/m);
|
||
const nameMatch = section.match(/^name:\s*(.+)\s*$/m);
|
||
const expectedBlockMatch = section.match(/^expected:\s*\|\n([\s\S]*?)(?=^\w[\w-]*:\s)/m)
|
||
|| section.match(/^expected:\s*\|\n([\s\S]+)/m);
|
||
const expectedInlineMatch = section.match(/^expected:\s*(.+)\s*$/m);
|
||
|
||
if (!numberMatch || !nameMatch || (!expectedBlockMatch && !expectedInlineMatch)) {
|
||
if (!numberMatch && !nameMatch && !expectedBlockMatch && !expectedInlineMatch) {
|
||
const pendingTest = parseFirstPendingTest(content);
|
||
if (pendingTest) {
|
||
return pendingTest;
|
||
}
|
||
error('Current Test section is non-structured and no pending UAT test remains to resume');
|
||
}
|
||
error('Current Test section is malformed');
|
||
}
|
||
|
||
let expected: string;
|
||
if (expectedBlockMatch) {
|
||
expected = expectedBlockMatch[1]
|
||
.split('\n')
|
||
.map((line: string) => line.replace(/^ {2}/, ''))
|
||
.join('\n')
|
||
.trim();
|
||
} else {
|
||
expected = expectedInlineMatch![1].trim();
|
||
}
|
||
|
||
return {
|
||
complete: false,
|
||
number: parseInt(numberMatch![1], 10),
|
||
name: sanitizeForDisplay(nameMatch![1].trim()),
|
||
expected: sanitizeForDisplay(expected),
|
||
};
|
||
}
|
||
|
||
function parseFirstPendingTest(content: string): CurrentTest | null {
|
||
// Use the seam to locate the ## Tests section (ADR-1372 T5).
|
||
const testsSection = collectSection(
|
||
content,
|
||
(h) => /^tests$/i.test(h.text) && h.level === 2,
|
||
{ levelBounded: true },
|
||
);
|
||
if (!testsSection) {
|
||
return null;
|
||
}
|
||
|
||
const sectionBody = testsSection.body;
|
||
|
||
// Within the Tests section body, find ### N. Name sub-headings.
|
||
// tokenizeHeadings operates on the section body as a standalone document,
|
||
// filtering to level-3 headings matching the UAT-specific "N. Name" pattern.
|
||
// The UAT-specific item parsing (number extraction, result parsing) stays caller-side.
|
||
const subHeadings = tokenizeHeadings(sectionBody).filter(
|
||
(h) => h.level === 3 && /^\d+\.\s+/.test(h.text),
|
||
);
|
||
|
||
for (let i = 0; i < subHeadings.length; i += 1) {
|
||
const current = subHeadings[i];
|
||
const next = subHeadings[i + 1];
|
||
// Slice the block for this sub-test from the section body text
|
||
const block = next
|
||
? sectionBody.slice(current.offset, next.offset)
|
||
: sectionBody.slice(current.offset);
|
||
|
||
if (!/^result:\s*\[?pending\]?\s*$/im.test(block)) {
|
||
continue;
|
||
}
|
||
|
||
// Extract the UAT-specific number and name from the heading text
|
||
const headingParts = current.text.match(/^(\d+)\.\s+(.+)$/);
|
||
if (!headingParts) continue;
|
||
const testNumber = parseInt(headingParts[1], 10);
|
||
const testName = headingParts[2].trim();
|
||
|
||
const expected = parseExpectedFromTestBlock(block);
|
||
if (!expected) {
|
||
error(`Pending UAT test ${testNumber} is missing an expected field`);
|
||
}
|
||
|
||
return {
|
||
complete: false,
|
||
number: testNumber,
|
||
name: sanitizeForDisplay(testName),
|
||
expected: sanitizeForDisplay(expected),
|
||
};
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
function parseExpectedFromTestBlock(block: string): string | null {
|
||
const expectedBlockMatch = block.match(/^expected:\s*\|\n([\s\S]*?)(?=^\w[\w-]*:\s)/m)
|
||
|| block.match(/^expected:\s*\|\n([\s\S]+)/m);
|
||
if (expectedBlockMatch) {
|
||
return expectedBlockMatch[1]
|
||
.split('\n')
|
||
.map((line: string) => line.replace(/^ {2}/, ''))
|
||
.join('\n')
|
||
.trim();
|
||
}
|
||
|
||
const expectedInlineMatch = block.match(/^expected:\s*(.+)\s*$/m);
|
||
return expectedInlineMatch ? expectedInlineMatch[1].trim() : null;
|
||
}
|
||
|
||
// ─── buildCheckpoint ──────────────────────────────────────────────────────────
|
||
//
|
||
// Localized frame strings (#2402): the checkpoint banner + instruction line are
|
||
// the byte-for-byte block verify-work.md reprints verbatim, so the model can't
|
||
// translate it after the fact — the frame must already be in `response_language`
|
||
// when this function returns it. Bounded table with an ENGLISH FALLBACK for
|
||
// unset/unrecognized languages keeps the default path byte-identical.
|
||
|
||
interface CheckpointFrame {
|
||
banner: string;
|
||
instruction: string;
|
||
direction?: 'rtl';
|
||
}
|
||
|
||
const CHECKPOINT_BOX_WIDTH = 64; // total column width of the ╔══...╗ border, borders stay byte-identical
|
||
|
||
const CHECKPOINT_FRAMES: Record<string, CheckpointFrame> = {
|
||
english: {
|
||
banner: 'CHECKPOINT: Verification Required',
|
||
instruction: 'Type `pass` or describe what\'s wrong.',
|
||
},
|
||
spanish: {
|
||
banner: 'PUNTO DE CONTROL: Verificación requerida',
|
||
instruction: 'Escribe `pass` o describe qué está mal.',
|
||
},
|
||
french: {
|
||
banner: 'POINT DE CONTRÔLE : Vérification requise',
|
||
instruction: 'Tapez `pass` ou décrivez ce qui ne va pas.',
|
||
},
|
||
german: {
|
||
banner: 'KONTROLLPUNKT: Überprüfung erforderlich',
|
||
instruction: 'Gib `pass` ein oder beschreibe, was nicht stimmt.',
|
||
},
|
||
portuguese: {
|
||
banner: 'PONTO DE VERIFICAÇÃO: Verificação necessária',
|
||
instruction: 'Digite `pass` ou descreva o que está errado.',
|
||
},
|
||
japanese: {
|
||
banner: 'チェックポイント: 検証が必要です',
|
||
instruction: '`pass` と入力するか、問題点を説明してください。',
|
||
},
|
||
chinese: {
|
||
banner: '检查点:需要验证',
|
||
instruction: '输入 `pass` 或描述问题所在。',
|
||
},
|
||
korean: {
|
||
banner: '체크포인트: 검증 필요',
|
||
instruction: '`pass`를 입력하거나 문제를 설명하세요.',
|
||
},
|
||
italian: {
|
||
banner: 'PUNTO DI CONTROLLO: Verifica richiesta',
|
||
instruction: 'Digita `pass` o descrivi cosa non va.',
|
||
},
|
||
dutch: {
|
||
banner: 'CONTROLEPUNT: Verificatie vereist',
|
||
instruction: 'Typ `pass` of beschrijf wat er mis is.',
|
||
},
|
||
polish: {
|
||
banner: 'PUNKT KONTROLNY: Wymagana weryfikacja',
|
||
instruction: 'Wpisz `pass` lub opisz, co jest nie tak.',
|
||
},
|
||
russian: {
|
||
banner: 'КОНТРОЛЬНАЯ ТОЧКА: требуется проверка',
|
||
instruction: 'Введите `pass` или опишите, что не так.',
|
||
},
|
||
ukrainian: {
|
||
banner: 'КОНТРОЛЬНА ТОЧКА: потрібна перевірка',
|
||
instruction: 'Введіть `pass` або опишіть, що не так.',
|
||
},
|
||
turkish: {
|
||
banner: 'KONTROL NOKTASI: Doğrulama gerekli',
|
||
instruction: '`pass` yazın veya sorunu açıklayın.',
|
||
},
|
||
hindi: {
|
||
banner: 'चेकपॉइंट: सत्यापन आवश्यक',
|
||
instruction: '`pass` लिखें या बताएं कि क्या गलत है।',
|
||
},
|
||
arabic: {
|
||
banner: 'نقطة تحقق: المراجعة مطلوبة',
|
||
instruction: 'اكتب `pass` أو صف المشكلة.',
|
||
direction: 'rtl',
|
||
},
|
||
vietnamese: {
|
||
banner: 'ĐIỂM KIỂM TRA: Cần xác minh',
|
||
instruction: 'Nhập `pass` hoặc mô tả vấn đề.',
|
||
},
|
||
indonesian: {
|
||
banner: 'TITIK PEMERIKSAAN: Verifikasi diperlukan',
|
||
instruction: 'Ketik `pass` atau jelaskan apa yang salah.',
|
||
},
|
||
};
|
||
|
||
// Free-form response_language aliases → canonical CHECKPOINT_FRAMES key.
|
||
const CHECKPOINT_LANGUAGE_ALIASES: Record<string, string> = {
|
||
english: 'english', en: 'english', 'en-us': 'english', 'en-gb': 'english',
|
||
spanish: 'spanish', es: 'spanish', 'español': 'spanish', espanol: 'spanish', castellano: 'spanish',
|
||
french: 'french', fr: 'french', 'français': 'french', francais: 'french',
|
||
german: 'german', de: 'german', deutsch: 'german',
|
||
portuguese: 'portuguese', pt: 'portuguese', 'pt-br': 'portuguese', 'português': 'portuguese', portugues: 'portuguese', 'brazilian portuguese': 'portuguese',
|
||
japanese: 'japanese', ja: 'japanese', '日本語': 'japanese',
|
||
chinese: 'chinese', zh: 'chinese', 'zh-cn': 'chinese', 'zh-tw': 'chinese', mandarin: 'chinese', 'simplified chinese': 'chinese', 'traditional chinese': 'chinese', '中文': 'chinese',
|
||
korean: 'korean', ko: 'korean', '한국어': 'korean',
|
||
italian: 'italian', it: 'italian', italiano: 'italian',
|
||
dutch: 'dutch', nl: 'dutch', nederlands: 'dutch', flemish: 'dutch', vlaams: 'dutch',
|
||
polish: 'polish', pl: 'polish', polski: 'polish',
|
||
russian: 'russian', ru: 'russian', 'ru-ru': 'russian', 'русский': 'russian',
|
||
ukrainian: 'ukrainian', uk: 'ukrainian', ua: 'ukrainian', 'українська': 'ukrainian',
|
||
turkish: 'turkish', tr: 'turkish', 'türkçe': 'turkish', turkce: 'turkish',
|
||
hindi: 'hindi', hi: 'hindi', 'हिन्दी': 'hindi', 'हिंदी': 'hindi',
|
||
arabic: 'arabic', ar: 'arabic', 'العربية': 'arabic',
|
||
vietnamese: 'vietnamese', vi: 'vietnamese', 'tiếng việt': 'vietnamese', 'tieng viet': 'vietnamese',
|
||
indonesian: 'indonesian', id: 'indonesian', 'bahasa indonesia': 'indonesian',
|
||
};
|
||
|
||
function resolveCheckpointFrame(responseLanguage: string | undefined): CheckpointFrame {
|
||
if (!responseLanguage) return CHECKPOINT_FRAMES.english;
|
||
const key = CHECKPOINT_LANGUAGE_ALIASES[
|
||
responseLanguage.trim().normalize('NFC').toLowerCase()
|
||
];
|
||
return (key && CHECKPOINT_FRAMES[key]) || CHECKPOINT_FRAMES.english;
|
||
}
|
||
|
||
// Approximate terminal-cell width. East Asian Width W/F code points occupy two
|
||
// cells, while Unicode combining marks occupy no additional cell beyond their
|
||
// base character. Counting only W/F ranges is insufficient for scripts such as
|
||
// Devanagari: Hindi vowel signs and viramas are combining marks, and treating
|
||
// each as a full cell visibly shifts the checkpoint box's right border.
|
||
function isWideCodePoint(codePoint: number): boolean {
|
||
return (
|
||
(codePoint >= 0x1100 && codePoint <= 0x115f) || // Hangul Jamo
|
||
codePoint === 0x2329 || codePoint === 0x232a ||
|
||
(codePoint >= 0x2e80 && codePoint <= 0x303e) || // CJK Radicals .. CJK Symbols and Punctuation
|
||
(codePoint >= 0x3041 && codePoint <= 0x33ff) || // Hiragana .. CJK Compatibility
|
||
(codePoint >= 0x3400 && codePoint <= 0x4dbf) || // CJK Unified Ideographs Extension A
|
||
(codePoint >= 0x4e00 && codePoint <= 0x9fff) || // CJK Unified Ideographs
|
||
(codePoint >= 0xa000 && codePoint <= 0xa4cf) || // Yi Syllables
|
||
(codePoint >= 0xac00 && codePoint <= 0xd7a3) || // Hangul Syllables
|
||
(codePoint >= 0xf900 && codePoint <= 0xfaff) || // CJK Compatibility Ideographs
|
||
(codePoint >= 0xfe30 && codePoint <= 0xfe4f) || // CJK Compatibility Forms
|
||
(codePoint >= 0xff00 && codePoint <= 0xff60) || // Fullwidth Forms
|
||
(codePoint >= 0xffe0 && codePoint <= 0xffe6) ||
|
||
(codePoint >= 0x20000 && codePoint <= 0x3fffd) // CJK Unified Ideographs Extension B+ / supplementary
|
||
);
|
||
}
|
||
|
||
// Non-spacing/enclosing marks and format controls occupy zero terminal cells.
|
||
// Spacing combining marks (General_Category=Mc), such as Devanagari vowel
|
||
// signs, still advance the cursor and must contribute one column.
|
||
const ZERO_WIDTH_MARK_RE = /\p{gc=Mn}|\p{gc=Me}|\p{gc=Cf}/u;
|
||
|
||
// Iterates by Unicode code point (not UTF-16 code unit) so astral characters
|
||
// are measured once, not as two surrogate units.
|
||
function displayWidth(text: string): number {
|
||
let width = 0;
|
||
for (const ch of text) {
|
||
if (ZERO_WIDTH_MARK_RE.test(ch)) continue;
|
||
width += isWideCodePoint(ch.codePointAt(0) as number) ? 2 : 1;
|
||
}
|
||
return width;
|
||
}
|
||
|
||
// Pads `text` into a `║ text… ║` line matching CHECKPOINT_BOX_WIDTH. Content
|
||
// that overflows the box (a longer translated string) is left unpadded rather
|
||
// than truncated — a slightly ragged border beats losing text.
|
||
function checkpointBoxLine(text: string): string {
|
||
const innerWidth = CHECKPOINT_BOX_WIDTH - 2;
|
||
const content = ` ${text}`;
|
||
const padLength = innerWidth - displayWidth(content);
|
||
const padded = padLength > 0 ? content + ' '.repeat(padLength) : content;
|
||
return `║${padded}║`;
|
||
}
|
||
|
||
const RTL_ISOLATE = '\u2067';
|
||
const POP_DIRECTIONAL_ISOLATE = '\u2069';
|
||
|
||
function isolateCheckpointFrameText(text: string, frame: CheckpointFrame): string {
|
||
return frame.direction === 'rtl'
|
||
? `${RTL_ISOLATE}${text}${POP_DIRECTIONAL_ISOLATE}`
|
||
: text;
|
||
}
|
||
|
||
function buildCheckpoint(currentTest: { number: number; name: string; expected: string }, responseLanguage?: string): string {
|
||
const frame = resolveCheckpointFrame(responseLanguage);
|
||
const banner = isolateCheckpointFrameText(frame.banner, frame);
|
||
const instruction = isolateCheckpointFrameText(frame.instruction, frame);
|
||
return [
|
||
'╔══════════════════════════════════════════════════════════════╗',
|
||
checkpointBoxLine(banner),
|
||
'╚══════════════════════════════════════════════════════════════╝',
|
||
'',
|
||
`**Test ${currentTest.number}: ${currentTest.name}**`,
|
||
'',
|
||
currentTest.expected,
|
||
'',
|
||
'──────────────────────────────────────────────────────────────',
|
||
instruction,
|
||
'──────────────────────────────────────────────────────────────',
|
||
].join('\n');
|
||
}
|
||
|
||
// ─── parseUatItems ────────────────────────────────────────────────────────────
|
||
|
||
function parseUatItems(content: string): UatItem[] {
|
||
const items: UatItem[] = [];
|
||
// Match test blocks: ### N. Name\nexpected: ...\nresult: ...\n
|
||
// Accept both bare (result: pending) and bracketed (result: [pending]) formats (#2273)
|
||
const testPattern = /###\s*(\d+)\.\s*([^\n]+)\nexpected:\s*([^\n]+)\nresult:\s*\[?(\w+)\]?(?:\n(?:reported|reason|blocked_by):\s*[^\n]*)?/g;
|
||
let match: RegExpExecArray | null;
|
||
while ((match = testPattern.exec(content)) !== null) {
|
||
const [, num, name, expected, result] = match;
|
||
if (result === 'pending' || result === 'skipped' || result === 'blocked') {
|
||
// Extract optional fields — limit to current test block (up to next ### or EOF)
|
||
const afterMatch = content.slice(match.index);
|
||
const nextHeading = afterMatch.indexOf('\n###', 1);
|
||
const blockText = nextHeading > 0 ? afterMatch.slice(0, nextHeading) : afterMatch;
|
||
const reasonMatch = blockText.match(/reason:\s*(.+)/);
|
||
const blockedByMatch = blockText.match(/blocked_by:\s*(.+)/);
|
||
|
||
const item: UatItem = {
|
||
test: parseInt(num, 10),
|
||
name: name.trim(),
|
||
expected: expected.trim(),
|
||
result,
|
||
category: categorizeItem(result, reasonMatch?.[1], blockedByMatch?.[1]),
|
||
};
|
||
if (reasonMatch) item.reason = reasonMatch[1].trim();
|
||
if (blockedByMatch) item.blocked_by = blockedByMatch[1].trim();
|
||
items.push(item);
|
||
}
|
||
}
|
||
items.push(...parseGapsItems(content));
|
||
return items;
|
||
}
|
||
|
||
// ─── parseGapsItems ───────────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* Extract unresolved entries from a UAT file's `## Gaps` section (#2286).
|
||
*
|
||
* `## Gaps` records open findings as a YAML-lite bullet list (see
|
||
* `templates/UAT.md`'s `## Gaps` block: `- truth: "..."` followed by indented
|
||
* continuation lines `status:` / `reason:` / `severity:` / `test:` / etc.,
|
||
* and — for `artifacts:` / `missing:` — a further-nested `- ` sub-list).
|
||
* `parseUatItems`'s `### N.` test-block regex never looks at this section at
|
||
* all, so a UAT file whose only outstanding findings live in `## Gaps` was
|
||
* silently invisible — the false-negative this fix addresses.
|
||
*
|
||
* Reuses the existing `collectSection` seam (already used elsewhere in this
|
||
* file for `## Current Test` / `## Tests`) to locate the section. Field
|
||
* extraction is deliberately NOT done via `iterateBullets`: that seam folds
|
||
* every continuation line onto ONE space-joined `text` string per bullet,
|
||
* which erases line boundaries — a `key:` scan against that flattened text
|
||
* matches the FIRST `key:`-shaped substring anywhere, including one that
|
||
* happens to appear inside an EARLIER field's own quoted free-text value
|
||
* (e.g. `truth: "The status: resolved workflow should trigger"` — a real
|
||
* `status: failed` on the next line would never be reached, silently
|
||
* DROPPING a genuinely open gap — the exact false-negative class #2286
|
||
* exists to fix, so the fix must not reintroduce it). `splitGapsEntries` /
|
||
* `extractGapEntryFields` below instead walk the section PER LINE and only
|
||
* recognise a field at the START of its own (trimmed) line, so a `key:`
|
||
* embedded inside another field's quoted value can never be mistaken for a
|
||
* field declaration.
|
||
*
|
||
* Every entry whose `status` is present and NOT `resolved` (case-insensitive)
|
||
* is surfaced — mirroring the "ignore passing/resolved" convention already
|
||
* used for `### N.` test blocks (`result: pass` is never surfaced) and the
|
||
* VERIFICATION table-row PASS/resolved skip (`hasPassResult`, below). An
|
||
* entry with NO parseable `status:` field is surfaced too, as `result:
|
||
* 'unknown'` — #2286 is a false-NEGATIVE bug, and a `## Gaps` entry only
|
||
* exists to record an outstanding finding (a template-conformant RESOLVED
|
||
* entry always carries an explicit `status: resolved`); a garbled or
|
||
* non-conformant entry is far more likely to be an unresolved finding whose
|
||
* `status:` line failed to parse than a genuinely resolved one, so the
|
||
* fail-safe direction is to surface it rather than silently drop it.
|
||
*/
|
||
function parseGapsItems(content: string): UatItem[] {
|
||
const gapsSection = collectSection(
|
||
content,
|
||
(h) => /^gaps$/i.test(h.text) && h.level === 2,
|
||
{ levelBounded: true },
|
||
);
|
||
if (!gapsSection) return [];
|
||
|
||
const items: UatItem[] = [];
|
||
|
||
for (const entryLines of splitGapsEntries(gapsSection.body)) {
|
||
const fields = extractGapEntryFields(entryLines);
|
||
const rawStatus = fields.status;
|
||
if (rawStatus && rawStatus.toLowerCase() === 'resolved') continue;
|
||
// Fail-safe: missing/garbled status surfaces as 'unknown' rather than
|
||
// being dropped (see doc comment above).
|
||
const status = rawStatus || 'unknown';
|
||
|
||
const truth = fields.truth;
|
||
const reason = fields.reason;
|
||
const testNum = fields.test;
|
||
|
||
const item: UatItem = {
|
||
name: truth || rawGapEntryText(entryLines),
|
||
result: status,
|
||
category: categorizeItem(status, reason, undefined),
|
||
};
|
||
if (testNum && /^\d+$/.test(testNum)) item.test = parseInt(testNum, 10);
|
||
if (reason) item.reason = reason;
|
||
items.push(item);
|
||
}
|
||
|
||
// #2766: union with the table form. A `|`-leading line is never a `- ` bullet
|
||
// opener, so a section mixing bullet entries and a table surfaces both with no
|
||
// double-counting.
|
||
items.push(...parseGapsTableItems(gapsSection.body));
|
||
|
||
return items;
|
||
}
|
||
|
||
/**
|
||
* Split a section body into its GFM pipe tables, one entry per table (#2766).
|
||
*
|
||
* Shared by `parseGapsTableItems` and `parseDeferredTableItems` so the
|
||
* header/delimiter/table-boundary handling — the fiddly part — lives in exactly
|
||
* one place, and the two consumers only decide what a data row MEANS.
|
||
*
|
||
* Header detection is lookahead-free: the last data-shaped row is held in
|
||
* `pending` until the NEXT line decides its fate — a delimiter row
|
||
* (`|---|---|`) proves the held row was a header, anything else promotes it to a
|
||
* data row. So a conventional table drops exactly its header, a HEADERLESS table
|
||
* keeps every row (hand-authored planning tables often omit the delimiter), and
|
||
* a header with no data rows yields nothing. A prose or blank line ends the
|
||
* current table, so two tables separated by text are read independently and each
|
||
* drops its own header.
|
||
*
|
||
* Reuses the canonical `isDelimiterRow` shape check from markdown-table.cts
|
||
* rather than re-deriving it. Deliberately NOT routed through
|
||
* `parseMarkdownTable`, which reads only the FIRST table in a body and treats
|
||
* ragged/headerless shapes as errors (ADR-2143 §3) — correct for the mandated
|
||
* tables in STATE.md/ROADMAP.md, but the wrong contract here, where a malformed
|
||
* hand-written table must still surface its rows rather than be dropped.
|
||
*/
|
||
function collectTableRows(sectionBody: string): { header: string[] | null; rows: string[][] }[] {
|
||
const tables: { header: string[] | null; rows: string[][] }[] = [];
|
||
let current: { header: string[] | null; rows: string[][] } | null = null;
|
||
let pending: string[] | null = null;
|
||
|
||
const ensure = (): void => {
|
||
if (!current) current = { header: null, rows: [] };
|
||
};
|
||
const flushPending = (): void => {
|
||
if (pending) {
|
||
ensure();
|
||
current!.rows.push(pending);
|
||
pending = null;
|
||
}
|
||
};
|
||
const endTable = (): void => {
|
||
flushPending();
|
||
if (current) {
|
||
tables.push(current);
|
||
current = null;
|
||
}
|
||
};
|
||
|
||
for (const rawLine of sectionBody.split('\n')) {
|
||
const line = rawLine.replace(/\r$/, '').trim();
|
||
if (!line.startsWith('|')) {
|
||
endTable();
|
||
continue;
|
||
}
|
||
const cells = splitTableRow(line);
|
||
if (cells.length === 0) continue;
|
||
if (isDelimiterRow(cells)) {
|
||
ensure();
|
||
current!.header = pending; // may be null for a delimiter-first table
|
||
pending = null;
|
||
continue;
|
||
}
|
||
flushPending();
|
||
pending = cells;
|
||
}
|
||
endTable();
|
||
|
||
return tables;
|
||
}
|
||
|
||
/**
|
||
* Header-name → canonical Gaps field (#2766).
|
||
*
|
||
* Anchored on the `## Gaps` field vocabulary `templates/UAT.md` mandates for the
|
||
* YAML-lite bullet form (truth/status/reason/severity/test), plus the obvious
|
||
* synonyms a human writing the same information as a table reaches for instead.
|
||
*/
|
||
const GAPS_COLUMN_ALIASES: Record<string, 'truth' | 'status' | 'reason' | 'severity' | 'test'> = {
|
||
truth: 'truth', gap: 'truth', finding: 'truth', item: 'truth',
|
||
description: 'truth', issue: 'truth', name: 'truth',
|
||
status: 'status', result: 'status', state: 'status',
|
||
reason: 'reason', note: 'reason', notes: 'reason',
|
||
detail: 'reason', details: 'reason', evidence: 'reason',
|
||
severity: 'severity',
|
||
test: 'test', '#': 'test', 'test #': 'test', 'test number': 'test',
|
||
};
|
||
|
||
function mapGapsHeader(header: string[] | null): Record<string, number> | null {
|
||
if (!header) return null;
|
||
const columns: Record<string, number> = {};
|
||
header.forEach((cell, idx) => {
|
||
const key = GAPS_COLUMN_ALIASES[cell.trim().toLowerCase().replace(/\*+/g, '')];
|
||
if (key && !(key in columns)) columns[key] = idx;
|
||
});
|
||
return Object.keys(columns).length > 0 ? columns : null;
|
||
}
|
||
|
||
/**
|
||
* Extract gap entries from GFM pipe tables in a `## Gaps` section (#2766) — a
|
||
* UNION with the YAML-lite bullet scan in `parseGapsItems`, for the same reason
|
||
* `parseDeferredTableItems` exists: `splitGapsEntries` keys entirely on `- `
|
||
* bullet openers, so a table-shaped `## Gaps` section yielded ZERO items and
|
||
* every finding in it was silently invisible.
|
||
*
|
||
* Neither `templates/UAT.md` nor `templates/verification-report.md` documents a
|
||
* table for this section (both mandate the bullet/numbered form), so a table
|
||
* here is off-template hand-authoring — which is precisely why it must not fail
|
||
* silently. Note `parseVerificationItems` in this same file already reads table
|
||
* rows AND numbered AND bullet items as a union because the live sections mix
|
||
* shapes; the Gaps and deferred parsers never got the same treatment.
|
||
*
|
||
* When a header row is present its columns are mapped by name against the
|
||
* template's own field vocabulary (see GAPS_COLUMN_ALIASES) so a tabled gap
|
||
* carries the same status/reason/test fields as its bullet equivalent and
|
||
* `categorizeItem` classifies it identically. With no recognizable header, the
|
||
* row degrades to a joined-cells name with status `unknown` — surfaced, not
|
||
* dropped, matching this module's established fail-safe stance.
|
||
*
|
||
* Resolution follows the bullet path exactly: an entry is skipped ONLY on an
|
||
* explicit resolved marker — the mapped `status` column reading `resolved`, or,
|
||
* absent a status column, any cell reading exactly `resolved`. A gap with no
|
||
* parseable status is NEVER treated as resolved.
|
||
*/
|
||
function parseGapsTableItems(sectionBody: string): UatItem[] {
|
||
const items: UatItem[] = [];
|
||
|
||
for (const { header, rows } of collectTableRows(sectionBody)) {
|
||
const columns = mapGapsHeader(header);
|
||
for (const cells of rows) {
|
||
const at = (key: string): string =>
|
||
(columns && key in columns ? (cells[columns[key]] ?? '').trim() : '');
|
||
|
||
const rawStatus = at('status');
|
||
if (rawStatus && rawStatus.toLowerCase() === 'resolved') continue;
|
||
// No status column: fall back to an explicit resolved marker in any cell
|
||
// (the headerless-table equivalent of `status: resolved`).
|
||
if (!columns || !('status' in columns)) {
|
||
if (cells.some(c => /^resolved$/i.test(c.trim()))) continue;
|
||
}
|
||
|
||
const truth = at('truth');
|
||
const reason = at('reason');
|
||
const testNum = at('test');
|
||
const name = truth || cells.filter(c => c !== '').join(' — ');
|
||
if (!name) continue;
|
||
|
||
const status = rawStatus || 'unknown';
|
||
const item: UatItem = {
|
||
name,
|
||
result: status,
|
||
category: categorizeItem(status, reason || undefined, undefined),
|
||
};
|
||
if (testNum && /^\d+$/.test(testNum)) item.test = parseInt(testNum, 10);
|
||
if (reason) item.reason = reason;
|
||
items.push(item);
|
||
}
|
||
}
|
||
|
||
return items;
|
||
}
|
||
|
||
// ─── parseDeferredItems ────────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* Extract unresolved entries from a phase directory's `deferred-items.md`
|
||
* (#2287) — the SCOPE BOUNDARY convention `agents/gsd-executor.md` instructs
|
||
* the executor to follow: "Log out-of-scope discoveries to `deferred-items.md`
|
||
* in the phase directory". Nothing previously read this file back, so a
|
||
* deferred entry was permanently invisible outside the phase directory.
|
||
*
|
||
* The writer convention (unchanged by this fix, per the issue's stated
|
||
* out-of-scope) emits a plain bullet list, typically under a `## Deferred
|
||
* Items` heading (see the issue's own reproduction fixture), one entry per
|
||
* top-level `- ` line with optional indented continuation lines. There is no
|
||
* mandated heading text, so if no `## Deferred Items`-shaped level-2 heading
|
||
* is found, the WHOLE file is scanned as the entry list — fail-safe, so an
|
||
* agent writing a differently-headed (or headless) deferred-items.md still
|
||
* has its entries surfaced rather than silently skipped.
|
||
*
|
||
* Reuses the same per-line field/entry-splitting seams as `parseGapsItems`
|
||
* (`splitGapsEntries`, `extractGapEntryFields`, `rawGapEntryText`) — an entry
|
||
* is RESOLVED only when it carries an explicit `status: resolved` field
|
||
* (case-insensitive), mirroring the established Gaps convention so a human or
|
||
* follow-up agent can mark a deferred item done in place, keeping
|
||
* `deferred-items.md` the single source of truth (no duplicate
|
||
* `.planning/todos/pending/*.md` entry required). Every other entry —
|
||
* including one with no `status:` field at all — is UNRESOLVED and is
|
||
* surfaced.
|
||
*
|
||
* #3457: when the section body contains headings, entries are delimited by
|
||
* LEAF headings (see `splitDeferredHeadingEntries`) rather than by bullets —
|
||
* the executor convention writes one deferred item as a heading followed by
|
||
* sibling `- **Field:** …` bullets, which the bullet-only split mis-counted as
|
||
* one item PER BULLET. A body with no headings keeps the original
|
||
* one-bullet-per-item split unchanged.
|
||
*/
|
||
/**
|
||
* One `deferred-items.md` entry with its RAW (un-lowercased) `status:` field
|
||
* value (`''` when the entry carries no parseable status). #3458 follow-up:
|
||
* `parseDeferredItems` (below) is now DEFINED IN TERMS OF this — it filters
|
||
* to `status !== 'resolved'` — and `audit.cts`'s `scanDeferredItems` also
|
||
* consumes this directly so it can tell `resolved` (fixed for real, never
|
||
* counted), the newer `acknowledged` (suppressed-but-tallied, #3458
|
||
* follow-up), and everything else (open) apart WITHOUT a second,
|
||
* independent entry-boundary/field-extraction pass that could drift from
|
||
* this one.
|
||
*/
|
||
function parseDeferredItemsWithStatus(content: string): Array<{ name: string; status: string }> {
|
||
const deferredSection = collectSection(
|
||
content,
|
||
(h) => /^deferred\s+items$/i.test(h.text) && h.level === 2,
|
||
{ levelBounded: true },
|
||
);
|
||
const sectionBody = deferredSection ? deferredSection.body : content;
|
||
|
||
const items: Array<{ name: string; status: string }> = [];
|
||
|
||
// #3457: heading-delimited shape — an entry's fields live in sibling bullets
|
||
// (`- **Status:** resolved`), so the bullet marker is stripped on EVERY line
|
||
// before field extraction, not just line 0 (which `extractGapEntryFields`
|
||
// does for the headless/Gaps shape, where a later `- ` line is a nested
|
||
// sub-list, not a field).
|
||
const headingEntries = splitDeferredHeadingEntries(sectionBody);
|
||
const entries = headingEntries !== null
|
||
? headingEntries.map((entryLines) => ({
|
||
lines: entryLines,
|
||
fields: extractGapEntryFields(entryLines.map(stripLeadingBulletMarker)),
|
||
}))
|
||
: splitGapsEntries(sectionBody).map((entryLines) => ({
|
||
lines: entryLines,
|
||
fields: extractGapEntryFields(entryLines),
|
||
}));
|
||
|
||
for (const { lines: entryLines, fields } of entries) {
|
||
const text = rawGapEntryText(entryLines);
|
||
if (!text) continue;
|
||
|
||
items.push({ name: text, status: fields.status || '' });
|
||
}
|
||
|
||
// #2766: union with the table form — see parseDeferredTableItems. Executors
|
||
// write this file by hand with no mandated shape, and a GFM table is a natural
|
||
// choice for the common "test → failing seeds" case, which produced ZERO items.
|
||
// Table rows carry no independently-parseable status column in general —
|
||
// `parseDeferredTableItems` already excludes resolved/done/pass rows at its
|
||
// own layer (any cell reading exactly one of those three) — so anything it
|
||
// returns here is inherently open; `acknowledge` (#3458 follow-up) has no
|
||
// representable field to write for a table row, so those are reported with
|
||
// status `''` (never `resolved`/`acknowledged`) and remain permanently
|
||
// un-acknowledgeable via the CLI writer — a known, deliberate limitation
|
||
// (see `acknowledgeDeferredItem`'s doc comment).
|
||
items.push(...parseDeferredTableItems(sectionBody).map((item) => ({ name: item.name, status: '' })));
|
||
|
||
return items;
|
||
}
|
||
|
||
function parseDeferredItems(content: string): UatItem[] {
|
||
return parseDeferredItemsWithStatus(content)
|
||
.filter((entry) => !(entry.status && entry.status.toLowerCase() === 'resolved'))
|
||
.map((entry) => ({
|
||
name: entry.name,
|
||
result: 'unresolved',
|
||
category: 'deferred',
|
||
}));
|
||
}
|
||
|
||
// ─── acknowledgeDeferredItem ───────────────────────────────────────────────────
|
||
|
||
/** Result of `acknowledgeDeferredItem`. */
|
||
interface AcknowledgeDeferredItemResult {
|
||
content: string;
|
||
status: 'ok' | 'not_found' | 'ambiguous' | 'unsupported_heading_shape' | 'already_resolved' | 'match_verification_failed';
|
||
}
|
||
|
||
/**
|
||
* CLI-writer half of the #3458 follow-up deferred_items suppression seam.
|
||
* Sets the ONE deferred entry whose rendered text (`rawGapEntryText`, the
|
||
* same value `parseDeferredItemsWithStatus`/the audit's JSON output surface
|
||
* as `name`/`text`) exactly equals `targetText` to `status: acknowledged` —
|
||
* a NEW terminal value, distinct from the existing `resolved` (which keeps
|
||
* meaning "actually fixed"). This is the marker for this category: unlike
|
||
* every other audit category (a sibling `audit_acknowledged` frontmatter map
|
||
* that never touches the artifact's own `status:`), a deferred-items.md
|
||
* entry's `status:` field carries no OTHER meaning, so the field itself
|
||
* doubles as the marker — self-invalidating for free: edit the entry's
|
||
* `status:` away from `acknowledged` (or delete the field) and it resurfaces
|
||
* with no separate cleanup step, exactly like every other category's marker.
|
||
*
|
||
* Deliberately refuses (`unsupported_heading_shape`) rather than guess when
|
||
* the section uses the heading-delimited (#3457) entry shape: reliably
|
||
* mapping a `splitDeferredHeadingEntries` entry back to its EXACT source line
|
||
* span is not safely derivable without re-deriving that function's
|
||
* leaf/container walk against a document that may also mix in headless
|
||
* (`splitGapsEntries`-derived) entries between headings — attempting it risks
|
||
* writing into the WRONG entry. The bullet-only (headless) shape below is the
|
||
* primary, documented SCOPE BOUNDARY convention and is handled precisely.
|
||
*
|
||
* Also refuses `ambiguous` (2+ entries share the exact same text — status must
|
||
* be unique to identify one) and `not_found`, and is a no-op
|
||
* (`already_resolved`) on an entry already carrying `status: resolved` — the
|
||
* verdict-preserving direction: acknowledging a genuinely-fixed item would
|
||
* silently downgrade its terminal state.
|
||
*
|
||
* SPAN-CARRIED, not re-searched (F1, #3458 follow-up review — see
|
||
* `splitGapsEntriesWithSpans`'s doc comment): the target entry's location
|
||
* within `sectionBody` is the (start, end) character span recorded by
|
||
* `splitGapsEntriesWithSpans` in the SAME pass that produced `entryLines` /
|
||
* `targetText` above — never re-derived afterwards by searching. The
|
||
* previous implementation re-found the entry with a regex anchored on its
|
||
* own (escaped) exact text; that regex necessarily matches the FIRST
|
||
* occurrence of that text within `sectionBody`, which is not always the
|
||
* entry that was actually selected (a continuation/quoted line inside an
|
||
* EARLIER or LATER entry can carry byte-identical text) — and because the
|
||
* mis-targeted span is byte-identical to `targetText`, no downstream check
|
||
* on the WRITTEN text could ever distinguish a wrong-entry write from a
|
||
* correct one. Carrying the span removes the re-derivation step entirely:
|
||
* there is no second search to mis-target.
|
||
*
|
||
* Section-anchored (BLOCKER 1, #3458 follow-up review): the span is
|
||
* `sectionBody`-relative — the SAME string `matches`/the `ambiguous` guard
|
||
* were computed over — not `content`-relative, so an identical bullet living
|
||
* outside `## Deferred Items` (e.g. in an unrelated `# Notes` or a
|
||
* UAT/VERIFICATION body) can never steal the write. The span is translated
|
||
* into `content`-relative offsets via `deferredSection.bodyStart` (the
|
||
* section's own start offset, an invariant `collectSection` guarantees:
|
||
* `content.slice(bodyStart, bodyEnd) === body`). Before writing, the
|
||
* spanned text's own raw entry is re-derived and compared against
|
||
* `targetText` one more time — this is now a GENUINE invariant check (the
|
||
* span was computed by `splitGapsEntriesCore`'s independent offset
|
||
* bookkeeping, a different code path than the `entryLines`/`targetText`
|
||
* comparison above), not a no-op — if it does not match, the write is
|
||
* refused with `match_verification_failed` rather than risk touching the
|
||
* wrong span.
|
||
*/
|
||
function acknowledgeDeferredItem(content: string, targetText: string): AcknowledgeDeferredItemResult {
|
||
const deferredSection = collectSection(
|
||
content,
|
||
(h) => /^deferred\s+items$/i.test(h.text) && h.level === 2,
|
||
{ levelBounded: true },
|
||
);
|
||
const sectionBody = deferredSection ? deferredSection.body : content;
|
||
|
||
if (splitDeferredHeadingEntries(sectionBody) !== null) {
|
||
return { content, status: 'unsupported_heading_shape' };
|
||
}
|
||
|
||
const entries = splitGapsEntriesWithSpans(sectionBody);
|
||
const matches = entries
|
||
.map((entry) => ({ entry, text: rawGapEntryText(entry.lines) }))
|
||
.filter((e) => e.text === targetText);
|
||
|
||
if (matches.length === 0) return { content, status: 'not_found' };
|
||
if (matches.length > 1) return { content, status: 'ambiguous' };
|
||
|
||
const { entry } = matches[0];
|
||
const { lines: entryLines, start, end } = entry;
|
||
const fields = extractGapEntryFields(entryLines);
|
||
if (fields.status && fields.status.toLowerCase() === 'resolved') {
|
||
return { content, status: 'already_resolved' };
|
||
}
|
||
|
||
// Anchor to the SAME section body `matches`/the `ambiguous` guard above
|
||
// were computed over (BLOCKER 1) — never the whole `content`, which could
|
||
// contain an identical bullet elsewhere. `start`/`end` are the entry's own
|
||
// span, carried directly from `splitGapsEntriesWithSpans` — no re-search.
|
||
const sectionOffset = deferredSection ? deferredSection.bodyStart : 0;
|
||
const matchedLines = sectionBody.slice(start, end).split('\n');
|
||
|
||
// Genuine invariant re-verification (see doc comment above): the span was
|
||
// computed by a code path independent of the `entryLines`/`targetText`
|
||
// comparison that selected this entry — this catches real drift between
|
||
// the two rather than a regex trivially guaranteed to agree with itself.
|
||
const strippedForVerify = matchedLines.map((l) => l.replace(/\r$/, ''));
|
||
if (rawGapEntryText(strippedForVerify) !== targetText) {
|
||
return { content, status: 'match_verification_failed' };
|
||
}
|
||
|
||
const matchIndexInContent = sectionOffset + start;
|
||
const statusFieldRe = /^\s*(?:-\s+)?(\*+status:\*+|status:)/i;
|
||
const statusLineIdx = matchedLines.findIndex((rawLine) => statusFieldRe.test(rawLine.replace(/\r$/, '')));
|
||
|
||
// No CRLF-preservation branch here (WARNING 1, #3458 follow-up review):
|
||
// every write goes through `platformWriteSync` → `normalizeContent`, which
|
||
// for a `.md` path unconditionally runs `_normalizeMd` — whole-file
|
||
// `\r\n` → `\n`, plus blank-line normalization around headings/lists — on
|
||
// EVERY write, not just this one. That is this codebase's single,
|
||
// deliberate OS-facing I/O seam (`shell-command-projection.cts`), applied
|
||
// uniformly to every `.md` writer; carving out one exception here would
|
||
// fight it rather than follow it, for a guarantee (byte-identical CRLF on
|
||
// disk) the seam already makes impossible. A marker write on a CRLF
|
||
// `deferred-items.md` normalizes the WHOLE file to LF, same as any other
|
||
// `.md` write in this codebase — expected, not a regression to guard
|
||
// against. Where a source line still carries a trailing `\r` (read from an
|
||
// on-disk CRLF document before normalization), `String.prototype.replace`
|
||
// consumes it as part of `.*$` and the replacement text does not
|
||
// reproduce it, so it is dropped here too — consistent with the eventual
|
||
// whole-file normalization rather than duplicating it.
|
||
let newMatchedLines: string[];
|
||
if (statusLineIdx === -1) {
|
||
const bulletIndentMatch = matchedLines[0].match(/^(\s*)-\s+/);
|
||
const continuationIndent = ' '.repeat((bulletIndentMatch ? bulletIndentMatch[1].length : 0) + 2);
|
||
newMatchedLines = [
|
||
matchedLines[0],
|
||
`${continuationIndent}status: acknowledged`,
|
||
...matchedLines.slice(1),
|
||
];
|
||
} else {
|
||
const original = matchedLines[statusLineIdx];
|
||
const replaced = original.replace(
|
||
/^(\s*(?:-\s+)?)(\*+status:\*+|status:)(\s*).*$/i,
|
||
(_m, indent: string, key: string, ws: string) => `${indent}${key}${ws}acknowledged`,
|
||
);
|
||
newMatchedLines = matchedLines.slice();
|
||
newMatchedLines[statusLineIdx] = replaced;
|
||
}
|
||
|
||
const newContent = content.slice(0, matchIndexInContent) + newMatchedLines.join('\n') + content.slice(matchIndexInContent + (end - start));
|
||
return { content: newContent, status: 'ok' };
|
||
}
|
||
|
||
/**
|
||
* Strip one leading `- ` bullet marker (#3457). Heading-delimited deferred
|
||
* entries carry their fields as sibling bullets; `extractGapEntryFields` only
|
||
* de-bullets line 0 (Gaps-protective — there, a later `- ` line is a nested
|
||
* sub-list), so the deferred heading path de-bullets every line itself before
|
||
* field extraction. Non-bullet lines pass through untouched.
|
||
*/
|
||
function stripLeadingBulletMarker(line: string): string {
|
||
return line.replace(/^(\s*)-\s+/, '');
|
||
}
|
||
|
||
/**
|
||
* Split a deferred-items section body into entries delimited by LEAF headings
|
||
* (#3457). Returns `null` when the body contains no heading at all — the
|
||
* caller then falls back to `splitGapsEntries`, keeping headless
|
||
* one-bullet-per-item files byte-for-byte on the pre-#3457 path.
|
||
*
|
||
* A heading is a CONTAINER (group/provenance/title label, contributes no
|
||
* entry) iff the NEXT heading is deeper — a deeper heading lives inside its
|
||
* span. Otherwise it is a LEAF: an entry boundary. This handles all three
|
||
* corpus shapes without hardcoding a depth: flat `#` title + `##` entries
|
||
* (title's next heading is deeper → container; each `##` followed by a
|
||
* same-or-shallower heading → leaf), a `##` container with `###` entries
|
||
* (container's next heading is deeper), and mixed-depth files where a
|
||
* childless `##` entry sits alongside a `##` group with `###` children — every
|
||
* childless heading is a leaf at whatever depth it is written. The shallower
|
||
* rules the issue reports as already tried (split on every heading; shallowest
|
||
* level; deepest level) each mis-count one of these shapes.
|
||
*
|
||
* A leaf entry is [heading text, ...body lines up to the next heading] and is
|
||
* kept only when its body (minus table lines) contains at least one `- `
|
||
* bullet:
|
||
* - a prose-only or bare heading contributes nothing — "prose is not an item"
|
||
* is this parser's pre-existing contract (see the `# Notes` case);
|
||
* - a table-only body is left entirely to `parseDeferredTableItems`, which
|
||
* unions over the same section body, so the heading cannot double-count the
|
||
* table's rows.
|
||
*
|
||
* Lines before the first heading, and lines directly under a container heading
|
||
* (before its first child), are split one-bullet-per-item by the unchanged
|
||
* `splitGapsEntries` — headless parity, so loose bullets before a later
|
||
* heading group (the mixed shape) stay one item each.
|
||
*/
|
||
function splitDeferredHeadingEntries(sectionBody: string): string[][] | null {
|
||
const headings = tokenizeHeadings(sectionBody);
|
||
if (headings.length === 0) return null;
|
||
|
||
const lines = sectionBody.split('\n');
|
||
const headingByLine = new Map<number, { text: string; isContainer: boolean }>();
|
||
for (let i = 0; i < headings.length; i++) {
|
||
// Container iff the next heading is deeper (see doc comment). An empty
|
||
// heading text (`##` alone) does not itself mean container — the flag is
|
||
// carried explicitly so a bare LEAF heading still opens an entry.
|
||
const isContainer = i + 1 < headings.length && headings[i + 1].level > headings[i].level;
|
||
headingByLine.set(headings[i].line, { text: headings[i].text, isContainer });
|
||
}
|
||
|
||
const entries: string[][] = [];
|
||
let current: string[] | null = null; // accumulating a leaf heading's entry
|
||
let pending: string[] = []; // preamble / container-heading body lines
|
||
let currentHasBullet = false;
|
||
|
||
const flushCurrent = (): void => {
|
||
// Keep the leaf entry only when its body carries a bullet; the heading
|
||
// text line itself (element 0) never counts as one.
|
||
if (current !== null && currentHasBullet) entries.push(current);
|
||
current = null;
|
||
currentHasBullet = false;
|
||
};
|
||
const flushPending = (): void => {
|
||
entries.push(...splitGapsEntries(pending.join('\n')));
|
||
pending = [];
|
||
};
|
||
|
||
for (let i = 0; i < lines.length; i++) {
|
||
const lineNo = i + 1;
|
||
const heading = headingByLine.get(lineNo);
|
||
if (heading !== undefined) {
|
||
flushCurrent();
|
||
// Headless-shaped region (preamble / container-direct bullets) ends at
|
||
// ANY heading; flushing here keeps entries in document order even when
|
||
// a container's direct bullets precede its first child entry.
|
||
flushPending();
|
||
if (!heading.isContainer) {
|
||
// Leaf heading: open an entry with the heading text as line 0.
|
||
current = [heading.text];
|
||
currentHasBullet = false;
|
||
}
|
||
continue;
|
||
}
|
||
// Table lines belong to parseDeferredTableItems, never to a heading entry.
|
||
if (/^\s*\|/.test(lines[i].replace(/\r$/, ''))) continue;
|
||
if (current !== null) {
|
||
current.push(lines[i]);
|
||
if (/^\s*-\s/.test(lines[i].replace(/\r$/, ''))) currentHasBullet = true;
|
||
} else {
|
||
pending.push(lines[i]);
|
||
}
|
||
}
|
||
flushCurrent();
|
||
flushPending();
|
||
|
||
return entries;
|
||
}
|
||
|
||
/**
|
||
* Extract deferred entries from GFM pipe tables in a deferred-items.md body
|
||
* (#2766) — a UNION with the bullet scan in `parseDeferredItems`.
|
||
*
|
||
* Cells are joined with ` — ` rather than taking only the first: these tables
|
||
* carry the useful detail in the later columns (the failing seeds, the reason,
|
||
* the owner), and dropping them would surface a name with no context.
|
||
*
|
||
* A row is skipped when any cell reads exactly `resolved`/`done`/`pass`
|
||
* (case-insensitive), mirroring the "explicit resolution only" convention
|
||
* `parseGapsItems` uses for `status: resolved` and `parseVerificationItems` uses
|
||
* for its `hasPassResult` cell scan — so a human can close a tabled deferred
|
||
* item in place and keep deferred-items.md the single source of truth.
|
||
*
|
||
* Deliberately permissive: an unrelated table in a deferred-items.md (say a
|
||
* table of environment notes) will surface as deferred entries. That is the
|
||
* correct fail-safe direction for a false-NEGATIVE bug — the whole file exists to
|
||
* record outstanding work, and this module's established stance (see
|
||
* parseGapsItems' 'unknown'-status fallback) is to surface a questionable entry
|
||
* rather than silently drop a real one.
|
||
*/
|
||
function parseDeferredTableItems(sectionBody: string): UatItem[] {
|
||
const items: UatItem[] = [];
|
||
|
||
for (const { rows } of collectTableRows(sectionBody)) {
|
||
for (const cells of rows) {
|
||
if (cells.some(c => /^(resolved|done|pass)$/i.test(c))) continue;
|
||
const name = cells.filter(c => c !== '').join(' — ');
|
||
if (!name) continue;
|
||
items.push({
|
||
name,
|
||
result: 'unresolved',
|
||
category: 'deferred',
|
||
});
|
||
}
|
||
}
|
||
|
||
return items;
|
||
}
|
||
|
||
/**
|
||
* One `splitGapsEntries` entry together with the exact character SPAN it
|
||
* occupies within the `sectionBody` it was derived from —
|
||
* `sectionBody.slice(start, end)` is the entry's own original text,
|
||
* byte-for-byte (CRLF preserved, unlike `lines`, which strips a trailing
|
||
* `\r` off every line). See `splitGapsEntriesWithSpans`'s doc comment for why
|
||
* a caller would want this over the plain `lines` shape.
|
||
*/
|
||
interface GapsEntrySpan {
|
||
lines: string[];
|
||
start: number;
|
||
end: number;
|
||
}
|
||
|
||
/**
|
||
* Shared walk behind `splitGapsEntries` and `splitGapsEntriesWithSpans` — ONE
|
||
* pass over `sectionBody` that both groups its lines into entries (see
|
||
* `splitGapsEntries`'s doc comment for the grouping rule) AND records each
|
||
* entry's (start, end) character offset within `sectionBody`. Extracted so
|
||
* the two public shapes can never drift apart on what counts as an entry
|
||
* boundary — a second, independently-written grouping pass is exactly how a
|
||
* span-carrying sibling could disagree with the plain-lines version it is
|
||
* supposed to be span-annotating.
|
||
*/
|
||
function splitGapsEntriesCore(sectionBody: string): GapsEntrySpan[] {
|
||
const rawLines = sectionBody.split('\n');
|
||
const lineStarts: number[] = [];
|
||
const lineEnds: number[] = [];
|
||
let cursor = 0;
|
||
for (const rawLine of rawLines) {
|
||
lineStarts.push(cursor);
|
||
cursor += rawLine.length;
|
||
lineEnds.push(cursor);
|
||
cursor += 1; // the '\n' separator — absent after the final line, but nothing reads past it
|
||
}
|
||
|
||
const entries: GapsEntrySpan[] = [];
|
||
let current: string[] | null = null;
|
||
let currentStartLine = -1;
|
||
let currentEndLine = -1;
|
||
let baseIndent: number | null = null;
|
||
|
||
const flush = (): void => {
|
||
if (current !== null) {
|
||
entries.push({ lines: current, start: lineStarts[currentStartLine], end: lineEnds[currentEndLine] });
|
||
}
|
||
};
|
||
|
||
rawLines.forEach((rawLine, idx) => {
|
||
const line = rawLine.replace(/\r$/, '');
|
||
const bulletMatch = line.match(/^(\s*)-\s/);
|
||
if (bulletMatch) {
|
||
const indent = bulletMatch[1].length;
|
||
if (baseIndent === null) baseIndent = indent;
|
||
if (indent <= baseIndent) {
|
||
flush();
|
||
current = [line];
|
||
currentStartLine = idx;
|
||
currentEndLine = idx;
|
||
return;
|
||
}
|
||
}
|
||
if (current !== null) {
|
||
current.push(line);
|
||
currentEndLine = idx;
|
||
}
|
||
// else: pre-first-bullet content (e.g. the template's HTML comment) — discarded.
|
||
});
|
||
flush();
|
||
|
||
return entries;
|
||
}
|
||
|
||
/**
|
||
* Split a `## Gaps` section body into per-entry line groups on TOP-LEVEL
|
||
* `- ` bullet openers.
|
||
*
|
||
* The indentation of the FIRST bullet line encountered establishes the
|
||
* "top-level" indent for the whole section; any subsequent `- `-opening line
|
||
* at that same indent (or shallower) starts a NEW entry, while everything
|
||
* more deeply indented — field continuation lines (` status: ...`) AND
|
||
* nested sub-lists (` - src/foo.ts` under ` artifacts:`) — is folded into
|
||
* the CURRENT entry. This keeps a `artifacts:`/`missing:` sub-list's `- `
|
||
* items from being mis-split into spurious standalone entries (#2286 review
|
||
* LOW finding).
|
||
*
|
||
* Lines before the first bullet (e.g. the `<!-- YAML format ... -->` comment
|
||
* the template emits) are discarded. An empty/whitespace-only section body
|
||
* (heading present, no bullets) returns `[]`.
|
||
*/
|
||
function splitGapsEntries(sectionBody: string): string[][] {
|
||
return splitGapsEntriesCore(sectionBody).map((entry) => entry.lines);
|
||
}
|
||
|
||
/**
|
||
* Sibling of `splitGapsEntries` (F1, #3458 follow-up review) that ADDITIVELY
|
||
* carries each entry's character span — every existing `splitGapsEntries`
|
||
* caller (`parseGapsItems`, `parseDeferredItemsWithStatus`,
|
||
* `splitDeferredHeadingEntries`'s `flushPending`) is unaffected and keeps
|
||
* using the plain `lines`-only shape. `acknowledgeDeferredItem` is the one
|
||
* caller that needs a span: it used to select an entry via `splitGapsEntries`
|
||
* and then RE-FIND that entry's location with a fresh regex search over
|
||
* `sectionBody` — matching the FIRST occurrence of the entry's exact text,
|
||
* not necessarily the entry actually selected (a continuation/quoted line
|
||
* inside a DIFFERENT entry can carry byte-identical text). Because the
|
||
* mis-targeted span is byte-identical to the target text, no check on the
|
||
* WRITTEN result could ever tell a wrong-entry write apart from a correct
|
||
* one. Carrying the span out of THIS same pass — the one that already knows
|
||
* exactly where the entry lives — removes the re-derivation step entirely.
|
||
*/
|
||
function splitGapsEntriesWithSpans(sectionBody: string): GapsEntrySpan[] {
|
||
return splitGapsEntriesCore(sectionBody);
|
||
}
|
||
|
||
/**
|
||
* Extract `key: value` fields from one Gaps entry's lines, anchored to the
|
||
* START of each (bullet-marker-stripped, trimmed) line — never scanning the
|
||
* REST of a line, so a colon-bearing phrase inside a quoted `truth`/`reason`
|
||
* value is never misread as a field declaration (see `parseGapsItems`'s doc
|
||
* comment for the false-negative this specifically guards against).
|
||
*
|
||
* Recognises a double-quoted value (`truth: "..."`, stripped of its wrapping
|
||
* quotes — the value may itself contain any character, including `:`) or a
|
||
* bare value (`status: open`, `test: 2`, `artifacts: []`) taken verbatim.
|
||
* The FIRST occurrence of a given key wins (top-level fields always precede
|
||
* any nested sub-list content in the template's field ordering); later
|
||
* `key:`-shaped nested-list content is captured, if it parses as one, but
|
||
* never overrides an already-seen top-level field.
|
||
*
|
||
* #3457: markdown emphasis around the KEY (`**Status:** resolved` — the
|
||
* deferred-items convention bolds every field, and a bolded resolution marker
|
||
* previously failed this regex outright and surfaced as its own bogus
|
||
* unresolved entry) is unwrapped before the match, still anchored at the
|
||
* start of the line. The unwrapped key is lower-cased, because the bolded
|
||
* convention form is Title-cased (`**Status:**`) while the field vocabulary
|
||
* this module reads is lowercase (`status`) — the same normalization
|
||
* `mapGapsHeader` already applies to table header cells. Bare (unbolded) keys
|
||
* keep their literal case, and mid-line emphasis is untouched, preserving the
|
||
* start-anchored decoy invariant above.
|
||
*/
|
||
function extractGapEntryFields(entryLines: string[]): Record<string, string> {
|
||
const fields: Record<string, string> = {};
|
||
const fieldLineRe = /^([A-Za-z_][A-Za-z0-9_-]*):\s*(.*)$/;
|
||
const boldedKeyRe = /^\*+([A-Za-z_][A-Za-z0-9_-]*):\*+/;
|
||
|
||
entryLines.forEach((rawLine, idx) => {
|
||
const line = rawLine.replace(/\r$/, '');
|
||
// Strip ONLY the entry-opening bullet marker (idx 0); a bullet marker on
|
||
// a later line belongs to a nested sub-list and is handled by
|
||
// `splitGapsEntries` already folding it in — it is not itself a field
|
||
// line unless it independently matches `key: value` after stripping.
|
||
const bulletStripped = line.match(/^(\s*)-\s+(.*)$/);
|
||
const content = (idx === 0 && bulletStripped ? bulletStripped[2] : line.trim())
|
||
.replace(boldedKeyRe, (_m, key: string) => `${key.toLowerCase()}:`);
|
||
|
||
const m = fieldLineRe.exec(content);
|
||
if (!m) return;
|
||
const key = m[1];
|
||
let value = m[2].trim();
|
||
if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) {
|
||
value = value.slice(1, -1);
|
||
}
|
||
if (!(key in fields)) fields[key] = value;
|
||
});
|
||
|
||
return fields;
|
||
}
|
||
|
||
/** Fallback display text for a Gaps entry with no parseable `truth:` field. */
|
||
function rawGapEntryText(entryLines: string[]): string {
|
||
return entryLines
|
||
.map((l, i) => (i === 0 ? l.replace(/^(\s*)-\s+/, '') : l.trim()))
|
||
.join(' ')
|
||
.trim();
|
||
}
|
||
|
||
// ─── parseVerificationItems ───────────────────────────────────────────────────
|
||
|
||
function parseVerificationItems(content: string, status: string, sourcePath?: string): UatItem[] {
|
||
const items: UatItem[] = [];
|
||
if (status === 'human_needed') {
|
||
// #2286: the frontmatter's structured `human_verification:` YAML array
|
||
// (extractFrontmatter) is the PRIMARY source of truth when present and
|
||
// non-empty — it fully bypasses the body-shape scan below, so a file
|
||
// whose frontmatter declares the array doesn't require any particular
|
||
// `## Human Verification` body shape at all. An absent or empty array
|
||
// (length 0) falls back to the body scan unchanged.
|
||
const frontmatter = extractFrontmatter(content, sourcePath);
|
||
const humanVerification = frontmatter.human_verification;
|
||
if (Array.isArray(humanVerification) && humanVerification.length > 0) {
|
||
humanVerification.forEach((entry, idx) => {
|
||
items.push({
|
||
test: idx + 1,
|
||
name: normalizeHumanVerificationEntry(entry),
|
||
result: 'human_needed',
|
||
category: 'human_uat',
|
||
});
|
||
});
|
||
return items;
|
||
}
|
||
|
||
// Use the seam to locate the ## Human Verification section (ADR-1372 T5).
|
||
const hvSection = collectSection(
|
||
content,
|
||
(h) => /^human\s+verification/i.test(h.text) && h.level === 2,
|
||
{ levelBounded: true },
|
||
);
|
||
if (hvSection) {
|
||
// #2245 review Fix 3: reverted to the pre-Phase-4 (HEAD 2cbf18642)
|
||
// implementation. The live Human Verification section is NOT a strict
|
||
// GFM table — the planner/verifier templates mix table rows, numbered
|
||
// items, and bullet items in the same section (and a `### N.` heading
|
||
// format is common too), so a table-XOR-list read (parse a table, and
|
||
// if it parses, suppress numbered/bullet items entirely) silently
|
||
// dropped items on any mixed or malformed section: a malformed
|
||
// `| N | … |` table with no valid header/delimiter yielded ZERO items
|
||
// instead of reading the rows positionally. This per-line scan reads
|
||
// table rows AND numbered items AND bullet items as a UNION (whichever
|
||
// pattern a given line matches), exactly like OLD, and reads
|
||
// `| N | desc |` rows even without a valid table header/delimiter.
|
||
//
|
||
// #2245 audit: the table-row branch's CELL SPLIT is name/position-
|
||
// addressed via `splitTableRow` (escape-aware, canonical) instead of a
|
||
// hand-rolled pipe regex — candidacy itself is decided WITHOUT a table
|
||
// regex (a leading `|` plus a purely-numeric first cell), so this no
|
||
// longer needs an allow-adhoc-markdown suppression at all.
|
||
const lines = hvSection.body.split('\n');
|
||
for (const line of lines) {
|
||
const trimmedLine = line.trim();
|
||
// Match table rows: | N | description | ... — candidacy requires a
|
||
// leading pipe and a purely-numeric first cell (mirrors what the old
|
||
// regex effectively required: a "|digit|" cell immediately followed
|
||
// by more content), with at least 2 physical cells so a bare "| N |"
|
||
// with nothing after it is NOT treated as a row.
|
||
//
|
||
// #2245 review Fix 9: this is NOT the same as OLD for a row whose
|
||
// ONLY content past the digit cell is trailing whitespace (e.g.
|
||
// "| N | ", no second delimiting `|`). OLD's `([^|]+)` regex ran
|
||
// against the RAW (untrimmed) line and its `\s*` would backtrack to
|
||
// let `[^|]+` swallow that trailing whitespace, so OLD matched and
|
||
// pushed an item with an EMPTY (`.trim()`-collapsed) name. Here,
|
||
// `trimmedLine = line.trim()` strips that trailing whitespace BEFORE
|
||
// `splitTableRow` ever sees it, collapsing the line to a single cell
|
||
// (`candidateCells.length === 1`), which fails the `>= 2` check —
|
||
// the item is silently dropped instead. A real, acceptable behaviour
|
||
// change (an empty-named UAT item is not useful either way), but the
|
||
// two implementations are NOT equivalent on this input.
|
||
let tableCells: string[] | null = null;
|
||
if (trimmedLine.startsWith('|')) {
|
||
const candidateCells = splitTableRow(trimmedLine);
|
||
if (candidateCells.length >= 2 && /^\d+$/.test(candidateCells[0])) {
|
||
tableCells = candidateCells;
|
||
}
|
||
}
|
||
// Match bullet items: - description
|
||
const bulletMatch = line.match(/^[-*]\s+(.+)/);
|
||
// Match numbered items: 1. description
|
||
const numberedMatch = line.match(/^(\d+)\.\s+(.+)/);
|
||
|
||
if (tableCells) {
|
||
// Skip rows that already have a passing result (PASS, pass, resolved, etc.)
|
||
// — checked over every cell AFTER the description column, mirroring
|
||
// OLD's rowRemainder scan (which only ever saw cells past the
|
||
// description, the description itself having already been consumed).
|
||
const hasPassResult = tableCells.slice(2).some(c => /^pass$/i.test(c) || /^resolved$/i.test(c));
|
||
if (hasPassResult) continue;
|
||
items.push({
|
||
test: parseInt(tableCells[0], 10),
|
||
name: tableCells[1] ?? '',
|
||
result: 'human_needed',
|
||
category: 'human_uat',
|
||
});
|
||
} else if (numberedMatch) {
|
||
items.push({
|
||
test: parseInt(numberedMatch[1], 10),
|
||
name: numberedMatch[2].trim(),
|
||
result: 'human_needed',
|
||
category: 'human_uat',
|
||
});
|
||
} else if (bulletMatch && bulletMatch[1].length > 10) {
|
||
items.push({
|
||
name: bulletMatch[1].trim(),
|
||
result: 'human_needed',
|
||
category: 'human_uat',
|
||
});
|
||
}
|
||
}
|
||
|
||
// #2286: fall back to the `### N. <label>` heading + bold-led paragraph
|
||
// shape (the canonical form emitted by `templates/verification-report.md`
|
||
// — `### 1. {Test Name}` followed by `**Test:** ... **Expected:** ...
|
||
// **Why human:** ...`), which the table/bullet/numbered per-line scan
|
||
// above never recognises (a `###`-prefixed line matches none of those
|
||
// three patterns). Uses the same `tokenizeHeadings` seam
|
||
// `parseFirstPendingTest` already uses for `### N.` sub-headings,
|
||
// applied here to the Human Verification section body. Runs in
|
||
// addition to (a union with) the scan above — the two shapes don't
|
||
// collide, so this only adds items a `###` heading page would have
|
||
// silently produced zero for.
|
||
const hvSubHeadings = tokenizeHeadings(hvSection.body).filter(
|
||
(h) => h.level === 3 && /^\d+\.\s+/.test(h.text),
|
||
);
|
||
for (let i = 0; i < hvSubHeadings.length; i += 1) {
|
||
const current = hvSubHeadings[i];
|
||
const next = hvSubHeadings[i + 1];
|
||
const block = next
|
||
? hvSection.body.slice(current.offset, next.offset)
|
||
: hvSection.body.slice(current.offset);
|
||
const bodyAfterHeading = block.slice(block.indexOf('\n') + 1);
|
||
// Require a bold-led paragraph body (`**Test:** ...`) to distinguish
|
||
// a genuine verification item from an unrelated numbered heading.
|
||
if (!/^\s*\*\*/.test(bodyAfterHeading)) continue;
|
||
|
||
const headingParts = current.text.match(/^(\d+)\.\s+(.+)$/);
|
||
if (!headingParts) continue;
|
||
items.push({
|
||
test: parseInt(headingParts[1], 10),
|
||
name: headingParts[2].trim(),
|
||
result: 'human_needed',
|
||
category: 'human_uat',
|
||
});
|
||
}
|
||
}
|
||
}
|
||
// gaps_found items are already handled by plan-phase --gaps pipeline
|
||
return items;
|
||
}
|
||
|
||
/**
|
||
* Normalize a single `human_verification:` frontmatter array entry (#2286)
|
||
* into a display-ready name.
|
||
*
|
||
* #2286 review (LOW finding): `extractFrontmatter`'s generic array-item
|
||
* parser (`src/frontmatter.cts`, the `line.trim().startsWith('- ')` branch)
|
||
* has NO notion of nested key/value objects — regardless of whether the
|
||
* source YAML was authored as `- test: "..."` (an implied-but-unsupported
|
||
* shorthand) or `- "plain string"`, it ALWAYS pushes the raw post-`- ` text
|
||
* (with only a single layer of wrapping quotes stripped) as a plain string.
|
||
* There is therefore no reliable signal here to distinguish a genuine
|
||
* `key: value`-shaped pseudo-field from a legitimate plain string that
|
||
* itself happens to start with a word and a colon (e.g. `"Confirm: the
|
||
* button responds"`). A prior version of this function stripped a leading
|
||
* `word:` prefix on the assumption it was always a flattened nested-object
|
||
* key — that assumption is false, and it silently truncated real plain-string
|
||
* content. No such stripping is applied: any residual wrapping-quote noise
|
||
* left by `extractFrontmatter`'s own (anchor-only) quote handling is cleaned
|
||
* up, and everything else is preserved verbatim.
|
||
*/
|
||
function normalizeHumanVerificationEntry(raw: unknown): string {
|
||
if (typeof raw !== 'string') {
|
||
return raw === null || raw === undefined ? '' : JSON.stringify(raw);
|
||
}
|
||
const s = raw.trim().replace(/^["']+|["']+$/g, '').trim();
|
||
return s || raw.trim();
|
||
}
|
||
|
||
// ─── categorizeItem ───────────────────────────────────────────────────────────
|
||
|
||
function categorizeItem(result: string, reason?: string, blockedBy?: string): UatCategory {
|
||
if (result === 'blocked' || blockedBy) {
|
||
if (blockedBy) {
|
||
if (/server/i.test(blockedBy)) return 'server_blocked';
|
||
if (/device|physical/i.test(blockedBy)) return 'device_needed';
|
||
if (/build|release|preview/i.test(blockedBy)) return 'build_needed';
|
||
if (/third.party|twilio|stripe/i.test(blockedBy)) return 'third_party';
|
||
}
|
||
return 'blocked';
|
||
}
|
||
if (result === 'skipped') {
|
||
if (reason) {
|
||
if (/server|not running|not available/i.test(reason)) return 'server_blocked';
|
||
if (/simulator|physical|device/i.test(reason)) return 'device_needed';
|
||
if (/build|release|preview/i.test(reason)) return 'build_needed';
|
||
}
|
||
return 'skipped_unresolved';
|
||
}
|
||
if (result === 'pending') return 'pending';
|
||
if (result === 'human_needed') return 'human_uat';
|
||
return 'unknown';
|
||
}
|
||
|
||
export = {
|
||
cmdAuditUat,
|
||
cmdRenderCheckpoint,
|
||
parseCurrentTest,
|
||
buildCheckpoint,
|
||
CHECKPOINT_FRAMES,
|
||
CHECKPOINT_LANGUAGE_ALIASES,
|
||
resolveCheckpointFrame,
|
||
checkpointBoxLine,
|
||
parseDeferredItems,
|
||
parseDeferredItemsWithStatus,
|
||
acknowledgeDeferredItem,
|
||
};
|