Files
msd-core/get-shit-done/bin/lib/phase-command-router.cjs
Tom Boucher b533f71857 chore: introduce CommandRoutingHub and migrate phase-command-router (PoC) (#3828)
* feat(routing): add CommandRoutingHub with behavioral test suite (#3788)

Introduces createHub({ mode, sdkLoader, cjsRegistry, manifest }) and
hub.dispatch({ family, subcommand, args, cwd, raw }) -> Result with a
closed 6-value ERROR_KINDS frozen enum. Hub never throws, never prints,
and enforces no transparent fallback between sdk/cjs modes. 34 behavioral
tests cover all errorKind values, mode fixation, and the no-throw contract.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(routing): migrate phase-command-router to CommandRoutingHub (#3788)

Rewrites phase-command-router.cjs to dispatch through CommandRoutingHub.
Public entry point routePhaseCommand({ phase, args, cwd, raw, error }) is
unchanged. The adapter determines mode (sdk/cjs) from env + tryLoadSdk(),
constructs a hub, dispatches, and translates the pure Result back to
output()/error() calls. New behavioral test suite (23 tests) replaces the
old mock-heavy approach and includes two integration tests through the real hub.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(routing): ADR + glossary + changeset for CommandRoutingHub (#3788)

Adds ADR-3788 documenting the hub's design contract (pure result, fixed mode,
closed 6-value errorKind enum, no transparent fallback). Adds Command Routing
Hub glossary entry to CONTEXT.md and a one-paragraph reference to
ARCHITECTURE.md. Changeset fragment records the Changed entry.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(docs): rename ADR to sequential convention 0012 (#3788)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(inventory): register CommandRoutingHub in INVENTORY (#3788)

Add command-routing-hub.cjs row to docs/INVENTORY.md CLI Modules table,
bump headline count from 72 to 73, and regenerate INVENTORY-MANIFEST.json
via scripts/gen-inventory-manifest.cjs --write.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(adr): add 0012 to ADR index (#3788)

Add entry for 0012-command-routing-hub.md to the index table in
docs/adr/README.md so the enh-3271-sdk-adr-structure lint passes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(lint): bump phase test-file ceiling to accommodate command-router suite (#3788)

phase-command-router.test.cjs added by the CommandRoutingHub migration
pushes the phase prefix cluster from 4 to 5 test files. Bump the allowlist
ceiling from 4 to 5 (issue 3788) so lint-test-file-count passes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(routing): preserve phase.mvp-mode JSON error and ROADMAP scan through hub (#3788)

mvp-mode was never registered in the SDK; the pre-#3788 CJS router
always dispatched it via the CJS handler even when sdkAvailable was
true. After the hub migration, SDK-mode hubs (Docker, where the SDK
build exists) sent mvp-mode to the SDK bridge, which returned
SdkDispatchFailed with reason 'unknown' instead of the expected
'usage' code, and failed ROADMAP lookups. Fix by short-circuiting
mvp-mode to the CJS handler before hub construction, matching the
pre-migration observable behaviour.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(adr): note SDK-incomplete subcommand limitation in ADR-0012 (#3788)

* fix(inventory): bump CLI Modules headline to 74 after rebase onto main (#3788)

Upstream added code-review-flags.cjs (72→73) at the same time our branch
added command-routing-hub.cjs. After rebase both modules exist (74 total)
but the headline stayed at 73; bump to 74.

* fix(routing): remove dead mvp-mode handler from cjsRegistry (#3788)

The cjsRegistry['phase']['mvp-mode'] handler (previously lines 65–68)
was unreachable: the early-return bypass at line 56 intercepts mvp-mode
before hub construction in CJS mode, and in SDK mode cjsRegistry is
passed as undefined. Remove the dead handler; all 57 tests still pass.

* docs(adr): correct router count in ADR-0012 (#3788)

The context section cited "eight" routers including "frontmatter" but
there is no frontmatter-command-router.cjs. The actual count is seven:
phase, phases, roadmap, state, verify, validate, init.

* fix(routing): guard missing subcommand + use ERROR_KINDS constant (#3788)

Two fixes in phase-command-router.cjs:

1. Add early-return for missing subcommand before hub construction.
   Pre-#3788 the routeCjsCommandFamily fell through to error() for
   undefined args[1]; post-#3788 the hub's manifest check skips falsy
   subcommands, which would have sent bare 'phase' into SDK dispatch
   in SDK mode instead of the expected "Available: ..." error message.

2. Switch on ERROR_KINDS.UnknownCommand instead of bare 'UnknownCommand'
   string, per ADR-0012's closed-enum contract ("callers switch on
   ERROR_KINDS values, not bare string literals").

* docs(routing): fix factual errors in ARCHITECTURE, ADR-0012, changeset (#3788)

Three corrections:

1. ARCHITECTURE.md: softened "All CJS command family routers dispatch
   through CommandRoutingHub" — only phase-command-router.cjs is
   migrated in this PR; remaining routers still use routeCjsCommandFamily
   and migrate in follow-up issues.

2. ADR-0012: corrected the SDK mvp-mode claim. The ADR said "the SDK
   has no equivalent entry" but sdk/src/query/command-static-catalog-
   domain.ts:104-105 registers phase.mvp-mode. The actual reason for
   the early-return bypass is divergent ROADMAP scan behaviour and
   error reason codes, not SDK absence.

3. .changeset/mellow-tigers-gather.md: corrected pr: 1 → pr: 3828.

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 23:32:10 -04:00

227 lines
9.5 KiB
JavaScript

'use strict';
const { PHASE_SUBCOMMANDS } = require('./command-aliases.generated.cjs');
const { output } = require('./core.cjs');
// ─── SDK bridge (Phase 6) — shared loader via cjs-sdk-bridge.cjs ──────────────
const { tryLoadSdk, getExecuteForCjs } = require('./cjs-sdk-bridge.cjs');
// ─── CommandRoutingHub (issue #3788) ──────────────────────────────────────────
const { createHub, ERROR_KINDS } = require('./command-routing-hub.cjs');
/**
* Manifest-backed phase subcommand router.
* Keeps gsd-tools.cjs thin while preserving existing command semantics.
*
* Phase 6: all CJS-handled phase subcommands are dispatched via executeForCjs
* when the SDK is available. CJS fallback retained when:
* - GSD_WORKSTREAM is active (workstream-scoped requests fall through to CJS).
* - SDK is unavailable (build not present).
*
* SDK-only (unsupported in CJS router):
* - list-plans: SDK-only.
* - list-artifacts: SDK-only.
* - scaffold: routed through top-level scaffold command.
*
* CJS-only subcommands: none.
*
* #3788: dispatch is now mediated by CommandRoutingHub. The public entry point
* and observable CLI behaviour are unchanged.
*/
function routePhaseCommand({ phase, args, cwd, raw, error }) {
const activeWorkstream = process.env.GSD_WORKSTREAM;
const sdkAvailable = !activeWorkstream && tryLoadSdk();
// ── Unsupported / SDK-only subcommands ─────────────────────────────────────
// Resolved before dispatch so the error message matches the pre-#3788 text.
const UNSUPPORTED = {
'list-plans': 'phase list-plans is SDK-only. Use: gsd-sdk query phase.list-plans ...',
'list-artifacts': 'phase list-artifacts is SDK-only. Use: gsd-sdk query phase.list-artifacts ...',
scaffold: 'phase scaffold is routed through the top-level scaffold command.',
};
const subcommand = args[1];
if (subcommand && UNSUPPORTED[subcommand]) {
error(UNSUPPORTED[subcommand]);
return;
}
// ── No subcommand → reject early with helpful error ────────────────────────
// Pre-#3788 code resolved unknown subcommands via routeCjsCommandFamily which
// fell through to error() when no handler matched (including undefined).
// Post-#3788 the hub's manifest check is skipped for falsy subcommand, so we
// must guard here to preserve the deterministic "Available: ..." error message.
if (!subcommand) {
const available = PHASE_SUBCOMMANDS.filter(s => !UNSUPPORTED[s]).join(', ');
error(`Unknown phase subcommand. Available: ${available}`);
return;
}
// ── CJS-only subcommands (always bypass SDK path) ──────────────────────────
// `mvp-mode` has a CJS-native implementation in phase.cmdPhaseMvpMode that
// differs from the SDK query layer (different ROADMAP scan + error codes).
// Dispatch it early so the SDK hub path is never reached for this subcommand,
// preserving the pre-migration observable behaviour (correct exit code,
// correct JSON error reason code, correct ROADMAP scan).
if (subcommand === 'mvp-mode') {
phase.cmdPhaseMvpMode(cwd, args.slice(2), raw);
return;
}
// ── Build the CJS registry ──────────────────────────────────────────────────
// Each handler receives a ctx object from the hub and must return a HubResult.
const cjsRegistry = {
phase: {
'next-decimal': (_ctx) => {
phase.cmdPhaseNextDecimal(cwd, args[2], raw);
return { ok: true, data: null };
},
add: (_ctx) => {
let customId = null;
const descArgs = [];
for (let i = 2; i < args.length; i++) {
const token = args[i];
if (token === '--raw') {
continue;
}
if (token === '--id') {
const id = args[i + 1];
if (!id || id.startsWith('--')) {
return { ok: false, errorKind: 'InvalidArgs', message: '--id requires a value' };
}
customId = id;
i++;
} else if (token.startsWith('--')) {
return { ok: false, errorKind: 'InvalidArgs', message: `phase add does not support ${token}` };
} else {
descArgs.push(token);
}
}
phase.cmdPhaseAdd(cwd, descArgs.join(' '), raw, customId);
return { ok: true, data: null };
},
'add-batch': (_ctx) => {
const descFlagIdx = args.indexOf('--descriptions');
let descriptions;
if (descFlagIdx !== -1) {
const rawDescriptions = args[descFlagIdx + 1];
if (!rawDescriptions || rawDescriptions.startsWith('--')) {
return { ok: false, errorKind: 'InvalidArgs', message: '--descriptions must be a JSON array' };
}
try {
descriptions = JSON.parse(rawDescriptions);
} catch {
return { ok: false, errorKind: 'InvalidArgs', message: '--descriptions must be a JSON array' };
}
if (!Array.isArray(descriptions)) {
return { ok: false, errorKind: 'InvalidArgs', message: '--descriptions must be a JSON array' };
}
} else {
descriptions = args.slice(2).filter(a => a !== '--raw');
}
phase.cmdPhaseAddBatch(cwd, descriptions, raw);
return { ok: true, data: null };
},
insert: (_ctx) => {
if (args.includes('--dry-run')) {
return { ok: false, errorKind: 'InvalidArgs', message: 'phase insert does not support --dry-run' };
}
phase.cmdPhaseInsert(cwd, args[2], args.slice(3).join(' '), raw);
return { ok: true, data: null };
},
remove: (_ctx) => {
const removeArgs = args.slice(2).filter(token => token !== '--raw');
let forceFlag = false;
const positional = [];
for (const token of removeArgs) {
if (token === '--force') {
forceFlag = true;
continue;
}
if (token.startsWith('--')) {
return { ok: false, errorKind: 'InvalidArgs', message: `phase remove does not support ${token}` };
}
positional.push(token);
}
if (positional.length !== 1) {
return { ok: false, errorKind: 'InvalidArgs', message: 'phase remove accepts exactly one phase number' };
}
phase.cmdPhaseRemove(cwd, positional[0], { force: forceFlag }, raw);
return { ok: true, data: null };
},
complete: (_ctx) => {
phase.cmdPhaseComplete(cwd, args[2], raw);
return { ok: true, data: null };
},
},
};
// ── Build the SDK loader ────────────────────────────────────────────────────
function sdkLoader() {
const execute = getExecuteForCjs();
if (!execute) return null;
// Wrap executeForCjs to match the hub's sdkLoader contract:
// hub calls sdkLoader() -> returns the execute function itself.
return execute;
}
// ── Build manifest (available subcommands for UnknownCommand detection) ─────
// `availableSubcommands` is what the error message shows. It excludes
// SDK-only unsupported commands (already handled above) but does NOT include
// 'mvp-mode' because it was absent from PHASE_SUBCOMMANDS in the original
// and was not shown in the "Available:" list there either.
//
// `manifestSubcommands` is the full routing set for the hub — it includes
// 'mvp-mode' (which the original code routed via a handler even without a
// manifest entry) so the hub's UnknownCommand check passes for it.
const availableSubcommands = PHASE_SUBCOMMANDS.filter(s => !UNSUPPORTED[s]);
const manifestSubcommands = ['mvp-mode', ...availableSubcommands];
const manifest = { phase: manifestSubcommands };
// ── Construct hub (mode fixed at call time based on env + SDK availability) ─
const mode = sdkAvailable ? 'sdk' : 'cjs';
const hub = createHub({
mode,
sdkLoader: mode === 'sdk' ? sdkLoader : undefined,
cjsRegistry: mode === 'cjs' ? cjsRegistry : undefined,
manifest,
});
// ── Dispatch ────────────────────────────────────────────────────────────────
const result = hub.dispatch({
family: 'phase',
subcommand,
args: args.slice(2),
cwd,
raw,
});
// ── Translate result → CLI output / error (adapter responsibility) ──────────
if (!result.ok) {
if (result.errorKind === ERROR_KINDS.UnknownCommand) {
const available = availableSubcommands.join(', ');
error(`Unknown phase subcommand. Available: ${available}`);
return;
}
// InvalidArgs, HandlerRefusal, HandlerFailure, SdkLoadFailed, SdkDispatchFailed
error(result.message);
return;
}
// SDK path: the hub wraps executeForCjs; data projection is the adapter's job.
// CJS handlers call output() themselves (inside phase.cmdPhase*()), so no
// further output call is needed for cjs mode.
if (mode === 'sdk') {
if (raw) {
output(null, true, typeof result.data === 'string' ? result.data : String(result.data ?? ''));
} else {
output(result.data);
}
}
}
module.exports = {
routePhaseCommand,
};