pi-spine 2.16.0 → 2.17.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 (33) hide show
  1. package/package.json +1 -1
  2. package/skills/create-spine-tasks/SKILL.md +3 -1
  3. package/skills/create-spine-tasks/references/contract-template.md +12 -12
  4. package/skills/create-spine-tasks/references/prompt-template.md +8 -6
  5. package/skills/spine-autonomous-operator/SKILL.md +2 -0
  6. package/skills/spine-autonomous-operator/references/agent-shell-batch-policy.md +1 -1
  7. package/skills/spine-orchestrate-waves/SKILL.md +6 -4
  8. package/skills/spine-orchestrate-waves/references/outer-loop.md +16 -1
  9. package/skills/spine-release-operator/SKILL.md +3 -0
  10. package/skills/spine-release-operator/references/pi-async-orchestration.md +2 -1
  11. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +14 -0
  12. package/src/batch/batch-guards.mjs +14 -0
  13. package/src/batch/batch-meta-reconstruct.mjs +5 -2
  14. package/src/batch/engine-lanes/merge.mjs +16 -11
  15. package/src/batch/engine-lanes/phase.mjs +45 -0
  16. package/src/batch/engine-lanes/queue.mjs +1 -1
  17. package/src/batch/engine-lanes.mjs +9 -37
  18. package/src/batch/engine.mjs +8 -16
  19. package/src/batch/post-merge-finalize.mjs +128 -0
  20. package/src/batch/post-merge-limbo.mjs +14 -85
  21. package/src/batch/readers/spine-state.mjs +22 -1
  22. package/src/batch/readers/taskplane-state.mjs +22 -1
  23. package/src/batch/reconcile-batch.mjs +1 -1
  24. package/src/batch/resume-common.mjs +1 -1
  25. package/src/batch/resume-multi.mjs +6 -2
  26. package/src/batch/resume.mjs +1 -1
  27. package/src/batch/review-spawn.mjs +4 -3
  28. package/src/cli/journal-follow.mjs +3 -1
  29. package/src/cli/lane-logs.mjs +3 -1
  30. package/src/cli/settings-slash.mjs +2 -1
  31. package/src/config/worker-context.mjs +2 -1
  32. package/src/tasks/analyze/index.mjs +2 -1
  33. package/src/tasks/validate-contract-warn.mjs +45 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.16.0",
3
+ "version": "2.17.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -307,7 +307,7 @@ Use [references/prompt-template.md](references/prompt-template.md). Spine-specif
307
307
  - **Environment** — include `npm run typecheck && SPINE_WORKER_STUB=1 npm test` when that is the project test command
308
308
  - **Git Commit Convention** — `feat(SP-###): …` at step boundaries
309
309
  - **Worker tools** — when Review Level > 0, steps must note `spine_review_step` after each step
310
- - **Testing step (required for all tasks)** — every packet MUST include `### Step N: Testing & Verification` inside `## Steps`, placed **before** `## Completion Criteria`. This applies to **docs-only Review Level 0 tasks** as well — omitting the step causes `prompt_parse_failed` at batch launch (SP-075). Docs-only tasks still run the full test suite; they may omit the coverage-gate checkbox when no application code changes.
310
+ - **Testing step (required for all tasks)** — every packet MUST include `### Step N: Testing & Verification` inside `## Steps`, placed **before** `## Completion Criteria`. This applies to **docs-only Review Level 0 tasks** as well — omitting the step causes `prompt_parse_failed` at batch launch (SP-075). Docs-only tasks still run the full test suite; they may omit lint and coverage-gate checkboxes when no application code changes. **Code tasks:** Contract `testCommand` must prefix project lint/analyze (`npm run lint &&` for pi-spine).
311
311
  - **Coverage gate** — when the task changes application code, add a coverage verification checkbox in the Testing step using `testing.testWithCoverage` (≥77% line coverage policy)
