Files
msd-core/tests/command-routing-hub.test.cjs
Tom Boucher ff4a57b78c chore(#1671): migrate the remaining 13 LARGE/XL workflows to the fragment model — Phase 6.3 (#3030)
* chore(#2994): fragmentize progress.md forensic audit onto the fragment model

Extract the --forensic-gated forensic_audit step to
workflows/progress/steps/forensic-audit.md behind a section marker, and
repair progress.md's init line to forward --forensic so the atom is
actually true in production rather than only under direct CLI tests.

progress.md shrinks 32630 -> 27207 bytes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize the four manifest-wired workflows

new-project, quick, new-milestone and progress each already had a
dedicated cmdInit* entry point but zero marked sections. Extract nine
gated bodies to workflows/<wf>/steps/ behind section markers and repair
each init line to forward its flags.

Fold --full into the discuss/research/validate facts inside cmdInitQuick
so the when= grammar never sees an OR, per the chunked-mode precedent.

Fixes found while working, per the no-defer rule:
- cmdInitProgress passed no phase info to buildSectionManifestField, so
  state:phase-mvp-mode was permanently false — an atom in the vocabulary
  whose fact could never be computed.
- the quick init router folded flag tokens into the free-text
  description, which the new forwarding would have corrupted.
- a #2508 dispatch note was nested inside quick.md's Agent(prompt=)
  fence, leaking orchestrator guidance into the subagent prompt.
- progress.md had a 3-vs-4 backtick outer-fence imbalance.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize verify-work.md and admit state:ui-phase-active

Wire cmdInitVerifyWork to buildSectionManifestField — it was a dedicated
entry point that never emitted a manifest — and mark two sections.

state:ui-phase-active folds (plan:pre hooks include an active ui step) OR
(the phase dir holds a *-UI-SPEC.md) into one boolean in init.cts, so the
grammar still sees a single operator-free atom. The inner Playwright-MCP
check stays as prose inside the fragment: it is live session state and no
init seam can precompute it.

The MVP false-branch note is a real fallback, not redundant prose, so it
sits outside the marker — gating it away would delete the text needed
precisely when MVP mode is off.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(#2994): follow moved workflow content in drift guards

Retarget every guard that asserted on content this branch moved into
workflows/<wf>/steps/, mirroring 815b3d897. Each retargeted assertion was
verified to still fail when its step file is blanked, so none was
weakened into vacuity.

Three assertions in verify-mvp-uat were genuinely red. Three more were
worse than red — passing for the wrong reason:
- quick-commit-boundary and worktree-cleanup anchored on indexOf('Step
  5.6'), which matched a later cross-reference and sliced 16069 chars
  that coincidentally held the asserted substrings. Replaced with an
  expandWorkflowSections helper that splices step content back in place.
- phase6-review-capabilities lost its end boundary and widened to EOF.
- playwright-ui-verify matched 'UI' in an unrelated bullet and 'fall
  back' in a subagent-dispatch line after the real content moved.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize code-review and complete-milestone, admit three atoms

Add dedicated cmdInitCodeReview and cmdInitCompleteMilestone entry points
alongside the shared generic ones rather than modifying them — init.phase-op
and init.manager carry a CRITICAL blast radius (179 dependents, 24
processes) and stay byte-identical for their other callers.

Admit flag:--fix, state:fallow-enabled and state:git-create-tag, each with
a consuming section and a fact its own entry point computes.

Both sections had the resolver-in-body hazard: the fallow config-gate and
the git.create_tag check each sat inside the very block being gated, so
gating would have disabled the resolver that decides the gate. Both are
hoisted into init and the bodies now consume the resolved fact.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(#2994): retarget code-review and milestone drift guards, fix two red tests

Retarget guards that asserted on content moved into steps/, proving
non-vacuity by blanking each step file and confirming failure.

Also fixes two genuinely red tests found while working, per the no-defer
rule:
- workflow-fragments' frozen-vocabulary lock was missing
  state:ui-phase-active, so commit 7ef7f8336 shipped red. Lint and build
  both passed over it, which is why neither is sufficient verification.
- code-review's quick.md capability-hook assertion carried a stale
  delimiter after the 18ff35d20 extraction.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize autonomous.md and admit state:plan-strategy-converge

Five sections share one atom, the pattern plan-phase already uses for
flag:--research-phase. The atom folds --converge OR --cross-ai into a
single boolean in cmdInitAutonomous so the grammar stays operator-free.

cmdInitAutonomous is additive; init.milestone-op, init.manager and
init.phase-op are untouched and still consumed. The $PLAN_STRATEGY bash
resolver is deliberately retained — ungated local-planning bullets still
read it, so the init-side fact supplements it rather than replacing it.

converge-fail-fast required splitting one bash fence so the always-run
CONVERGENCE_ARGS construction stays outside the marker. All three
flag-absent fallbacks were left outside their markers.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize review and discuss-phase-assumptions

Admit state:reviewer-instances-configured (two peripheral notes share it;
the core reviewer-lane dispatch stays unmarked — it is the workflow's
primary always-evaluated logic, not an optional branch) and
state:auto-advance-active, which folds --auto OR two config keys into one
boolean so the grammar stays operator-free.

discuss-phase-assumptions was the highest-risk edit in this PR. Its
auto_advance step is a full if/elif/else; gating it whole would have
deleted the flag-absent fallback needed exactly when --auto is off. Split
verified exact: resolvers 636-651 and the 'End here' fallback 668-669 both
stay outside the marker; only 653-667 is gated.

Adds emitted-drift acks for the two files that grew — review.md (+55 B)
and autonomous.md (+737 B from 80799211c, which had none and would have
red-gated the push.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): fragmentize docs-update, update, transition and new-milestone Part A

Completes the 13-workflow rollout. Three of these had no init call at all
and gained a dedicated entry point plus their first gsd_run query line.

Admits state:is-monorepo and adds state:next-channel, state:workstream-active
and state:flat-mode. Vocabulary 26 -> 30 atoms.

Part A of new-milestone applies when NO workstream is active — the negation
of state:workstream-active. Rather than teach the grammar negation, which is
the Greenspun drift the frozen list exists to prevent, it gets a separate
positively-phrased atom whose fact is the inverse. Part B, which always runs,
stays outside the marker.

flag:--verify-only is deliberately NOT admitted: docs-update has no
contiguous purely-additive region for it, and an atom without a consuming
section is dead vocabulary. Evidence recorded in the slice report.

update.md reuses its existing resolved $GSD_TOOLS rather than prepending the
canonical preamble, which would have clobbered it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): stop automated-ui-verification re-resolving its own gate, retire dead vocabulary

Two defects the new tests caught.

The automated-ui-verification step re-ran gsd_run loop render-hooks and
recomputed UI_PHASE_ACTIVE inside a body that is only read when that fact
is already true — the circular self-disabling pattern this design forbids,
introduced by 3c654b168. cmdInitVerifyWork now exposes ui_phase_active and
the step consumes it. Its launcher preamble goes too: no gsd_run remains.
The Playwright-MCP check stays as prose — that is live session state.

Dead vocabulary predating this PR: flag:--full and state:needs-codebase-map
were admitted with a gate-1 claim that never materialized. flag:--full is
removed, redundant once quick folds it into discuss/research/validate.
state:needs-codebase-map gets the real consumer it always lacked, gating
new-project's codebase-map offer. Vocabulary 30 -> 29, and no atom is now
without a consuming section.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(#2994): add the atom-admission, inversion and resolver-hoist gates

The two existing parity guards prove vocabulary/predicate symmetry but
never that a fact is computed — an atom no cmdInit* assembles evaluates
false forever. These close that hole:

- per-atom satisfiability for all 29 atoms, plus an anti-vacuity assertion
  so the loop cannot silently cover zero atoms
- dead-vocabulary check against the shipped manifest
- inversion guard: the flag-absent fallbacks in discuss-phase-assumptions
  and verify-work must stay outside their markers
- data-driven resolver-hoist guard over the shipped manifest, so a future
  extraction cannot reintroduce the circular class
- compound-fold coverage (--full, --cross-ai, --rc, config-only --auto)
- null-vs-[] degraded/computed distinction, and flag value shapes

Also repairs the frozen-vocabulary lock, which was stale and red for the
seven atoms earlier commits on this branch shipped.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(#2994): add changeset for the fragment-model rollout

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(#2994): cite the issue on the two new allow-test-rule exemptions

ADR-456 requires an issue ref on the same line as the annotation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(#2994): correct the atom-count claims after retiring flag:--full

The vocabulary doc comments still said 30 entries; it is 29 since
flag:--full was removed as dead vocabulary.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): dedupe the phase-fallback block and harden --ws parsing

Review findings.

MAJOR: the three new init entry points each pasted a verbatim copy of the
guardedFindPhase/guardedGetRoadmapPhase fallback, taking the repo from four
copies to seven — DEFECT.GENERATIVE-FIX. Extracted applyRoadmapFallback and
folded six of the seven; each call site keeps its own field-set via a
closure. Duplication removed rather than papered over with a parity test.
cmdInitPhaseOp stays out: its fallback omits has_reviews, so it is not a
byte-identical copy, and it is CRITICAL-radius.

LOW, pre-existing: GSD_WS captured [^[:space:]]+ and expands unquoted, so a
workstream name holding glob metacharacters would expand against the
filesystem. Narrowed to [A-Za-z0-9._-]+. The unquoted expansion is kept —
it must word-split into two args and vanish when empty.

Also restores the vocabulary ordering convention, and fixes a masked test
bug the mandated run surfaced: the flag-forwarding guard checked only the
first init line per workflow, but new-milestone has two, so a real failure
was reporting exit 0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): drop the stale new-milestone emitted-drift ack

new-milestone.md was acked for a +406 B growth measured against an
intermediate commit. Net against origin/next it SHRANK by 8 bytes, so
nothing needed the ack and it explained nothing — which the differential
attribution check reports as a stale acknowledgment, not a pass.

update.md's entry stays: it genuinely grew +703 B.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): resolve the 15 failures from the full matrix run

All 15 were real and identical on both lanes.

REAL REGRESSION: autonomous.md hit 41479 chars against the #2196 guard's
40960 cap — a CHARS cap distinct from the LARGE tier byte cap, which the
five section stubs pushed it over. Extracted the 3a.5 UI Design Contract
body to references/; now 39968 chars, and the file nets -795 B vs base, so
its growth ack is deleted rather than left stale.

REAL DEFECT: docs referenced /gsd-transition, which is not a live
registered command. Reworded.

STALE FIXTURE: the emission byte-identity test hardcoded two marked
workflows; this branch legitimately marks fifteen. Fixture corrected — the
source was right.

The rest were drift guards over the eight workflows the earlier sweep did
not cover, retargeted at where the content now lives with non-vacuity
proven by blanking each step file and confirming failure. The GSD_WS
forwarding guard was checked as a possible real break and is not one: the
charclass narrowing is intact and forwarding works end to end.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): drop the ack for a newly-added reference file

A new file's emitted ripple is attributable to the diff that adds it, so
the acknowledgment explained nothing and the differential check reports it
as stale. Removing the last entry removes the fragment — an empty one
signals nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#2994): retarget the UI-contract guards and clear two transitive advisories

The §3a.5 extraction that brought autonomous.md under the #2196 char cap
moved its body to references/autonomous-ui-design-contract.md, so ten
guards in autonomous-ui-steps and check-ui-safety-gate were asserting it
against the host. Retargeted via a combined read, each proven non-vacuous
by blanking the reference file and confirming failure.

This class had already bitten twice on this branch because each sweep was
scoped to the workflows touched at that moment, so this one was
exhaustive: ~70 test files across all 13 workflows, zero further broken or
vacuous assertions found.

Also clears two high transitive advisories the matrix flagged on one lane
— fast-uri GHSA-7p8r-x3mc-p8w7 and three ip-address SSRF/trust-boundary
issues. Both pre-date this branch: package-lock.json was untouched until
now, so the production tree was byte-identical to the base. Lockfile-only,
package.json unchanged, verified against a real npm ci install.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(#2994): backfill changeset pr number to 3030

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-03 19:59:58 -04:00

1889 lines
78 KiB
JavaScript

'use strict';
/**
* Behavioral contract tests for the CommandRoutingHub (issue #3788, #175).
*
* #175: mode/sdkLoader/SdkDispatchFailed dropped. Hub always routes CJS.
*
* Testing rules in force (CONTRIBUTING.md § Testing Standards):
* 1. No readFileSync of source files. All assertions are on return values
* from the hub's dispatch() function.
* 2. Stub cjsRegistry / manifest — the hub is the unit under test.
* No real SDK load, no real CJS handler invocation (except one integration
* path in the phase-command-router migration tests).
* 3. ERROR_KINDS is a frozen enum. Tests switch on its values, not string literals.
* 4. Hub must never throw. Every error surface arrives as { ok: false, ... }.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const {
createHub,
ERROR_KINDS,
makeUnknownCommand,
makeInvalidArgs,
makeHandlerRefusal,
makeHandlerFailure,
} = require('../gsd-core/bin/lib/command-routing-hub.cjs');
// ─── Frozen taxonomy lock ─────────────────────────────────────────────────────
// #175: SdkDispatchFailed and SdkLoadFailed are removed from the closed enum.
// The set shrinks from 6 to 4 values.
const EXPECTED_ERROR_KINDS = Object.freeze(new Set([
'UnknownCommand',
'InvalidArgs',
'HandlerRefusal',
'HandlerFailure',
]));
describe('CommandRoutingHub — ERROR_KINDS taxonomy', () => {
test('exports a frozen ERROR_KINDS object', () => {
assert.ok(Object.isFrozen(ERROR_KINDS), 'ERROR_KINDS must be frozen');
});
test('ERROR_KINDS contains exactly the 4 documented values (SdkDispatchFailed and SdkLoadFailed removed)', () => {
const actual = new Set(Object.values(ERROR_KINDS));
assert.deepStrictEqual(actual, EXPECTED_ERROR_KINDS);
});
test('ERROR_KINDS does NOT contain SdkDispatchFailed', () => {
assert.ok(!Object.values(ERROR_KINDS).includes('SdkDispatchFailed'),
'SdkDispatchFailed must not be in ERROR_KINDS after #175');
});
test('ERROR_KINDS does NOT contain SdkLoadFailed', () => {
assert.ok(!Object.values(ERROR_KINDS).includes('SdkLoadFailed'),
'SdkLoadFailed must not be in ERROR_KINDS after #175');
});
test('ERROR_KINDS keys match their values (self-documenting enum)', () => {
for (const [key, value] of Object.entries(ERROR_KINDS)) {
assert.equal(key, value, `ERROR_KINDS.${key} should equal '${key}' but got '${value}'`);
}
});
});
// ─── createHub validation ──────────────────────────────────────────────────────
// #175: mode param is removed. Hub is constructed without mode.
describe('CommandRoutingHub — createHub validation', () => {
test('constructs successfully without any mode parameter', () => {
// Hub no longer requires mode — no throw when mode is absent
const hub = createHub({ cjsRegistry: {} });
assert.ok(typeof hub.dispatch === 'function');
});
test('mode parameter is ignored — passing mode: sdk does not route to SDK', () => {
// Even if a legacy caller passes mode:'sdk', the hub must use CJS dispatch.
const cjsCalls = [];
const hub = createHub({
mode: 'sdk',
cjsRegistry: {
phase: {
add: (_ctx) => { cjsCalls.push(true); return { ok: true, data: 'cjs-dispatched' }; },
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
// Must route through CJS, not SDK
assert.ok(result.ok, `Expected ok:true but got: ${JSON.stringify(result)}`);
assert.equal(result.data, 'cjs-dispatched', 'Hub must dispatch through CJS regardless of mode parameter');
assert.equal(cjsCalls.length, 1, 'CJS handler must be called exactly once');
});
test('mode parameter is ignored — passing mode: cjs also routes through CJS', () => {
const cjsCalls = [];
const hub = createHub({
mode: 'cjs',
cjsRegistry: {
state: {
load: (_ctx) => { cjsCalls.push(true); return { ok: true, data: 'state-loaded' }; },
},
},
});
const result = hub.dispatch({ family: 'state', subcommand: 'load', args: [], cwd: '/', raw: false });
assert.ok(result.ok);
assert.equal(result.data, 'state-loaded');
assert.equal(cjsCalls.length, 1);
});
test('sdkLoader parameter is inert — passing sdkLoader does not cause SDK dispatch', () => {
// sdkLoader is removed; passing it must not cause the Hub to call it
const sdkCalls = [];
const hub = createHub({
sdkLoader: () => { sdkCalls.push(true); return () => ({ ok: true, data: 'sdk-data' }); },
cjsRegistry: {
phase: {
add: (_ctx) => ({ ok: true, data: 'cjs-data' }),
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.equal(sdkCalls.length, 0, 'sdkLoader must never be called — it is removed in #175');
assert.ok(result.ok);
assert.equal(result.data, 'cjs-data');
});
});
// ─── Happy path — always CJS ──────────────────────────────────────────────────
describe('CommandRoutingHub — happy path, CJS dispatch', () => {
test('dispatch returns { ok: true, data } from CJS handler result', () => {
const hub = createHub({
cjsRegistry: {
phase: {
complete: (_ctx) => ({ ok: true, data: { completed: true } }),
},
},
manifest: { phase: ['complete'] },
});
const result = hub.dispatch({ family: 'phase', subcommand: 'complete', args: ['01'], cwd: '/tmp', raw: false });
assert.ok(result.ok);
assert.deepEqual(result.data, { completed: true });
});
test('dispatch passes full context to CJS handler', () => {
const received = [];
const hub = createHub({
cjsRegistry: {
roadmap: {
analyze: (ctx) => { received.push(ctx); return { ok: true, data: null }; },
},
},
});
hub.dispatch({ family: 'roadmap', subcommand: 'analyze', args: ['--verbose'], cwd: '/myproj', raw: true });
assert.equal(received.length, 1);
assert.equal(received[0].family, 'roadmap');
assert.equal(received[0].subcommand, 'analyze');
assert.deepEqual(received[0].args, ['--verbose']);
assert.equal(received[0].cwd, '/myproj');
assert.equal(received[0].raw, true);
});
test('handler returning undefined is treated as ok:true with data:null', () => {
const hub = createHub({
cjsRegistry: {
state: {
load: (_ctx) => undefined,
},
},
});
const result = hub.dispatch({ family: 'state', subcommand: 'load', args: [], cwd: '/', raw: false });
assert.ok(result.ok);
assert.equal(result.data, null);
});
test('handler returning a plain value wraps it as data payload', () => {
const hub = createHub({
cjsRegistry: {
verify: {
check: (_ctx) => 'all-good',
},
},
});
const result = hub.dispatch({ family: 'verify', subcommand: 'check', args: [], cwd: '/', raw: false });
assert.ok(result.ok);
assert.equal(result.data, 'all-good');
});
});
// ─── kind: UnknownCommand ─────────────────────────────────────────────────────
describe('CommandRoutingHub — kind: UnknownCommand', () => {
test('unknown family in manifest returns UnknownCommand', () => {
const hub = createHub({
cjsRegistry: {},
manifest: { phase: ['add'] },
});
const result = hub.dispatch({ family: 'bogus', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.UnknownCommand);
});
test('unknown subcommand in manifest returns UnknownCommand', () => {
const hub = createHub({
cjsRegistry: {},
manifest: { phase: ['add'] },
});
const result = hub.dispatch({ family: 'phase', subcommand: 'nonexistent', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.UnknownCommand);
});
test('missing family in cjsRegistry returns UnknownCommand (no manifest)', () => {
const hub = createHub({
cjsRegistry: { state: { load: () => ({ ok: true, data: null }) } },
});
const result = hub.dispatch({ family: 'bogus-family', subcommand: 'sub', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.UnknownCommand);
});
test('missing subcommand in cjsRegistry returns UnknownCommand', () => {
const hub = createHub({
cjsRegistry: { phase: { add: () => ({ ok: true, data: null }) } },
});
const result = hub.dispatch({ family: 'phase', subcommand: 'not-there', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.UnknownCommand);
});
});
// ─── kind: InvalidArgs ────────────────────────────────────────────────────────
describe('CommandRoutingHub — kind: InvalidArgs', () => {
test('handler returning InvalidArgs result propagates it', () => {
const hub = createHub({
cjsRegistry: {
phase: {
insert: (_ctx) => ({
ok: false,
kind: ERROR_KINDS.InvalidArgs,
arg: 'phase-number',
reason: 'phase insert requires a phase number',
}),
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'insert', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.InvalidArgs);
assert.ok(result.reason.includes('phase number'));
});
});
// ─── kind: HandlerRefusal ─────────────────────────────────────────────────────
describe('CommandRoutingHub — kind: HandlerRefusal', () => {
test('handler returning HandlerRefusal result propagates it', () => {
const hub = createHub({
cjsRegistry: {
phase: {
'list-plans': (_ctx) => ({
ok: false,
kind: ERROR_KINDS.HandlerRefusal,
reason: 'phase list-plans is not supported in this router.',
}),
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'list-plans', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerRefusal);
});
});
// ─── kind: HandlerFailure ─────────────────────────────────────────────────────
describe('CommandRoutingHub — kind: HandlerFailure', () => {
test('hub does not throw when CJS handler throws — returns HandlerFailure', () => {
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => { throw new Error('handler blew up'); },
},
},
});
let result;
assert.doesNotThrow(() => {
result = hub.dispatch({ family: 'phase', subcommand: 'add', args: ['desc'], cwd: '/', raw: false });
});
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerFailure);
assert.ok(result.message.includes('handler blew up'));
});
test('HandlerFailure cause carries the thrown error', () => {
const originalError = new Error('boom');
const hub = createHub({
cjsRegistry: {
state: {
load: (_ctx) => { throw originalError; },
},
},
});
const result = hub.dispatch({ family: 'state', subcommand: 'load', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerFailure);
assert.strictEqual(result.cause, originalError);
});
});
// ─── hub never throws ─────────────────────────────────────────────────────────
describe('CommandRoutingHub — hub never throws', () => {
test('hub does not throw even when cjsRegistry is completely absent', () => {
const hub = createHub({});
let result;
assert.doesNotThrow(() => {
result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
});
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.UnknownCommand);
});
test('hub does not throw when dispatch receives malformed request', () => {
const hub = createHub({ cjsRegistry: {} });
let result;
assert.doesNotThrow(() => {
// Missing family — would normally throw on string ops
result = hub.dispatch({ family: undefined, subcommand: 'add', args: [], cwd: '/', raw: false });
});
// Result is an error, not a thrown exception
assert.ok(!result.ok);
});
});
// ─── P1.2: Typed-payload discriminated union (#176) ──────────────────────────
// Each error variant carries ONLY its own typed payload.
// `errorKind` field renamed to `kind`; generic `message`/`details` removed
// from variants that have dedicated fields.
describe('CommandRoutingHub — P1.2 typed-payload discriminated union (#176)', () => {
// ── UnknownCommand: { ok, kind, command } — no message, no details ──────────
test('UnknownCommand has exactly { ok, kind, command } — nothing else', () => {
const hub = createHub({
cjsRegistry: {},
manifest: { phase: ['add'] },
});
const result = hub.dispatch({ family: 'bogus', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.UnknownCommand);
assert.equal(typeof result.command, 'string');
assert.ok(result.command.length > 0, 'command field must be non-empty');
// Strict field set — no errorKind, no message, no details
const keys = Object.keys(result).sort();
assert.deepStrictEqual(keys, ['command', 'kind', 'ok']);
});
test('UnknownCommand for unknown subcommand carries the command string', () => {
const hub = createHub({
cjsRegistry: {},
manifest: { phase: ['add'] },
});
const result = hub.dispatch({ family: 'phase', subcommand: 'nonexistent', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.UnknownCommand);
assert.ok(result.command.includes('nonexistent'), `Expected command to include 'nonexistent', got: ${result.command}`);
});
test('UnknownCommand from missing cjsRegistry family carries the command string', () => {
const hub = createHub({
cjsRegistry: { state: { load: () => ({ ok: true, data: null }) } },
});
const result = hub.dispatch({ family: 'bogus-family', subcommand: 'sub', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.UnknownCommand);
assert.ok(result.command.includes('bogus-family'), `Expected command to include 'bogus-family', got: ${result.command}`);
});
// ── InvalidArgs: { ok, kind, arg, reason } — no message, no details ─────────
test('InvalidArgs result from handler is propagated with kind/arg/reason fields', () => {
const hub = createHub({
cjsRegistry: {
phase: {
insert: (_ctx) => ({
ok: false,
kind: ERROR_KINDS.InvalidArgs,
arg: '--dry-run',
reason: 'phase insert does not support --dry-run',
}),
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'insert', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.InvalidArgs);
assert.equal(result.arg, '--dry-run');
assert.ok(result.reason.includes('--dry-run'));
// Strict field set
const keys = Object.keys(result).sort();
assert.deepStrictEqual(keys, ['arg', 'kind', 'ok', 'reason']);
});
// ── HandlerRefusal: { ok, kind, reason } — no message, no details ────────────
test('HandlerRefusal result from handler is propagated with kind/reason fields', () => {
const hub = createHub({
cjsRegistry: {
phase: {
'list-plans': (_ctx) => ({
ok: false,
kind: ERROR_KINDS.HandlerRefusal,
reason: 'phase list-plans is not supported in this router.',
}),
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'list-plans', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerRefusal);
assert.ok(result.reason.includes('not supported'));
// Strict field set
const keys = Object.keys(result).sort();
assert.deepStrictEqual(keys, ['kind', 'ok', 'reason']);
});
// ── HandlerFailure: { ok, kind, message, cause? } — cause carries the Error ──
test('HandlerFailure from throw has { ok, kind, message, cause } — no details', () => {
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => { throw new Error('handler blew up'); },
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: ['desc'], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerFailure);
assert.ok(result.message.includes('handler blew up'));
assert.ok(result.cause instanceof Error);
// Strict field set (cause present when Error thrown)
const keys = Object.keys(result).sort();
assert.deepStrictEqual(keys, ['cause', 'kind', 'message', 'ok']);
});
test('HandlerFailure cause carries the original thrown Error object', () => {
const originalError = new Error('boom');
const hub = createHub({
cjsRegistry: {
state: {
load: (_ctx) => { throw originalError; },
},
},
});
const result = hub.dispatch({ family: 'state', subcommand: 'load', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerFailure);
assert.strictEqual(result.cause, originalError);
});
// ── ERROR_KINDS values used as `kind` discriminator — still work ─────────────
test('ERROR_KINDS values are stable string constants matching their key names', () => {
assert.equal(ERROR_KINDS.UnknownCommand, 'UnknownCommand');
assert.equal(ERROR_KINDS.InvalidArgs, 'InvalidArgs');
assert.equal(ERROR_KINDS.HandlerRefusal, 'HandlerRefusal');
assert.equal(ERROR_KINDS.HandlerFailure, 'HandlerFailure');
});
});
// ─── No SDK path — single-dispatch invariant ──────────────────────────────────
// #175: Hub is always CJS. There is no SDK path to fall through to.
describe('CommandRoutingHub — single CJS dispatch invariant (#175)', () => {
test('two dispatches through the same hub produce consistent CJS results', () => {
const calls = [];
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => { calls.push('add'); return { ok: true, data: 'added' }; },
complete: (_ctx) => { calls.push('complete'); return { ok: true, data: 'done' }; },
},
},
});
const r1 = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
const r2 = hub.dispatch({ family: 'phase', subcommand: 'complete', args: [], cwd: '/', raw: false });
assert.ok(r1.ok);
assert.equal(r1.data, 'added');
assert.ok(r2.ok);
assert.equal(r2.data, 'done');
assert.deepEqual(calls, ['add', 'complete']);
});
test('manifest check still applies in CJS-only hub', () => {
const hub = createHub({
cjsRegistry: { phase: { add: () => ({ ok: true, data: null }) } },
manifest: { phase: ['add'] },
});
const known = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
const unknown = hub.dispatch({ family: 'phase', subcommand: 'nonexistent', args: [], cwd: '/', raw: false });
assert.ok(known.ok);
assert.ok(!unknown.ok);
assert.equal(unknown.kind, ERROR_KINDS.UnknownCommand);
});
});
// ─── P1.2 Review Finding 1: Hub runtime-validates ok:false handler returns ────
// A handler that returns { ok: false, kind: 'InvalidArgs', message: 'oops' }
// (missing `reason`, has stray `message`) must NOT pass through unchanged.
// Hub must coerce it to a HandlerFailure with a contract-violation message.
describe('CommandRoutingHub — Finding 1: runtime-validation of handler ok:false returns', () => {
test('malformed InvalidArgs return (missing reason, has stray message) is coerced to HandlerFailure', () => {
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => ({
ok: false,
kind: 'InvalidArgs',
message: 'oops', // wrong: should be reason, not message
// missing: arg, reason
}),
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.ok(!result.ok, 'result must be an error');
assert.equal(result.kind, ERROR_KINDS.HandlerFailure,
`Expected HandlerFailure but got kind: ${result.kind}`);
assert.ok(
result.message.includes('malformed') || result.message.includes('contract') ||
result.message.includes('InvalidArgs') || result.message.includes('reason'),
`Expected contract-violation message, got: ${result.message}`
);
});
test('malformed HandlerRefusal return (missing reason) is coerced to HandlerFailure', () => {
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => ({
ok: false,
kind: 'HandlerRefusal',
message: 'refuse', // wrong: should be reason
// missing: reason
}),
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerFailure);
assert.ok(typeof result.message === 'string' && result.message.length > 0);
});
test('malformed HandlerFailure return (missing message) is coerced to HandlerFailure', () => {
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => ({
ok: false,
kind: 'HandlerFailure',
// missing: message
details: 'something', // extraneous
}),
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerFailure);
assert.ok(typeof result.message === 'string' && result.message.length > 0);
});
test('well-formed InvalidArgs return is NOT coerced — passes through unchanged', () => {
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => ({
ok: false,
kind: 'InvalidArgs',
arg: '--dry-run',
reason: 'not supported',
}),
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.InvalidArgs);
assert.equal(result.arg, '--dry-run');
assert.equal(result.reason, 'not supported');
});
test('unknown kind in ok:false return is coerced to HandlerFailure', () => {
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => ({
ok: false,
kind: 'SomeLegacyKind',
errorKind: 'SomeLegacyKind',
}),
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerFailure);
});
});
// ─── P1.2 Review Finding 2: Non-Error throws preserve the original throwable ──
// When a handler throws a non-Error (plain object, string, number), the Hub must
// wrap it in an Error and attach .thrown = originalValue.
describe('CommandRoutingHub — Finding 2: non-Error throws preserve original throwable', () => {
test('handler throwing a plain object → HandlerFailure with cause.thrown === original', () => {
const thrown = { custom: 'payload', code: 42 };
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => { throw thrown; },
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerFailure);
assert.ok(result.cause instanceof Error,
`result.cause must be an Error, got: ${typeof result.cause}`);
assert.strictEqual(result.cause.thrown, thrown,
'cause.thrown must be the original thrown object');
});
test('handler throwing a string → HandlerFailure with cause.thrown === original string', () => {
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => { throw 'just a string'; },
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerFailure);
assert.ok(result.cause instanceof Error,
`result.cause must be an Error, got: ${typeof result.cause}`);
assert.strictEqual(result.cause.thrown, 'just a string',
'cause.thrown must be the original thrown string');
});
test('handler throwing a number → HandlerFailure with cause.thrown === original number', () => {
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => { throw 404; },
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerFailure);
assert.ok(result.cause instanceof Error);
assert.strictEqual(result.cause.thrown, 404);
});
test('handler throwing a real Error still works — cause is the Error itself (no .thrown wrapping)', () => {
const original = new Error('real error');
const hub = createHub({
cjsRegistry: {
phase: {
add: (_ctx) => { throw original; },
},
},
});
const result = hub.dispatch({ family: 'phase', subcommand: 'add', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.HandlerFailure);
assert.strictEqual(result.cause, original, 'Error throws must have cause === original Error');
// No .thrown on real Error cause
assert.equal(result.cause.thrown, undefined);
});
});
// ─── P1.2 Review Finding 3: Factory returns are Object.frozen ─────────────────
// Each makeXxx factory must return a frozen object so callers cannot mutate
// the variant invariant.
describe('CommandRoutingHub — Finding 3: factory returns are Object.frozen', () => {
test('makeUnknownCommand returns a frozen object', () => {
const result = makeUnknownCommand('phase bogus');
assert.ok(Object.isFrozen(result),
'makeUnknownCommand must return a frozen object');
});
test('makeInvalidArgs returns a frozen object', () => {
const result = makeInvalidArgs('--dry-run', 'not supported');
assert.ok(Object.isFrozen(result),
'makeInvalidArgs must return a frozen object');
});
test('makeHandlerRefusal returns a frozen object', () => {
const result = makeHandlerRefusal('not supported');
assert.ok(Object.isFrozen(result),
'makeHandlerRefusal must return a frozen object');
});
test('makeHandlerFailure returns a frozen object', () => {
const result = makeHandlerFailure('something broke', new Error('orig'));
assert.ok(Object.isFrozen(result),
'makeHandlerFailure must return a frozen object');
});
test('frozen factory results cannot be mutated', () => {
const result = makeUnknownCommand('phase bogus');
// In strict mode, mutation of a frozen object throws TypeError
assert.throws(
() => { result.command = 'tampered'; },
TypeError,
'Mutating a frozen factory result must throw TypeError'
);
});
});
// ─── P1.2 Review Finding 4: makeHandlerFailure wraps non-Error causes ─────────
// If cause is provided but is not an Error, wrap it so .cause instanceof Error.
// Attach .thrown = originalCause so it is not silently dropped.
describe('CommandRoutingHub — Finding 4: makeHandlerFailure wraps non-Error causes', () => {
test('makeHandlerFailure("msg", "string-cause") → cause instanceof Error', () => {
const result = makeHandlerFailure('msg', 'string-cause');
assert.ok(result.cause instanceof Error,
`cause must be an Error, got: ${typeof result.cause}`);
});
test('makeHandlerFailure("msg", "string-cause") → cause.thrown === "string-cause"', () => {
const result = makeHandlerFailure('msg', 'string-cause');
assert.strictEqual(result.cause.thrown, 'string-cause',
'cause.thrown must be the original non-Error cause');
});
test('makeHandlerFailure with a plain object cause → cause instanceof Error with .thrown', () => {
const obj = { code: 42, detail: 'bad' };
const result = makeHandlerFailure('msg', obj);
assert.ok(result.cause instanceof Error);
assert.strictEqual(result.cause.thrown, obj);
});
test('makeHandlerFailure with a real Error cause → cause is the original Error (no wrapping)', () => {
const original = new Error('real');
const result = makeHandlerFailure('msg', original);
assert.strictEqual(result.cause, original,
'Real Error causes must not be wrapped');
});
test('makeHandlerFailure without cause → result.cause is undefined', () => {
const result = makeHandlerFailure('msg');
assert.equal(result.cause, undefined);
});
test('makeHandlerFailure with null cause → behaves as no cause (undefined)', () => {
// null is not an Error, but "not provided" — treat as absent
const result = makeHandlerFailure('msg', null);
// null should not be wrapped into an Error — it's equivalent to "no cause"
assert.equal(result.cause, undefined);
});
});
// ─── Amendment #1642: exitReason? field on InvalidArgs (Phase 1, #1644) ───────
// The optional exitReason? field carries an ERROR_REASON enum value separately
// from the existing `reason` explanation text. The factory conditionally adds
// the field only when a truthy third arg is provided, preserving the strict-keys
// invariant tested above (L444).
describe('CommandRoutingHub — exitReason? field on InvalidArgs (#1644 / amendment #1642)', () => {
test('makeInvalidArgs(arg, reason) 2-arg form omits exitReason key (strict-keys invariant preserved)', () => {
const result = makeInvalidArgs('--phase', '--phase must be an integer');
const keys = Object.keys(result).sort();
assert.deepStrictEqual(keys, ['arg', 'kind', 'ok', 'reason'],
`2-arg form must NOT include exitReason key; got: ${JSON.stringify(keys)}`);
assert.equal(result.exitReason, undefined);
});
test('makeInvalidArgs(arg, reason, exitReason) 3-arg form includes exitReason key with the value', () => {
const result = makeInvalidArgs('--phase', '--phase must be an integer', 'USAGE');
const keys = Object.keys(result).sort();
assert.deepStrictEqual(keys, ['arg', 'exitReason', 'kind', 'ok', 'reason'],
`3-arg form must include exitReason key; got: ${JSON.stringify(keys)}`);
assert.equal(result.exitReason, 'USAGE');
});
test('makeInvalidArgs(arg, reason, undefined) treats undefined as absent (omits key)', () => {
const result = makeInvalidArgs('--phase', '--phase must be an integer', undefined);
const keys = Object.keys(result).sort();
assert.deepStrictEqual(keys, ['arg', 'kind', 'ok', 'reason'],
`undefined exitReason must be omitted; got: ${JSON.stringify(keys)}`);
});
test('makeInvalidArgs(arg, reason, "") treats empty string as absent (omits key)', () => {
const result = makeInvalidArgs('--phase', '--phase must be an integer', '');
const keys = Object.keys(result).sort();
assert.deepStrictEqual(keys, ['arg', 'kind', 'ok', 'reason'],
`empty-string exitReason must be omitted; got: ${JSON.stringify(keys)}`);
});
test('3-arg factory result is still frozen', () => {
const result = makeInvalidArgs('--phase', 'required', 'USAGE');
assert.ok(Object.isFrozen(result), '3-arg factory result must be frozen');
});
test('hub.dispatch propagates handler-returned InvalidArgs with exitReason unchanged', () => {
const hub = createHub({
cjsRegistry: {
unit: {
check: (_ctx) => ({
ok: false,
kind: ERROR_KINDS.InvalidArgs,
arg: '--flag',
reason: 'not supported',
exitReason: 'USAGE',
}),
},
},
});
const result = hub.dispatch({ family: 'unit', subcommand: 'check', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.InvalidArgs);
assert.equal(result.arg, '--flag');
assert.equal(result.reason, 'not supported');
assert.equal(result.exitReason, 'USAGE',
`Hub must propagate exitReason from handler-returned InvalidArgs; got: ${JSON.stringify(result)}`);
});
test('hub.dispatch still accepts InvalidArgs WITHOUT exitReason (no contract regression)', () => {
const hub = createHub({
cjsRegistry: {
unit: {
check: (_ctx) => ({
ok: false,
kind: ERROR_KINDS.InvalidArgs,
arg: '--flag',
reason: 'not supported',
}),
},
},
});
const result = hub.dispatch({ family: 'unit', subcommand: 'check', args: [], cwd: '/', raw: false });
assert.ok(!result.ok);
assert.equal(result.kind, ERROR_KINDS.InvalidArgs);
assert.equal(result.exitReason, undefined,
`Hub must not synthesize exitReason when handler omits it; got: ${JSON.stringify(result)}`);
});
test('hub validator does NOT reject InvalidArgs with exitReason (well-formed extension)', () => {
// The runtime validator (_validateErrResult) coerces MALFORMED returns to HandlerFailure.
// A well-formed InvalidArgs with the new exitReason field must NOT be coerced.
const hub = createHub({
cjsRegistry: {
unit: {
check: (_ctx) => ({
ok: false,
kind: ERROR_KINDS.InvalidArgs,
arg: '--flag',
reason: 'required',
exitReason: 'USAGE',
}),
},
},
});
const result = hub.dispatch({ family: 'unit', subcommand: 'check', args: [], cwd: '/', raw: false });
assert.equal(result.kind, ERROR_KINDS.InvalidArgs,
`Extended InvalidArgs must not be coerced to HandlerFailure; got kind: ${result.kind}`);
});
});
// ────────────────────────────────────────────────────────────────────────
// Folded from tests/bug-167-query-meta-command.test.cjs — consolidation epic #1969 (B2 #1971)
// ────────────────────────────────────────────────────────────────────────
{
const { describe: __foldDescribe } = require('node:test');
__foldDescribe("folded:bug-167-query-meta-command (consolidation epic #1969 B2 #1971)", () => {
'use strict';
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { runGsdTools } = require('./helpers.cjs');
test('bug #167: query meta-command prefixes direct gsd-tools calls', () => {
const direct = runGsdTools(['init.progress']);
assert.equal(direct.success, true, `init.progress failed: ${direct.error || direct.output}`);
const meta = runGsdTools(['query', 'init.progress']);
assert.equal(meta.success, true, `query init.progress failed: ${meta.error || meta.output}`);
assert.deepEqual(
JSON.parse(meta.output),
JSON.parse(direct.output),
'query-prefixed and direct invocations should return identical init.progress payloads'
);
});
});
}
// ────────────────────────────────────────────────────────────────────────
// Folded from tests/bug-1818-unknown-flags.test.cjs — consolidation epic #1969 (B2 #1971)
// ────────────────────────────────────────────────────────────────────────
{
const { describe: __foldDescribe } = require('node:test');
__foldDescribe("folded:bug-1818-unknown-flags (consolidation epic #1969 B2 #1971)", () => {
/**
* Regression test for bug #1818, updated for #3019.
*
* Original #1818 invariant: gsd-tools must NOT silently ignore --help/-h
* and proceed with a destructive command — that turned AI-agent
* hallucinations into accidental data loss (e.g. `phases clear --help`
* deleting phase dirs because the flag was dropped).
*
* #3019 update: the same destructive-protection invariant still holds,
* but the response shape changed. Previously --help → non-zero error
* exit. Now --help → render top-level usage and exit 0 WITHOUT running
* the command. Both shapes satisfy the original invariant ("the
* destructive command did not execute"); the new shape also restores
* subcommand discoverability for `gsd-sdk query <subcommand> --help`.
*
* The tests therefore assert two things:
* 1. The destructive command did NOT run (anti-hallucination invariant).
* 2. The output contains the top-level usage (#3019 discoverability).
*
* --version remains rejected — it's never a valid gsd-tools flag and has
* no discovery use-case.
*/
'use strict';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { runGsdTools, createTempProject, cleanup, isUsageOutput } = require('./helpers.cjs');
describe('unknown flag guard (bug #1818, updated for #3019)', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
// ── --help renders usage and does NOT run the destructive command ────────
test('phases clear --help renders usage and does NOT clear phase dirs', () => {
// Create a sentinel phase dir so we can assert it survives.
const phaseDir = path.join(tmpDir, '.planning', 'phases', 'phase-99');
fs.mkdirSync(phaseDir, { recursive: true });
fs.writeFileSync(path.join(phaseDir, 'PLAN.md'), 'sentinel');
const result = runGsdTools(['phases', 'clear', '--help'], tmpDir);
assert.strictEqual(result.success, true, 'help renders, no error exit');
assert.ok(isUsageOutput(result.output), `expected top-level usage, got: ${result.output}`);
// Anti-hallucination invariant: the destructive command did NOT run.
assert.ok(fs.existsSync(phaseDir), 'phase dir must survive — clear must not have executed');
assert.ok(fs.existsSync(path.join(phaseDir, 'PLAN.md')));
});
test('generate-slug hello --help renders usage and does NOT emit a slug', () => {
const ok = runGsdTools(['generate-slug', 'hello'], tmpDir);
assert.strictEqual(ok.success, true, 'control: generate-slug works without --help');
// The control output is just the slug; the help output is the usage.
const slugOut = ok.output;
assert.ok(slugOut && !isUsageOutput(slugOut), `control should not be usage: ${slugOut}`);
const result = runGsdTools(['generate-slug', 'hello', '--help'], tmpDir);
assert.strictEqual(result.success, true);
assert.ok(isUsageOutput(result.output), 'help renders top-level usage');
assert.notEqual(result.output, slugOut, 'help output must differ from the slug — generate-slug must not have run');
});
test('phase complete --help renders usage and does NOT mark a phase complete', () => {
const result = runGsdTools(['phase', 'complete', '--help'], tmpDir);
assert.strictEqual(result.success, true);
assert.ok(isUsageOutput(result.output));
// success:true + isUsageOutput is sufficient: if the destructive path
// had executed it would have emitted a phase-resolution error to stderr
// (success:false), not the usage to stdout (success:true).
});
test('state load --help renders usage', () => {
const result = runGsdTools(['state', 'load', '--help'], tmpDir);
assert.strictEqual(result.success, true);
assert.ok(isUsageOutput(result.output));
});
// ── -h shorthand: same shape ─────────────────────────────────────────────
test('phases clear -h renders usage and does NOT clear phase dirs', () => {
const phaseDir = path.join(tmpDir, '.planning', 'phases', 'phase-42');
fs.mkdirSync(phaseDir, { recursive: true });
const result = runGsdTools(['phases', 'clear', '-h'], tmpDir);
assert.strictEqual(result.success, true);
assert.ok(isUsageOutput(result.output));
assert.ok(fs.existsSync(phaseDir), 'phase dir must survive');
});
test('generate-slug hello -h renders usage', () => {
const result = runGsdTools(['generate-slug', 'hello', '-h'], tmpDir);
assert.strictEqual(result.success, true);
assert.ok(isUsageOutput(result.output));
});
// ── --version is still rejected — no discovery use-case ──────────────────
test('generate-slug hello --version is rejected', () => {
const result = runGsdTools(['generate-slug', 'hello', '--version'], tmpDir);
assert.strictEqual(result.success, false);
assert.match(result.error, /--version/);
});
// ── current-timestamp --help: same as the others ─────────────────────────
test('current-timestamp --help renders usage', () => {
const result = runGsdTools(['current-timestamp', '--help'], tmpDir);
assert.strictEqual(result.success, true);
assert.ok(isUsageOutput(result.output));
});
});
});
}
// ────────────────────────────────────────────────────────────────────────
// Folded from tests/feat-3255-json-errors-mode.test.cjs — consolidation epic #1969 (B2 #1971)
// ────────────────────────────────────────────────────────────────────────
{
const { describe: __foldDescribe } = require('node:test');
__foldDescribe("folded:feat-3255-json-errors-mode (consolidation epic #1969 B2 #1971)", () => {
/**
* Tests for the --json-errors mode added in #3255.
*
* When gsd-tools is invoked with --json-errors, all error() calls emit a
* structured JSON object to stderr:
*
* { ok: false, reason: "<error_code>", message: "<human text>" }
*
* This lets tests assert on typed reason codes instead of grepping free-form
* stderr text. All assertions below parse the captured stderr via JSON.parse
* and inspect typed fields — never result.error.includes() (#2974 / k001).
*
* Covered error paths (representative set, each exercises a different branch):
* 1. Unknown top-level command → reason: "sdk_unknown_command"
* 2. Unknown dotted command → reason: "sdk_unknown_command"
* 3. Missing required argument → reason: "usage" (--pick without value)
* 4. Config key not found → reason: "config_key_not_found"
* 5. Unknown subcommand → reason: "sdk_unknown_command"
* 6. GSD_JSON_ERRORS=1 env var → same structured output without --flag
* 7. Successful command unaffected
* 8. Error object shape is stable ({ok, reason, message})
* 9. Single error line per invocation
* 10. Unknown flag → reason: "usage"
*/
'use strict';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
// Helper: run gsd-tools with --json-errors and parse the structured stderr.
// Returns the parsed object, or throws if stderr is not valid JSON.
function runJsonErrors(args, tmpDir, env = {}) {
const allArgs = ['--json-errors', ...args];
const result = runGsdTools(allArgs, tmpDir, env);
// Must have failed
assert.strictEqual(result.success, false,
`Expected failure with --json-errors for args: ${args.join(' ')}\nstdout: ${result.output}\nstderr: ${result.error}`);
let parsed;
try {
parsed = JSON.parse(result.error);
} catch (e) {
throw new Error(
`--json-errors must emit valid JSON on stderr.\n` +
`Args: ${args.join(' ')}\n` +
`stderr: ${result.error}\n` +
`parse error: ${e.message}`
);
}
return parsed;
}
describe('feat #3255: --json-errors mode emits structured error objects', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
// ── 1. Unknown top-level command ─────────────────────────────────────────
test('unknown top-level command emits { ok: false, reason: "sdk_unknown_command" }', () => {
const parsed = runJsonErrors(['totally-unknown-command-xyzzy'], tmpDir);
assert.strictEqual(parsed.ok, false,
'error object must have ok: false');
assert.strictEqual(parsed.reason, 'sdk_unknown_command',
`reason must be "sdk_unknown_command", got: ${parsed.reason}`);
assert.ok(typeof parsed.message === 'string' && parsed.message.length > 0,
'message must be a non-empty string');
});
// ── 2. Unknown dotted command ────────────────────────────────────────────
test('unknown dotted command (foo.bar) emits { ok: false, reason: "sdk_unknown_command" }', () => {
const parsed = runJsonErrors(['foo.bar'], tmpDir);
assert.strictEqual(parsed.ok, false,
'error object must have ok: false');
assert.strictEqual(parsed.reason, 'sdk_unknown_command',
`dotted unknown command reason must be "sdk_unknown_command", got: ${parsed.reason}`);
assert.ok(typeof parsed.message === 'string' && parsed.message.length > 0,
'message must be a non-empty string');
});
// ── 3. Missing --pick value ───────────────────────────────────────────────
test('--pick without value emits { ok: false, reason: "usage" }', () => {
const parsed = runJsonErrors(['generate-slug', 'test-text', '--pick'], tmpDir);
assert.strictEqual(parsed.ok, false,
'error object must have ok: false');
assert.strictEqual(parsed.reason, 'usage',
`missing --pick value reason must be "usage", got: ${parsed.reason}`);
assert.ok(typeof parsed.message === 'string' && parsed.message.length > 0,
'message must be a non-empty string');
});
// ── 4. Config key not found ───────────────────────────────────────────────
test('config-get for absent key emits { ok: false, reason: "config_key_not_found" }', () => {
// Initialise config.json first so we reach the "key not found" branch
// rather than the "no config.json" branch.
runGsdTools(['config-ensure-section'], tmpDir);
const parsed = runJsonErrors(['config-get', 'nonexistent_config_key_xyzzy'], tmpDir);
assert.strictEqual(parsed.ok, false,
'error object must have ok: false');
assert.strictEqual(parsed.reason, 'config_key_not_found',
`reason must be "config_key_not_found", got: ${parsed.reason}`);
assert.ok(typeof parsed.message === 'string' && parsed.message.length > 0,
'message must be a non-empty string');
});
// ── 5. Unknown subcommand within a domain ────────────────────────────────
test('unknown intel subcommand emits { ok: false, reason: "sdk_unknown_command" }', () => {
const parsed = runJsonErrors(['intel', 'bogus-subcommand-xyzzy'], tmpDir);
assert.strictEqual(parsed.ok, false,
'error object must have ok: false');
assert.strictEqual(parsed.reason, 'sdk_unknown_command',
`unknown subcommand reason must be "sdk_unknown_command", got: ${parsed.reason}`);
assert.ok(typeof parsed.message === 'string' && parsed.message.length > 0,
'message must be a non-empty string');
});
// ── 6. GSD_JSON_ERRORS=1 env var activates structured mode ───────────────
test('GSD_JSON_ERRORS=1 env var produces same structured error as --json-errors flag', () => {
// Run with env var instead of --json-errors flag
const result = runGsdTools(
['totally-unknown-command-xyzzy'],
tmpDir,
{ GSD_JSON_ERRORS: '1' }
);
assert.strictEqual(result.success, false,
'command must fail');
let parsed;
try {
parsed = JSON.parse(result.error);
} catch (e) {
throw new Error(
`GSD_JSON_ERRORS=1 must emit valid JSON on stderr.\n` +
`stderr: ${result.error}\n` +
`parse error: ${e.message}`
);
}
assert.strictEqual(parsed.ok, false,
'error object must have ok: false');
assert.strictEqual(parsed.reason, 'sdk_unknown_command',
`reason must be "sdk_unknown_command", got: ${parsed.reason}`);
});
// ── 7. Successful commands are unaffected by --json-errors ───────────────
test('successful command with --json-errors flag still succeeds normally', () => {
const result = runGsdTools(
['--json-errors', 'generate-slug', 'hello-world'],
tmpDir
);
assert.strictEqual(result.success, true,
`Successful command must not be broken by --json-errors flag.\nstderr: ${result.error}`);
assert.ok(result.output.length > 0,
'stdout must be non-empty for successful generate-slug');
});
// ── 8. Error object shape is stable (no extra top-level keys) ────────────
test('error object contains exactly {ok, reason, message} — no extra keys', () => {
const parsed = runJsonErrors(['totally-unknown-command-xyzzy'], tmpDir);
const keys = Object.keys(parsed).sort();
assert.deepStrictEqual(keys, ['message', 'ok', 'reason'],
`error object must have exactly {ok, reason, message}. Got keys: ${keys.join(', ')}`);
});
// ── 9. Multiple errors in one session: only the first error is emitted ───
test('only one error JSON line is emitted per invocation (process exits on first error)', () => {
const result = runGsdTools(
['--json-errors', 'totally-unknown-command-xyzzy'],
tmpDir
);
assert.strictEqual(result.success, false, 'must fail');
const lines = result.error.trim().split('\n').filter(l => l.length > 0);
assert.strictEqual(lines.length, 1,
`stderr must contain exactly one JSON line, got ${lines.length}:\n${result.error}`);
// Also verify the single line is valid JSON
const parsed = JSON.parse(lines[0]);
assert.strictEqual(parsed.ok, false);
});
// ── 10. Unknown flag emits { ok: false, reason: "usage" } ────────────────
test('unknown version flag emits { ok: false, reason: "usage" }', () => {
const parsed = runJsonErrors(['--version', 'generate-slug', 'x'], tmpDir);
assert.strictEqual(parsed.ok, false, 'error object must have ok: false');
assert.strictEqual(parsed.reason, 'usage',
`--version flag reason must be "usage", got: ${parsed.reason}`);
});
});
});
}
// ────────────────────────────────────────────────────────────────────────
// Folded from tests/feat-3310-followup-typed-codes.test.cjs — consolidation epic #1969 (B2 #1971)
// ────────────────────────────────────────────────────────────────────────
{
const { describe: __foldDescribe } = require('node:test');
__foldDescribe("folded:feat-3310-followup-typed-codes (consolidation epic #1969 B2 #1971)", () => {
/**
* Follow-up tests for #3310: every remaining `error()` call at a subcommand
* boundary or usage check in `gsd-tools.cjs` carries a typed `ERROR_REASON`.
*
* #3304 wired four representative paths (unknown top-level command, unknown
* intel subcommand, missing --pick value, --version flag). The rest fell
* through to `ERROR_REASON.UNKNOWN`. This file locks the post-#3310 contract:
*
* - Every "Unknown <subsystem> subcommand" emits reason: "sdk_unknown_command".
* - Every "Usage: ..." / missing-required-arg path emits reason: "usage".
*
* All assertions parse stderr via JSON.parse — never `.includes()` — per the
* #2974 / CONTRIBUTING.md "Prohibited: Raw Text Matching" rule.
*/
'use strict';
const { describe, test, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
// Run gsd-tools with GSD_JSON_ERRORS=1 (env-var activation, exercises the
// path #3304 added alongside the --json-errors flag) and parse the
// structured stderr. Returns the parsed object; throws if stderr is not JSON.
function runJsonErrors(args, tmpDir, env = {}) {
const result = runGsdTools(args, tmpDir, { ...env, GSD_JSON_ERRORS: '1' });
assert.strictEqual(result.success, false,
`Expected failure with GSD_JSON_ERRORS=1 for args: ${args.join(' ')}\n` +
`stdout: ${result.output}\nstderr: ${result.error}`);
let parsed;
try {
parsed = JSON.parse(result.error);
} catch (e) {
throw new Error(
`GSD_JSON_ERRORS=1 must emit valid JSON on stderr.\n` +
`Args: ${args.join(' ')}\nstderr: ${result.error}\nparse error: ${e.message}`
);
}
return parsed;
}
// Assert the typed-IR contract: object shape + reason. Keeps the per-test
// boilerplate minimal so each error-path test reads as a single fact.
function assertTypedError(parsed, expectedReason, label) {
assert.strictEqual(parsed.ok, false,
`${label}: error object must have ok: false`);
assert.strictEqual(parsed.reason, expectedReason,
`${label}: reason must be "${expectedReason}", got: ${parsed.reason}`);
assert.ok(typeof parsed.message === 'string' && parsed.message.length > 0,
`${label}: message must be a non-empty string`);
}
describe('feat #3310: typed ERROR_REASON codes on remaining error paths', () => {
let tmpDir;
beforeEach(() => {
tmpDir = createTempProject();
});
afterEach(() => {
cleanup(tmpDir);
});
// ── Unknown <subsystem> subcommand → SDK_UNKNOWN_COMMAND ────────────────
// Each of these used to fall through to reason: "unknown" before #3310.
test('unknown template subcommand → sdk_unknown_command', () => {
const parsed = runJsonErrors(['template', 'bogus-subcommand-xyzzy'], tmpDir);
assertTypedError(parsed, 'sdk_unknown_command', 'template');
});
test('unknown frontmatter subcommand → sdk_unknown_command', () => {
// frontmatter expects subcommand at args[1] and file at args[2]; pass a
// bogus subcommand with a placeholder file so we definitely reach the
// unknown-subcommand branch, not an earlier validation.
const parsed = runJsonErrors(
['frontmatter', 'bogus-subcommand-xyzzy', 'placeholder.md'],
tmpDir
);
assertTypedError(parsed, 'sdk_unknown_command', 'frontmatter');
});
test('unknown requirements subcommand → sdk_unknown_command', () => {
const parsed = runJsonErrors(['requirements', 'bogus-subcommand-xyzzy'], tmpDir);
assertTypedError(parsed, 'sdk_unknown_command', 'requirements');
});
test('unknown milestone subcommand → sdk_unknown_command', () => {
const parsed = runJsonErrors(['milestone', 'bogus-subcommand-xyzzy'], tmpDir);
assertTypedError(parsed, 'sdk_unknown_command', 'milestone');
});
test('unknown uat subcommand → sdk_unknown_command', () => {
const parsed = runJsonErrors(['uat', 'bogus-subcommand-xyzzy'], tmpDir);
assertTypedError(parsed, 'sdk_unknown_command', 'uat');
});
test('unknown todo subcommand → sdk_unknown_command', () => {
const parsed = runJsonErrors(['todo', 'bogus-subcommand-xyzzy'], tmpDir);
assertTypedError(parsed, 'sdk_unknown_command', 'todo');
});
test('unknown workstream subcommand → sdk_unknown_command', () => {
const parsed = runJsonErrors(['workstream', 'bogus-subcommand-xyzzy'], tmpDir);
assertTypedError(parsed, 'sdk_unknown_command', 'workstream');
});
test('unknown graphify subcommand → sdk_unknown_command', () => {
const parsed = runJsonErrors(['graphify', 'bogus-subcommand-xyzzy'], tmpDir);
assertTypedError(parsed, 'sdk_unknown_command', 'graphify');
});
test('unknown learnings subcommand → sdk_unknown_command', () => {
const parsed = runJsonErrors(['learnings', 'bogus-subcommand-xyzzy'], tmpDir);
assertTypedError(parsed, 'sdk_unknown_command', 'learnings');
});
// ── Missing required positional/flag values → USAGE ─────────────────────
// These previously emitted reason: "unknown" because the second argument
// to error() was absent.
test('missing --cwd value → usage', () => {
// The --cwd flag is consumed before the command dispatcher; passing it
// bare with no following value triggers the usage error at L253/L258.
const parsed = runJsonErrors(['--cwd'], tmpDir);
assertTypedError(parsed, 'usage', '--cwd missing value');
});
test('invalid --cwd directory → usage', () => {
// --cwd <nonexistent-path> hits the existsSync / isDirectory check at L264.
const parsed = runJsonErrors(
['--cwd', '/this/path/should/not/exist/anywhere/xyzzy', 'state', 'load'],
tmpDir
);
assertTypedError(parsed, 'usage', 'invalid --cwd directory');
});
test('intel query missing term → usage', () => {
const parsed = runJsonErrors(['intel', 'query'], tmpDir);
assertTypedError(parsed, 'usage', 'intel query missing term');
});
test('intel patch-meta missing file path → usage', () => {
const parsed = runJsonErrors(['intel', 'patch-meta'], tmpDir);
assertTypedError(parsed, 'usage', 'intel patch-meta missing file');
});
test('intel extract-exports missing file path → usage', () => {
const parsed = runJsonErrors(['intel', 'extract-exports'], tmpDir);
assertTypedError(parsed, 'usage', 'intel extract-exports missing file');
});
test('graphify query missing term → usage', () => {
const parsed = runJsonErrors(['graphify', 'query'], tmpDir);
assertTypedError(parsed, 'usage', 'graphify query missing term');
});
test('learnings query missing --tag → usage', () => {
const parsed = runJsonErrors(['learnings', 'query'], tmpDir);
assertTypedError(parsed, 'usage', 'learnings query missing --tag');
});
test('learnings prune missing --older-than → usage', () => {
const parsed = runJsonErrors(['learnings', 'prune'], tmpDir);
assertTypedError(parsed, 'usage', 'learnings prune missing --older-than');
});
test('learnings delete missing id → usage', () => {
const parsed = runJsonErrors(['learnings', 'delete'], tmpDir);
assertTypedError(parsed, 'usage', 'learnings delete missing id');
});
test('extract-messages missing project arg → usage', () => {
// L877 — args[1] is undefined or starts with '--'.
const parsed = runJsonErrors(['extract-messages'], tmpDir);
assertTypedError(parsed, 'usage', 'extract-messages missing project');
});
test('write-profile missing --input → usage', () => {
const parsed = runJsonErrors(['write-profile'], tmpDir);
assertTypedError(parsed, 'usage', 'write-profile missing --input');
});
test('detect-custom-files missing --config-dir → usage', () => {
const parsed = runJsonErrors(['detect-custom-files'], tmpDir);
assertTypedError(parsed, 'usage', 'detect-custom-files missing --config-dir');
});
test('detect-custom-files invalid --config-dir → usage', () => {
const parsed = runJsonErrors(
['detect-custom-files', '--config-dir', '/nonexistent/path/xyzzy'],
tmpDir
);
assertTypedError(parsed, 'usage', 'detect-custom-files invalid --config-dir');
});
// ── Shape regression guard: every newly-typed path emits the canonical
// {ok, reason, message} object — no leakage of reason: "unknown". ────
test('every remaining typed path emits the canonical {ok, reason, message} shape', () => {
const probes = [
['template', 'bogus'],
['frontmatter', 'bogus', 'placeholder.md'],
['requirements', 'bogus'],
['milestone', 'bogus'],
['uat', 'bogus'],
['todo', 'bogus'],
['workstream', 'bogus'],
['graphify', 'bogus'],
['learnings', 'bogus'],
['intel', 'query'],
['extract-messages'],
['write-profile'],
['detect-custom-files'],
];
for (const args of probes) {
const parsed = runJsonErrors(args, tmpDir);
const keys = Object.keys(parsed).sort();
assert.deepStrictEqual(keys, ['message', 'ok', 'reason'],
`args ${args.join(' ')}: keys must be exactly {ok,reason,message}, got ${keys.join(',')}`);
assert.notStrictEqual(parsed.reason, 'unknown',
`args ${args.join(' ')}: reason must be a typed code, not the fallback "unknown"`);
}
});
});
});
}
// ────────────────────────────────────────────────────────────────────────
// Folded from tests/bug-853-bg-dispatch-runtime-gating.test.cjs — consolidation epic #1969 (B2 #1971)
// ────────────────────────────────────────────────────────────────────────
{
const { describe: __foldDescribe } = require('node:test');
__foldDescribe("folded:bug-853-bg-dispatch-runtime-gating (consolidation epic #1969 B2 #1971)", () => {
'use strict';
/**
* Regression guard — bug(#853): /gsd-manager and /gsd-autonomous --interactive
* silently skipped worktree isolation + independent verification because they
* dispatched Plan/Execute via Agent(run_in_background=true). On Claude Code a
* backgrounded agent has no Agent/Task tool, so it cannot spawn the nested
* subagents (worktree executors, plan-checker, verifier). The workflows must
* now resolve dispatch capability from the registry (#1708) and run inline
* everywhere except runtimes where dispatch.background && dispatch.backgroundDispatch
* are both true (currently: codex, cursor).
*
* Phase B (#1708): the prose `RUNTIME === 'codex'` rule is graduated to a typed
* `gsd_run query dispatch-should-flatten` query backed by shouldFlattenDispatch()
* from host-integration.cjs and the documentation-sourced capability registry.
*/
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { createTempProject, cleanup: cleanupDir, runGsdTools } = require('./helpers.cjs');
const WORKFLOWS_DIR = path.join(__dirname, '..', 'gsd-core', 'workflows');
// allow-test-rule: source-text-is-the-product (see #1708)
const MANAGER = fs.readFileSync(path.join(WORKFLOWS_DIR, 'manager.md'), 'utf8');
// allow-test-rule: source-text-is-the-product (see #1708)
const AUTONOMOUS = fs.readFileSync(path.join(WORKFLOWS_DIR, 'autonomous.md'), 'utf8');
describe('bug-853 — manager/autonomous gate background dispatch by runtime', () => {
test('manager.md resolves dispatch-should-flatten before dispatching plan/execute', () => {
// Two dispatch sites (plan + execute), each must use dispatch-should-flatten.
// allow-test-rule: source-text-is-the-product (see #1708)
const matches = MANAGER.match(/dispatch-should-flatten/g) || [];
assert.ok(matches.length >= 2, 'manager.md must use dispatch-should-flatten for both plan and execute dispatch');
});
test('manager.md documents why most runtimes cannot background-dispatch', () => {
// Accept both old singular form (backgrounded agent has no) and new plural form (backgrounded agents have no)
// allow-test-rule: source-text-is-the-product (see #1708)
assert.match(MANAGER, /backgrounded agents? ha(?:s|ve) no `Agent`\/`Task` tool/);
});
test('manager.md gates background dispatch on FLATTEN=false and runs plan/execute inline otherwise', () => {
// Background path uses FLATTEN is false
// allow-test-rule: source-text-is-the-product (see #1708)
assert.match(MANAGER, /If `FLATTEN` is `false`[\s\S]{0,400}?run_in_background=true/);
// Inline is the default/else branch for plan — anchored on FLATTEN=true language (not runtime name)
assert.match(
MANAGER,
/Otherwise[\s\S]{0,100}?`FLATTEN`[\s\S]{0,400}?Skill\(skill="gsd-plan-phase"/,
);
// Inline is the default/else branch for execute — anchored on FLATTEN=true language (not runtime name)
assert.match(
MANAGER,
/Otherwise[\s\S]{0,100}?`FLATTEN`[\s\S]{0,400}?Skill\(skill="gsd-execute-phase"/,
);
});
test('manager.md compound action preamble uses FLATTEN language (not hardcoded runtime names)', () => {
// allow-test-rule: source-text-is-the-product (see #1708)
const compoundActionSection = MANAGER.match(
/### Compound Action \(background \+ inline\)[\s\S]*?Inline verification:/,
);
assert.ok(compoundActionSection, 'manager.md must document compound action runtime dispatch');
// Must gate on FLATTEN being false (not runtime name)
assert.match(
compoundActionSection[0],
/If `FLATTEN` is `false`[\s\S]{0,400}?Spawn all background agents first[\s\S]{0,300}?plan\/execute/,
);
// Otherwise / inline branch must reference FLATTEN being true
assert.match(
compoundActionSection[0],
/Otherwise[\s\S]{0,260}?`FLATTEN`[\s\S]{0,260}?`true`[\s\S]{0,260}?inline/,
);
// Must NOT still hardcode "On Codex:" in this section
assert.doesNotMatch(
compoundActionSection[0],
/\*\*On Codex:\*\*/,
);
// Must NOT still hardcode "On Claude Code or any other non-Codex runtime:"
assert.doesNotMatch(
compoundActionSection[0],
/On Claude Code or any other non-Codex runtime:/,
);
});
test('autonomous.md gates interactive background dispatch using dispatch-should-flatten', () => {
// Two dispatch sites (3b plan + 3c execute), each must use dispatch-should-flatten.
// allow-test-rule: source-text-is-the-product (see #1708)
const autoFlattenMatches = AUTONOMOUS.match(/dispatch-should-flatten/g) || [];
assert.ok(autoFlattenMatches.length >= 2, 'autonomous.md must use dispatch-should-flatten in both 3b (plan) and 3c (execute) interactive branches');
// Accept both old singular form (backgrounded agent has no) and new plural form (backgrounded agents have no)
assert.match(AUTONOMOUS, /backgrounded agents? ha(?:s|ve) no `Agent`\/`Task` tool/);
});
test('autonomous.md gates interactive background dispatch on FLATTEN=false; runs plan/execute inline otherwise', () => {
// Background block: run_in_background=true appears within the FLATTEN=false branch and gsd-plan-phase is nearby
// allow-test-rule: source-text-is-the-product (see #1708)
assert.match(AUTONOMOUS, /If `FLATTEN` is `false`[\s\S]{0,1200}?run_in_background=true[\s\S]{0,600}?gsd-plan-phase/);
// Background block: run_in_background=true appears within the FLATTEN=false branch and gsd-execute-phase is nearby
assert.match(AUTONOMOUS, /If `FLATTEN` is `false`[\s\S]{0,3000}?run_in_background=true[\s\S]{0,200}?gsd-execute-phase/);
// Inline is the otherwise/else branch for plan — anchored on FLATTEN=true language (not runtime name).
// #2994: the window between `FLATTEN` and the inline Skill() call widened
// past manager.md's 400 because this branch now carries a
// state:plan-strategy-converge conditional-read stub (converge-dispatch-inline,
// gsd-core/workflows/autonomous/steps/converge-dispatch-inline.md) ahead of
// the local-planning fallback — the stub's full step-file path is more
// verbose than the terse `Skill()` call it replaced.
assert.match(
AUTONOMOUS,
/Otherwise[\s\S]{0,100}?`FLATTEN`[\s\S]{0,700}?Skill\(skill="gsd-plan-phase"/,
);
// Inline is the otherwise/else branch for execute — anchored on FLATTEN=true language (not runtime name)
assert.match(
AUTONOMOUS,
/Otherwise[\s\S]{0,100}?`FLATTEN`[\s\S]{0,400}?Skill\(skill="gsd-execute-phase"/,
);
});
});
describe('dispatch-should-flatten query — behavioral', () => {
// #853 / #1708: The typed query replaces prose-level RUNTIME===codex checks.
// shouldFlattenDispatch returns false only when both dispatch.background AND
// dispatch.backgroundDispatch are true in the capability registry.
//
// Registry values (from host-integration-capability-matrix.md):
// codex: background=true, backgroundDispatch=true → shouldFlatten=false (may background)
// claude: background=true, backgroundDispatch=false → shouldFlatten=true (must inline)
// cursor: background=true, backgroundDispatch=true → shouldFlatten=false (may background)
// unknown: no entry → fail-closed → shouldFlatten=true (must inline)
test('runtime=codex → shouldFlatten=false (background dispatch safe)', () => {
const tmpDir = createTempProject();
try {
const result = runGsdTools(['query', 'dispatch-should-flatten', '--raw'], tmpDir, {
GSD_RUNTIME: 'codex',
});
assert.ok(result.success, `Expected success, got error: ${result.error}`);
assert.strictEqual(result.output, 'false', `codex should return false (may background), got: ${result.output}`);
} finally {
cleanupDir(tmpDir);
}
});
test('runtime=claude → shouldFlatten=true (must inline)', () => {
const tmpDir = createTempProject();
try {
const result = runGsdTools(['query', 'dispatch-should-flatten', '--raw'], tmpDir, {
GSD_RUNTIME: 'claude',
});
assert.ok(result.success, `Expected success, got error: ${result.error}`);
assert.strictEqual(result.output, 'true', `claude should return true (must inline), got: ${result.output}`);
} finally {
cleanupDir(tmpDir);
}
});
test('runtime=cursor → shouldFlatten=false (background dispatch safe)', () => {
const tmpDir = createTempProject();
try {
const result = runGsdTools(['query', 'dispatch-should-flatten', '--raw'], tmpDir, {
GSD_RUNTIME: 'cursor',
});
assert.ok(result.success, `Expected success, got error: ${result.error}`);
assert.strictEqual(result.output, 'false', `cursor should return false (may background), got: ${result.output}`);
} finally {
cleanupDir(tmpDir);
}
});
test('unknown runtime → shouldFlatten=true (fail-closed → must inline)', () => {
// An unknown runtime has no registry entry → dispatch is null → fail-closed to true.
const tmpDir = createTempProject();
try {
const result = runGsdTools(['query', 'dispatch-should-flatten', '--raw'], tmpDir, {
GSD_RUNTIME: 'unknown-runtime-xyz',
});
// The query must succeed (exit 0) even for unknown runtimes — fail-closed not crash-closed.
assert.ok(result.success, `Expected success (fail-closed), got error: ${result.error}`);
assert.strictEqual(result.output, 'true', `unknown runtime should return true (fail-closed), got: ${result.output}`);
} finally {
cleanupDir(tmpDir);
}
});
test('--json flag returns structured { runtime, shouldFlatten, dispatch }', () => {
const tmpDir = createTempProject();
try {
const result = runGsdTools(['query', 'dispatch-should-flatten', '--json'], tmpDir, {
GSD_RUNTIME: 'codex',
});
assert.ok(result.success, `Expected success, got error: ${result.error}`);
let parsed;
try {
parsed = JSON.parse(result.output);
} catch {
assert.fail(`Expected valid JSON output, got: ${result.output}`);
}
assert.strictEqual(parsed.runtime, 'codex');
assert.strictEqual(parsed.shouldFlatten, false);
assert.ok(parsed.dispatch !== null && typeof parsed.dispatch === 'object', 'dispatch should be an object');
assert.strictEqual(parsed.dispatch.backgroundDispatch, true);
} finally {
cleanupDir(tmpDir);
}
});
test('config.runtime takes precedence when GSD_RUNTIME not set', () => {
// GSD_RUNTIME > config.runtime > 'claude'
// Write config.json with runtime=codex; no GSD_RUNTIME override.
const tmpDir = createTempProject();
try {
fs.writeFileSync(
path.join(tmpDir, '.planning', 'config.json'),
JSON.stringify({ runtime: 'codex' }),
'utf-8',
);
// Override GSD_RUNTIME to '' (empty string) so any ambient value is cleared.
// resolveRuntimeNameFromCandidates treats empty string as absent (normalizes
// to '' which is falsy → skipped → falls through to config.runtime=codex).
// This is the only way to suppress an ambient GSD_RUNTIME since runGsdTools
// merges { ...process.env, ...TEST_ENV_BASE, ...env } — passing '' as the
// override overwrites the ambient value at the correct merge position.
const result = runGsdTools(['query', 'dispatch-should-flatten', '--raw'], tmpDir, {
GSD_RUNTIME: '',
});
// config.runtime=codex with GSD_RUNTIME cleared → codex backgrounds → shouldFlatten=false
assert.ok(result.success, `Expected success, got error: ${result.error}`);
assert.strictEqual(result.output, 'false', `config.runtime=codex (GSD_RUNTIME cleared) should return false (may background), got: ${result.output}`);
} finally {
cleanupDir(tmpDir);
}
});
});
});
}
// ────────────────────────────────────────────────────────────────────────
// Folded from tests/bug-3683-command-cross-reference-invariant.test.cjs — consolidation epic #1969 (B3 #1972)
// ────────────────────────────────────────────────────────────────────────
{
const { describe: __foldDescribe } = require('node:test');
__foldDescribe("folded:bug-3683-command-cross-reference-invariant (consolidation epic #1969 B3 #1972)", () => {
// allow-test-rule: source-text-is-the-product (see #3683)
// commands/gsd/*.md bodies are the deployed contract — cross-references between
// them must stay coherent. This test inspects .md source to enforce the invariant.
'use strict';
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const COMMANDS_DIR = path.resolve(__dirname, '..', 'commands', 'gsd');
function readKnownTargets() {
const commandNames = fs.readdirSync(COMMANDS_DIR)
.filter(f => f.endsWith('.md'))
.map(f => f.slice(0, -3));
return { commandNames, knownTargets: new Set(commandNames) };
}
function stripFrontmatter(src) {
return src.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '');
}
// Word-boundary lookbehind matching fix-slash-commands.cjs buildColonPattern / buildPattern
// Excludes path-y characters (~, ., /) so `~/gsd-workspaces`, `./gsd-foo`, `path/gsd-bar` don't match.
// Trailing `(?![\w-]*\/)` rejects filesystem path segments like `${VAR}/gsd-core/bin` (the
// runtime-launcher shim) where a non-path char (e.g. `}`) precedes `/gsd-core/` — those are
// directory paths to the gsd-core/ runtime, not slash-command references (#604 rename).
const REF_PATTERN = /(?<![a-zA-Z0-9_~./-])\/gsd[:-]([a-zA-Z0-9_-]+)(?![\w-]*\/)/g;
describe('bug-3683 command cross-reference invariant', () => {
test('all /gsd:<X> and /gsd-<X> body refs resolve to known command base-names', () => {
const { commandNames, knownTargets: knownSet } = readKnownTargets();
const mdFiles = commandNames.sort().map(n => path.join(COMMANDS_DIR, `${n}.md`));
const failures = [];
for (const filePath of mdFiles) {
const src = fs.readFileSync(filePath, 'utf-8');
const body = stripFrontmatter(src);
const lines = body.split('\n');
const relFile = path.relative(path.resolve(__dirname, '..'), filePath);
lines.forEach((line, idx) => {
REF_PATTERN.lastIndex = 0;
let m;
while ((m = REF_PATTERN.exec(line)) !== null) {
const ref = m[1];
if (!knownSet.has(ref)) {
const sep = m[0].includes(':') ? ':' : '-';
failures.push({
file: relFile,
line: idx + 1,
ref: `/gsd${sep}${ref}`,
excerpt: line.trim(),
});
}
}
});
}
if (failures.length > 0) {
const msg = failures
.map(f => ` ${f.file}:${f.line} — dangling ref "${f.ref}" — ${f.excerpt}`)
.join('\n');
assert.fail(`Dangling command cross-references found:\n${msg}`);
}
});
});
});
}