* test(#3413): failing-first suite for the line-terminator seam Phase 2 of epic #3212 (ADR-3212 §3/§6/§7). Tests only — src/text-lines.cts does not exist yet, so tests/text-lines.test.cjs fails with MODULE_NOT_FOUND at its require line, which is the intended RED. The frontmatter.test.cjs additions drive #3360 (confirmed-bug) fail-first: parseMustHavesBlock currently returns [] for every must_haves block on a CRLF-authored plan file, because \r is its own LineTerminator in ECMAScript and two /m-anchored \s* patterns can absorb it, inflating a captured indent by one character and tripping the "not nested under must_haves" guard. Verified locally against the current (unfixed) compiled module: both the direct repro and the silent-exit "blank line before must_haves:" variant return [] today. A parity property test (crlf vs lf must deep-equal for every block name) matches a pattern this maintainer has required repeatedly for prior CRLF fixes in this codebase (Cortex-recorded, verify_intent=held). The no-crlf-fragile-split.rule.test.cjs additions lock the eslint rule's future fix-hint text (pointing at splitLines()) and its self-reference non-violation (the seam's own correct \r?\n split must never flag itself). Design: .gsd/phase/chore-3413-text-lines-seam/40-design.md Test matrix: .gsd/phase/chore-3413-text-lines-seam/50-test-matrix.md * chore(#3413): src/text-lines.cts owns line-terminator handling Phase 2 of epic #3212 (ADR-3212 §3/§6/§7). Adds splitLines/normalizeEol/ detectEol/joinLines and migrates frontmatter.cts onto it. parseMustHavesBlock (#3360, confirmed-bug) returned [] for every must_haves block on a CRLF plan file. Root cause: \r is its own LineTerminator in ECMAScript, so under /m two \s*-anchored indentation lookups could match at the position INSIDE a \r\n pair and absorb the terminator, inflating the captured indent by one character and tripping the "not nested under must_haves" guard. Two silent exits, one with a diagnostic and one without (a blank line before must_haves: hits the silent path). Fixed by converting both lookups from a whole-string /m match to split-then-scan — splitLines first, then a per-line, non-/m match — the same structural pattern parseYamlRegion (30 lines away in the same file) already used safely. Nothing downstream of the two lookups changed; blockLines is now sliced from the already-split array instead of re-splitting a substring, but its contents are unchanged for LF input, and the per-line dash/kv parsing loop is untouched. A parity property test (CRLF and LF plans parse to identical must_haves for every block name) matches a pattern this maintainer has required repeatedly for prior CRLF fixes in this file's neighborhood (Cortex: 7 recorded decisions, verify_intent -> held). frontmatter.cts's other .split(/\r?\n/) call sites (parseYamlRegion, isFrontmatterShaped, sliceTopLevelFrontmatterSegments, spliceFrontmatter) are rerouted onto splitLines — a literal 1:1 substitution, zero behavior change, since splitLines IS that same regex plus a type guard. The 4 scripts/normalizeLineEndings copies (gen-registry, gen-loop-host- contract, gen-capability-registry, gen-context-index) are deleted and rerouted onto normalizeEol, which strips a bare unpaired \r exactly like the deleted copies did (not just \r\n pairs) -- verified against each script's own --check mode against its real generated output. local/no-crlf-fragile-split widens from tests/ to src/**/*.cts, with its fix-hint message now naming splitLines() instead of the raw regex -- the prohibition finally has a primitive to point at. Detection logic unchanged in this phase (deliberate scope limit, see design doc Known limits: the rule doesn't yet recognize safeReadFile/platformReadSync as a content source, and has no detector for the \s-adjacent-to-anchor shape that is #3360's actual mechanism -- the CLASS is converged by the direct fix + regression test regardless). joinLines/detectEol are NOT wired into frontmatter.cts's own write path (cmdFrontmatterSet/Merge -> platformWriteSync) -- verified that platformWriteSync already, unconditionally converts CRLF->LF on every .md write today as a pre-existing policy owned by a different module, and ADR-3212's backward-compatibility clause rules out a file-format change in any phase. Stated explicitly in Known limits rather than left for a reader to discover. Six-gate ripple: .gitignore, eslint.config.mjs (src/**/*.cts block), docs/INVENTORY.md + INVENTORY-MANIFEST.json (regenerated), CONTEXT.md glossary (Text Lines Module, mirroring Phase 1's Pattern Module entry). Design: .gsd/phase/chore-3413-text-lines-seam/40-design.md Test matrix: .gsd/phase/chore-3413-text-lines-seam/50-test-matrix.md * fix(#3413): fix 13 pre-existing CRLF-fragile splits the widened rule found Widening local/no-crlf-fragile-split from tests/ to src/**/*.cts (the previous commit) immediately surfaced 13 real, pre-existing violations across 10 files -- undetected until now because the rule never scanned src/. This is the exact defect class ADR-3212 exists to close, playing out again one phase after Phase 1 hit the same shape ("the new lint rule -- once live -- found 27 more"). Per CLAUDE.md's no-defer rule, fixed inline rather than deferred or suppressed; there is no established suppression convention for this rule in src/ and inventing one now would undermine the point of widening it. audit.cts, broken-windows.cts, core-utils.cts, init.cts, milestone.cts, phase.cts (x3), profile-output.cts, roadmap.cts (x2): bare-\n splits or regex character classes widened to \r?\n / [^\r\n], each following the same pattern already established migrating frontmatter.cts. phase-estimation.cts: `\r?(?:\n|$)` restructured to `(?:\r?\n|\r?$)` -- already semantically CRLF-safe, but the rule's lexical scanner doesn't recognize \r? guarding a group (only \r? immediately before a literal \n). Verified the two forms are equivalent across all four EOL/EOF cases before restructuring, not assumed. roadmap-upgrade.cts needed two coupled sites, not the one flagged line: computeMigrationPlan and applyMigration must agree on line representation for the lines[edit.lineIndex] === edit.from equality check to hold, and the write-back needed joinLines + detectEol -- a plain lines.join('\n') was silently flattening a CRLF ROADMAP.md to LF wholesale on every migration. This is the first real production consumer of joinLines/detectEol in this epic (frontmatter.cts's own write path doesn't use them -- see the previous commit's Known limits). Fixing the 13 flagged sites surfaced 4 more adjacent same-shape sites the rule doesn't track (.search() and new RegExp(dynamicString) aren't in its tracked call/construction set). Investigated each empirically -- hand-tracing this exact bug class already produced one wrong conclusion earlier in this phase (a detectEol design-doc arithmetic error), so these were verified with real CRLF fixtures rather than reasoned about on paper: - audit.cts (scanTodos): REAL bug, fixed. `bodyMatch.trim().split ('\n')[0]` leaked a trailing \r into a user-visible todo summary on CRLF input -- .trim() only strips the string's outer edges, not a \r sitting mid-string before the first bare \n. Now splitLines(...) [0]. - phase.cts (cmdPhaseInsert, bullet-style branch): REAL bug, fixed. [^\n]* in targetBulletPattern swallowed a line's trailing \r on CRLF input, shifting the computed insert position to land INSIDE the \r\n pair; combined with a hardcoded '\n' bullet separator, a CRLF ROADMAP.md ended up with a mixed CRLF/LF result after an insert. Fixed with two coupled changes (either alone still corrupts, verified both ways): [^\r\n]* in the pattern, and the new bullet's leading terminator now comes from detectEol(rawContent). - roadmap.cts (cmdRoadmapAnnotateDependencies phase-boundary scan): investigated, genuinely safe, left untouched. The .search(/\n#{2,4} .../) boundary-finder and the [^\n]*-based heading match were empirically verified on a 3-phase CRLF fixture -- the only stray \r ends up at the tail of an intermediate phaseSection string that is only ever used for .test()-based idempotency checks, never for an exact-match comparison or written back to disk. No corruption on round-trip. Every fix re-verified: npm run build:lib clean, npx eslint 'src/**/*.cts' --no-cache reports 0 problems (was 13), and each fixed function's existing LF-input tests were spot-checked unchanged. * fix(#3413): apply orthogonal review findings Two isolated review engines (correctness + security) ran against the full diff and found three majors, one real security issue, and several disclosure-worthy minors. All fixed or explicitly disclosed with evidence; nothing deferred. MAJOR — detectEol's tie-break contradicted its own documented contract. Code returned '\n' on a 1:1 crlf/bare-LF tie; every doc (design doc, CONTEXT.md, the function's own comment) says ties resolve to '\r\n'. The existing test masked this by reusing the same tie fixture the buggy code happened to satisfy, rather than a genuine LF-majority case. Root cause: an Edit attempted earlier in this phase to fix this exact arithmetic error was blocked by the tier guard, and a later dispatch was incorrectly told it had already landed. Fixed: condition is now crlfCount >= bareLfCount; the test fixture corrected to a genuine 2:1 majority, with a new explicit tie-case test. MAJOR — phase.cts's cmdPhaseInsert built an EOL-aware bulletEntry via detectEol(rawContent), justified by a comment claiming a hardcoded '\n' corrupts a CRLF ROADMAP.md. False: this write goes through platformWriteSync, whose normalizeContent/_normalizeMd unconditionally converts CRLF->LF for any .md target — the templating was inert dead code, erased before the file is ever written. Reverted to hardcoded '\n', comment corrected to state the true reasoning. The separate [^\n]* -> [^\r\n]* widening one function up (a real splice-position fix, independent of final EOL) was kept. MAJOR — roadmap-upgrade.cts's stated rationale for switching onto splitLines/joinLines was wrong (both functions always agreed on line representation, before and after — the claimed equality-check risk never existed), and the change it justified introduced a real regression: forcing every line onto one dominant terminator silently rewrites untouched lines' EOL on a mixed-CRLF/LF ROADMAP.md. This write path uses raw fs.writeFileSync, not platformWriteSync, so unlike the phase.cts case above the regression is genuinely live. Fixing this took two attempts. The first attempt (revert to split('\n')/join('\n') plus a suppression comment) was correctly blocked by an agent that discovered local/no-crlf-fragile-split is a PROTECTED_RULES entry in tests/portability-rule-disable-ban.test.cjs — a hard, out-of-band, ADR-1703-governed guardrail banning any eslint-disable of this rule anywhere in src/**/*.cts. That agent also detected and correctly disregarded an injected instruction that appeared in tool output during a git operation, per this session's untrusted-content policy. The actual fix: computeMigrationPlan reverted to roadmapContent.split('\n') (confirmed lint-clean — the rule's data-flow tracking only follows a variable's initializer, and this one is declared empty then reassigned in a try block). applyMigration's write-back now splices edits against the ORIGINAL content string via indexOf('\n', pos) boundary-walking instead of a full split/rejoin, so every untouched character — including every line's own terminator — is copied byte-for-byte. A capture-group split (/(\r\n|\n)/, preserving terminators inline) was tried first and empirically confirmed to still trip the rule before this approach was chosen instead. MINOR (security) — roadmap.cts's cmdRoadmapAnnotateDependencies used the STRING form of String#replace, so $&, $`, $', $1-$9 inside must_haves.truths content (author-controlled) were interpreted as replacement directives, splicing unrelated ROADMAP.md text into the result. Fixed with the function-replacement form, which is never pattern-interpreted. Verified before/after with the reviewer's exact repro. Also disclosed rather than silently left: test matrix row 31 (four planned CRLF-materialized regression tests) was never implemented as separate files — corrected to record the actual verification (a manual --check run plus incidental existing coverage via each script's normalizeLineEndings: normalizeEol alias). parseMustHavesBlock's LF behavior was claimed byte-for-byte unchanged but the old yaml.indexOf(blockMatch[0]) substring search could match an unrelated earlier occurrence of the header text (e.g. inside a quoted value) — the split-then-scan fix incidentally also closes this, a strict improvement now recorded in the design doc rather than left implicit. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3413): checkpoint 2 red — missing eslint ignore entry, RuleTester config error Checkpoint 2 came back red with 5 failures on the reviewed sha, both gaps genuinely undetectable by any local gate. eslint.config.mjs was missing the 'gsd-core/bin/lib/text-lines.cjs' ignores-list entry (ADR-457: generated .cjs artifacts are excluded from direct type-aware linting). Phase 1's sibling entry (pattern.cjs) sits two lines above it and was the exact precedent read while researching the six-gate ripple for this module -- missed anyway. Caught by tests/repo-invariants.test.cjs's bin/lib coverage-tracking test, which only runs on the remote suite. tests/no-crlf-fragile-split.rule.test.cjs's row-32 case specified both `messageId` and `message` on the same RuleTester error assertion -- ESLint's RuleTester rejects that combination outright. This existed since the test was first authored and was never caught locally: `npx eslint` only lints the file's syntax, it does not execute RuleTester, and local `node --test` is hard-blocked in this repo -- the assertion had never actually RUN before this checkpoint. It was even present in checkpoint 1's failure list, listed there as one of the "expected RED" tests; I matched it against my expected-failures list by test NAME only and never inspected the actual failure detail closely enough to notice it was failing for the wrong reason (a RuleTester config error, not the intended message-text mismatch). Fixed by keeping `message` (the exact-text assertion the test exists to make) and dropping `messageId`. Verified the crlfFragileSplit message string in eslint-rules/no-crlf-fragile-split.cjs matches this assertion character-for-character, and swept every other invalid case in the file for the same double-specification bug (none found -- all pre-existing cases use messageId alone). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(#3413): add Fixed changeset for the #3360 CRLF parsing fix The sole user-visible effect of this phase. No breaking-change label or Changed fragment needed — ADR-3212's Backward Compatibility section names the Node floor (Phase 1, already shipped) as the epic's only breaking change; Phase 2 has none. * chore(#3413): backfill changeset pr number to 3420 --------- Co-authored-by: sim <sim@local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
507 lines
18 KiB
JavaScript
507 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 { normalizeEol } = require('../gsd-core/bin/lib/text-lines.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');
|
|
}
|
|
|
|
// ─── 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 (normalizeEol(committed) !== normalizeEol(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: normalizeEol,
|
|
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);
|
|
}
|