* 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>
240 lines
7.8 KiB
JavaScript
240 lines
7.8 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Command Routing Hub — issue #3788.
|
|
*
|
|
* A pure-result dispatch hub that centralizes the mode decision (SDK vs CJS),
|
|
* the error taxonomy, and the no-throw contract that all command-family routers
|
|
* currently duplicate independently.
|
|
*
|
|
* Design:
|
|
* createHub({ mode, sdkLoader, cjsRegistry, manifest }) -> hub
|
|
* hub.dispatch({ family, subcommand, args, cwd, raw }) -> Result
|
|
*
|
|
* Result = { ok: true, data }
|
|
* | { ok: false, errorKind, message, details? }
|
|
*
|
|
* Invariants:
|
|
* - `mode` is fixed at construction; never re-evaluated per dispatch.
|
|
* - Hub never prints to stdout/stderr, never calls process.exit.
|
|
* - Hub never throws — all internal throws are caught and converted to
|
|
* { ok: false, errorKind: 'HandlerFailure', message, details }.
|
|
* - No transparent fallback: an SDK-mode hub that encounters an SDK crash
|
|
* returns { ok: false, errorKind: 'SdkDispatchFailed' }; it does NOT
|
|
* silently retry via the CJS registry.
|
|
* - The errorKind taxonomy is closed. Callers switch on ERROR_KINDS values.
|
|
*/
|
|
|
|
/**
|
|
* Closed errorKind enum. Export as a frozen object so callers can switch on
|
|
* ERROR_KINDS.UnknownCommand etc. without relying on bare string literals.
|
|
*
|
|
* @readonly
|
|
*/
|
|
const ERROR_KINDS = Object.freeze({
|
|
/** The requested family/subcommand combination is not present in the manifest. */
|
|
UnknownCommand: 'UnknownCommand',
|
|
/** The handler rejected the supplied arguments before executing. */
|
|
InvalidArgs: 'InvalidArgs',
|
|
/** A CJS handler returned an explicit refusal (e.g. unsupported subcommand). */
|
|
HandlerRefusal: 'HandlerRefusal',
|
|
/** A handler threw an unexpected exception. */
|
|
HandlerFailure: 'HandlerFailure',
|
|
/** The sdkLoader function threw or returned a falsy value at dispatch time. */
|
|
SdkLoadFailed: 'SdkLoadFailed',
|
|
/** The SDK was loaded but threw or returned ok:false during execution. */
|
|
SdkDispatchFailed: 'SdkDispatchFailed',
|
|
});
|
|
|
|
/**
|
|
* @typedef {{ ok: true, data: unknown }} OkResult
|
|
* @typedef {{ ok: false, errorKind: string, message: string, details?: unknown }} ErrResult
|
|
* @typedef {OkResult | ErrResult} HubResult
|
|
*/
|
|
|
|
/**
|
|
* @typedef {object} HubOptions
|
|
* @property {'sdk' | 'cjs'} mode - Dispatch mode, fixed at construction.
|
|
* @property {() => unknown} [sdkLoader] - Callable that returns the SDK execute
|
|
* function (or throws). Only used when mode === 'sdk'.
|
|
* @property {Record<string, Record<string, (ctx: object) => HubResult>>} [cjsRegistry] -
|
|
* Nested map of family -> subcommand -> handler. Only used when mode === 'cjs'.
|
|
* @property {Record<string, string[]>} [manifest] - Map of family -> known subcommands.
|
|
* Used for UnknownCommand detection regardless of mode.
|
|
*/
|
|
|
|
/**
|
|
* Construct a CommandRoutingHub.
|
|
*
|
|
* @param {HubOptions} options
|
|
* @returns {{ dispatch: (req: object) => HubResult }}
|
|
*/
|
|
function createHub({ mode, sdkLoader, cjsRegistry, manifest }) {
|
|
if (mode !== 'sdk' && mode !== 'cjs') {
|
|
throw new TypeError(`CommandRoutingHub: mode must be 'sdk' or 'cjs', got ${JSON.stringify(mode)}`);
|
|
}
|
|
|
|
// Validate mode once at construction; never re-check per dispatch.
|
|
const _mode = mode;
|
|
const _sdkLoader = sdkLoader;
|
|
const _cjsRegistry = cjsRegistry;
|
|
const _manifest = manifest;
|
|
|
|
/**
|
|
* Dispatch a command through the hub.
|
|
*
|
|
* @param {{ family: string, subcommand: string, args?: unknown[], cwd?: string, raw?: boolean }} req
|
|
* @returns {HubResult}
|
|
*/
|
|
function dispatch(req) {
|
|
try {
|
|
return _dispatch(req);
|
|
} catch (err) {
|
|
return {
|
|
ok: false,
|
|
errorKind: ERROR_KINDS.HandlerFailure,
|
|
message: err instanceof Error ? err.message : String(err),
|
|
details: { originalError: err },
|
|
};
|
|
}
|
|
}
|
|
|
|
function _dispatch(req) {
|
|
const { family, subcommand, args = [], cwd, raw } = req;
|
|
|
|
// ── manifest check (applies to both modes) ──────────────────────────────
|
|
if (_manifest) {
|
|
const knownSubcommands = _manifest[family];
|
|
if (!knownSubcommands) {
|
|
return {
|
|
ok: false,
|
|
errorKind: ERROR_KINDS.UnknownCommand,
|
|
message: `Unknown command family: ${family}`,
|
|
};
|
|
}
|
|
if (subcommand && !knownSubcommands.includes(subcommand)) {
|
|
return {
|
|
ok: false,
|
|
errorKind: ERROR_KINDS.UnknownCommand,
|
|
message: `Unknown subcommand: ${family} ${subcommand}`,
|
|
};
|
|
}
|
|
}
|
|
|
|
if (_mode === 'sdk') {
|
|
return _dispatchSdk({ family, subcommand, args, cwd, raw });
|
|
}
|
|
|
|
return _dispatchCjs({ family, subcommand, args, cwd, raw });
|
|
}
|
|
|
|
function _dispatchSdk({ family, subcommand, args, cwd, raw }) {
|
|
// Load the SDK execute function (or return SdkLoadFailed).
|
|
let executeForCjs;
|
|
try {
|
|
executeForCjs = _sdkLoader ? _sdkLoader() : null;
|
|
} catch (err) {
|
|
return {
|
|
ok: false,
|
|
errorKind: ERROR_KINDS.SdkLoadFailed,
|
|
message: `SDK load failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
details: { originalError: err },
|
|
};
|
|
}
|
|
|
|
if (!executeForCjs || typeof executeForCjs !== 'function') {
|
|
return {
|
|
ok: false,
|
|
errorKind: ERROR_KINDS.SdkLoadFailed,
|
|
message: 'SDK loader did not return a callable execute function',
|
|
};
|
|
}
|
|
|
|
// Call the SDK. No transparent fallback — any error becomes SdkDispatchFailed.
|
|
let result;
|
|
try {
|
|
result = executeForCjs({
|
|
registryCommand: subcommand ? `${family}.${subcommand}` : family,
|
|
registryArgs: args,
|
|
legacyCommand: family,
|
|
legacyArgs: [subcommand, ...args].filter(Boolean),
|
|
mode: raw ? 'raw' : 'json',
|
|
projectDir: cwd,
|
|
});
|
|
} catch (err) {
|
|
return {
|
|
ok: false,
|
|
errorKind: ERROR_KINDS.SdkDispatchFailed,
|
|
message: err instanceof Error ? err.message : String(err),
|
|
details: { originalError: err },
|
|
};
|
|
}
|
|
|
|
if (!result || !result.ok) {
|
|
const message = (result && result.errorDetails && result.errorDetails.message)
|
|
? result.errorDetails.message
|
|
: `${family}${subcommand ? ' ' + subcommand : ''} failed (${result && result.errorKind})`;
|
|
return {
|
|
ok: false,
|
|
errorKind: ERROR_KINDS.SdkDispatchFailed,
|
|
message,
|
|
details: result || {},
|
|
};
|
|
}
|
|
|
|
return { ok: true, data: result.data };
|
|
}
|
|
|
|
function _dispatchCjs({ family, subcommand, args, cwd, raw }) {
|
|
if (!_cjsRegistry) {
|
|
return {
|
|
ok: false,
|
|
errorKind: ERROR_KINDS.UnknownCommand,
|
|
message: `No CJS registry provided for family: ${family}`,
|
|
};
|
|
}
|
|
|
|
const familyHandlers = _cjsRegistry[family];
|
|
if (!familyHandlers) {
|
|
return {
|
|
ok: false,
|
|
errorKind: ERROR_KINDS.UnknownCommand,
|
|
message: `Unknown command family: ${family}`,
|
|
};
|
|
}
|
|
|
|
const handler = subcommand ? familyHandlers[subcommand] : familyHandlers[''];
|
|
if (typeof handler !== 'function') {
|
|
return {
|
|
ok: false,
|
|
errorKind: ERROR_KINDS.UnknownCommand,
|
|
message: `Unknown subcommand: ${family} ${subcommand}`,
|
|
};
|
|
}
|
|
|
|
// Invoke the handler. It must return a HubResult or throw.
|
|
// If it throws, the outer try/catch in dispatch() catches it.
|
|
const result = handler({ family, subcommand, args, cwd, raw });
|
|
|
|
// If the handler returned a well-formed HubResult, pass it through.
|
|
if (result && typeof result === 'object' && 'ok' in result) {
|
|
return result;
|
|
}
|
|
|
|
// If the handler returned nothing (undefined), treat as success with no data.
|
|
if (result === undefined || result === null) {
|
|
return { ok: true, data: null };
|
|
}
|
|
|
|
// Any other return value is treated as the data payload.
|
|
return { ok: true, data: result };
|
|
}
|
|
|
|
return { dispatch };
|
|
}
|
|
|
|
module.exports = {
|
|
createHub,
|
|
ERROR_KINDS,
|
|
};
|