fix(#2590): emit Workflow scripts the Workflow tool accepts; make the backend reachable (#2681)

* fix(#2590): emit Workflow scripts the Workflow tool accepts; make the backend reachable

Every emitted script was rejected. Four invalid constructs, the first fatal on
its own, so the Workflow backend could never dispatch a wave:

  1. no `export const meta = {…}` first statement -> whole script rejected
  2. resumeFromRunId("<id>")  -> "resumeFromRunId is not defined". It is a
     Workflow TOOL INPUT parameter, not a script function. The run id still
     reaches the caller via summary.resumeRunId, to pass as that input.
  3. budget(<n>)              -> "budget is not a function". `budget` is a
     read-only object { total, spent(), remaining() } fed by the caller's token
     directive; a script cannot set it. Recorded as intent in a comment.
  4. parallel(agent(…), agent(…)) -> "parallel() expects an array of functions".
     Now parallel([() => agent(…), …]) — passing agent() results directly also
     started every agent eagerly, before parallel() could bound concurrency.

The single-plan stage had its own branch with the same parallel() defect; both
branches are now one array-emitting path. Waves also emit phase() calls whose
titles match meta.phases exactly, so progress groups correctly.

Two secondary defects kept the script from ever being REACHED — which is why
this shipped undetected:

  5. NOTHING resolved the Agent SDK version. The fragment claimed there was "no
     scriptable way" to introspect it and told callers to omit the flag, so
     gate 5 returned agent_sdk_version_unknown on every automated run while
     `capability state` still reported active:true. True for bash, false for
     Node: the router now reads the installed @anthropic-ai/claude-agent-sdk
     version, walking node_modules up the tree and reading package.json
     directly — require.resolve throws ERR_PACKAGE_PATH_NOT_EXPORTED because the
     SDK's exports map does not expose ./package.json. Precedence: explicit flag
     > GSD_AGENT_SDK_VERSION > installed. Fail-closed is preserved; an
     unresolvable version still declines to inline. A too-old SDK now reports
     the truthful agent_sdk_version_below_floor instead of unknown.
  6. The runtime fallback was `--runtime > GSD_RUNTIME > 'unknown'`, diverging
     from the canonical `GSD_RUNTIME > config.runtime > 'claude'`, so any
     invocation without --runtime reported runtime_not_claude on an ordinary
     Claude project. Now delegates to runtime-slash.resolveRuntime.

The fragment's `${AGENT_SDK_VERSION:+--agent-sdk-version "$AGENT_SDK_VERSION"}`
snippet is removed rather than repaired: it was also shell-dependent — zsh does
not word-split unquoted parameter expansions, so it collapsed to a single argv
element, argValue() never matched, and the run failed into the same
agent_sdk_version_unknown, indistinguishable from genuinely unknown. Auto-
resolution removes the need for the construct entirely.

Verified with the issue's own repro: no flags now reaches the version gate; an
SDK above the floor yields backend:"workflow" with a script that parses as a
real ES module.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015TCwhbMuY37DzRMCfzTABJ

* fix(#2590): sync generated registry, repair sibling tests, reject duplicate wave ids

Findings from the isolated review, all fixed.

HIGH — gsd-core/bin/lib/capability-registry.cjs was stale, and `lint:ci` was
already RED because of it. The registry embeds the fragment text INLINE, so the
shipped/installed copy still taught the exact broken contract this PR fixes:
the old `${AGENT_SDK_VERSION:+…}` bash line and the "OMIT the flag when unknown"
guidance. Regenerated. (I had read `lint:ci` by grepping its output instead of
checking its exit code, so I recorded a red chain as green — checking $? now.)

HIGH — three existing tests asserted the OLD broken shape and would have failed
CI; none was touched by the first commit:
  tests/fix-2285-claude-orchestration-wiring.test.cjs — matched resumeFromRunId("…")
  tests/claude-orchestration.test.cjs                 — .includes('budget(')
  tests/claude-orchestration-command-router.test.cjs  — .includes('budget(')
Each now asserts the corrected contract: the id/pool reaches the caller via
summary, and neither construct is ever CALLED. Two sibling assertions had also
gone vacuous — `.includes('resumeFromRunId')` still passed, but only because the
new explanatory COMMENT contains that substring, not because anything is wired.
Rewritten to assert the real property.

MEDIUM — duplicate wave ids were never rejected. Plan-id uniqueness was checked
within a wave, but nothing checked wave ids across waves. That was harmless
before; it is not now, because each wave emits a `phase("Wave <id>")` call plus a
matching meta.phases entry and the tool matches titles by exact string — two
waves sharing an id would collapse into one progress group and misattribute the
second wave's agents to the first. Rejected at validation, with tests either
side of the boundary.

MEDIUM — the fragment contradicted itself (its "Manifest construction" header
still listed $AGENT_SDK_VERSION as orchestrator-built) and, more seriously, never
told the orchestrator to pass summary.resumeRunId as the Workflow tool's
resumeFromRunId INPUT. Since this PR moves resume from a broken in-script call to
a tool-invocation input, an implementer following only the fragment would have
silently regressed phase-resume to a no-op. Both fixed.

MEDIUM — docs/how-to/enable-claude-orchestration-workflow-backend.md and
docs/explanation/claude-orchestration-capability.md documented
`resumeFromRunId("<id>")` and `budget(<tokens>)` as current correct output —
teaching the bug as the feature. Updated to the real contract, including the
required meta block and the thunk-array parallel() form. (The changeset is
`Fixed`, so the docs gate exempts this; it is corrected because it is wrong,
not because a gate demanded it.)

LOW — the router's top-of-file comment still described the divergent
`--runtime > GSD_RUNTIME > 'unknown'` chain as current, ninety lines above the
fix; and inserting resolveInstalledAgentSdkVersion had orphaned
resolveDetectionArgs' JSDoc above the wrong function. Both repaired.

lint:ci now exits 0 (verified by exit code, not by reading output).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015TCwhbMuY37DzRMCfzTABJ

* chore(#2590): backfill changeset pr number (#2681)

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-07-26 20:49:38 -04:00
committed by GitHub
parent c3958018dd
commit 0d08c32048
13 changed files with 584 additions and 79 deletions

View File

@@ -13,8 +13,11 @@
*
* Subcommands:
* detect-backend [--runtime <id>] [--agent-sdk-version <ver>] [--no-nested-dispatch]
* Resolves whether the Workflow backend should activate. `--runtime`
* defaults to the GSD_RUNTIME env var (or 'unknown'). Reads the
* Resolves whether the Workflow backend should activate. Both flags are
* OPTIONAL (#2590): `--runtime` falls back to the canonical
* `GSD_RUNTIME > config.runtime > 'claude'` chain, and
* `--agent-sdk-version` to `GSD_AGENT_SDK_VERSION` then the installed
* @anthropic-ai/claude-agent-sdk version. Reads the
* `claude_orchestration.*` keys from .planning/config.json. Emits
* { available, backend, reason }.
*
@@ -45,6 +48,8 @@ import io = require('./io.cjs');
import core = require('./claude-orchestration.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
import configLoader = require('./config-loader.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
import runtimeSlash = require('./runtime-slash.cjs');
const { output } = io;
const { detectWorkflowBackend, emitWorkflowScript, resolveWaveDispatch } = core;
@@ -98,14 +103,62 @@ function resolveFlatClaudeOrchestrationConfig(cwd: string): Record<string, unkno
return flatConfig;
}
/**
* Resolve the installed Agent SDK version (#2590).
*
* The `execute:wave:pre` fragment claimed the orchestrator "has no scriptable
* way to introspect the live Agent SDK version" and told callers to omit the
* flag — so gate 5 returned `agent_sdk_version_unknown` on every automated run
* and the Workflow backend never activated, while `capability state` still
* reported it `active: true`. That claim is true for BASH, but this router runs
* in Node: the installed package's own package.json is authoritative and
* requires no flag at all.
*
* Resolution is side-effect-free and fails closed to undefined (gate 5 then
* declines, exactly as before) rather than guessing a version.
*/
const AGENT_SDK_PKG = path.join('@anthropic-ai', 'claude-agent-sdk', 'package.json');
function resolveInstalledAgentSdkVersion(cwd: string): string | undefined {
// Walk node_modules up the tree by hand rather than require.resolve: the SDK's
// `exports` map does not expose './package.json', so require.resolve throws
// ERR_PACKAGE_PATH_NOT_EXPORTED. Reading the file directly is exports-map
// independent and cannot execute package code.
for (const start of [cwd, __dirname]) {
let dir: string;
try { dir = path.resolve(start); } catch { continue; }
for (;;) {
try {
const pkgPath = path.join(dir, 'node_modules', AGENT_SDK_PKG);
if (fs.existsSync(pkgPath)) {
const parsed = JSON.parse(fs.readFileSync(pkgPath, 'utf8')) as { version?: unknown };
if (typeof parsed.version === 'string' && parsed.version.length > 0) return parsed.version;
}
} catch { /* unreadable/malformed — keep walking */ }
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
}
return undefined;
}
/**
* Resolve `--runtime`/`--agent-sdk-version`/`--no-nested-dispatch` into the
* `{ runtimeId, hostIntegration, agentSdkVersion }` triple both `detect-backend`
* and `resolve-wave-dispatch` pass to the pure detection seam.
*/
function resolveDetectionArgs(args: string[]): { runtimeId: string; hostIntegration: { dispatch: { nested: boolean; background: boolean } }; agentSdkVersion: string | undefined } {
const runtimeId = argValue(args, '--runtime') || process.env['GSD_RUNTIME'] || 'unknown';
const agentSdkVersion = argValue(args, '--agent-sdk-version');
function resolveDetectionArgs(args: string[], cwd?: string): { runtimeId: string; hostIntegration: { dispatch: { nested: boolean; background: boolean } }; agentSdkVersion: string | undefined } {
// #2590: the old fallback chain was `--runtime > GSD_RUNTIME > 'unknown'`,
// diverging from the canonical `GSD_RUNTIME > config.runtime > 'claude'` used
// by runtime-slash.resolveRuntime — so ANY manual invocation without
// --runtime reported `runtime_not_claude` on a perfectly ordinary Claude
// project. Delegate to the canonical resolver instead of re-deriving it.
const runtimeId = argValue(args, '--runtime') || runtimeSlash.resolveRuntime(cwd || null);
// Explicit flag wins (lets a caller pin a version); then the environment;
// then the actually-installed SDK.
const agentSdkVersion = argValue(args, '--agent-sdk-version')
|| process.env['GSD_AGENT_SDK_VERSION']
|| resolveInstalledAgentSdkVersion(cwd || process.cwd());
const noNested = args.includes('--no-nested-dispatch');
const hostIntegration = noNested ? { dispatch: { nested: false, background: true } } : CAPABLE_HOST;
return { runtimeId, hostIntegration, agentSdkVersion };
@@ -146,7 +199,7 @@ function readWavesManifest(wavesPath: string, error: (msg: string, reason?: stri
* SDK version come from flags (the orchestrator already knows these) or env.
*/
function cmdDetectBackend(args: string[], cwd: string, raw: boolean): void {
const { runtimeId, hostIntegration, agentSdkVersion } = resolveDetectionArgs(args);
const { runtimeId, hostIntegration, agentSdkVersion } = resolveDetectionArgs(args, cwd);
const flatConfig = resolveFlatClaudeOrchestrationConfig(cwd);
const result = detectWorkflowBackend({ runtimeId, hostIntegration, config: flatConfig, agentSdkVersion });
output(result, raw);
@@ -214,7 +267,7 @@ function cmdResolveWaveDispatch(args: string[], cwd: string, raw: boolean, error
const read = readWavesManifest(wavesPath, (msg) => error('resolve-wave-dispatch: ' + msg));
if (!read.ok) return; // read/parse failure — error() already surfaced it loudly above
const { runtimeId, hostIntegration, agentSdkVersion } = resolveDetectionArgs(args);
const { runtimeId, hostIntegration, agentSdkVersion } = resolveDetectionArgs(args, cwd);
const flatConfig = resolveFlatClaudeOrchestrationConfig(cwd);
const budgetTokens = budgetRaw !== undefined ? parseInt(budgetRaw, 10) : undefined;

View File

@@ -402,6 +402,12 @@ function emitWorkflowScript(input: EmitInput | null | undefined): EmitOk | EmitE
if (!Array.isArray(waves) || waves.length === 0) {
return { ok: false, reason: 'waves must be a non-empty array' };
}
// Wave ids must be unique ACROSS waves, not just plan ids within one (#2590).
// Each wave emits a `phase("Wave <id>")` call plus a matching meta.phases
// entry, and the Workflow tool matches phase titles by exact string — two
// waves sharing an id would collapse into one progress group and misattribute
// every agent in the second wave to the first.
const seenWaveIds = new Set<string>();
for (let i = 0; i < waves.length; i++) {
const w = waves[i];
if (w === null || typeof w !== 'object' || typeof w.id !== 'string') {
@@ -410,6 +416,10 @@ function emitWorkflowScript(input: EmitInput | null | undefined): EmitOk | EmitE
if (!isScriptableIdentifier(w.id)) {
return { ok: false, reason: 'waves[' + i + '].id must not contain newlines/quotes/backslash/control chars' };
}
if (seenWaveIds.has(w.id)) {
return { ok: false, reason: 'duplicate wave id "' + w.id + '" — wave ids must be unique (phase titles must map 1:1)' };
}
seenWaveIds.add(w.id);
if (!Array.isArray(w.plans) || w.plans.length === 0) {
return { ok: false, reason: 'waves[' + i + '] must have a non-empty plans array' };
}
@@ -442,15 +452,43 @@ function emitWorkflowScript(input: EmitInput | null | undefined): EmitOk | EmitE
: null;
const lines: string[] = [];
// `export const meta = {…}` MUST be the first statement in the script — the
// Workflow tool rejects the whole script otherwise (#2590). Leading comments
// are not statements, but the meta block is emitted first regardless so the
// contract holds under the strictest reading of "first statement".
//
// meta.phases must be a PURE LITERAL (no variables, calls, spreads, or
// template interpolation), and its titles are matched EXACTLY against the
// phase() calls emitted below.
lines.push('export const meta = {');
lines.push(' name: ' + quoteString('gsd-execute-' + runId) + ',');
lines.push(' description: ' + quoteString('GSD wave dispatch for ' + phaseDir) + ',');
lines.push(' phases: [');
for (const w of waves) {
lines.push(' { title: ' + quoteString('Wave ' + w.id) + ', detail: '
+ quoteString(w.plans.length + ' plan(s)') + ' },');
}
lines.push(' ],');
lines.push('}');
lines.push('');
lines.push('// GSD Workflow script — generated by the claude-orchestration capability (#1143)');
lines.push('// phase: ' + phaseDir);
lines.push('// BETA: preview-grade; on any failure the orchestrator falls back to inline dispatch.');
lines.push('// Composes the SAME gsd-executor agent as the inline path, so artifacts (SUMMARY.md)');
lines.push('// and commits are produced identically. Worktree isolation is per-plan (use_worktree)');
lines.push('// and mirrors execute-phase.md step 2.5\'s submodule gate exactly (#2772 / #2285).');
lines.push('resumeFromRunId(' + quoteString(runId) + ')');
lines.push('//');
// resumeFromRunId is a Workflow TOOL INPUT parameter, not a script function —
// calling it threw "resumeFromRunId is not defined" (#2590). The run id is
// carried in summary.resumeRunId for the caller to pass as that input.
lines.push('// resume: pass ' + quoteString(runId) + ' as the Workflow tool\'s resumeFromRunId input');
lines.push('// (it is a tool parameter, NOT a script function).');
if (budgetTokens !== null) {
lines.push('budget(' + budgetTokens + ')');
// `budget` is a read-only object ({ total, spent(), remaining() }) supplied
// by the caller's token directive — a script cannot SET it, and `budget(n)`
// threw "budget is not a function" (#2590). Recorded as intent only.
lines.push('// budget: ' + budgetTokens + ' output tokens intended for this run; `budget` is');
lines.push('// read-only in a Workflow script — set it via the caller\'s token directive.');
}
lines.push('');
@@ -464,6 +502,8 @@ function emitWorkflowScript(input: EmitInput | null | undefined): EmitOk | EmitE
totalPlans += wave.plans.length;
lines.push('// Wave ' + wave.id);
// Title must match this wave's meta.phases entry EXACTLY.
lines.push('phase(' + quoteString('Wave ' + wave.id) + ')');
for (let si = 0; si < stages.length; si++) {
const stagePlanIds = stages[si];
// Resolve back to plan objects for briefs (ids are unique within a wave — validated above).
@@ -471,21 +511,15 @@ function emitWorkflowScript(input: EmitInput | null | undefined): EmitOk | EmitE
if (stages.length > 1) {
lines.push('// Stage ' + si + (si > 0 ? ' (sequential — files_modified overlap)' : ''));
}
if (stagePlans.length === 1) {
const p = stagePlans[0];
lines.push('parallel(');
lines.push(' agent(' + quoteString(p.brief) + ', ' + agentOptions(p) + ')');
lines.push(')');
} else {
lines.push('parallel(');
for (const p of stagePlans) {
lines.push(' agent(' + quoteString(p.brief) + ', ' + agentOptions(p) + '),');
}
// Replace trailing comma on the last agent line with nothing.
const lastIdx = lines.length - 1;
lines[lastIdx] = lines[lastIdx].replace(/,$/, '');
lines.push(')');
// parallel() takes an ARRAY OF THUNKS — `parallel(agent(…), agent(…))`
// threw "parallel() expects an array of functions" (#2590). Passing
// agent() results directly would also start every agent eagerly, before
// parallel() could bound concurrency.
lines.push('await parallel([');
for (const p of stagePlans) {
lines.push(' () => agent(' + quoteString(p.brief) + ', ' + agentOptions(p) + '),');
}
lines.push('])');
}
if (wi < waves.length - 1) lines.push('');
}