* refactor(hub): tighten Result<T> to typed-payload-per-kind discriminated union (#176) Each Hub error variant now carries only its own typed payload. The generic `errorKind` field is renamed to `kind`; `message`/`details` escape hatches are removed from Hub-emitted errors. Factory functions (makeUnknownCommand, makeInvalidArgs, makeHandlerRefusal, makeHandlerFailure) are exported and used in phase-command-router.cjs. Callers switch on `result.kind`. Part of ADR-0174 P1.2. <!-- docs-exempt: no docs/ changes; API is internal to Hub callers --> Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(hub): act on P1.2 review findings (#176) Addresses 4 review findings on PR #221: - Hub now runtime-validates ok:false variants against the typed shape and coerces malformed returns to HandlerFailure with a contract- violation message (codex finding #1, code-review finding #1) - catch path now preserves the original throwable for non-Error throws via an Error wrapper with .thrown attached (codex finding #2) - All 4 factory returns are Object.freeze'd (review finding #9) - makeHandlerFailure validates cause is Error; non-Error causes are wrapped with .thrown attached (review finding #10) Tests added for each finding (TDD red → green). Refs #176. Part of #174. * fix(docs-lint): add docs-exempt markers to both P1.2 changeset fragments Both `176-typed-result-discriminated-union.md` and `176-hub-p1.2-review-findings.md` carry `type: Changed` which triggers the docs-required lint. Neither fragment had a `<!-- docs-exempt: <reason> -->` marker, causing `docs-lint` to fail with `FAIL_DOCS_MISSING`. Added the per-fragment exemption marker to both (the repo has no `no-docs` label). This is a purely internal SDK refactor (ADR-0174 P1.2) with no public docs surface. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
199 lines
8.3 KiB
JavaScript
199 lines
8.3 KiB
JavaScript
'use strict';
|
|
|
|
const { PHASE_SUBCOMMANDS } = require('./command-aliases.generated.cjs');
|
|
|
|
// ─── CommandRoutingHub (issue #3788, simplified in #175, typed in #176) ───────
|
|
const { createHub, ERROR_KINDS, makeInvalidArgs } = require('./command-routing-hub.cjs');
|
|
|
|
/**
|
|
* Manifest-backed phase subcommand router.
|
|
* Keeps gsd-tools.cjs thin while preserving existing command semantics.
|
|
*
|
|
* #175: Hub is CJS-only. The SDK bridge is still separately invokable via
|
|
* bin/lib/cjs-sdk-bridge.cjs, but the Hub no longer routes to it.
|
|
*
|
|
* SDK-only (unsupported in CJS router — error returned before dispatch):
|
|
* - list-plans: SDK-only.
|
|
* - list-artifacts: SDK-only.
|
|
* - scaffold: routed through top-level scaffold command.
|
|
*
|
|
* CJS-only subcommands: mvp-mode (dispatched directly, before hub).
|
|
*
|
|
* #3788: dispatch is mediated by CommandRoutingHub. The public entry point
|
|
* and observable CLI behaviour are unchanged.
|
|
*/
|
|
function routePhaseCommand({ phase, args, cwd, raw, error }) {
|
|
// ── 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 (dispatched directly, before hub) ─────────────────
|
|
// `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 to preserve 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 makeInvalidArgs('--id', '--id requires a value');
|
|
}
|
|
customId = id;
|
|
i++;
|
|
} else if (token.startsWith('--')) {
|
|
return makeInvalidArgs(token, `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 makeInvalidArgs('--descriptions', '--descriptions must be a JSON array');
|
|
}
|
|
try {
|
|
descriptions = JSON.parse(rawDescriptions);
|
|
} catch {
|
|
return makeInvalidArgs('--descriptions', '--descriptions must be a JSON array');
|
|
}
|
|
if (!Array.isArray(descriptions)) {
|
|
return makeInvalidArgs('--descriptions', '--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 makeInvalidArgs('--dry-run', '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 makeInvalidArgs(token, `phase remove does not support ${token}`);
|
|
}
|
|
positional.push(token);
|
|
}
|
|
if (positional.length !== 1) {
|
|
return makeInvalidArgs('<phase-number>', '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 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 ──────────────────────────────────────────────────────────
|
|
// #175: Hub is CJS-only — no mode param, no sdkLoader.
|
|
const hub = createHub({ cjsRegistry, manifest });
|
|
|
|
// ── Dispatch ────────────────────────────────────────────────────────────────
|
|
const result = hub.dispatch({
|
|
family: 'phase',
|
|
subcommand,
|
|
args: args.slice(2),
|
|
cwd,
|
|
raw,
|
|
});
|
|
|
|
// ── Translate result → CLI output / error (adapter responsibility) ──────────
|
|
// CJS handlers call output() themselves (inside phase.cmdPhase*()).
|
|
// No further output call is needed here.
|
|
if (!result.ok) {
|
|
if (result.kind === ERROR_KINDS.UnknownCommand) {
|
|
const available = availableSubcommands.join(', ');
|
|
error(`Unknown phase subcommand. Available: ${available}`);
|
|
return;
|
|
}
|
|
if (result.kind === ERROR_KINDS.InvalidArgs || result.kind === ERROR_KINDS.HandlerRefusal) {
|
|
// #176: typed payload — reason holds the human-readable message
|
|
error(result.reason);
|
|
return;
|
|
}
|
|
// HandlerFailure: message field
|
|
error(result.message);
|
|
return;
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
routePhaseCommand,
|
|
};
|