* test(#3412): failing-first suite for the pattern-construction seam Phase 1 of epic #3212 (ADR-3212 §1/§2/§7). Tests only — src/pattern.cts and eslint-rules/no-adhoc-regex-escape.cjs do not exist yet, so both suites fail with MODULE_NOT_FOUND, which is the intended RED. Locks the measured behavior rather than the assumed behavior: RegExp.escape hex-escapes the leading character of nearly every string ("abc" -> "\x61bc"), so the suite asserts match-equivalence against an inlined historical oracle (the implementation being deleted) rather than byte-equivalence of pattern text — 200 seeded fast-check runs plus a fixed corpus, 0 mismatches. Also locks the latent character-class range bug this phase fixes as a side effect: a hyphen-bearing value interpolated into [...] currently forms a real range and matches an unintended character; post-migration it must not. * chore(#3412): src/pattern.cts owns runtime-value regex construction Phase 1 of epic #3212 (ADR-3212 §1/§2/§6/§7). Adds the pattern seam delegating to the built-in RegExp.escape, deletes every hand-rolled copy, and raises the Node floor to the Active LTS line. The census was low, three times over. ADR-3212 counted 10 copies; a graph query found 12; the new lint rule — once live — found 27 more. The difference is that the census counted named helper FUNCTIONS while the rule counts the escape SHAPE, so inline .replace(<class>, '\$&') copies were never in scope. ADR §1's actual requirement is that no module outside the seam escapes a value for regex use, so all of them are, and CLAUDE.md's no-defer rule makes them this change's work. Fourth consecutive epic here whose copy count was low — the argument for ADR-3180 Amendment 3's "state N found by the guard" rule. Also corrected mid-implementation: the survey reported phase-id.cts's escapeRegex had 0 external importers. It had 8 production importers, making its removal a public-surface change to an ADR-2121-owned module and requiring an update to that ADR's locked-surface test. Blast radius revised Medium-High -> High. RegExp.escape is match-equivalent but NOT text-equivalent: it hex-escapes the leading char of nearly every string ("abc" -> "\x61bc"). Equivalence is proven by a seeded fast-check property test against the deleted implementation as oracle. It also fixes a latent bug: a hyphen-bearing value interpolated into a character class previously formed a real range and matched an unintended character. Node floor 22 -> 24 (RegExp.escape is Node 24+), across engines, .nvmrc, package-lock, 9 CI matrix entries, and 5 docs. The aggregate `required-tests` context is unchanged and no job was added or removed, so branch protection cannot be orphaned by the dropped lanes. Enforced by eslint-rules/no-adhoc-regex-escape.cjs (shape-matched, with structural provenance for reviewed pattern-fragment constants rather than a name heuristic) plus a whole-tree companion guard covering the directories ESLint's globs miss. * fix(#3412): close the _SOURCE guard evasion, correct two false claims Three findings from the orthogonal review pass, all fixed. 1. The ESLint rule's `_SOURCE` provenance fallback was pure identifier- name matching with no binding check, so `new RegExp(userInput_SOURCE)` — a function parameter — sailed past the guard. That is the same rename-evasion class issue #3410 documents, reopened by the very fallback meant to complement the structural check. Now bound to the identifier's actual binding kind: import, require-derived const, or module-scope const; parameters, `let`/`var`, and unresolvable bindings fail closed. Four RuleTester cases cover the evasion and prove the legitimate cross-module case still passes. 2. src/pattern.cts's own header carried the stale pre-correction counts (12 copies / 17 call sites) while CONTEXT.md and the design doc carried the corrected ones (~39 / ~44) — a self-contradiction inside the PR whose entire purpose is deleting divergent copies. Rewritten, preserving the durable lesson: a named-function census cannot see inline copies; only a shape-matching guard can. 3. The claim that all deleted copies threw TypeError on non-string was false. phase-id.cts's copy — the one with 8 external importers — did String(value).replace(...) and never threw. The seam's locked signature does not coerce, so this is a real, now-disclosed behavior change rather than the pure preservation the tests asserted. Audited all 32 invocations across the 8 importers and 6 in-file callers: every one is safe by construction (upstream truthy guard or a string-producing derivation), verified by runtime probe against the compiled modules rather than by TS compilation, which cannot see a runtime undefined. Corrected the false claim in both the test comment and the design doc, and added it to Known limits. * docs(#3412): add Changed changeset for the Node 24 floor The only user-visible break in this phase. The escape-behavior change is internal and match-equivalent, so it carries no user-facing note. * fix(#3412): resolve the seam's require graph in script fixtures and packaging Checkpoint 2 came back red with 90 failures on the node24 lane. Three distinct defects, all introduced by routing scripts/ through the new pattern seam, none reproducible by any local gate: 1. ~82 failures — tests/adr-index-gate.test.cjs and tests/removed-but-needed-lint.test.cjs copy a scripts/*.cjs into an mkdtemp fixture and spawn it there (necessary: those scripts resolve their scan root from __dirname/.., so running the real script would scan the real repo). Each harness hand-listed the dependencies to copy alongside. Adding require('../gsd-core/bin/lib/pattern.cjs') to gen-adr-index.cjs made both lists silently incomplete -> MODULE_NOT_FOUND, plus 17 downstream 'did not emit parseable JSON' failures from the same crash. Fixed as a class, not an instance: new tests/helpers/copy-script- fixture.cjs walks a script's transitive static relative-require graph and copies it, so dependencies are derived and never re-declared. It throws (naming the unbuilt artifact) instead of letting the child die with a bare MODULE_NOT_FOUND. Verified for all four seam-consuming scripts: gen-adr-index, lint-removed-but-needed, gen-loop-host- contract, sync-runtime-launcher. 2. 2 failures — scripts/ ships wholesale but eslint-rules/ does not, so the new scripts/lint-no-adhoc-regex-escape.cjs would be MODULE_NOT_FOUND in a published install (#2858 guard). Excluded from the tarball, matching the existing precedent for gen-emitted- baseline.cjs, which is excluded for the identical reason, and locked with a test modeled on that one. Confirmed against a real npm pack: 890 files, 0 from eslint-rules/, and gsd-core/bin/lib/pattern.cjs present (so the other four scripts' requires are legitimate). 3. 6 failures — tests/phase-id.test.cjs asserted the literal escaped source text ('0*29', 'PROJ-42'). RegExp.escape is match-equivalent to the retired hand-rolled escaper but NOT text-equivalent: it hex- escapes the leading character and all hyphens ('0*\x329', '\x50ROJ\x2d42'). Verified NOT a behavior change — 576 match decisions across all three real interpolation prefixes, zero divergence. Those tests now compile each source into the same heading regex src/roadmap.cts's searchPhaseInContent builds and assert what matches and what does not, including the 'i'-flag canonicalization the hex escape has to preserve. Re-pinning the new literals would have rebuilt the same brittleness one layer down. Adds a test for the property the escape exists for: a dot in '1.2' must not act as a wildcard. Also shares one definition of 'a require' between the packaging guard and the fixture copier, so the two cannot disagree about what they scan. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3412): refuse to copy a fixture dependency outside the fixture root copyScriptWithDeps resolved each relative require and joined the repo-relative result onto fixtureRoot. A require resolving OUTSIDE the repo yields a '../'-prefixed relative path, so path.join climbed out of the fixture and wrote into the surrounding temp dir (verified: repoRoot=/repo + depAbs=/etc/passwd wrote /tmp/etc/passwd). No script in the tree does this today, so this closes an available escape rather than an active one. Refuses via the existing unresolved- require path so the failure names the offending specifier. Covered by a negative proof that the guard fires and that nothing lands outside the fixture. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3412): parse requires instead of pattern-matching them; restore the foreign-prefix contract Applies all findings from the second orthogonal review round, re-run because real code changed after round 1. HIGH (security) — extractRequires stripped BLOCK comments before LINE comments, so a '//' comment containing '/*' opened a phantom block comment, and a '//' inside a string literal truncated the line. Both hid real requires: 'const u="http://x"; require("./real.cjs")' returned [], and four real requires in gsd-core/bin/gsd-tools.cjs were invisible. Replaced with a real AST parse via espree. This is ADR-3212's own Decision 4 — tokenizer-first for stateful grammars — applied to the case it describes; comment/string/regex nesting is exactly such a grammar, which is why the regex version was wrong. The function was moved byte-identical out of the #2858 packaging guard, so the bug PRE-DATES this branch and has been a live blind spot there: a shipped script could have required an unshipped path undetected. Fixing it makes that guard strictly stronger than on next. espree is promoted from a transitive eslint dependency to an explicit devDependency rather than relying on hoisting. The script parse attempt sets ecmaFeatures.globalReturn because Node wraps CommonJS bodies in a function, making a top-level return legal — scripts/check-coverage-gate .cjs relies on it, and without the flag the guard throws on a file it is supposed to scan. Verified 0 unparseable across all 324 .cjs/.js under scripts/, bin/, and gsd-core/bin/, and 0 new violations against a real npm pack, so the exact extractor does not newly fail the guard. MEDIUM (security) — the repo-containment check guarded dependencies but not the entry path. One escapesContainment predicate now guards both. LOW (security) — containment was lexical while fs follows symlinks, and a directory symlink could mint a fresh dedupe key per level. realpath now resolves both repoRoot and each dependency before the decision, and the realpath-derived path is the dedupe key. Destination layout still uses the original repo-relative path, so copied trees are unchanged. MAJOR (standards) — the round-1 behavioral rewrite of phase-id tests lost the foreign-prefix contract: every assertion was satisfied by an impl returning [A-Z]+\x2d42, i.e. ANY project code — the exact #3599 bug class the exact-source prevents. The literal assertions it replaced were catching this. Now asserts the compiled regex REJECTS a different prefix with the same number. MAJOR (standards) — the test hand-duplicated production's heading regex with no parity guard (CLAUDE.md's 'Generative Fix Divergence'). Removed the parallel surface instead of policing it: src/roadmap.cts exports buildPhaseHeadingRegex, searchPhaseInContent calls it, the test imports it. Byte-identical .source and .flags verified for both escaped forms. MINOR — '..foo' no longer false-flagged as an escape; the inverted spurious-vs-missing doc claim corrected; the dead allow-test-rule header removed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(#3412): backfill changeset pr number to 3416 * fix(#3412): make the escape guard's own regex linear, reword an injection-scan collision Two CI failures on PR #3416, both in code this branch added. CodeQL js/redos (high) — REPLACE_CALL_RE's outer alternation let a bracket run be consumed EITHER by the character-class branch OR one character at a time by the trailing catch-all, so a failing match explored both parses of every pair. Measured on the real regex: n=26 -> 204ms, n=28 -> 791ms, n=30 -> 3475ms, a clean 2^n. This script scans repo source, so a file with a long bracket run after '.replace(/' would hang CI outright — a guard against undisciplined pattern construction was itself the worst pattern in the diff. Fixed the way ADR-3212 already prescribes: the catch-all branch now excludes '[' and ']' so a bracket can only be consumed by the class branch (this is what makes it linear), and every quantifier is bounded (the locked bounded-quantifiers decision) as a second line of defense. Now 0ms at n=2000. Disclosed coverage tradeoff, recorded at the constant: a regex literal with a BARE unescaped ']' outside a class is no longer matched by this backstop. No census shape has that form, and the AST rule remains the primary detector. Verified the guard did not go blind doing it: a real census-shape violation is still reported, and an allow-adhoc-regex-escape suppression comment is still honored. Regression test drives the exported findViolations on a 2000-repetition adversarial input and asserts the RESULT. It makes no wall-clock assertion — elapsed-time tests are forbidden — so a regression surfaces as a harness timeout, which is the correct signal. Prompt injection scan — 'must not act as a regex wildcard' in a test comment matched the scanner's jailbreak pattern act\s+as\s+(a|an|if| my). Reworded to 'behave as'. Deliberately NOT allowlisted: silencing a whole test file over one phrase would blunt the scanner permanently, and the comment has nothing to do with injection. Neither failure was reachable from the remote runner — CodeQL and the injection scan are not in that matrix, so the sha it passed was green and still wrong. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: sim <sim@local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
521 lines
18 KiB
JavaScript
521 lines
18 KiB
JavaScript
#!/usr/bin/env node
|
|
'use strict';
|
|
|
|
/**
|
|
* gen-loop-host-contract.cjs — generates gsd-core/bin/lib/loop-host-contract.cjs
|
|
* from the <!-- gsd:loop-host ... --> blocks in the five step workflows.
|
|
*
|
|
* Usage:
|
|
* node scripts/gen-loop-host-contract.cjs # print to stdout
|
|
* node scripts/gen-loop-host-contract.cjs --write # write loop-host-contract.cjs
|
|
* node scripts/gen-loop-host-contract.cjs --check # exit 1 if committed file is stale
|
|
*
|
|
* ADR-894 phase 3a-impl-2. Parses structured markers from workflow files,
|
|
* cross-checks declared agent-roles against actual agent references in each
|
|
* workflow, asserts that the union of all points equals the 12 canonical points,
|
|
* and emits a committed CommonJS module exporting the contract array.
|
|
*/
|
|
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
|
|
const { ExitError, runMain } = require('./lib/cli-exit.cjs');
|
|
const { escapeRegex: escapeRegExp } = require('../gsd-core/bin/lib/pattern.cjs');
|
|
|
|
const ROOT = path.resolve(__dirname, '..');
|
|
const WORKFLOWS_DIR = path.join(ROOT, 'gsd-core', 'workflows');
|
|
const CONTRACT_PATH = path.join(ROOT, 'gsd-core', 'bin', 'lib', 'loop-host-contract.cjs');
|
|
|
|
// The five step workflows in pipeline order
|
|
const STEP_WORKFLOWS = [
|
|
{ file: 'discuss-phase.md', step: 'discuss' },
|
|
{ file: 'plan-phase.md', step: 'plan' },
|
|
{ file: 'execute-phase.md', step: 'execute' },
|
|
{ file: 'verify-work.md', step: 'verify' },
|
|
{ file: 'ship.md', step: 'ship' },
|
|
];
|
|
|
|
// Canonical 12 loop points in pipeline order
|
|
const CANONICAL_POINTS = [
|
|
'discuss:pre',
|
|
'discuss:post',
|
|
'plan:pre',
|
|
'plan:post',
|
|
'execute:pre',
|
|
'execute:wave:pre',
|
|
'execute:wave:post',
|
|
'execute:post',
|
|
'verify:pre',
|
|
'verify:post',
|
|
'ship:pre',
|
|
'ship:post',
|
|
];
|
|
|
|
// FIX 1: Per-step canonical point ownership. Each step must declare exactly these points.
|
|
const EXPECTED_POINTS_BY_STEP = {
|
|
discuss: ['discuss:pre', 'discuss:post'],
|
|
plan: ['plan:pre', 'plan:post'],
|
|
execute: ['execute:pre', 'execute:wave:pre', 'execute:wave:post', 'execute:post'],
|
|
verify: ['verify:pre', 'verify:post'],
|
|
ship: ['ship:pre', 'ship:post'],
|
|
};
|
|
|
|
// Role → agent-name mapping used for cross-check.
|
|
// Each non-orchestrator role must correspond to an actual agent reference in
|
|
// the workflow file (e.g. gsd-planner, gsd-executor, gsd-verifier, etc.).
|
|
const ROLE_TO_AGENT = {
|
|
researcher: 'gsd-phase-researcher',
|
|
planner: 'gsd-planner',
|
|
checker: 'gsd-plan-checker',
|
|
executor: 'gsd-executor',
|
|
verifier: 'gsd-verifier',
|
|
};
|
|
|
|
// ─── Parser ───────────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Parse a single <!-- gsd:loop-host ... --> block from file content.
|
|
* Returns a plain object with keys: step, points[], agentRoles[], produces[], consumes[].
|
|
* Throws a descriptive error if the block is malformed or missing.
|
|
*
|
|
* Block format (one key: value per line, comma-separated list values):
|
|
* <!-- gsd:loop-host
|
|
* step: plan
|
|
* points: plan:pre, plan:post
|
|
* agent-roles: researcher, planner, checker
|
|
* produces: PLAN.md
|
|
* consumes: CONTEXT.md
|
|
* -->
|
|
*
|
|
* For empty list values (e.g. "consumes:") the field is an empty array.
|
|
*
|
|
* @param {string} content File content
|
|
* @param {string} fileName For error messages
|
|
* @returns {{ step: string, points: string[], agentRoles: string[], coreArtifacts: { produces: string[], consumes: string[] } }}
|
|
*/
|
|
function parseLoopHostBlock(content, fileName) {
|
|
// FIX 2: Detect ALL marker blocks — more than one is a hard error.
|
|
const blockRe = /<!--\s*gsd:loop-host\s*([\s\S]*?)-->/g;
|
|
const allMatches = Array.from(content.matchAll(blockRe));
|
|
if (allMatches.length === 0) {
|
|
throw new Error(fileName + ': missing <!-- gsd:loop-host ... --> block');
|
|
}
|
|
if (allMatches.length > 1) {
|
|
throw new Error(
|
|
fileName + ': expected exactly one gsd:loop-host marker block, found ' + allMatches.length,
|
|
);
|
|
}
|
|
|
|
const blockBody = allMatches[0][1];
|
|
|
|
// FIX 2: Detect duplicate keys within the block.
|
|
const RECOGNIZED_KEYS = ['step', 'points', 'agent-roles', 'produces', 'consumes'];
|
|
const keyCounts = {};
|
|
for (const line of blockBody.split('\n')) {
|
|
const trimmed = line.trim();
|
|
for (const key of RECOGNIZED_KEYS) {
|
|
if (trimmed === key + ':' || trimmed.startsWith(key + ': ') || trimmed.startsWith(key + ':')) {
|
|
keyCounts[key] = (keyCounts[key] || 0) + 1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
for (const key of RECOGNIZED_KEYS) {
|
|
if (keyCounts[key] > 1) {
|
|
throw new Error(fileName + ': duplicate key \'' + key + '\' in gsd:loop-host marker');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Parse a field line: "key: value1, value2" → [value1, value2] (trimmed, empty strings removed)
|
|
*/
|
|
function parseField(key) {
|
|
// Split on newlines and find the line starting with "key:"
|
|
const lines = blockBody.split('\n');
|
|
for (const line of lines) {
|
|
const trimmed = line.trim();
|
|
if (trimmed === key + ':' || trimmed.startsWith(key + ': ') || trimmed.startsWith(key + ':')) {
|
|
const colonIdx = trimmed.indexOf(':');
|
|
const raw = trimmed.slice(colonIdx + 1).trim();
|
|
if (raw === '') return [];
|
|
return raw.split(',').map((s) => s.trim()).filter((s) => s.length > 0);
|
|
}
|
|
}
|
|
throw new Error(fileName + ': gsd:loop-host block missing required field "' + key + '"');
|
|
}
|
|
|
|
function parseScalar(key) {
|
|
const lines = blockBody.split('\n');
|
|
for (const line of lines) {
|
|
const trimmed = line.trim();
|
|
if (trimmed === key + ':' || trimmed.startsWith(key + ': ') || trimmed.startsWith(key + ':')) {
|
|
const colonIdx = trimmed.indexOf(':');
|
|
const val = trimmed.slice(colonIdx + 1).trim();
|
|
if (val === '') {
|
|
throw new Error(fileName + ': gsd:loop-host block field "' + key + '" must be a non-empty string');
|
|
}
|
|
return val;
|
|
}
|
|
}
|
|
throw new Error(fileName + ': gsd:loop-host block missing required field "' + key + '"');
|
|
}
|
|
|
|
const step = parseScalar('step');
|
|
const points = parseField('points');
|
|
const agentRoles = parseField('agent-roles');
|
|
const produces = parseField('produces');
|
|
const consumes = parseField('consumes');
|
|
|
|
if (points.length === 0) {
|
|
throw new Error(fileName + ': gsd:loop-host block "points" must have at least one value');
|
|
}
|
|
if (agentRoles.length === 0) {
|
|
throw new Error(fileName + ': gsd:loop-host block "agent-roles" must have at least one value');
|
|
}
|
|
|
|
return {
|
|
step,
|
|
points,
|
|
agentRoles,
|
|
coreArtifacts: { produces, consumes },
|
|
};
|
|
}
|
|
|
|
// ─── Cross-check: declared roles vs. actual agent references ─────────────────
|
|
|
|
/**
|
|
* For each non-orchestrator role in agentRoles, verify the workflow content
|
|
* contains a reference to the corresponding agent name.
|
|
*
|
|
* @param {string} content Full workflow file content
|
|
* @param {string[]} agentRoles Roles declared in the block
|
|
* @param {string} fileName For error messages
|
|
* @returns {string[]} Array of error strings; empty = OK
|
|
*/
|
|
function crossCheckRoles(content, agentRoles, fileName) {
|
|
const errors = [];
|
|
for (const role of agentRoles) {
|
|
if (role === 'orchestrator') continue; // orchestrator = host itself; no agent file needed
|
|
const agentName = ROLE_TO_AGENT[role];
|
|
if (!agentName) {
|
|
errors.push(
|
|
fileName + ': declared agent-role "' + role + '" has no entry in ROLE_TO_AGENT mapping',
|
|
);
|
|
continue;
|
|
}
|
|
// FIX 3: Use word-boundary match so "gsd-plan-checker-v2" does NOT satisfy a required
|
|
// "gsd-plan-checker". Treat '-' as part of the token: boundary = start/end of string or
|
|
// a character that is neither \w nor '-'.
|
|
// Note: this is a presence check (any reference in the file), not a spawn-site check —
|
|
// a known limitation; spawn-site checks would require AST-level analysis.
|
|
const agentRe = new RegExp(
|
|
'(^|[^\\w-])' + escapeRegExp(agentName) + '($|[^\\w-])',
|
|
);
|
|
if (!agentRe.test(content)) {
|
|
errors.push(
|
|
fileName + ': declared agent-role "' + role + '" maps to agent "' + agentName +
|
|
'" but "' + agentName + '" is not referenced anywhere in the workflow file',
|
|
);
|
|
}
|
|
}
|
|
return errors;
|
|
}
|
|
|
|
// ─── 12-points coverage assertion ────────────────────────────────────────────
|
|
|
|
/**
|
|
* Assert that the union of all points across all contract entries equals
|
|
* exactly the 12 canonical points (no more, no fewer), AND that each step
|
|
* declares exactly its own canonical points (FIX 1: per-step ownership).
|
|
*
|
|
* @param {{ step: string, points: string[] }[]} entries
|
|
* @returns {string[]} Error strings; empty = OK
|
|
*/
|
|
function assertPointsCoverage(entries) {
|
|
const errors = [];
|
|
|
|
// FIX 1: Per-step ownership check — each step must declare exactly its own canonical points.
|
|
for (const entry of entries) {
|
|
const expected = EXPECTED_POINTS_BY_STEP[entry.step];
|
|
if (!expected) continue; // unknown step — caught elsewhere
|
|
const expectedSet = new Set(expected);
|
|
const actualSet = new Set(entry.points);
|
|
let mismatch = false;
|
|
for (const p of expectedSet) {
|
|
if (!actualSet.has(p)) mismatch = true;
|
|
}
|
|
for (const p of actualSet) {
|
|
if (!expectedSet.has(p)) mismatch = true;
|
|
}
|
|
if (mismatch) {
|
|
errors.push(
|
|
'step "' + entry.step + '" declares points [' + entry.points.join(', ') +
|
|
'] but expected [' + expected.join(', ') + ']',
|
|
);
|
|
}
|
|
}
|
|
|
|
// Global union + duplicate check (belt and suspenders alongside per-step check).
|
|
const allPoints = new Set();
|
|
for (const entry of entries) {
|
|
for (const p of entry.points) {
|
|
if (allPoints.has(p)) {
|
|
errors.push('point "' + p + '" declared more than once across all step workflows');
|
|
}
|
|
allPoints.add(p);
|
|
}
|
|
}
|
|
|
|
const canonical = new Set(CANONICAL_POINTS);
|
|
for (const p of allPoints) {
|
|
if (!canonical.has(p)) {
|
|
errors.push('declared point "' + p + '" is not in the canonical 12-point set');
|
|
}
|
|
}
|
|
for (const p of canonical) {
|
|
if (!allPoints.has(p)) {
|
|
errors.push('canonical point "' + p + '" is not declared in any step workflow');
|
|
}
|
|
}
|
|
return errors;
|
|
}
|
|
|
|
// ─── Contract builder ─────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Read and parse all five step workflows. Returns the contract array.
|
|
* Throws on any parse or cross-check error.
|
|
*
|
|
* @param {string} [workflowsDir] Override for testing
|
|
* @returns {{ step: string, points: string[], agentRoles: string[], coreArtifacts: { produces: string[], consumes: string[] } }[]}
|
|
*/
|
|
function buildContract(workflowsDir) {
|
|
const resolvedDir = workflowsDir !== undefined ? workflowsDir : WORKFLOWS_DIR;
|
|
const contract = [];
|
|
const allErrors = [];
|
|
|
|
for (const { file, step } of STEP_WORKFLOWS) {
|
|
const filePath = path.join(resolvedDir, file);
|
|
let content;
|
|
try {
|
|
content = fs.readFileSync(filePath, 'utf8');
|
|
} catch (err) {
|
|
allErrors.push('Could not read ' + file + ': ' + String(err.message));
|
|
continue;
|
|
}
|
|
|
|
let entry;
|
|
try {
|
|
entry = parseLoopHostBlock(content, file);
|
|
} catch (err) {
|
|
allErrors.push(String(err.message));
|
|
continue;
|
|
}
|
|
|
|
// Validate the declared step matches the expected step for this file
|
|
if (entry.step !== step) {
|
|
allErrors.push(
|
|
file + ': gsd:loop-host block declares step "' + entry.step +
|
|
'" but expected "' + step + '"',
|
|
);
|
|
}
|
|
|
|
// Cross-check roles
|
|
const roleErrors = crossCheckRoles(content, entry.agentRoles, file);
|
|
allErrors.push(...roleErrors);
|
|
|
|
contract.push(entry);
|
|
}
|
|
|
|
if (allErrors.length > 0) {
|
|
throw new Error('Loop host contract generation failed:\n' + allErrors.map((e) => ' ' + e).join('\n'));
|
|
}
|
|
|
|
// Assert 12-points coverage
|
|
const pointErrors = assertPointsCoverage(contract);
|
|
if (pointErrors.length > 0) {
|
|
throw new Error('Loop host contract points coverage failed:\n' + pointErrors.map((e) => ' ' + e).join('\n'));
|
|
}
|
|
|
|
return contract;
|
|
}
|
|
|
|
// ─── Serialization ────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Serialize the contract array to a CommonJS module string.
|
|
*
|
|
* @param {object[]} contract
|
|
* @returns {string}
|
|
*/
|
|
function serializeContract(contract) {
|
|
const lines = [];
|
|
|
|
lines.push("'use strict';");
|
|
lines.push('');
|
|
lines.push('/**');
|
|
lines.push(' * loop-host-contract.cjs — generated by scripts/gen-loop-host-contract.cjs');
|
|
lines.push(' * DO NOT EDIT BY HAND. Run: node scripts/gen-loop-host-contract.cjs --write');
|
|
lines.push(' * ADR-894 §3 — Loop Host Contract, generated from workflow markers.');
|
|
lines.push(' * 12 points: discuss:pre/post, plan:pre/post, execute:pre/wave:pre/wave:post/post,');
|
|
lines.push(' * verify:pre/post, ship:pre/post. Per-step agentRoles and coreArtifacts.');
|
|
lines.push(' */');
|
|
lines.push('');
|
|
lines.push('const LOOP_HOST_CONTRACT = ' + JSON.stringify(contract, null, 2) + ';');
|
|
lines.push('');
|
|
lines.push('module.exports = { LOOP_HOST_CONTRACT };');
|
|
lines.push('');
|
|
|
|
return lines.join('\n');
|
|
}
|
|
|
|
// ─── --check diff helper ──────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* Normalize line endings to LF for CRLF-agnostic comparison.
|
|
* FIX 4: The serializer has no nondeterministic content (no timestamp), so
|
|
* the generated-by-line stripping that was here has been removed — full content
|
|
* comparison is now used so header drift is caught by --check.
|
|
*
|
|
* @param {string} content
|
|
* @returns {string}
|
|
*/
|
|
function normalizeLineEndings(content) {
|
|
return content.replace(/\r/g, '');
|
|
}
|
|
|
|
// ─── Main ─────────────────────────────────────────────────────────────────────
|
|
|
|
function main() {
|
|
const flag = process.argv[2];
|
|
|
|
if (flag === '--check') {
|
|
let contract;
|
|
try {
|
|
contract = buildContract();
|
|
} catch (err) {
|
|
process.stderr.write(String(err.message) + '\n');
|
|
throw new ExitError(1, 'loop-host contract generation failed');
|
|
}
|
|
const live = serializeContract(contract);
|
|
|
|
if (!fs.existsSync(CONTRACT_PATH)) {
|
|
process.stderr.write(
|
|
'gsd-core/bin/lib/loop-host-contract.cjs does not exist. Run:\n' +
|
|
' node scripts/gen-loop-host-contract.cjs --write\n',
|
|
);
|
|
throw new ExitError(1);
|
|
}
|
|
|
|
const committed = fs.readFileSync(CONTRACT_PATH, 'utf8');
|
|
// FIX 4: Compare full content (no generated-by stripping) so header drift is caught.
|
|
if (normalizeLineEndings(committed) !== normalizeLineEndings(live)) {
|
|
process.stderr.write(
|
|
'gsd-core/bin/lib/loop-host-contract.cjs is stale. Run:\n' +
|
|
' node scripts/gen-loop-host-contract.cjs --write\n',
|
|
);
|
|
throw new ExitError(1);
|
|
}
|
|
|
|
process.stdout.write('gsd-core/bin/lib/loop-host-contract.cjs is up to date.\n');
|
|
} else if (flag === '--write') {
|
|
let contract;
|
|
try {
|
|
contract = buildContract();
|
|
} catch (err) {
|
|
process.stderr.write(String(err.message) + '\n');
|
|
throw new ExitError(1, 'loop-host contract generation failed — file not written');
|
|
}
|
|
const content = serializeContract(contract);
|
|
fs.mkdirSync(path.dirname(CONTRACT_PATH), { recursive: true });
|
|
fs.writeFileSync(CONTRACT_PATH, content, 'utf8');
|
|
process.stdout.write('Wrote ' + CONTRACT_PATH + '\n');
|
|
} else {
|
|
// Default: print to stdout
|
|
let contract;
|
|
try {
|
|
contract = buildContract();
|
|
} catch (err) {
|
|
process.stderr.write(String(err.message) + '\n');
|
|
throw new ExitError(1, 'loop-host contract generation failed');
|
|
}
|
|
process.stdout.write(serializeContract(contract) + '\n');
|
|
}
|
|
}
|
|
|
|
// ─── Derived single-source-of-truth exports ───────────────────────────────────
|
|
|
|
/**
|
|
* Repo-relative paths to every host-loop workflow file, derived from STEP_WORKFLOWS.
|
|
* This is the ONLY canonical enumeration of host-loop files — all consumers (tests,
|
|
* registry generator, conformance gate) must derive from this rather than maintaining
|
|
* a separate hardcoded list.
|
|
*/
|
|
const HOST_LOOP_FILES = STEP_WORKFLOWS.map((w) => 'gsd-core/workflows/' + w.file);
|
|
|
|
/**
|
|
* Pure function: scan a text string for `loop render-hooks <point>` call sites.
|
|
* Returns a Set of matched point strings.
|
|
*
|
|
* @param {string} text Content of a workflow file (or any text).
|
|
* @returns {Set<string>}
|
|
*/
|
|
function scanWiredPoints(text) {
|
|
const re = /loop render-hooks\s+([a-z:]+)/g;
|
|
const result = new Set();
|
|
let m;
|
|
while ((m = re.exec(text)) !== null) {
|
|
result.add(m[1]);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* Read every host-loop workflow file and return the union of all wired loop points
|
|
* (i.e. points that have a `loop render-hooks <point>` call site).
|
|
*
|
|
* @param {string} [repoRoot] Path to the repository root. Defaults to ROOT.
|
|
* @returns {Set<string>}
|
|
*/
|
|
function getWiredLoopPoints(repoRoot) {
|
|
const resolvedRoot = repoRoot !== undefined ? repoRoot : ROOT;
|
|
const result = new Set();
|
|
for (const relPath of HOST_LOOP_FILES) {
|
|
const absPath = path.join(resolvedRoot, relPath);
|
|
let content;
|
|
try {
|
|
content = fs.readFileSync(absPath, 'utf8');
|
|
} catch (err) {
|
|
throw new Error('getWiredLoopPoints: cannot read host-loop file ' + absPath + ': ' + err.message);
|
|
}
|
|
for (const point of scanWiredPoints(content)) {
|
|
result.add(point);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// ─── Exports (for tests) ─────────────────────────────────────────────────────
|
|
|
|
module.exports = {
|
|
parseLoopHostBlock,
|
|
crossCheckRoles,
|
|
assertPointsCoverage,
|
|
buildContract,
|
|
serializeContract,
|
|
normalizeLineEndings,
|
|
STEP_WORKFLOWS,
|
|
HOST_LOOP_FILES,
|
|
CANONICAL_POINTS,
|
|
EXPECTED_POINTS_BY_STEP,
|
|
ROLE_TO_AGENT,
|
|
scanWiredPoints,
|
|
getWiredLoopPoints,
|
|
};
|
|
|
|
// ─── CLI entry point ──────────────────────────────────────────────────────────
|
|
|
|
if (require.main === module) {
|
|
runMain(main);
|
|
}
|