feat(#961): capability command mechanism (commandFamilies index + default-case dispatch) — ADR-857 phase 4d-impl-1 (#964)
* feat(#961): capability command mechanism — commandFamilies index + default-case dispatch (ADR-857 phase 4d-impl-1) Build the capability command mechanism per ADR-959: the `commands` declaration field on the feature role, the registry commandFamilies index, and a real dispatchCapabilityCommand consulted in runCommand's default case (replacing the dead _dispatchNonFamily shim's role). The registry DISCOVERS a standard route*Command (no rebuilt handler table). On a default-case command, dispatch enforces a bare-.cjs-basename, resolves the module under gsd-core/bin/lib/, asserts confinement, requires the resolved path, and own-property-guards the router export before calling it. A require.main===module guard makes gsd-tools.cjs importable for tests; the CLI path is unchanged. Additive: commandFamilies is empty today, so the default case is behavior- preserving for every command; the 10 dead _dispatchNonFamily sites are untouched (future migration markers). The graphify cutover is the separate next step. Closes #961 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#961): surface capability router failures structurally + enforce sync contract Review follow-up: dispatchCapabilityCommand now wraps the router invocation so an unexpected (non-ExitError) throw is converted to a structured, attributed error(msg, SDK_FAIL_FAST) — honoring --json-errors — instead of escaping as a raw stack trace; an intentional ExitError propagates unchanged. An async router (returns a thenable) is rejected loudly with a structured error (the contract is synchronous, like the 12 host routers). Not shipped as "consistent with existing behavior": the host's pre-existing version of this gap is filed as #965. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -256,6 +256,122 @@ function _dispatchNonFamily({ registryCommand, registryArgs, legacyCommand, lega
|
||||
return false;
|
||||
}
|
||||
|
||||
// ─── ADR-959: Capability Command Dispatch ─────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Dispatch a command via the capability registry's commandFamilies index.
|
||||
*
|
||||
* Consulted in the `default` case of `runCommand` BEFORE the unknown-command
|
||||
* error is emitted. Returns:
|
||||
* true — command was "consumed" (found in registry, or a dispatch error was
|
||||
* emitted); "Unknown command" is suppressed in all consumed cases.
|
||||
* false — command not found in the registry (including prototype-pollution
|
||||
* guard hits and missing/empty commandFamilies); caller falls through
|
||||
* to the existing unknown-command error path.
|
||||
* Behavior-preserving when commandFamilies is empty ({}).
|
||||
*
|
||||
* Injectable for tests:
|
||||
* - `registry` defaults to require('./lib/capability-registry.cjs')
|
||||
* - `requireModule` defaults to a confinement-checked loader that resolves the
|
||||
* module path relative to bin/lib/ and asserts it stays within that directory
|
||||
* before requiring — defense-in-depth against corrupted/hand-edited registry entries.
|
||||
*
|
||||
* @param {object} opts
|
||||
* @param {string} opts.command The command name (top-level gsd-tools command)
|
||||
* @param {string[]} opts.args Remaining args passed to the router
|
||||
* @param {string} opts.cwd Project working directory
|
||||
* @param {boolean} opts.raw Raw output mode flag
|
||||
* @param {Function} opts.error Error reporter (core.error)
|
||||
* @param {object} [opts.registry] Injectable registry (for tests)
|
||||
* @param {Function} [opts.requireModule] Injectable module loader (for tests)
|
||||
* @returns {boolean} true if the command was dispatched, false otherwise
|
||||
*/
|
||||
function dispatchCapabilityCommand({ command, args, cwd, raw, error, registry, requireModule }) {
|
||||
// Prototype-pollution guard: reject reserved property names as command keys
|
||||
if (command === '__proto__' || command === 'constructor' || command === 'prototype') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Resolve defaults (injectable for tests)
|
||||
const reg = registry !== undefined ? registry : require('./lib/capability-registry.cjs');
|
||||
|
||||
// Default requireModule: confined to bin/lib/ — validate the module name is a
|
||||
// safe bare .cjs basename (no path separators, no directory traversal), then
|
||||
// resolve and assert confinement, then require the RESOLVED absolute path so
|
||||
// the checked representation and the required representation are identical.
|
||||
const libDir = path.join(__dirname, 'lib');
|
||||
const defaultRequireModule = function (m) {
|
||||
// Step 1: validate m is a bare .cjs basename — same conservative pattern the
|
||||
// generator uses. Rejects any value with path separators (/, \, ..) or
|
||||
// missing the .cjs extension before we even touch the filesystem.
|
||||
if (typeof m !== 'string' || !/^[A-Za-z0-9._-]+\.cjs$/.test(m)) {
|
||||
throw new Error('capability module must be a bare .cjs basename: ' + JSON.stringify(m));
|
||||
}
|
||||
// Step 2: confinement check — belt-and-suspenders even after the basename
|
||||
// validation above. Resolved path must be inside libDir (not equal to it,
|
||||
// and must start with libDir + sep so "libDir-suffix" can't sneak through).
|
||||
const resolved = path.resolve(libDir, m);
|
||||
if (resolved === libDir || !resolved.startsWith(libDir + path.sep)) {
|
||||
throw new Error('capability module path escapes bin/lib/: ' + JSON.stringify(m));
|
||||
}
|
||||
// Step 3: require the resolved absolute path — the SAME representation that
|
||||
// was checked above, not the concatenated './lib/' + m string.
|
||||
return require(resolved);
|
||||
};
|
||||
const loadModule = requireModule !== undefined ? requireModule : defaultRequireModule;
|
||||
|
||||
// Look up the command family in the registry
|
||||
const families = reg && reg.commandFamilies;
|
||||
if (!families || typeof families !== 'object') return false;
|
||||
|
||||
const entry = families[command];
|
||||
if (!entry || typeof entry !== 'object') return false;
|
||||
|
||||
// Resolve and call the router
|
||||
let mod;
|
||||
try {
|
||||
mod = loadModule(entry.module);
|
||||
} catch (_) {
|
||||
// Module not found, load error, or confinement violation — surface a
|
||||
// diagnostic and return true (consumed) so "Unknown command" is suppressed.
|
||||
error('capability command "' + command + '" module "' + entry.module + '" failed to load');
|
||||
return true; // consumed — don't emit "Unknown command"
|
||||
}
|
||||
|
||||
// Own-property guard: prevent invoking inherited prototype methods
|
||||
// (constructor, toString, hasOwnProperty, etc.) as a router when the registry
|
||||
// entry names one of those. Must come before the typeof check.
|
||||
if (!mod || !Object.prototype.hasOwnProperty.call(mod, entry.router)) {
|
||||
error('capability command "' + command + '" router "' + entry.router + '" is not an own export of module "' + entry.module + '"');
|
||||
return true; // consumed — don't emit "Unknown command"
|
||||
}
|
||||
const fn = mod[entry.router];
|
||||
if (typeof fn !== 'function') {
|
||||
// Router export not found — surface a diagnostic and return true (consumed)
|
||||
// so "Unknown command" is suppressed.
|
||||
error('capability command "' + command + '" router "' + entry.router + '" is not a function in module "' + entry.module + '"');
|
||||
return true; // consumed — don't emit "Unknown command"
|
||||
}
|
||||
|
||||
let _result;
|
||||
try {
|
||||
_result = fn({ args, cwd, raw, error });
|
||||
} catch (e) {
|
||||
if (e instanceof ExitError) throw e; // intentional structured error from the router (honors --json-errors) — propagate untouched
|
||||
error(
|
||||
'capability command "' + command + '" router "' + entry.router + '" in module "' + entry.module + '" threw: ' + (e && e.message ? e.message : String(e)),
|
||||
ERROR_REASON.SDK_FAIL_FAST,
|
||||
);
|
||||
}
|
||||
if (_result && typeof _result.then === 'function') {
|
||||
error(
|
||||
'capability command "' + command + '" router "' + entry.router + '" in module "' + entry.module + '" must be synchronous (returned a Promise); async capability routers are not supported.',
|
||||
ERROR_REASON.SDK_FAIL_FAST,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ─── Arg parsing helpers ──────────────────────────────────────────────────────
|
||||
|
||||
// ─── CLI Router ───────────────────────────────────────────────────────────────
|
||||
@@ -1966,6 +2082,13 @@ async function runCommand(command, args, cwd, raw, defaultValue, originalCommand
|
||||
}
|
||||
|
||||
default: {
|
||||
// ADR-959: try capability-registry dispatch before emitting the unknown-command error.
|
||||
// An unmigrated command still hits its hardcoded `case` above — untouched.
|
||||
// A migrated command's `case` is removed at cutover, so it reaches here and
|
||||
// dispatchCapabilityCommand routes it to the capability's registered router.
|
||||
// With commandFamilies={} today, this always returns false and is a no-op.
|
||||
if (dispatchCapabilityCommand({ command, args, cwd, raw, error })) break;
|
||||
|
||||
// #3243: if the caller passed a dotted form (e.g. "foo.bar"), the shim
|
||||
// above split it so `command` here is the head ("foo"). Use
|
||||
// originalCommand to reconstruct the original dotted form and suggest
|
||||
@@ -1987,4 +2110,12 @@ async function runCommand(command, args, cwd, raw, defaultValue, originalCommand
|
||||
}
|
||||
}
|
||||
|
||||
runMain(main);
|
||||
// ─── CLI entry point ──────────────────────────────────────────────────────────
|
||||
if (require.main === module) {
|
||||
runMain(main);
|
||||
}
|
||||
|
||||
// ─── Exports (for tests) ──────────────────────────────────────────────────────
|
||||
// ADR-959: export dispatchCapabilityCommand so tests can exercise it with
|
||||
// synthetic registry + requireModule injections.
|
||||
module.exports = { dispatchCapabilityCommand };
|
||||
|
||||
@@ -230,6 +230,8 @@ const configSchema = {
|
||||
|
||||
const runtimes = {};
|
||||
|
||||
const commandFamilies = {};
|
||||
|
||||
const capabilityClusters = {
|
||||
"ui": [
|
||||
"ui-phase",
|
||||
@@ -275,6 +277,7 @@ module.exports = {
|
||||
configKeys,
|
||||
configSchema,
|
||||
runtimes,
|
||||
commandFamilies,
|
||||
capabilityClusters,
|
||||
profileMembership,
|
||||
requiresClosure,
|
||||
|
||||
Reference in New Issue
Block a user