312
312
  - **Contract (required for new SP-\* tasks)** — add `## Contract` after `## File Scope` using [references/contract-template.md](references/contract-template.md). Include `testCommand` for code tasks; use `` `true` `` for docs-only S tasks. When `testCommand` is `` `true` `` (docs-only), **always** include `fileScopeMustChange` listing at least one documentation deliverable path — without it, workers can pass contract by creating only `.DONE` (SP-214 batch `20260612T204048`, SP-457 batch `20260703T022335`). When using `fileScopeMustNotChange`, follow parallel-only semantics and never ban `spine-tasks/**` (see contract template and [File Scope and parallel batches](#file-scope-and-parallel-batches)). Legacy `TP-*` packets may omit Contract when `contract.legacyTaskIdPrefixes` includes `TP-`.
313
313
  - **Completion** — worker creates `{task-folder}/.DONE`; batch engine may auto-commit remaining work
@@ -556,6 +556,7 @@ Before reporting launch commands:
556
556
  - [ ] Every **Must Update** doc path also appears in `## File Scope` ([#144](https://github.com/beettlle/pi-spine/issues/144))
557
557
  - [ ] Docs-only tasks: consider `fileScopeMustNotChange` on `src/**`, `bin/**` ([#142](https://github.com/beettlle/pi-spine/issues/142)); see [Docs-only contract pattern](#docs-only-contract-pattern-fr-sta-12)
558
558
  - [ ] S/M patch Contract uses scoped `node --test` — not `npm test` or `npm test -- path` ([#141](https://github.com/beettlle/pi-spine/issues/141), SP-522)
559
+ - [ ] Code tasks (File Scope touches `src/**`, `bin/**`, `tests/**`, or `scripts/**`): Contract `testCommand` prefixes project lint/analyze (`npm run lint &&` for pi-spine)
559
560
  - [ ] Shared-module behavior change: `rg` old strings in `tests/`; all hit files in `testCommand` or documented for post-integrate `release:check` ([post-integrate-regression-gate.md](../spine-release-operator/references/post-integrate-regression-gate.md))
560
561
  - [ ] Plan waves ≤8 tasks when possible — `spine plan` warns when exceeded ([#143](https://github.com/beettlle/pi-spine/issues/143), SP-524)
561
562
  - [ ] When parallelism is intended: `spine plan` shows `N lanes in parallel` for that wave — or document why overlapping scopes / real deps forced serial collapse ([#193](https://github.com/beettlle/pi-spine/issues/193))
@@ -586,6 +587,7 @@ Hydration commits (STATUS.md expansions) may happen mid-step for crash recovery.
586
587
  - **Self-contained PROMPT.md** — the worker has no memory of this conversation. Cross-model reviewers receive a **fresh spawn** (FR-REV-04) with only the review request, diff, and Contract — not `referenceDocs` or worker rules. Place acceptance criteria and spec references in PROMPT `## Mission`, `## Contract`, and step checkboxes.
587
588
  - **Issue links in Mission ([#147](https://github.com/beettlle/pi-spine/issues/147))** — Use `Closes #N` when this task fully resolves the issue. Use `Partial #N` when this task is one of several addressing the issue. Place on the first line of `## Mission` (not `Closes: [#N]` or `GitHub: [#N]` variants).
588
589
  - **Scoped `testCommand` for cross-model batches** — lane worktrees differ from dev checkouts; broad `flutter test` / `npm test` can fail in lanes even when targeted tests pass. See [cross-model authoring guidance](references/contract-template.md#cross-model-authoring-worker--reviewer) for the `testCommand` decision table.
590
+ - **Lint in code-task contracts** — prefix `testCommand` with project lint/analyze (`npm run lint &&` for pi-spine). Contract verify runs the authored command in-lane; without lint, ESLint failures surface only at operator post-integrate `release:check` (post-mortem v2.15.0 F-C). Docs-only (`testCommand: true`) stays exempt.
589
591
  - **Scoped contract ≠ full regression** — changing shared modules (diagnosis, reconcile, parse-prompt) can break tests outside the task's scoped `testCommand`. Authors must `rg` old strings in `tests/` and include related test files in Contract, or rely on operator post-integrate `release:check` on `main` ([post-integrate-regression-gate.md](../spine-release-operator/references/post-integrate-regression-gate.md)).
590
592
  - **S/M patch tasks: no coverage gate in Contract** — do not chain `npm run coverage:check` or bare `npm test` in `## Contract` `testCommand` on Size S/M tasks; integrate gate owns full coverage at merge. Use scoped `node --test path/to.test.mjs` (SP-521 / [#141](https://github.com/beettlle/pi-spine/issues/141)). `spine tasks validate` warns when violated.
591
593
  - **Testing step required (never omit)** — every task packet needs `### Step N: Testing & Verification` inside `## Steps`, before `## Completion Criteria`. **Do not skip this for docs-only or Review Level 0 tasks** — the worker rejects packets without a Testing step. Use `testing.test` from spine config; for **code deliverables**, also include `testing.testWithCoverage` and a **≥77% line coverage** checkbox (see prompt template). Docs-only tasks may omit the coverage checkbox.
@@ -15,7 +15,7 @@ Normative schema: [PRD v2.0 implementation handoff §4](../../docs/PRD-v2.0-impl
15
15
 
16
16
  | Field | Value |
17
17
  |-------|-------|
18
- | testCommand | `npm run coverage:check` |
18
+ | testCommand | `npm run lint && npm run typecheck && SPINE_WORKER_STUB=1 node --experimental-strip-types --test tests/batch/final-verdict.test.mjs` |
19
19
  | fileScopeMustChange | `src/batch/review.mjs`, `bin/spine-tasks.mjs` |
20
20
  | fileScopeMustNotChange | `src/planner/**` |
21
21
  | minLineCoverage | 77 |
@@ -36,7 +36,7 @@ Avoid `` `bin/a.mjs,bin/b.mjs` `` — `tasks validate` warns (or errors in requi
36
36
 
37
37
  | Field | When to include | Value format |
38
38
  |-------|-----------------|--------------|
39
- | `testCommand` | **Required** for code tasks (Review Level ≥ 1, Size M/L, or implementation steps) | Shell command in backticks; max 500 chars; no newlines. Use `` `true` `` for docs-only S tasks with no code changes. When `` `true` ``, **always** pair with `fileScopeMustChange` (see below). |
39
+ | `testCommand` | **Required** for code tasks (Review Level ≥ 1, Size M/L, or implementation steps) | Shell command in backticks; max 500 chars; no newlines. **Code tasks:** prefix with project lint/analyze (`npm run lint &&` for pi-spine; `flutter analyze` scoped for Flutter). Contract verify executes this command at final review — lint runs in-lane when authored here. Post-integrate `release:check` remains the whole-repo backstop (full suite + coverage). Use `` `true` `` for docs-only S tasks with no code changes. When `` `true` ``, **always** pair with `fileScopeMustChange` (see below). |
40
40
  | `fileScopeMustChange` | When you need proof specific paths were touched; **required** when `testCommand` is `` `true` `` | Comma-separated paths/globs relative to repo root; **one backtick per path** (not `` `a.mjs,b.mjs` ``). Trailing `/` means directory prefix match (e.g. `src/domain/types/` matches any file under that directory). For docs-only tasks, list at least one documentation deliverable path — without it, workers can pass contract by creating only `.DONE` (SP-214 batch `20260612T204048`, SP-457 batch `20260703T022335`). |
41
41
  | `fileScopeMustNotChange` | When **parallel lanes** must not collide on product paths (see semantics below) | Comma-separated paths/globs relative to repo root; **one backtick per path** |
42
42
  | `minLineCoverage` | When task changes application code | Integer 0–100 (pi-spine policy: **77**) |
@@ -101,7 +101,7 @@ Symptom in journal: `testCommand` passes but `fileScopeMustNotChange` fails with
101
101
 
102
102
  | Field | Value |
103
103
  |-------|-------|
104
- | testCommand | `npm test -- tests/tasks/validate-cli.test.mjs` |
104
+ | testCommand | `npm run lint && npm run typecheck && SPINE_WORKER_STUB=1 node --experimental-strip-types --test tests/tasks/validate-cli.test.mjs` |
105
105
  ```
106
106
 
107
107
  ### M task with coverage gate
@@ -111,7 +111,7 @@ Symptom in journal: `testCommand` passes but `fileScopeMustNotChange` fails with
111
111
 
112
112
  | Field | Value |
113
113
  |-------|-------|
114
- | testCommand | `npm run coverage:check` |
114
+ | testCommand | `npm run lint && npm run typecheck && SPINE_WORKER_STUB=1 node --experimental-strip-types --test tests/tasks/validate-prompt.test.mjs` |
115
115
  | fileScopeMustChange | `src/tasks/packet/validate-prompt.mjs` |
116
116
  | minLineCoverage | 77 |
117
117
  ```
@@ -150,7 +150,7 @@ For docs-only tasks, add `fileScopeMustNotChange` on product-code directories so
150
150
  | Situation | Contract pattern |
151
151
  |-----------|------------------|
152
152
  | No application code changes; documentation or skill text only | `` `true` `` + `fileScopeMustChange` on deliverable doc paths (+ optional `fileScopeMustNotChange` on `src/**`, `bin/**`) |
153
- | Small code change with an existing targeted test file | `` `node --test tests/feature.test.mjs` `` (see [scoped testCommand](#scoped-testcommand) below) |
153
+ | Small code change with an existing targeted test file | `` `npm run lint && npm run typecheck && node --test tests/feature.test.mjs` `` (see [scoped testCommand](#scoped-testcommand) below) |
154
154
  | Code change but no narrow test yet; full suite unsafe in lane | Scoped command matching the Testing step, or split into a code task + docs task |
155
155
 
156
156
  Use docs-only when the worker's only product deliverable is documentation. Use scoped `node --test` when the task changes application code — even Size S/M patches should not use bare `` `npm test` `` or `` `npm test -- path` `` in Contract ([#141](https://github.com/beettlle/pi-spine/issues/141)).
@@ -162,7 +162,7 @@ Use docs-only when the worker's only product deliverable is documentation. Use s
162
162
 
163
163
  | Field | Value |
164
164
  |-------|-------|
165
- | testCommand | `npm run typecheck && SPINE_WORKER_STUB=1 npm test` |
165
+ | testCommand | `npm run lint && npm run typecheck && SPINE_WORKER_STUB=1 node --experimental-strip-types --test tests/batch/final-verdict.test.mjs` |
166
166
  | fileScopeMustChange | `src/batch/review.mjs` |
167
167
  | fileScopeMustNotChange | `src/planner/**`, `src/batch/journal.mjs` |
168
168
  | artifactsMustExist | `tests/batch/final-verdict.test.mjs` |
@@ -177,7 +177,7 @@ Use when a task runs a multi-hour external matrix or CI arm with little in-repo
177
177
 
178
178
  | Field | Value |
179
179
  |-------|-------|
180
- | testCommand | `npm run typecheck && SPINE_WORKER_STUB=1 npm test` |
180
+ | testCommand | `npm run lint && npm run typecheck && SPINE_WORKER_STUB=1 node --experimental-strip-types --test tests/batch/status-classification-align.test.mjs` |
181
181
  | stallTimeoutMinutes | 240 |
182
182
  | extendGraceOnFileScope | true |
183
183
  | fileScopeMustChange | `spine-tasks/SP-029-*/STATUS.md` |
@@ -222,11 +222,11 @@ Reviewers spawn as **fresh sessions** with no memory of the worker session (FR-R
222
222
  | Task type | Recommended `testCommand` |
223
223
  |-----------|---------------------------|
224
224
  | Docs-only, no code changes | `` `true` `` **and** `fileScopeMustChange` with at least one deliverable doc path |
225
- | Single module, targeted tests exist | `` `node --test tests/feature.test.mjs` `` or `` `flutter test test/unit/services/foo_test.dart` `` |
226
- | **Shared-module behavior change** (diagnosis, reconcile, parse-prompt, worktree, doctor) | Chain **all** related `tests/**/*.test.mjs` from `rg` for old strings — not only the new test file (see below) |
227
- | Full-suite safe in lane worktree | `` `npm run typecheck && SPINE_WORKER_STUB=1 npm test` `` |
228
- | Coverage gate required (pi-spine ≥77%) | `` `npm run coverage:check` `` |
229
- | Long external job (>2h) | Scoped command + `stallTimeoutMinutes` and `extendGraceOnFileScope` in Contract (see SP-314 example above) |
225
+ | Single module, targeted tests exist (Size S/M) | `` `npm run lint && npm run typecheck && node --test tests/feature.test.mjs` `` or `` `flutter analyze && flutter test test/unit/services/foo_test.dart` `` |
226
+ | **Shared-module behavior change** (diagnosis, reconcile, parse-prompt, worktree, doctor) | `` `npm run lint &&` `` then chain **all** related `tests/**/*.test.mjs` from `rg` for old strings — not only the new test file (see below) |
227
+ | Full-suite safe in lane worktree (Size L) | `` `npm run lint && npm run typecheck && SPINE_WORKER_STUB=1 npm test` `` |
228
+ | Coverage gate required (pi-spine ≥77%, Size L) | `` `npm run lint && npm run coverage:check` `` |
229
+ | Long external job (>2h) | `` `npm run lint &&` `` scoped command + `stallTimeoutMinutes` and `extendGraceOnFileScope` in Contract (see SP-314 example above) |
230
230
 
231
231
  ### Shared-module behavior changes
232
232
 
@@ -109,14 +109,16 @@ Review Level 0 is ONLY for trivial changes. Most M+ tasks need Level ≥1.
109
109
  ### Step [N-1]: Testing & Verification
110
110
 
111
111
  > **Required for every task** — including docs-only and Review Level 0 packets.
112
- > ZERO test failures allowed. This step runs the FULL test suite as a quality gate.
113
- > Use `testCommand` from `## Contract` (often chains `npm run typecheck` with tests).
112
+ > ZERO test failures allowed. Run the commands below; do **not** assume the Testing step equals full CI parity.
113
+ > Contract verify runs only `testCommand` from `## Contract` at final review.
114
+ > Operator post-integrate `npm run release:check` owns the whole-repo gate (typecheck → lint → full tests → coverage).
114
115
  >
115
- > **Docs-only tasks:** keep this step; run the full test suite. Omit the coverage-gate
116
- > checkbox below when the task does not change application code.
116
+ > **Code tasks** (File Scope touches `src/`, `bin/`, `tests/`, or `scripts/`): include `npm run lint` in Contract `testCommand` and mirror it here.
117
+ > **Docs-only tasks:** keep this step; run the full test suite from project config. Omit lint and coverage checkboxes when no application code changes.
117
118
 
118
- - [ ] Run FULL test suite: `[test command from project config]`
119
- - [ ] Run coverage gate: `[testWithCoverage command, e.g. npm run coverage:check]` — **≥77% line coverage** on in-scope changed code (code-related tasks only; omit for docs-only)
119
+ - [ ] Run lint (code tasks only): `npm run lint` — or project analyze command when present
120
+ - [ ] Run Contract `testCommand`: `[exact command from ## Contract — typically lint && typecheck && scoped node --test]`
121
+ - [ ] Run coverage gate (only when Contract requires it): `[testWithCoverage command, e.g. npm run coverage:check]` — **≥77% line coverage** on in-scope changed code
120
122
  - [ ] Run integration tests (if applicable)
121
123
  - [ ] Fix all failures
122
124
 
@@ -205,6 +205,8 @@ test "${PIPESTATUS[0]}" -eq 0
205
205
 
206
206
  Full reference: [post-integrate-regression-gate.md](../spine-release-operator/references/post-integrate-regression-gate.md).
207
207
 
208
+ **Contract vs gate:** contract verify runs only authored `testCommand` (new packets should include lint); post-integrate `release:check` validates the merged tree (full suite + coverage). Do not skip §3.3a because contract verify passed.
209
+
208
210
  **If non-zero:** fix on `main`, commit, re-run. Do **not** start wave N+1 until green.
209
211
 
210
212
  ### 3.4 Advance
@@ -86,7 +86,7 @@ Full reference: [post-integrate-regression-gate.md](../../spine-release-operator
86
86
  | Do | Do not |
87
87
  |----|--------|
88
88
  | Verify `$?` or `${PIPESTATUS[0]}` after `release:check` | Use `\| tail` alone for pass/fail |
89
- | Re-run after manual merge / conflict resolution | Assume scoped task `testCommand` covered full CI |
89
+ | Re-run after manual merge / conflict resolution | Assume scoped task `testCommand` covered full CI (includes **lint** — contract verify does not unless authored) |
90
90
 
91
91
  ---
92
92
 
@@ -130,6 +130,7 @@ Full reference: [references/outer-loop.md](references/outer-loop.md).
130
130
  Inspect `.spine/runtime/<batchId>/evidence/`:
131
131
 
132
132
  - [ ] Contract verify passed for every task in the wave
133
+ - [ ] Contract pass does **not** imply lint or full CI passed — contract runs only authored `testCommand`; post-integrate `release:check` still required after integrate
133
134
  - [ ] Test output present and scoped (not truncated by `maxBuffer` — avoid bare full-suite `testCommand` in PROMPTs)
134
135
  - [ ] Review artifacts acceptable (`.reviews/` or engine-stored review verdicts)
135
136
  - [ ] No unexpected `fileScopeMustChange` / `fileScopeMustNotChange` violations
@@ -142,7 +143,7 @@ Inspect `.spine/runtime/<batchId>/evidence/`:
142
143
 
143
144
  | Diagnosis | Agent action |
144
145
  |-----------|--------------|
145
- | `needs_integrate` | Evidence checklist → `spine gate approve` → `spine integrate` → `spine batch complete` → push |
146
+ | `needs_integrate` | Evidence checklist → `spine gate approve` → `spine integrate` → `spine batch complete` → post-integrate `release:check` (exit 0) → push |
146
147
  | `needs_retry` | `spine batch retry <taskId>` then `spine batch resume` (detached); amend PROMPT contract if scope wrong |
147
148
  | `needs_retry` + `review_exhausted` | Inspect `.reviews/` feedback; fix implementation or packet scope, then retry |
148
149
  | `needs_retry` + `contract_failed` | Edit `PROMPT.md` `testCommand` or file scope, then retry |
@@ -180,7 +181,7 @@ When all waves finish, report:
180
181
  1. **Waves executed** — indices, task IDs per wave
181
182
  2. **Land loops** — integrate commits, push status
182
183
  3. **Recoveries** — retries, contract fixes, conflict resolution
183
- 4. **Verification** — paste `spine preflight` and final `spine plan pending` (should show 0 pending)
184
+ 4. **Verification** — last wave post-integrate `release:check` log path + verified exit 0; paste `spine preflight` and final `spine plan pending` (should show 0 pending)
184
185
  5. **Follow-ups** — deferred tasks, CONTEXT.md tech debt, issues to file
185
186
 
186
187
  ---
@@ -209,6 +210,7 @@ When all waves finish, report:
209
210
  ```text
210
211
  Resume spine wave orchestration: spine plan pending --json → pick next wave W →
211
212
  spine batch start pending --wave W (detached) → spine status --diagnose → spine wait →
212
- branch on diagnosis (evidence checklist before gate approve) → integrate → batch complete → push →
213
- repeat until plan shows 0 waves. Post completion report.
213
+ branch on diagnosis (evidence checklist before gate approve) → integrate → batch complete →
214
+ post-integrate npm run release:check (verify exit 0) → push → repeat until plan shows 0 waves.
215
+ Post completion report.
214
216
  ```
@@ -82,6 +82,21 @@ Increment `$WAVE` and repeat until `spine plan pending` shows no remaining waves
82
82
 
83
83
  ---
84
84
 
85
+ ## Evidence checklist (before `spine gate approve`)
86
+
87
+ Inspect `.spine/runtime/<batchId>/evidence/`:
88
+
89
+ - [ ] Contract verify passed for every task in the wave
90
+ - [ ] Contract pass does **not** imply lint or full CI passed — contract runs only authored `testCommand`; post-integrate `release:check` still required after integrate
91
+ - [ ] Test output present and scoped (not truncated by `maxBuffer`)
92
+ - [ ] Review artifacts acceptable
93
+ - [ ] No unexpected file-scope violations
94
+ - [ ] Operator explicitly approves landing — never auto-approve without reading evidence
95
+
96
+ See [post-integrate-regression-gate.md](../../spine-release-operator/references/post-integrate-regression-gate.md) for contract vs `release:check` scope.
97
+
98
+ ---
99
+
85
100
  ## Multi-wave strategy
86
101
 
87
102
  **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:
@@ -108,7 +123,7 @@ After `spine wait` returns or `spine status --diagnose` reports a non-running st
108
123
 
109
124
  | Diagnosis | Agent action |
110
125
  |-----------|--------------|
111
- | `needs_integrate` | Review evidence under `.spine/runtime/<batchId>/evidence/` → `spine gate approve` → `spine integrate` → `spine batch complete` → push |
126
+ | `needs_integrate` | Review evidence under `.spine/runtime/<batchId>/evidence/` → `spine gate approve` → `spine integrate` → `spine batch complete` → post-integrate `release:check` (exit 0) → push |
112
127
  | `needs_retry` | `spine batch retry <taskId>` then `spine batch resume` (detached); amend PROMPT contract if scope is wrong |
113
128
  | `needs_retry` + `review_exhausted` | Inspect `.reviews/` feedback; fix implementation or packet scope, then retry |
114
129
  | `needs_retry` + `contract_failed` | Edit `PROMPT.md` `testCommand` or file scope, then retry |
@@ -233,6 +233,7 @@ For every task in manifest scope:
233
233
  - [ ] Doc paths in File Scope match Documentation Requirements (#144)
234
234
  - [ ] `dependencies.json` matches PROMPT `## Dependencies`
235
235
  - [ ] Same-wave tasks have disjoint `fileScopeMustChange`
236
+ - [ ] Code tasks: Contract `testCommand` prefixes project lint/analyze (`npm run lint &&` for pi-spine) — see [contract-template.md](../../create-spine-tasks/references/contract-template.md)
236
237
 
237
238
  ```bash
238
239
  spine tasks validate <release-scope>
@@ -337,6 +338,8 @@ test "${PIPESTATUS[0]}" -eq 0
337
338
 
338
339
  Full reference: [post-integrate-regression-gate.md](references/post-integrate-regression-gate.md).
339
340
 
341
+ **Why this gate still runs when contracts include lint:** contract verify runs only the authored `testCommand` in an isolated lane; post-integrate `release:check` validates the **merged tree** (full suite, coverage, cross-file call sites). Do not skip §4.3a because contract verify passed.
342
+
340
343
  **If non-zero:** fix on `main`, commit, re-run gate. Do **not** start wave N+1, push, or proceed to Phase 5 until green.
341
344
 
342
345
  **Do not** judge pass/fail from `tail` output — `tail` exits 0 even when `release:check` failed.
@@ -29,7 +29,8 @@ Paste diagnosis headline and exit evidence. Do not claim success without CLI out
29
29
  ### onDone prompt template (release:check)
30
30
 
31
31
  ```text
32
- release:check monitor completed. Read tail of /tmp/pi-spine-release-check.log.
32
+ release:check monitor completed. Verify exit code from monitor metadata (not log tail alone).
33
+ Read /tmp/pi-spine-release-check.log for failure details when exit is non-zero.
33
34
  If exit 0: present pre-publish checklist from docs/release/npm-publish.md.
34
35
  If non-zero: STOP; summarize first failing step; do not bump version.
35
36
  ```
@@ -38,6 +38,19 @@ echo "release:check exit: $?"
38
38
 
39
39
  ---
40
40
 
41
+ ## Contract verify vs release:check
42
+
43
+ | Layer | What runs | What it catches |
44
+ |-------|-----------|-----------------|
45
+ | Contract verify (per task) | PROMPT `testCommand` in lane worktree | Scoped tests, typecheck, and **lint when authored** (`npm run lint && …`) |
46
+ | Post-integrate `release:check` (per wave) | `npm run typecheck && npm run lint && SPINE_WORKER_STUB=1 npm test && npm run coverage:check` | Whole-repo typecheck, lint, full suite, coverage, cross-file drift |
47
+
48
+ **Authoring rule (new packets):** code tasks prefix Contract `testCommand` with project lint/analyze so ESLint failures surface in-lane, not only here. Post-integrate `release:check` remains mandatory after every land loop — it catches merged-tree gaps contracts cannot see.
49
+
50
+ **Anti-pattern:** defer lint fixes to Phase 5 publish only — run this gate after **each wave** so lint regressions fail before wave N+1 starts.
51
+
52
+ ---
53
+
41
54
  ## Verification discipline
42
55
 
43
56
  | Do | Do not |
@@ -45,6 +58,7 @@ echo "release:check exit: $?"
45
58
  | Run full `npm run release:check` | Pipe through `tail` or `head` for pass/fail decisions |
46
59
  | Verify exit code explicitly (`$?` or `${PIPESTATUS[0]}`) | Claim "passed" from truncated log tail |
47
60
  | Save log path in manifest publish checklist | Assume scoped task `testCommand` covered full CI suite |
61
+ | Treat contract verify as CI parity | Contract pass does not imply lint or full-suite pass — only `release:check` does |
48
62
 
49
63
  **Anti-pattern:** `npm run release:check 2>&1 | tail -20` — `tail` exits 0 even when `release:check` failed.
50
64
 
@@ -67,3 +67,17 @@ export function rejectNestedBatchStart(projectRoot) {
67
67
  `Parent batch: ${parentBatchId}, projectRoot: ${projectRoot}\n`,
68
68
  };
69
69
  }
70
+
71
+ /**
72
+ * @param {string} batchId
73
+ * @returns {{ ok: true, exitCode: 0, batchId: string, paused: true, output: string }}
74
+ */
75
+ export function buildEnginePausedResult(batchId) {
76
+ return {
77
+ ok: true,
78
+ exitCode: 0,
79
+ batchId,
80
+ paused: true,
81
+ output: "Batch paused.\n",
82
+ };
83
+ }
@@ -9,8 +9,11 @@ import { BATCH_META_FILENAME, batchMetaPath } from "./batch-meta.mjs";
9
9
  import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
10
10
  import { rebuildBatchStateFromJournal } from "./journal-rebuild.mjs";
11
11
  import { computePendingTasks, findResumableWave } from "./resume-validation.mjs";
12
- import { createInitialBatchState, clearBatchEnginePid, saveSpineBatchState } from "./state.mjs";
13
- import { loadSpineBatchState } from "./state-io.mjs";
12
+ // Leaf rewire (SP-735 / #267): state-io/state-guards are leaves; state.mjs stays only for
13
+ // createInitialBatchState, which is defined in the state facade.
14
+ import { createInitialBatchState } from "./state.mjs";
15
+ import { loadSpineBatchState, saveSpineBatchState } from "./state-io.mjs";
16
+ import { clearBatchEnginePid } from "./state-guards.mjs";
14
17
  import { laneTaskBranch, laneWorktreePath } from "./worktree.mjs";
15
18
 
16
19
  /**
@@ -27,7 +27,6 @@ import { recordWaveMergeResult } from "../merge/wave-merge-state.mjs";
27
27
  import { recordMergeBlocked } from "../lifecycle.mjs";
28
28
  import { appendJournalEvent } from "../journal.mjs";
29
29
  import { countCommitsAhead, gitPorcelain } from "../lane-commit.mjs";
30
- import { maybeFinalizeAfterWaveMerge } from "../post-merge-limbo.mjs";
31
30
  import { saveSpineBatchState } from "../state.mjs";
32
31
  import { loadTaskFileScopePaths } from "./queue.mjs";
33
32
  import { laneTaskBranch } from "../worktree.mjs";
@@ -606,9 +605,11 @@ export function mergeLaneToOrch({
606
605
  }
607
606
 
608
607
  /**
609
- * @param {object} params
608
+ * @param {object} params — includes optional `finalizeAfterWaveMerge(hookParams)` hook injected
609
+ * by callers that own the limbo graph (`maybeFinalizeAfterWaveMerge` from post-merge-limbo.mjs,
610
+ * SP-734). Omitted → skip post-wave-merge finalize.
610
611
  */
611
- export async function mergeWaveLanesToOrch({
612
+ export function mergeWaveLanesToOrch({
612
613
  projectRoot,
613
614
  state,
614
615
  batchId,
@@ -616,6 +617,7 @@ export async function mergeWaveLanesToOrch({
616
617
  orchBranch,
617
618
  waveIndex,
618
619
  resumed = false,
620
+ finalizeAfterWaveMerge = null,
619
621
  }) {
620
622
  const waveTaskIds = state.wavePlan?.[waveIndex] ?? [];
621
623
  const needsReplanTask = (state.tasks ?? []).find(
@@ -730,14 +732,17 @@ export async function mergeWaveLanesToOrch({
730
732
  });
731
733
  saveSpineBatchState(projectRoot, state);
732
734
 
733
- const finalizeResult = maybeFinalizeAfterWaveMerge({
734
- projectRoot,
735
- state,
736
- batchId,
737
- orchBranch,
738
- waveIndex,
739
- resumed,
740
- });
735
+ const finalizeResult =
736
+ typeof finalizeAfterWaveMerge === "function"
737
+ ? finalizeAfterWaveMerge({
738
+ projectRoot,
739
+ state,
740
+ batchId,
741
+ orchBranch,
742
+ waveIndex,
743
+ resumed,
744
+ })
745
+ : null;
741
746
 
742
747
  return {
743
748
  ok: true,
@@ -0,0 +1,45 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Batch phase transition helpers for the engine-lanes facade.
4
+ * Leaf module: journals phase changes without importing resume/limbo/reconcile.
5
+ */
6
+
7
+ import { appendJournalEvent } from "../journal.mjs";
8
+
9
+ /**
10
+ * @param {string} fromPhase
11
+ * @param {string} toPhase
12
+ */
13
+ function phaseTransitionEventType(fromPhase, toPhase) {
14
+ if (fromPhase === "planning" && toPhase === "running") return "batch.started";
15
+ if (toPhase === "completed") return "batch.completed";
16
+ if (toPhase === "failed") return "batch.failed";
17
+ if (toPhase === "aborted") return "batch.aborted";
18
+ return null;
19
+ }
20
+
21
+ /**
22
+ * @param {object} params
23
+ */
24
+ function recordPhaseTransition({ projectRoot, batchId, fromPhase, toPhase, extra = {} }) {
25
+ const type = phaseTransitionEventType(fromPhase, toPhase);
26
+ if (!type) return;
27
+ appendJournalEvent(projectRoot, batchId, type, {
28
+ fromPhase,
29
+ toPhase,
30
+ ...extra,
31
+ });
32
+ }
33
+
34
+ export function transitionPhase(state, newPhase, ctx) {
35
+ const fromPhase = state.phase;
36
+ if (fromPhase === newPhase) return;
37
+ state.phase = newPhase;
38
+ recordPhaseTransition({
39
+ projectRoot: ctx.projectRoot,
40
+ batchId: ctx.batchId,
41
+ fromPhase,
42
+ toPhase: newPhase,
43
+ ...ctx.extra,
44
+ });
45
+ }
@@ -167,7 +167,7 @@ export function buildTasksAndLanesFromPlan({ plan, discovered, projectRoot, batc
167
167
  /**
168
168
  * @param {object} params
169
169
  */
170
- export async function skipTaskDoneOnDisk({
170
+ export function skipTaskDoneOnDisk({
171
171
  projectRoot,
172
172
  state,
173
173
  batchId,
@@ -1,6 +1,14 @@
1
1
  // @ts-nocheck
2
2
  /**
3
3
  * Lane task execution facade — re-exports split modules and phase transitions.
4
+ *
5
+ * Cycle-free ownership (#267 / SP-736): this facade participates in no batch import
6
+ * cycle and must stay that way. It must not import from the resume/limbo/reconcile
7
+ * cluster (resume-multi.mjs, post-merge-limbo.mjs, reconcile*.mjs, gate.mjs) —
8
+ * resume entry points (resume.mjs) import this facade, never the reverse. Lane-phase
9
+ * helpers live under engine-lanes/* leaves (queue, merge, review, matrix, commit,
10
+ * orch-sync). `tests/arch/import-cycles.test.mjs` enforces this with an empty
11
+ * ALLOWED_CLUSTER_CYCLES.
4
12
  */
5
13
 
6
14
  import fs from "node:fs";
@@ -80,43 +88,7 @@ export {
80
88
 
81
89
  export { runMatrixTaskOnLane, runMatrixSubLane } from "./engine-lanes/matrix-run.mjs";
82
90
 
83
- /**
84
- * @param {string} fromPhase
85
- * @param {string} toPhase
86
- */
87
- function phaseTransitionEventType(fromPhase, toPhase) {
88
- if (fromPhase === "planning" && toPhase === "running") return "batch.started";
89
- if (toPhase === "completed") return "batch.completed";
90
- if (toPhase === "failed") return "batch.failed";
91
- if (toPhase === "aborted") return "batch.aborted";
92
- return null;
93
- }
94
-
95
- /**
96
- * @param {object} params
97
- */
98
- function recordPhaseTransition({ projectRoot, batchId, fromPhase, toPhase, extra = {} }) {
99
- const type = phaseTransitionEventType(fromPhase, toPhase);
100
- if (!type) return;
101
- appendJournalEvent(projectRoot, batchId, type, {
102
- fromPhase,
103
- toPhase,
104
- ...extra,
105
- });
106
- }
107
-
108
- export function transitionPhase(state, newPhase, ctx) {
109
- const fromPhase = state.phase;
110
- if (fromPhase === newPhase) return;
111
- state.phase = newPhase;
112
- recordPhaseTransition({
113
- projectRoot: ctx.projectRoot,
114
- batchId: ctx.batchId,
115
- fromPhase,
116
- toPhase: newPhase,
117
- ...ctx.extra,
118
- });
119
- }
91
+ export { transitionPhase } from "./engine-lanes/phase.mjs";
120
92
 
121
93
  export async function runTaskOnLane({
122
94
  projectRoot,
@@ -10,7 +10,11 @@ import { runBatchPreflight, resolveTasksRoot } from "../config/spine-preflight-l
10
10
  import { loadSpineConfig } from "../config/spine-config-load.mjs";
11
11
  import { integrateOrchToBase } from "./integrate.mjs";
12
12
  import { installAttachedEngineShutdownHandlers } from "./attached-engine-handoff.mjs";
13
- import { finalizeBatchForIntegrate, tryFinalizePostMergeLimbo } from "./post-merge-limbo.mjs";
13
+ import {
14
+ finalizeBatchForIntegrate,
15
+ maybeFinalizeAfterWaveMerge,
16
+ tryFinalizePostMergeLimbo,
17
+ } from "./post-merge-limbo.mjs";
14
18
  import { detectPostMergeLimboForResume } from "./resume-multi-validate.mjs";
15
19
  import { appendJournalEvent } from "./journal.mjs";
16
20
  import { persistBatchMetaFromStartState } from "./batch-meta.mjs";
@@ -45,20 +49,7 @@ import {
45
49
  skipTaskDoneOnDisk,
46
50
  transitionPhase,
47
51
  } from "./engine-lanes.mjs";
48
- import { rejectNestedBatchStart } from "./batch-guards.mjs";
49
-
50
- /**
51
- * @param {string} batchId
52
- */
53
- function buildEnginePausedResult(batchId) {
54
- return {
55
- ok: true,
56
- exitCode: 0,
57
- batchId,
58
- paused: true,
59
- output: "Batch paused.\n",
60
- };
61
- }
52
+ import { buildEnginePausedResult, rejectNestedBatchStart } from "./batch-guards.mjs";
62
53
 
63
54
  export {
64
55
  assessWaveMergeEligibility,
@@ -285,7 +276,7 @@ export async function startBatch({
285
276
  if (pauseAtTick.stop) {
286
277
  return buildEnginePausedResult(batchId);
287
278
  }
288
- /** @type {Map<number, { lane: object, runs: Array<{ taskId: string, run: () => Promise<{ ok: boolean, aborted?: boolean }> }> }>} */
279
+ /** @type {Map<number, { lane: object, runs: Array<{ taskId: string, run: () => Promise<{ ok: boolean, aborted?: boolean }> | { ok: boolean, aborted?: boolean, skipped?: boolean } }> }>} */
289
280
  const runsByLane = new Map();
290
281
 
291
282
  for (let laneInTick = 0; laneInTick < (tick.lanes?.length ?? 0); laneInTick++) {
@@ -430,6 +421,7 @@ export async function startBatch({
430
421
  baseBranch,
431
422
  orchBranch,
432
423
  waveIndex: wave.index,
424
+ finalizeAfterWaveMerge: maybeFinalizeAfterWaveMerge,
433
425
  });
434
426
  if (!mergeResult.ok) {
435
427
  return {
@@ -0,0 +1,128 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Post-merge finalize leaf — wave-merge finalize hook without the limbo module graph (SP-734 / #267).
4
+ *
5
+ * Cycle-safe imports only (`journal.mjs`, `merge/wave-merge-state.mjs`). The heavy
6
+ * dependencies (`detectPostMergeLimboForResume` from resume-multi-validate.mjs and
7
+ * `tryFinalizePostMergeLimbo` from post-merge-limbo.mjs, which transitively pull in
8
+ * gate.mjs → reconcile → resume-multi) are injected via `createMaybeFinalizeAfterWaveMerge`
9
+ * so `engine-lanes/merge.mjs` never imports `post-merge-limbo.mjs`.
10
+ */
11
+
12
+ import { readJournalEvents } from "./journal.mjs";
13
+ import { recordWaveMergeResult } from "./merge/wave-merge-state.mjs";
14
+
15
+ /**
16
+ * Sync missing mergeResults rows from journal merge_completed events (SP-378, GitHub #59).
17
+ *
18
+ * @param {object} params
19
+ * @param {string} params.projectRoot
20
+ * @param {object} params.state
21
+ * @param {string} params.batchId
22
+ */
23
+ export function hydrateMergeResultsFromJournal({ projectRoot, state, batchId }) {
24
+ const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
25
+ if (!Number.isFinite(totalWaves) || totalWaves <= 0) {
26
+ return false;
27
+ }
28
+
29
+ const events = readJournalEvents(projectRoot, batchId);
30
+ const mergeCompleted = events.filter((event) => event.type === "batch.merge_completed");
31
+ if (mergeCompleted.length < 1) {
32
+ return false;
33
+ }
34
+
35
+ let changed = false;
36
+ for (let waveIndex = 0; waveIndex < totalWaves; waveIndex++) {
37
+ const waveEvents = mergeCompleted.filter(
38
+ (event) => Number(event.payload?.waveIndex ?? -1) === waveIndex,
39
+ );
40
+ if (waveEvents.length < 1) {
41
+ continue;
42
+ }
43
+
44
+ const existing = (state.mergeResults ?? []).find((entry) => entry?.waveIndex === waveIndex);
45
+ if (existing && String(existing.status ?? "") === "succeeded") {
46
+ continue;
47
+ }
48
+
49
+ const lastEvent = waveEvents.at(-1);
50
+ const mergeCommit =
51
+ typeof lastEvent?.payload?.mergeCommit === "string" ? lastEvent.payload.mergeCommit : null;
52
+ recordWaveMergeResult({
53
+ state,
54
+ waveIndex,
55
+ status: "succeeded",
56
+ mergeCommit,
57
+ });
58
+ changed = true;
59
+ }
60
+
61
+ return changed;
62
+ }
63
+
64
+ /**
65
+ * @param {object|null|undefined} state
66
+ * @param {number} waveIndex
67
+ */
68
+ export function isLastWaveIndex(state, waveIndex) {
69
+ if (!state || typeof state !== "object") return false;
70
+ const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
71
+ if (!Number.isFinite(totalWaves) || totalWaves <= 0) return false;
72
+ return waveIndex >= totalWaves - 1;
73
+ }
74
+
75
+ /**
76
+ * Build the post-wave-merge finalize hook with injected limbo dependencies (SP-734).
77
+ * Keeps `engine-lanes/merge.mjs` free of the post-merge-limbo → gate → reconcile →
78
+ * resume-multi import cycle: callers that already own the limbo graph inject the real
79
+ * implementations.
80
+ *
81
+ * @param {object} deps
82
+ * @param {(params: { projectRoot: string, state: object }) => boolean} deps.detectPostMergeLimbo
83
+ * @param {(params: object) => object|null} deps.tryFinalizeLimbo
84
+ * @returns {(params: object) => object|null}
85
+ */
86
+ export function createMaybeFinalizeAfterWaveMerge({ detectPostMergeLimbo, tryFinalizeLimbo }) {
87
+ /**
88
+ * Finalize immediately after the last wave merge so post-merge limbo never opens
89
+ * (SP-280, SP-281 — attached engine + resume orphan race).
90
+ *
91
+ * @param {object} params
92
+ * @param {string} params.projectRoot
93
+ * @param {object} params.state
94
+ * @param {string} params.batchId
95
+ * @param {string} params.orchBranch
96
+ * @param {number} params.waveIndex
97
+ * @param {boolean} [params.resumed]
98
+ * @param {boolean} [params.resumeForced]
99
+ */
100
+ return function maybeFinalizeAfterWaveMerge({
101
+ projectRoot,
102
+ state,
103
+ batchId,
104
+ orchBranch,
105
+ waveIndex,
106
+ resumed = false,
107
+ resumeForced = false,
108
+ }) {
109
+ if (String(state.phase ?? "") === "completed") {
110
+ return null;
111
+ }
112
+ hydrateMergeResultsFromJournal({ projectRoot, state, batchId: String(state.batchId ?? "") });
113
+ if (!isLastWaveIndex(state, waveIndex)) {
114
+ return null;
115
+ }
116
+ if (!detectPostMergeLimbo({ projectRoot, state })) {
117
+ return null;
118
+ }
119
+ return tryFinalizeLimbo({
120
+ projectRoot,
121
+ state,
122
+ batchId,
123
+ orchBranch,
124
+ resumed,
125
+ resumeForced,
126
+ });
127
+ };
128
+ }
@@ -11,9 +11,12 @@ import {
11
11
  } from "./detached-spawn.mjs";
12
12
  import { loadGateRecord, openIntegrateGateAfterBatchComplete } from "./gate.mjs";
13
13
  import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
14
- import { recordWaveMergeResult } from "./merge/wave-merge-state.mjs";
15
14
  import { detectPostMergeLimboForResume } from "./resume-multi-validate.mjs";
16
15
  import { isPostMergeLimbo } from "./limbo-detect.mjs";
16
+ import {
17
+ createMaybeFinalizeAfterWaveMerge,
18
+ hydrateMergeResultsFromJournal,
19
+ } from "./post-merge-finalize.mjs";
17
20
  import {
18
21
  clearBatchEnginePid,
19
22
  loadSpineBatchState,
@@ -22,6 +25,7 @@ import {
22
25
  } from "./state.mjs";
23
26
 
24
27
  export { isPostMergeLimbo } from "./limbo-detect.mjs";
28
+ export { hydrateMergeResultsFromJournal, isLastWaveIndex } from "./post-merge-finalize.mjs";
25
29
 
26
30
  const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
27
31
 
@@ -39,52 +43,8 @@ export function resolveDefaultSpineBin(spineBin) {
39
43
 
40
44
  /**
41
45
  * Sync missing mergeResults rows from journal merge_completed events (SP-378, GitHub #59).
42
- *
43
- * @param {object} params
44
- * @param {string} params.projectRoot
45
- * @param {object} params.state
46
- * @param {string} params.batchId
46
+ * Implementation lives in the `post-merge-finalize.mjs` leaf (SP-734); re-exported here.
47
47
  */
48
- export function hydrateMergeResultsFromJournal({ projectRoot, state, batchId }) {
49
- const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
50
- if (!Number.isFinite(totalWaves) || totalWaves <= 0) {
51
- return false;
52
- }
53
-
54
- const events = readJournalEvents(projectRoot, batchId);
55
- const mergeCompleted = events.filter((event) => event.type === "batch.merge_completed");
56
- if (mergeCompleted.length < 1) {
57
- return false;
58
- }
59
-
60
- let changed = false;
61
- for (let waveIndex = 0; waveIndex < totalWaves; waveIndex++) {
62
- const waveEvents = mergeCompleted.filter(
63
- (event) => Number(event.payload?.waveIndex ?? -1) === waveIndex,
64
- );
65
- if (waveEvents.length < 1) {
66
- continue;
67
- }
68
-
69
- const existing = (state.mergeResults ?? []).find((entry) => entry?.waveIndex === waveIndex);
70
- if (existing && String(existing.status ?? "") === "succeeded") {
71
- continue;
72
- }
73
-
74
- const lastEvent = waveEvents.at(-1);
75
- const mergeCommit =
76
- typeof lastEvent?.payload?.mergeCommit === "string" ? lastEvent.payload.mergeCommit : null;
77
- recordWaveMergeResult({
78
- state,
79
- waveIndex,
80
- status: "succeeded",
81
- mergeCommit,
82
- });
83
- changed = true;
84
- }
85
-
86
- return changed;
87
- }
88
48
 
89
49
  /**
90
50
  * @param {object} params
@@ -326,54 +286,23 @@ export function finalizeAttachedLandLoopBeforeExit({
326
286
  };
327
287
  }
328
288
 
329
- /**
330
- * @param {object|null|undefined} state
331
- * @param {number} waveIndex
332
- */
333
- export function isLastWaveIndex(state, waveIndex) {
334
- if (!state || typeof state !== "object") return false;
335
- const totalWaves = Number(state.totalWaves ?? state.wavePlan?.length ?? 0);
336
- if (!Number.isFinite(totalWaves) || totalWaves <= 0) return false;
337
- return waveIndex >= totalWaves - 1;
338
- }
339
-
340
289
  /**
341
290
  * Finalize immediately after the last wave merge so post-merge limbo never opens
342
291
  * (SP-280, SP-281 — attached engine + resume orphan race).
343
292
  *
293
+ * Built from the `post-merge-finalize.mjs` leaf with the limbo detection/finalize
294
+ * implementations injected (SP-734) so `engine-lanes/merge.mjs` can receive this hook
295
+ * without importing the limbo module graph.
296
+ *
344
297
  * @param {object} params
345
298
  * @param {boolean} [params.resumed]
346
299
  * @param {boolean} [params.resumeForced]
347
300
  * @returns {ReturnType<typeof finalizeBatchForIntegrate>|null}
348
301
  */
349
- export function maybeFinalizeAfterWaveMerge({
350
- projectRoot,
351
- state,
352
- batchId,
353
- orchBranch,
354
- waveIndex,
355
- resumed = false,
356
- resumeForced = false,
357
- }) {
358
- if (String(state.phase ?? "") === "completed") {
359
- return null;
360
- }
361
- hydrateMergeResultsFromJournal({ projectRoot, state, batchId: String(state.batchId ?? "") });
362
- if (!isLastWaveIndex(state, waveIndex)) {
363
- return null;
364
- }
365
- if (!detectPostMergeLimboForResume({ projectRoot, state })) {
366
- return null;
367
- }
368
- return tryFinalizePostMergeLimbo({
369
- projectRoot,
370
- state,
371
- batchId,
372
- orchBranch,
373
- resumed,
374
- resumeForced,
375
- });
376
- }
302
+ export const maybeFinalizeAfterWaveMerge = createMaybeFinalizeAfterWaveMerge({
303
+ detectPostMergeLimbo: detectPostMergeLimboForResume,
304
+ tryFinalizeLimbo: tryFinalizePostMergeLimbo,
305
+ });
377
306
 
378
307
  /**
379
308
  * Whether resume should take the post-merge limbo fast path (no worker re-run).
@@ -1,6 +1,27 @@
1
1
  // @ts-nocheck
2
2
  /**
3
3
  * Parse pi-spine batch-state.json (schema v1, tolerant reader).
4
+ *
5
+ * The normalized shape is declared locally so this reader stays a leaf in the batch import
6
+ * graph: a JSDoc type-import pointing at reconcile.mjs makes the arch cycle detector see a
7
+ * readers -> reconcile edge even though no runtime import exists (SP-735 / #267).
8
+ *
9
+ * @typedef {object} NormalizedBatchState
10
+ * @property {string} source
11
+ * @property {string} batchId
12
+ * @property {string} phase
13
+ * @property {string} baseBranch
14
+ * @property {string|null} orchBranch
15
+ * @property {unknown} startedAt
16
+ * @property {unknown} endedAt
17
+ * @property {number} failedTasks
18
+ * @property {number} succeededTasks
19
+ * @property {number} totalTasks
20
+ * @property {unknown[]} mergeResults
21
+ * @property {Array<object>} tasks
22
+ * @property {Array<object>} segments
23
+ * @property {Array<object>} lanes
24
+ * @property {Record<string, unknown>} raw
4
25
  */
5
26
 
6
27
  const TERMINAL_SUCCESS = new Set(["completed", "succeeded", "skipped"]);
@@ -9,7 +30,7 @@ const ACTIVE = new Set(["pending", "running"]);
9
30
 
10
31
  /**
11
32
  * @param {unknown} raw
12
- * @returns {import("../reconcile.mjs").NormalizedBatchState | null}
33
+ * @returns {NormalizedBatchState | null}
13
34
  */
14
35
  export function parseSpineBatchState(raw) {
15
36
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
@@ -1,6 +1,27 @@
1
1
  // @ts-nocheck
2
2
  /**
3
3
  * Parse Taskplane `.pi/batch-state.json` for dogfood reconciliation.
4
+ *
5
+ * The normalized shape is declared locally so this reader stays a leaf in the batch import
6
+ * graph: a JSDoc type-import pointing at reconcile.mjs makes the arch cycle detector see a
7
+ * readers -> reconcile edge even though no runtime import exists (SP-735 / #267).
8
+ *
9
+ * @typedef {object} NormalizedBatchState
10
+ * @property {string} source
11
+ * @property {string} batchId
12
+ * @property {string} phase
13
+ * @property {string} baseBranch
14
+ * @property {string|null} orchBranch
15
+ * @property {unknown} startedAt
16
+ * @property {unknown} endedAt
17
+ * @property {number} failedTasks
18
+ * @property {number} succeededTasks
19
+ * @property {number} totalTasks
20
+ * @property {unknown[]} mergeResults
21
+ * @property {Array<object>} tasks
22
+ * @property {Array<object>} segments
23
+ * @property {Array<object>} lanes
24
+ * @property {Record<string, unknown>} raw
4
25
  */
5
26
 
6
27
  const TERMINAL_SUCCESS = new Set(["completed", "succeeded", "skipped", "done"]);
@@ -9,7 +30,7 @@ const ACTIVE = new Set(["pending", "running", "executing"]);
9
30
 
10
31
  /**
11
32
  * @param {unknown} raw
12
- * @returns {import("../reconcile.mjs").NormalizedBatchState | null}
33
+ * @returns {NormalizedBatchState | null}
13
34
  */
14
35
  export function parseTaskplaneBatchState(raw) {
15
36
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
@@ -22,7 +22,7 @@ import { inferWorkerDoneMissingFailure } from "./diagnosis-worker-done-missing.m
22
22
  import { inferEngineOrphanCause } from "./diagnosis-parent-exit.mjs";
23
23
  import { findStubMarkedSucceededTask } from "./diagnosis-stub.mjs";
24
24
  import { detectOrphanRunning, journalEventsSinceResume } from "./orphan-detect.mjs";
25
- import { computePendingTasks } from "./resume-multi.mjs";
25
+ import { computePendingTasks } from "./resume-validation.mjs";
26
26
  import { computeStatusProgress } from "./status-json.mjs";
27
27
  import {
28
28
  detectBatchStateDrift,
@@ -8,7 +8,7 @@ import path from "node:path";
8
8
  import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
9
9
  import { appendJournalEvent } from "./journal.mjs";
10
10
  import { recomputeTaskCounters } from "./state.mjs";
11
- import { loadTaskFileScopePaths } from "./engine-lanes.mjs";
11
+ import { loadTaskFileScopePaths } from "./engine-lanes/queue.mjs";
12
12
  import { laneWorktreePath } from "./worktree.mjs";
13
13
 
14
14
  /**
@@ -7,10 +7,13 @@ import { loadSpineConfig } from "../config/spine-config-load.mjs";
7
7
  import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
8
8
  import { resolveTasksRoot } from "../config/spine-preflight-lib.mjs";
9
9
  import { assessWaveMergeEligibility } from "./engine-scope.mjs";
10
- import { mergeWaveLanesToOrch } from "./engine-lanes.mjs";
10
+ import { mergeWaveLanesToOrch } from "./engine-lanes/merge.mjs";
11
11
  import { recordResumePhaseTransition } from "./resume-common.mjs";
12
12
  import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
13
- import { finalizeResumedBatchForIntegrate } from "./post-merge-limbo.mjs";
13
+ import {
14
+ finalizeResumedBatchForIntegrate,
15
+ maybeFinalizeAfterWaveMerge,
16
+ } from "./post-merge-limbo.mjs";
14
17
  import {
15
18
  succeededWaveMergeIndices,
16
19
  waveTasksAllTerminal,
@@ -211,6 +214,7 @@ export async function resumeMultiTaskBatch({ projectRoot, force = false, resumeC
211
214
  orchBranch,
212
215
  waveIndex,
213
216
  resumed: true,
217
+ finalizeAfterWaveMerge: maybeFinalizeAfterWaveMerge,
214
218
  });
215
219
  if (!mergeResult.ok) {
216
220
  return {
@@ -16,7 +16,7 @@ import { finalizeResumedBatchForIntegrate, isPostMergeLimbo } from "./post-merge
16
16
  import { prepareOrphanResumeHandoff } from "./resume-engine.mjs";
17
17
  import { appendJournalEvent, readJournalEvents } from "./journal.mjs";
18
18
  import { commitLaneWorktree, filterPorcelain, gitPorcelain } from "./lane-commit.mjs";
19
- import { mergeLaneToOrch } from "./engine-lanes.mjs";
19
+ import { mergeLaneToOrch } from "./engine-lanes/merge.mjs";
20
20
  import {
21
21
  loadResumeFileScopePaths,
22
22
  recordResumePhaseTransition,
@@ -181,8 +181,9 @@ export function isEarlyArtifactHonorAllowed(reviewType, contractVerifyResult) {
181
181
 
182
182
  /**
183
183
  * @param {object} params
184
+ * @returns {Promise<object>} Resolves with the reviewer spawn result (real async child-process wait).
184
185
  */
185
- export async function spawnReviewerPi({
186
+ export function spawnReviewerPi({
186
187
  worktreePath,
187
188
  taskFolder,
188
189
  reviewPrompt,
@@ -194,11 +195,11 @@ export async function spawnReviewerPi({
194
195
  contractVerifyResult = null,
195
196
  }) {
196
197
  if (!reviewerPiCommandExists("pi")) {
197
- return {
198
+ return Promise.resolve({
198
199
  spawnFailed: true,
199
200
  exitCode: 127,
200
201
  error: "pi not available for reviewer spawn",
201
- };
202
+ });
202
203
  }
203
204
 
204
205
  const piArgs = buildReviewerPiArgs({
@@ -157,8 +157,10 @@ const defaultDeps = {
157
157
  * @param {string[]} [options.args]
158
158
  * @param {boolean} [options.follow]
159
159
  * @param {typeof defaultDeps} [options.deps]
160
+ * @returns {{ exitCode: number, output: string } | Promise<{ exitCode: number, output: string }>}
161
+ * Plain result for the non-follow path; a Promise that resolves on SIGINT/SIGTERM when following.
160
162
  */
161
- export async function runJournalFollow(options) {
163
+ export function runJournalFollow(options) {
162
164
  const { projectRoot, args = [], follow = true, deps = defaultDeps } = options;
163
165
  const { batchId: argBatchId, laneId, json } = parseJournalFollowArgs(args);
164
166
  let batchId = null;
@@ -190,8 +190,10 @@ const defaultDeps = {
190
190
  * @param {string[]} [options.args]
191
191
  * @param {boolean} [options.follow]
192
192
  * @param {typeof defaultDeps} [options.deps]
193
+ * @returns {{ exitCode: number, output: string } | Promise<{ exitCode: number, output: string }>}
194
+ * Plain result for the non-follow path; a Promise that resolves on SIGINT/SIGTERM when following.
193
195
  */
194
- export async function runLaneLogs(options) {
196
+ export function runLaneLogs(options) {
195
197
  const { projectRoot, args = [], follow: followOverride, deps = defaultDeps } = options;
196
198
  const { batchId: argBatchId, laneNumber, taskId: argTaskId, follow: argFollow } =
197
199
  parseLaneLogsArgs(args);
@@ -66,8 +66,9 @@ function parseSetArgs(argsText) {
66
66
  * @param {string} args
67
67
  * @param {{ notify: (message: string, level: string) => void }} ui
68
68
  * @param {string} [cwd]
69
+ * @returns {void}
69
70
  */
70
- export async function runSpineSettingsSlash(args, ui, cwd = process.cwd()) {
71
+ export function runSpineSettingsSlash(args, ui, cwd = process.cwd()) {
71
72
  const trimmed = args.trim();
72
73
 
73
74
  if (trimmed === "set" || trimmed.startsWith("set ")) {
@@ -223,8 +223,9 @@ export function emitWorkerRulesSelected(journal, payload) {
223
223
  * @param {string[]} [params.taskFileScope]
224
224
  * @param {number} [params.byteCap]
225
225
  * @param {WorkerRulesJournalContext} [params.journal]
226
+ * @returns {{ text: string, entries: object[], truncated: boolean, skipped: string[], bytesUsed: number, byteCap: number, selection: object, error?: string, blockedPath?: string }}
226
227
  */
227
- export async function buildWorkerContextAsync({
228
+ export function buildWorkerContextAsync({
228
229
  config = {},
229
230
  projectRoot = process.cwd(),
230
231
  taskFileScope = [],
@@ -334,8 +334,9 @@ function throwAnalyzeError(message, { suggestedCommand, exitCode = 2 } = {}) {
334
334
 
335
335
  /**
336
336
  * @param {{ projectRoot?: string, scope?: string }} [args]
337
+ * @returns {{ scope: ReturnType<typeof parseScope>, result: object, output: string, exitCode: number }}
337
338
  */
338
- export async function analyzeTasksScope({ projectRoot = process.cwd(), scope = 'all' } = {}) {
339
+ export function analyzeTasksScope({ projectRoot = process.cwd(), scope = 'all' } = {}) {
339
340
  const configResult = loadSpineConfig(projectRoot);
340
341
  if (configResult.error) {
341
342
  throwAnalyzeError(configResult.error.message, {
@@ -15,7 +15,23 @@ export const TEST_COMMAND_NPM_TEST_FIX_HINT =
15
15
  export const TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT =
16
16
  "npm test -- <path> runs the full suite, not the path argument. Use scoped node --test path/to.test.mjs instead.";
17
17
 
18
+ /** Code tasks should chain project lint/analyze in Contract testCommand (post-mortem v2.15.0 F-C). */
19
+ export const TEST_COMMAND_LINT_MISSING_FIX_HINT =
20
+ "Prefix Contract testCommand with project lint/analyze (pi-spine: npm run lint &&). Docs-only testCommand: true is exempt.";
21
+
18
22
  const PATCH_TASK_SIZES = new Set(["S", "M"]);
23
+ const LINT_IN_TEST_COMMAND_RE = /\b(?:lint|eslint|analyze)\b/;
24
+
25
+ /**
26
+ * @param {string | null | undefined} testCommand
27
+ * @returns {boolean}
28
+ */
29
+ function testCommandIncludesLintOrAnalyze(testCommand) {
30
+ if (!testCommand || testCommand === "true") {
31
+ return true;
32
+ }
33
+ return LINT_IN_TEST_COMMAND_RE.test(testCommand);
34
+ }
19
35
 
20
36
  /** Matches `npm test --` followed by at least one path/token argument. */
21
37
  export const NPM_TEST_DASH_DASH_RE = /\bnpm\s+test\s+--\s+\S+/;
@@ -94,6 +110,33 @@ export function collectNpmTestDashDashWarnings(parsed, options = {}) {
94
110
  return [formatNpmTestDashDashIssue(taskSize)];
95
111
  }
96
112
 
113
+ /**
114
+ * Warn when code-task contracts omit project lint/analyze from testCommand (post-mortem v2.15.0 F-C).
115
+ *
116
+ * @param {ReturnType<import("./packet/parse-prompt.mjs").parseContract>} parsed
117
+ * @param {{ taskSize?: "S"|"M"|"L"|"XL"|null }} [options]
118
+ * @returns {string[]}
119
+ */
120
+ export function collectLintMissingWarnings(parsed, options = {}) {
121
+ const taskSize = options.taskSize ?? null;
122
+ if (taskSize !== "S" && taskSize !== "M" && taskSize !== "L") {
123
+ return [];
124
+ }
125
+
126
+ const testCommand = parsed?.testCommand;
127
+ if (!testCommand || testCommand === "true") {
128
+ return [];
129
+ }
130
+
131
+ if (testCommandIncludesLintOrAnalyze(testCommand)) {
132
+ return [];
133
+ }
134
+
135
+ return [
136
+ `Contract testCommand omits project lint/analyze on Size ${taskSize} code task. ${TEST_COMMAND_LINT_MISSING_FIX_HINT}`,
137
+ ];
138
+ }
139
+
97
140
  /**
98
141
  * Warn when S/M task contracts chain full-suite gates in testCommand.
99
142
  *
@@ -129,11 +172,13 @@ export function collectTestCommandScopeWarnings(parsed, options = {}) {
129
172
  );
130
173
  }
131
174
 
175
+ warnings.push(...collectLintMissingWarnings(parsed, { taskSize }));
132
176
  return warnings;
133
177
  }
134
178
 
135
179
  if (taskSize === "L") {
136
180
  warnings.push(...collectNpmTestDashDashWarnings(parsed, { taskSize, mode }));
181
+ warnings.push(...collectLintMissingWarnings(parsed, { taskSize }));
137
182
  }
138
183
 
139
184
  return warnings;