Files
msd-core/tests/helpers/compact-content-variant.cjs
Tom Boucher a27cb6b2fa enhance(#4139): Phase 6 — the lazily-read remainder and the artifact templates (#4540)
* enhance(#4406): the lazily-read remainder and the artifact templates

ADR-4139 Decision 3, Phase 6 of the #4139 Compact Content epic. Covers stream 1b
(gsd-core/workflows/<name>/{modes,steps,templates}/*.md) and stream 4
(gsd-core/templates/**) with a variant-swap mechanism, confirmed with the user:
two independent, complete files per covered path (canonical + .compact.md
sibling), with the gate picking which one gets Read at the call site. This is
a different shape from Phase 5's spine+detail partition, and is safe here
specifically because these files are already reached only by a runtime Read —
a missed Read already means zero overlay content today, with or without
workflow.compact_content, so selecting between two independently-complete
files introduces no new failure mode (documented in
gsd-core/references/compact-content-gate.md's new "Streams 1b and 4" section).

Disposition, after inspecting every candidate rather than trusting a byte-size
threshold (same rigor Phase 5 applied to review.md):

- Stream 1b: 1 of 78 files compacted (help/modes/full.md, a user-facing
  reference doc emitted verbatim, not orchestrator instruction). The other 9
  size-threshold candidates are dominated by fail-closed guards, exact CLI
  invocations, or output-format contracts (AskUserQuestion blocks) — recorded
  not-worth-compacting, same reasoning as Phase 5's review.md.
- Stream 4: a ground-truth reachability audit replaced the initial size-only
  candidate list. Two files (summary.md, user-setup.md) got compact variants;
  a third (spec.md) was drafted, then dropped after discovering its only two
  call sites are eager @-includes, not a runtime Read — stream-1 material
  hiding under gsd-core/templates/, not stream-4's actual mechanism. summary.md
  itself has 3 eager call sites and only 1 genuine runtime-Read call site
  (execute-plan.md); only that one was wired, so the compact variant's savings
  apply to the sequential single-plan execution path only.
- Discovered while auditing reachability: 12 gsd-core/templates/** files with
  zero references anywhere in workflow/agent/command prose, compiled source,
  or tests — dead scaffolding predating this phase. Deleted in this same PR
  per this repo's no-defer policy, after re-verifying against a computed
  path.join(...) pattern (not just a plain-string search) that nearly caused
  two genuinely load-bearing templates (user-profile.md, dev-preferences.md)
  to be misclassified as dead.

New checker (tests/helpers/compact-content-variant.cjs): registration,
reachability, protected-content-preserved, size-smaller — replacing Phase
3/5's disjointness/completeness checks, which assume a partition rather than
two deliberately-overlapping documents. The reachability check's own
"unprefixed match" guard had a real bug (rejected the repo's own
`~/.claude/gsd-core/...` convention), caught by running it against the
already-wired help/modes/full.compact.md pair rather than only synthetic
fixtures — fixed to anchor on the nearest `gsd-core` path segment instead.

Template consumer parity (tests/compact-content-template-variant-parity.test.cjs):
proves each compact variant's `## File Template` fenced block — the actual
output-format contract a generated SUMMARY.md/USER-SETUP.md is parsed
against — is byte-identical to the canonical file, then runs the one real
deterministic consumer (gsd-core/bin/lib/coverage.cjs's classifyContent,
backing `gsd-tools uat classify-coverage`) against content built from that
shared contract.

Added a sibling benchmark script (scripts/benchmark-compact-content-variants.cjs)
rather than extending the existing spine/detail one — different data shape,
and the existing script's own contract deliberately isolates it from a
test-only helper's shape changing.

Emitted-drift acknowledgement: not needed. Every changed/added path in this
diff is hand-authored and present in the diff itself, so diffEmitted's
attribution loop resolves `via` to the path's own source before reaching the
ack-lookup branch (same reasoning Phase 5 verified for its own diff).

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

* enhance(#4406): address code-review findings on the variant-swap gate

- docs/CONFIGURATION.md and gsd-core/references/planning-config.md's
  workflow.compact_content entries described only the spine+detail mechanism
  (Phase 5) and were missing this phase's variant-swap mechanism and its
  benchmark:compact-content-variants script entirely — required since this
  PR's changeset is type Added (CLAUDE.md's "Missing Docs for Changesets"
  rule). Both now describe both mechanisms and which call sites are wired.
- Added the missing RED^-1/no-op fixture for checkProtectedContentPreserved:
  a canonical file with zero <!-- gsd:protected --> blocks must be a
  no-op, not a violation — the only branch of that function the existing
  fixtures didn't exercise.
- Collapsed findCompactFiles/findMarkdownFiles in
  tests/helpers/compact-content-variant.cjs into one findFilesWithSuffix
  helper — the two were identical recursive walks differing only in the
  extension predicate (minor Duplicated-Code finding).

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

* fix(#4406): restore copilot-instructions.md, a false-positive dead-template classification

gsd-test caught this, not static analysis: 10 real failures in
tests/copilot-install.test.cjs, tests/installer-migration-install.integration.test.cjs,
and tests/repo-layout.test.cjs — all downstream of bin/install.js's Copilot install
path, which does
fs.readFileSync(path.join(targetDir, 'gsd-core', 'templates', 'copilot-instructions.md'))
after copying gsd-core/templates/** into the target project, then merges it into both
.github/copilot-instructions.md and (local installs) AGENTS.md. The reachability audit
that flagged this file as dead checked src/*.cts and gsd-core/bin/*.cjs but never the
repo-root bin/install.js — a separately maintained installer bundle outside the
src/-to-gsd-core/bin/lib/ compiled-output convention. The fs.existsSync guard around
that read degrades to a silent skip rather than a crash when the template is missing,
which is why this surfaced only once the real E2E install test ran, not from any
static check.

Re-verified the remaining 11 deleted filenames against bin/install.js specifically
(plain substring and quoted-filename search) before trusting that list — all 11 have
zero hits there, confirmed dead by the same standard this one file failed.

Regenerated the installer emitted-tree goldens (tests/fixtures/install-tree/*.json) to
reflect the restored file, and corrected the "Removed" changeset (jolly-lynx-sprint.md)
and the phase design doc from 12 to 11 deleted files.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Emitted-Drift-Ack-Growth: execute-plan.md — call-site wiring for the summary.md and user-setup.md .compact.md variants
Emitted-Drift-Ack-Growth: help.md — call-site wiring for full.compact.md, same variant-resolution rule

* docs(#4406): backfill changeset PR numbers

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

* fix(#4406): resolve removed-but-needed lint findings on the dead-template deletion

CI's own full-test matrix (not gsd-test's matrix, which does not run this
check) caught 4 more false-positive dead-template classifications via
tests/removed-but-needed-lint.test.cjs / scripts/lint-removed-but-needed.cjs
— a literal, word-boundary basename check across .github/workflows/,
gsd-core/, and docs/ (excluding docs/adr/** and docs/research/**) for every
file a PR deletes. It has no semantic awareness, so a deleted template's
basename colliding with something else entirely still fires:

- claude-md.md: gsd-core/templates/README.md had a stale table row claiming
  /gsd-profile reads this template to generate CLAUDE.md. Verified false (no
  code reads it anywhere, same search that already covered bin/install.js) —
  fixed the row to *(inline)*, matching every other command-generated
  artifact in that table. File stays deleted.
- codebase/testing.md: collided with docs/guides/testing.md, an illustrative
  example row in docs-update.md's sample output table (an unrelated real
  generated-docs path). Swapped the example topic to "contributing" — the
  row is illustrative, any topic works. File stays deleted.
- codebase/architecture.md, codebase/stack.md: collided with docs/reference/
  planning-artifacts.md's directory listing of a user's own generated
  .planning/codebase/architecture.md and stack.md output — the same
  semantic mismatch already investigated and dismissed as unrelated earlier
  in this phase's audit, now caught by a gate instead of judgment. That
  listing repeats across 5 locale copies of the doc.
- continue-here.md: collided with the real .continue-here.md pause-work
  artifact, referenced across 15+ locale and workflow files.

For the last two, the lint's own error message offers "restore the file or
update every consumer in the same commit." Rewording 15+ files across
languages I cannot verify translation quality for, to shave 2 already-tiny
templates that were merely presumed dead, is disproportionate to this PR's
actual scope — restored codebase/architecture.md, codebase/stack.md, and
continue-here.md instead, and corrected docs/ARCHITECTURE.md's Templates
section accordingly.

Final confirmed-dead set: claude-md.md, codebase/concerns.md,
codebase/conventions.md, codebase/integrations.md, codebase/structure.md,
codebase/testing.md, debug-subagent-prompt.md, discovery.md — 8 files, down
from the original 12. Verified locally: GSD_REMOVED_BUT_NEEDED_BASE=next
node scripts/lint-removed-but-needed.cjs now passes clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Emitted-Drift-Ack-Growth: docs-update.md — swapped an illustrative example-table topic (testing -> contributing) to avoid a removed-but-needed basename collision with the deleted codebase/testing.md template; net +10 bytes

* fix(#4406): split codex-config.test.cjs to fix a genuine Windows CI timeout

Root cause of the `full test (windows-latest, 24, shard 2/3)` failure the
user asked to be actually fixed, not just re-run past: PR #4497 (landed
2026-09-07, one day before this PR's CI run) isolated
tests/codex-config.test.cjs into its own dedicated chunk because its
measured weight (17.87, ~45% of the post-cut Windows budget) made it unsafe
to share a chunk with any other file. That isolation was necessary but not
sufficient — even alone, with zero companion-file contention, the file's
real Windows execution time sits right at the 600s per-chunk ceiling. Two
independent CI runs on two unrelated PRs (this one and #4154) were both
killed within ~1.4s of the identical 600000ms mark — not random contention,
a deterministic near-miss the isolation fix couldn't address because it
never reduced the file's own cost, only removed the risk of a companion
file's cost stacking on top of it (which the PR #4497 comment explicitly
anticipated: "if a future profiling pass genuinely speeds up
codex-config.test.cjs itself, this isolation can be revisited").

The file itself explains why it's this heavy: 11,262 lines / 433 tests / 79
describe blocks, accumulated over dozens of bug-fix PRs (#2695, #2760,
#3245, #3285, #3346, #3426, #3427, #3562, #3566, #3582, #3808, and more),
several of which are explicitly documented as "folded" in from separate
files that were never actually split back out ("Verified non-duplicate
against both the pre-existing target and the other three folded sources").

Split into 4 files by top-level AST statement boundaries (never a naive
column-0 regex — an early attempt at that overcounted 79 apparent
"describe(" matches when only 21 are genuinely top-level; the rest are
nested inside a handful of large folded-in blocks, which a regex can't tell
apart from real top-level statements). Verified lossless twice: the split
script asserts byte-for-byte reconstruction of every source character, and
independently, total test()/describe() call counts match exactly between
the original file and the sum across all 4 new files (433/79 both sides).
Each new file carries the complete original shared header (imports/helpers)
for safety; per-file unused-import warnings from that duplication are
resolved via ESLint-precise alias renames (`{ foo: _foo }`, the standard
form for an intentionally-unused destructured binding — never a bare `{
_foo }`, which would destructure a different, nonexistent property).

No change needed to scripts/run-tests.cjs's ISOLATED_HEAVY_FILES or its
pinned test in tests/run-tests-harness.test.cjs: the file that keeps the
original name (tests/codex-config.test.cjs) is now only ~28% of the
original's size and safely isolated in its own chunk as before; the other
three new files re-enter normal weight-balanced packing, none individually
close to disproportionate. Confirmed no other file hardcodes the hardcoded
filename anywhere that would silently stop these tests from running (the
CI test-selection scripts determine scope algorithmically, not by literal
filename).

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

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-08 14:31:04 -04:00

294 lines
11 KiB
JavaScript

'use strict';
/**
* Shared library for the compact-content VARIANT guard (ADR-4139, epic #4139,
* Phase 6 #4406). See `gsd-core/references/compact-content-gate.md` §"Streams
* 1b and 4 — variant resolution" for the operational rule this module checks;
* this file is the mechanics, not the source of truth for behavior.
*
* This is a DIFFERENT shape from `compact-content-split.cjs` (Phase 3, stream
* 1's spine+detail partition). A partition is one document split into two
* halves that must never overlap (disjointness) and whose union must equal
* the original (completeness). A variant pair is two INDEPENDENT, complete
* documents that are EXPECTED to overlap heavily — the compact file is a
* hand-terser rewrite of the same content, not an extracted remainder. So
* this module has no disjointness check and no completeness-at-split-time
* check; it has the five checks `40-design.md` (Phase 6) describes instead:
*
* 1. Registration — `discoverRegisteredVariants` (a `.compact.md`
* file with no canonical sibling is not a registered pair; the guard
* test reports it as an orphan).
* 2. Reachability — `checkReachability` (a registered pair whose
* compact path is never named by any spine's "Read ... variant
* resolution" call site is unwired dead weight).
* 3. Protected content preserved — `checkProtectedContentPreserved` (a
* `<!-- gsd:protected -->` block's lines must appear verbatim in BOTH
* files, since nothing is "moved" in a variant pair — it is duplicated).
* 4. Size smaller — `checkSizeSmaller`.
* 5. Template consumer parity — NOT implemented here; it needs a real
* artifact-generation + real-parser round trip per template, which is
* the domain of `tests/compact-content-template-variant-parity.test.cjs`
* directly, not a generic file-shape check.
*
* This module only reads (filesystem + a search of markdown source for
* literal path substrings). No writes, no network, no git.
*/
const fs = require('node:fs');
const path = require('node:path');
const { extractProtectedBlocks, normalizeNonTrivialLines } = require('./compact-content-split.cjs');
/** Default scan roots: everywhere a `.compact.md` sibling can legally live. */
const DEFAULT_VARIANT_ROOTS = [
path.join(__dirname, '..', '..', 'gsd-core', 'workflows'),
path.join(__dirname, '..', '..', 'gsd-core', 'templates'),
];
/** Every markdown-source root a spine/fragment might name a variant path from. */
const DEFAULT_SEARCH_ROOTS = [
path.join(__dirname, '..', '..', 'gsd-core', 'workflows'),
];
const COMPACT_SUFFIX = '.compact.md';
/**
* Recursively list every file under `dir` whose name ends with `suffix`.
* Shared by both file-discovery needs this module has — `.compact.md` files
* (`findCompactFiles`) and general `.md` files to search for reachability
* (`findMarkdownFiles`) — which otherwise duplicated the same walk with only
* the extension predicate differing.
* @param {string} dir
* @param {string} suffix
* @returns {string[]} absolute paths
*/
function findFilesWithSuffix(dir, suffix) {
const results = [];
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return results;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
results.push(...findFilesWithSuffix(full, suffix));
} else if (entry.isFile() && entry.name.endsWith(suffix)) {
results.push(full);
}
}
return results;
}
/**
* Recursively list every `*.compact.md` file under `dir`.
* @param {string} dir
* @returns {string[]} absolute paths
*/
function findCompactFiles(dir) {
return findFilesWithSuffix(dir, COMPACT_SUFFIX);
}
/**
* Discover every registered compact/canonical variant pair under `roots`.
*
* A pair is registered by a `<dir>/<stem>.compact.md` file existing on disk —
* there is no separate registry. Its canonical sibling is `<dir>/<stem>.md`
* in the SAME directory. A `.compact.md` file with no canonical sibling is
* still returned (with `canonicalExists: false`) so the registration check
* can report it as an orphan by name, rather than silently skipping it.
*
* @param {string[]} roots
* @returns {{compactPath: string, canonicalPath: string, canonicalExists: boolean}[]}
*/
function discoverRegisteredVariants(roots = DEFAULT_VARIANT_ROOTS) {
const pairs = [];
for (const root of roots) {
for (const compactPath of findCompactFiles(root)) {
const dir = path.dirname(compactPath);
const stem = path.basename(compactPath, COMPACT_SUFFIX);
const canonicalPath = path.join(dir, `${stem}.md`);
pairs.push({
compactPath,
canonicalPath,
canonicalExists: fs.existsSync(canonicalPath),
});
}
}
return pairs.sort((a, b) => a.compactPath.localeCompare(b.compactPath));
}
/**
* Check 1 — registration. A `.compact.md` file must have a canonical sibling.
* @param {ReturnType<typeof discoverRegisteredVariants>} pairs
*/
function checkRegistration(pairs) {
const violations = [];
for (const pair of pairs) {
if (!pair.canonicalExists) {
violations.push({ kind: 'orphan_compact_file', compactPath: pair.compactPath });
}
}
return violations;
}
/**
* Check 2 — reachability. A registered pair's compact path must be named by
* at least one markdown file under `searchRoots` (a spine's "Read ... variant
* resolution" call site). Three needle forms, matched differently, because
* this corpus has two live conventions for naming these paths (found by
* walking up from the compact file itself to its nearest `gsd-core` ancestor,
* so this works the same way against the real repo and against a fixture
* that builds its own `<tmp>/gsd-core/...` tree):
*
* - The `gsd-core/<rest>` form (e.g. `gsd-core/workflows/autonomous/steps/
* converge-fail-fast.md`'s own convention) is unambiguous on its own — a
* different, longer path coincidentally ending in this exact multi-segment
* suffix is not a realistic false positive, so a plain substring match is
* sufficient without the "unprefixed" guard below.
* - The `<rest>` form without the leading `gsd-core/` (e.g. `workflows/help/
* modes/full.compact.md`, `help.md`'s own dispatch-table convention) is
* equally unambiguous for the same reason.
* - The bare `<stem>.compact.md` form has no such guarantee — a same-named
* file under an unrelated nested directory (the exact class of bug already
* hit once this phase: `discuss-phase/templates/context.md` vs. the root
* `templates/context.md`) could grant it a false reachability. This form
* keeps the `isUnprefixedMatch` guard from `namesFragmentAsEntryPoint`
* (`scripts/lint-response-language-coverage.cjs`): a path character
* immediately before the match means this is the tail of some longer,
* different path, not the fragment itself.
*
* @param {ReturnType<typeof discoverRegisteredVariants>} pairs
* @param {string[]} searchRoots
*/
function checkReachability(pairs, searchRoots = DEFAULT_SEARCH_ROOTS) {
const violations = [];
const haystacks = [];
for (const root of searchRoots) {
for (const file of findMarkdownFiles(root)) {
haystacks.push(fs.readFileSync(file, 'utf8'));
}
}
for (const pair of pairs) {
if (!pair.canonicalExists) continue; // already reported by checkRegistration
const gsdCoreRelative = relativeToNearestGsdCore(pair.compactPath);
const stem = path.basename(pair.compactPath, COMPACT_SUFFIX);
const bareNeedle = `${stem}${COMPACT_SUFFIX}`;
const reached = haystacks.some((text) => {
if (gsdCoreRelative && (text.includes(`gsd-core/${gsdCoreRelative}`) || text.includes(gsdCoreRelative))) {
return true;
}
return isUnprefixedMatch(text, bareNeedle);
});
if (!reached) {
violations.push({ kind: 'unreachable_compact_file', compactPath: pair.compactPath });
}
}
return violations;
}
/**
* Walk up from `filePath` to the nearest ancestor directory literally named
* `gsd-core`, and return the path from there to `filePath` (POSIX-separated).
* Returns `null` if no such ancestor exists. Anchoring on the literal
* `gsd-core` segment — rather than a hardcoded repo-root constant — is what
* lets this match both the real repo and a fixture built under its own
* `<tmp>/gsd-core/...` tree the same way.
* @param {string} filePath
* @returns {string | null}
*/
function relativeToNearestGsdCore(filePath) {
const segments = filePath.split(path.sep);
const idx = segments.lastIndexOf('gsd-core');
if (idx === -1) return null;
return segments.slice(idx + 1).join('/');
}
/** Is `needle` present in `text` with no path character immediately before it (any line)? */
function isUnprefixedMatch(text, needle) {
return text.split(/\r?\n/).some((line) => {
const at = line.indexOf(needle);
if (at === -1) return false;
const before = at > 0 ? line[at - 1] : '';
return !/[A-Za-z0-9_\-./]/.test(before);
});
}
function findMarkdownFiles(dir) {
return findFilesWithSuffix(dir, '.md');
}
/**
* Check 3 — protected content preserved. Every protected block's non-trivial
* lines in the canonical file must also appear (verbatim, after the same
* normalization the partition guard uses) somewhere in the compact sibling.
* Unlike the partition guard, this is NOT a sentinel-presence check on the
* compact file itself — the compact file need not carry `<!-- gsd:protected -->`
* markers of its own, since it is not itself audited for content it might
* shed later; it only must not have DROPPED the protected wording.
*
* @param {ReturnType<typeof discoverRegisteredVariants>} pairs
*/
function checkProtectedContentPreserved(pairs) {
const violations = [];
for (const pair of pairs) {
if (!pair.canonicalExists) continue;
const canonical = fs.readFileSync(pair.canonicalPath, 'utf8');
const compact = fs.readFileSync(pair.compactPath, 'utf8');
const { blocks } = extractProtectedBlocks(canonical);
if (blocks.length === 0) continue;
const compactLines = new Set(normalizeNonTrivialLines(compact));
for (const block of blocks) {
const missing = block.lines
.map((l) => l.trim())
.filter((l) => l.length > 0)
.filter((l) => !compactLines.has(l));
if (missing.length > 0) {
violations.push({
kind: 'protected_content_dropped',
canonicalPath: pair.canonicalPath,
compactPath: pair.compactPath,
missing,
});
}
}
}
return violations;
}
/**
* Check 4 — size smaller. The compact file must be strictly smaller than its
* canonical sibling; a same-size-or-larger "compact" file is not one.
* @param {ReturnType<typeof discoverRegisteredVariants>} pairs
*/
function checkSizeSmaller(pairs) {
const violations = [];
for (const pair of pairs) {
if (!pair.canonicalExists) continue;
const canonicalSize = fs.statSync(pair.canonicalPath).size;
const compactSize = fs.statSync(pair.compactPath).size;
if (!(compactSize < canonicalSize)) {
violations.push({
kind: 'compact_not_smaller',
canonicalPath: pair.canonicalPath,
compactPath: pair.compactPath,
canonicalSize,
compactSize,
});
}
}
return violations;
}
module.exports = {
DEFAULT_VARIANT_ROOTS,
DEFAULT_SEARCH_ROOTS,
COMPACT_SUFFIX,
discoverRegisteredVariants,
checkRegistration,
checkReachability,
checkProtectedContentPreserved,
checkSizeSmaller,
};