Files
msd-core/tests/command-routing-hub.test.cjs
Tom Boucher 5fa4dcd78c fix: recover silently-excluded test dirs + test-architecture audit hardening (#1195)
* fix: recurse test discovery so subdir test suites actually run

scripts/run-tests.cjs discovered tests with a flat readdirSync(testDir),
silently excluding tests/observability/ (4 files), tests/dispatch/ (1) and
tests/installer-migrations/ (1) — 94 passing tests — from `npm test` and all
CI lanes. Walk the tree recursively (relative subpaths preserved), classify
suites by basename, and add a fail-on-zero-executed guard for suite/default
runs (escape hatch GSD_ALLOW_EMPTY_SUITE=1) while preserving the empty
--files/--files-from path the CI inert lane relies on.

Unit suite 735 -> 741 files; surfaces ADR-227's observability/dispatch seam.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test: retire 5 verified-worthless tests

Adversarial verification confirmed these 5 prove nothing — their coverage is
provided more strictly elsewhere:
- enh-2790 'has a name: field' spot-checks (command-contract enforces /^gsd[:-]/)
- command-routing-hub duplicate construct + duplicate ERROR_KINDS assertions
- no-cjs-sdk-handsync-tooling (guarded files that never existed on main; bug-190
  covers the real retired SDK artifacts)
- runtime-artifact-layout cline edge case (subsumed by the explicit-global test
  and bug-782-cline-skills-emission)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test: add ADR-218 release version-validation coverage

ADR-218 (reject leading-zero versions like 1.01.0; npm duplicate pre-check) had
zero tests — the logic lived only in release.yml bash. Add a test that extracts
the actual rejection regexes from the workflow and exercises them against a
boundary table (leading-zero/malformed rejected, valid accepted) plus structural
wiring assertions. Goes red if the regex is reverted to [0-9]+.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test: redesign weak tests into behavioral, deterministic assertions

Per the ADR test audit, rewrite 27 weak test files (test-only, no source
changes) so each can go red for the defect it guards:
- kill pass-always assert.ok(true) placeholders (research-cli, worktree-baseref,
  bug-260 security guard, eslint-rules x24, clusters '|| true')
- replace source-text grep with behavioral calls (install Kilo, sh-hook-paths,
  plan-review-convergence) and add a repo-layout governance test
- de-flake real-clock/Math.random coupling (phase last_updated, bug-3707 mtime,
  context-utilization property, feat-3594)
- fix independence/shared-state violations (bug-492 singleton, issue-844 tmpRoot,
  core reapStaleTempFiles, active-workstream TTY, feat-488 GSD_HOME)
- strengthen property/shape-only tests (research-provider/store classification +
  collision) and unconditional plugin.json schema validation (issue-766)

Verified: all 28 files run together 1220 pass / 0 fail / 1 skip.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore: add no-tautological-assert lint rule, error in test suite

New custom ESLint rule (eslint-rules/no-tautological-assert.cjs) bans asserts
that can never fail: assert(true)/assert.ok(<always-truthy literal>),
'cond || true' inside an assert, and equality asserts comparing two identical
literals. Wired as error on tests/**; full sweep confirmed zero existing
violations so the suite stays green. Prevents the placeholder-assert regressions
the audit redesigns just removed. RuleTester coverage added (6 valid, 8 invalid).

Note: no-only-tests was already enforced via eslint-plugin-no-only-tests, so no
duplicate rule was added.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore: gate new allow-test-rule exemptions to require an issue ref

ADR-456 requires any allow-test-rule exemption added after the ADR to carry a
tracking issue number, but nothing enforced it. New ratchet gate
(scripts/lint-allow-test-rule-refs.cjs, wired into lint:ci) fails when a NEW
allow-test-rule comment lacks a #NNN/URL reference; the 323 existing untracked
exemptions are grandfathered in an allowlist that ratchets down as they gain
refs. Red-green verified (novel untracked offender fails; compliant passes).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* docs: add ADR test-audit evidence report (#1192)

Full risk-first qa-test-architect audit of the ADR portfolio (37 ADRs + 4
platform lenses, adversarial verification of retire verdicts) that drove the
P0 discovery fix, ADR-218 coverage, 5 retires, 27 redesigns, and the two new
lint gates. Filed as point-in-time evidence under docs/issueevidence/, named
for tracking issue #1192.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test: replace pre-existing raw NUL byte with escape in feat-3594 fixture

feat-3594's null-byte parser fixture contained a literal NUL byte (pre-existing
on next at b10e5681 — confirmed: base blob has 1 NUL, this fix has 0), which
made git treat the file as binary and would break grep/editors. Switch to the
\x00 escape; the runtime string value (a real NUL in the parser input) is
unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test: address adversarial-review findings

Codex adversarial pass over the branch:
- capability-registry drift test no longer mutates the committed generated
  capability-registry.cjs in place (concurrency hazard) — uses in-memory
  checkPipeline comparison instead.
- allow-test-rule ratchet now detects exemptions in ALL comment forms (block
  /* */ too, matching no-source-grep) so a block comment can't bypass it;
  one newly-surfaced pre-existing offender grandfathered (323->324).
- install.test Kilo case asserts on what install(false,'kilo') actually writes
  rather than manually calling configureKiloPermissions (masked the call site).
- issue-766 drops the undeclared transitive ajv dep for explicit structural
  assertions from the schema fixture.
- adr-218 test notes the hotfix leading-zero gap is tracked in #1186.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: address code-review findings (subdir discovery, rule + test gaps)

xhigh code review surfaced 15 confirmed issues, all fixed:
- run-tests.cjs --files now resolves subdir tests by bare basename + handles
  Windows backslash paths (ambiguous basenames error clearly).
- affected-tests-lib.cjs listTestFiles made recursive — the targeted CI lane was
  silently dropping changed subdir tests (same false-green class the audit fixed).
- no-tautological-assert now catches 'true || cond' and empty []/{}  equality.
- verify-test-quality: restore provenance-classification coverage, tighten the
  writeFile circular-detection check, guard the module-level file read.
- sh-hook-paths: cover the global-install .sh delegation branch (#2045 guard).
- active-workstream null-guard runs deterministically (no longer skipped on TTY).
- adr-218 structural guards tightened (major/minor leading-zero; needs: membership).
- repo-layout AGENTS.md guard no longer false-alarms on equivalent refactors.
- cross-ai ordering guard fails red when the step is missing.
- issue-766 parses required fields from the schema fixture (auto-enforced).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test: stub USERPROFILE alongside HOME in feat-488 (Windows parity)

The feat-488 redesign stubbed process.env.HOME but not USERPROFILE; os.homedir()
resolves from USERPROFILE on Windows, so the home stub was not hermetic there —
caught by windows-test-parity-guard (stubsHomeNoUserProfile). Save/set/restore
USERPROFILE symmetrically with HOME (delete-if-originally-undefined).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* chore: reconcile allow-test-rule allowlist after rebase onto next

Rebasing onto current next pulled in merged PR #1170, which added
inventory-headings-countfree.test.cjs (a baseline allow-test-rule exemption) and
deleted inventory-counts.test.cjs. Grandfather the former and prune the latter so
the ratchet matches the merged tree. No new debt from this PR.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 23:35:08 -04:00

839 lines
30 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);
});
});