* fix(#1882): distinguish unterminated frontmatter from absent frontmatter
extractFrontmatter returned {} both for a document with no frontmatter and for
one whose fence was opened and never closed, so a file truncated mid-write was
byte-identical to a legitimate no-metadata file. Verified live through
`gsd-tools frontmatter get`: both printed {} with exit 0 and nothing on stderr.
Per ADR-1411's "corrupt is not absent" amendment the {} return is preserved
exactly -- no caller may break -- and the cause is surfaced out-of-band as a
deduplicated, unconditional stderr diagnostic. That mechanism lands as a shared
leaf module rather than a per-site copy because three sibling findings in the
same epic need it identically; four hand-rolled copies of one behaviour is the
generative-fix-divergence defect class.
The discriminator is deliberately not "opened but never closed". A Markdown
document whose first line is a thematic break takes that exact branch, so
flagging on the missing fence alone reports corruption on good Markdown -- the
failure mode this class of check has shipped with before. The unterminated
region is instead run through extractFrontmatter's own parser (extracted as
parseYamlRegion so the probe and the real parse can never diverge) and reported
only when it yields at least one key.
Also folds an inline defect found while working: src/config-loader.cts carried
two NUL bytes in the JSDoc added by this epic's Phase 1 (3eb1cede2), making it
the only non-text file under src. file(1) reported it as data and text tools
silently skipped it, defeating the audit rule that says to search the authored
source; tsc passed because the bytes sat inside a comment, so no gate caught it.
It is live on next.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* test(#1882): pin unterminated-frontmatter detection and its negative space
Covers the discriminator on both sides. The positive rows are the issue's own
repro (LF and CRLF) plus the key-count boundary 0/1/2 around the ">= 1 parsed
key" threshold. The negative rows are the documents that reach the same branch
and must stay silent -- above all a Markdown thematic break at byte 0, which is
how this class of check has previously shipped a false positive on valid
Markdown.
Deduplication is tested on both halves of the composite key: a repeat of the
same (path, cause) is suppressed, a genuine second failure in a different file
is not, and a Windows and POSIX spelling of one path resolve to a single key.
The reset seam is asserted to actually clear -- #2674 is the precedent where a
reset that silently failed to clear made every later dedup assertion a vacuous
pass, and the cases only passed because each happened to pick an unused key, so
every case here uses a path unique to itself.
Assertions are on typed surfaces throughout -- the frozen reason enum and the
dedup-set size -- never on diagnostic prose. The one CLI-level case asserts a
differential between two runs (whether stderr is empty) rather than matching a
message, and is the wired user-reachable surface for this fix. Stream failure is
injected by overriding process.stderr.write and restoring it, never chmod 0o000,
which root bypasses.
Two properties guard the ~50 call sites of the changed function: the new
optional path argument is inert with respect to the parsed value, and LF/CRLF
spellings of a document still parse identically.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(#1882): raise the truncation threshold and repair the dedup key
Isolated adversarial review found the one-key discriminator false-positives on
ordinary Markdown: a thematic break above a single labelled line -- `Note:`,
`Author:`, `TODO:`, `See:` -- parses as exactly one key and was reported as
corruption, which is the precise failure the design claimed to prevent and the
changeset promised was fixed. The threshold is now two keys. A file truncated
after exactly one key becomes a false negative; that is the same
precision-over-recall direction already taken at zero keys, and every GSD
artefact this guards carries two or more frontmatter keys.
Three dedup-key defects, each of which could silently swallow a real diagnostic:
- Backslash normalization is removed. A backslash is a legal filename character
on Linux and macOS, so folding it to a forward slash made two genuinely
different files share one key. Two spellings of one Windows path may now
report twice; two distinct files can never silence each other. Lost signal is
the worse failure.
- The key namespaces are tagged so a file literally named like the unnamed
digest fallback can no longer collide with a path-less caller whose content
hashes to that digest -- computable for any predictable content, no brute
force needed.
- The source identity is computed once rather than hashed twice per emission.
Corrects the previous commit. The two NUL bytes in src/config-loader.cts were
NOT in a JSDoc comment as that message claimed; they were deliberate separators
in the live dedup key, and stripping them degraded it to bare concatenation.
They are restored as escape sequences -- byte-identical runtime string, and the
file is text again so grep can see it. The diagnostic script that misled me
indexed a character-offset string with a byte offset.
Also threads sourcePath through the STATE.md and PLAN.md readers so the two
artefacts epic #1879 is actually about name their file rather than reporting
under a content digest.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* test(#1882): correct fixtures and assertions left behind by the review fixes
The previous commit changed two behaviours deliberately and the suite still
encoded the old ones, so gsd-test came back red with six failures across both
lanes -- all of them mine.
Fixtures carrying a single frontmatter key no longer clear the two-key
truncation threshold, so the CLI differential and the two path-less dedup cases
were asserting a diagnostic that is now correctly withheld. They now carry two
keys, which is what a real interrupted write of a GSD artefact looks like.
The Windows/POSIX case asserted that two spellings of one path collapse to a
single key -- the exact folding that was removed because it also collapsed
genuinely distinct POSIX files whose names contain a backslash. Inverted to
assert they now report separately, with the reasoning recorded inline so the
trade is not silently reversed later: mild duplicate noise on one Windows path
is acceptable, a swallowed diagnostic is not.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(#1882): name the file at every read site, and report each file once
The diagnostic reached only the four frontmatter CLI verbs, so ~47 of 53 call
sites reported a truncated file under an anonymous content digest instead of
naming it. Since naming the file is the whole point -- it is what an operator
can act on -- that was a gap in the deliverable, not a scoping choice. 43 of 53
sites now pass the resolved path.
Closing it surfaced a defect the original design missed. A single truncated
STATE.md is parsed twice in a normal run: once by the read wrapper, which holds
the path, and again by a pure core downstream, which is handed only the string
and cannot know it. Those two parses keyed separately, so one file produced two
diagnostics -- and wiring more sites made the collision more likely, not less.
Every emission now registers both identities the input could be known by and
checks both before writing, so whichever caller arrives first speaks and the
other is suppressed. Distinct files with distinct content still report
separately, which is the property ADR-1411 actually requires; two files whose
truncated content is byte-identical collapse to one report, which stays the
documented limit.
Ten call sites deliberately keep no path. Two are frontmatter's own round-trip
checks during set and merge, where passing a path would report on every write.
The other eight are the state-transition pure cores, which ADR-1769 defines as
(content, intent, deps) -> newContent with injected I/O; threading a path
through them would contradict that recorded decision, so it is surfaced rather
than taken unilaterally. With the widened key they no longer double-report, and
in the normal flow the named parse runs first, so the file is still named.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(#1882): inject the STATE.md path into the transition cores
The six state-transition cores parsed STATE.md frontmatter without knowing
which file it came from, so a truncated STATE.md reached the operator as an
anonymous content digest on exactly the artefact epic #1879 is named for.
ADR-1769 section 3 shapes these as (content, intent, deps) -> newContent with
injected deps, and deps is the seam for precisely this: something the core
cannot derive without doing I/O. It already carries roadmapProvider and a
phase-inventory provider on that basis, each documented as injected rather than
imported so the core stays pure and testable without disk access. A resolved
path is data, not I/O, so an optional sourcePath member extends the established
pattern rather than contradicting it, and every existing stub keeps compiling
because the member is optional.
updateCore and reconcileCurrentPosition take no deps and are left alone. With
the widened dedup key they cannot double-report, and in the normal flow the read
wrapper has already named the file by the time they run.
Also regenerates gsd-core/bin/lib/state-transition.cjs. That artifact is tracked
rather than gitignored, unlike most of its siblings, so leaving it stale would
have shipped a runtime without this change to anyone reading the repo without
building. tsc had skipped the re-emit because its incremental build info still
recorded an emit that had since been reverted, so the stale output survived a
clean build; clearing tsconfig.build.tsbuildinfo forced it. The
compiled-artifact-sync gate is what surfaced the drift and now reports all nine
tracked artifacts matching their source.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(#1882): stop the widened dedup key from hiding a second file
The previous commit widened the dedup guard so one file parsed twice -- once by
a read wrapper holding the path, once by a pure core holding only the string --
reported once instead of twice. It did that by checking BOTH keys before
emitting, which silently traded one defect for a worse one: two DIFFERENT files
whose truncated content happened to be byte-identical now collided on the shared
content digest, and the second file's diagnostic was swallowed. That is the
over-coarse keying ADR-1411 explicitly forbids, reintroduced while fixing
something else.
The guard now checks only the key matching what the caller actually knows -- a
named read checks its path key, a path-less read checks its digest key -- while
still recording every key the input could later be identified by. The redundant
path-less re-parse of an already-named file stays silent, and two distinct files
always both report.
Verified across all six orderings: same file named-then-anonymous reports once;
two different files with identical content report twice; two different files
with different content report twice; the same path twice reports once; two
path-less parses of identical content report once; two path-less parses of
different content report twice.
The suite caught this -- twenty failures, all in the unusable-input tests that
reuse one truncated fixture across different paths. The local probe written
alongside the broken change did not, because it compared two files with
different content and could therefore only confirm the expected behaviour.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* test(#1882): count diagnostics emitted, not identities interned
The suite measured the size of the dedup set as a stand-in for "how many
diagnostics were emitted". That held only while one emission recorded exactly
one key. Once an emission began recording every identity the input could later
be matched by -- a path key and a content key for the same file -- the set grew
by two per write and twenty assertions read 2 where they expected 1.
The production behaviour was correct throughout; the proxy was not. Set size
counts identities, which is an implementation detail of the guard. The
behavioural claim these tests exist to make is how many diagnostics an operator
actually saw, so the module now exposes that directly as an emission counter and
the suite asserts on it. The set-size accessor stays for assertions genuinely
about key shape.
The local probe written alongside the change did not catch this because it
counted process.stderr.write calls -- the right thing -- while the suite counted
set growth. Verification now asserts both and requires them to agree, so a
future divergence between the counter and real writes fails immediately rather
than being discovered a bench run later.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* test(#1882): retire two assertions that outlived the behaviour they described
Both tests encoded assumptions the dedup fix invalidated, and both were caught
by the suite rather than by the probe written alongside the change.
The forged-path case asserted that a file named like the anonymous digest
fallback must not suppress a later path-less report. That premise is gone: an
emission now records every identity its input could be matched by, so ANY named
report of some content silences the anonymous re-parse of that same content --
which is the same-file guard working as intended, and has nothing to do with the
crafted name. The property still worth defending is that a crafted filename can
never silence a real file reported under its own path, so that is what the test
now asserts, with the deliberate suppression documented beside it.
The reset-seam case ended by reading the size of the dedup set and expecting 1.
Set size counts interned identities, not diagnostics written, and one emission
now interns two. It asserts the emission counter for the event and keeps a
weaker set-size check for the interning.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(#1882): close the review findings on the discriminator, dry-run and counter
Three orthogonal review passes ran against the final diff. Their findings:
A labelled preamble under a leading rule was still misreported. Raising the key
threshold to two only moved the boundary, because two colon-labelled lines are
as common in ordinary prose as one -- a document opening with a rule over an
Author and a Reviewed-by line, then prose, was called corrupt. Key count alone
cannot separate the two. What does is what follows: a write interrupted part way
through a frontmatter block ends mid-block, so every line of the region is still
frontmatter-shaped, whereas a document merely opening with a rule goes on to
prose. Both conditions are now required, and each closes a false-positive class
the other leaves open. Nested list values and indented continuations stay
frontmatter-shaped, so legitimate truncations are unaffected.
`state rebuild --dry-run` reported a truncated STATE.md anonymously. The write
path is named only because readModifyWriteStateMd parses with the path first;
the dry-run branch reads the file directly and never did. Dry-run is the
read-only mode an operator reaches for first when they suspect corruption, so it
is the one that most needed to name the file. reconcileCurrentPosition takes the
path as an optional argument now and rebuildCore passes it down. That function
was previously left alone on the grounds that a read wrapper always names the
file first -- this is the flow that disproves it.
The emission counter counted write attempts rather than writes, so on a broken
stderr it claimed a diagnostic had reached the operator when nothing had. It is
incremented only after a write that completed, and the broken-stderr test now
asserts the count as well as the return value.
Two documentation defects. The module described a guarantee it does not keep:
one file yields one diagnostic only when the named read comes first. The reverse
ordering emits twice, and that is deliberate -- a path-less caller cannot
identify its file, so suppressing the later named report would also suppress a
genuine second failure in a different file whenever two files share identical
truncated bytes, which ADR-1411 ranks the worse failure. The comment now states
the asymmetric guarantee and a test pins it. Separately, the CONTEXT.md glossary
entry still described backslash normalization that a later commit removed, and
asserted the opposite of what the tests pin; no lint checks prose against code,
so nothing caught it.
Also converts three body-level try/finally blocks to t.after(), per
CONTRIBUTING.md's rule that try/finally belongs only in helpers with no test
context -- the file's own emissionsDuring helper already did this correctly.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* docs(#1882): tell the operator what the truncated-frontmatter warning means
A user who has just seen the new warning is acting, not studying, so this lands
in the How-To quadrant beside the other "if you see X" branches in
debug-a-failed-execution, not in reference or explanation. It gives them what
the warning means for this run, three steps to restore the file, and the fact
that the warning changes no return value or exit code.
It also states the case that matters more than the warning itself: silence does
not prove the file is intact. GSD says nothing when the partial block carries
fewer than two fields or reads as prose, because a Markdown document opening
with a horizontal rule is indistinguishable from one of those. A reader chasing
missing metadata needs to know not to treat quiet as clean. Why that threshold
exists is explanation and deliberately stays out of a how-to.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* chore(#1882): backfill changeset pr number to 2712
* test(#1882): constrain each branch of the frontmatter-shape check
CI's mutation gate came in at 61.56 against a threshold of 62, and the surviving
mutants were concentrated in isFrontmatterShaped -- the function added last, in
response to review, and the only one never given tests of its own. It was
exercised solely through extractFrontmatter, which covers the composite decision
but leaves each branch of the predicate unconstrained: drop the blank-line
filter, or any one of the three shape alternatives, and every existing assertion
still passed.
Four cases now pin the halves independently. A blank line inside an interrupted
block must not disqualify it, which constrains the filter and its comparison. An
unindented list item and an indented folded-scalar continuation each exercise one
shape alternative that no other case reaches on its own -- the folded line is
neither a key nor a list item, so it is the only input that distinguishes the
indented branch. And two keys followed by prose must stay silent, which is the
negative half: it fails if the predicate is ever mutated to accept everything,
and it is the case that proves key count alone was never sufficient.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* test(#1882): register the unusable-input suite with the frontmatter mutation shard
The mutation gate reported an identical 61.56 across two runs whose only
difference was four added tests. That is the tell: the tests were never
executed. The frontmatter shard runs a fixed file list in stryker.config.mjs and
scripts/mutation-matrix.cjs, and tests/unusable-input.test.cjs was in neither, so
the entire suite covering the new unterminated-fence branch was invisible to the
gate while passing perfectly well in the normal run.
So the score was not measuring weak tests, it was measuring absent ones: #1882
added mutants to frontmatter.cjs and no test in the shard covered them. Both
lists gain the file; the config already notes they must stay in sync.
This is a registration ripple a new test file carries when it covers a
mutation-tracked module, alongside the .gitignore, eslint, inventory, glossary
and size-baseline ripples a new module carries. Nothing warned about it, which
is why two runs were spent before the identical score gave it away.
Refs #1879
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
456 lines
22 KiB
JavaScript
456 lines
22 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Unusable-input diagnostic — the out-of-band half of ADR-1411's "corrupt is not absent"
|
|
* amendment (epic #1879), and its first adopter, extractFrontmatter (#1882).
|
|
*
|
|
* What is under test is a BEHAVIOUR CHANGE ON A SILENT CHANNEL: every return value is
|
|
* preserved exactly, and the only observable difference is that a genuinely-unusable input
|
|
* now produces one diagnostic. So the assertions here are all on typed surfaces — the
|
|
* frozen reason enum and the dedup-set size — never on the diagnostic prose, per
|
|
* CONTRIBUTING.md's ban on raw text matching against stdout/stderr/file content.
|
|
*
|
|
* Independence note: the dedup set is process-global. Every case below resets it AND uses a
|
|
* path unique to that case. #2674 is the cautionary precedent in this repo — a reset helper
|
|
* that cleared two of three sets was a silent no-op for the very suite that existed to test
|
|
* it, and the cases only passed because each happened to pick a key no other case reused.
|
|
*/
|
|
|
|
const { describe, test } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
|
|
const {
|
|
UNUSABLE_REASON,
|
|
warnUnusableInput,
|
|
_resetUnusableInputWarningsForTests,
|
|
_unusableInputWarningCountForTests,
|
|
_unusableInputEmissionCountForTests,
|
|
_sanitizeSourceForTests,
|
|
} = require('../gsd-core/bin/lib/unusable-input.cjs');
|
|
|
|
const { extractFrontmatter, UNTERMINATED_KEY_THRESHOLD } = require('../gsd-core/bin/lib/frontmatter.cjs');
|
|
|
|
/**
|
|
* Run `fn` with stderr captured, and report how many NEW diagnostics it produced.
|
|
*
|
|
* The count comes from the dedup set, not from parsing what was written — that is the typed
|
|
* surface. stderr is stubbed only to keep the suite's own output clean; the stub is restored
|
|
* in a `finally` inside this standalone helper, which is the one place CONTRIBUTING.md
|
|
* permits try/finally (a helper with no access to test context).
|
|
*/
|
|
function emissionsDuring(fn) {
|
|
const before = _unusableInputEmissionCountForTests();
|
|
const original = process.stderr.write;
|
|
process.stderr.write = () => true;
|
|
try {
|
|
fn();
|
|
} finally {
|
|
process.stderr.write = original;
|
|
}
|
|
return _unusableInputEmissionCountForTests() - before;
|
|
}
|
|
|
|
/** Parse `content` under a path unique to the calling case, returning [result, emissions]. */
|
|
function parseUnder(content, sourcePath) {
|
|
let result;
|
|
const emitted = emissionsDuring(() => {
|
|
result = extractFrontmatter(content, sourcePath);
|
|
});
|
|
return [result, emitted];
|
|
}
|
|
|
|
const TRUNCATED_LF = '---\nphase: 01\nplan: 02\n';
|
|
const TRUNCATED_CRLF = '---\r\nphase: 01\r\nplan: 02\r\n';
|
|
|
|
// ─── The reason vocabulary is a contract ─────────────────────────────────────
|
|
|
|
describe('UNUSABLE_REASON', () => {
|
|
test('is frozen and holds exactly the reasons that have an emitting call site', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
assert.ok(Object.isFrozen(UNUSABLE_REASON), 'enum must be frozen');
|
|
// Locking the key set is what makes adding a reason three coordinated changes
|
|
// (enum + call site + this assertion) instead of a silent widening.
|
|
assert.deepStrictEqual(Object.keys(UNUSABLE_REASON).sort(), ['FRONTMATTER_UNTERMINATED']);
|
|
assert.strictEqual(UNUSABLE_REASON.FRONTMATTER_UNTERMINATED, 'frontmatter_unterminated');
|
|
});
|
|
|
|
test('an unrecognised reason emits nothing rather than a diagnostic naming undefined', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const emitted = emissionsDuring(() => {
|
|
const wrote = warnUnusableInput({ reason: 'not_a_real_reason', source: '/u/unknown.md' });
|
|
assert.strictEqual(wrote, false, 'unknown reason must report that it wrote nothing');
|
|
});
|
|
assert.strictEqual(emitted, 0);
|
|
});
|
|
});
|
|
|
|
// ─── The discriminator: truncated vs. everything that merely looks like it ───
|
|
|
|
describe('extractFrontmatter — flags a genuinely truncated frontmatter', () => {
|
|
test('unterminated fence carrying two keys is reported, and still returns {}', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [result, emitted] = parseUnder(TRUNCATED_LF, '/u/truncated-lf.md');
|
|
assert.deepStrictEqual(result, {}, 'return value must be preserved exactly');
|
|
assert.strictEqual(emitted, 1);
|
|
});
|
|
|
|
test('CRLF unterminated fence is reported identically to LF', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [result, emitted] = parseUnder(TRUNCATED_CRLF, '/u/truncated-crlf.md');
|
|
assert.deepStrictEqual(result, {});
|
|
assert.strictEqual(emitted, 1);
|
|
});
|
|
|
|
test('an indented "---" is not a closing fence, so the file is still truncated', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [result, emitted] = parseUnder('---\nphase: 01\nplan: 02\n ---\n', '/u/indented-close.md');
|
|
assert.deepStrictEqual(result, {});
|
|
assert.strictEqual(emitted, 1);
|
|
});
|
|
});
|
|
|
|
describe('extractFrontmatter — stays silent on everything that is not corruption', () => {
|
|
// Each row here is a document that reaches, or nearly reaches, the same branch as a
|
|
// truncated file. A diagnostic on any of them is a false positive on valid input.
|
|
const silentCases = [
|
|
['a document with no frontmatter at all', 'plain body\nmore\n'],
|
|
['a Markdown thematic break at byte 0', '---\nSome heading text\n\nA paragraph, no more dashes.\n'],
|
|
['a thematic break followed by a second one', '---\nIntro\n\n---\n\nMore\n'],
|
|
['a well-formed but empty frontmatter block', '---\n---\nbody\n'],
|
|
['an opening fence with nothing after it', '---\n'],
|
|
['a bare "---" with no newline', '---'],
|
|
['an empty document', ''],
|
|
['a BOM before the fence', '\uFEFF---\ntitle: x\n---\nbody\n'],
|
|
['a blank line before the fence', '\n---\ntitle: x\n---\n'],
|
|
['an opening fence with a trailing space', '--- \ntitle: x\n---\n'],
|
|
// #1882 review blocker: a thematic break above ONE labelled prose line is ordinary
|
|
// technical writing and parses as exactly one key. Each of these was flagged as
|
|
// corruption before the threshold moved to two.
|
|
['a thematic break above a Note: paragraph', '---\nNote: this is just a markdown paragraph, not frontmatter.\n'],
|
|
['a thematic break above an Author byline', '---\nAuthor: Jane Doe\n'],
|
|
['a thematic break above a TODO line', '---\nTODO: fix this later\n'],
|
|
['a thematic break above a See: link', '---\nSee: https://example.com\n'],
|
|
];
|
|
|
|
silentCases.forEach(([label, content], caseIndex) => {
|
|
test(`${label} produces no diagnostic`, () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, emitted] = parseUnder(content, `/u/silent-${caseIndex}.md`);
|
|
assert.strictEqual(emitted, 0, `${label} must not be reported as corruption`);
|
|
});
|
|
});
|
|
|
|
test('a thematic break above TWO labelled lines followed by prose stays silent', () => {
|
|
// Review finding: raising the key threshold to 2 only moved the boundary — two labelled
|
|
// lines are as common in ordinary prose as one. What separates a truncated write from a
|
|
// document opening with a rule is that a truncated write ends mid-block, so EVERY line is
|
|
// still frontmatter-shaped; this document goes on to prose.
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, emitted] = parseUnder(
|
|
'---\nAuthor: Jane Doe\nReviewed-by: John Smith\n\nOrdinary prose, no other --- anywhere.\n',
|
|
'/u/two-labelled-lines.md',
|
|
);
|
|
assert.strictEqual(emitted, 0, 'a labelled preamble above prose is not a truncated file');
|
|
});
|
|
|
|
// The shape check decides whether an unterminated region reads as an interrupted frontmatter
|
|
// block or as a document that merely opened with a rule. These four pin each half of that
|
|
// decision independently; without them the predicate's individual branches are unconstrained
|
|
// and a mutation that drops any one of them still passes.
|
|
test('a blank line inside an interrupted block does not disqualify it', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, emitted] = parseUnder('---\nphase: 01\n\nplan: 02\n', '/u/shape-blank-line.md');
|
|
assert.strictEqual(emitted, 1, 'blank lines are skipped, not treated as non-frontmatter');
|
|
});
|
|
|
|
test('an unindented list item counts as frontmatter-shaped', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, emitted] = parseUnder('---\nphase: 01\nmust_haves:\n- alpha\n', '/u/shape-flat-list.md');
|
|
assert.strictEqual(emitted, 1);
|
|
});
|
|
|
|
test('an indented folded-scalar continuation counts as frontmatter-shaped', () => {
|
|
// This line is neither a key nor a list item, so it is the only case that exercises the
|
|
// indented-continuation branch on its own.
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, emitted] = parseUnder('---\nphase: 01\ndescription: >\n folded text\n', '/u/shape-folded.md');
|
|
assert.strictEqual(emitted, 1);
|
|
});
|
|
|
|
test('two keys followed by prose is NOT frontmatter-shaped', () => {
|
|
// The negative half: enough keys to clear the threshold, but the region goes on to prose,
|
|
// so it is a document opening with a rule rather than an interrupted write.
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, emitted] = parseUnder(
|
|
'---\nphase: 01\nplan: 02\n\nOrdinary prose sentence here.\n',
|
|
'/u/shape-then-prose.md',
|
|
);
|
|
assert.strictEqual(emitted, 0, 'key count alone must not be sufficient');
|
|
});
|
|
|
|
test('a truncated block whose values are nested lists is still reported', () => {
|
|
// The shape check must not reject legitimate frontmatter: list items and indented
|
|
// continuations are frontmatter-shaped too.
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, emitted] = parseUnder('---\nphase: 01\nmust_haves:\n - alpha\n - beta\n', '/u/nested.md');
|
|
assert.strictEqual(emitted, 1);
|
|
});
|
|
|
|
test('a well-formed document still parses its keys and stays silent', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
let parsed;
|
|
const emitted = emissionsDuring(() => {
|
|
parsed = extractFrontmatter('---\ntitle: x\nstatus: draft\n---\nbody\n', '/u/well-formed.md');
|
|
});
|
|
assert.deepStrictEqual(parsed, { title: 'x', status: 'draft' });
|
|
assert.strictEqual(emitted, 0);
|
|
});
|
|
|
|
test('a four-dash close keeps its pre-existing lenient parse and stays silent', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
let parsed;
|
|
const emitted = emissionsDuring(() => {
|
|
parsed = extractFrontmatter('---\ntitle: x\n----\n', '/u/four-dash.md');
|
|
});
|
|
assert.deepStrictEqual(parsed, { title: 'x' });
|
|
assert.strictEqual(emitted, 0);
|
|
});
|
|
});
|
|
|
|
// ─── Boundary: the discriminator's threshold is ">= 2 parsed keys" ──────────
|
|
|
|
describe('extractFrontmatter — key-count boundary around the >=2 threshold', () => {
|
|
test('below threshold: zero keys is silent', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, emitted] = parseUnder('---\njust prose, no colon\n', '/u/boundary-0.md');
|
|
assert.strictEqual(emitted, 0);
|
|
});
|
|
|
|
test('limit-1: exactly one key is silent — a labelled line under a thematic break', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, emitted] = parseUnder('---\na: 1\n', '/u/boundary-1.md');
|
|
assert.strictEqual(emitted, 0, 'one key is ambiguous with ordinary Markdown');
|
|
});
|
|
|
|
test('limit: exactly two keys is reported', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, emitted] = parseUnder('---\na: 1\nb: 2\n', '/u/boundary-2.md');
|
|
assert.strictEqual(emitted, UNTERMINATED_KEY_THRESHOLD - 1);
|
|
});
|
|
|
|
test('limit+1: three keys is reported exactly once, not once per key', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, emitted] = parseUnder('---\na: 1\nb: 2\nc: 3\n', '/u/boundary-3.md');
|
|
assert.strictEqual(emitted, 1);
|
|
});
|
|
});
|
|
|
|
// ─── Deduplication: both halves of the composite key ────────────────────────
|
|
|
|
describe('diagnostic deduplication', () => {
|
|
test('the same file reported twice yields one diagnostic', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, first] = parseUnder(TRUNCATED_LF, '/u/dedup-same.md');
|
|
const [, second] = parseUnder(TRUNCATED_LF, '/u/dedup-same.md');
|
|
assert.strictEqual(first, 1);
|
|
assert.strictEqual(second, 0, 'a repeat of the same fault must be suppressed');
|
|
});
|
|
|
|
test('a genuine second failure in a DIFFERENT file is never suppressed', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, a] = parseUnder(TRUNCATED_LF, '/u/dedup-fileA.md');
|
|
const [, b] = parseUnder(TRUNCATED_LF, '/u/dedup-fileB.md');
|
|
assert.strictEqual(a, 1);
|
|
assert.strictEqual(b, 1, 'keying too coarsely would hide a real second fault');
|
|
});
|
|
|
|
test('the key includes the cause, so one file can report two different causes', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const source = '/u/dedup-two-causes.md';
|
|
const emitted = emissionsDuring(() => {
|
|
const first = warnUnusableInput({
|
|
reason: UNUSABLE_REASON.FRONTMATTER_UNTERMINATED,
|
|
source,
|
|
});
|
|
const repeat = warnUnusableInput({
|
|
reason: UNUSABLE_REASON.FRONTMATTER_UNTERMINATED,
|
|
source,
|
|
});
|
|
assert.strictEqual(first, true);
|
|
assert.strictEqual(repeat, false, 'same (path, cause) must dedup');
|
|
});
|
|
assert.strictEqual(emitted, 1);
|
|
});
|
|
|
|
test('two spellings of one Windows path may report twice — the accepted trade', () => {
|
|
// Separator folding was REMOVED: it collapsed genuinely distinct POSIX files whose
|
|
// names contain a backslash. The residual cost is that one Windows file written two
|
|
// ways can report twice. Mild noise is strictly preferable to a swallowed diagnostic,
|
|
// and this test pins the direction of that trade so it is not silently reversed.
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, backslash] = parseUnder(TRUNCATED_LF, 'C:\\proj\\phases\\PLAN.md');
|
|
const [, forward] = parseUnder(TRUNCATED_LF, 'C:/proj/phases/PLAN.md');
|
|
assert.strictEqual(backslash, 1);
|
|
assert.strictEqual(forward, 1, 'noise is acceptable; a lost diagnostic is not');
|
|
});
|
|
|
|
test('path-less callers dedup on content, so identical content reports once', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, first] = parseUnder(TRUNCATED_LF, undefined);
|
|
const [, second] = parseUnder(TRUNCATED_LF, undefined);
|
|
assert.strictEqual(first, 1);
|
|
assert.strictEqual(second, 0);
|
|
});
|
|
|
|
test('path-less callers with DIFFERENT content each report', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, first] = parseUnder('---\nalpha: 1\na2: x\n', undefined);
|
|
const [, second] = parseUnder('---\nbeta: 2\nb2: y\n', undefined);
|
|
assert.strictEqual(first, 1);
|
|
assert.strictEqual(second, 1);
|
|
});
|
|
|
|
test('an empty-string path falls back to the content key rather than keying on ""', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, first] = parseUnder('---\ngamma: 1\ng2: x\n', ' ');
|
|
const [, second] = parseUnder('---\ndelta: 2\nd2: y\n', ' ');
|
|
assert.strictEqual(first, 1);
|
|
assert.strictEqual(second, 1, 'blank paths must not collapse distinct files into one key');
|
|
});
|
|
|
|
test('only the offending file is reported when a good file is parsed alongside it', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const emitted = emissionsDuring(() => {
|
|
extractFrontmatter('---\nok: 1\n---\nbody\n', '/u/mixed-good.md');
|
|
extractFrontmatter(TRUNCATED_LF, '/u/mixed-bad.md');
|
|
extractFrontmatter('---\nalso: 2\n---\nbody\n', '/u/mixed-good-2.md');
|
|
});
|
|
assert.strictEqual(emitted, 1);
|
|
});
|
|
|
|
test('anonymous-first then named reports twice — the documented asymmetry', () => {
|
|
// Pinned deliberately. A path-less caller cannot identify its file, so suppressing the
|
|
// later NAMED report would also suppress a genuine second failure in a DIFFERENT file
|
|
// whenever two files share byte-identical truncated content. ADR-1411 ranks that swallow
|
|
// the worse failure, so the duplicate is accepted and the named line carries the filename.
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, anonymous] = parseUnder(TRUNCATED_LF, undefined);
|
|
const [, named] = parseUnder(TRUNCATED_LF, '/u/anon-then-named.md');
|
|
assert.strictEqual(anonymous, 1);
|
|
assert.strictEqual(named, 1, 'the named report must still name the file');
|
|
});
|
|
|
|
test('one file parsed both with and without a path reports exactly once', () => {
|
|
// A read wrapper knows the path; a pure core downstream (state-transition.cts, per
|
|
// ADR-1769) is handed only the string. Keying those two parses separately reported the
|
|
// SAME truncated file twice, under a path key and a digest key.
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, named] = parseUnder(TRUNCATED_LF, '/u/both-identities.md');
|
|
const [, anonymous] = parseUnder(TRUNCATED_LF, undefined);
|
|
assert.strictEqual(named, 1);
|
|
assert.strictEqual(anonymous, 0, 'the same file must not report twice under two keys');
|
|
});
|
|
|
|
test('widening the key does not merge two genuinely different files', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, a] = parseUnder('---\nphase: 01\nplan: 02\n', '/u/widen-a.md');
|
|
const [, b] = parseUnder('---\nphase: 09\nplan: 09\n', '/u/widen-b.md');
|
|
assert.strictEqual(a, 1);
|
|
assert.strictEqual(b, 1, 'distinct content in distinct files must still both report');
|
|
});
|
|
|
|
test('the reset seam actually clears state, so the same key can report again', () => {
|
|
// #2674 shape: a reset that silently fails to clear turns every later dedup assertion
|
|
// into a vacuous pass. Prove the seam by re-reporting a key that was just suppressed.
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, first] = parseUnder(TRUNCATED_LF, '/u/reset-seam.md');
|
|
const [, suppressed] = parseUnder(TRUNCATED_LF, '/u/reset-seam.md');
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, afterReset] = parseUnder(TRUNCATED_LF, '/u/reset-seam.md');
|
|
assert.strictEqual(first, 1);
|
|
assert.strictEqual(suppressed, 0);
|
|
assert.strictEqual(afterReset, 1, 'reset must genuinely empty the dedup set');
|
|
assert.strictEqual(_unusableInputEmissionCountForTests(), 1,
|
|
'exactly one diagnostic was written after the reset');
|
|
assert.ok(_unusableInputWarningCountForTests() >= 1,
|
|
'and at least one identity was interned for it');
|
|
});
|
|
});
|
|
|
|
// ─── Hostile input ───────────────────────────────────────────────────────────
|
|
|
|
describe('hostile input', () => {
|
|
test('a literal backslash in a POSIX filename does not collide with a real directory', () => {
|
|
// Review finding: folding backslashes to '/' unconditionally made these two GENUINELY
|
|
// different files share one key on Linux/macOS, where '\\' is a legal filename
|
|
// character, and silently swallowed the second diagnostic.
|
|
_resetUnusableInputWarningsForTests();
|
|
const [, withBackslash] = parseUnder(TRUNCATED_LF, '/repo/weird\\name/PLAN.md');
|
|
const [, withSlash] = parseUnder(TRUNCATED_LF, '/repo/weird/name/PLAN.md');
|
|
assert.strictEqual(withBackslash, 1);
|
|
assert.strictEqual(withSlash, 1, 'two distinct files must never silence each other');
|
|
});
|
|
|
|
test('a path spelled like the unnamed-digest fallback cannot pre-seed suppression', () => {
|
|
// Review finding: the digest of any predictable content can be computed and used as a
|
|
// filename, so the two key namespaces must be disjoint by construction.
|
|
_resetUnusableInputWarningsForTests();
|
|
const crypto = require('node:crypto');
|
|
const digest = crypto.createHash('sha256').update(TRUNCATED_LF).digest('hex').slice(0, 16);
|
|
const [, forged] = parseUnder(TRUNCATED_LF, `<unnamed:${digest}>`);
|
|
const [, realFile] = parseUnder(TRUNCATED_LF, '/u/forge-victim.md');
|
|
assert.strictEqual(forged, 1);
|
|
assert.strictEqual(realFile, 1,
|
|
'a crafted filename must never suppress a real file reported by its own path');
|
|
// The anonymous re-report of byte-identical content IS suppressed, deliberately: that is
|
|
// the same-file guard (named read first, path-less re-parse second). The forged name buys
|
|
// an attacker nothing there, because ANY path-ful report of that content does the same.
|
|
});
|
|
|
|
test('a NUL in the path cannot forge a collision with another key', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
// The key separator is NUL. If it were not stripped, "a\0frontmatter_unterminated"
|
|
// supplied as a *path* would collide with the real key for path "a".
|
|
const [, forged] = parseUnder(TRUNCATED_LF, '/u/collide\u0000frontmatter_unterminated');
|
|
const [, genuine] = parseUnder(TRUNCATED_LF, '/u/collide');
|
|
assert.strictEqual(forged, 1);
|
|
assert.strictEqual(genuine, 1, 'a crafted path must not suppress a real report');
|
|
});
|
|
|
|
test('control characters are stripped from the source before it is used', () => {
|
|
// Asserted on the sanitizer's RETURN VALUE, not by capturing what reached stderr.
|
|
// Scraping the rendered stream and regex-testing it is the shape CONTRIBUTING.md bans
|
|
// (Prohibited: Raw Text Matching on Test Outputs) — the rule targets the mechanism,
|
|
// not just prose-wording checks, so the typed surface is the correct fix.
|
|
_resetUnusableInputWarningsForTests();
|
|
const cleaned = _sanitizeSourceForTests('/u/ansi\u001b[31mred\u0007\u0000.md');
|
|
assert.strictEqual(cleaned, '/u/ansi[31mred.md');
|
|
for (const ch of cleaned) {
|
|
assert.ok(ch.charCodeAt(0) > 31 && ch.charCodeAt(0) !== 127,
|
|
'sanitized source must contain no C0 or DEL bytes');
|
|
}
|
|
});
|
|
|
|
test('a large unterminated region completes without pathological behaviour', () => {
|
|
_resetUnusableInputWarningsForTests();
|
|
const big = '---\n' + Array.from({ length: 5000 }, (_, i) => `k${i}: v${i}`).join('\n') + '\n';
|
|
const [result, emitted] = parseUnder(big, '/u/large-unterminated.md');
|
|
assert.deepStrictEqual(result, {}, 'still returns the preserved sentinel');
|
|
assert.strictEqual(emitted, 1);
|
|
});
|
|
|
|
test('a failing stderr write is swallowed and never escalates into a throw', (t) => {
|
|
// Fault injection by method override + restore, never chmod 0o000: root bypasses mode
|
|
// bits, so a permission-based version of this test would silently pass with zero
|
|
// coverage in root Docker/CI.
|
|
_resetUnusableInputWarningsForTests();
|
|
const original = process.stderr.write;
|
|
t.after(() => { process.stderr.write = original; });
|
|
process.stderr.write = () => { throw new Error('EPIPE injected'); };
|
|
const result = extractFrontmatter(TRUNCATED_LF, '/u/broken-stderr.md');
|
|
assert.deepStrictEqual(result, {}, 'a broken stderr must not change the return value');
|
|
assert.strictEqual(_unusableInputEmissionCountForTests(), 0,
|
|
'a write that threw must not be counted as a diagnostic the operator saw');
|
|
});
|
|
});
|