chore(#2932): emit a per-invocation section manifest from the init bundle (#2987)

* chore(#2932): emit a per-invocation section manifest from init

Extends the init bundle with a typed per-invocation section manifest so an
invocation loads only the branch guidance it will actually take.

The three flag/state-gated branches in execute-phase.md move into their own
step files; the parent keeps its gsd:section markers wrapping a one-line
on-demand reference, so each section's prose lives in exactly one file and
the parent shrinks 93369 -> 89507 bytes. A new drift-guarded generator
derives the shipped section manifest from those markers, and a new pure
evaluator maps invocation facts to applicable section ids.

The evaluator is a lookup over the frozen WHEN_VOCABULARY, never a parser
(Greenspun's Tenth Rule, ADR-1671:69); a parity test asserts the vocabulary
and the predicate map stay exhaustively in sync.

Closes #2932

* fix(#2932): fail closed on prototype-chain when values

An isolated adversarial review found WHEN_PREDICATES[section.when] was a
bracket lookup on a plain-prototype object, so inherited Object.prototype
members resolved as predicates: "constructor"/"toString"/"valueOf"/
"hasOwnProperty" returned truthy and SILENTLY INCLUDED the section, and
"__proto__" threw an untyped TypeError carrying no .reason. Both violate
the module's documented fail-closed contract, and the manifest is read from
disk at run time so it cannot be assumed trustworthy.

Builds the predicate map on a null prototype and guards the lookup with an
explicit Object.hasOwn check. Adds table-driven coverage for nine
Object.prototype-shaped keys asserting the TYPED reason (asserting only
that it throws would still pass while broken) plus a fast-check property
injecting a hostile value at an arbitrary document position.

* test(#2932): retarget execute-phase step assertions at extracted step files

* fix(#2932): emit typed reasons for generator lib-load and write failures

* fix(#2932): restore launcher preamble in extracted steps and refresh derived fixtures

* chore(#2932): backfill changeset pr number to 2987

---------

Co-authored-by: sim <sim@local>
This commit is contained in:
Tom Boucher
2026-08-02 12:34:41 -04:00
committed by GitHub
parent 33985c11a9
commit a987cf2731
46 changed files with 2680 additions and 179 deletions

View File

@@ -99,7 +99,10 @@ const VERIFY_PHASE_PATH = path.join(__dirname, '..', 'gsd-core', 'workflows', 'v
const AUDIT_FIX_PATH = path.join(__dirname, '..', 'gsd-core', 'workflows', 'audit-fix.md');
// #1857: execute-phase's regression-gate test-command resolution was extracted
// to this step file (execute-phase.md is size-frozen — phase-6 capstone).
const REGRESSION_GATE_PATH = path.join(__dirname, '..', 'gsd-core', 'workflows', 'execute-phase', 'steps', 'regression-gate.md');
// #2932: steps/regression-gate.md now only discovers prior-phase test files and
// delegates (via "Read and execute") to steps/regression-gate-run.md, which
// carries the actual test-command resolution (Makefile/config-get priority).
const REGRESSION_GATE_PATH = path.join(__dirname, '..', 'gsd-core', 'workflows', 'execute-phase', 'steps', 'regression-gate-run.md');
function assertMakefileCheckBeforeNpmTest(filePath, label) {
const content = fs.readFileSync(filePath, 'utf-8');

View File

@@ -75,16 +75,31 @@ describe('execute-phase workflow: wave filtering', () => {
test('workflow has partial-wave completion guardrail', () => {
const content = fs.readFileSync(WORKFLOW_PATH, 'utf-8');
// handle_partial_wave_execution was extracted to
// gsd-core/workflows/execute-phase/steps/partial-wave.md. The parent now only
// references it via a <gsd:section> pointer, so assert the pointer is present here
// and then read the actual step body from the extracted file below.
assert.ok(
content.includes('<step name="handle_partial_wave_execution">'),
content.includes('gsd-core/workflows/execute-phase/steps/partial-wave.md'),
'workflow should reference the extracted partial-wave step file'
);
const PARTIAL_WAVE_STEP_PATH = path.join(
__dirname, '..', 'gsd-core', 'workflows', 'execute-phase', 'steps', 'partial-wave.md'
);
assert.ok(fs.existsSync(PARTIAL_WAVE_STEP_PATH), 'partial-wave step file should exist');
const stepContent = fs.readFileSync(PARTIAL_WAVE_STEP_PATH, 'utf-8');
assert.ok(
stepContent.includes('<step name="handle_partial_wave_execution">'),
'workflow should have a partial wave handling step'
);
assert.ok(
content.includes('Do NOT run phase verification'),
stepContent.includes('Do NOT run phase verification'),
'partial wave step should skip phase verification'
);
assert.ok(
content.includes('Do NOT mark the phase complete'),
stepContent.includes('Do NOT mark the phase complete'),
'partial wave step should skip phase completion'
);
});

View File

@@ -251,8 +251,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -303,6 +306,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -322,8 +322,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -374,6 +377,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -321,8 +321,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -373,6 +376,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -250,8 +250,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -302,6 +305,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -254,8 +254,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -306,6 +309,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -322,8 +322,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -374,6 +377,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -357,8 +357,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -409,6 +412,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -252,8 +252,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -304,6 +307,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -322,8 +322,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -374,6 +377,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -251,8 +251,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -303,6 +306,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -322,8 +322,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -374,6 +377,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -281,8 +281,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -333,6 +336,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -317,8 +317,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -369,6 +372,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -322,8 +322,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -374,6 +377,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -219,8 +219,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -271,6 +274,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -251,8 +251,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -303,6 +306,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -251,8 +251,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -303,6 +306,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -251,8 +251,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -303,6 +306,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -322,8 +322,11 @@
"gsd-core/workflows/execute-phase.md",
"gsd-core/workflows/execute-phase/steps/codebase-drift-gate.md",
"gsd-core/workflows/execute-phase/steps/executor-isolation-dispatch.md",
"gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md",
"gsd-core/workflows/execute-phase/steps/partial-wave.md",
"gsd-core/workflows/execute-phase/steps/per-plan-worktree-gate.md",
"gsd-core/workflows/execute-phase/steps/post-merge-gate.md",
"gsd-core/workflows/execute-phase/steps/regression-gate-run.md",
"gsd-core/workflows/execute-phase/steps/regression-gate.md",
"gsd-core/workflows/execute-phase/steps/worktree-recovery-policy.md",
"gsd-core/workflows/execute-plan.md",
@@ -374,6 +377,7 @@
"gsd-core/workflows/resume-project.md",
"gsd-core/workflows/review.md",
"gsd-core/workflows/scan.md",
"gsd-core/workflows/section-manifest.json",
"gsd-core/workflows/secure-phase.md",
"gsd-core/workflows/session-report.md",
"gsd-core/workflows/settings-advanced.md",

View File

@@ -0,0 +1,569 @@
'use strict';
/**
* gen-section-manifest.cjs drift-guard tests — 50-test-matrix.md rows 29-41
* (issue #2932, epic #1671 Phase 5,
* `.gsd/phase/chore-2932-init-section-manifest/50-test-matrix.md` section D).
*
* Every test spawns the real CLI (execFileSync) against a temp fixture tree
* shaped like the real repo (`<root>/gsd-core/workflows/<name>.md` +
* `<root>/gsd-core/workflows/<name>/steps/<id>.md`), using the generator's
* `--workflows-dir`/`--manifest-path`/`--repo-root` overrides — no fs
* monkeypatching except rows 40/41, which inject the exact fault
* `writeManifestAtomically` cannot otherwise be made to hit (CONTRIBUTING.md
* / CLAUDE.md cross-platform IO-failure rule: monkeypatch the `fs` method,
* restore via `t.after()`, never `chmod 0o000`).
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { createTempDir, cleanup } = require('./helpers.cjs');
const {
buildFreshManifest,
writeManifestAtomically,
loadWorkflowFragmentsLib,
checkReport,
ManifestBuildError,
REASON,
WORKFLOW_FRAGMENTS_LIB_PATH,
} = require('../scripts/gen-section-manifest.cjs');
const ROOT = path.resolve(__dirname, '..');
const SCRIPT = path.join(ROOT, 'scripts', 'gen-section-manifest.cjs');
const STACK_FRAME_RE = /\n\s+at\s+\S+\s+\(.*:\d+:\d+\)/;
// ─── Fixture builder ───────────────────────────────────────────────────────
/**
* Build a `<tmpRoot>/gsd-core/workflows/` tree containing one workflow file
* plus (optionally) its `steps/` directory, matching the real repo's
* relative shape exactly so `--repo-root <tmpRoot>` produces the same
* `gsd-core/workflows/...` POSIX `read` paths the real generator emits.
*
* @param {string} tmpRoot
* @param {string} workflowName - e.g. "sample" -> gsd-core/workflows/sample.md
* @param {string} sourceContent
* @param {{[stepFileName: string]: string}} [stepFiles]
* @returns {{ workflowsDir: string, manifestPath: string }}
*/
function buildFixture(tmpRoot, workflowName, sourceContent, stepFiles = {}) {
const workflowsDir = path.join(tmpRoot, 'gsd-core', 'workflows');
fs.mkdirSync(workflowsDir, { recursive: true });
fs.writeFileSync(path.join(workflowsDir, `${workflowName}.md`), sourceContent, 'utf8');
if (Object.keys(stepFiles).length > 0) {
const stepsDir = path.join(workflowsDir, workflowName, 'steps');
fs.mkdirSync(stepsDir, { recursive: true });
for (const [name, content] of Object.entries(stepFiles)) {
fs.writeFileSync(path.join(stepsDir, name), content, 'utf8');
}
}
return { workflowsDir, manifestPath: path.join(workflowsDir, 'section-manifest.json') };
}
/** A single well-formed marker + matching step-file body. */
function markerSource(id, when, refFile) {
return [
'# Sample workflow',
'',
`<!-- gsd:section id="${id}" when="${when}" -->`,
`Read and execute \`gsd-core/workflows/sample/steps/${refFile}\`.`,
'<!-- /gsd:section -->',
'',
].join('\n');
}
/**
* @param {string[]} args
* @param {string} cwd
* @returns {{code: number, stdout: string, stderr: string}}
*/
function runGenSectionManifest(args, cwd = ROOT) {
try {
const stdout = execFileSync(process.execPath, [SCRIPT, ...args], {
cwd,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'pipe'],
timeout: 30000,
});
return { code: 0, stdout, stderr: '' };
} catch (err) {
return {
code: err.status ?? 1,
stdout: err.stdout ? err.stdout.toString() : '',
stderr: err.stderr ? err.stderr.toString() : '',
};
}
}
function parseJsonReport(stdout) {
return JSON.parse(stdout.trim());
}
// ─── D. Generator drift-guard (rows 29-41) ─────────────────────────────────
describe('gen-section-manifest.cjs --check / --write (matrix D)', () => {
test('checkExitsZeroWhenManifestMatchesSource (row 29)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
const { workflowsDir, manifestPath } = buildFixture(
tmpRoot,
'sample',
markerSource('handle-x', 'always', 'handle-x.md'),
{ 'handle-x.md': '<step name="handle_x">\nbody\n</step>\n' },
);
const fresh = buildFreshManifest(workflowsDir, tmpRoot);
fs.writeFileSync(manifestPath, JSON.stringify(fresh, null, 2) + '\n', 'utf8');
const r = runGenSectionManifest([
'--check', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(r.code, 0, `stderr: ${r.stderr}`);
});
test('checkExitsOneAndNamesFileWhenManifestIsStale (row 30)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
const { workflowsDir, manifestPath } = buildFixture(
tmpRoot,
'sample',
markerSource('handle-x', 'always', 'handle-x.md'),
{ 'handle-x.md': '<step name="handle_x">\nbody\n</step>\n' },
);
// Stale: valid shape, but "when" no longer matches the source's marker.
fs.writeFileSync(
manifestPath,
JSON.stringify({ sections: [{ id: 'handle-x', when: 'flag:--wave', read: 'gsd-core/workflows/sample/steps/handle-x.md' }] }, null, 2) + '\n',
'utf8',
);
const r = runGenSectionManifest([
'--check', '--json', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(r.code, 1);
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, 'no bare stack trace for a stale manifest');
const report = parseJsonReport(r.stdout);
assert.equal(report.ok, false);
assert.equal(report.reason, REASON.FAIL_STALE);
assert.equal(report.subject, manifestPath, 'report must name the stale manifest file');
});
test('writeThenCheckRoundTripsClean (row 31)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
const { workflowsDir, manifestPath } = buildFixture(
tmpRoot,
'sample',
markerSource('handle-x', 'always', 'handle-x.md'),
{ 'handle-x.md': '<step name="handle_x">\nbody\n</step>\n' },
);
const w = runGenSectionManifest([
'--write', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(w.code, 0, `stderr: ${w.stderr}`);
assert.ok(fs.existsSync(manifestPath));
const c = runGenSectionManifest([
'--check', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(c.code, 0, '--check must be clean immediately after --write');
});
test('checkFailsCleanlyWhenManifestAbsent (row 32)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
const { workflowsDir, manifestPath } = buildFixture(
tmpRoot,
'sample',
markerSource('handle-x', 'always', 'handle-x.md'),
{ 'handle-x.md': '<step name="handle_x">\nbody\n</step>\n' },
);
assert.equal(fs.existsSync(manifestPath), false, 'sanity: manifest must not exist yet');
const r = runGenSectionManifest([
'--check', '--json', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(r.code, 1);
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, 'an absent manifest must not crash, just fail closed');
const report = parseJsonReport(r.stdout);
assert.equal(report.ok, false);
assert.equal(report.reason, REASON.FAIL_MANIFEST_MISSING);
assert.equal(report.subject, manifestPath);
});
test('checkFailsCleanlyOnEmptyManifestFile (row 33)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
const { workflowsDir, manifestPath } = buildFixture(
tmpRoot,
'sample',
markerSource('handle-x', 'always', 'handle-x.md'),
{ 'handle-x.md': '<step name="handle_x">\nbody\n</step>\n' },
);
fs.writeFileSync(manifestPath, '', 'utf8');
const r = runGenSectionManifest([
'--check', '--json', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(r.code, 1);
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, 'no stack trace for an empty manifest file');
const report = parseJsonReport(r.stdout);
assert.equal(report.ok, false);
assert.equal(report.reason, REASON.FAIL_MANIFEST_UNPARSEABLE);
});
test('rejectsValidJsonThatIsNotTheExpectedShape (row 34)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
const { workflowsDir, manifestPath } = buildFixture(
tmpRoot,
'sample',
markerSource('handle-x', 'always', 'handle-x.md'),
{ 'handle-x.md': '<step name="handle_x">\nbody\n</step>\n' },
);
for (const hostileJson of ['0', '"s"', '[]', 'null', 'true']) {
fs.writeFileSync(manifestPath, hostileJson, 'utf8');
const r = runGenSectionManifest([
'--check', '--json', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(r.code, 1, `hostile JSON ${hostileJson} must fail --check`);
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, `hostile JSON ${hostileJson} must not crash`);
const report = parseJsonReport(r.stdout);
assert.equal(report.ok, false, `hostile JSON ${hostileJson}`);
assert.equal(report.reason, REASON.FAIL_MANIFEST_MALFORMED_SHAPE, `hostile JSON ${hostileJson}`);
}
});
test('checkFailsWhenMarkerReferencesMissingStepFile (row 35)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
// Marker present, but the step file it names is never created.
const { workflowsDir, manifestPath } = buildFixture(
tmpRoot,
'sample',
markerSource('handle-x', 'always', 'handle-x.md'),
{},
);
const r = runGenSectionManifest([
'--check', '--json', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(r.code, 1);
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, 'a missing step file must not crash the generator');
const report = parseJsonReport(r.stdout);
assert.equal(report.ok, false);
assert.equal(report.reason, REASON.FAIL_MISSING_STEP_FILE);
assert.equal(
report.subject,
'gsd-core/workflows/sample/steps/handle-x.md',
'report must name the missing step file path',
);
});
test('checkFailsOnOrphanStepFile (row 36)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
// handle-x.md is the legitimate marker target; stray.md is referenced by
// nothing (not the marker, not any prose in the parent or in handle-x.md).
const { workflowsDir, manifestPath } = buildFixture(
tmpRoot,
'sample',
markerSource('handle-x', 'always', 'handle-x.md'),
{
'handle-x.md': '<step name="handle_x">\nbody\n</step>\n',
'stray.md': '<step name="unreachable">\nnever referenced anywhere\n</step>\n',
},
);
const r = runGenSectionManifest([
'--check', '--json', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(r.code, 1);
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, 'an orphan step file must not crash the generator');
const report = parseJsonReport(r.stdout);
assert.equal(report.ok, false);
assert.equal(report.reason, REASON.FAIL_ORPHAN_STEP_FILE);
assert.equal(
report.subject,
'gsd-core/workflows/sample/steps/stray.md',
'report must name the orphan step file path',
);
});
test('nestedStepReferenceIsNotFlaggedAsOrphan (supplemental: proves the reachability fixed-point, not just the negative case)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
// handle-x.md is the marker target; handle-x.md's OWN prose delegates to
// handle-x-run.md, which is referenced by NO marker directly — mirrors
// the real repo's regression-gate.md -> regression-gate-run.md shape.
const { workflowsDir, manifestPath } = buildFixture(
tmpRoot,
'sample',
markerSource('handle-x', 'always', 'handle-x.md'),
{
'handle-x.md': 'Read and execute `gsd-core/workflows/sample/steps/handle-x-run.md`.\n',
'handle-x-run.md': 'the nested run body\n',
},
);
const fresh = buildFreshManifest(workflowsDir, tmpRoot);
assert.equal(fresh.sections.length, 1);
fs.writeFileSync(manifestPath, JSON.stringify(fresh, null, 2) + '\n', 'utf8');
const r = runGenSectionManifest([
'--check', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(r.code, 0, `handle-x-run.md must resolve as reachable, not orphan; stderr: ${r.stderr}`);
});
test('producesIdenticalManifestForCrlfAndLfSources (row 37)', (t) => {
const lfRoot = createTempDir('gen-section-manifest-lf-');
const crlfRoot = createTempDir('gen-section-manifest-crlf-');
t.after(() => {
cleanup(lfRoot);
cleanup(crlfRoot);
});
const lfSource = markerSource('handle-x', 'state:has-prior-phases', 'handle-x.md');
const lfStep = '<step name="handle_x">\nbody\n</step>\n';
const { workflowsDir: lfDir } = buildFixture(lfRoot, 'sample', lfSource, { 'handle-x.md': lfStep });
const { workflowsDir: crlfDir } = buildFixture(
crlfRoot,
'sample',
lfSource.replace(/\n/g, '\r\n'),
{ 'handle-x.md': lfStep.replace(/\n/g, '\r\n') },
);
const lfManifest = buildFreshManifest(lfDir, lfRoot);
const crlfManifest = buildFreshManifest(crlfDir, crlfRoot);
assert.deepEqual(crlfManifest, lfManifest, 'CRLF and LF sources must produce an identical manifest');
});
test('ignoresSectionShapedLineInsideFencedBlock (row 38)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
const source = [
'# Sample workflow',
'',
'<!-- gsd:section id="handle-x" when="always" -->',
'Read and execute `gsd-core/workflows/sample/steps/handle-x.md`.',
'<!-- /gsd:section -->',
'',
'Documentation of the marker grammar (must NOT be treated as real):',
'```',
'<!-- gsd:section id="fake" when="always" -->',
'never a real section',
'<!-- /gsd:section -->',
'```',
'',
].join('\n');
const { workflowsDir, manifestPath } = buildFixture(tmpRoot, 'sample', source, {
'handle-x.md': '<step name="handle_x">\nbody\n</step>\n',
});
const fresh = buildFreshManifest(workflowsDir, tmpRoot);
assert.equal(fresh.sections.length, 1, 'the fenced marker-shaped lines must not produce a section');
assert.equal(fresh.sections[0].id, 'handle-x');
fs.writeFileSync(manifestPath, JSON.stringify(fresh, null, 2) + '\n', 'utf8');
const r = runGenSectionManifest([
'--check', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(r.code, 0, `stderr: ${r.stderr}`);
});
test('leavesLoopHostMarkerUntouched (row 39)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
const source = [
'<!-- gsd:loop-host name="example" -->',
'',
'# Sample workflow',
'',
'<!-- gsd:section id="handle-x" when="always" -->',
'Read and execute `gsd-core/workflows/sample/steps/handle-x.md`.',
'<!-- /gsd:section -->',
'',
].join('\n');
const { workflowsDir, manifestPath } = buildFixture(tmpRoot, 'sample', source, {
'handle-x.md': '<step name="handle_x">\nbody\n</step>\n',
});
const fresh = buildFreshManifest(workflowsDir, tmpRoot);
assert.equal(fresh.sections.length, 1, 'gsd:loop-host must never be treated as a gsd:section marker');
assert.equal(fresh.sections[0].id, 'handle-x');
fs.writeFileSync(manifestPath, JSON.stringify(fresh, null, 2) + '\n', 'utf8');
const r = runGenSectionManifest([
'--check', '--workflows-dir', workflowsDir, '--manifest-path', manifestPath, '--repo-root', tmpRoot,
]);
assert.equal(r.code, 0, `stderr: ${r.stderr}`);
});
test('writesManifestAtomically (row 40)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
const manifestPath = path.join(tmpRoot, 'section-manifest.json');
const originalContent = '{"sections":[{"id":"pre-existing","when":"always","read":"x.md"}]}\n';
fs.writeFileSync(manifestPath, originalContent, 'utf8');
// Cross-platform IO-failure injection (CLAUDE.md rule): monkeypatch the
// fs method, restore via t.after() (never chmod 0o000 — root bypasses
// mode bits, silently zero-coverage in root Docker/CI).
const origRenameSync = fs.renameSync;
fs.renameSync = function patchedRenameSync() {
throw new Error('injected rename failure (never a real fs fault)');
};
t.after(() => {
fs.renameSync = origRenameSync;
});
assert.throws(() => writeManifestAtomically(manifestPath, '{"sections":[]}\n'), (err) => {
// Finding 2 (#2932 review): the throw site must attach the typed
// FAIL_WRITE_ERROR reason, not just a plain ExitError, so a downstream
// `--write --json` consumer can emit the same {ok,reason,subject}
// envelope every other failure path in this file produces.
assert.ok(err instanceof ManifestBuildError, 'must throw a ManifestBuildError, not a plain ExitError');
assert.equal(err.reason, REASON.FAIL_WRITE_ERROR);
assert.equal(err.subject, manifestPath);
return true;
});
assert.equal(
fs.readFileSync(manifestPath, 'utf8'),
originalContent,
'a rename failure must leave the pre-existing manifest completely untouched, never truncated',
);
const leftoverTmp = fs.readdirSync(tmpRoot).filter((f) => f.includes('.tmp-'));
assert.deepEqual(leftoverTmp, [], 'the temp file must be cleaned up even when the rename step fails');
});
test('surfacesWriteFailureAndCleansTemp (row 41)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
const manifestPath = path.join(tmpRoot, 'section-manifest.json');
assert.equal(fs.existsSync(manifestPath), false, 'sanity: no pre-existing manifest');
const origWriteFileSync = fs.writeFileSync;
fs.writeFileSync = function patchedWriteFileSync(target, ...rest) {
if (target === manifestPath || (typeof target === 'string' && target.includes('.tmp-'))) {
throw new Error('injected write failure (never a real fs fault)');
}
return origWriteFileSync.call(fs, target, ...rest);
};
t.after(() => {
fs.writeFileSync = origWriteFileSync;
});
assert.throws(() => writeManifestAtomically(manifestPath, '{"sections":[]}\n'), (err) => {
assert.ok(err instanceof ManifestBuildError, 'must throw a ManifestBuildError, not a plain ExitError');
assert.equal(err.reason, REASON.FAIL_WRITE_ERROR);
assert.equal(err.subject, manifestPath);
return true;
});
assert.equal(fs.existsSync(manifestPath), false, 'the target manifest must never be created on a write failure');
const leftover = fs.readdirSync(tmpRoot).filter((f) => f.includes('.tmp-'));
assert.deepEqual(leftover, [], 'no temp file must leak when the initial write itself fails');
});
test('loadWorkflowFragmentsLib throws ManifestBuildError with FAIL_LIB_NOT_BUILT when the compiled lib cannot be read (Finding 2, #2932 review)', (t) => {
// Cross-platform IO-failure injection (CLAUDE.md rule): monkeypatch the
// `fs` method Node's own module loader uses to read the file content
// (never chmod 0o000 — root bypasses mode bits, silently zero-coverage in
// root Docker/CI, and would also mutate a file shared by concurrent test
// workers). The real compiled artifact is never touched or renamed.
const origReadFileSync = fs.readFileSync;
fs.readFileSync = function patchedReadFileSync(target, ...rest) {
if (target === WORKFLOW_FRAGMENTS_LIB_PATH) {
throw new Error('injected read failure (never a real fs fault)');
}
return origReadFileSync.call(fs, target, ...rest);
};
t.after(() => {
fs.readFileSync = origReadFileSync;
});
assert.throws(() => loadWorkflowFragmentsLib(), (err) => {
assert.ok(err instanceof ManifestBuildError, 'must throw a ManifestBuildError, not a plain ExitError');
assert.equal(err.reason, REASON.FAIL_LIB_NOT_BUILT);
assert.equal(err.subject, 'gsd-core/bin/lib/workflow-fragments.cjs');
assert.match(err.message, /npm run build:lib/);
return true;
});
});
test('checkReport surfaces FAIL_LIB_NOT_BUILT as the same typed envelope other --check failures produce (Finding 2, #2932 review)', (t) => {
const tmpRoot = createTempDir('gen-section-manifest-');
t.after(() => cleanup(tmpRoot));
const { workflowsDir, manifestPath } = buildFixture(
tmpRoot,
'sample',
markerSource('handle-x', 'always', 'handle-x.md'),
{ 'handle-x.md': '<step name="handle_x">\nbody\n</step>\n' },
);
const origReadFileSync = fs.readFileSync;
fs.readFileSync = function patchedReadFileSync(target, ...rest) {
if (target === WORKFLOW_FRAGMENTS_LIB_PATH) {
throw new Error('injected read failure (never a real fs fault)');
}
return origReadFileSync.call(fs, target, ...rest);
};
t.after(() => {
fs.readFileSync = origReadFileSync;
});
const report = checkReport(workflowsDir, manifestPath, tmpRoot);
assert.equal(report.ok, false);
assert.equal(report.reason, REASON.FAIL_LIB_NOT_BUILT);
assert.equal(report.subject, 'gsd-core/bin/lib/workflow-fragments.cjs');
});
});
// ─── REASON enum shape lock (mirrors gen-context-index.cjs precedent) ──────
describe('gen-section-manifest.cjs REASON enum', () => {
test('REASON key set is exactly the documented set', () => {
assert.deepEqual(Object.keys(REASON).sort(), [
'FAIL_LIB_NOT_BUILT',
'FAIL_MANIFEST_MALFORMED_SHAPE',
'FAIL_MANIFEST_MISSING',
'FAIL_MANIFEST_UNPARSEABLE',
'FAIL_MISSING_STEP_FILE',
'FAIL_ORPHAN_STEP_FILE',
'FAIL_SOURCE_PARSE_ERROR',
'FAIL_STALE',
'FAIL_WRITE_ERROR',
'OK_UP_TO_DATE',
]);
});
test('REASON is frozen', () => {
assert.ok(Object.isFrozen(REASON));
});
});

View File

@@ -6,9 +6,11 @@ const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const { runGsdTools, cleanup, absPlanningPath } = require('./helpers.cjs');
const { spawnSync } = require('node:child_process');
const { runGsdTools, cleanup, absPlanningPath, TOOLS_PATH } = require('./helpers.cjs');
const { createFixture, seedPhase } = require('./fixtures/index.cjs');
const { createTempProject, createTempDir } = require('./helpers.cjs');
const { executionContextRefs } = require('../scripts/command-contract-helpers.cjs');
describe('init commands', () => {
let tmpDir;
@@ -2972,3 +2974,342 @@ test('bug-3491: new-project.md gates `git init` on in_nested_subdir, not just ha
});
});
}
// ─────────────────────────────────────────────────────────────────────────────
// Folded from tests/init-section-manifest.test.cjs — #2932 (epic #1671 Phase 5)
// ─────────────────────────────────────────────────────────────────────────────
//
// init CLI negative matrix for `section_manifest`. Covers
// `.gsd/phase/chore-2932-init-section-manifest/50-test-matrix.md` section E
// (rows 42-59) plus row 62. Drives the REAL CLI through the dispatch seam
// (`spawnSync(process.execPath, [...])` with argv ARRAYS — never shell strings) so
// hostile inputs (rows 55/56) prove no shell interpolation and no path escape.
//
// Each test asserts: exit status, structured JSON result, absence of project-tree
// fs mutation, and no stack trace in non-debug stderr — never substring-matching
// rendered prose (local/no-source-grep).
describe('init section manifest', () => {
const GSD_ROOT = path.join(__dirname, '..', 'gsd-core');
const COMMANDS_DIR = path.join(__dirname, '..', 'commands', 'gsd');
// ── Drivers ─────────────────────────────────────────────────────────────
/**
* Invokes the real CLI dispatch seam with an argv ARRAY (never a shell string),
* so shell metacharacters in an argument (rows 55/56) can never be interpreted
* by a shell — spawnSync with an array bypasses the shell entirely. Always runs
* with GSD_JSON_ERRORS=1 so an error path yields a typed `{ ok, reason, message }`
* envelope instead of prose, per CONTRIBUTING.md "Prohibited: Raw Text Matching".
*/
function runSectionManifestCli(args, cwd, env = {}) {
const result = spawnSync(process.execPath, [TOOLS_PATH, 'query', ...args], {
cwd,
encoding: 'utf8',
env: { ...process.env, GSD_JSON_ERRORS: '1', ...env },
timeout: 30000,
});
let stdout = result.stdout || '';
// output() spills payloads over 50KB to a tmpfile and prints "@file:<path>"
// (src/io.cts) — dereference it exactly as the workflow itself does.
if (stdout.startsWith('@file:')) {
stdout = fs.readFileSync(stdout.slice('@file:'.length).trim(), 'utf8');
}
return { status: result.status, stdout, stderr: result.stderr || '' };
}
function runExecutePhase(phaseArgs, cwd, env = {}) {
return runSectionManifestCli(['init.execute-phase', ...phaseArgs], cwd, env);
}
function parseOkJson(result, label) {
assert.equal(result.status, 0, `${label}: expected exit 0, got ${result.status} (stderr: ${result.stderr})`);
assertNoStackTrace(result.stderr, label);
return JSON.parse(result.stdout);
}
function parseErrorJson(result, label) {
assert.notEqual(result.status, 0, `${label}: expected non-zero exit`);
assertNoStackTrace(result.stderr, label);
return JSON.parse(result.stderr);
}
/** Node stack-trace frames look like "\n at fn (file:line:col)" — a structural
* signal, not a content match on any file's prose. */
function assertNoStackTrace(text, label) {
assert.ok(!/\n\s+at\s+\S+/.test(text || ''), `${label}: unexpected stack trace: ${text}`);
}
/** Recursive, sorted snapshot of a directory's structure — name/size/mtime triples,
* used to assert a read-only `query` command mutates nothing under the project tree. */
function snapshotSectionManifestTree(dir) {
const out = [];
function walk(d, rel) {
let entries;
try {
entries = fs.readdirSync(d, { withFileTypes: true });
} catch {
return;
}
entries.sort((a, b) => a.name.localeCompare(b.name));
for (const entry of entries) {
const relPath = rel ? `${rel}/${entry.name}` : entry.name;
const full = path.join(d, entry.name);
if (entry.isDirectory()) {
out.push(`D:${relPath}`);
walk(full, relPath);
} else {
const st = fs.statSync(full);
out.push(`F:${relPath}:${st.size}`);
}
}
}
walk(dir, '');
return out;
}
function seedSinglePhaseProject(t, prefix) {
const dir = createTempProject(prefix);
t.after(() => cleanup(dir));
seedPhase(dir, '01-widgets', {});
return dir;
}
// ── E42-43: baseline manifest emission, with/without --wave ─────────────
describe('init execute-phase: section_manifest emission (#2932)', () => {
test('emitsSectionManifestWithoutWaveFlag', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e42-');
const before = snapshotSectionManifestTree(dir);
const body = parseOkJson(runExecutePhase(['1'], dir), 'no-flag');
assert.deepStrictEqual(snapshotSectionManifestTree(dir), before, 'query command must not mutate the project tree');
assert.ok(body.section_manifest, 'section_manifest must be present');
assert.equal(body.section_manifest.workflow, 'execute-phase');
assert.ok(!body.section_manifest.included.includes('partial-wave'), 'partial-wave must be excluded without --wave');
assert.ok(body.section_manifest.excluded.includes('partial-wave'));
assert.deepStrictEqual(body.section_manifest.read, []);
});
test('emitsSectionManifestIncludingPartialWaveWithWaveFlag (#2932 headline acceptance criterion)', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e43-');
const body = parseOkJson(runExecutePhase(['1', '--wave', '1'], dir), 'with-wave');
assert.ok(body.section_manifest);
assert.deepStrictEqual(body.section_manifest.included, ['partial-wave']);
assert.ok(!body.section_manifest.excluded.includes('partial-wave'));
assert.deepStrictEqual(body.section_manifest.read, [
'gsd-core/workflows/execute-phase/steps/partial-wave.md',
]);
});
});
// ── E44-46: phase argument boundary ────────────────────────────────────
describe('init execute-phase: phase argument boundary (#2932)', () => {
test('failsWhenPhaseArgumentMissing', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e44-');
const err = parseErrorJson(runExecutePhase([], dir), 'missing-phase');
assert.equal(err.ok, false);
assert.equal(typeof err.reason, 'string');
assert.equal(typeof err.message, 'string');
});
test('failsOnEmptyPhaseArgument', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e45-');
const err = parseErrorJson(runExecutePhase([''], dir), 'empty-phase');
assert.equal(err.ok, false);
});
test('failsOnWhitespaceOnlyPhaseArgument', (t) => {
// Test-matrix row 46 names "non-zero" as expected. Empirically, cmdInitExecutePhase's
// guard is `if (!phase)`, which is false for a non-empty whitespace string — this
// pre-existing idiom is SHARED by every phase-taking init subcommand (plan-phase,
// todos, phase-op, ...), not introduced by #2932, and changing it here would be a
// blast-radius violation of the CRITICAL routeInitCommand rating (37 affected files).
// " " instead falls through to guardedFindPhase, which returns no match — the same
// graceful "not found" degrade the path-traversal/shell-metachar rows (55/56) require,
// not a crash. This test locks the REAL, current, exit-0 "not found" behavior rather
// than the matrix's a-priori assumption; see the dispatch report for this reconciliation.
const dir = seedSinglePhaseProject(t, 'gsd-e46-');
const body = parseOkJson(runExecutePhase([' '], dir), 'whitespace-phase');
assert.equal(body.phase_found, false);
assert.ok(body.section_manifest, 'manifest is still emitted — it does not depend on phase_found');
});
});
// ── E47-52: --wave token-presence semantics ──────────────────────────────
describe('init execute-phase: --wave token-presence semantics (#2932)', () => {
test('treatsValuelessWaveFlagAsPresent', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e47-');
const body = parseOkJson(runExecutePhase(['1', '--wave'], dir), 'valueless-wave');
assert.deepStrictEqual(body.section_manifest.included, ['partial-wave']);
});
test('treatsWaveZeroAsPresent', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e48-');
const body = parseOkJson(runExecutePhase(['1', '--wave', '0'], dir), 'wave-zero');
assert.deepStrictEqual(body.section_manifest.included, ['partial-wave']);
});
test('treatsDuplicateWaveFlagsIdempotently', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e49-');
const body = parseOkJson(runExecutePhase(['1', '--wave', '1', '--wave', '2'], dir), 'dup-wave');
assert.deepStrictEqual(body.section_manifest.included, ['partial-wave']);
});
test('handlesMalformedWaveAssignments', (t) => {
// Documented handling (decision made during this dispatch): parseNamedArgs's
// booleanFlags check is an EXACT token match against the literal "--wave" —
// "--wave=" and "--wave==1" are different literal tokens, so neither activates
// the flag. No crash either way; this is the same exact-match discipline that
// keeps "--waves"/"--wave-filter" from false-activating (row 52).
const dir = seedSinglePhaseProject(t, 'gsd-e50-');
for (const token of ['--wave=', '--wave==1']) {
const body = parseOkJson(runExecutePhase(['1', token], dir), `malformed-wave:${token}`);
assert.ok(!body.section_manifest.included.includes('partial-wave'), `"${token}" must not activate --wave`);
}
});
test('doesNotConsumeFollowingFlagAsWaveValue', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e51-');
const body = parseOkJson(runExecutePhase(['1', '--wave', '--weird'], dir), 'wave-then-weird');
// Boolean-flag semantics: --wave never reads a following token as its value,
// so an adjacent flag-shaped token is simply ignored, not eaten or mis-parsed.
assert.deepStrictEqual(body.section_manifest.included, ['partial-wave']);
});
test('nearMissFlagNamesDoNotActivateWave', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e52-');
for (const flag of ['--waves', '--wave-filter']) {
const body = parseOkJson(runExecutePhase(['1', flag], dir), `near-miss:${flag}`);
assert.ok(!body.section_manifest.included.includes('partial-wave'), `"${flag}" must not activate --wave`);
}
});
});
// ── E53: unknown subcommand ───────────────────────────────────────────────
describe('init dispatch: unknown subcommand (#2932 row 53)', () => {
test('reportsUnknownInitSubcommand', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e53-');
const err = parseErrorJson(runSectionManifestCli(['init.frobnicate'], dir), 'unknown-subcommand');
assert.equal(err.ok, false);
assert.equal(err.reason, 'sdk_unknown_command');
});
});
// ── E54-56: hostile inputs ────────────────────────────────────────────────
describe('init execute-phase: hostile inputs (#2932)', () => {
test('handlesVeryLongAndUnicodeValues', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e54-');
const longUnicodeValue = 'x'.repeat(20000) + '你好\u{1f600}';
const result = runExecutePhase(['1', '--wave', longUnicodeValue], dir);
assert.equal(result.status, 0, `expected exit 0, got ${result.status} (stderr: ${result.stderr})`);
assertNoStackTrace(result.stderr, 'long-unicode-value');
const body = JSON.parse(result.stdout);
assert.deepStrictEqual(body.section_manifest.included, ['partial-wave']);
const longPhaseResult = runExecutePhase(['1' + 'z'.repeat(20000)], dir);
assert.equal(longPhaseResult.status, 0);
assertNoStackTrace(longPhaseResult.stderr, 'long-phase-value');
});
test('doesNotInterpolateShellMetacharactersInPhase', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e55-');
const sentinel = path.join(dir, 'pwned-sentinel');
const hostilePhase = `1; touch ${sentinel}; $(touch ${sentinel}) \`touch ${sentinel}\` && touch ${sentinel} || touch ${sentinel}`;
const result = runExecutePhase([hostilePhase], dir);
assert.equal(result.status, 0, `expected exit 0 (no shell execution), got ${result.status}`);
assertNoStackTrace(result.stderr, 'shell-metachars');
assert.ok(!fs.existsSync(sentinel), 'shell metacharacters in the phase argument must never be interpreted — argv array bypasses the shell entirely');
});
test('rejectsPathTraversalStylePhaseValue', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e56-');
const before = snapshotSectionManifestTree(dir);
const body = parseOkJson(runExecutePhase(['../../../../etc/passwd'], dir), 'path-traversal');
assert.deepStrictEqual(snapshotSectionManifestTree(dir), before, 'no fs mutation from a traversal-shaped phase value');
assert.equal(body.phase_found, false, 'a traversal-shaped value must never resolve to a real phase');
assert.ok(
!String(body.phase_dir || '').includes('etc/passwd'),
'phase_dir must never resolve outside the project tree',
);
});
});
// ── E57-58: degraded path — manifest artifact missing/malformed ─────────
describe('init execute-phase: section_manifest degrades to null (#2932)', () => {
test('degradesToNullManifestWhenArtifactMissing', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e57-');
const missingPath = path.join(dir, 'does-not-exist-section-manifest.json');
const result = runExecutePhase(['1'], dir, { GSD_SECTION_MANIFEST: missingPath });
assert.equal(result.status, 0, `expected exit 0 despite missing manifest artifact, got ${result.status} (stderr: ${result.stderr})`);
assertNoStackTrace(result.stderr, 'manifest-missing');
const body = JSON.parse(result.stdout);
assert.equal(body.section_manifest, null);
});
test('degradesToNullManifestWhenArtifactMalformed', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e58-');
const badPath = path.join(dir, 'bad-section-manifest.json');
fs.writeFileSync(badPath, '{ this is not valid json');
const result = runExecutePhase(['1'], dir, { GSD_SECTION_MANIFEST: badPath });
assert.equal(result.status, 0, `expected exit 0 despite malformed manifest artifact, got ${result.status} (stderr: ${result.stderr})`);
assertNoStackTrace(result.stderr, 'manifest-malformed');
const body = JSON.parse(result.stdout);
assert.equal(body.section_manifest, null);
});
test('degradesToNullManifestWhenArtifactWrongShape', (t) => {
// Extends row 58: valid JSON, wrong shape (design doc + init.cts loadSectionManifestSections
// both name this as a degraded case distinct from "not JSON at all").
const dir = seedSinglePhaseProject(t, 'gsd-e58b-');
const wrongShapePath = path.join(dir, 'wrong-shape-section-manifest.json');
fs.writeFileSync(wrongShapePath, JSON.stringify([1, 2, 3]));
const result = runExecutePhase(['1'], dir, { GSD_SECTION_MANIFEST: wrongShapePath });
assert.equal(result.status, 0);
const body = JSON.parse(result.stdout);
assert.equal(body.section_manifest, null);
});
});
// ── E59: independence — other init subcommands unaffected ───────────────
describe('init dispatch: other subcommands unaffected (#2932 row 59, CRITICAL radius guard)', () => {
test('leavesOtherInitSubcommandsUnchanged', (t) => {
const dir = seedSinglePhaseProject(t, 'gsd-e59-');
const planPhase = parseOkJson(runSectionManifestCli(['init.plan-phase', '1'], dir), 'plan-phase');
assert.equal(planPhase.phase_found, true);
assert.ok(!('section_manifest' in planPhase), 'section_manifest must be execute-phase-only, never leak into plan-phase');
const resume = parseOkJson(runSectionManifestCli(['init.resume'], dir), 'resume');
assert.ok(!('section_manifest' in resume), 'section_manifest must never leak into resume');
});
});
// ── Row 62: stub <execution_context> @-refs still resolve (ADR-0002) ────
describe('commands/gsd/execute-phase.md: <execution_context> @-refs resolve (#2932 row 62)', () => {
test('stubExecutionContextRefStillResolves', () => {
const stubPath = path.join(COMMANDS_DIR, 'execute-phase.md');
const content = fs.readFileSync(stubPath, 'utf-8');
const refs = executionContextRefs(content);
assert.ok(refs.length > 0, 'execute-phase.md stub must declare at least one execution_context @-ref');
const workflowRef = refs.find((r) => r.normalized === 'workflows/execute-phase.md');
assert.ok(workflowRef, 'execute-phase.md stub must @-reference workflows/execute-phase.md');
for (const ref of refs) {
assert.ok(
fs.existsSync(path.join(GSD_ROOT, ref.normalized)),
`execution_context @-ref "${ref.normalized}" must resolve to a file that exists on disk`,
);
}
});
});
});

