Files
msd-core/get-shit-done/bin/lib/state-command-router.cjs
Tom Boucher 7ebcf41939 feat(3567): state.* router delegates via executeForCjs + Phase 5.0 worker fix (Phase 5.1 of #3524)
Phase 5.1 of the CJS↔SDK hard-seam migration (parent #3524). Migrates
the bin/lib/state-command-router.cjs handlers map to delegate every
canonical state subcommand through the executeForCjs synchronous
primitive (shipped in Phase 5.0, PR #3558).

## Bundled fix for Phase 5.0 worker defect

Discovered during Phase 5.1 implementation that the Phase 5.0
worker drops projectDir and workstream from
RuntimeBridgeExecuteInput. The dispatch closure at
sdk/src/runtime-bridge-sync/worker.ts:41-42 hardcoded projectDir
to '', so registry handlers that read .planning/ from projectDir
(every state.* handler) saw an empty path and failed. Phase 5.0's
pinning tests passed because they exercised commands that don't
depend on projectDir (generate-slug takes its arg directly;
unknown_command doesn't dispatch). Maintainer authorized bundling
the fix into this PR.

Fix: moved QueryNativeDirectAdapter construction inside the
dispatchNative lambda so request.projectDir and request.workstream
close over the per-request values. Per-request adapter construction
adds <1ms overhead; correctness wins. Regression test at
sdk/src/runtime-bridge-sync/projectdir-regression.test.ts demonstrates
RED before fix → GREEN after.

Phase 5.0's index.test.ts native_failure fixture was passing
because of the bug — it relied on projectDir = '' producing a
specific error path. Updated to use a /nonexistent-... path that
triggers ENOENT under realpath, producing native_failure as intended.

## What landed for Phase 5.1

- bin/lib/state-command-router.cjs migrated. Every subcommand
  entry in the handlers map dispatches via executeForCjs when SDK
  is available, with transparent fallback to the existing CJS
  handlers in state.cjs if (a) SDK is not built / not present, or
  (b) GSD_WORKSTREAM is set (the sync-bridge worker cannot serve
  workstream-scoped commands per the SDK transport architecture).
- Special cases preserved:
  - load --raw: SDK data formatted into key=value lines matching
    cmdStateLoad's exact format.
  - complete-phase: CJS-only (no SDK counterpart yet).
  - add-roadmap-evolution: stays on the unsupported list (SDK-only).
- Golden parity tests added for 12 previously-uncovered state
  subcommands: advance-plan, record-metric, update-progress,
  add-decision, add-blocker, resolve-blocker, record-session,
  signal-waiting, signal-resume, planned-phase, milestone-switch,
  prune.

## Design decisions worth reviewer visibility

1. Lazy SDK loading with CJS fallback. The migration routes via
   executeForCjs only when the SDK is loadable; otherwise falls
   back to the existing CJS handlers. Conservative for rollback —
   if the SDK build is broken on a deploy, state commands keep
   working via the CJS path. Trade-off: drift surface is not
   structurally eliminated yet — the CJS handlers remain reachable.

2. Workstream → CJS fallback. The SDK transport forces subprocess
   for workstream commands, but subprocess is disabled in the sync
   bridge. When GSD_WORKSTREAM is set, the entire state command
   falls back to CJS rather than failing. Workstream users continue
   running the CJS handlers; the SDK path is exercised only in the
   default (no workstream) case.

3. Two documented parity divergences. state.record-metric: CJS
   auto-creates ## Performance Metrics section when absent; SDK
   returns {recorded: false, reason}. Test requires fixture with
   the section present. state.prune: CJS counts phases from disk;
   SDK reads from frontmatter fields. Test asserts structural shape
   rather than exact equality.

## Numbers

- Full CJS suite: 9323/9323 pass (baseline 9323; +0 net because
  the 12 new parity tests are SDK-side vitest, not CJS-side).
- SDK vitest sync-bridge: 10/10 pass.
- Regression test: 3/3 pass (proved RED before fix, GREEN after).
- tests/state.test.cjs (the safety net): 104/104 pass unchanged.

## Performance

gsd-tools state load via the SDK path: 49ms first call (Worker
startup), 43-44ms steady-state median. Slower than the
Phase 5.0-measured 0.1ms because state.load does fs reads on top
of the bridge overhead. Still well within the budget for CJS
dispatcher overhead.

Closes #3567.
2026-05-15 14:34:25 -04:00

318 lines
11 KiB
JavaScript

'use strict';
const { STATE_SUBCOMMANDS } = require('./command-aliases.generated.cjs');
const { routeCjsCommandFamily } = require('./cjs-command-router-adapter.cjs');
const { output } = require('./core.cjs');
// ─── SDK bridge (Phase 5.1) ─────────────────────────────────────────────────
// executeForCjs requires the compiled dist artifact. The require() path is
// resolved from gsd-tools.cjs's node_modules rather than this file's location,
// so we use a lazy require to avoid resolution errors on environments that
// haven't built the SDK yet.
let _executeForCjs = null;
let _formatStateLoadRawStdout = null;
function tryLoadSdk() {
if (_executeForCjs !== null) return true;
try {
const bridgeModule = require('@gsd-build/sdk/dist/runtime-bridge-sync/index.js');
_executeForCjs = bridgeModule.executeForCjs;
// formatStateLoadRawStdout is in state-project-load (re-exported from SDK dist)
const loadModule = require('@gsd-build/sdk/dist/query/state-project-load.js');
_formatStateLoadRawStdout = loadModule.formatStateLoadRawStdout;
return true;
} catch {
return false;
}
}
/**
* Dispatch a subcommand via the SDK sync bridge.
*
* Returns true if dispatched successfully, false if the SDK is unavailable.
* The caller must still handle result.ok=false as a hard error.
*
* @param {string} registryCommand - Registry command name (e.g. 'state.json')
* @param {string[]} registryArgs - Args for the registry handler
* @param {string} cwd - Project directory
* @param {boolean} raw - Raw output mode
* @param {Function} error - Error reporter
* @param {Function} [rawFormatter] - Optional raw output formatter (for state.load)
* @returns {boolean} true if handled, false to fall through to CJS
*/
function dispatchViaSdk(registryCommand, registryArgs, legacyArgs, cwd, raw, error, rawFormatter) {
if (!tryLoadSdk()) return false;
const result = _executeForCjs({
registryCommand,
registryArgs,
legacyCommand: 'state',
legacyArgs,
mode: raw ? 'raw' : 'json',
projectDir: cwd,
// workstream: not threaded here — GSDTransport forces subprocess for workstream
// requests and subprocess is disabled in the worker. Workstream commands fall
// back to the CJS path (see routeStateCommand guard below).
});
if (!result.ok) {
error(result.errorDetails && result.errorDetails.message
? result.errorDetails.message
: `state ${registryCommand} failed (${result.errorKind})`);
return true; // handled (error was reported)
}
if (raw && rawFormatter) {
const rawText = rawFormatter(result.data);
const fs = require('fs');
fs.writeSync(1, rawText);
} else {
output(result.data);
}
return true;
}
/**
* Manifest-backed state subcommand router.
* Keeps gsd-tools.cjs thin while preserving existing command semantics.
*
* Phase 5.1: handlers that have SDK equivalents are dispatched via
* executeForCjs (the sync bridge). CJS fallback is retained for:
* - complete-phase: no SDK counterpart.
* - Any command when GSD_WORKSTREAM is active (GSDTransport forces subprocess
* for workstream requests; subprocess is disabled in the sync bridge worker).
* - Any command when the SDK is not available (build not present).
*/
function routeStateCommand({ state, args, cwd, raw, parseNamedArgs, error }) {
const parsePlans = (plans) => {
const parsedPlans = plans == null ? null : Number.parseInt(plans, 10);
if (plans != null && Number.isNaN(parsedPlans)) {
error('Invalid --plans value. Expected an integer.');
return null;
}
return parsedPlans;
};
// Workstream guard: if GSD_WORKSTREAM is set, the sync bridge worker cannot
// handle the request (GSDTransport.subprocessReason returns 'workstream_forced'
// and subprocess is disabled in the worker). Fall back to CJS path for all
// workstream-scoped state commands.
const activeWorkstream = process.env.GSD_WORKSTREAM;
const sdkAvailable = !activeWorkstream && tryLoadSdk();
// Helper: build SDK-backed handler that falls through to CJS on SDK failure.
// cjsFallback is called when SDK is unavailable or when the subcommand has no
// SDK counterpart.
function sdkHandler(registryCommand, registryArgs, legacyArgs, rawFormatter, cjsFallback) {
if (!sdkAvailable) return cjsFallback;
return () => {
const handled = dispatchViaSdk(
registryCommand, registryArgs, legacyArgs, cwd, raw, error, rawFormatter,
);
if (!handled) cjsFallback();
};
}
routeCjsCommandFamily({
args,
subcommands: ['load', 'complete-phase', ...STATE_SUBCOMMANDS.filter((s) => s !== 'load')],
defaultSubcommand: 'load',
unsupported: {
'add-roadmap-evolution': 'state add-roadmap-evolution is SDK-only. Use: gsd-sdk query state.add-roadmap-evolution ...',
},
error,
unknownMessage: (subcommand, available) => `Unknown state subcommand: "${subcommand}". Available: ${available.join(', ')}`,
handlers: {
load: sdkHandler(
'state.load',
[],
args.slice(1),
_formatStateLoadRawStdout,
() => state.cmdStateLoad(cwd, raw),
),
json: sdkHandler(
'state.json',
[],
args.slice(1),
null,
() => state.cmdStateJson(cwd, raw),
),
get: sdkHandler(
'state.get',
args.slice(2),
args.slice(1),
null,
() => state.cmdStateGet(cwd, args[2], raw),
),
update: sdkHandler(
'state.update',
args.slice(2),
args.slice(1),
null,
() => state.cmdStateUpdate(cwd, args[2], args[3]),
),
patch: sdkHandler(
'state.patch',
args.slice(2),
args.slice(1),
null,
() => {
const patches = {};
for (let i = 2; i < args.length; i += 2) {
const key = args[i].replace(/^--/, '');
const value = args[i + 1];
if (key && value !== undefined) {
patches[key] = value;
}
}
state.cmdStatePatch(cwd, patches, raw);
},
),
'advance-plan': sdkHandler(
'state.advance-plan',
[],
args.slice(1),
null,
() => state.cmdStateAdvancePlan(cwd, raw),
),
'record-metric': sdkHandler(
'state.record-metric',
args.slice(2),
args.slice(1),
null,
() => {
const { phase: p, plan, duration, tasks, files } = parseNamedArgs(args, ['phase', 'plan', 'duration', 'tasks', 'files']);
state.cmdStateRecordMetric(cwd, { phase: p, plan, duration, tasks, files }, raw);
},
),
'update-progress': sdkHandler(
'state.update-progress',
[],
args.slice(1),
null,
() => state.cmdStateUpdateProgress(cwd, raw),
),
'add-decision': sdkHandler(
'state.add-decision',
args.slice(2),
args.slice(1),
null,
() => {
const { phase: p, summary, 'summary-file': summary_file, rationale, 'rationale-file': rationale_file } = parseNamedArgs(args, ['phase', 'summary', 'summary-file', 'rationale', 'rationale-file']);
state.cmdStateAddDecision(cwd, { phase: p, summary, summary_file, rationale: rationale || '', rationale_file }, raw);
},
),
'add-blocker': sdkHandler(
'state.add-blocker',
args.slice(2),
args.slice(1),
null,
() => {
const { text, 'text-file': text_file } = parseNamedArgs(args, ['text', 'text-file']);
state.cmdStateAddBlocker(cwd, { text, text_file }, raw);
},
),
'resolve-blocker': sdkHandler(
'state.resolve-blocker',
args.slice(2),
args.slice(1),
null,
() => state.cmdStateResolveBlocker(cwd, parseNamedArgs(args, ['text']).text, raw),
),
'record-session': sdkHandler(
'state.record-session',
args.slice(2),
args.slice(1),
null,
() => {
const { 'stopped-at': stopped_at, 'resume-file': resume_file } = parseNamedArgs(args, ['stopped-at', 'resume-file']);
state.cmdStateRecordSession(cwd, { stopped_at, resume_file: resume_file || 'None' }, raw);
},
),
'begin-phase': sdkHandler(
'state.begin-phase',
args.slice(2),
args.slice(1),
null,
() => {
const { phase: p, name, plans } = parseNamedArgs(args, ['phase', 'name', 'plans']);
state.cmdStateBeginPhase(cwd, p, name, parsePlans(plans), raw);
},
),
'signal-waiting': sdkHandler(
'state.signal-waiting',
args.slice(2),
args.slice(1),
null,
() => {
const { type, question, options, phase: p } = parseNamedArgs(args, ['type', 'question', 'options', 'phase']);
state.cmdSignalWaiting(cwd, type, question, options, p, raw);
},
),
'signal-resume': sdkHandler(
'state.signal-resume',
[],
args.slice(1),
null,
() => state.cmdSignalResume(cwd, raw),
),
'planned-phase': sdkHandler(
'state.planned-phase',
args.slice(2),
args.slice(1),
null,
() => {
const { phase: p, plans } = parseNamedArgs(args, ['phase', 'name', 'plans']);
state.cmdStatePlannedPhase(cwd, p, parsePlans(plans), raw);
},
),
validate: sdkHandler(
'state.validate',
[],
args.slice(1),
null,
() => state.cmdStateValidate(cwd, raw),
),
sync: sdkHandler(
'state.sync',
args.slice(2),
args.slice(1),
null,
() => {
const { verify } = parseNamedArgs(args, [], ['verify']);
state.cmdStateSync(cwd, { verify }, raw);
},
),
prune: sdkHandler(
'state.prune',
args.slice(2),
args.slice(1),
null,
() => {
const { 'keep-recent': keepRecent, 'dry-run': dryRun } = parseNamedArgs(args, ['keep-recent'], ['dry-run']);
state.cmdStatePrune(cwd, { keepRecent: keepRecent || '3', dryRun: !!dryRun }, raw);
},
),
// complete-phase: CJS-only — no SDK counterpart.
'complete-phase': () => {
const { phase: p } = parseNamedArgs(args, ['phase']);
state.cmdStateCompletePhase(cwd, raw, p || args[2]);
},
'milestone-switch': sdkHandler(
'state.milestone-switch',
args.slice(2),
args.slice(1),
null,
() => {
const { milestone, name } = parseNamedArgs(args, ['milestone', 'name']);
state.cmdStateMilestoneSwitch(cwd, milestone, name, raw);
},
),
},
});
}
module.exports = {
routeStateCommand,
};