pi-spine 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/bin/spine-batch.mjs +3 -2
  2. package/bin/spine.mjs +12 -0
  3. package/extensions/spine/slash-commands.ts +170 -1
  4. package/package.json +6 -3
  5. package/skills/spine-orchestrate-waves/SKILL.md +200 -0
  6. package/skills/spine-orchestrate-waves/references/outer-loop.md +165 -0
  7. package/skills/spine-release-operator/SKILL.md +341 -0
  8. package/skills/spine-release-operator/references/issue-intake-checklist.md +107 -0
  9. package/skills/spine-release-operator/references/issue-template.md +51 -0
  10. package/skills/spine-release-operator/references/release-manifest-template.md +76 -0
  11. package/skills/spine-release-operator/references/release-profiles.md +100 -0
  12. package/src/batch/batch-state-io.mjs +137 -0
  13. package/src/batch/contract-prelanded.mjs +116 -14
  14. package/src/batch/contract-verify.mjs +26 -2
  15. package/src/batch/diagnosis-alternatives.mjs +8 -0
  16. package/src/batch/diagnosis.mjs +28 -2
  17. package/src/batch/engine.mjs +10 -1
  18. package/src/batch/integrate-worktree.mjs +65 -15
  19. package/src/batch/lane-dirty-check.mjs +6 -1
  20. package/src/batch/lifecycle.mjs +10 -6
  21. package/src/batch/reconcile.mjs +254 -0
  22. package/src/batch/state.mjs +18 -1
  23. package/src/cli/batch-complete.mjs +16 -0
  24. package/src/cli/sync-base.mjs +354 -0
  25. package/src/config/defaults.mjs +8 -1
  26. package/src/config/spine-preflight-lib.mjs +146 -2
  27. package/src/doctor/agents-model-inherit.mjs +318 -0
  28. package/src/doctor/run-doctor-checks.mjs +14 -0
  29. package/templates/spine-config.json +4 -0
  30. package/templates/spine-worktree-setup-flutter.sh +44 -0
@@ -7,7 +7,8 @@ import {
7
7
  resumeBatchDetached,
8
8
  startBatchDetached,
9
9
  } from "../src/batch/detached-start.mjs";
10
- import { completeBatch, dismissBatch } from "../src/batch/lifecycle.mjs";
10
+ import { dismissBatch } from "../src/batch/lifecycle.mjs";
11
+ import { runBatchComplete } from "../src/cli/batch-complete.mjs";
11
12
  import { forceMergeWave, startBatch } from "../src/batch/engine.mjs";
12
13
  import { parseBatchStartWaveFilter } from "../src/planner/wave-scope.mjs";
13
14
  import { pauseBatch } from "../src/batch/pause.mjs";
@@ -238,7 +239,7 @@ export async function runSpineBatch(options) {
238
239
  }
239
240
 
