diff --git a/docs/INVENTORY-MANIFEST.json b/docs/INVENTORY-MANIFEST.json index e921e8ea0..8d9973418 100644 --- a/docs/INVENTORY-MANIFEST.json +++ b/docs/INVENTORY-MANIFEST.json @@ -265,7 +265,6 @@ "artifacts.cjs", "audit.cjs", "cjs-command-router-adapter.cjs", - "cjs-sdk-bridge.cjs", "clusters.cjs", "code-review-flags.cjs", "command-aliases.cjs", diff --git a/docs/INVENTORY.md b/docs/INVENTORY.md index f96b2f834..f6811b054 100644 --- a/docs/INVENTORY.md +++ b/docs/INVENTORY.md @@ -362,7 +362,7 @@ The `gsd-planner` agent is decomposed into a core agent plus reference modules t --- -## CLI Modules (72 shipped) +## CLI Modules (71 shipped) Full listing: `get-shit-done/bin/lib/*.cjs`. @@ -373,7 +373,6 @@ Full listing: `get-shit-done/bin/lib/*.cjs`. | `artifacts.cjs` | Canonical artifact registry — known `.planning/` root file names; used by `gsd-health` W019 lint | | `audit.cjs` | Audit dispatch, audit open sessions, audit storage helpers | | `cjs-command-router-adapter.cjs` | Shared compatibility adapter for manifest-backed CJS command-family routers | -| `cjs-sdk-bridge.cjs` | Shared SDK runtime-bridge loader (`tryLoadSdk`/`getExecuteForCjs`); consumed by every CJS router and `gsd-tools.cjs` to delegate canonical commands to the SDK in-process | | `clusters.cjs` | Skill cluster definitions for the runtime surface module (ADR-0011 Phase 2) | | `code-review-flags.cjs` | Typed flag parser for `/gsd:code-review`; exports `parseCodeReviewFlags(argv)` (→ `{ fix, all, auto, depth, files }`) and `resolveCodeReviewWorkflow(flags)` (→ `'code-review.md' \| 'code-review-fix.md'`); canonical dispatch seam for `--fix`/`--all`/`--auto` routing | | `command-aliases.cjs` | Alias/subcommand metadata for manifest-backed family routers | diff --git a/get-shit-done/bin/gsd-tools.cjs b/get-shit-done/bin/gsd-tools.cjs index 350b2ef05..5e403d9f8 100755 --- a/get-shit-done/bin/gsd-tools.cjs +++ b/get-shit-done/bin/gsd-tools.cjs @@ -199,19 +199,10 @@ const { routePhasesCommand } = require('./lib/phases-command-router.cjs'); const { routeValidateCommand } = require('./lib/validate-command-router.cjs'); const { routeRoadmapCommand } = require('./lib/roadmap-command-router.cjs'); -// ─── SDK bridge (Phase 6 inline family / non-family delegation) ─────────────── -// For inline case blocks that have SDK counterparts (frontmatter, config, and -// non-family commands), we attempt to dispatch via executeForCjs (the sync -// bridge). CJS handlers are retained as fallback when SDK is unavailable. -// -// NOTE: migrate-config, detect-custom-files, config-path, and find-phase -// are CJS-native special cases; see comments inline. - -// Shared loader for the synchronous SDK runtime bridge; see -// `bin/lib/cjs-sdk-bridge.cjs`. All canonical-command CJS dispatchers (the -// per-family routers and the non-family helper below) consume the same loader -// so a change to the SDK-load contract lands in one place. -const { tryLoadSdk: _tryLoadSdkBridge, getExecuteForCjs } = require('./lib/cjs-sdk-bridge.cjs'); +// ─── Bridge collapsed (Phase 4) ──────────────────────────────────────────────── +// Non-family commands now run through their CJS handlers directly. Keep the +// helper contract so existing call sites remain unchanged during the phase +// sequence; it always returns false so callers fall through to CJS. /** * Attempt SDK dispatch for a non-family command. @@ -231,55 +222,15 @@ const { tryLoadSdk: _tryLoadSdkBridge, getExecuteForCjs } = require('./lib/cjs-s * @param {Function} opts.output - output emitter (core.output) */ function _dispatchNonFamily({ registryCommand, registryArgs, legacyCommand, legacyArgs, cwd, raw, error, output }) { - if (!_tryLoadSdkBridge()) return false; - let result; - try { - result = getExecuteForCjs()({ - registryCommand, - registryArgs, - legacyCommand, - legacyArgs, - // Always request typed JSON from the bridge; CJS `output(data, raw)` handles - // user-facing rendering. Passing `mode: 'raw'` would make the bridge - // pre-render result.data to a JSON string that the CJS output path then - // double-stringifies (returning a JSON string of a JSON string). - mode: 'json', - projectDir: cwd, - workstream: process.env.GSD_WORKSTREAM || undefined, - }); - } catch { - // Bridge threw (e.g. synckit worker crash, Atomics failure on Windows). - // Return false so the caller falls through to the CJS handler. - return false; - } - if (!result.ok) { - const message = (result.errorDetails && result.errorDetails.message) - || `${legacyCommand} (${registryCommand}) failed (${result.errorKind})`; - // Propagate the structured reason code through to CJS `error()` so the - // `--json-errors` JSON-shaped stderr carries the typed reason (e.g. - // 'config_key_not_found') instead of the generic 'unknown'. Handlers - // tag the GSDError with `.reason` and the worker forwards it via - // errorDetails.reason. (Bugs #2943, #3086.) - const reason = result.errorDetails && result.errorDetails.reason; - if (reason) { - error(message, reason); - } else { - error(message); - } - return true; // handled (error reported) - } - // CJS parity for --raw output (config.cjs:525 `output(value, raw, String(value))`): - // when the caller asked for --raw and the SDK returned a scalar, pass that - // scalar through as `rawValue` so core.output() emits the bare string - // representation instead of JSON-stringifying it. Non-scalar shapes fall - // through to the structured JSON path, matching `output(obj, raw)`. - const data = result.data; - if (raw && (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean')) { - output(data, raw, String(data)); - } else { - output(data, raw); - } - return true; + void registryCommand; + void registryArgs; + void legacyCommand; + void legacyArgs; + void cwd; + void raw; + void error; + void output; + return false; } // ─── Arg parsing helpers ────────────────────────────────────────────────────── diff --git a/get-shit-done/bin/lib/cjs-sdk-bridge.cjs b/get-shit-done/bin/lib/cjs-sdk-bridge.cjs deleted file mode 100644 index 6f5c3ea52..000000000 --- a/get-shit-done/bin/lib/cjs-sdk-bridge.cjs +++ /dev/null @@ -1,136 +0,0 @@ -'use strict'; - -/** - * CJS↔SDK Sync Runtime Bridge Adapter — Phase 5/6 of #3524. - * - * Single shared loader for the synchronous SDK runtime bridge that every CJS - * command-router family file and `gsd-tools.cjs` non-family dispatcher - * delegates through. Centralizing the load prevents the seven-fold duplicated - * `tryLoadSdk` blocks that existed across the routers from drifting against - * each other (the exact anti-pattern the Phase 6 hand-sync lint is meant to - * stop, applied to the SDK-load logic itself). - * - * Load path policy: the bridge resolves the bundled SDK by package-relative - * filesystem path, NOT by the `@opengsd/gsd-sdk` package name. The package name - * is not installed in the root `node_modules` (it lives as a sibling workspace - * package, not a dependency), and the SDK's public entry doesn't re-export - * `executeForCjs` or `formatStateLoadRawStdout` anyway. Using the relative - * path means the loader works identically in (a) the development checkout - * (`/sdk/dist/...`) and (b) the published package layout - * (`node_modules/get-shit-done-redux/sdk/dist/...`) because the `files` array in - * `package.json` keeps `sdk/dist` at the same path inside the published - * tarball. - * - * The previous implementation used `require('@opengsd/gsd-sdk')`, which always - * failed because the package was unresolvable from the consumer location. - * That cached `_loadFailed = true` for the lifetime of the process and made - * every router silently fall through to CJS — defeating Phase 5/6's entire - * goal. The integration test at `tests/cjs-sdk-bridge-integration.test.cjs` - * locks the load-success invariant so this regression cannot recur. - * - * Usage: - * const { tryLoadSdk, getExecuteForCjs } = require('./cjs-sdk-bridge.cjs'); - * if (tryLoadSdk()) { - * const result = getExecuteForCjs()({ ... }); - * } - * - * Plus `getFormatStateLoadRawStdout()` for the `state load --raw` adapter and - * `getSdkModule()` for routers that need the raw runtime-bridge-sync module. - */ - -const path = require('path'); - -// Computed once at module load. Resolves the bundled SDK relative to this -// file's on-disk location, so both dev and post-install layouts work. -// /get-shit-done/bin/lib/cjs-sdk-bridge.cjs -// /sdk/dist/runtime-bridge-sync/index.js -// /sdk/dist/query/state-project-load.js -const RUNTIME_BRIDGE_PATH = path.resolve( - __dirname, - '..', - '..', - '..', - 'sdk', - 'dist', - 'runtime-bridge-sync', - 'index.js', -); -const STATE_PROJECT_LOAD_PATH = path.resolve( - __dirname, - '..', - '..', - '..', - 'sdk', - 'dist', - 'query', - 'state-project-load.js', -); - -let _runtimeBridge = null; -let _formatStateLoadRawStdout = null; -let _loadFailed = false; - -/** - * Load the bundled SDK runtime bridge once and cache the result. Returns true - * on success, false if the dist artifacts are missing (e.g. `npm run - * build:sdk` has not been executed in a fresh dev checkout) or if the - * expected `executeForCjs` export is absent. Cached result is reused on - * subsequent calls. - */ -function tryLoadSdk() { - if (_runtimeBridge) return true; - if (_loadFailed) return false; - try { - // eslint-disable-next-line global-require - const bridge = require(RUNTIME_BRIDGE_PATH); - if (typeof bridge.executeForCjs !== 'function') { - _loadFailed = true; - return false; - } - // eslint-disable-next-line global-require - const stateProjectLoad = require(STATE_PROJECT_LOAD_PATH); - if (typeof stateProjectLoad.formatStateLoadRawStdout !== 'function') { - _loadFailed = true; - return false; - } - _runtimeBridge = bridge; - _formatStateLoadRawStdout = stateProjectLoad.formatStateLoadRawStdout; - return true; - } catch { - _loadFailed = true; - return false; - } -} - -/** - * Returns the cached `executeForCjs` function, or null if `tryLoadSdk()` has - * not been called or returned false. Callers must check `tryLoadSdk()` first. - */ -function getExecuteForCjs() { - return _runtimeBridge ? _runtimeBridge.executeForCjs : null; -} - -/** - * Returns the cached `formatStateLoadRawStdout` function, or null. Used by - * the state command router for the `state load --raw` adapter that projects - * SDK return data into the legacy key=value lines format. - */ -function getFormatStateLoadRawStdout() { - return _formatStateLoadRawStdout; -} - -/** - * Returns the cached runtime-bridge-sync module object after a successful - * `tryLoadSdk()`, or null. Provided for callers that need additional named - * exports beyond `executeForCjs`. - */ -function getSdkModule() { - return _runtimeBridge; -} - -module.exports = { - tryLoadSdk, - getExecuteForCjs, - getFormatStateLoadRawStdout, - getSdkModule, -}; diff --git a/get-shit-done/bin/lib/init-command-router.cjs b/get-shit-done/bin/lib/init-command-router.cjs index 69d6e72c3..e10105ecf 100644 --- a/get-shit-done/bin/lib/init-command-router.cjs +++ b/get-shit-done/bin/lib/init-command-router.cjs @@ -2,10 +2,6 @@ const { INIT_SUBCOMMANDS } = require('./command-aliases.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'); /** * Manifest-backed init subcommand router. @@ -20,44 +16,8 @@ const { tryLoadSdk, getExecuteForCjs } = require('./cjs-sdk-bridge.cjs'); * SDK-only (unsupported in CJS router): none. */ function routeInitCommand({ init, args, cwd, raw, parseNamedArgs, error }) { - const activeWorkstream = process.env.GSD_WORKSTREAM; - const sdkAvailable = !activeWorkstream && tryLoadSdk(); - - function sdkHandler(registryCommand, registryArgs, legacyArgs, cjsFallback) { - if (!sdkAvailable) return cjsFallback; - return () => { - let result; - try { - result = getExecuteForCjs()({ - registryCommand, - registryArgs, - legacyCommand: 'init', - legacyArgs, - // #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. - mode: raw ? 'raw' : 'json', - projectDir: cwd, - }); - } catch { - // Bridge threw (e.g. synckit worker crash, Atomics failure on Windows). - // Fall through to CJS handler — the CJS path is the designed safety net. - return cjsFallback(); - } - if (!result.ok) { - error(result.errorDetails && result.errorDetails.message - ? result.errorDetails.message - : `init ${registryCommand} failed (${result.errorKind})`); - return; - } - if (raw) { - output(null, true, typeof result.data === 'string' ? result.data : String(result.data ?? '')); - } else { - output(result.data); - } - }; + function sdkHandler(_registryCommand, _registryArgs, _legacyArgs, cjsFallback) { + return cjsFallback; } routeCjsCommandFamily({ diff --git a/get-shit-done/bin/lib/phases-command-router.cjs b/get-shit-done/bin/lib/phases-command-router.cjs index a38a8bb03..7918e1799 100644 --- a/get-shit-done/bin/lib/phases-command-router.cjs +++ b/get-shit-done/bin/lib/phases-command-router.cjs @@ -2,10 +2,6 @@ const { PHASES_SUBCOMMANDS } = require('./command-aliases.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'); /** * Manifest-backed phases subcommand router. @@ -25,37 +21,8 @@ const { tryLoadSdk, getExecuteForCjs } = require('./cjs-sdk-bridge.cjs'); * CJS-only subcommands: none. */ function routePhasesCommand({ phase, milestone, 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 () => { - const result = getExecuteForCjs()({ - registryCommand, - registryArgs, - legacyCommand: 'phases', - legacyArgs, - // #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. - mode: raw ? 'raw' : 'json', - projectDir: cwd, - }); - if (!result.ok) { - error(result.errorDetails && result.errorDetails.message - ? result.errorDetails.message - : `phases ${registryCommand} failed (${result.errorKind})`); - return; - } - if (raw) { - output(null, true, typeof result.data === 'string' ? result.data : String(result.data ?? '')); - } else { - output(result.data); - } - }; + function sdkHandler(_registryCommand, _registryArgs, _legacyArgs, cjsFallback) { + return cjsFallback; } routeCjsCommandFamily({ diff --git a/get-shit-done/bin/lib/roadmap-command-router.cjs b/get-shit-done/bin/lib/roadmap-command-router.cjs index 3740d255b..18ef35332 100644 --- a/get-shit-done/bin/lib/roadmap-command-router.cjs +++ b/get-shit-done/bin/lib/roadmap-command-router.cjs @@ -2,10 +2,6 @@ const { ROADMAP_SUBCOMMANDS } = require('./command-aliases.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'); /** * Manifest-backed roadmap subcommand router. @@ -20,50 +16,8 @@ const { tryLoadSdk, getExecuteForCjs } = require('./cjs-sdk-bridge.cjs'); * SDK-only (unsupported in CJS router): none. */ function routeRoadmapCommand({ roadmap, args, cwd, raw, error }) { - const activeWorkstream = process.env.GSD_WORKSTREAM; - // GSD_SDK_NESTED is set by SDK handlers that spawn gsd-tools.cjs as a - // child process (e.g. roadmapAnnotateDependencies). Without this guard - // the child process re-dispatches through the SDK bridge, which spawns - // again, ad infinitum until the synckit 15s timeout fires. Bug #3537 - // annotate-dependencies parity. - const nested = process.env.GSD_SDK_NESTED === '1'; - const sdkAvailable = !activeWorkstream && !nested && tryLoadSdk(); - - function sdkHandler(registryCommand, registryArgs, legacyArgs, cjsFallback) { - if (!sdkAvailable) return cjsFallback; - return () => { - let result; - try { - result = getExecuteForCjs()({ - registryCommand, - registryArgs, - legacyCommand: 'roadmap', - legacyArgs, - // #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. - mode: raw ? 'raw' : 'json', - projectDir: cwd, - }); - } catch { - // Bridge threw (e.g. synckit worker crash, Atomics failure on Windows). - // Fall through to CJS handler — the CJS path is the designed safety net. - return cjsFallback(); - } - if (!result.ok) { - error(result.errorDetails && result.errorDetails.message - ? result.errorDetails.message - : `roadmap ${registryCommand} failed (${result.errorKind})`); - return; - } - if (raw) { - output(null, true, typeof result.data === 'string' ? result.data : String(result.data ?? '')); - } else { - output(result.data); - } - }; + function sdkHandler(_registryCommand, _registryArgs, _legacyArgs, cjsFallback) { + return cjsFallback; } routeCjsCommandFamily({ diff --git a/get-shit-done/bin/lib/state-command-router.cjs b/get-shit-done/bin/lib/state-command-router.cjs index ddd3034ad..2648b56a1 100644 --- a/get-shit-done/bin/lib/state-command-router.cjs +++ b/get-shit-done/bin/lib/state-command-router.cjs @@ -2,138 +2,6 @@ const { STATE_SUBCOMMANDS } = require('./command-aliases.cjs'); const { routeCjsCommandFamily } = require('./cjs-command-router-adapter.cjs'); -const { output } = require('./core.cjs'); -const { - tryLoadSdk, - getExecuteForCjs, - getFormatStateLoadRawStdout, -} = require('./cjs-sdk-bridge.cjs'); - -// Subcommands whose CJS contract is exit-non-zero (stderr) ONLY when the -// underlying STATE.md is missing — not for in-state errors like -// "field not found". CJS `cmdStateGet` calls `error('STATE.md not found')` → -// exit 1 for the missing-file case but `output({ error: 'Section or field -// "X" not found' }, raw)` → exit 0 for the missing-field case. Mutation -// commands always use output() (exit 0) even when STATE.md is missing, so -// they are absent from this set entirely. -const EXIT_ON_STATE_MD_MISSING = new Set(['state.get']); -const STATE_MD_MISSING_MESSAGE = 'STATE.md not found'; - -// Subcommands whose CJS contract is always exit-0 — they emit -// { error: '...' } JSON via output() for every failure case (missing STATE.md, -// missing required args, validation failures). When the SDK returns -// result.ok === false for these subcommands we must NOT call error() (exit 1); -// instead we surface the SDK error message as exit-0 JSON so callers can -// JSON.parse the response and branch on the error field. -const OUTPUT_ON_SDK_ERROR = new Set([ - 'state.record-metric', - 'state.advance-plan', - 'state.record-session', - 'state.add-decision', - 'state.add-blocker', - 'state.resolve-blocker', - 'state.update-progress', -]); - -// The bridge loader verifies both `executeForCjs` and `formatStateLoadRawStdout` -// are present before returning success, so this router can call `tryLoadSdk()` -// directly without an additional capability check. - -/** - * 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; - - // When a CJS-side rawFormatter is supplied (e.g. state.load --raw → key=value - // lines), always request 'json' from the bridge so the SDK returns the typed - // data object. Passing mode: 'raw' would make the bridge pre-render to a - // string and the formatter would no-op. For subcommands without a rawFormatter, - // honor the user's --raw flag and let the bridge do default rendering. - const bridgeMode = rawFormatter ? 'json' : (raw ? 'raw' : 'json'); - - let result; - try { - result = getExecuteForCjs()({ - registryCommand, - registryArgs, - legacyCommand: 'state', - legacyArgs, - mode: bridgeMode, - projectDir: cwd, - // Phase 6 fix: workstream is now threaded through to the native handler. - // GSDTransport no longer forces subprocess for workstream-scoped requests — - // the worker's dispatchNative closure correctly passes workstream to - // registry.dispatch() (Phase 5.1 fix), enabling native workstream dispatch. - workstream: process.env.GSD_WORKSTREAM || undefined, - }); - } catch { - // Bridge threw (e.g. synckit worker crash, Atomics failure on Windows). - // Return false so the caller falls through to the CJS handler. - return false; - } - - if (!result.ok) { - // Mutation subcommands whose CJS contract is always exit-0: surface the SDK - // error as JSON output (exit 0) rather than calling error() (exit 1). This - // preserves the CJS contract for callers that JSON.parse stdout and branch on - // the error field — particularly important on Windows/Node 24 where the SDK - // bridge returns result.ok===false for validation failures (e.g. missing - // required args) instead of propagating them as result.data.error objects. - if (OUTPUT_ON_SDK_ERROR.has(registryCommand)) { - const msg = result.errorDetails && result.errorDetails.message - ? result.errorDetails.message - : `state ${registryCommand} failed (${result.errorKind})`; - output({ error: msg }); - return true; - } - error(result.errorDetails && result.errorDetails.message - ? result.errorDetails.message - : `state ${registryCommand} failed (${result.errorKind})`); - return true; // handled (error was reported) - } - - // Surface STATE.md-missing as a CJS-style fatal error (exit non-zero, - // stderr) for the specific subcommands whose CJS contract uses error() not - // output() for that case. The exact "STATE.md not found" message is the - // canonical signal both CJS and SDK use — other "error" shapes (e.g. - // "Section or field X not found" from state.get with present STATE.md) - // stay as exit-0 JSON output so shell-script consumers JSON.parse the - // output and branch on the error field without process-exit handling. - if ( - EXIT_ON_STATE_MD_MISSING.has(registryCommand) - && result.data - && typeof result.data === 'object' - && result.data.error === STATE_MD_MISSING_MESSAGE - ) { - error(result.data.error); - return true; - } - - if (raw && rawFormatter) { - const rawText = rawFormatter(result.data); - const fs = require('fs'); - fs.writeSync(1, rawText); - } else if (raw) { - // #3631: bridge was called with mode:'raw', so result.data is the scalar - // string the CJS path would have printed. Bypass output()'s JSON path. - output(null, true, typeof result.data === 'string' ? result.data : String(result.data ?? '')); - } else { - output(result.data); - } - return true; -} /** * Manifest-backed state subcommand router. @@ -156,22 +24,8 @@ function routeStateCommand({ state, args, cwd, raw, parseNamedArgs, error }) { return parsedPlans; }; - // Phase 6 fix: workstream commands are now handled natively in the sync bridge - // worker. GSDTransport no longer forces subprocess for workstream-scoped requests; - // the worker threads workstream through to registry.dispatch() correctly. - const sdkAvailable = 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(); - }; + function sdkHandler(_registryCommand, _registryArgs, _legacyArgs, _rawFormatter, cjsFallback) { + return cjsFallback; } routeCjsCommandFamily({ @@ -188,11 +42,7 @@ function routeStateCommand({ state, args, cwd, raw, parseNamedArgs, error }) { 'state.load', [], args.slice(1), - // Resolved lazily — the formatter getter returns null until - // tryLoadSdk() runs inside dispatchViaSdk. sdkHandler only invokes - // this formatter when SDK dispatch succeeds, so by then the bridge - // has cached the formatter and the getter returns the real function. - (...formatterArgs) => getFormatStateLoadRawStdout()(...formatterArgs), + null, () => state.cmdStateLoad(cwd, raw), ), json: sdkHandler( diff --git a/get-shit-done/bin/lib/validate-command-router.cjs b/get-shit-done/bin/lib/validate-command-router.cjs index dc8d1e309..1d93a9605 100644 --- a/get-shit-done/bin/lib/validate-command-router.cjs +++ b/get-shit-done/bin/lib/validate-command-router.cjs @@ -3,10 +3,6 @@ const { VALIDATE_SUBCOMMANDS } = require('./command-aliases.cjs'); const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.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'); /** * Manifest-backed validate subcommand router. @@ -25,44 +21,8 @@ const { tryLoadSdk, getExecuteForCjs } = require('./cjs-sdk-bridge.cjs'); * SDK-only (unsupported in CJS router): none. */ function routeValidateCommand({ verify, args, cwd, raw, parseNamedArgs, output: outputFn, error }) { - const activeWorkstream = process.env.GSD_WORKSTREAM; - const sdkAvailable = !activeWorkstream && tryLoadSdk(); - - function sdkHandler(registryCommand, registryArgs, legacyArgs, cjsFallback) { - if (!sdkAvailable) return cjsFallback; - return () => { - let result; - try { - result = getExecuteForCjs()({ - registryCommand, - registryArgs, - legacyCommand: 'validate', - legacyArgs, - // #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. - mode: raw ? 'raw' : 'json', - projectDir: cwd, - }); - } catch { - // Bridge threw (e.g. synckit worker crash, Atomics failure on Windows). - // Fall through to CJS handler — the CJS path is the designed safety net. - return cjsFallback(); - } - if (!result.ok) { - error(result.errorDetails && result.errorDetails.message - ? result.errorDetails.message - : `validate ${registryCommand} failed (${result.errorKind})`); - return; - } - if (raw) { - output(null, true, typeof result.data === 'string' ? result.data : String(result.data ?? '')); - } else { - output(result.data); - } - }; + function sdkHandler(_registryCommand, _registryArgs, _legacyArgs, cjsFallback) { + return cjsFallback; } routeCjsCommandFamily({ diff --git a/get-shit-done/bin/lib/verify-command-router.cjs b/get-shit-done/bin/lib/verify-command-router.cjs index 918955bc5..adc398760 100644 --- a/get-shit-done/bin/lib/verify-command-router.cjs +++ b/get-shit-done/bin/lib/verify-command-router.cjs @@ -2,10 +2,6 @@ const { VERIFY_SUBCOMMANDS } = require('./command-aliases.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'); /** * Manifest-backed verify subcommand router. @@ -20,44 +16,8 @@ const { tryLoadSdk, getExecuteForCjs } = require('./cjs-sdk-bridge.cjs'); * SDK-only (unsupported in CJS router): none. */ function routeVerifyCommand({ verify, 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 () => { - let result; - try { - result = getExecuteForCjs()({ - registryCommand, - registryArgs, - legacyCommand: 'verify', - legacyArgs, - // #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. - mode: raw ? 'raw' : 'json', - projectDir: cwd, - }); - } catch { - // Bridge threw (e.g. synckit worker crash, Atomics failure on Windows). - // Fall through to CJS handler — the CJS path is the designed safety net. - return cjsFallback(); - } - if (!result.ok) { - error(result.errorDetails && result.errorDetails.message - ? result.errorDetails.message - : `verify ${registryCommand} failed (${result.errorKind})`); - return; - } - if (raw) { - output(null, true, typeof result.data === 'string' ? result.data : String(result.data ?? '')); - } else { - output(result.data); - } - }; + function sdkHandler(_registryCommand, _registryArgs, _legacyArgs, cjsFallback) { + return cjsFallback; } routeCjsCommandFamily({ diff --git a/sdk/package-lock.json b/sdk/package-lock.json index eb06cc245..aa3c4cb07 100644 --- a/sdk/package-lock.json +++ b/sdk/package-lock.json @@ -10,7 +10,6 @@ "license": "MIT", "dependencies": { "@anthropic-ai/claude-agent-sdk": "^0.2.84", - "synckit": "^0.11.12", "ws": "8.20.1" }, "bin": { @@ -803,18 +802,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@pkgr/core": { - "version": "0.2.9", - "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.2.9.tgz", - "integrity": "sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA==", - "license": "MIT", - "engines": { - "node": "^12.20.0 || ^14.18.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/pkgr" - } - }, "node_modules/@rollup/rollup-android-arm-eabi": { "version": "4.60.0", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.0.tgz", @@ -1707,21 +1694,6 @@ "url": "https://github.com/sponsors/antfu" } }, - "node_modules/synckit": { - "version": "0.11.12", - "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.12.tgz", - "integrity": "sha512-Bh7QjT8/SuKUIfObSXNHNSK6WHo6J1tHCqJsuaFDP7gP0fkzSfTxI8y85JrppZ0h8l0maIgc2tfuZQ6/t3GtnQ==", - "license": "MIT", - "dependencies": { - "@pkgr/core": "^0.2.9" - }, - "engines": { - "node": "^14.18.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/synckit" - } - }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", diff --git a/sdk/package.json b/sdk/package.json index 6fc62fa19..b1bee07a6 100644 --- a/sdk/package.json +++ b/sdk/package.json @@ -45,7 +45,6 @@ }, "dependencies": { "@anthropic-ai/claude-agent-sdk": "^0.2.84", - "synckit": "^0.11.12", "ws": "8.20.1" }, "devDependencies": { diff --git a/sdk/src/runtime-bridge-sync/index.test.ts b/sdk/src/runtime-bridge-sync/index.test.ts deleted file mode 100644 index 4c297a429..000000000 --- a/sdk/src/runtime-bridge-sync/index.test.ts +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Pinning tests for the executeForCjs synchronous primitive. - * - * Covers: - * - Success path: known read-only command returns { ok: true, data, exitCode: 0 } - * - unknown_command: unknown command key returns { ok: false, errorKind: 'unknown_command' } - * - native_failure: handler that throws a generic Error returns { ok: false, errorKind: 'native_failure' } - * - internal_error mapping tracked as a TODO until a deterministic TypeError fixture exists - * - Idempotency: calling twice with identical input produces identical output - * - Sync nature: returned value is not a Promise - */ - -import { describe, it, expect, beforeAll } from 'vitest'; -import type { RuntimeBridgeSyncResult } from './index.js'; - -// We import after build — the test runner loads the TS via tsx/vitest, -// but executeForCjs creates a Worker which loads the compiled worker.js. -// So we must build before running these tests. In CI, build runs first. -// In local dev, run `npm run build` before vitest. - -let executeForCjs: (input: import('./index.js').ExecuteForCjsInput) => RuntimeBridgeSyncResult; - -beforeAll(async () => { - // Dynamic import so we get an actionable error if the module is missing - // (RED phase: will fail here with "Cannot find module") - const mod = await import('./index.js'); - executeForCjs = mod.executeForCjs; -}); - -describe('executeForCjs - sync primitive', () => { - it('returns a non-Promise object synchronously', () => { - const result = executeForCjs({ - registryCommand: 'generate-slug', - registryArgs: ['My Phase'], - legacyCommand: 'generate-slug', - legacyArgs: ['My Phase'], - mode: 'json', - projectDir: '/tmp', - }); - - // Must NOT be a Promise - expect(result).not.toBeInstanceOf(Promise); - expect(typeof result).toBe('object'); - // .ok must be accessible synchronously - expect('ok' in result).toBe(true); - }); - - it('success: generate-slug returns ok:true with data and exitCode:0', () => { - const result = executeForCjs({ - registryCommand: 'generate-slug', - registryArgs: ['My Phase'], - legacyCommand: 'generate-slug', - legacyArgs: ['My Phase'], - mode: 'json', - projectDir: '/tmp', - }); - - expect(result.ok).toBe(true); - if (!result.ok) throw new Error('Expected ok:true'); - expect(result.exitCode).toBe(0); - expect(result.data).toBeDefined(); - // generate-slug returns { slug: 'my-phase' } - expect((result.data as Record).slug).toBe('my-phase'); - }); - - it('unknown_command: returns ok:false with errorKind unknown_command', () => { - const result = executeForCjs({ - registryCommand: '__nonexistent_command_xyz__', - registryArgs: [], - legacyCommand: '__nonexistent_command_xyz__', - legacyArgs: [], - mode: 'json', - projectDir: '/tmp', - }); - - expect(result.ok).toBe(false); - if (result.ok) throw new Error('Expected ok:false'); - expect(result.errorKind).toBe('unknown_command'); - expect(result.exitCode).not.toBe(0); - }); - - it('native_failure: handler execution failure is classified as native_failure', () => { - // generate-slug with no args throws a GSDError (validation) — that maps to validation_error. - // We need a command that throws a plain Error (GSDToolsError classification.kind='failure'). - // - // Phase 5.1 fix note: the Phase 5.0 fixture used projectDir='/tmp' with an absolute - // path arg that started with /tmp — after the worker fix threads projectDir correctly, - // frontmatter.get returns a soft ok:true error instead of throwing (path escape check - // passes, then realpath on the nonexistent path returns ok:true with error field). - // Updated fixture: use a completely nonexistent projectDir so resolvePathUnderProject - // calls realpath('/nonexistent...') and throws ENOENT, which is classified as native_failure. - const result = executeForCjs({ - registryCommand: 'frontmatter.get', - registryArgs: ['file.md'], - legacyCommand: 'frontmatter get', - legacyArgs: ['file.md'], - mode: 'json', - projectDir: '/nonexistent-absolutely-does-not-exist-project-dir', - }); - - expect(result.ok).toBe(false); - if (result.ok) throw new Error('Expected ok:false'); - expect(result.errorKind).toBe('native_failure'); - expect(result.exitCode).not.toBe(0); - }); - - it.todo('internal_error: requires fixture command that throws TypeError'); - - it('unknown_command: unregistered command is classified as unknown_command', () => { - const result = executeForCjs({ - registryCommand: '__nonexistent_xyz__', - registryArgs: [], - legacyCommand: '__nonexistent_xyz__', - legacyArgs: [], - mode: 'json', - projectDir: '/tmp', - }); - - expect(result.ok).toBe(false); - if (result.ok) throw new Error('Expected ok:false'); - expect(result.errorKind).toBe('unknown_command'); - }); - - it('idempotency: calling twice with identical input returns identical output', () => { - const input = { - registryCommand: 'generate-slug', - registryArgs: ['Idempotency Test'], - legacyCommand: 'generate-slug', - legacyArgs: ['Idempotency Test'], - mode: 'json' as const, - projectDir: '/tmp', - }; - - const result1 = executeForCjs(input); - const result2 = executeForCjs(input); - - expect(result1.ok).toBe(result2.ok); - expect(result1.exitCode).toBe(result2.exitCode); - if (result1.ok && result2.ok) { - expect(JSON.stringify(result1.data)).toBe(JSON.stringify(result2.data)); - } - }); - - it('idempotency: unknown command returns same errorKind on repeat calls', () => { - const input = { - registryCommand: '__idempotency_test_unknown__', - registryArgs: [], - legacyCommand: '__idempotency_test_unknown__', - legacyArgs: [], - mode: 'json' as const, - projectDir: '/tmp', - }; - - const result1 = executeForCjs(input); - const result2 = executeForCjs(input); - - expect(result1.ok).toBe(false); - expect(result2.ok).toBe(false); - if (!result1.ok && !result2.ok) { - expect(result1.errorKind).toBe(result2.errorKind); - expect(result1.exitCode).toBe(result2.exitCode); - } - }); -}); diff --git a/sdk/src/runtime-bridge-sync/index.ts b/sdk/src/runtime-bridge-sync/index.ts deleted file mode 100644 index 774b512d4..000000000 --- a/sdk/src/runtime-bridge-sync/index.ts +++ /dev/null @@ -1,154 +0,0 @@ -/** - * executeForCjs — synchronous SDK runtime bridge primitive. - * - * Provides a synchronous `executeForCjs()` function that CJS callers can use - * to invoke any registered SDK command without dealing with async/await or - * top-level-await restrictions that prevent CJS from using the async bridge. - * - * ## Mechanism - * - * Uses `synckit` (Atomics.wait + SharedArrayBuffer + worker_threads) to run - * the async `QueryRuntimeBridge.execute()` in a worker thread and block the - * calling thread until the result is available. The worker is spawned lazily - * on first call and reused for all subsequent calls. - * - * ## Worker overhead - * - * - First call (worker startup + native bridge construction): ~80 ms. - * - Subsequent calls (steady state): ~0.1 ms per call (excluding handler work). - * - * ## CRITICAL: Do NOT call from an async context - * - * `executeForCjs` uses `Atomics.wait` under the hood, which **blocks the - * calling thread**. Calling it from inside an async function that is itself - * running on the Node.js main thread event loop will **deadlock** because - * the event loop cannot process the worker's response message while blocked. - * - * Safe callers: - * - CJS modules evaluated at require-time (synchronous module initialisation). - * - Worker threads that are not using the event loop. - * - * Unsafe callers: - * - Any `async function` on the main thread. - * - Anything inside a `Promise` callback on the main thread. - * - * ## CJS consumption - * - * ```js - * const { executeForCjs } = require('@opengsd/gsd-sdk/dist/runtime-bridge-sync/index.js'); - * const result = executeForCjs({ registryCommand: 'generate-slug', registryArgs: ['My Phase'], ... }); - * if (result.ok) console.log(result.data); // { slug: 'my-phase' } - * ``` - * - * @module runtime-bridge-sync - */ - -import { createSyncFn } from 'synckit'; -import { fileURLToPath } from 'node:url'; -import { dirname, join } from 'node:path'; -import type { RuntimeBridgeExecuteInput } from '../query-runtime-bridge.js'; - -// Re-export the input type so callers can import it alongside executeForCjs -export type { RuntimeBridgeExecuteInput }; - -// Convenience alias for callers who prefer a shorter name -export type ExecuteForCjsInput = RuntimeBridgeExecuteInput; - -// ─── Result type ───────────────────────────────────────────────────────────── - -/** - * The 6 canonical error kinds from ADR-0001 Dispatch Policy Module. - */ -export type SyncErrorKind = - | 'unknown_command' - | 'native_failure' - | 'native_timeout' - | 'fallback_failure' - | 'validation_error' - | 'internal_error'; - -/** - * Discriminated union returned by `executeForCjs`. - * - * - `ok: true` — command executed successfully. `data` is the handler's return value. - * - `ok: false` — command failed. `errorKind` identifies the failure category. - */ -export type RuntimeBridgeSyncResult = - | { ok: true; data: unknown; exitCode: 0 } - | { - ok: false; - exitCode: number; - errorKind: SyncErrorKind; - errorDetails?: unknown; - stderrLines: string[]; - }; - -// ─── Lazy sync-fn factory ────────────────────────────────────────────────── - -// Resolve worker path to the compiled dist artifact. -// -// The worker MUST be the compiled JS file (dist/runtime-bridge-sync/worker.js), -// NOT the TypeScript source. This is because: -// 1. synckit spawns the worker via Node.js directly (no tsx transform). -// 2. When vitest runs tests from the TS source tree, import.meta.url points to -// src/, not dist/. We must redirect to dist/ in all cases. -// -// Strategy: navigate from the current file's directory to the package root, -// then resolve to dist/runtime-bridge-sync/worker.js. -// The current file lives either in: -// src/runtime-bridge-sync/ (vitest TS source context) -// dist/runtime-bridge-sync/ (compiled CJS/ESM consumer context) -// In both cases, two levels up is the package root (sdk/). -const _moduleUrl = import.meta.url; - -function resolveWorkerPath(): string { - const currentDir = dirname(fileURLToPath(_moduleUrl)); - // currentDir is either src/runtime-bridge-sync or dist/runtime-bridge-sync. - // Two levels up is the sdk/ package root. - const pkgRoot = join(currentDir, '..', '..'); - return join(pkgRoot, 'dist', 'runtime-bridge-sync', 'worker.js'); -} - -let _syncFn: ((input: RuntimeBridgeExecuteInput) => RuntimeBridgeSyncResult) | null = null; - -function getSyncFn(): (input: RuntimeBridgeExecuteInput) => RuntimeBridgeSyncResult { - if (_syncFn) return _syncFn; - const workerPath = resolveWorkerPath(); - _syncFn = createSyncFn<(input: RuntimeBridgeExecuteInput) => Promise>( - workerPath, - { timeout: 60_000 }, - ); - return _syncFn; -} - -// ─── Public API ─────────────────────────────────────────────────────────────── - -/** - * Execute a registered SDK command synchronously. - * - * This function blocks the calling thread until the command completes. - * It must NOT be called from an async context on the main event-loop thread - * (see module-level JSDoc for details). - * - * @param input - The command input, matching RuntimeBridgeExecuteInput. - * @returns A RuntimeBridgeSyncResult — either ok:true with data, or ok:false with errorKind. - * - * @example - * ```js - * const { executeForCjs } = require('@opengsd/gsd-sdk/dist/runtime-bridge-sync/index.js'); - * const result = executeForCjs({ - * registryCommand: 'generate-slug', - * registryArgs: ['My Phase'], - * legacyCommand: 'generate-slug', - * legacyArgs: ['My Phase'], - * mode: 'json', - * projectDir: '/path/to/project', - * }); - * if (result.ok) { - * console.log(result.data.slug); // 'my-phase' - * } - * ``` - */ -export function executeForCjs(input: RuntimeBridgeExecuteInput): RuntimeBridgeSyncResult { - return getSyncFn()(input); -} diff --git a/sdk/src/runtime-bridge-sync/projectdir-regression.test.ts b/sdk/src/runtime-bridge-sync/projectdir-regression.test.ts deleted file mode 100644 index e8c68432a..000000000 --- a/sdk/src/runtime-bridge-sync/projectdir-regression.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -/** - * Regression test for the Phase 5.0 worker bug: projectDir and workstream were - * dropped from RuntimeBridgeExecuteInput before being forwarded to - * registry.dispatch(). The worker constructed a module-scoped - * QueryNativeDirectAdapter with a hardcoded projectDir='' — meaning any handler - * that reads .planning/ (e.g. state.*) would either fail silently or read from - * the process CWD rather than the requested project directory. - * - * Fix (Phase 5.1): the adapter is now constructed per-request inside - * dispatchNative so request.projectDir and request.workstream close over the - * correct values. - * - * These tests must: - * - FAIL against the unfixed worker (projectDir='', handler sees wrong dir). - * - PASS against the fixed worker (projectDir threaded correctly). - * - * NOTE: executeForCjs uses a compiled dist/ worker (see index.ts comments). - * The tests here call executeForCjs, which requires the worker to be rebuilt - * before the fix is observable. Run `npm run build` in sdk/ first. - */ - -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { mkdir, writeFile, rm } from 'node:fs/promises'; -import { join } from 'node:path'; -import { tmpdir } from 'node:os'; -import { executeForCjs } from './index.js'; - -// ─── Fixture STATE.md with parseable frontmatter ────────────────────────── - -const FIXTURE_STATE = `--- -gsd_state_version: 1.0 -milestone: v9.1 -milestone_name: Regression Test Milestone -status: executing ---- - -# Project State - -## Current Position - -Phase: 9 (Regression Tests) — EXECUTING -Plan: 1 of 2 -Status: Executing Phase 9 -Last activity: 2026-05-15 -- Regression test started - -Progress: [█████░░░░░] 50% -`; - -// ─── Helpers ─────────────────────────────────────────────────────────────── - -let tmpDir: string; - -beforeAll(async () => { - tmpDir = join( - tmpdir(), - `gsd-projectdir-regression-${Date.now()}-${Math.random().toString(36).slice(2)}`, - ); - await mkdir(join(tmpDir, '.planning'), { recursive: true }); - await writeFile(join(tmpDir, '.planning', 'STATE.md'), FIXTURE_STATE, 'utf-8'); -}); - -afterAll(async () => { - await rm(tmpDir, { recursive: true, force: true }); -}); - -// ─── Tests ───────────────────────────────────────────────────────────────── - -describe('executeForCjs projectDir regression (Phase 5.0 bug)', () => { - it('threads projectDir to the handler: state.json returns frontmatter data from the tmpdir fixture', () => { - // This test FAILS against the unfixed worker because projectDir='' causes - // the handler to look for .planning/STATE.md relative to '' (process CWD), - // which does not have a STATE.md fixture. The handler returns { error: 'STATE.md not found' }. - // - // With the fix, projectDir=tmpDir is forwarded and the handler reads the fixture. - const result = executeForCjs({ - registryCommand: 'state.json', - registryArgs: [], - legacyCommand: 'state', - legacyArgs: ['json'], - mode: 'json', - projectDir: tmpDir, - }); - - expect(result.ok).toBe(true); - if (!result.ok) return; // narrow for TS - - const data = result.data as Record; - - // The handler should have found the fixture and returned parsed frontmatter. - // Key assertions: these fields come from FIXTURE_STATE and are absent from - // any STATE.md that might exist at ''. - expect(data).not.toHaveProperty('error'); - expect(data.milestone).toBe('v9.1'); - expect(data.milestone_name).toBe('Regression Test Milestone'); - expect(data.status).toBe('executing'); - }); - - it('negative: nonexistent projectDir returns ok:true with {error} (handler-level not-found)', () => { - // A completely nonexistent directory: handler cannot find .planning/STATE.md - // and returns a structured error payload rather than throwing. This is the - // expected "soft failure" shape for state.json on a missing project. - const result = executeForCjs({ - registryCommand: 'state.json', - registryArgs: [], - legacyCommand: 'state', - legacyArgs: ['json'], - mode: 'json', - projectDir: '/nonexistent-gsd-project-regression-test-dir', - }); - - // The handler returns { data: { error: 'STATE.md not found' } } — ok:true - // because it is a domain-level not-found, not a dispatch error. - expect(result.ok).toBe(true); - if (!result.ok) return; - - const data = result.data as Record; - expect(data).toHaveProperty('error'); - expect(String(data.error)).toMatch(/STATE\.md not found/i); - }); - - it('workstream support: GSDTransport routes workstream requests natively (Phase 6 fix)', () => { - // Phase 6 fix: GSDTransport no longer forces subprocess for workstream-scoped - // requests. The worker's dispatchNative closure (Phase 5.1 fix) correctly - // threads request.workstream through to registry.dispatch(), so native handlers - // route to the workstream-scoped .planning/workstreams// directory. - // - // The workstream 'some-workstream' has no separate STATE.md in tmpDir/ - // .planning/workstreams/some-workstream/, so the handler returns a domain-level - // "not found" error (ok:true with {error:...}) — exactly like the nonexistent - // projectDir case. This confirms native dispatch was used (subprocess would - // have returned ok:false / errorKind). - const result = executeForCjs({ - registryCommand: 'state.json', - registryArgs: [], - legacyCommand: 'state', - legacyArgs: ['json'], - mode: 'json', - projectDir: tmpDir, - workstream: 'some-workstream', - }); - - // Native dispatch used → ok:true (handler-level not-found, not a dispatch error). - expect(result.ok).toBe(true); - if (!result.ok) return; - const data = result.data as Record; - // Domain-level not-found: workstream's STATE.md doesn't exist in the fixture. - expect(data).toHaveProperty('error'); - expect(String(data.error)).toMatch(/STATE\.md not found/i); - }); -}); diff --git a/sdk/src/runtime-bridge-sync/worker.ts b/sdk/src/runtime-bridge-sync/worker.ts deleted file mode 100644 index c8d26f0fe..000000000 --- a/sdk/src/runtime-bridge-sync/worker.ts +++ /dev/null @@ -1,224 +0,0 @@ -/** - * Synckit worker for executeForCjs. - * - * Loaded by synckit's worker pool. Constructs a native-only QueryRuntimeBridge - * lazily (once per worker lifetime) and handles async execution, projecting - * results into the RuntimeBridgeSyncResult discriminated union. - * - * The bridge is configured with: - * - allowFallbackToSubprocess: false — keeps the worker self-contained with no - * child-process spawning. Unknown commands surface as 'unknown_command' errors. - * - strictSdk: false — lets the transport surface 'unknown_command' rather than - * throwing before dispatch. - */ -import { runAsWorker } from 'synckit'; -import { createRegistry } from '../query/index.js'; -import { GSDTransport } from '../gsd-transport.js'; -import { QueryExecutionPolicy } from '../query-execution-policy.js'; -import { QueryNativeDirectAdapter } from '../query-native-direct-adapter.js'; -import { QueryNativeHotpathAdapter } from '../query-native-hotpath-adapter.js'; -import { QueryRuntimeBridge } from '../query-runtime-bridge.js'; -import { GSDToolsError } from '../gsd-tools-error.js'; -import { GSDError, ErrorClassification } from '../errors.js'; -import { createQueryNativeErrorFactory } from '../query-tools-error-factory.js'; -import { formatQueryRawOutput } from '../query-raw-output-projection.js'; -import type { RuntimeBridgeExecuteInput } from '../query-runtime-bridge.js'; -import type { RuntimeBridgeSyncResult, SyncErrorKind } from './index.js'; - -// ─── Lazy bridge singleton ────────────────────────────────────────────────── - -let bridgeInstance: QueryRuntimeBridge | null = null; - -function getBridge(): QueryRuntimeBridge { - if (bridgeInstance) return bridgeInstance; - - const registry = createRegistry(); - - const NATIVE_TIMEOUT_MS = 30_000; // 30 s ceiling for any single handler - const nativeErrorFactory = createQueryNativeErrorFactory(NATIVE_TIMEOUT_MS); - - // Build a per-request adapter inside dispatchNative so that projectDir and - // workstream from the request close over the correct values. The Phase 5.0 - // bug was a module-scoped adapter that hardcoded projectDir = '' — any - // handler reading .planning/ (e.g. state.*) received an empty path and - // silently failed or read from the process CWD. Constructing per-request - // adds microseconds; correctness wins. (fix for latent bug, Phase 5.1) - const transport = new GSDTransport(registry, { - dispatchNative: (request) => { - const adapter = new QueryNativeDirectAdapter({ - timeoutMs: NATIVE_TIMEOUT_MS, - dispatch: (registryCommand, registryArgs) => - registry.dispatch(registryCommand, registryArgs, request.projectDir, request.workstream), - ...nativeErrorFactory, - }); - return adapter.dispatchResult( - request.legacyCommand, - request.legacyArgs, - request.registryCommand, - request.registryArgs, - ); - }, - // #3631: forward raw-mode projection so mode:'raw' returns the per-command - // scalar string (next-decimal token, get-phase section, etc.) instead of - // falling back to generic JSON-stringify. Without this, family-router - // sdkHandlers requesting mode:'raw' under --raw receive a stringified - // JSON IR — the regression #3577 introduced for every family router. - formatNativeRaw: (registryCommand, data) => formatQueryRawOutput(registryCommand, data), - // Subprocess fallback stubs — never called because allowFallbackToSubprocess=false - execSubprocessJson: () => - Promise.reject(new Error('Subprocess fallback disabled in sync bridge worker')), - execSubprocessRaw: () => - Promise.reject(new Error('Subprocess fallback disabled in sync bridge worker')), - }); - - const executionPolicy = new QueryExecutionPolicy(transport); - - // Hotpath adapter: construct a stub that satisfies the QueryRuntimeBridge - // constructor. executeForCjs does not invoke dispatchHotpath so this - // adapter is never actually called. We still need a valid instance because - // QueryRuntimeBridge requires one at construction time. - const stubDirectAdapter = new QueryNativeDirectAdapter({ - timeoutMs: NATIVE_TIMEOUT_MS, - dispatch: () => Promise.reject(new Error('stub: hotpath direct adapter not used')), - ...nativeErrorFactory, - }); - const hotpathAdapter = new QueryNativeHotpathAdapter( - () => true, - stubDirectAdapter, - () => Promise.reject(new Error('hotpath json fallback disabled')), - () => Promise.reject(new Error('hotpath raw fallback disabled')), - ); - - bridgeInstance = new QueryRuntimeBridge( - registry, - executionPolicy, - hotpathAdapter, - () => true, // always prefer native - { - allowFallbackToSubprocess: false, - strictSdk: false, - }, - ); - - return bridgeInstance; -} - -// ─── Error classification ─────────────────────────────────────────────────── - -/** - * Map a caught error into the 6-kind ADR-0001 error taxonomy. - * - * GSDToolsError.classification.kind: 'timeout' | 'failure' - * GSDError.classification: ErrorClassification enum - * - * Mapping: - * - 'Subprocess fallback disabled' message → unknown_command (no native adapter for command) - * - GSDToolsError timeout kind → native_timeout - * - GSDError Validation → validation_error - * - GSDError Blocked → validation_error (semantic: prerequisite missing) - * - TypeError (programming error) → internal_error - * - GSDToolsError failure + TypeError cause → internal_error - * - GSDToolsError failure → native_failure - * - Unknown Error → internal_error - */ -function readReason(error: unknown): string | undefined { - // Handlers can pin a CJS-style ERROR_REASON snake_case code on the GSDError - // they throw (e.g. configGet → 'config_key_not_found'). The worker - // propagates it through errorDetails so the CJS dispatcher can call - // `error(msg, reason)` and `--json-errors` clients see a typed reason - // rather than the generic 'unknown'. (Bugs #2943, #3086.) - if (error && typeof error === 'object' && 'reason' in error) { - const r = (error as { reason?: unknown }).reason; - if (typeof r === 'string' && r.length > 0) return r; - } - return undefined; -} - -function classifyError(error: unknown): { kind: SyncErrorKind; exitCode: number; message: string; reason?: string } { - if (error instanceof GSDToolsError) { - const { classification, exitCode, message } = error; - - // Unknown command: transport throws 'Subprocess fallback disabled: command ... cannot run without native dispatch' - if ( - classification.kind === 'failure' && - message.includes('Subprocess fallback disabled:') && - message.includes('cannot run without native dispatch') - ) { - return { kind: 'unknown_command', exitCode: exitCode ?? 1, message }; - } - - if (classification.kind === 'timeout') { - return { kind: 'native_timeout', exitCode: exitCode ?? 1, message }; - } - - // Unwrap the cause once. The native direct adapter wraps every non- - // GSDToolsError thrown by a handler in a GSDToolsError via - // `createNativeFailureError`, preserving the original via `cause`. - // Classification of validation / blocked errors therefore has to walk - // through to the cause — otherwise every GSDError validation surfaces - // as `native_failure` and callers cannot distinguish "you gave me bad - // input" from "the SDK crashed." (Phase 6 / #3592 contract bug.) - const cause = (error as NodeJS.ErrnoException & { cause?: unknown }).cause; - if (cause instanceof GSDError) { - const reason = readReason(cause); - if ( - cause.classification === ErrorClassification.Validation || - cause.classification === ErrorClassification.Blocked - ) { - return { kind: 'validation_error', exitCode: 10, message: cause.message, reason }; - } - // Execution-classified GSDError is a 'handler said no' result — - // exitCode 1, internal_error kind for taxonomy purposes, but pass - // the structured reason through so the CJS dispatcher can render - // the proper `--json-errors` shape. - return { kind: 'internal_error', exitCode: 1, message: cause.message, reason }; - } - if (cause instanceof TypeError) { - return { kind: 'internal_error', exitCode: exitCode ?? 1, message }; - } - - return { kind: 'native_failure', exitCode: exitCode ?? 1, message }; - } - - if (error instanceof GSDError) { - const { classification, message } = error; - const reason = readReason(error); - if ( - classification === ErrorClassification.Validation || - classification === ErrorClassification.Blocked - ) { - return { kind: 'validation_error', exitCode: 10, message, reason }; - } - return { kind: 'internal_error', exitCode: 1, message, reason }; - } - - if (error instanceof TypeError) { - const message = error.message; - return { kind: 'internal_error', exitCode: 1, message }; - } - - const message = error instanceof Error ? error.message : String(error); - return { kind: 'internal_error', exitCode: 1, message }; -} - -// ─── Worker entry point ───────────────────────────────────────────────────── - -runAsWorker(async (input: RuntimeBridgeExecuteInput): Promise => { - const bridge = getBridge(); - - try { - const data = await bridge.execute(input); - return { ok: true, data, exitCode: 0 }; - } catch (error: unknown) { - const { kind, exitCode, message, reason } = classifyError(error); - const errorDetails: { message: string; reason?: string } = { message }; - if (reason) errorDetails.reason = reason; - return { - ok: false, - exitCode, - errorKind: kind, - errorDetails, - stderrLines: [], - }; - } -}); diff --git a/tests/bug-190-bridge-collapse.test.cjs b/tests/bug-190-bridge-collapse.test.cjs new file mode 100644 index 000000000..97ff6cd11 --- /dev/null +++ b/tests/bug-190-bridge-collapse.test.cjs @@ -0,0 +1,45 @@ +'use strict'; + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const ROOT = path.join(__dirname, '..'); + +function read(rel) { + return fs.readFileSync(path.join(ROOT, rel), 'utf8'); +} + +test('bridge collapse removes cjs-sdk-bridge and runtime-bridge-sync seam', () => { + const bridgePath = path.join(ROOT, 'get-shit-done', 'bin', 'lib', 'cjs-sdk-bridge.cjs'); + const runtimeSyncDir = path.join(ROOT, 'sdk', 'src', 'runtime-bridge-sync'); + + assert.equal(fs.existsSync(bridgePath), false, 'cjs-sdk-bridge.cjs must be removed'); + assert.equal(fs.existsSync(runtimeSyncDir), false, 'sdk/src/runtime-bridge-sync must be removed'); + + const routers = [ + 'get-shit-done/bin/lib/init-command-router.cjs', + 'get-shit-done/bin/lib/roadmap-command-router.cjs', + 'get-shit-done/bin/lib/state-command-router.cjs', + 'get-shit-done/bin/lib/validate-command-router.cjs', + 'get-shit-done/bin/lib/verify-command-router.cjs', + 'get-shit-done/bin/lib/phases-command-router.cjs', + ]; + + for (const rel of routers) { + const src = read(rel); + assert.equal( + src.includes('cjs-sdk-bridge.cjs'), + false, + `${rel} must not import cjs-sdk-bridge.cjs`, + ); + } + + const sdkPkg = JSON.parse(read('sdk/package.json')); + assert.equal( + Object.prototype.hasOwnProperty.call(sdkPkg.dependencies || {}, 'synckit'), + false, + 'sdk/package.json must not include synckit', + ); +}); diff --git a/tests/cjs-sdk-bridge-integration.test.cjs b/tests/cjs-sdk-bridge-integration.test.cjs deleted file mode 100644 index 799eb7ce6..000000000 --- a/tests/cjs-sdk-bridge-integration.test.cjs +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; - -/** - * Integration test for `get-shit-done/bin/lib/cjs-sdk-bridge.cjs` — locks the - * load-success invariant that Phase 5/6 silently violated before this PR. - * - * Original bug: the bridge used `require('@opengsd/gsd-sdk')` to load the - * runtime-bridge module. That package name is not resolvable from the root - * `node_modules` (the SDK lives at `./sdk/` as a sibling, not a dependency), - * and even if it were, the public entry didn't expose `executeForCjs` or - * `formatStateLoadRawStdout`. `tryLoadSdk()` always returned false, - * `_loadFailed` was cached for the process lifetime, and every CJS router - * silently fell through to the CJS fallback path — making the entire - * CJS→SDK delegation in Phase 5/6 dead code. CI passed because the fallback - * still executed CJS handlers, masking the regression. - * - * This test proves: - * 1. `tryLoadSdk()` returns true on the current checkout. - * 2. `getExecuteForCjs()` returns a real function (not null). - * 3. `getFormatStateLoadRawStdout()` returns a real function (not null). - * 4. Calling `executeForCjs` with a real canonical registry command - * produces a successful SDK result — proving the bridge actually - * dispatches through the runtime bridge rather than failing/falling back. - * - * Requires `sdk/dist/` to exist (i.e. `npm run build:sdk` has run). The - * project's `pretest` hook runs `build:sdk` before tests, so this is met by - * default. If `dist/` is missing, the assertion failures in this file - * surface the cause directly rather than silently masking under fallback. - */ - -const { test, describe, afterEach } = require('node:test'); -const assert = require('node:assert/strict'); -const path = require('node:path'); - -const BRIDGE_PATH = path.join(__dirname, '..', 'get-shit-done', 'bin', 'lib', 'cjs-sdk-bridge.cjs'); -const initialExitCode = process.exitCode; - -afterEach(() => { - process.exitCode = initialExitCode; -}); - -describe('cjs-sdk-bridge: SDK runtime bridge integration', () => { - test('tryLoadSdk() resolves the bundled SDK on the current checkout', () => { - // Fresh require each run so module-level caches reset. - delete require.cache[require.resolve(BRIDGE_PATH)]; - const bridge = require(BRIDGE_PATH); - const loaded = bridge.tryLoadSdk(); - assert.strictEqual( - loaded, - true, - 'tryLoadSdk() must return true; if false, the bridge can no longer ' + - 'locate sdk/dist/runtime-bridge-sync/index.js or its exports — every ' + - 'CJS router will fall back to the per-side CJS handler.', - ); - }); - - test('getExecuteForCjs() returns a function after a successful load', () => { - const bridge = require(BRIDGE_PATH); - bridge.tryLoadSdk(); - assert.strictEqual(typeof bridge.getExecuteForCjs(), 'function'); - }); - - test('getFormatStateLoadRawStdout() returns a function after a successful load', () => { - const bridge = require(BRIDGE_PATH); - bridge.tryLoadSdk(); - assert.strictEqual(typeof bridge.getFormatStateLoadRawStdout(), 'function'); - }); - - test('executeForCjs() actually dispatches a canonical registry command (not a fallback)', () => { - const bridge = require(BRIDGE_PATH); - assert.strictEqual(bridge.tryLoadSdk(), true); - const executeForCjs = bridge.getExecuteForCjs(); - - // `generate-slug` is a canonical, project-independent command in the SDK - // registry. It does not require a `.planning/` fixture, so its success - // proves the bridge dispatch path works end-to-end without confounding - // it with project-state setup. Same command Phase 5.0's smoke test uses. - const result = executeForCjs({ - registryCommand: 'generate-slug', - registryArgs: ['Phase 6 Bridge Wired'], - legacyCommand: 'generate-slug', - legacyArgs: ['Phase 6 Bridge Wired'], - mode: 'json', - projectDir: process.cwd(), - }); - - assert.strictEqual( - result.ok, - true, - `executeForCjs result.ok must be true; got: ${JSON.stringify(result)}. ` + - 'If this fails, the bridge loaded but registry.dispatch did not return ' + - 'a typed-ok result for a known-canonical command — the seam is broken.', - ); - assert.ok(result.data && typeof result.data === 'object', 'result.data must be an object'); - assert.strictEqual(result.data.slug, 'phase-6-bridge-wired'); - assert.strictEqual(result.exitCode, 0); - }); -}); diff --git a/tests/cjs-sdk-bridge-seam-contracts.test.cjs b/tests/cjs-sdk-bridge-seam-contracts.test.cjs deleted file mode 100644 index b743f12a6..000000000 --- a/tests/cjs-sdk-bridge-seam-contracts.test.cjs +++ /dev/null @@ -1,507 +0,0 @@ -'use strict'; - -/** - * Phase 6 (issue #3524 / PR #3577) — CJS↔SDK seam behavioral contract tests. - * - * Issue #3592 explicitly tracks the migration away from text-existence / - * source-grep tests onto behavioral contract tests. This file is the - * behavioral contract surface for everything Phase 6 introduced: - * - * • `get-shit-done/bin/lib/cjs-sdk-bridge.cjs` — load + cache + surface - * • `sdk/src/runtime-bridge-sync/index.ts` — sync dispatch primitive - * (returns `RuntimeBridgeSyncResult`, a discriminated union with a - * fixed `SyncErrorKind` taxonomy) - * • The 7 family routers (`init|phase|phases|roadmap|state|validate| - * verify-command-router.cjs`) + top-level `gsd-tools.cjs` dispatch — - * each must route a canonical registry command through the bridge - * and emit a JSON-shaped result on stdout. - * • Workstream-scoped commands — Phase 6 made these native; the - * bridge must accept a `workstream` field and the CLI must still - * fall back to CJS when `GSD_WORKSTREAM` is set (the gate the - * routers use to defer to per-side CJS handlers). - * - * Test rules in force (from `CONTRIBUTING.md` § Testing Standards and - * issue #3592): - * - * 1. No `readFileSync` of any `.cjs` source file to assert text - * content. Every assertion is on a parsed JSON object, a - * filesystem fact, an exit code, or a frozen enum value. - * 2. No `assert.match`/`.includes` on free-form child-process stdout - * or stderr. Either parse JSON, or assert on a structured field - * via the bridge API directly. - * 3. Frozen enums describe the canonical taxonomies the production - * code MUST emit. Drift between production and test fails the - * object-shape lock test, not a substring lookup. - * 4. Filesystem assertions use `fs.statSync().isFile()` / `.size` — - * never read the file content back as a substring assertion. - */ - -const { describe, test, beforeEach, afterEach } = require('node:test'); -const assert = require('node:assert/strict'); -const fs = require('node:fs'); -const path = require('node:path'); - -const { createTempProject, cleanup, runGsdTools } = require('./helpers.cjs'); - -const REPO_ROOT = path.join(__dirname, '..'); -const BRIDGE_PATH = path.join(REPO_ROOT, 'get-shit-done', 'bin', 'lib', 'cjs-sdk-bridge.cjs'); - -// ─── Frozen taxonomies ──────────────────────────────────────────────────────── -// -// These describe the canonical shapes Phase 6 ships. Tests assert against the -// enum values, not against substring matches. Adding a new error kind or a -// new bridge export requires updating BOTH the production code AND the -// matching frozen set below — that's three coordinated edits, which is the -// drift-prevention property the new contract pattern is meant to provide. - -/** SDK runtime-bridge-sync `SyncErrorKind` taxonomy (sdk/src/runtime-bridge-sync/index.ts:62-68). */ -const SYNC_ERROR_KIND = Object.freeze({ - UNKNOWN_COMMAND: 'unknown_command', - NATIVE_FAILURE: 'native_failure', - NATIVE_TIMEOUT: 'native_timeout', - FALLBACK_FAILURE: 'fallback_failure', - VALIDATION_ERROR: 'validation_error', - INTERNAL_ERROR: 'internal_error', -}); - -const SYNC_ERROR_KIND_VALUES = Object.freeze(new Set(Object.values(SYNC_ERROR_KIND))); - -/** Surface of `cjs-sdk-bridge.cjs`. Adding an export requires updating both. */ -const BRIDGE_EXPORTS = Object.freeze([ - 'tryLoadSdk', - 'getExecuteForCjs', - 'getFormatStateLoadRawStdout', - 'getSdkModule', -]); - -/** TransportMode values accepted by executeForCjs. Bridge must support both. */ -const TRANSPORT_MODE = Object.freeze({ JSON: 'json', RAW: 'raw' }); - -// ─── Bridge module helper ───────────────────────────────────────────────────── -// -// Fresh-require the bridge once per describe block so each test sees an -// isolated load state. `delete require.cache[...]` is the canonical -// reset; never patch internals. - -function freshBridge() { - delete require.cache[require.resolve(BRIDGE_PATH)]; - return require(BRIDGE_PATH); -} - -// ─── 1. Bridge module surface contract ───────────────────────────────────────── - -describe('phase 6: cjs-sdk-bridge surface', () => { - test('exposes exactly the documented exports — frozen set', () => { - const bridge = freshBridge(); - const actual = Object.keys(bridge).sort(); - assert.deepStrictEqual( - actual, - [...BRIDGE_EXPORTS].sort(), - 'bridge surface drifted from BRIDGE_EXPORTS — update both production code and the frozen set together', - ); - }); - - test('every documented export is a function', () => { - const bridge = freshBridge(); - for (const name of BRIDGE_EXPORTS) { - assert.strictEqual(typeof bridge[name], 'function', `${name} must be a function`); - } - }); -}); - -// ─── 2. Bridge load + cache contract ────────────────────────────────────────── - -describe('phase 6: cjs-sdk-bridge load lifecycle', () => { - test('tryLoadSdk resolves the bundled SDK on a working checkout', () => { - const bridge = freshBridge(); - assert.strictEqual(bridge.tryLoadSdk(), true); - }); - - test('post-load getters return non-null when tryLoadSdk succeeded', () => { - const bridge = freshBridge(); - bridge.tryLoadSdk(); - assert.strictEqual(typeof bridge.getExecuteForCjs(), 'function'); - assert.strictEqual(typeof bridge.getFormatStateLoadRawStdout(), 'function'); - const mod = bridge.getSdkModule(); - assert.ok(mod && typeof mod === 'object', 'getSdkModule must return the cached module object'); - assert.strictEqual(typeof mod.executeForCjs, 'function'); - }); - - test('repeated tryLoadSdk calls return the cached result (same reference)', () => { - const bridge = freshBridge(); - bridge.tryLoadSdk(); - const fn1 = bridge.getExecuteForCjs(); - bridge.tryLoadSdk(); - const fn2 = bridge.getExecuteForCjs(); - assert.strictEqual(fn1, fn2, 'getExecuteForCjs must return the same cached function'); - }); - - test('pre-load getters return null', () => { - const bridge = freshBridge(); - assert.strictEqual(bridge.getExecuteForCjs(), null); - assert.strictEqual(bridge.getFormatStateLoadRawStdout(), null); - assert.strictEqual(bridge.getSdkModule(), null); - }); -}); - -// ─── 3. executeForCjs discriminated-union result shape ──────────────────────── - -describe('phase 6: executeForCjs RuntimeBridgeSyncResult shape', () => { - let bridge; - let executeForCjs; - let tmpDir; - - beforeEach(() => { - bridge = freshBridge(); - bridge.tryLoadSdk(); - executeForCjs = bridge.getExecuteForCjs(); - tmpDir = createTempProject(); - }); - - afterEach(() => { - cleanup(tmpDir); - }); - - test('ok:true result shape — { ok, data, exitCode }', () => { - const result = executeForCjs({ - registryCommand: 'generate-slug', - registryArgs: ['Phase 6 Seam Contract'], - legacyCommand: 'generate-slug', - legacyArgs: ['Phase 6 Seam Contract'], - mode: TRANSPORT_MODE.JSON, - projectDir: tmpDir, - }); - assert.strictEqual(result.ok, true); - assert.strictEqual(result.exitCode, 0); - assert.ok(result.data && typeof result.data === 'object', 'data must be an object on ok:true'); - assert.strictEqual(typeof result.data.slug, 'string'); - }); - - test('ok:false result for unknown command — errorKind ∈ SyncErrorKind, exitCode ≠ 0', () => { - const result = executeForCjs({ - registryCommand: 'totally.unknown.command.xyz', - registryArgs: [], - legacyCommand: 'totally.unknown.command.xyz', - legacyArgs: [], - mode: TRANSPORT_MODE.JSON, - projectDir: tmpDir, - }); - assert.strictEqual(result.ok, false); - assert.notStrictEqual(result.exitCode, 0); - assert.ok( - SYNC_ERROR_KIND_VALUES.has(result.errorKind), - `errorKind "${result.errorKind}" must be one of ${[...SYNC_ERROR_KIND_VALUES].join(', ')}`, - ); - assert.ok(Array.isArray(result.stderrLines), 'stderrLines must be an array on ok:false'); - }); - - test('mode:"json" returns parsed data, never a JSON-encoded string', () => { - // Regression for the Wave-1 bug where routers passed `mode: 'raw'` and the - // bridge pre-rendered to a JSON string that CJS output() then double- - // stringified. result.data MUST be a structured object/array/primitive - // — never a string that itself parses as JSON. - const result = executeForCjs({ - registryCommand: 'generate-slug', - registryArgs: ['Mode Json Check'], - legacyCommand: 'generate-slug', - legacyArgs: ['Mode Json Check'], - mode: TRANSPORT_MODE.JSON, - projectDir: tmpDir, - }); - assert.strictEqual(result.ok, true); - assert.notStrictEqual(typeof result.data, 'string', - 'mode:"json" must hand callers parsed data, not a serialized JSON blob'); - }); -}); - -// ─── 4. CLI family-router dispatch contracts ────────────────────────────────── -// -// One representative read-only command per family. Each test: -// 1. Invokes the CLI through `runGsdTools` (real child process). -// 2. Asserts exit success. -// 3. Parses stdout as JSON. -// 4. Asserts on a structured field, not on prose. -// -// This is the byte-for-byte parity contract Phase 6 promised: SDK-routed -// commands emit the same JSON shape as the legacy CJS handlers used to. - -describe('phase 6: CLI family-router dispatch emits structured JSON', () => { - let tmpDir; - - beforeEach(() => { - tmpDir = createTempProject(); - // Minimal ROADMAP fixture for any family that scans it. - fs.writeFileSync( - path.join(tmpDir, '.planning', 'ROADMAP.md'), - [ - '# v1.0 Roadmap', - '', - '### Phase 1: Foundation', - '**Goal:** Setup', - '**Requirements**: REQ-01', - '**Plans:** 0 plans', - '', - ].join('\n'), - ); - fs.writeFileSync( - path.join(tmpDir, '.planning', 'STATE.md'), - [ - '# State', - '', - '**Current Phase:** 01', - '**Status:** In progress', - '**Total Plans in Phase:** 0', - '**Progress:** [░░░░░░░░░░] 0%', - '**Last Activity:** 2026-05-15', - '', - ].join('\n'), - ); - }); - - afterEach(() => { - cleanup(tmpDir); - }); - - test('roadmap.get-phase emits found:true with structured phase fields', () => { - const result = runGsdTools(['roadmap', 'get-phase', '1'], tmpDir); - assert.ok(result.success, `roadmap get-phase failed: ${result.error}`); - const payload = JSON.parse(result.output); - assert.strictEqual(payload.found, true); - assert.strictEqual(payload.phase_number, '1'); - assert.strictEqual(payload.phase_name, 'Foundation'); - }); - - test('roadmap.analyze emits a milestones array', () => { - const result = runGsdTools(['roadmap', 'analyze'], tmpDir); - assert.ok(result.success, `roadmap analyze failed: ${result.error}`); - const payload = JSON.parse(result.output); - assert.ok(Array.isArray(payload.phases), 'phases must be an array'); - }); - - test('phase next-decimal emits a structured next/base shape', () => { - const result = runGsdTools(['phase', 'next-decimal', '1'], tmpDir); - assert.ok(result.success, `phase next-decimal failed: ${result.error}`); - const payload = JSON.parse(result.output); - assert.strictEqual(payload.base_phase, '01'); - assert.strictEqual(typeof payload.next, 'string'); - assert.ok(Array.isArray(payload.existing), 'existing must be an array'); - }); - - test('phases list emits a directories array with count', () => { - const result = runGsdTools(['phases', 'list'], tmpDir); - assert.ok(result.success, `phases list failed: ${result.error}`); - const payload = JSON.parse(result.output); - assert.ok(Array.isArray(payload.directories), 'directories must be an array'); - assert.strictEqual(typeof payload.count, 'number'); - }); - - test('state json emits a frontmatter object with progress', () => { - const result = runGsdTools(['state', 'json'], tmpDir); - assert.ok(result.success, `state json failed: ${result.error}`); - const payload = JSON.parse(result.output); - assert.strictEqual(payload.gsd_state_version, '1.0'); - assert.ok(payload.progress && typeof payload.progress === 'object', - 'progress must be a structured object, not a serialized string'); - }); - - test('init plan-phase emits phase_found + model fields', () => { - const result = runGsdTools(['init', 'plan-phase', '1'], tmpDir); - assert.ok(result.success, `init plan-phase failed: ${result.error}`); - const payload = JSON.parse(result.output); - assert.strictEqual(payload.phase_found, true); - assert.strictEqual(payload.phase_number, '1'); - assert.strictEqual(typeof payload.researcher_model, 'string'); - }); - - test('validate consistency emits valid + warnings array', () => { - const result = runGsdTools(['validate', 'consistency'], tmpDir); - assert.ok(result.success, `validate consistency failed: ${result.error}`); - const payload = JSON.parse(result.output); - assert.ok(typeof payload.valid === 'boolean' || Array.isArray(payload.warnings), - 'validate consistency must emit either {valid, warnings} shape'); - }); - - test('find-phase for non-existent phase emits found:false (not a process error)', () => { - const result = runGsdTools(['find-phase', '99'], tmpDir); - assert.ok(result.success, `find-phase should not error on missing phase: ${result.error}`); - const payload = JSON.parse(result.output); - assert.strictEqual(payload.found, false); - }); -}); - -// ─── 5. mode:"json" prevents double-stringify (Wave 1 bug regression) ───────── - -describe('phase 6: mode:"json" never double-stringifies the data', () => { - let tmpDir; - - beforeEach(() => { - tmpDir = createTempProject(); - fs.writeFileSync( - path.join(tmpDir, '.planning', 'ROADMAP.md'), - [ - '# v1.0', - '', - '### Phase 1: Setup', - '**Goal:** Initial setup', - '', - ].join('\n'), - ); - }); - - afterEach(() => { - cleanup(tmpDir); - }); - - // The Wave-1 bug shape: stdout looked like JSON of JSON, e.g. - // "\"{\\n \\\"found\\\": true\"". - // After the fix, stdout is a single JSON object that parses to an object — - // never a string that itself parses to an object. - test('roadmap get-phase stdout parses to an object, not a JSON-encoded string', () => { - const result = runGsdTools(['roadmap', 'get-phase', '1'], tmpDir); - assert.ok(result.success, `command failed: ${result.error}`); - const first = JSON.parse(result.output); - assert.strictEqual( - typeof first, - 'object', - 'CLI stdout for a JSON-mode command must parse directly to an object', - ); - assert.notStrictEqual( - typeof first, - 'string', - 'double-stringify regression: stdout parsed to a string that would itself parse as JSON', - ); - }); -}); - -// ─── 6. Workstream-scoped CJS fallback gate ──────────────────────────────────── -// -// Phase 6 made workstream-scoped commands native in the SDK transport, BUT the -// CJS routers still force CJS fallback when `GSD_WORKSTREAM` is set in the -// environment, so workstream-aware tests and inspections can target a -// specific workstream's `.planning/` slice without round-tripping through -// the synckit worker. Both modes must work and must produce the same JSON -// shape for the same input fixture. - -describe('phase 6: GSD_WORKSTREAM gate routes through CJS fallback consistently', () => { - let tmpDir; - - beforeEach(() => { - tmpDir = createTempProject(); - fs.writeFileSync( - path.join(tmpDir, '.planning', 'ROADMAP.md'), - ['# v1.0', '', '### Phase 1: Setup', '**Goal:** Setup', ''].join('\n'), - ); - }); - - afterEach(() => { - cleanup(tmpDir); - }); - - test('roadmap get-phase produces identical structured output with and without GSD_WORKSTREAM unset', () => { - const sdkPath = runGsdTools(['roadmap', 'get-phase', '1'], tmpDir); - assert.ok(sdkPath.success, `SDK dispatch failed: ${sdkPath.error}`); - const sdkPayload = JSON.parse(sdkPath.output); - - // When GSD_WORKSTREAM is set, the router falls through to CJS. For the - // primary planning slice (no workstream subdir yet), passing the env var - // should still parse the same ROADMAP.md and emit the same fields. - const cjsPath = runGsdTools(['roadmap', 'get-phase', '1'], tmpDir, { GSD_WORKSTREAM: '' }); - assert.ok(cjsPath.success, `CJS fallback dispatch failed: ${cjsPath.error}`); - const cjsPayload = JSON.parse(cjsPath.output); - - // Compare structured fields, never the rendered text. - assert.strictEqual(sdkPayload.found, cjsPayload.found); - assert.strictEqual(sdkPayload.phase_number, cjsPayload.phase_number); - assert.strictEqual(sdkPayload.phase_name, cjsPayload.phase_name); - }); -}); - -// ─── 7. Validation-error contract for malformed input ────────────────────────── -// -// When a registry command receives an invalid argument, the bridge must map -// the error to `validation_error` in the SyncErrorKind taxonomy and surface a -// non-zero exit code. This is the "negative path" coverage that #3592 -// explicitly calls out as required. - -describe('phase 6: validation errors map to SyncErrorKind.validation_error', () => { - let bridge; - let executeForCjs; - let tmpDir; - - beforeEach(() => { - bridge = freshBridge(); - bridge.tryLoadSdk(); - executeForCjs = bridge.getExecuteForCjs(); - tmpDir = createTempProject(); - }); - - afterEach(() => { - cleanup(tmpDir); - }); - - test('find-phase with empty phase identifier returns ok:false + validation_error', () => { - const result = executeForCjs({ - registryCommand: 'find-phase', - registryArgs: [], - legacyCommand: 'find-phase', - legacyArgs: [], - mode: TRANSPORT_MODE.JSON, - projectDir: tmpDir, - }); - assert.strictEqual(result.ok, false); - assert.strictEqual(result.errorKind, SYNC_ERROR_KIND.VALIDATION_ERROR, - `validation errors must map to ${SYNC_ERROR_KIND.VALIDATION_ERROR}, got ${result.errorKind}`); - assert.notStrictEqual(result.exitCode, 0, 'validation_error must produce a non-zero exit code'); - }); -}); - -// ─── 8. Filesystem-fact write contract ───────────────────────────────────────── -// -// Phase 6 routes phase.add through the SDK. After a successful add, the -// phase directory and ROADMAP entry must be on disk. Test asserts on -// filesystem facts (`existsSync`, `statSync().isDirectory()`, file size > 0) -// — never reads the file content back as a substring assertion. - -describe('phase 6: phase.add SDK dispatch writes the expected filesystem facts', () => { - let tmpDir; - - beforeEach(() => { - tmpDir = createTempProject(); - fs.writeFileSync( - path.join(tmpDir, '.planning', 'ROADMAP.md'), - [ - '# v1.0 Roadmap', - '', - '### Phase 1: Foundation', - '**Goal:** Setup', - '', - '---', - '', - ].join('\n'), - ); - }); - - afterEach(() => { - cleanup(tmpDir); - }); - - test('phase add User Dashboard creates phase 2 directory + appends ROADMAP entry', () => { - const before = fs.statSync(path.join(tmpDir, '.planning', 'ROADMAP.md')); - const result = runGsdTools(['phase', 'add', 'User', 'Dashboard'], tmpDir); - assert.ok(result.success, `phase add failed: ${result.error}`); - - const payload = JSON.parse(result.output); - assert.strictEqual(payload.phase_number, 2); - assert.strictEqual(payload.slug, 'user-dashboard'); - - // Filesystem facts: the directory exists and is a directory; the roadmap - // file grew (write happened). We do not read the file back to look for - // substrings — that's the prohibited pattern. - const phaseDir = path.join(tmpDir, '.planning', 'phases', '02-user-dashboard'); - assert.ok(fs.existsSync(phaseDir), 'new phase directory must exist on disk'); - assert.ok(fs.statSync(phaseDir).isDirectory(), 'phase path must be a directory'); - - const after = fs.statSync(path.join(tmpDir, '.planning', 'ROADMAP.md')); - assert.ok(after.size > before.size, 'ROADMAP.md must grow when phase add appends an entry'); - }); -}); diff --git a/tests/runtime-bridge-sync-smoke.test.cjs b/tests/runtime-bridge-sync-smoke.test.cjs deleted file mode 100644 index c6dc12532..000000000 --- a/tests/runtime-bridge-sync-smoke.test.cjs +++ /dev/null @@ -1,103 +0,0 @@ -'use strict'; - -/** - * CJS smoke test for the executeForCjs synchronous primitive (Phase 5.0 #3555). - * - * Verifies that the compiled dist artifact can be required from a CJS context - * and that executeForCjs returns the expected result shape synchronously. - * - * This is the critical end-to-end proof that the primitive works for CJS callers - * — the actual point of Phase 5.0. - */ - -const { describe, test } = require('node:test'); -const assert = require('node:assert/strict'); -const path = require('node:path'); -const { pathToFileURL } = require('node:url'); - -const REPO_ROOT = path.join(__dirname, '..'); -const BRIDGE_PATH = path.join(REPO_ROOT, 'sdk', 'dist', 'runtime-bridge-sync', 'index.js'); -// Node's ESM loader rejects Windows absolute paths with `import()` — must be a -// file:// URL. pathToFileURL is a no-op for POSIX paths (produces file:///abs/...). -const BRIDGE_URL = pathToFileURL(BRIDGE_PATH).href; - -describe('runtime-bridge-sync CJS smoke test', () => { - test('executeForCjs is exported and is a function', async () => { - // Use dynamic import because Node 24 supports require() of ESM but - // the module is ESM (NodeNext output). Dynamic import works in all contexts. - const mod = await import(BRIDGE_URL); - assert.strictEqual(typeof mod.executeForCjs, 'function', 'executeForCjs must be a function'); - }); - - test('executeForCjs returns ok:true for generate-slug (success path)', async () => { - const { executeForCjs } = await import(BRIDGE_URL); - - const result = executeForCjs({ - registryCommand: 'generate-slug', - registryArgs: ['My Smoke Test Phase'], - legacyCommand: 'generate-slug', - legacyArgs: ['My Smoke Test Phase'], - mode: 'json', - projectDir: '/tmp', - }); - - // The returned value must be a plain object, not a Promise - assert.strictEqual(typeof result, 'object', 'result must be an object'); - assert.ok(!(result instanceof Promise), 'result must not be a Promise'); - assert.ok('ok' in result, 'result must have ok property'); - - assert.strictEqual(result.ok, true, 'expected ok:true'); - assert.strictEqual(result.exitCode, 0, 'expected exitCode:0'); - assert.ok(result.data != null, 'expected data to be non-null'); - - const data = result.data; - assert.strictEqual(typeof data, 'object', 'data must be an object'); - assert.strictEqual(data.slug, 'my-smoke-test-phase', 'expected slug'); - }); - - test('executeForCjs returns ok:false for unknown command', async () => { - const { executeForCjs } = await import(BRIDGE_URL); - - const result = executeForCjs({ - registryCommand: '__smoke_test_unknown_command__', - registryArgs: [], - legacyCommand: '__smoke_test_unknown_command__', - legacyArgs: [], - mode: 'json', - projectDir: '/tmp', - }); - - assert.strictEqual(typeof result, 'object', 'result must be an object'); - assert.ok(!(result instanceof Promise), 'result must not be a Promise'); - assert.strictEqual(result.ok, false, 'expected ok:false'); - assert.ok(result.exitCode !== 0, 'expected non-zero exitCode'); - assert.ok('errorKind' in result, 'expected errorKind property'); - assert.strictEqual(result.errorKind, 'unknown_command', 'expected unknown_command errorKind'); - assert.ok(Array.isArray(result.stderrLines), 'expected stderrLines array'); - }); - - test('executeForCjs result shape matches RuntimeBridgeSyncResult discriminated union', async () => { - const { executeForCjs } = await import(BRIDGE_URL); - - // Success shape - const success = executeForCjs({ - registryCommand: 'current-timestamp', - registryArgs: ['date'], - legacyCommand: 'current-timestamp', - legacyArgs: ['date'], - mode: 'json', - projectDir: '/tmp', - }); - - assert.ok('ok' in success, 'success result must have ok'); - if (success.ok) { - assert.strictEqual(success.exitCode, 0); - assert.ok('data' in success); - } else { - // current-timestamp might fail if args aren't what it expects; just check shape - assert.ok('errorKind' in success); - assert.ok('stderrLines' in success); - assert.ok(Array.isArray(success.stderrLines)); - } - }); -});