Files
msd-core/capabilities/claude-orchestration/fragments/execute-wave-pre.md
Tom Boucher 2f86278b5e fix(#3003): opt-in mechanism for intentional deletions in worktree.cleanup-wave (#3757)
* test(#3003): failing-first suite for declared deletions in cleanup-wave

Binds the guard's opt-in before it exists, so the suite is RED against next.

The rows that carry the weight are the over-authorization set: a directory
declaration must not authorize its children, a glob declaration must authorize
nothing, and a declaration must not act as a string prefix of another path.
Each of those BLOCKS, and each would PASS under a prefix, glob, or startsWith
matcher — which is how a path list quietly degrades into the boolean opt-in
#3003 explicitly rejected. The glob row matters most: declaredScopePrefix
already returns null ("matches everything") for a glob-leading pattern, correct
for the advisory it serves and catastrophic for a gate.

Also pinned: a failed deletion check blocks on its own reason rather than being
filtered into a pass; the block detail names only the undeclared residue so the
operator is not misdirected by paths that were fine; an entry with no
declaration blocks exactly as before; junk and non-array declarations do not
authorize; and a blocked entry still isolates rather than aborting the wave
(#2852, which must stay fixed).

Two advisory rows cover an interaction found while designing: git diff
--name-only includes deleted paths, so without unioning the declaration into
the #2596 scope check, authorizing a deletion would raise
SCOPE_OUT_OF_DECLARED against the very path just authorized.

A seeded property states the whole invariant the three over-authorization rows
sample: a deletion merges iff its normalized path is in the declared set.

* feat(#3003): declared deletions opt-in for the cleanup-wave guard

The deletions guard blocked the merge-back of any executor branch whose diff
removed a file, with no way to say a removal was intended. A plan that folded
one test file into a sibling could not be merged by the tool meant to merge it,
forcing a manual --no-ff outside the tool -- strictly less safe than what the
guard protects against.

A plan now declares removals in its own frontmatter (files_deleted), and that
list rides the same path files_modified already travels: plan-document parse ->
phase plan JSON -> the per-plan worktree gate -> record-agent/create
--deletions -> declared_deletions on the manifest entry -> the guard. The guard
blocks only the deletions NOT in that list.

A path list rather than a boolean, per the pinned decision: a boolean disarms
the guard for the whole entry, so an unexpected deletion riding along with a
declared one would pass unnoticed. Matching is exact after the module's shared
normalizer -- never a prefix, never a glob. Both would let one declaration
authorize a whole set, which is the mass-deletion accident the guard exists to
catch. That also means declaredScopePrefix is deliberately NOT reused here: it
returns null ("matches everything") for a glob-leading pattern, which is right
for the advisory it serves and would silently disarm a gate.

The block detail now carries only the undeclared residue, so an operator is not
sent looking at paths that were fine. A failed deletion check still blocks on
its own reason and is never filtered into a pass. A blocked entry still
isolates rather than aborting the wave (#2852).

The #2596 scope advisory unions the declaration into its declared set --
git diff --name-only includes deleted paths, so without that, authorizing a
deletion would immediately warn that the same path was out of declared scope.

Optional and additive throughout: files_deleted is absent from
PLAN_REQUIRED_FIELDS, a manifest entry without declared_deletions keeps the
original unconditional block, and omitting --deletions leaves the on-disk entry
shape untouched.

Supersedes the spent #2856 emitted-drift ack entry for execute-phase.md, the
same supersede that entry performed on #3370 and #3370 on #3324.

* fix(#3003): wire --deletions on every dispatch surface, not just one

Review found the feature inert on two of three dispatch paths. execute-phase.md
(harness inline) passed --deletions, but the orchestrator-worktree path
(executor-isolation-dispatch.md, worktree.create) and the Fleet-parallel batch
path (capabilities/claude-orchestration/fragments/execute-wave-pre.md,
worktree.record-agent) still passed only --files. A plan declaring
files_deleted would have merged on one path and been blocked on the other two
-- the exact bug #3003 exists to fix, left unfixed where most of the isolation
actually runs.

Worse, per-plan-worktree-gate.md already claimed --deletions was passed 'on the
same worktree.record-agent / worktree.create calls', which was false for both
untouched sites. A doc asserting coverage that does not exist is how a gap
survives review.

All four surfaces now pass the flag, verified by sweeping every .md under
gsd-core/, capabilities/, commands/, skills/ and agents/ that invokes
worktree.record-agent or worktree.create: each one that passes --files now also
passes --deletions. The isolation-dispatch note explains why this flag, unlike
--files, is not advisory -- omitting it does not skip a check, it blocks a
merge the plan declared.

Regenerates capability-registry.cjs, which the fragment edit made stale.

Neither newly-grown file needs an emitted-drift ack: executor-isolation-dispatch.md
sits under workflows/execute-phase/steps/ and execute-wave-pre.md under
capabilities/, both outside currentSizes()'s non-recursive scan of
gsd-core/workflows/ and agents/.

* docs(#3003): document files_deleted where a plan author will actually find it

The feature's entire user surface is one plan-frontmatter field, and the
canonical reference for that frontmatter -- docs/reference/plan-md.md, the table
that documents every other key -- never mentioned it. A field nobody can
discover ships as a field nobody uses. Adds the files_deleted row and an example
entry in all five locales (en, ja-JP, zh-CN, ko-KR, pt-BR), stating the property
that makes the opt-in safe: matching is exact per path after separator
normalization, with no globs and no directory prefixes, so a declaration can
never authorize more than it literally lists, and omitting the field keeps the
guard's original unconditional block.

Also corrects two claims in the scope-conformance how-to that this change made
false. Its opening paragraph described the recorded declared scope as
files_modified alone; declared_deletions is now unioned into that comparison.
Its "Renames are not detected specially" bullet asserted the deletions guard
blocks any entry whose diff contains a deletion, full stop -- which was the
whole point of #3003 and is no longer true. Reworked to say what now decides a
rename's fate: declare the old path in files_deleted and both halves become
ordinary paths for the advisory check, which is also why the old path needs no
separate files_modified entry.

Documentation that describes the pre-change behavior of the thing being changed
is worse than no documentation, because a reader trusts it.

* fix(#3003): close every review finding on the declared-deletions opt-in

Two independent isolated reviewers, correctness and security. Neither found a
blocker; both found real defects, and the directive treats a finding at any
severity as blocking. All of them are fixed here.

MAJOR -- the submodule worktree gate could not see a deletion-only plan.
per-plan-worktree-gate.md intersected $SUBMODULE_PATHS against $PLAN_FILES
alone, while $PLAN_DELETIONS was extracted and then never used. Before
files_deleted existed, a path had to appear in files_modified to be planned at
all, so the gate saw it; the new field plus the new docs telling authors a
deleted path needs no files_modified entry opened a hole where a plan whose only
submodule touch is a removal kept worktree isolation on -- the exact case #2772
disabled it for. Both channels now feed the intersection. Note the posture is
deliberately the OPPOSITE of the cleanup-wave guard: there the channels stay
apart because a deletion AUTHORIZATION must never be inferred; here they merge
because a safety fallback must never MISS a touch.

MAJOR -- same-wave conflict detection could not see a deletion. The planner's
implicit-dependency rule compared files_modified only, so plan A editing
src/x.ts and plan B declaring files_deleted: [src/x.ts] scored as conflict-free
and ran in parallel: one branch removing what the other is writing, which is the
sharpest conflict there is. Overlap is now computed across both channels.

MINOR (both reviewers, one root cause) -- the advisory union gave one field two
matching rules. declared_deletions was unioned into the scope list handed to
planWaveScopeConformance, which reads it with prefix-and-glob semantics. So a
field that is exact-match-only at the gate silently became wider at the
advisory: ["*.md"], inert at the gate, yielded a null prefix meaning "matches
everything" and muted the advisory completely, and ["src"] muted all of src/.
The union also activated the advisory on plans that declared no modification
scope at all, warning on every modified path. Replaced with subtraction from the
findings, gated on files_modified alone. One field, one rule, everywhere.

MINOR -- core.quotepath made the feature silently inert for non-ASCII paths.
git emits "tests/\303\251.ts" C-escaped and quoted, which never equals the
declared plain path, so a correctly declared deletion of tests/é.ts would block
forever with nothing pointing at the encoding. Both diffs now pass
-c core.quotepath=false.

NIT -- flag() consumed a following flag as a value, so --deletions --files x
swallowed --files and dropped both. Now treated as a missing declaration, which
fails closed. Fixed at both call sites; the helper is duplicated verbatim in
cmdWorktreeRecordAgent and cmdWorktreeCreate and leaving one would reintroduce it.

TEST -- one test passed for the wrong reason. "a declared deletion is in scope
for the advisory" asserted only that warnings omit the deleted path; under a
full revert the entry blocks first, warnings come back empty, and the negative
assertion passes anyway. It now asserts the entry actually merged, which is the
load-bearing half. Four regressions added, one per fix above.

Docs corrected rather than extended. The rename bullet in the scope-conformance
how-to claimed a rename whose delete side is undeclared never reaches the
advisory. Verified false: git's rename detection is on by default, so a pure
rename is a single R entry that appears in no --diff-filter=D output and was
never gated, before or after #3003. Only a rename that edits enough to fall
below the similarity threshold decomposes into add+delete. The pre-existing
sentence made the same wrong claim; this restates it correctly instead of
sharpening the error. The localized plan-md.md reference edits are reverted:
the PR template requires docs content added here to be English, and the
translations already lag by three fields, so English-only is the repo's
standing posture, not an oversight.

Agent-file size caps respected: gsd-planner.md is XL-tier by bytes but carries a
separate 49152-LF-CHAR cap asserted by four suites, so its edit is deliberately
terse and lands at 49141 with 11 chars of headroom, with the rationale moved to
docs/reference/plan-md.md, which has no cap. gsd-plan-checker.md lands at 49107
bytes, 45 under the LARGE cap. Both acks merged into the existing fragments that
already name those paths, since two ack sources may never name the same path.

* fix(#3003): decode git's path quoting instead of changing the git argv

The previous commit's non-ASCII fix turned the remote suite red: 44 failures,
42 of them "unexpected git call: -c core.quotepath=false diff --diff-filter=D
--name-only ...". The suite's git mocks match on exact argv, so adding two
flags to the deletions diff and the advisory diff invalidated every existing
fixture in tests/worktree-safety.test.cjs. Rewriting dozens of fixtures to
accommodate one flag would be paying a large Hyrum's-law bill to fix a small
defect.

Both execGit calls are reverted to their original argv. The C-quoting is now
decoded in normalizeScopePath instead, via a new decodeGitQuotedPath helper.
That is the better fix on its own merits, not merely the cheaper one: the git
argv is untouched so no fixture moves, the decode lands on the ONE normalizer
already applied to both sides of the comparison so the declared and reported
paths cannot disagree, and it holds regardless of the user's own core.quotepath
setting rather than only when we remember to override it.

A value not wrapped in a leading AND trailing quote is returned completely
untouched, so the plain-ASCII path -- the overwhelmingly common case -- is
byte-identical to before. Escapes decode to BYTES collected into a Buffer and
UTF-8 decoded only at the end, because \303\251 is two bytes forming one
character and decoding them separately yields mojibake. Malformed input never
throws: a trailing lone backslash or a short octal escape degrades to the
literal character, since one bad path must not take down a cleanup wave.

Caught while reviewing the helper: the non-escape branch pushed a UTF-16 code
unit rather than UTF-8 bytes. Git always escapes non-ASCII so its own output was
fine, but this normalizer runs on the DECLARED side too, and an author may write
a quoted path holding a literal é -- pushing 0xE9 alone is invalid UTF-8, so the
declaration would decode to a replacement character and silently stop matching.
That is precisely the failure this change removes, reintroduced on the other
side of the comparison. Now converts whole code points, surrogate pairs intact.

The other 2 failures: tests/parallel-dependent-plans.test.cjs pins the exact
unbackticked substring "files_modified overlap" in gsd-planner.md, and rewording
that comment to "declared-scope overlap" deleted it. The comment is restored
verbatim and the files_deleted change rides in the pseudocode and the Rule
sentence instead. Recorded in the ack fragment so the next contributor does not
rediscover it the same way.

Four regression tests cover the decode through the public cleanup-wave seam
(the helper is module-private): a declared non-ASCII deletion merges against a
C-quoted git report, the symmetric case where the DECLARATION is the quoted
form, an undeclared non-ASCII deletion still blocks with the residue naming the
decoded path an operator can act on, and a path merely containing a quote is
left alone. Plain ASCII was already covered and is not duplicated.

* fix(#3003): revert the leading-dash flag guard, the review nit was wrong

The remote suite came back with 2 failures, down from 44, and both point at the
same thing: tests/worktree-safety.test.cjs:7045 already pins the opposite
contract, deliberately.

  test('a flag-shaped --files value is not re-parsed as a flag', ...)
    recordAgent(['--files', '--branch'])
    -> files_modified === ['--branch']
    -> branch === 'worktree-agent-a1'  ("the real --branch value must be untouched")

So consuming the next argv element positionally, whatever its shape, is the
tested intent of this parser, not an oversight. The security reviewer's nit
claimed --deletions --files x would "swallow --files and drop both". It does
not: each flag runs its own indexOf, so --deletions records the literal
'--files' while --files independently still resolves to x. And that literal is
a path git never reports as deleted, so it authorizes nothing -- already
fail-closed with no guard at all. The guard bought no safety and silently
changed --files behavior along the way, outside this issue's scope.

Reverted at both call sites, which are byte-identical again, along with the test
asserting the reverted behavior and the docs sentence describing it. The nit is
recorded as REJECTED in the review artifact with the reasoning above, rather
than as fixed -- a finding that turns out to be wrong should leave a trace of
why, or the next reviewer files it again.

docs/CLI-TOOLS.md now states the positional-read behavior plainly instead, so
the next person meets it as documented intent rather than rediscovering it
through a red suite.

* chore(#3003): backfill changeset pr number to 3757

* test(#3003): cover parsePlanDocument's filesDeleted branch to clear the mutation gate

CI's Stryker shard for plan-document failed at 73.28 against a break threshold
of 75: 170 killed, 62 survived, 232 total. Eight of those survivors are the
filesDeleted block this issue added to parsePlanDocument, which shipped with no
direct coverage at all -- the field was exercised end to end through the
cleanup-wave tests, but the parser itself was never called with a plan that
declares it, so every mutant in the block lived.

Four tests, each pinned to specific mutants rather than written for coverage
percentage:

- absent key yields exactly [] -- kills the array-literal seed
  (["Stryker was here"]) and the `fmDeleted = true` conditional, which would
  otherwise produce ["true"]
- a scalar underscore `files_deleted:` wraps into a one-element array -- kills
  `fmDeleted = false`, the `&&` logical-operator swap, the `fm[""]` string
  mutation on the first operand, the emptied if-block, and the ternary's
  non-array branch
- an array-valued hyphenated `files-deleted:` maps element-wise -- kills the
  `fm[""]` mutation on the SECOND operand (only reachable when the legacy
  hyphen alias is the one carrying the value) and the ternary's array branch
- an empty list yields [] -- boundary case, and a genuinely distinct one from
  the absent key: [] is truthy in JS so it ENTERS the if, and only
  Array.isArray's true branch mapping over nothing produces the same []

Threshold arithmetic: 174 of 232 are needed for 75%, and these take it to about
178, so the shard clears with margin rather than landing on the line.

Every expected value was confirmed by executing the built parser before being
asserted, not inferred from reading the source.

---------

Co-authored-by: sim <sim@local>
2026-08-22 13:17:51 -04:00

15 KiB
Raw Blame History

Claude orchestration — Workflow execution backend (BETA)

Injected at execute:wave:pre into: executor only when claude_orchestration.enabled is true. Default-off; onError: skip.

When this contribution is active

The Claude orchestration capability is default-off and BETA. It activates only when ALL of the following hold:

  1. claude_orchestration.enabled is true in .planning/config.json, AND
  2. the active runtime is Claude Code (the Workflow tool is Claude / Agent SDK-specific), AND
  3. claude_orchestration.execution_backend resolves to workflow — either explicitly, or via auto — and the Agent SDK version is >= claude_orchestration.min_agent_sdk_version (default 0.3.149). The SDK floor applies in both auto and workflow modes (fail-closed: a pre-release or older SDK never activates the preview backend).

Detection is fail-closed: any miss degrades to inline, manual, one-agent-per- message dispatch — exactly today's behaviour. On a non-Claude runtime this contribution is a no-op.

Why execute:wave:pre (not execute:wave:post)

This is a dispatch-backend selector — it decides HOW a wave's executor agents are spawned. That decision has to be made BEFORE the wave's Agent() calls in execute-phase.md step 3, not after the wave has already finished (#2285). The capability previously registered at execute:wave:post, which fires only after worktree merge/post-merge tests/tracking updates — by then the wave was already dispatched inline, so the contribution was structurally unable to change how dispatch happened. This fragment is injected at the point that actually precedes dispatch.

What the orchestrator does when the Workflow backend is active

Before spawning executor agents for the current wave (execute-phase.md step 3), resolve the dispatch backend through the single composed CLI seam:

gsd-tools claude-orchestration resolve-wave-dispatch \
  --waves "$WAVE_MANIFEST_PATH" --run-id "$PHASE_RUN_ID" \
  --runtime "$RUNTIME" \
  --phase-dir "$PHASE_DIR" --raw

--agent-sdk-version is no longer passed here (#2590). The router resolves the installed Agent SDK version itself; see Agent SDK version below. The former ${AGENT_SDK_VERSION:+--agent-sdk-version "$AGENT_SDK_VERSION"} line was also shell-dependent: zsh does not word-split unquoted parameter expansions, so it collapsed to a SINGLE argv element there, argValue() never matched, and the run failed into agent_sdk_version_unknown — indistinguishable from genuinely unknown. Pass --agent-sdk-version <ver> explicitly only to pin a version.

This composes detectWorkflowBackend (the gate ladder above) with emitWorkflowScript (the wave→plan mapping below) in ONE call — the pure function backing it is resolveWaveDispatch in gsd-core/bin/lib/claude-orchestration.cjs. Response shape: { backend: 'inline'|'workflow', reason, script?, summary? }.

Manifest construction ($WAVE_MANIFEST_PATH, $PHASE_RUN_ID, $PHASE_DIR)

These are NOT pre-existing execute-phase.md variables — the orchestrator builds them at this step, from data it already has in-context from discover_and_group_plans (the PLAN_INDEX JSON) and step 2.5 (the per-plan USE_WORKTREES_FOR_PLAN decision):

  1. $PHASE_DIR — reuse {phase_dir} from the INIT bundle (already loaded in the initialize step). No new value needed.

  2. $PHASE_RUN_ID — a stable identifier for THIS phase-execution attempt, so resumeFromRunId can resume an interrupted run without re-dispatching plans the Workflow tool already completed. Construct it deterministically — execute-{phase_number}-{phase_slug} — from INIT's phase_number/phase_slug (both are already validated identifiers used elsewhere in this workflow, so they satisfy emitWorkflowScript's isScriptableIdentifier check). Do NOT mint a new random id per wave — the SAME $PHASE_RUN_ID is reused for every wave in the phase so the Workflow tool can correctly track cross-wave resume state.

  3. $WAVE_MANIFEST_PATH — a fresh temp file for THIS wave's manifest (one wave = one waves array with a single entry, matching the wave-by-wave dispatch loop; do not batch multiple waves into one manifest — waves are dispatched in wave order, not all at once):

    WAVE_MANIFEST_PATH=$(mktemp "${TMPDIR:-/tmp}/gsd-wave-dispatch-XXXXXX") && mv "$WAVE_MANIFEST_PATH" "$WAVE_MANIFEST_PATH.json" && WAVE_MANIFEST_PATH="$WAVE_MANIFEST_PATH.json"
    

    Then use the Write tool (not a bash/jq pipeline — the orchestrator already has every field parsed in-context) to write the manifest JSON to $WAVE_MANIFEST_PATH:

    {
      "waves": [
        {
          "id": "wave-{N}",
          "plans": [
            {
              "id": "{plan_id}",
              "brief": "{the SAME <objective>...<success_criteria> prompt block step 3 builds for this plan's inline Agent() call}",
              "files_modified": ["{from PLAN_INDEX.plans[].files_modified for this plan}"],
              "use_worktree": {true unless step 2.5 set USE_WORKTREES_FOR_PLAN=false for this plan}
            }
          ]
        }
      ]
    }
    
    • id — the plan id from PLAN_INDEX, e.g. "01-01".
    • brief — MUST carry the same task content as step 3's inline Agent() prompt (the <objective>/<execution_context>/<required_reading>/ <success_criteria> block, with {plan_number}/{phase_number}/ {phase_name} substituted) — a short summary here would NOT reproduce step 3's behavior and would violate the "identical artifacts" contract.
    • files_modified — copy verbatim from the plan's PLAN_INDEX entry.
    • use_worktree — true for every plan UNLESS step 2.5's per-plan worktree gate (execute-phase/steps/per-plan-worktree-gate.md) set USE_WORKTREES_FOR_PLAN=false for that plan (submodule-touching plan, or project-level USE_WORKTREES=false) — in which case pass false here so emitWorkflowScript omits isolation: "worktree" for that plan (#2772 / #2285 finding 1). Never hardcode true — that would force worktree isolation on a plan the inline path explicitly keeps out of worktrees.
  4. $AGENT_SDK_VERSION — no longer built here; the router resolves it.

Agent SDK version: the orchestrator has no bash-computable way to introspect the live Agent SDK version — but the router runs in Node, so it resolves the version itself (#2590), in this order:

  1. an explicit --agent-sdk-version <ver> (pin a version),
  2. GSD_AGENT_SDK_VERSION,
  3. the installed @anthropic-ai/claude-agent-sdk package version, read from its package.json on disk by walking node_modules up the tree. (Read directly rather than via require.resolve: the SDK's exports map does not expose ./package.json, so require.resolve throws ERR_PACKAGE_PATH_NOT_EXPORTED.)

Previously nothing computed this at all, so gate 5 returned agent_sdk_version_unknown on every automated run and the Workflow backend could never activate — while gsd-tools capability state still reported the capability active: true. Fail-closed is preserved: when no version can be resolved, gate 5 still declines to inline. What changed is that a resolvable version is now actually found, so a genuinely-too-old SDK reports agent_sdk_version_below_floor — the truthful reason — instead of unknown.

If backend == "workflow": run the emitted script via the Workflow tool for THIS wave instead of the per-message Agent() loop in step 3. The script composes the SAME gsd-executor agent type the inline path uses, with worktree isolation applied PER PLAN from the manifest's use_worktree field (see emitWorkflowScript):

  • waves → one or more sequential parallel() barriers — each wave is a barrier group; when plans within a wave share files_modified, they are split into separate sequential stages within that wave's barrier.
  • plans → agent(brief, { agentType: 'gsd-executor', isolation: 'worktree' }) when use_worktree is not false, or agent(brief, { agentType: 'gsd-executor' }) (no isolation) when it is — so the produced SUMMARY.md and commits are identical to inline dispatch, INCLUDING the inline path's submodule safety gate (#2772 / #2285 finding 1).
  • files_modified overlap → separate sequential stages — the same overlap rule execute-phase already applies inline (step 1 of the wave loop).
  • resumeFromRunId — pass summary.resumeRunId as the Workflow tool's resumeFromRunId INPUT when you invoke the tool. It is a tool parameter, not a script function; the script deliberately does not call it (#2590 — doing so threw "resumeFromRunId is not defined" and rejected the entire script). Omitting it from the tool invocation silently regresses phase-resume to a no-op: an interrupted phase re-runs completed plans.

After the run: manifest bridge into the merge chain (#3302)

The single Workflow tool call replaces step 3's per-plan Agent() loop — which also means step 3's manifest bookkeeping (creation + per-agent recording) does NOT happen on this path. The orchestrator MUST bridge the run's per-agent results into the SAME manifest-scoped merge chain inline dispatch uses, before steps 4–5.8, which then run unchanged:

  1. Create the manifest BEFORE invoking the tool (this is step 3's creation block, which this path skips). When ANY plan in the wave has use_worktree not false:

    if [ -z "${WAVE_WORKTREE_MANIFEST:-}" ]; then
      M=$(mktemp "${TMPDIR:-/tmp}/gsd-worktree-wave-XXXXXX") && mv "$M" "$M.json" && WAVE_WORKTREE_MANIFEST="$M.json" || exit 1  # XXXXXX must be path-final on BSD/macOS (#1520)
      # Persist the dispatch-time orchestrator worktree root so wave-cleanup pins back
      # to the orchestrator's OWN worktree (#630), exactly as inline dispatch does.
      ORCH_ROOT=$(git rev-parse --show-toplevel)
      ORCH_ROOT="$ORCH_ROOT" MANIFEST="$WAVE_WORKTREE_MANIFEST" node -e 'const fs=require("fs");fs.writeFileSync(process.env.MANIFEST,JSON.stringify({orchestrator_root:process.env.ORCH_ROOT||null,worktrees:[]})+"\n")'
      export WAVE_WORKTREE_MANIFEST
    fi
    
  2. Invoke the Workflow tool with the emitted script and resumeFromRunId: summary.resumeRunId. The script top-level returns one entry per dispatched plan: { plan, expects_worktree, metadata }. metadata is that plan's executor <worktree_metadata> JSON ({agent_id, worktree_path, branch, expected_base} — captured by the executor itself per agents/gsd-executor.md), or null when the agent's result carried none (interrupted agent, resumed-from-cache plan, or a non-worktree plan).

  3. Record every worktree plan exactly as inline dispatch does at step 3's "After each Agent() returns" — one worktree.record-agent per returned entry with expects_worktree: true and complete metadata:

    gsd_run query worktree.record-agent --manifest "$WAVE_WORKTREE_MANIFEST" \
      --agent-id "<metadata.agent_id>" --path "<metadata.worktree_path>" \
      --branch "<metadata.branch>" --base "<metadata.expected_base>" \
      --files "<plan files_modified, space-separated>" \
      --deletions "<plan files_deleted, space-separated>"
    

    --deletions (#3003) carries the plan's declared files_deleted so a plan that scoped a file removal merges through cleanup-wave instead of being blocked. Unlike --files it is not advisory: omitting it leaves the deletions guard blocking on any deletion at all, so this dispatch path must pass it or plans declaring a removal fail to merge here while succeeding on the inline path.

    The verb's write-strict validation applies as inline: on a non-zero exit or any missing field, stop and ask for recovery — do not append an under-populated entry.

  4. HALT on uncapturable metadata — never a silently-empty manifest (#3302). After recording, the manifest must hold one entry per expects_worktree: true outcome (summary.worktreePlans from resolve-wave-dispatch is the expected count). Any shortfall — a null metadata, a missing/empty field, or a count mismatch — means commits are stranded on their worktree-wf_* branches and worktree.cleanup-wave would merge nothing while the phase looks green. STOP the phase with the failing plan id and the recovery hint below; do NOT run worktree.cleanup-wave and do NOT proceed to step 4.

    Recovery hint: the unmerged worktree-wf_* branch still holds the work. Recover the missing metadata from the run's per-agent result journal (journal.jsonl — one {"type":"result",…} line per agent — in the Workflow run's transcript dir), re-run worktree.record-agent by hand, then re-run cleanup. If the journal cannot be recovered either, merge the branch manually after review — never discard it.

  5. Resume (resumeFromRunId). Cached/resumed agents do not re-emit their final messages, so a previously-completed plan can return with metadata: null. Recover that plan's metadata from the ORIGINAL run's journal (same hint as above). If it cannot be recovered, fail loudly per rule 4 — a resumed run must never report success over silently-dropped agent work.

  6. Non-worktree plans (expects_worktree: false — use_worktree: false in the manifest): they ran without isolation; their commits are already on the main working tree. No record-agent entry, no manifest write.

With the manifest populated, steps 4–5.8 (wait/completion bookkeeping, step 5.5's manifest-scoped worktree.cleanup-wave, post-merge gate, tracking update) run UNCHANGED — the Workflow backend replaces HOW agents are spawned and returns their metadata; the merge chain itself is the inline path's own, now with real input.

If backend == "inline" (any gate miss, or resolve-wave-dispatch itself unavailable/erroring): proceed to step 3's standard per-message Agent() dispatch — the default, byte-identical-to-today path. onError: skip on this contribution means a resolve-wave-dispatch command failure is treated exactly like an inline result, never as a fatal wave error.

Fallback contract

Detection is fail-closed end-to-end: capability disabled, non-Claude runtime, execution_backend:"inline", missing/incapable host descriptor, unknown or below-floor Agent SDK version, or an emitWorkflowScript failure on a malformed wave manifest — ANY of these degrades to backend:"inline" and execute-phase's standard inline dispatch (step 3) runs unmodified. The Workflow backend never partially activates; the executor MUST NOT assume parallelism, a shared budget, or resume-from-run-id semantics when backend == "inline".