240
241
  if (parsed.subcommand === "complete") {
241
- const result = completeBatch({
242
+ const result = runBatchComplete({
242
243
  projectRoot,
243
244
  batchId: parsed.batchId,
244
245
  detectManualMerge: parsed.detectManualMerge,
package/bin/spine.mjs CHANGED
@@ -88,6 +88,13 @@ async function cmdDashboard(args) {
88
88
  if (result.exitCode !== 0) process.exit(result.exitCode);
89
89
  }
90
90
 
91
+ async function cmdSyncBase(args) {
92
+ const { runSpineSyncBase } = await import("../src/cli/sync-base.mjs");
93
+ const result = runSpineSyncBase({ projectRoot: process.cwd(), args });
94
+ process.stdout.write(result.output ?? "");
95
+ if (result.exitCode !== 0) process.exit(result.exitCode);
96
+ }
97
+
91
98
  async function cmdVerify(args) {
92
99
  const { runSpineVerify } = await import("./spine-cli/verify.mjs");
93
100
  const result = runSpineVerify({ projectRoot: process.cwd(), args });
@@ -260,6 +267,7 @@ ${c.bold}Commands:${c.reset}
260
267
  ${c.cyan}report progress${c.reset} Emit task.step_completed to batch journal (FR-WORK-09)
261
268
  ${c.cyan}gate${c.reset} Inspect or resolve integrate gate (FR-GATE)
262
269
  ${c.cyan}integrate${c.reset} Merge orch branch into base (FR-INT-01)
270
+ ${c.cyan}sync-base${c.reset} Sync human checkout after isolated integrate (FR-WT-08)
263
271
  ${c.cyan}verify${c.reset} Phase exit verification checklists
264
272
  ${c.cyan}journal${c.reset} Replay orchestration journal timeline
265
273
  ${c.cyan}state${c.reset} Validate batch-state cache schema
@@ -317,6 +325,7 @@ ${c.bold}Examples:${c.reset}
317
325
  spine report progress --step N # journal step progress (worker shell-out)
318
326
  spine gate [approve|reject|status] # integrate gate FSM
319
327
  spine integrate [--dry-run] [--force-integrate] # merge orch branch into main
328
+ spine sync-base [--dry-run] [--json] # sync checkout after isolated land
320
329
  spine journal replay --batch 20260601T120000 # audit timeline for a batch
321
330
  spine state validate # validate active batch-state.json
322
331
  spine next # suggested next command (dry-run)
@@ -418,6 +427,9 @@ if (isCliEntrypoint(import.meta.url)) {
418
427
  case "integrate":
419
428
  await handleIntegrate(args);
420
429
  break;
430
+ case "sync-base":
431
+ await cmdSyncBase(args);
432
+ break;
421
433
  case "verify":
422
434
  await cmdVerify(args);
423
435
  break;
@@ -29,6 +29,7 @@ export const SPINE_SLASH_COMMAND_NAMES = [
29
29
  "spine-dashboard",
30
30
  "spine-validate",
31
31
  "spine-handoff",
32
+ "spine-orchestrate",
32
33
  ] as const;
33
34
 
34
35
  type SpineSlashCommandName = (typeof SPINE_SLASH_COMMAND_NAMES)[number];
@@ -108,6 +109,11 @@ const SPINE_SLASH_COMMANDS: SpineSlashCommandSpec[] = [
108
109
  name: "spine-handoff",
109
110
  description: "Write operator handoff note (usage: /spine-handoff [--batch ID])",
110
111
  },
112
+ {
113
+ name: "spine-orchestrate",
114
+ description:
115
+ "Multi-wave outer loop checklist from plan (usage: /spine-orchestrate [pending|all] [--from-wave N])",
116
+ },
111
117
  ];
112
118
 
113
119
  function runSpinePreflight(cwd = process.cwd()) {
@@ -149,11 +155,14 @@ function runSpineDeps(argsText: string, cwd = process.cwd()) {
149
155
  };
150
156
  }
151
157
 
152
- function runSpinePlan(argsText: string, cwd = process.cwd()) {
158
+ function runSpinePlan(argsText: string, cwd = process.cwd(), { json = false } = {}) {
153
159
  const tokens = String(argsText ?? "")
154
160
  .trim()
155
161
  .split(/\s+/)
156
162
  .filter(Boolean);
163
+ if (json) {
164
+ tokens.push("--json");
165
+ }
157
166
 
158
167
  const result = spawnSync(
159
168
  process.execPath,
@@ -171,6 +180,131 @@ function runSpinePlan(argsText: string, cwd = process.cwd()) {
171
180
  };
172
181
  }
173
182
 
183
+ interface OrchestratePlanWave {
184
+ index: number;
185
+ taskIds?: string[];
186
+ }
187
+
188
+ interface OrchestratePlan {
189
+ scope?: { mode?: string };
190
+ waves?: OrchestratePlanWave[];
191
+ tasks?: Record<string, { title?: string | null }>;
192
+ metadata?: { tasksSelected?: number; tasksExcluded?: number };
193
+ }
194
+
195
+ /** Parse `/spine-orchestrate` args: scope (pending|all) and optional --from-wave N. */
196
+ export function parseSpineOrchestrateArgs(argsText: string) {
197
+ const tokens = String(argsText ?? "")
198
+ .trim()
199
+ .split(/\s+/)
200
+ .filter(Boolean);
201
+
202
+ let scope = "pending";
203
+ let fromWave = 0;
204
+
205
+ for (let index = 0; index < tokens.length; index += 1) {
206
+ const token = tokens[index];
207
+ if (token === "--from-wave") {
208
+ fromWave = Number(tokens[index + 1]);
209
+ index += 1;
210
+ continue;
211
+ }
212
+ if (!token.startsWith("--")) {
213
+ scope = token;
214
+ }
215
+ }
216
+
217
+ return { scope, fromWave };
218
+ }
219
+
220
+ function formatOrchestrateTaskLine(taskId: string, tasks?: OrchestratePlan["tasks"]) {
221
+ const title = tasks?.[taskId]?.title?.trim();
222
+ return title ? `${taskId} — ${title}` : taskId;
223
+ }
224
+
225
+ /** Build the structured orchestration prompt from a planner JSON plan. */
226
+ export function formatOrchestratePrompt(
227
+ plan: OrchestratePlan,
228
+ { scope, fromWave }: { scope: string; fromWave: number },
229
+ ) {
230
+ const waves = plan.waves ?? [];
231
+ if (waves.length === 0) {
232
+ const excluded = plan.metadata?.tasksExcluded ?? 0;
233
+ return [
234
+ "Spine orchestration — no waves in plan",
235
+ "",
236
+ `Scope: ${scope} · 0 wave(s)`,
237
+ excluded > 0 ? `${excluded} task(s) excluded (.DONE on disk)` : "",
238
+ "",
239
+ "No pending waves — all discovered tasks may be complete.",
240
+ "",
241
+ "→ spine plan all",
242
+ "→ /skill:spine-orchestrate-waves for full decision tree",
243
+ ]
244
+ .filter(Boolean)
245
+ .join("\n");
246
+ }
247
+
248
+ if (!Number.isInteger(fromWave) || fromWave < 0 || fromWave >= waves.length) {
249
+ return [
250
+ "Spine orchestration — invalid --from-wave",
251
+ "",
252
+ `--from-wave ${fromWave} is out of range (plan has ${waves.length} wave(s)).`,
253
+ "",
254
+ "→ spine plan pending",
255
+ ].join("\n");
256
+ }
257
+
258
+ const selectedWaves = waves.filter((wave) => wave.index >= fromWave);
259
+ const nextWave = selectedWaves[0];
260
+ const nextTaskIds = nextWave?.taskIds ?? [];
261
+
262
+ const lines = [
263
+ "Spine multi-wave orchestration",
264
+ "",
265
+ `Scope: ${scope} · ${waves.length} wave(s) · starting at wave ${fromWave}`,
266
+ nextWave
267
+ ? `Next wave: ${nextWave.index} · ${nextTaskIds.map((taskId) => formatOrchestrateTaskLine(taskId, plan.tasks)).join(", ")}`
268
+ : "",
269
+ "",
270
+ "## Wave plan",
271
+ "",
272
+ ];
273
+
274
+ for (const wave of selectedWaves) {
275
+ const taskIds = wave.taskIds ?? [];
276
+ lines.push(`Wave ${wave.index} · ${taskIds.length} task(s)`);
277
+ for (const taskId of taskIds) {
278
+ lines.push(` · ${formatOrchestrateTaskLine(taskId, plan.tasks)}`);
279
+ }
280
+ lines.push("");
281
+ }
282
+
283
+ lines.push(
284
+ "## Outer loop (per wave — you decide gate/integrate)",
285
+ "",
286
+ "1. spine preflight",
287
+ `2. spine batch start ${scope} --wave W --attached`,
288
+ "3. spine wait --until completed,needs_integrate,failed,aborted,needs_retry --timeout 4h",
289
+ "4. spine status --diagnose",
290
+ "5. spine gate status # review .spine/runtime/<batchId>/evidence/",
291
+ "6. spine gate approve # agent judgment — NOT auto-run by /spine-orchestrate",
292
+ "7. spine integrate",
293
+ "8. spine batch complete",
294
+ "9. git push origin <baseBranch> # when remote sync desired",
295
+ "",
296
+ "Repeat for the next wave after land loop completes.",
297
+ "This command does NOT auto-approve gates or auto-integrate.",
298
+ "",
299
+ "## Skill",
300
+ "",
301
+ "Load: /skill:spine-orchestrate-waves",
302
+ "Doc: docs/adoption/agent-orchestrated-waves.md",
303
+ );
304
+
305
+ return lines.filter((line, index, all) => !(line === "" && all[index - 1] === "")).join("\n");
306
+ }
307
+
174
308
  function runSpineBatchDismiss(argsText: string, cwd = process.cwd()) {
175
309
  const tokens = ["dismiss", ...String(argsText ?? "").trim().split(/\s+/).filter(Boolean)];
176
310
 
@@ -724,6 +858,39 @@ async function spineIntegrateHandler(args: string, ctx: ExtensionCommandContext)
724
858
  ctx.ui.notify(result.output || "integrate completed", "info");
725
859
  }
726
860
 
861
+ async function spineOrchestrateHandler(args: string, ctx: ExtensionCommandContext): Promise<void> {
862
+ const { scope, fromWave } = parseSpineOrchestrateArgs(args);
863
+
864
+ const preflight = runSpinePreflight();
865
+ if (!preflight.ok) {
866
+ ctx.ui.notify(
867
+ `Batch preflight failed — fix issues before orchestrating.
868
+
869
+ ${preflight.output}
870
+ `,
871
+ "error",
872
+ );
873
+ return;
874
+ }
875
+
876
+ const planResult = runSpinePlan(scope, process.cwd(), { json: true });
877
+ if (!planResult.ok) {
878
+ ctx.ui.notify(planResult.output || "spine plan failed", "error");
879
+ return;
880
+ }
881
+
882
+ let plan: OrchestratePlan;
883
+ try {
884
+ plan = JSON.parse(planResult.output) as OrchestratePlan;
885
+ } catch {
886
+ ctx.ui.notify(planResult.output || "spine plan returned invalid JSON", "error");
887
+ return;
888
+ }
889
+
890
+ const prompt = formatOrchestratePrompt(plan, { scope, fromWave });
891
+ ctx.ui.notify(prompt, "info");
892
+ }
893
+
727
894
  async function spineSettingsHandler(args: string, ctx: ExtensionCommandContext): Promise<void> {
728
895
  await runSpineSettingsSlash(args, ctx);
729
896
  }
@@ -800,6 +967,8 @@ export function registerSpineSlashCommands(pi: ExtensionAPI): void {
800
967
  ? spineValidateHandler
801
968
  : name === "spine-handoff"
802
969
  ? spineHandoffHandler
970
+ : name === "spine-orchestrate"
971
+ ? spineOrchestrateHandler
803
972
  : stubHandler(name),
804
973
  });
805
974
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -8,7 +8,9 @@
8
8
  "agent",
9
9
  "orchestration",
10
10
  "task-runner",
11
- "parallel"
11
+ "parallel",
12
+ "spine-orchestrate-waves",
13
+ "spine-orchestrate"
12
14
  ],
13
15
  "bin": {
14
16
  "spine": "bin/spine.mjs"
@@ -35,7 +37,8 @@
35
37
  "test:core": "SPINE_SUPPRESS_JOURNAL_ATTACH=1 node --experimental-strip-types --test tests/*.test.mjs tests/cli/*.test.mjs tests/compat/*.test.mjs tests/tasks/*.test.mjs tests/config/*.test.mjs tests/config/cursor-rules/*.test.mjs tests/planner/*.test.mjs tests/agents/*.test.mjs tests/adoption/*.test.mjs tests/dashboard/*.test.mjs tests/doctor/*.test.mjs tests/migrate/*.test.mjs tests/worker-tools/*.test.mjs tests/coverage/*.test.mjs",
36
38
  "test:coverage": "node scripts/run-coverage.mjs --report-only",
37
39
  "coverage:check": "node scripts/run-coverage.mjs",
38
- "prepublishOnly": "npm run typecheck && SPINE_WORKER_STUB=1 npm test && npm run coverage:check"
40
+ "release:check": "npm run typecheck && npm run lint && SPINE_WORKER_STUB=1 npm test && npm run coverage:check",
41
+ "prepublishOnly": "npm run release:check"
39
42
  },
40
43
  "repository": {
41
44
  "type": "git",
@@ -0,0 +1,200 @@
1
+ ---
2
+ name: spine-orchestrate-waves
3
+ version: 1.0.0
4
+ description: Orchestrate multi-wave spine batches with an external agent outer loop — wave selection, land loop, evidence review, gate approval, integrate, and recovery. Use when asked to "run all waves", "orchestrate spine", "hands-off spine development", "land loop", "orchestrate pending tasks", or drive multi-wave batches from pi, Cursor, or OpenCode.
5
+ compatibility: Requires spine CLI from pi-spine, consumer repo with `.spine/spine-config.json`. Run from consumer repo root (or pi-spine when dogfooding).
6
+ ---
7
+
8
+ # Spine Orchestrate Waves
9
+
10
+ Drive **multi-wave spine development** from an external agent session. Spine owns batch execution, review, contract verify, and integrate gates; **you** (the agent) own wave selection, `spine wait`, evidence review, `gate approve`, integrate decisions, retry/dismiss, and conflict resolution.
11
+
12
+ **Gate approval by the external agent is intentional** — workers receive `not_supported` from `spine_request_gate` (FR-SHIP-13). Do not expect workers to approve integrate gates.
13
+
14
+ Invoke explicitly: `/skill:spine-orchestrate-waves`, `/spine-orchestrate pending`, or "orchestrate all pending spine waves."
15
+
16
+ **Not** for authoring task packets — use `create-spine-tasks`. **Not** for curated semver releases — use `spine-release-operator`.
17
+
18
+ ## Skill boundaries
19
+
20
+ | Concern | Delegate to |
21
+ |---------|-------------|
22
+ | Task packet authoring | `create-spine-tasks` skill |
23
+ | Curated release subset | `spine-release-operator` skill |
24
+ | Canonical how-to prose | [references/outer-loop.md](references/outer-loop.md) (synced from `docs/adoption/agent-orchestrated-waves.md`) |
25
+ | Slash entry (`/spine-orchestrate`) | pi-spine extension — wave plan + outer loop checklist |
26
+ | Single-task suggested command | `/spine-next` inside land loop |
27
+
28
+ ## Prerequisites
29
+
30
+ - pi-spine installed (`pi install npm:pi-spine` or local link)
31
+ - `.spine/spine-config.json` present (`spine init` if missing)
32
+ - Tasks decomposed into waves (`spine plan pending` shows wave structure)
33
+ - Familiarity with [operator-runbook §4 land loop](../../docs/adoption/operator-runbook.md#4-land-loop)
34
+
35
+ ---
36
+
37
+ ## Decision tree
38
+
39
+ Use this tree after each `spine wait` or when resuming orchestration.
40
+
41
+ ```
42
+ START
43
+ │
44
+ ├─ spine preflight
45
+ │ └─ fail → fix env/config; do not start batch
46
+ │
47
+ ├─ spine plan <scope> [--json]
48
+ │ └─ waveCount == 0 → DONE (no pending work)
49
+ │
50
+ └─ FOR each wave W (from --from-wave or 0):
51
+ │
52
+ ├─ spine batch start <scope> --wave W --attached
53
+ ├─ spine wait --until completed,needs_integrate,failed,aborted,needs_retry --timeout 4h
54
+ ├─ spine status --diagnose
55
+ │
56
+ └─ diagnosis?
57
+ ├─ needs_integrate → EVIDENCE CHECKLIST → land loop → next wave
58
+ ├─ needs_retry → retry branch (below) → resume; do not start next wave
59
+ ├─ failed / aborted → journal + packet fix → dismiss/retry; do not start next wave
60
+ ├─ merge_blocked → resolve conflicts → resume --force; stay on wave
61
+ ├─ engine_orphaned / worker_orphaned → recover (below); no second attached engine
62
+ ├─ completed → batch complete + push if needed → next wave
63
+ └─ running / paused → wait or resume; do not start parallel engine
64
+ ```
65
+
66
+ **Hard stops before next wave:**
67
+
68
+ - Land loop incomplete (`integrate` + `batch complete` + push when remote sync desired)
69
+ - Unresolved `failed`, `aborted`, or `needs_retry` on current wave
70
+ - Active `spine run sequence --attached` on same batch (state corruption risk)
71
+
72
+ ---
73
+
74
+ ## Wave picker algorithm
75
+
76
+ 1. Run `spine plan pending` (or `spine plan all` / explicit task scope).
77
+ 2. Parse wave index and task list:
78
+ - **JSON:** `spine plan pending --json` → `waveCount`, per-wave `tasks[]`
79
+ - **Text:** read wave headers from CLI output
80
+ 3. Choose **W** = lowest index with pending tasks, unless operator passed `--from-wave N`.
81
+ 4. If prior wave landed on `main`, re-run `spine plan` — dependency graph may have shifted.
82
+ 5. Prefer **≤4 M-sized tasks per wave**; if plan shows oversized wave, note stall risk but proceed unless operator asked to replan.
83
+
84
+ ---
85
+
86
+ ## Per-wave outer loop
87
+
88
+ From consumer repo root:
89
+
90
+ ```bash
91
+ spine preflight
92
+ WAVE=0 # or next index from plan
93
+
94
+ spine batch start pending --wave $WAVE --attached
95
+ spine wait --until completed,needs_integrate,failed,aborted,needs_retry --timeout 4h
96
+
97
+ spine status --diagnose
98
+ # Read headline + suggestedCommand
99
+
100
+ spine gate status
101
+ # Inspect .spine/runtime/<batchId>/evidence/
102
+
103
+ spine gate approve # only after evidence checklist passes
104
+ spine integrate
105
+ spine batch complete
106
+ git push origin <baseBranch> # when remote sync desired
107
+ ```
108
+
109
+ Increment `WAVE` and repeat until `spine plan pending` shows no remaining waves.
110
+
111
+ **Optional script template:** `spine run sequence pending --attached --dry-run` — execute each printed block with judgment; do **not** chain `--auto-approve-gate` with real pi workers.
112
+
113
+ Full reference: [references/outer-loop.md](references/outer-loop.md).
114
+
115
+ ---
116
+
117
+ ## Evidence checklist (before `spine gate approve`)
118
+
119
+ Inspect `.spine/runtime/<batchId>/evidence/`:
120
+
121
+ - [ ] Contract verify passed for every task in the wave
122
+ - [ ] Test output present and scoped (not truncated by `maxBuffer` — avoid bare full-suite `testCommand` in PROMPTs)
123
+ - [ ] Review artifacts acceptable (`.reviews/` or engine-stored review verdicts)
124
+ - [ ] No unexpected `fileScopeMustChange` / `fileScopeMustNotChange` violations
125
+ - [ ] Integrate merge preview acceptable (no surprise files outside task scope)
126
+ - [ ] Operator/agent explicitly approves landing — **never** auto-approve without reading evidence
127
+
128
+ ---
129
+
130
+ ## Diagnosis → agent action
131
+
132
+ | Diagnosis | Agent action |
133
+ |-----------|--------------|
134
+ | `needs_integrate` | Evidence checklist → `spine gate approve` → `spine integrate` → `spine batch complete` → push |
135
+ | `needs_retry` | `spine batch retry <taskId>` then `spine batch resume --attached`; amend PROMPT contract if scope wrong |
136
+ | `needs_retry` + `review_exhausted` | Inspect `.reviews/` feedback; fix implementation or packet scope, then retry |
137
+ | `needs_retry` + `contract_failed` | Edit `PROMPT.md` `testCommand` or file scope, then retry |
138
+ | `failed` | Inspect journal (`spine journal follow`); fix contract/env before retry |
139
+ | `needs_replan` | Read `{taskFolder}/.reviews/final-*.md`; edit PROMPT scope, then retry |
140
+ | `merge_blocked` | Resolve conflicts on orch branch or lane worktree; `spine batch resume --force` |
141
+ | `engine_orphaned` | Do **not** start a second attached engine; `spine batch retry <taskId>` or `spine batch resume --attached --force` after confirming dead PIDs |
142
+ | `worker_orphaned` | `spine batch retry <taskId>` (reconciles orphan running → failed) |
143
+ | `worker_done_missing` | Read worker output log from headline; fix blocker, then `spine batch retry <taskId>` |
144
+ | `completed` | Run `spine batch complete` if not archived, then push |
145
+ | `state_drift` | `spine batch retry <taskId>`; then `spine batch resume --attached --force` |
146
+
147
+ ---
148
+
149
+ ## Anti-patterns
150
+
151
+ | Anti-pattern | Correct approach |
152
+ |--------------|------------------|
153
+ | `spine batch resume --attached` while `spine run sequence --attached` is active | One entry point; kill stale engines first (`spine status --diagnose`) |
154
+ | Approving gate without reading evidence | Always inspect evidence directory before `spine gate approve` |
155
+ | Expecting workers to call `spine_request_gate` for integrate | Agent drives gate approval from host shell |
156
+ | `--auto-approve-gate` with real pi workers | Per-wave agent loop with explicit gate approval |
157
+ | Starting next wave before land loop completes | Complete integrate + batch complete + push before next wave |
158
+ | Bare full-suite `testCommand` with large output | Scope `testCommand` to relevant test files |
159
+
160
+ ---
161
+
162
+ ## Multi-wave completion report
163
+
164
+ When all waves finish, report:
165
+
166
+ 1. **Waves executed** — indices, task IDs per wave
167
+ 2. **Land loops** — integrate commits, push status
168
+ 3. **Recoveries** — retries, contract fixes, conflict resolution
169
+ 4. **Verification** — paste `spine preflight` and final `spine plan pending` (should show 0 pending)
170
+ 5. **Follow-ups** — deferred tasks, CONTEXT.md tech debt, issues to file
171
+
172
+ ---
173
+
174
+ ## Related docs
175
+
176
+ | Doc | Relevance |
177
+ |-----|-----------|
178
+ | [references/outer-loop.md](references/outer-loop.md) | Full synced how-to |
179
+ | [docs/adoption/agent-orchestrated-waves.md](../../docs/adoption/agent-orchestrated-waves.md) | Canonical doc (update source for sync) |
180
+ | [docs/adoption/operator-runbook.md](../../docs/adoption/operator-runbook.md) | Land loop, recovery |
181
+ | [docs/adoption/bootstrap-checklist.md](../../docs/adoption/bootstrap-checklist.md) | First batch setup |
182
+ | `.cursor/rules/spine-operator-cursor.mdc` | Cursor operator workflow |
183
+
184
+ ## Related issues
185
+
186
+ - [#90](https://github.com/beettlle/pi-spine/issues/90) — agent-orchestrated multi-wave outer loop
187
+ - [#79](https://github.com/beettlle/pi-spine/issues/79) — `--auto-approve-gate` (deprioritized; agent loop replaces need)
188
+ - [#82](https://github.com/beettlle/pi-spine/issues/82) — sequence stops on merge_blocked
189
+ - [#89](https://github.com/beettlle/pi-spine/issues/89) — nested attached engines
190
+
191
+ ---
192
+
193
+ ## Short prompt (resume mid-orchestration)
194
+
195
+ ```text
196
+ Resume spine wave orchestration: spine plan pending --json → pick next wave W →
197
+ spine batch start pending --wave W --attached → spine wait → spine status --diagnose →
198
+ branch on diagnosis (evidence checklist before gate approve) → integrate → batch complete → push →
199
+ repeat until plan shows 0 waves. Post completion report.
200
+ ```
@@ -0,0 +1,165 @@
1
+ # How to orchestrate multi-wave spine batches with an external agent
2
+
3
+ > **Sync source:** `docs/adoption/agent-orchestrated-waves.md` (canonical). Update the doc first, then re-copy here when content changes.
4
+
5
+ Run all pending tasks across multiple dependency waves without manual intervention between each step. An **external agent** (pi, OpenCode, Cursor, CI script) drives the land loop between waves while spine owns batch execution, review, and integrate gates.
6
+
7
+ **Gate approval by the external agent is intentional** — spine workers return `not_supported` from `spine_request_gate` (FR-SHIP-13). The agent-as-operator model decouples wave scheduling from engine internals.
8
+
9
+ ---
10
+
11
+ ## Prerequisites
12
+
13
+ - pi-spine installed and configured ([bootstrap-checklist.md](../../../docs/adoption/bootstrap-checklist.md))
14
+ - Tasks decomposed into dependency waves (`spine plan pending` shows wave structure)
15
+ - Familiarity with the [land loop](../../../docs/adoption/operator-runbook.md#4-land-loop)
16
+
17
+ ---
18
+
19
+ ## Responsibility split
20
+
21
+ | Layer | Owns |
22
+ |-------|------|
23
+ | **Spine engine** | Batch start, lane provisioning, worker spawn, review, contract verify, lane→orch merge, gate evidence, journal |
24
+ | **External agent** | Wave selection, `spine wait`, evidence review, `gate approve`, integrate decision, retry/dismiss, conflict resolution |
25
+
26
+ The engine never auto-approves the integrate gate or pushes to remote — those decisions belong to the operator (human or agent).
27
+
28
+ ---
29
+
30
+ ## Per-wave land loop
31
+
32
+ Run this sequence once per wave from the consumer repo root:
33
+
34
+ ```bash
35
+ spine preflight
36
+ WAVE=0 # agent picks the next wave index from plan output
37
+
38
+ spine batch start pending --wave $WAVE --attached
39
+ spine wait --until completed,needs_integrate,failed,aborted,needs_retry --timeout 4h
40
+
41
+ spine status --diagnose
42
+ # Read headline + suggestedCommand
43
+
44
+ # Land loop (after reviewing evidence)
45
+ spine gate status
46
+ # Inspect .spine/runtime/<batchId>/evidence/
47
+ spine gate approve
48
+ spine integrate
49
+ spine batch complete
50
+ git push origin main
51
+ ```
52
+
53
+ Increment `$WAVE` and repeat until `spine plan pending` shows no remaining waves.
54
+
55
+ ---
56
+
57
+ ## Multi-wave strategy
58
+
59
+ **Preferred: agent repeats per wave.** Each iteration is an independent land loop. The agent reviews evidence, approves or rejects the gate, handles failures, then starts the next wave. This approach:
60
+
61
+ - Decouples from `--auto-approve-gate` (which is stub/CI only)
62
+ - Allows the agent to react to partial wave success
63
+ - Avoids sequence halt issues on merge-blocked waves
64
+
65
+ **Optional: sequence dry-run as script template.** Generate the command sequence without executing:
66
+
67
+ ```bash
68
+ spine run sequence pending --attached --dry-run
69
+ ```
70
+
71
+ The agent can execute each printed block manually with judgment between steps.
72
+
73
+ **Not recommended for real pi:** `spine run sequence pending --auto-approve-gate --force` bypasses evidence review and is restricted to stub/CI environments by safety gates.
74
+
75
+ ---
76
+
77
+ ## Diagnosis → agent action table
78
+
79
+ After `spine wait` returns or `spine status --diagnose` reports a non-running state:
80
+
81
+ | Diagnosis | Agent action |
82
+ |-----------|--------------|
83
+ | `needs_integrate` | Review evidence under `.spine/runtime/<batchId>/evidence/` → `spine gate approve` → `spine integrate` → `spine batch complete` → push |
84
+ | `needs_retry` | `spine batch retry <taskId>` then `spine batch resume --attached`; amend PROMPT contract if scope is wrong |
85
+ | `needs_retry` + `review_exhausted` | Inspect `.reviews/` feedback; fix implementation or packet scope, then retry |
86
+ | `needs_retry` + `contract_failed` | Edit `PROMPT.md` `testCommand` or file scope, then retry |
87
+ | `failed` | Inspect journal (`spine journal follow`); fix contract/env before retry |
88
+ | `needs_replan` | Read reviewer feedback in `{taskFolder}/.reviews/final-*.md`; edit PROMPT scope, then retry |
89
+ | `merge_blocked` | Resolve conflicts on orch branch or lane worktree; `spine batch resume --force` |
90
+ | `engine_orphaned` | Do **not** start a second attached engine; `spine batch retry <taskId>` or `spine batch resume --attached --force` after confirming dead PIDs |
91
+ | `worker_orphaned` | `spine batch retry <taskId>` (reconciles orphan running → failed) |
92
+ | `worker_done_missing` | Read worker output log from headline; fix blocker, then `spine batch retry <taskId>` |
93
+ | `completed` | Already landed — run `spine batch complete` if not archived, then push |
94
+
95
+ ---
96
+
97
+ ## Anti-patterns
98
+
99
+ | Anti-pattern | Why it fails | Correct approach |
100
+ |--------------|-------------|------------------|
101
+ | Running `spine batch resume --attached` while `spine run sequence --attached` is active | Two engines on the same batch causes state corruption | Use one entry point; kill stale engines first (`spine status --diagnose` to check PIDs) |
102
+ | Approving gate without reading evidence | Merges untested or broken code to main | Always inspect `.spine/runtime/<batchId>/evidence/` before `spine gate approve` |
103
+ | Expecting workers to call `spine_request_gate` for integrate | Workers always receive `not_supported` (FR-SHIP-13) | Agent drives gate approval from the host shell |
104
+ | Using `--auto-approve-gate` with real pi workers | Bypasses evidence review; safety gates block this for real pi | Use per-wave agent loop with explicit gate approval |
105
+ | Starting next wave before land loop completes | Base branch diverges from orch; downstream waves may conflict | Complete `integrate` + `batch complete` + push before next wave |
106
+ | Bare full-suite `testCommand` with large output | Contract verify exceeds `maxBuffer` (10MB) and fails | Scope `testCommand` to relevant test files |
107
+
108
+ ---
109
+
110
+ ## Example: full backlog orchestration
111
+
112
+ ```bash
113
+ #!/usr/bin/env bash
114
+ set -euo pipefail
115
+
116
+ spine preflight
117
+
118
+ WAVES=$(spine plan pending --json | jq '.waveCount')
119
+
120
+ for ((WAVE=0; WAVE<WAVES; WAVE++)); do
121
+ echo "=== Wave $WAVE ==="
122
+
123
+ spine batch start pending --wave "$WAVE" --attached
124
+ spine wait --until completed,needs_integrate,failed,aborted,needs_retry --timeout 4h
125
+
126
+ DIAG=$(spine status --json | jq -r '.diagnosis')
127
+
128
+ if [ "$DIAG" = "needs_integrate" ]; then
129
+ spine gate status
130
+ spine gate approve
131
+ spine integrate
132
+ spine batch complete
133
+ git push origin main
134
+ else
135
+ echo "Wave $WAVE ended with diagnosis: $DIAG"
136
+ echo "Run: spine status --diagnose"
137
+ exit 1
138
+ fi
139
+ done
140
+
141
+ echo "All waves complete."
142
+ ```
143
+
144
+ Adapt for agent sessions: replace the bash loop with agent tool calls (`spine status --json` → parse → branch on diagnosis).
145
+
146
+ ---
147
+
148
+ ## Related docs
149
+
150
+ | Doc | Relevance |
151
+ |-----|-----------|
152
+ | [operator-runbook.md §4](../../../docs/adoption/operator-runbook.md#4-land-loop) | Land loop copy-paste sequence |
153
+ | [bootstrap-checklist.md](../../../docs/adoption/bootstrap-checklist.md) | First batch setup |
154
+ | [upstream-execution-workflow.md](../../../docs/adoption/upstream-execution-workflow.md) | PRD → task packets → batch |
155
+ | [QUICK-REFERENCE.md](../../../docs/QUICK-REFERENCE.md) | Command reference |
156
+ | [spine-orchestrate-waves SKILL.md](../SKILL.md) | pi skill entry with decision tree |
157
+
158
+ ## Related issues
159
+
160
+ - [#90](https://github.com/beettlle/pi-spine/issues/90) — agent-orchestrated multi-wave outer loop
161
+ - [#79](https://github.com/beettlle/pi-spine/issues/79) — `--auto-approve-gate` flag (deprioritized; agent loop replaces need)
162
+ - [#82](https://github.com/beettlle/pi-spine/issues/82) — sequence stops on merge_blocked
163
+ - [#84](https://github.com/beettlle/pi-spine/issues/84) — PROMPT authoring for cross-model
164
+ - [#71](https://github.com/beettlle/pi-spine/issues/71) — built-in supervisor (future; agent outer loop bridges gap)
165
+ - [#54](https://github.com/beettlle/pi-spine/issues/54) — `spine run sequence` (complementary, not replacement)