Deft directive swarm

From deftai/directive · View interactive version

Deft directive swarm is an AI agent skill from the GitHub repository deftai/directive. Parallel local agent orchestration. Use when running multiple agents on story-level xBRIEFs simultaneously — to scan active/ for allocatable work, set up isolated worktrees, launch agents with proven prompts, monitor progress, handle stalled review cycles, and close out PRs cleanly.

How to use this skill

Skill file

<!-- AUTO-GENERATED by task packs:render -- DO NOT EDIT MANUALLY -->

<!-- Purpose: rendered skill -->

<!-- Source of truth: packs/skills/skills-pack-0.1.json -->

<!-- Regenerate with: task packs:render -->

<!-- Edit the source, not this file. Slice instead of loading every SKILL.md: task packs:slice skills by-trigger --trigger <kw> (or list) -->

Deft Directive Swarm

Structured workflow for a monitor agent to orchestrate N parallel local agents working on story-level xBRIEFs from xbrief/active/.

Legend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.

⚠️ See also: swarm.md | deft-directive-review-cycle

Platform Requirements

! This skill requires GitHub as the SCM platform and the GitHub CLI (gh) to be installed and authenticated. Issue fetching, PR creation, and post-merge verification all depend on gh.

Branch-Protection Policy Guard

! Before any state mutation (creating worktrees, dispatching sub-agents, opening PRs), run the skill-level branch-policy guard (#746 / #747). Halt with the actionable disclosure message when the project's plan.policy.allowDirectCommitsToMaster is unresolvable AND DEFT_ALLOW_DEFAULT_BRANCH_COMMIT is unset:

deft verify:branch || exit 1

The swarm skill creates branches per agent so the guard is mostly informational here, but a malformed PROJECT-DEFINITION (missing plan.policy block AND no legacy narrative) is a fail-closed signal worth surfacing before the swarm spawns N agents.

Forge-outage drop-back (#3422)

! On attributed platform outage or repeated REST 429/502/503: drop GitHub I/O, report once to the human in chat, and re-probe on plan.policy.forgeOutageRetryMinutes (default 30; USER.md Personal wins; min 5; task policy:show --field=forgeOutageRetryMinutes). Local work that does not need the forge MAY continue. Depth: CODE2 § #3180 / #3422. Complements #3167 / #3180.

⊗ Tight retry, empty-commit thrash, or sending the human to github.com as the only remediation.

⊗ Auto-merge / --skip-ci because a status page is red.

Deterministic Questions Contract

! Every numbered-menu prompt rendered in this skill (Phase 0 Step 0 queue-driven promote prompts (#1142 / N2), Step 0.5 bridge approval gate, Step 5 final-approval gate, Phase 1 Step 3 file-overlap audit gate, Phase 5->6 ready-to-merge gate) MUST follow CODE0: render the canonical numbered menu in chat unless the host UI visibly preserves numeric option labels and returns numeric selections or exact displayed option text. The final two numbered options MUST be Discuss and Back, in that order. The Discuss-pause semantic is documented verbatim there -- on Discuss selection the agent MUST halt the in-progress sequence immediately, prompt What would you like to discuss?, and resume only on an explicit user signal. Implicit resumption is forbidden, and fallback chat replies MUST map only to the displayed number or exact displayed option text.

When to Use

Prerequisites

Host-adapter load path (#2928)

Large multi-host skills use a host-neutral core plus one per-host adapter after detect.

| Step | Action |

|------|--------|

| 1 | Read this thin SKILL (triggers, MUST gates, detect, route table) |

| 2 | Run Runtime Capability Detection (below) → stable platform descriptor |

| 3 | Load host-neutral depth: references/core-phase-*.md + references/core-ops.md as needed for the current phase |

| 4 | Load exactly one references/host-*.md from the route table |

| 5 | Launch / monitor / hand off using core + that adapter only |

Route table (detect → one adapter)

| Detected descriptor | Spawn primitive | Load adapter |

|---------------------|-----------------|--------------|

| warp-orchestrated / warp-manual | start_agent / Warp tabs | CODE3 |

| cursor-composer / cursor-cloud-agent | Cursor Task | CODE3 |

| claude-code | Claude Agent (run_in_background) / claude-agent | CODE4 |

| openclaw | sessions_spawn | CODE2 |

| grok-bot | Task / executor / CloudAgent (grok-bot-executor) | CODE2 |

| grok-build | spawn_subagent | CODE2 |

| generic-terminal (or explicit cloud) | serial / paste / oz agent run-cloud | CODE2 |

Core reference index (host-neutral)

| Phase / topic | File |

|---------------|------|

| Phase 0 — Allocate | CODE0 |

| Phase 1–2 — Select + Setup | CODE0 |

| Phase 3 — Launch (neutral + detect detail) | CODE0 |

| Phase 4 — Monitor | CODE0 |

| Phase 5–6 — Review + Close | CODE0 |

| Crash recovery, prompts, anti-patterns | CODE0 |

! Grok through-merge Phase 0 / Phase 3 launch (#4529 / #4821 / #5219 / #5229): dest-cwd class A residual first, stop-at after the push; then Approach 1 wait owner is a spawn_subagent review-monitor sibling (register + child-bound pr:watch --monitor-agent-id + verify:review-monitor --merge-path-arm --live-wait); then parent-retained closer after CLEAN. Approach 1 is the cheapest admitted babysit vs host monitor / bare shell watch (#5229); stamp host capability before CLI verify (writeHostCapabilityStamp / references/host-grok-build.md). Prefer the Approach 1 babysitter one-liner (formatApproach1CheapestAdmissionCard) over a parent-shell pr:watch. This card wins over Phase 0 / Phase 3 depth rows that still name Approach 1 sibling or parent-retained as the first partner. ⊗ Choose Approach 1 sibling or parent-retained without dest residual. ⊗ Arm merge-path with parent-shell pr:watch / host monitor alone when spawn_subagent is available. Depth: Envelope selection SLA; Phase 5–6 CODE10.

⊗ Load all host adapters “just in case.” Unused host wiring stays out of context (#2928).

≉ Paste full host manuals into this thin SKILL — keep detect short; depth lives in one adapter.

Hard gates (all hosts)

Solo-worker launch path (#3032 / #3669)

! #3032 solo-worker launch path = this skill's interactive path: Phase 0 default when no pre-approved cohort; Mode B worktrees (.deft-scratch/worktrees/<story-id>); envelope dispatch_kind: solo. Through-merge / N=1 still uses this path — not parent-as-leaf. Depth: CODE2, CODE3, CODE4.

! Sliced leans at ingest (#7085): when a story's accepted arc lean has a ## Slices section, ingest each slice from its own child issue (deft-slice: #<parent> <label> in the body); each slice is its own brief, worktree and product PR. The parent ingests only the items with no label and refuses when every item has one. Recipe: commands.md § Sliced leans (#7085).

! Headless task swarm:launch is the opt-in concurrent fast-path. task swarm:readiness exit 0 gates concurrent workers only. swarm:launch may emit dispatch_kind: solo for a single ungrouped story only after concurrent-ready gates pass.

! N=1 sequential swarm:launch mode is declined for first ship (#3669); multi-story sequential / fileOverlaps / conflict-group sequencing stays out of scope.

⊗ Treat closed #3666 as having discharged this discoverability debt (Gate A pointer ≠ AGENTS/commands/SKILL naming).

⊗ Invent a greenfield solo-worker CLI verb as the first remedy; ⊗ conclude no sanctioned solo path exists when swarm:launch / readiness refuses.

Proceed — no scope ceremony (#4956)

! After operator proceed on a cohort, do not schedule scope:record-approved-scope / mint stops. Fence is merge-base brief file_scope; depth: CODE2 § Proceed and scope ceremony, docs/scope-provenance.md.

⊗ Mid-cohort leave-harness mint or remint for proceed / file_scope growth (#4956).

! Changelog story scope (#6315): a story that adds a changelog entry lists its own concrete fragment path changelog.d/<issue>-<slug>.md in file_scope (mode either / fragments), not CHANGELOG.md or the changelog.d/ directory. swarm:readiness is unchanged: a shared path, directory or glob still overlaps. Depth: content/scm/changelog.md.

Worktree isolation before parallel spawn

! One isolated git worktree per parallel agent (Phase 2). Create worktrees or consume a worktree-map before dispatch.

! Before you start any implementation worker, run swarm:pre-dispatch -- --scope-id <story> --target-id <worktree> (begin); it also binds that worktree to its story, so the worker's commits are admitted (#6379).

! On OpenClaw, parallel leaves: worktree or worktree-map before sessions_spawn; worker cwd = that worktree; fail loud if the cohort would share the repo root (#2929). Full rules: CODE1.

⊗ DIY multi-leaf sessions_spawn without worktree prep (#2929).

Dest leaf ceremony (#5145)

! Dest through-merge / worktree leaves still need their own ritual — primary checkout ritual does not satisfy dest hooks.

! When dest .deft/ritual-state.json already exists, prefer session:start --rearm (maintainer: task session:start -- --rearm) over a full cold start — dest rearm Prefer-A when primary ritual top-level finalize_owed is already recorded (no dest --defer-owed required).

! Linked dest Prefer-A inherits primary top-level finalize_owed (deferred or ok). --rearm alone on primary/main still scans unless --defer-owed=<reason> is set. Keep --defer=cache_fresh=… soft paths. Standalone linked worktrees without a primary finalize_owed record still fail-closed.

⊗ Stampede N dest cold tip inventories before primary records finalize_owed / before Prefer-A is on tip. Depth: templates/agent-prompt-preamble.md §12.

! Owed completions are reported, not refused (#6409): every mutation session:start (cold / --rearm) runs the inventory, and owed rows, unknown included, never refuse a leaf. The always-on finalize owed report: line gives the count and names deft swarm:finalize-owed (the cleanup entry point; one run need not clear every row). Only an unresolvable repository still refuses; --defer-owed clears that and is otherwise only recorded. Owners still pass verify:orphan-active / verify:completed-tracked before DONE.

Next-phase tool dispatch (#2934)

! After a coding cohort completes (last expected child completion / cohort phase boundary), the parent MUST in the same turn either:

⊗ End the turn with only narrative “I will spawn…” / “review next” and zero tools (#2934).

~ Keep a small phase-state note: cohort_id → phase → next_action|terminal.

Parent-monitor after leaf announce (#2943 / hard-stop #3131)

! After any leaf completion event (subagent_announce / parent-push / host completion notify), the parent’s first response MUST be one of:

! Hard-stop (machine-checkable, not prose-only): MUST NOT emit N>2 near-identical assistant sentences (or streaming text chunks) in one turn with no tool_use / yield — FC14 text-repetition hang. Library: evaluateParentTurnShape in @deftai/directive-core/parent-turn-shape (packages/core/src/parent-turn-shape/). Hosts SHOULD abort the turn when ok === false. Operator recovery: docs/openclaw-agent-host.md § Operator recovery — FC14. Soft skill text is not sole mitigation (#3131).

! Thin DONE = failed leaf: completion without PR URL / merge evidence is failed (re-dispatch or take over) — not success. Prefer structured fields when present (prUrl, mergeStatus, emptyDiff).

⊗ Multi-sentence progress-only first response after announce with zero tools / yield (#2943 text-repetition hang).

⊗ N>2 near-identical assistant sentences with no tool_use / yield (FC14 / #3131 hard-stop).

⊗ Treat thin DONE (no PR URL / merge evidence) as success (#2943).

⊗ Rely on soft skill prose alone as the sole mitigation for the parent hang (#3131).

Completion latch after first consolidate (#3092)

! After the parent emits one user/caller-visible consolidate for a child runId / settle batch, identical or equivalent completion replay for the same key MUST be silent (no tools, no re-QC, no second final; host silent token when defined, e.g. OpenClaw NO_REPLY). Re-open only on new runId/batch, principal explicit reopen, or materially new evidence (new HEAD, new blocker class). Replay storms: at most one fail-loud note, then silent. Full MUST: templates/agent-prompt-preamble.md §11.5. Depth: references/core-phase-5-6.md. Orthogonal to empty settle ≠ done (#3044).

Dual stop — repair and monitor loops (#2442)

! Multi-iteration swarm repair and monitor loops MUST carry dual stop: success (goal/AC/clean gate) and a failure/budget stop. Single-turn probes (one status check, one heartbeat read) are exempt. Principle: main.md ## Dual Stop Rule (#2442). Defaults and halt-report shape live in CODE2 (monitor / takeover) and CODE3 (prompts + anti-patterns).

! Default failure envelope for repair/monitor class work (unless the operator or xBRIEF names a stricter one):

! On failure stop: halt automatic continuation; emit an operator-visible report (what was tried, what is missing, what human decision is needed). ⊗ Silent re-dispatch or infinite monitor continuation after the envelope is exhausted.

! Halt-report resume line (MUST, #3273 / #3448): Terminal dual-stop / hard-stop / conf-residual halt reports MUST end with leftover class (A/B/C) + residual class + conf (if any) + resolved #3095 floor + standing vs one-shot + PR URL (leftover= / floor= / standing=). One-shot phrases: pursue residual | follow-up hard-stop | same as conf-hold | continue dual-stopped PR. Standing phrases: until floor or loop | until greptile meets policy | pursue residuals until told otherwise. Pointer to § Operator follow-up after dual-stop / hard stop. Full template: CODE4.

! Composes with minimal-subgraph repair guidance (#2439): keep repairs minimal and bounded by dual-stop -- minimal repair is not a license to thrash. Durable delivery/acceptance circuit-breaker: #3143 packages/core/src/delivery-attempt/ (evaluatePreDispatch, unit ledger). Docs: docs/delivery-attempt.md. Skill defaults remain behavioral; mechanical gate lives in core.

Envelope selection SLA (#3153 / #4529)

! Default story / through-merge envelope is drive-to: merge-ready. Depth: CODE1.

! Grok through-merge: implement leaf MUST be stop-at: pr-open. Named leftover (class A) requires dest-cwd one-shot residual, stop-at after the push; Approach 1 remains wait owner (pr:watch + verify:review-monitor / review-monitor:register); parent-retained is closer plus post-merge scope:complete after that dest worker exists. Phase 6 monitor squash-merges via pr:wait-mergeable-and-merge (or parent-retained) only after CLEAN. swarm:finalize-cohort is leftover after merge. Dest spawn deny is BLOCKED or dest-cwd residual via native implementation-capable spawn (#4215) — not parent-primary. ⊗ Send class-A residual through process-only CLI grok --cwd (cannot edit/push). ⊗ Harvest a Grok drive-to: merge-ready continuation as that partner. ⊗ Parent-inline residual when dest spawn is available. ⊗ Use merge-release as this closer. ⊗ Claim swarm:finalize-cohort is the product squash-merge. Related: #4421. #4821.

! Cohort closer (#7082): in a cohort, a worker tries task scope:complete -- <active-path> --in-pr first (#6277); if refused, it stops at product merge with deft-story: N. The parent, as cohort closer, runs one task swarm:finalize-cohort -- --pr <merged only> --cohort <ids> (one lifecycle PR, no changelog fragment), keeps every named left-active story (unmerged, omitted or refused) for a later run, and owns each story until verify:completed-tracked and verify:orphan-active pass. A solo story keeps worker-owned completion. Depth: CODE5.

! Fresh-clone completed land (#4714): Before swarm:launch, each selected active brief MUST exist on fetched origin/<deliveryBranch> (human-reviewed activation PR). After product merge, Phase 6 swarm:finalize-cohort lands terminal briefs via a lifecycle PR; if the isolated delivery checkout lacks the active brief, it may materialize only exact bytes that match a reachable reviewed product/evidence blob from a retained dest — otherwise fail closed with source-recovery. Expected scoped closing refs without active/terminal records are not #2247 incidental skips. verify:completed-tracked -- --issue N on the fetched delivery tip is the close proof. ⊗ Treat GitHub-closed alone as DONE. ⊗ Copy a whole xbrief/ tree into the lifecycle checkout.

! Wait-merge is squash-after-CLEAN (#4822): Phase 5 babysit wait is pr:watch. Phase 6 pr:wait-mergeable-and-merge runs only after CLEAN. First-probe parse of clean_gate_holdout; SHA-matched confidence plus class A leftover is dest residual or BLOCKED, not cap-wait. sha_match stays blocking pr:watch. ⊗ Invent a third poller. ⊗ Harvest cascade.ts. ⊗ Recut #4821 dest-worker ownership. #4820 stays CLEAN-plus-SLizard/CI.

! Durable live wait after stop-at:pr-open (#4882): The Approach 1 wait owner or parent-retained closer MUST keep a still-running phase-correct wait for each open merge-path PR until CLEAN or an explicit option-C finish. Fresh sticky lease alone or Path B promise without a live wait is unarmed stand-down. Probe: task verify:review-monitor -- --pr <N> --merge-path-arm with --live-wait / --explicit-finish. Multi-PR cohort inventory: task verify:cohort-review-monitors -- --prs <csv> (#5318); swarm:verify-review-clean CLEAN ≠ inventory green. pr:watch --json wrappers MUST parse full stdout (pretty multi-line valid); line-split misses CLEAN (#5015). Prefer Approach 1 / native pr:watch.

⊗ Stand down unarmed on an open merge-path PR, or treat lease-only / homemade line-parsed pr-watch --json as armed (#4882).

Operator follow-up after dual-stop / hard stop (#3273)

Operator-initiated resume after dual-stop / hard stop / conf-hold — not automatic re-thrash. Depth (A/B/C leftover classes, standing vs one-shot, steps): CODE0 same section title. Portable consumer + maintainer (task / deft dual-invoke). Continue-until target is the resolved #3095 floor (task policy:show --field=minGreptileConfidence / deft policy:show --field=minGreptileConfidence: typed project policy > framework dogfood 5 > consumer default 4). ⊗ Hard-code 5/5. ⊗ Lower project policy to clear one PR.

Leftover classes (A/B/C, #3448): class A named leftover on already-touched files = in-AC residual, auto-continue under standing until floor or same-fingerprint loop. class B new subsystem / AC fight = park or follow-up. class C score-only = document / same-as-conf-hold. Already-touched leftover is class A unless it needs a new ledger/protocol/story (#2881).

One-shot vs standing: one-shot pursue residual = one pass then re-stop. Standing (until floor or loop / until greptile meets policy / pursue residuals until told otherwise) applies to open cohort / ordered-plan units, not only the last halted PR. Same-fingerprint stop: CODE4 Dual stop (normative). #2442 batch cap still applies.

Thin pointer: dual-invoke pr:merge-ready / pr:watch; spawn one residual worker or review-cycle owner per batch; document authorized conf floor for this PR only as human-merge/override trail (⊗ silent policy rewrite; pr:merge-ready still uses policy floor). ⊗ Unlimited auto-retry. ⊗ Parent self-implement (#2843).

Runtime Capability Detection (summary)

! Before selecting a launch method, probe the environment. Full probe text: CODE0.

  1. ! Probe for start_agent tool — Warp orchestrated.
  2. ! Probe for Warp environment — WARP_* without start_agent → warp-manual.
  3. ! Probe for the Cursor Task tool — Tier 1; descriptor cursor-composer / cursor-cloud-agent (#1877). Require Cursor signals (CURSOR_* or Cursor-only Task surface) — not bare Task alone.
  4. ! Probe for Claude Code — Tier 1; descriptor claude-code (#3134). Claude-unique signals only: Agent (or CreateAgent / SubagentStart) with background / run_in_background, and/or DEFT_PROBE_CLAUDE_CODE / DEFT_AGENT_RUNTIME=claude-code / CLAUDECODE. ⊗ Misclassify as cursor-composer via bare Task.
  5. ! Probe for the OpenClaw sessions_spawn tool — Tier 1; descriptor openclaw (#2875). Do NOT misclassify as grok-build or generic-terminal.
  6. ! Probe for Grok Bot — Tier 1; descriptor grok-bot (#4201). Unique signals only: question widgets, Task/executor/CloudAgent, routines, short main-chat beats, and/or DEFT_PROBE_GROK_BOT / DEFT_HAS_GROK_BOT_WIDGETS / DEFT_HAS_GROK_BOT_EXECUTOR / DEFT_AGENT_RUNTIME=grok-bot / GROK_BOT. Probe before spawn_subagent. ⊗ Misclassify as grok-build via bare spawn_subagent. ⊗ Misclassify as cursor-composer via bare Task.
  7. ! Probe for spawn_subagent tool — descriptor grok-build.
  8. ! Select launch path automatically — load the matching host adapter (route table). No static A/B/C menu.
  9. ! Return a stable platform descriptor for Phase 4/6: warp-orchestrated, warp-manual, cursor-composer, cursor-cloud-agent, claude-code, openclaw, grok-bot, grok-build, or generic-terminal.
  10. ? Cloud escape hatch — oz agent run-cloud only on explicit user request (host-generic).

⊗ Present static launch options instead of detecting capabilities at runtime.

⊗ Offer Warp-specific launch paths when not inside Warp.

⊗ Classify Claude Code as cursor-composer / generic-terminal when Claude-unique signals are present (#3134).

⊗ Classify Grok Bot as grok-build via bare spawn_subagent, or as cursor-composer via bare Task, when Grok-Bot-unique signals are present (#4201).

Retained addressable sub-agents (#3158)

Named mode beside dispatch-and-collect. Canon: CODE0 ## Retained addressable sub-agents (#3158).

| Mode | When | Mid-scope gate |

|------|------|----------------|

| retained-child (message-later / steer-mid-flight) | Host keeps a live, addressable child (agent_id / session name); parent can re-message or steer mid-flight | Single dispatch MAY pause for approval and continue the same child |

| dispatch-and-collect (one-shot) | Host has no continue/resume; worker terminal on tool-loop exit | Split-dispatch mandatory (#954): Scope A → report → approve → Scope B |

! After platform detect, read the loaded host adapter's Retained / continue-by-id note. Prefer continue-by-agent-id / resume-by-name / steerable mid-flight only when that adapter documents support.

! When the host cannot retain: keep one-shot envelopes and split-dispatch mid-scope gates. Do not claim message-later semantics the platform cannot deliver.

! Stance (#3164): retention is orchestration only — not mid-run constitution self-edit (managed AGENTS, pinned skills, policy).

! Topology (#3155): retained children MUST obey nuclear-family A2A bounds (parent/sibling/child only).

⊗ Force a second full dispatch on a retain-capable host solely because a mid-scope gate exists — re-message the live child instead.

⊗ Invent retain / resume on hosts whose adapter marks one-shot only.

Phase overview

| Phase | Goal | Depth |

|-------|------|-------|

| 0 Allocate | Queue cohort, readiness, approval | core-phase-0.md |

| 1 Select | Confirm candidates, file-overlap | core-phase-1-2.md |

| 2 Setup | Worktrees + prompt files | core-phase-1-2.md |

| 3 Launch | Detect, preflight, one host spawn | core-phase-3.md + one host-*.md |

| 4 Monitor | Heartbeats, takeover, no duplicate agents | core-phase-4.md (+ host notes) |

| 5 Review | Greptile clean, gates, next-phase tools | core-phase-5-6.md |

| 6 Close | Merge cascade, cohort sweep, cleanup | core-phase-5-6.md |

! Follow phases in order. Depth files hold the operative MUST rules; this page is the dispatch card.

Effort estimate on dispatch (#1581)

! When plan items carry optional effort (S/M/L/XL with time anchors in vbrief/vbrief.md), use them for sizing: S/M single-agent, L may need a dedicated agent, XL blocks dispatch until broken into S/M/L. Activate fails closed on XL. Depth: CODE2 Steps 2–3.

! Plan-item effort is post-planning (confirms/corrects provisional intake estimates). It is not session-start ritual input; ceremony dial (#3214) starts rapid and escalates — do not block cold-start ritual on missing plan-item effort. Headless: no operator confirmation for size or stage transitions.

Critical anti-patterns (dispatch card)

Full anti-pattern list: CODE0.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.