View File

@@ -102,7 +102,12 @@ describe('ADR-857 phase 6 verification and review capability migration', () => {
test('execute-phase code-review gate resolves execute:post hooks instead of inlining code_review config', () => {
const content = workflow('execute-phase.md');
const section = sectionBetween(content, '<step name="code_review_gate"', '<step name="close_parent_artifacts">');
// close_parent_artifacts was extracted to
// gsd-core/workflows/execute-phase/steps/gap-closure-artifacts.md; the parent now
// marks that boundary with a <!-- gsd:section id="gap-closure-artifacts" --> comment
// immediately after code_review_gate's closing </step>, so it remains the correct
// end-of-step delimiter for isolating this step's body.
const section = sectionBetween(content, '<step name="code_review_gate"', '<!-- gsd:section id="gap-closure-artifacts"');
assert.ok(section.includes('loop render-hooks execute:post'));
assert.ok(section.includes('gsd-${ref.skill}'));

View File

@@ -0,0 +1,201 @@
'use strict';
/**
* Property-based tests for src/section-manifest.cts (compiled to
* gsd-core/bin/lib/section-manifest.cjs) — issue #2932 (epic #1671 Phase 5).
* Covers 50-test-matrix.md rows 25-28.
*
* Document-shaped generators (CONTRIBUTING.md "Fixture provenance #2371",
* mirroring tests/workflow-fragments.property.test.cjs): section lists are
* generated as arbitrary document-order id/when sequences — the SHAPE a
* real `parseWorkflowSections` output would have — never by round-tripping
* through `selectSections`/`WHEN_PREDICATES` itself. `when` values are drawn
* from the module's own frozen `WHEN_VOCABULARY` re-export (imported from
* `workflow-fragments.cjs`, the true source of truth) rather than a
* hardcoded local copy, so the generator can never silently desync from
* production (DEFECT.GENERATIVE-FIX).
*
* Deterministic per CONTRIBUTING.md: seed and numRuns are pinned by
* tests/helpers/fast-check-setup.cjs (seed 42, numRuns 200).
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fc = require('./helpers/fast-check-setup.cjs');
const { selectSections, REASON } = require('../gsd-core/bin/lib/section-manifest.cjs');
const { WHEN_VOCABULARY } = require('../gsd-core/bin/lib/workflow-fragments.cjs');
const WHEN_VALUES = [...WHEN_VOCABULARY];
// Object.prototype-shaped `when` values — added during review — prototype-
// chain fail-open found by isolated adversarial pass. A bracket lookup on a
// plain frozen object resolves these as inherited members instead of failing
// closed; the totality property below must cover them too.
const HOSTILE_WHEN_VALUES = [
'constructor',
'toString',
'valueOf',
'hasOwnProperty',
'__proto__',
'prototype',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
];
// ─── Document-shaped generators ────────────────────────────────────────────
const whenArb = fc.constantFrom(...WHEN_VALUES);
// Ids are made unique WITHIN one generated document by suffixing the array
// index at assembly time (below) rather than relying on the raw string
// generator for uniqueness — this keeps the shape arbitrary while still
// letting assertions key on "this exact id".
const idBaseArb = fc.stringMatching(/^[a-z][a-z0-9-]{0,8}$/);
/** A document-order list of `{id, when}` sections, id uniqueness enforced by index-suffixing. */
const sectionsArb = fc
.array(fc.tuple(idBaseArb, whenArb), { minLength: 0, maxLength: 15 })
.map((pairs) => pairs.map(([base, when], idx) => ({ id: `${base}-${idx}`, when })));
const phaseNumberArb = fc.oneof(
fc.constant(null),
fc.constant(''),
fc.stringMatching(/^[0-9]{1,2}$/),
fc.stringMatching(/^[0-9]{1,2}\.[0-9]{1,2}$/),
);
const factsArb = fc.record({
waveFlag: fc.boolean(),
phaseNumber: phaseNumberArb,
hasPriorPhases: fc.boolean(),
});
// ─── Row 25: exact partition ────────────────────────────────────────────────
describe('property: selection is always an exact partition', () => {
test('selectionIsAlwaysAnExactPartitionOfInputSections', () => {
fc.assert(
fc.property(sectionsArb, factsArb, (sections, facts) => {
const { included, excluded } = selectSections(sections, facts);
const allIds = sections.map((s) => s.id);
// Union recovers every id exactly once, intersection is empty.
const unionSorted = [...included, ...excluded].sort();
assert.deepEqual(unionSorted, [...allIds].sort());
const intersection = included.filter((id) => excluded.includes(id));
assert.deepEqual(intersection, []);
}),
);
});
});
// ─── Row 26: `always` sections included under every fact combination ──────
describe('property: always sections are included under every fact combination', () => {
test('alwaysSectionsAreIncludedUnderEveryFactCombination', () => {
fc.assert(
fc.property(sectionsArb, factsArb, (sections, facts) => {
const { included } = selectSections(sections, facts);
const alwaysIds = sections.filter((s) => s.when === 'always').map((s) => s.id);
for (const id of alwaysIds) {
assert.equal(included.includes(id), true, `expected always-section "${id}" to be included`);
}
}),
);
});
});
// ─── Row 27: totality — never throws for vocab-valid when × arbitrary facts ─
describe('property: never throws for vocabulary-valid when and arbitrary facts', () => {
test('neverThrowsForVocabularyValidWhenAndArbitraryFacts', () => {
fc.assert(
fc.property(sectionsArb, factsArb, (sections, facts) => {
assert.doesNotThrow(() => selectSections(sections, facts));
}),
);
});
test('neverThrowsWhenFactsAreMissingKeysEntirely', () => {
// Totality also over PARTIAL facts objects (row 19's property-level
// twin): dropping zero or more of the three fact keys must never throw.
const factKeys = ['waveFlag', 'phaseNumber', 'hasPriorPhases'];
fc.assert(
fc.property(sectionsArb, factsArb, fc.subarray(factKeys), (sections, facts, keysToKeep) => {
const partialFacts = {};
for (const key of keysToKeep) partialFacts[key] = facts[key];
assert.doesNotThrow(() => selectSections(sections, partialFacts));
}),
);
});
});
// ─── Added during review: totality fails closed for prototype-shaped keys ──
// A hostile, Object.prototype-shaped `when` value injected anywhere in an
// otherwise vocab-valid document must always throw REASON.UNKNOWN_WHEN and
// must never appear in `included` — the prototype-chain fail-open the
// isolated adversarial pass found (constructor/toString/etc. resolving as
// truthy inherited members, or `__proto__` throwing an untyped error).
describe('property: prototype-shaped when values always fail closed', () => {
const hostileWhenArb = fc.constantFrom(...HOSTILE_WHEN_VALUES);
const hostileIdArb = fc.stringMatching(/^[a-z][a-z0-9-]{0,8}$/);
test('injectingAHostileWhenAnywhereAlwaysThrowsUnknownWhen', () => {
fc.assert(
fc.property(
sectionsArb,
hostileIdArb,
hostileWhenArb,
fc.nat(),
(sections, hostileIdBase, hostileWhen, rawIndex) => {
const hostileSection = { id: `hostile-${hostileIdBase}`, when: hostileWhen };
const insertAt = sections.length === 0 ? 0 : rawIndex % (sections.length + 1);
const withHostile = [...sections.slice(0, insertAt), hostileSection, ...sections.slice(insertAt)];
let caught;
try {
selectSections(withHostile, {});
} catch (err) {
caught = err;
}
assert.ok(caught instanceof TypeError, 'expected selectSections to throw for a hostile when value');
assert.equal(caught.reason, REASON.UNKNOWN_WHEN);
},
),
);
});
});
// ─── Row 28: order preservation ─────────────────────────────────────────────
describe('property: included ids preserve document order', () => {
test('includedIdsPreserveDocumentOrder', () => {
fc.assert(
fc.property(sectionsArb, factsArb, (sections, facts) => {
const { included, excluded } = selectSections(sections, facts);
const allIds = sections.map((s) => s.id);
// A subsequence check: the positions of `included` ids within
// `allIds`, taken in the order they appear in `included`, must be
// strictly increasing (never reordered relative to the input).
let cursor = -1;
for (const id of included) {
const pos = allIds.indexOf(id, cursor + 1);
assert.ok(pos > cursor, `id "${id}" out of document order in included[]`);
cursor = pos;
}
// Same subsequence guarantee for excluded[].
cursor = -1;
for (const id of excluded) {
const pos = allIds.indexOf(id, cursor + 1);
assert.ok(pos > cursor, `id "${id}" out of document order in excluded[]`);
cursor = pos;
}
}),
);
});
});

View File

@@ -0,0 +1,281 @@
'use strict';
/**
* Example-based unit tests for src/section-manifest.cts (compiled to
* gsd-core/bin/lib/section-manifest.cjs) — issue #2932 (epic #1671 Phase 5).
*
* Covers 50-test-matrix.md rows 1-24: section A (the pure `when=` evaluator)
* and section B (the `DEFECT.GENERATIVE-FIX` / Greenspun vocabulary parity
* guard against Phase 3's exported `WHEN_VOCABULARY`).
*
* No source-grep (CONTRIBUTING.md): every assertion is on typed values
* (`included`/`excluded` id arrays, the thrown error's `.reason`) — never on
* rendered text via `.includes()`/`.match()` of source/message prose.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const { selectSections, WHEN_PREDICATES, REASON } = require('../gsd-core/bin/lib/section-manifest.cjs');
const { WHEN_VOCABULARY } = require('../gsd-core/bin/lib/workflow-fragments.cjs');
// The three branch sections named throughout the design doc's behavior
// table, plus one `always` section — the exact shape `selectSections`
// consumes (structurally compatible with a parsed `WorkflowSection` array,
// but hand-built here since this suite tests the evaluator in isolation).
const BRANCH_SECTIONS = Object.freeze([
{ id: 'preamble', when: 'always' },
{ id: 'partial-wave', when: 'flag:--wave' },
{ id: 'gap-closure-artifacts', when: 'state:gap-closure-phase' },
{ id: 'regression-gate', when: 'state:has-prior-phases' },
]);
function facts(overrides) {
return { waveFlag: false, phaseNumber: null, hasPriorPhases: false, ...overrides };
}
// ─── Rows 1-8: happy path + combinations over W/D/P ─────────────────────────
describe('W/D/P combination matrix (design doc behavior table rows 1-8)', () => {
test('selectsOnlyAlwaysSectionsWhenNoFactsHold', () => {
const result = selectSections(BRANCH_SECTIONS, facts({}));
assert.deepEqual(result.included, ['preamble']);
assert.deepEqual(result.excluded, ['partial-wave', 'gap-closure-artifacts', 'regression-gate']);
});
test('includesPartialWaveWhenWaveFlagPresent', () => {
const result = selectSections(BRANCH_SECTIONS, facts({ waveFlag: true }));
assert.deepEqual(result.included, ['preamble', 'partial-wave']);
assert.deepEqual(result.excluded, ['gap-closure-artifacts', 'regression-gate']);
});
test('includesGapClosureWhenPhaseNumberHasDecimal', () => {
const result = selectSections(BRANCH_SECTIONS, facts({ phaseNumber: '3.1' }));
assert.deepEqual(result.included, ['preamble', 'gap-closure-artifacts']);
assert.deepEqual(result.excluded, ['partial-wave', 'regression-gate']);
});
test('includesRegressionGateWhenPriorPhasesExist', () => {
const result = selectSections(BRANCH_SECTIONS, facts({ hasPriorPhases: true }));
assert.deepEqual(result.included, ['preamble', 'regression-gate']);
assert.deepEqual(result.excluded, ['partial-wave', 'gap-closure-artifacts']);
});
test('includesBothWaveAndGapClosureWhenBothHold', () => {
const result = selectSections(BRANCH_SECTIONS, facts({ waveFlag: true, phaseNumber: '3.1' }));
assert.deepEqual(result.included, ['preamble', 'partial-wave', 'gap-closure-artifacts']);
assert.deepEqual(result.excluded, ['regression-gate']);
});
test('includesBothWaveAndRegressionWhenBothHold', () => {
const result = selectSections(BRANCH_SECTIONS, facts({ waveFlag: true, hasPriorPhases: true }));
assert.deepEqual(result.included, ['preamble', 'partial-wave', 'regression-gate']);
assert.deepEqual(result.excluded, ['gap-closure-artifacts']);
});
test('includesBothGapClosureAndRegressionWhenBothHold', () => {
const result = selectSections(BRANCH_SECTIONS, facts({ phaseNumber: '3.1', hasPriorPhases: true }));
assert.deepEqual(result.included, ['preamble', 'gap-closure-artifacts', 'regression-gate']);
assert.deepEqual(result.excluded, ['partial-wave']);
});
test('includesEveryBranchSectionWhenAllFactsHold', () => {
const result = selectSections(BRANCH_SECTIONS, facts({ waveFlag: true, phaseNumber: '3.1', hasPriorPhases: true }));
assert.deepEqual(result.included, ['preamble', 'partial-wave', 'gap-closure-artifacts', 'regression-gate']);
assert.deepEqual(result.excluded, []);
});
});
// ─── Rows 9-14: phase-number decimal boundary + hostile literal rule ───────
describe('gap-closure-phase predicate boundary and hostile inputs', () => {
test('treatsTrailingZeroDecimalPhaseAsGapClosure', () => {
assert.equal(WHEN_PREDICATES['state:gap-closure-phase'](facts({ phaseNumber: '3.0' })), true);
});
test('treatsZeroPaddedDecimalPhaseAsGapClosure', () => {
assert.equal(WHEN_PREDICATES['state:gap-closure-phase'](facts({ phaseNumber: '03.1' })), true);
});
test('treatsIntegerPhaseAsNotGapClosure', () => {
assert.equal(WHEN_PREDICATES['state:gap-closure-phase'](facts({ phaseNumber: '3' })), false);
assert.equal(WHEN_PREDICATES['state:gap-closure-phase'](facts({ phaseNumber: '04' })), false);
});
test('treatsNullPhaseNumberAsNotGapClosure', () => {
assert.equal(WHEN_PREDICATES['state:gap-closure-phase'](facts({ phaseNumber: null })), false);
});
test('treatsEmptyPhaseNumberAsNotGapClosure', () => {
assert.equal(WHEN_PREDICATES['state:gap-closure-phase'](facts({ phaseNumber: '' })), false);
});
test('treatsBareDotPhaseNumberLiterallyPerDocumentedRule', () => {
// The predicate is deliberately literal (`.includes('.')`) per the
// design doc's negative-space note — it does not invent a stricter
// regex the section body's documented rule does not claim.
assert.equal(WHEN_PREDICATES['state:gap-closure-phase'](facts({ phaseNumber: '.' })), true);
});
});
// ─── Rows 15-17: boundary section-list sizes ────────────────────────────────
describe('boundary section-list sizes (limit-1 / limit / limit+1)', () => {
test('returnsEmptySelectionForWorkflowWithNoSections', () => {
const result = selectSections([], facts({}));
assert.deepEqual(result, { included: [], excluded: [] });
});
test('partitionsSingleSectionWorkflow', () => {
const includedResult = selectSections([{ id: 'only', when: 'always' }], facts({}));
assert.deepEqual(includedResult, { included: ['only'], excluded: [] });
const excludedResult = selectSections([{ id: 'only', when: 'flag:--wave' }], facts({}));
assert.deepEqual(excludedResult, { included: [], excluded: ['only'] });
});
test('preservesDocumentOrderAcrossManySections', () => {
// Duplicates-by-when: several sections sharing the SAME when= value must
// each retain their own id and their own document-order position.
const sections = [
{ id: 's0', when: 'always' },
{ id: 's1', when: 'flag:--wave' },
{ id: 's2', when: 'always' },
{ id: 's3', when: 'flag:--wave' },
{ id: 's4', when: 'state:gap-closure-phase' },
{ id: 's5', when: 'always' },
{ id: 's6', when: 'state:has-prior-phases' },
];
const result = selectSections(sections, facts({ waveFlag: true }));
assert.deepEqual(result.included, ['s0', 's1', 's2', 's3', 's5']);
assert.deepEqual(result.excluded, ['s4', 's6']);
});
});
// ─── Row 18: fail-closed on unknown when= ───────────────────────────────────
describe('fail-closed on an unrecognized when= value', () => {
test('throwsOnWhenValueOutsideFrozenVocabulary', () => {
assert.throws(
() => selectSections([{ id: 'x', when: 'flag:--nonexistent' }], facts({})),
(err) => err instanceof TypeError && err.reason === REASON.UNKNOWN_WHEN,
);
});
});
// ─── Row 19: totality over facts ────────────────────────────────────────────
describe('totality: an absent fact key is treated as falsy, never throws', () => {
test('treatsAbsentFactAsFalseWithoutThrowing', () => {
assert.doesNotThrow(() => selectSections(BRANCH_SECTIONS, {}));
const result = selectSections(BRANCH_SECTIONS, {});
assert.deepEqual(result.included, ['preamble']);
assert.deepEqual(result.excluded, ['partial-wave', 'gap-closure-artifacts', 'regression-gate']);
});
});
// ─── Row 20: determinism + non-mutation ─────────────────────────────────────
describe('determinism and input non-mutation', () => {
test('isDeterministicAndDoesNotMutateInput', () => {
const sections = [
{ id: 'a', when: 'always' },
{ id: 'b', when: 'flag:--wave' },
];
const snapshotBefore = sections.map((s) => ({ ...s }));
const f = facts({ waveFlag: true });
const first = selectSections(sections, f);
const second = selectSections(sections, f);
assert.deepEqual(first, second);
assert.deepEqual(sections, snapshotBefore);
assert.equal(Array.isArray(sections), true);
assert.equal(sections.length, 2);
});
});
// ─── Rows 21-23: DEFECT.GENERATIVE-FIX vocabulary parity guard ─────────────
describe('WHEN_PREDICATES and WHEN_VOCABULARY parity (DEFECT.GENERATIVE-FIX)', () => {
test('everyFrozenVocabularyEntryHasAPredicate', () => {
for (const when of WHEN_VOCABULARY) {
assert.equal(typeof WHEN_PREDICATES[when], 'function', `expected a predicate for when="${when}"`);
}
});
test('everyPredicateKeyIsInTheFrozenVocabulary', () => {
for (const when of Object.keys(WHEN_PREDICATES)) {
assert.equal(WHEN_VOCABULARY.includes(when), true, `predicate key "${when}" is not in WHEN_VOCABULARY`);
}
});
test('failsWhenVocabularyGainsAnEntryWithoutAPredicate', () => {
// Simulates a 5th vocabulary entry being added without a corresponding
// predicate: the SAME parity check as row 21, run against a vocabulary
// array with an extra entry, must fail (i.e. NOT every entry has a
// predicate) until a predicate is added on the evaluator side too.
const widenedVocabulary = [...WHEN_VOCABULARY, 'state:not-yet-real'];
const missing = widenedVocabulary.filter((when) => typeof WHEN_PREDICATES[when] !== 'function');
assert.deepEqual(missing, ['state:not-yet-real']);
});
});
// ─── Row 24: REASON enum shape is locked ────────────────────────────────────
describe('REASON enum is frozen and its shape is locked', () => {
test('locksReasonEnumKeySet', () => {
assert.equal(Object.isFrozen(REASON), true);
assert.deepEqual(Object.keys(REASON).sort(), ['UNKNOWN_WHEN']);
});
});
// ─── Rows 25-33: Object.prototype-shaped when= values fail closed ──────────
// Added during review — prototype-chain fail-open found by isolated
// adversarial pass. A bracket lookup on a plain frozen object resolves
// inherited Object.prototype members (`constructor`, `toString`, etc.) as if
// they were predicates, silently including the section or throwing an
// untyped error instead of failing closed with REASON.UNKNOWN_WHEN.
describe('Object.prototype-shaped when= values fail closed (REASON.UNKNOWN_WHEN)', () => {
const HOSTILE_WHEN_VALUES = Object.freeze([
'constructor',
'toString',
'valueOf',
'hasOwnProperty',
'__proto__',
'prototype',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
]);
for (const when of HOSTILE_WHEN_VALUES) {
test(`throwsUnknownWhenFor_${when}`, () => {
assert.throws(
() => selectSections([{ id: 'x', when }], facts({})),
(err) => err instanceof TypeError && err.reason === REASON.UNKNOWN_WHEN,
);
});
test(`neverIncludesSectionFor_${when}`, () => {
let caught;
try {
selectSections([{ id: 'x', when }], facts({}));
} catch (err) {
caught = err;
}
assert.ok(caught, `expected selectSections to throw for when="${when}"`);
assert.equal(caught.reason, REASON.UNKNOWN_WHEN);
});
}
test('noneOfTheHostileValuesAppearInIncludedAcrossAMixedSectionList', () => {
for (const when of HOSTILE_WHEN_VALUES) {
assert.throws(
() => selectSections([{ id: 'safe', when: 'always' }, { id: 'hostile', when }], facts({})),
(err) => err instanceof TypeError && err.reason === REASON.UNKNOWN_WHEN,
);
}
});
});

View File

@@ -25,7 +25,12 @@ const fs = require('node:fs');
const path = require('node:path');
const ROOT = path.join(__dirname, '..');
// #2932: the regression-gate step was split — steps/regression-gate.md now only
// discovers prior-phase test files and delegates (via "Read and execute") to
// steps/regression-gate-run.md, which carries the actual command resolution,
// normalize-test-command call, timeout bound, and watch-mode abort mechanics.
const REGRESSION_GATE = path.join(ROOT, 'gsd-core', 'workflows', 'execute-phase', 'steps', 'regression-gate.md');
const REGRESSION_GATE_RUN = path.join(ROOT, 'gsd-core', 'workflows', 'execute-phase', 'steps', 'regression-gate-run.md');
const POST_MERGE_GATE = path.join(ROOT, 'gsd-core', 'workflows', 'execute-phase', 'steps', 'post-merge-gate.md');
const AUDIT_FIX = path.join(ROOT, 'gsd-core', 'workflows', 'audit-fix.md');
const VERIFY_PHASE = path.join(ROOT, 'gsd-core', 'workflows', 'verify-phase.md');
@@ -34,8 +39,9 @@ const EXECUTE_PHASE = path.join(ROOT, 'gsd-core', 'workflows', 'execute-phase.md
function read(p) { return fs.readFileSync(p, 'utf-8'); }
// The three gates that were unbounded/silently-continued: full normalize + configured timeout.
// Regression gate's mechanics now live in the delegated regression-gate-run.md (#2932).
const FULL_GATES = [
['regression gate', REGRESSION_GATE],
['regression gate', REGRESSION_GATE_RUN],
['post-merge gate', POST_MERGE_GATE],
['audit-fix gate', AUDIT_FIX],
];
@@ -86,7 +92,7 @@ describe('#1857: test gates normalize to one-shot and bound with a timeout', ()
test('the gates share ONE normalizer — the helper is a single source of truth', () => {
// The behaviour lives in src/normalize-test-command.cts; every gate invokes it
// by the same verb name, so a change to watch-defeat logic touches one place.
for (const file of [REGRESSION_GATE, POST_MERGE_GATE, AUDIT_FIX, VERIFY_PHASE]) {
for (const file of [REGRESSION_GATE_RUN, POST_MERGE_GATE, AUDIT_FIX, VERIFY_PHASE]) {
assert.match(read(file), /gsd_run query normalize-test-command/);
}
});
@@ -109,7 +115,7 @@ describe('#2350: every gate resolves build/test commands with --raw', () => {
// build a shell command it then runs. Add new gates here as they appear.
const GATE_FILES = [
['post-merge gate', POST_MERGE_GATE],
['regression gate', REGRESSION_GATE],
['regression gate', REGRESSION_GATE_RUN],
['verify-phase gate', VERIFY_PHASE],
['audit-fix gate', AUDIT_FIX],
];

View File

@@ -452,6 +452,37 @@ test('nonWorkflowMarkdownWithMarkerShapedLineIsNotComposed', () => {
// ─── Row 36: a malformed marker fails install loudly, with no partial emit ─
// ─── Row 63 (50-test-matrix.md, issue #2932 Phase 5): extracting
// execute-phase.md's 3 sections must not perturb any OTHER workflow's
// emission — independence guard for the CRITICAL blast radius Phase 5's own
// design doc calls out. Pure-function check (no spawn needed): composeWorkflow
// is a documented no-op for every unmarked file, so any file other than the
// one Phase 5 migrates must still compose to itself, byte-identical. ────────
test('leavesUnmarkedWorkflowEmissionByteIdentical', () => {
const workflowsDir = path.join(REPO_ROOT, 'gsd-core', 'workflows');
const workflowFiles = fs
.readdirSync(workflowsDir, { withFileTypes: true })
.filter((d) => d.isFile() && d.name.endsWith('.md'))
.map((d) => d.name);
assert.ok(workflowFiles.length > 1, 'sanity: there must be more than the pilot workflow on disk');
let checkedCount = 0;
for (const fileName of workflowFiles) {
if (fileName === 'execute-phase.md') continue; // the one file #2932 Phase 5 migrates
const filePath = path.join(workflowsDir, fileName);
const source = fs.readFileSync(filePath, 'utf8');
const composed = composeWorkflow(source, { sourcePath: filePath });
assert.equal(
composed,
source,
`${fileName}: emission drifted — Phase 5's execute-phase.md extraction must not touch any other workflow`,
);
checkedCount += 1;
}
assert.equal(checkedCount, workflowFiles.length - 1, 'every workflow file except execute-phase.md must have been checked');
});
test('malformedMarkersFailInstallWithoutPartialEmit', () => {
const malformed = '<!-- gsd:section id="broken" when="always" -->\nnever closed\n';
const overlayRepo = buildOverlayRepo({ 'gsd-core/workflows/execute-phase.md': malformed });