Files
msd-core/scripts/check-contract-drift.cjs
Tom Boucher 37b965c0d1 enhance(#4139): Phase 7 — the agent-skill seam picks the payload in code (#4553)
* enhance(#4139): Phase 7 — the agent-skill seam picks the payload in code

ADR-4139 stream 2. The non-Claude `#2454` persona fallback in cmdAgentSkills
(src/init.cts) now selects between a canonical agents/<name>.md and a
token-minimized agents/<name>.compact.md sibling based on
workflow.compact_content, resolved in code (a real function call with a real
exit code) rather than a prose config-get gate — the same precedent stream 1's
spine/detail split established for a load-bearing seam, applied here because
this seam already runs through TypeScript instead of an eager @-include.

A missing compact sibling falls back to the canonical persona and discloses
the fallback in the served payload itself (a leading HTML-comment provenance
line), so the Done-when contract — compact when on, canonical when off, never
silent or empty — holds even for an agent nobody has compacted yet.

Authored a .compact.md sibling for all 35 shipped agents (agents/gsd-*.md),
each an independent, complete rewrite (not an extraction — nothing is "moved"
the way spine/detail moves text) that preserves frontmatter, every @-include,
every output-format contract, and every guardrail verbatim while cutting
restatement and verbose framing. Verified mechanically: every pair registers
(a canonical sibling exists), every compact file is strictly smaller, and the
full @-include set matches canonical's — including which references are
standalone eager-load lines versus inline prose mentions, since demoting one
to inline changes what the host actually substitutes.

Traced the install path before writing any code (.gsd/phase/.../40-design.md):
stageAgentsForRuntimeWithConverter glob-copies every agents/*.md file with no
stem filtering under the default full profile, so the new .compact.md files
install for free with zero installer changes — matching issue #4407's stated
scope. A tiered agent profile that doesn't stage a compact sibling degrades
through the same fallback-with-provenance path already required for an
unauthored one, so no installer change is needed there either.

Extends tests/helpers/compact-content-variant.cjs with an AGENTS_ROOT export
(deliberately not folded into DEFAULT_VARIANT_ROOTS, since agent variants are
reached by a generic code construction rather than a literal path in prose,
and checkReachability's markdown-search shape has nothing to find there).
Reachability is instead proven behaviorally: tests/agent-skills.test.cjs's new
"#4407 compact payload selection" describe block spawns gsd_run agent-skills
against real compact/canonical fixture pairs and asserts on the served
payload, which can only pass if the seam genuinely wires through.

Fixed a pre-existing test whose agents/*.md glob incidentally matched the new
.compact.md siblings (tests/agent-skills.test.cjs's Skill-frontmatter drift
guard) and added the 35 new agents/*.compact.md entries to docs/INVENTORY.md's
roster, both real, unrelated-to-content defects the new files' mere existence
surfaced.

Regenerated: install-tree fixtures (19 runtimes now ship 35 more agent files
under the full profile), INVENTORY-MANIFEST.json, and the variant-swap token
benchmark baseline (npm run benchmark:compact-content-variants --write).

Closes #4407.

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

* fix(#4407): apply orthogonal review findings from the compact-payload seam

Standards axis of /code-review: extracted readNonEmptyFileOrNull(filePath)
to collapse the duplicated read-and-empty-check shape between the compact
and canonical branches in cmdAgentSkills, and updated the adjacent comment
enumerating flat JSON extras to name agent_payload_variant alongside
source/degraded (added by the prior commit, comment left stale).

Security review and the Spec axis found no defects requiring a code change;
their non-blocking observations (a pre-existing, unmodified path-construction
pattern; the reasoned, documented substitution of a behavioral test for the
literal reachability check) are recorded in
.gsd/phase/enhance-4407-agent-skill-seam/60-review.json.

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

* fix(#4407): repo-wide roster/cap fixes surfaced by shipping .compact.md agents

Root-caused via a real gsd-test run (93 failures) rather than guessing which
tests glob agents/ naively. Two classes of defect, both genuine:

1. Identity-roster confusion (11 files/areas): many tests and one production
   script derive "the set of GSD agents" from `readdirSync(agentsDir).filter(f
   => f.endsWith('.md'))`, which incidentally matched the new .compact.md
   variant siblings too — a compact file is a rendering of an EXISTING agent
   identity, not a new one. Fixed at the shared root
   (tests/helpers/agent-roster.cjs's listAgentFiles, which several tests
   already consolidated on) and at each independent glob that didn't use it:
   agent-size-budget.test.cjs (tier-cap lookup now strips the .compact suffix
   before checking XL/LARGE membership, so a compact file inherits its
   canonical sibling's tier instead of silently falling through to DEFAULT),
   agent-skills-bootstrap.test.cjs, check-contract-drift.test.cjs (the actual
   script, not just its test), codex-config.test.cjs (confirmed directly
   against generateCodexAgentToml that a compact role's derived sandbox_mode
   is byte-identical to its canonical sibling's before excluding it — not
   assumed), and copilot-install.test.cjs (two counts that legitimately DO
   need both files — an installed-file count and a full-conversion smoke test
   — fixed to expect 70, not stay pinned to 35).

   no-bare-gsd-tools-command-position.test.cjs needed the opposite kind of fix:
   two compact files reproduce descriptive prose already allowlisted at their
   canonical file's line number; added matching entries at the compact files'
   own line numbers rather than excluding them from the scan (a genuine bare
   gsd-tools command-position bug in a compact file would be as real a defect
   as in canonical).

2. A hard, non-ackable cap (found via emitted-attribution.test.cjs's real-tree
   run): six agents' compact renditions (gsd-debugger, gsd-executor,
   gsd-phase-researcher, gsd-plan-checker, gsd-planner, gsd-verifier) exceed
   the 32,768-byte NEW_FILE_CAP (ADR-1610) even after aggressive compaction —
   confirmed structural, not a compaction-quality gap: each is dominated by
   content this phase's own rules require verbatim (the ~2.6 KB gsd_run
   bootstrap preamble runtime-launcher-parity.test.cjs requires inlined in
   every agent that calls gsd_run, output-format contracts, guardrails).
   ADR-4139's prescribed remedy (spine + lazily-read parts) has no landing
   spot in cmdAgentSkills's single-file synchronous read. Removed these 6
   compact files rather than ship an over-cap file or invent a multi-part
   read mechanism out of scope for this phase; recorded by name with the
   reason in .gsd/phase/enhance-4407-agent-skill-seam/40-design.md and
   50-test-matrix.md, per #4407's own "or explicitly recorded as not worth
   covering" allowance. Their canonical personas are served correctly today
   via the fallback-with-disclosed-provenance path this phase's own Done-when
   #2 already requires — 29 of 35 agents now have a compact variant.

Also fixes an unrelated, genuinely pre-existing defect this gsd-test run
surfaced: gsd-core/workflows/execute-plan.md sat 21 bytes over its own
DEFAULT-tier hard cap (40,960 bytes) at the branch point, before any change in
this PR touched it — confirmed via `git show <merge-base>:...execute-plan.md
| wc -c`. Per CLAUDE.md's no-deferral rule, fixed inline rather than filed:
two meaning-preserving trims in the <success_criteria> block (a repeated
parenthetical replaced with a same-exception reference; one redundant
qualifier dropped) bring it to 40,940 bytes.

Regenerated install-tree fixtures, INVENTORY-MANIFEST.json, and the variant
benchmark baseline to reflect the 6 removed files. Docs/INVENTORY.md's 6
now-orphaned roster rows removed alongside them.

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

* fix(#4407): make .compact.md-aware roster checks resilient to partial coverage

Round 2 of the gsd-test-driven roster fixes: two checks assumed every agent
has a compact sibling (true for 29 of 35 after the NEW_FILE_CAP exception),
breaking once 6 stems legitimately have none.

- tests/agent-classification-parity.test.cjs: the INVENTORY.md parser was
  picking up the "### Compact Payload Variants" subsection's rows as
  phantom/uncounted entries in the primary/advanced/inventory-only
  classification this test validates — a compact row documents an existing
  agent's alternate rendition and never gets its own AGENTS.md heading, so it
  was never meant to participate in that classification. Excluded at the
  parser, not per-assertion.
- tests/copilot-install.test.cjs: the derived expected-file-list generator
  assumed every listAgentFiles() stem has a .compact.md source sibling;
  checks disk per stem now instead.

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

* docs(#4407): backfill changeset PR number

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-09 12:38:59 -04:00

301 lines
12 KiB
JavaScript

#!/usr/bin/env node
/**
* check-contract-drift.cjs
*
* Enforces that gsd-core/references/agent-contracts.md's `## Agent Registry`
* table stays in sync with reality:
*
* 1. The table itself must parse cleanly (no malformed rows).
* 2. Every agents/*.md file must have its fenced code blocks properly
* closed (an unclosed fence makes in-fence marker detection unreliable).
* 3. Every marker an agent actually emits in-fence, and every marker the
* registry declares for it, must agree (contractViolations' declared/
* emitted checks) -- unless the row opts out via `kind:
* artifact+query`/`structured-return`, in which case any emitted
* marker is itself a violation (vestigial_marker).
* 4. Every `sentinel-match` row's declared markers must have at least one
* exact-case consumer somewhere under gsd-core/workflows/, commands/,
* or agents/ (excluding the producing agent's own file).
* 5. Registry roster coverage: every agents/*.md file has exactly one
* row, every row names an agent file that exists
* (agent_without_contract / duplicate_registry_row / unknown_producer),
* and every file-shaped `Consumed by` entry resolves (unknown_consumer).
* 6. Read-tag arm: no `<files_to_read>` survives anywhere in the consumer
* corpus (legacy_read_tag), and whenever a declared consumer emits
* `<required_reading>` the producing agent's file must reference the
* gate (read_tag_gate_missing).
* 7. Reverse direction: a workflow/command matching a quoted `## TOKEN`
* no agent declares or emits is dispatch-on-phantom
* (unmatched_consumer_token) — F9's shape from the consumer side.
*
* Exit 0 = clean. Exit 1 = violations (with diagnostics on stderr).
*/
'use strict';
const fs = require('fs');
const path = require('path');
function resolveRoot(argv) {
const idx = argv.indexOf('--root');
if (idx === -1) return path.join(__dirname, '..');
const value = argv[idx + 1];
if (!value) {
throw new Error('check-contract-drift: --root requires a directory argument');
}
return path.resolve(value);
}
const ROOT = resolveRoot(process.argv.slice(2));
const CONTRACTS_FILE = path.join(ROOT, 'gsd-core', 'references', 'agent-contracts.md');
const AGENTS_DIR = path.join(ROOT, 'agents');
const WORKFLOWS_DIR = path.join(ROOT, 'gsd-core', 'workflows');
const COMMANDS_DIR = path.join(ROOT, 'commands');
const {
extractMarkers,
parseAgentContracts,
contractViolations,
readTagViolations,
parseConsumedByCell,
unmatchedConsumerTokens,
sanitizeEcho,
REMEDIES,
} = require('./command-contract-helpers.cjs');
const { runMain } = require('./lib/cli-exit.cjs');
// ─── helpers ────────────────────────────────────────────────────────────────
function walkMarkdownFiles(dir, acc) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return acc;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
walkMarkdownFiles(full, acc);
} else if (entry.isFile() && entry.name.endsWith('.md')) {
acc.push(full);
}
}
return acc;
}
function toRepoRelative(absPath) {
return path.relative(ROOT, absPath).split(path.sep).join('/');
}
/**
* referenceIncludes(content)
*
* Plain scan for `@~/.claude/gsd-core/references/*.md` tokens anywhere in an
* agent file's content -- inside an `<execution_context>` block (already
* covered structurally by `executionContextRefs` in command-contract-helpers,
* but a raw regex over the whole string picks those up too) and, just as
* importantly, OUTSIDE one: agents frequently point at a reference doc from
* plain prose (e.g. "See @~/.claude/gsd-core/references/planner-guidance.md
* for ...") rather than from the eager `<execution_context>` include list.
* An agent's completion-marker contract can be authored in such a reference
* file rather than the agent file itself -- gsd-planner declares
* `PLANNING COMPLETE` in its registry row, but the example heading itself
* lives in `gsd-core/references/planner-guidance.md`, which the agent only
* `@`-includes -- so the producer scan below must follow these includes to
* see markers an agent's contract legitimately delegates to a reference doc.
* Returns ROOT-relative paths (`gsd-core/references/foo.md`), de-duplicated.
*/
function referenceIncludes(content) {
const seen = new Set();
const re = /@~\/\.claude\/gsd-core\/references\/[A-Za-z0-9._-]+\.md/g;
let m;
while ((m = re.exec(content)) !== null) {
const relPath = 'gsd-core/references/' + m[0].slice('@~/.claude/gsd-core/references/'.length);
seen.add(relPath);
}
return [...seen];
}
function remedyFor(kind) {
return REMEDIES[kind] || 'review the registry row and agent file for drift';
}
// ─── run ─────────────────────────────────────────────────────────────────────
function main() {
if (!fs.existsSync(CONTRACTS_FILE)) {
process.stderr.write(`\nERROR check-contract-drift: contracts file not found at ${toRepoRelative(CONTRACTS_FILE)}\n\n`);
return 1;
}
const contractsMd = fs.readFileSync(CONTRACTS_FILE, 'utf-8');
const { rows: registry, errors: parseErrors } = parseAgentContracts(contractsMd);
// knownMarkers: every marker string declared anywhere in the registry --
// extractMarkers only ever resolves a heading against this vocabulary, it
// never falls back to guessing a shape. Includes `(unconsumed: …)` entries
// so their declared↔emitted agreement is checked too.
const knownMarkers = new Set();
for (const row of registry) {
for (const m of row.completion_markers || []) knownMarkers.add(m);
for (const m of row.unconsumed_markers || []) knownMarkers.add(m);
}
// producerMarkers: agent -> [in-fence marker strings that matched knownMarkers]
// candidateMarkers: agent -> [in-fence marker-shaped headings NOT in knownMarkers,
// deduped per marker — "emitted but undeclared" is a fact about the
// marker, not about each line or file it appears in]
// agentTexts: agent -> file content CONCATENATED with every
// references/*.md file the agent @-includes, for the read-tag arm's gate
// check. The fold is load-bearing: planner/executor/phase-researcher
// deliver the MUST-Read gate via the shared mandatory-initial-read.md
// include, so the agent file alone would report a gate that actually
// arrives (the same producer-scope gap referenceIncludes() fixes for
// markers, one layer up).
const producerMarkers = new Map();
const candidateMarkers = new Map();
const agentTexts = new Map();
const unclosedFenceViolations = [];
// #4407: .compact.md variant siblings are an alternate rendering of their
// canonical agent's SAME contract, not a distinct one — excluded so they
// don't need (and can't drift from) their own registry row.
const agentFiles = fs.existsSync(AGENTS_DIR)
? fs.readdirSync(AGENTS_DIR).filter(f => f.endsWith('.md') && !f.endsWith('.compact.md'))
: [];
for (const file of agentFiles) {
const agent = file.replace(/\.md$/, '');
const abs = path.join(AGENTS_DIR, file);
const content = fs.readFileSync(abs, 'utf-8');
// Single pass over the agent's @-included references: each file is read
// once and feeds BOTH the read-tag fold (agentTexts) and marker
// extraction (producer/candidate attribution).
const includeTexts = [];
for (const refRelPath of referenceIncludes(content)) {
try {
includeTexts.push(fs.readFileSync(path.join(ROOT, refRelPath), 'utf-8'));
} catch {
// include miss — lint-command-contract rule 4 owns @-ref existence
}
}
agentTexts.set(agent, [content, ...includeTexts].join('\n'));
const { markers, candidates, unclosedFence } = extractMarkers(agentTexts.get(agent), knownMarkers);
const inFenceMarkers = markers.filter(m => m.inFence).map(m => m.marker);
const inFenceCandidates = candidates.filter(m => m.inFence).map(m => m.marker);
producerMarkers.set(agent, inFenceMarkers);
candidateMarkers.set(agent, [...new Set(inFenceCandidates)]);
if (unclosedFence) {
unclosedFenceViolations.push({
kind: 'unclosed_fence',
agent,
marker: null,
detail: `${toRepoRelative(abs)} has an unterminated code fence`,
});
}
}
// consumerTexts: every *.md under gsd-core/workflows/, commands/, agents/
// — plus every file-shaped `Consumed by` entry that resolves on disk, so
// a row citing a reference doc or an ADR (e.g. intel-updater's
// docs/adr/22-plan-drift-guard.md) is validated against the real file and
// its text participates in consumer matching, not just workflows.
const consumerTexts = new Map();
const consumerDirs = [WORKFLOWS_DIR, COMMANDS_DIR, AGENTS_DIR];
for (const dir of consumerDirs) {
for (const abs of walkMarkdownFiles(dir, [])) {
consumerTexts.set(toRepoRelative(abs), fs.readFileSync(abs, 'utf-8'));
}
}
for (const row of registry) {
for (const rel of parseConsumedByCell(row.consumed_by)) {
if (consumerTexts.has(rel)) continue;
const abs = path.join(ROOT, rel);
try {
consumerTexts.set(rel, fs.readFileSync(abs, 'utf-8'));
} catch {
// absent — contractViolations reports it as unknown_consumer
}
}
}
const contractViolationsList = contractViolations({ registry, producerMarkers, candidateMarkers, consumerTexts });
const readTagViolationsList = readTagViolations({ registry, agentTexts, consumerTexts });
const reverseViolationsList = unmatchedConsumerTokens({ consumerTexts, vocabulary: knownMarkers });
const parseViolations = parseErrors.map(e => ({
kind: 'parse_error',
agent: null,
marker: null,
detail: `agent-contracts.md:${e.line} — ${e.reason}`,
}));
const allViolations = [
...parseViolations,
...unclosedFenceViolations,
...contractViolationsList,
...readTagViolationsList,
...reverseViolationsList,
];
const agentCount = registry.length;
const markerCount = registry.reduce((n, r) => n + (r.completion_markers || []).length, 0);
// --json: the typed surface tests consume (CONTRIBUTING "Raw Text
// Matching" rule — the human formatter below is for operators only).
if (process.argv.includes('--json')) {
console.log(
JSON.stringify({
check: 'check-contract-drift',
status: allViolations.length === 0 ? 'ok' : 'violations',
agents: agentCount,
markers: markerCount,
violations: allViolations.map((v) => ({
kind: v.kind,
agent: v.agent ?? null,
marker: v.marker ?? null,
detail: sanitizeEcho(v.detail),
})),
}),
);
return allViolations.length === 0 ? 0 : 1;
}
if (allViolations.length === 0) {
console.log(`ok check-contract-drift: ${agentCount} agents, ${markerCount} markers, 0 violations`);
return 0;
}
// group by violation kind
const byKind = new Map();
for (const v of allViolations) {
if (!byKind.has(v.kind)) byKind.set(v.kind, []);
byKind.get(v.kind).push(v);
}
process.stderr.write(
`\nERROR check-contract-drift: ${allViolations.length} violation(s) across ${byKind.size} kind(s)\n\n`,
);
for (const [kind, violations] of byKind) {
process.stderr.write(` ${kind} (${violations.length}):\n`);
for (const v of violations) {
const agentLabel = v.agent ? sanitizeEcho(v.agent) : '(registry)';
const markerLabel = v.marker ? ` marker "${sanitizeEcho(v.marker)}"` : '';
process.stderr.write(` - ${agentLabel}${markerLabel}: ${sanitizeEcho(v.detail)}\n`);
process.stderr.write(` remedy: ${remedyFor(kind)}\n`);
}
process.stderr.write('\n');
}
process.stderr.write('See gsd-core/references/agent-contracts.md for the registry contract spec.\n\n');
return 1;
}
runMain(main);