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>
This commit is contained in:
239
get-shit-done/bin/lib/command-routing-hub.cjs
Normal file
239
get-shit-done/bin/lib/command-routing-hub.cjs
Normal file
@@ -0,0 +1,239 @@
|
||||
'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,
|
||||
};
|
||||
@@ -1,12 +1,14 @@
|
||||
'use strict';
|
||||
|
||||
const { PHASE_SUBCOMMANDS } = require('./command-aliases.generated.cjs');
|
||||
const { routeCjsCommandFamily } = require('./cjs-command-router-adapter.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.
|
||||
@@ -22,164 +24,201 @@ const { tryLoadSdk, getExecuteForCjs } = require('./cjs-sdk-bridge.cjs');
|
||||
* - 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();
|
||||
|
||||
function sdkHandler(registryCommand, registryArgs, legacyArgs, cjsFallback) {
|
||||
if (!sdkAvailable) return cjsFallback;
|
||||
return () => {
|
||||
// #3631: under --raw, request mode:'raw' so the bridge runs the SDK's
|
||||
// raw projection (formatQueryRawOutput) and returns the scalar string
|
||||
// CJS callers used to print. We then bypass output()'s JSON-stringify
|
||||
// path by passing rawValue (the third positional). With mode:'json',
|
||||
// output() emits the JSON IR as before.
|
||||
const result = getExecuteForCjs()({
|
||||
registryCommand,
|
||||
registryArgs,
|
||||
legacyCommand: 'phase',
|
||||
legacyArgs,
|
||||
mode: raw ? 'raw' : 'json',
|
||||
projectDir: cwd,
|
||||
});
|
||||
if (!result.ok) {
|
||||
error(result.errorDetails && result.errorDetails.message
|
||||
? result.errorDetails.message
|
||||
: `phase ${registryCommand} failed (${result.errorKind})`);
|
||||
return;
|
||||
}
|
||||
if (raw) {
|
||||
output(null, true, typeof result.data === 'string' ? result.data : String(result.data ?? ''));
|
||||
} else {
|
||||
output(result.data);
|
||||
}
|
||||
};
|
||||
// ── 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;
|
||||
}
|
||||
|
||||
routeCjsCommandFamily({
|
||||
args,
|
||||
subcommands: PHASE_SUBCOMMANDS,
|
||||
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.',
|
||||
},
|
||||
error,
|
||||
unknownMessage: (_subcommand, available) => `Unknown phase subcommand. Available: ${available.join(', ')}`,
|
||||
handlers: {
|
||||
'mvp-mode': () => phase.cmdPhaseMvpMode(cwd, args.slice(2), raw),
|
||||
'next-decimal': sdkHandler(
|
||||
'phase.next-decimal',
|
||||
args.slice(2),
|
||||
args.slice(1),
|
||||
() => phase.cmdPhaseNextDecimal(cwd, args[2], raw),
|
||||
),
|
||||
add: sdkHandler(
|
||||
'phase.add',
|
||||
args.slice(2),
|
||||
args.slice(1),
|
||||
() => {
|
||||
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('--')) {
|
||||
error('--id requires a value');
|
||||
return;
|
||||
}
|
||||
customId = id;
|
||||
i++;
|
||||
} else if (token.startsWith('--')) {
|
||||
error(`phase add does not support ${token}`);
|
||||
return;
|
||||
} else {
|
||||
descArgs.push(token);
|
||||
}
|
||||
// ── 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;
|
||||
}
|
||||
phase.cmdPhaseAdd(cwd, descArgs.join(' '), raw, customId);
|
||||
},
|
||||
),
|
||||
'add-batch': sdkHandler(
|
||||
'phase.add-batch',
|
||||
args.slice(2),
|
||||
args.slice(1),
|
||||
() => {
|
||||
const descFlagIdx = args.indexOf('--descriptions');
|
||||
let descriptions;
|
||||
if (descFlagIdx !== -1) {
|
||||
const rawDescriptions = args[descFlagIdx + 1];
|
||||
if (!rawDescriptions || rawDescriptions.startsWith('--')) {
|
||||
error('--descriptions must be a JSON array');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
descriptions = JSON.parse(rawDescriptions);
|
||||
} catch {
|
||||
error('--descriptions must be a JSON array');
|
||||
return;
|
||||
}
|
||||
if (!Array.isArray(descriptions)) {
|
||||
error('--descriptions must be a JSON array');
|
||||
return;
|
||||
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 {
|
||||
descriptions = args.slice(2).filter(a => a !== '--raw');
|
||||
descArgs.push(token);
|
||||
}
|
||||
phase.cmdPhaseAddBatch(cwd, descriptions, raw);
|
||||
},
|
||||
),
|
||||
insert: sdkHandler(
|
||||
'phase.insert',
|
||||
args.slice(2),
|
||||
args.slice(1),
|
||||
() => {
|
||||
if (args.includes('--dry-run')) {
|
||||
error('phase insert does not support --dry-run');
|
||||
return;
|
||||
}
|
||||
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' };
|
||||
}
|
||||
phase.cmdPhaseInsert(cwd, args[2], args.slice(3).join(' '), raw);
|
||||
},
|
||||
),
|
||||
remove: sdkHandler(
|
||||
'phase.remove',
|
||||
args.slice(2),
|
||||
args.slice(1),
|
||||
() => {
|
||||
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('--')) {
|
||||
error(`phase remove does not support ${token}`);
|
||||
return;
|
||||
}
|
||||
positional.push(token);
|
||||
try {
|
||||
descriptions = JSON.parse(rawDescriptions);
|
||||
} catch {
|
||||
return { ok: false, errorKind: 'InvalidArgs', message: '--descriptions must be a JSON array' };
|
||||
}
|
||||
if (positional.length !== 1) {
|
||||
error('phase remove accepts exactly one phase number');
|
||||
return;
|
||||
if (!Array.isArray(descriptions)) {
|
||||
return { ok: false, errorKind: 'InvalidArgs', message: '--descriptions must be a JSON array' };
|
||||
}
|
||||
phase.cmdPhaseRemove(cwd, positional[0], { force: forceFlag }, raw);
|
||||
},
|
||||
),
|
||||
complete: sdkHandler(
|
||||
'phase.complete',
|
||||
args.slice(2),
|
||||
args.slice(1),
|
||||
() => phase.cmdPhaseComplete(cwd, args[2], raw),
|
||||
),
|
||||
} 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 = {
|
||||
|
||||
Reference in New Issue
Block a user