pi-spine 2.27.0 → 2.27.1

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 (38) hide show
  1. package/bin/spine-worker-runner.mjs +1 -0
  2. package/package.json +1 -1
  3. package/skills/create-spine-tasks/SKILL.md +60 -33
  4. package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
  5. package/skills/create-spine-tasks/references/contract-template.md +52 -7
  6. package/skills/create-spine-tasks/references/prompt-template.md +72 -8
  7. package/skills/spine-release-operator/SKILL.md +30 -51
  8. package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
  9. package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
  10. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
  11. package/skills/spine-release-operator/references/publish-recovery.md +62 -0
  12. package/src/batch/diagnosis-alternatives.mjs +16 -1
  13. package/src/batch/diagnosis-pending-lane.mjs +18 -0
  14. package/src/batch/diagnosis-review-infra.mjs +144 -0
  15. package/src/batch/diagnosis-suggested-command.mjs +9 -0
  16. package/src/batch/diagnosis.mjs +19 -20
  17. package/src/batch/engine-lanes/merge.mjs +0 -8
  18. package/src/batch/engine-lanes/review-poll.mjs +4 -1
  19. package/src/batch/engine-lanes.mjs +0 -1
  20. package/src/batch/gate-posture-approve.mjs +154 -15
  21. package/src/batch/integrate-path-delete.mjs +85 -0
  22. package/src/batch/integrate-worktree.mjs +20 -27
  23. package/src/batch/provider-quota.mjs +1 -1
  24. package/src/batch/reconcile-diagnosis.mjs +24 -77
  25. package/src/batch/review-artifacts.mjs +3 -2
  26. package/src/batch/review-level-effective.mjs +19 -0
  27. package/src/batch/review-spawn.mjs +12 -1
  28. package/src/batch/review-step-run.mjs +14 -2
  29. package/src/batch/reviewer-provider-error.mjs +153 -0
  30. package/src/batch/worker-prompt.mjs +5 -2
  31. package/src/config/cursor-rules/discover.mjs +38 -1
  32. package/src/config/settings-fields.mjs +5 -0
  33. package/src/config/spine-config-schema.mjs +38 -0
  34. package/src/doctor/pi-extension-hooks.mjs +322 -0
  35. package/src/doctor/run-doctor-checks.mjs +14 -1
  36. package/src/tasks/packet/validate-prompt.mjs +11 -1
  37. package/src/tasks/validate-contract-warn.mjs +16 -0
  38. package/templates/spine-config.json +1 -1
@@ -25,6 +25,7 @@ Invoke explicitly: `/skill:spine-release-operator` or "run a spine release cycle
25
25
  | Manifest format | [references/release-manifest-template.md](references/release-manifest-template.md) |
26
26
  | Post-integrate regression gate | [references/post-integrate-regression-gate.md](references/post-integrate-regression-gate.md) |
27
27
  | npm publish mechanics | `docs/release/npm-publish.md` |
28
+ | Publish failure / smoke recovery | [references/publish-recovery.md](references/publish-recovery.md) |
28
29
  | Upstream bug filing | [references/issue-template.md](references/issue-template.md) |
29
30
 
30
31
  ## Success criteria
@@ -141,11 +142,17 @@ skills/spine-release-operator/scripts/collect-release-intake.sh {TARGET}
141
142
 
142
143
  ```bash
143
144
  gh issue list --repo beettlle/pi-spine --state open --limit 100 \
144
- --json number,title,labels,body
145
+ --json number,title,labels
145
146
  gh issue list --repo beettlle/pi-spine --state open --label documentation --json number,title,labels
146
147
  gh issue list --repo beettlle/pi-spine --state open --label bug --json number,title,labels
147
148
  ```
148
149
 
150
+ Do **not** pull `body` for the whole backlog — 100 issue bodies cost more context than the rest of intake combined. Shortlist by title and labels, then read bodies only for candidates:
151
+
152
+ ```bash
153
+ gh issue view NNN --repo beettlle/pi-spine --json number,title,labels,body
154
+ ```
155
+
149
156
  **Pending tasks:**
150
157
 
151
158
  ```bash
@@ -253,6 +260,12 @@ For every task in manifest scope:
253
260
  - [ ] Same-wave tasks have disjoint `fileScopeMustChange`
254
261
  - [ ] 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)
255
262
 
263
+ **Cost hygiene** (see create-spine-tasks [Cost-aware authoring](../create-spine-tasks/SKILL.md#cost-aware-authoring)):
264
+ - [ ] Deterministic steps (smoke runs, generators, evidence collection) are `Type: execute` tasks, not LLM steps — no LLM worker supervises a long-running command ([#276](https://github.com/beettlle/pi-spine/issues/276))
265
+ - [ ] Review Level: 1 for code, 0 for execute/docs-only; Level 2 only for security, data-model, or hot shared modules
266
+ - [ ] Testing steps are scoped (`node --test --test-reporter=dot <files>`; docs-only runs `rg -l` hits) — no full-suite run in S/M packets; §4.3a `release:check` owns the full suite
267
+ - [ ] File Scope lists concrete paths (directory globs pull extra rule packs into every worker turn)
268
+
256
269
  ```bash
257
270
  spine tasks validate <release-scope>
258
271
  spine tasks analyze <release-scope>
@@ -276,6 +289,8 @@ Before the first wave, confirm the release manifest records **`Operator approved
276
289
 
277
290
  **Model pin:** one worker pin for the release — do not mid-release-edit `.spine/spine-config.json` agent pins. Escalate models only on content/contract failure, never quota/403 or launch storms (F7, [#248](https://github.com/beettlle/pi-spine/issues/248)). A doctor/preflight quota-risk escalate signal is intentionally **out of scope** for this release — deferred to a later release ([#248](https://github.com/beettlle/pi-spine/issues/248) optional AC).
278
291
 
292
+ **Reviewer isolation:** reviewers no longer load user extensions — they spawn with `pi -ne` by default (v2.27.1, [#334](https://github.com/beettlle/pi-spine/issues/334)), so extension overrides matter only when `agents.reviewer.loadUserExtensions` is `true`. If a review spawn or provider failure hits a task whose `.DONE` is already in the lane, recover by re-review (`spine batch retry <taskId>` → `spine batch resume`), not salvage — salvage lands unreviewed work and is a last resort.
293
+
279
294
  **Quota fallback is provider failover, not escalation** ([#329](https://github.com/beettlle/pi-spine/issues/329), v2.27.0): when `agents.quotaFallbackProfile` names a profile on a different provider pool, the engine moves the batch to that pool automatically — once per batch, sticky, journaled, without editing `.spine/spine-config.json` — and retries each quota-exhausted task once in its lane worktree. This is the sanctioned mid-release response to quota exhaustion; it does not count as a pin override under the rule above. When it fires, record it in the release manifest by pasting the `Agent pin override: yes (<date>, auto quota fallback <pool> -> <profile>, batch <id>)` line from `spine status --diagnose`.
280
295
 
281
296
  **Detached-first:** See [agent-shell-batch-policy.md](../spine-autonomous-operator/references/agent-shell-batch-policy.md). Omit `--attached` for release waves unless the operator shell is a persistent interactive terminal that blocks until batch completion.
@@ -300,7 +315,7 @@ MonitorCreate:
300
315
  command: spine batch start <release-scope> --wave N # detached — omit --attached (#163)
301
316
  description: Release wave N
302
317
  timeout: 0
303
- onDone: spine status --diagnose → §4.3 land loop or §4.4 recovery
318
+ onDone: spine status --diagnose → read evidence/summary.md → §4.3 land loop or §4.4 recovery
304
319
  ```
305
320
 
306
321
  **Blocking fallback** (Cursor Agent, non-pi, or after MonitorCreate orphan — see [agent-shell-batch-policy.md](../spine-autonomous-operator/references/agent-shell-batch-policy.md)):
@@ -308,7 +323,13 @@ MonitorCreate:
308
323
  ```bash
309
324
  spine batch start <release-scope> --wave N
310
325
  spine status --diagnose
311
- spine wait --until completed,failed,needs_integrate,needs_retry,aborted --timeout 4h
326
+ spine wait --until completed,failed,needs_integrate,needs_retry,aborted --timeout 4h --interval 60
327
+ ```
328
+
329
+ **Context discipline:** one blocking `spine wait` (or one Monitor wake) per wave — not repeated `spine status` polls. On wake, read `.spine/runtime/<batchId>/evidence/summary.md` (~2 KB). Never read `evidence/test-output.txt` (~240 KB) in full; extract the result lines:
330
+
331
+ ```bash
332
+ rg -n '^ℹ (tests|pass|fail)|^not ok' .spine/runtime/<batchId>/evidence/test-output.txt
312
333
  ```
313
334
 
314
335
  **Foreground `--attached`** (persistent interactive human terminal only):
@@ -322,10 +343,10 @@ spine batch start <release-scope> --wave N --attached
322
343
  ```bash
323
344
  spine status --diagnose
324
345
  # or block:
325
- spine wait --until completed,failed,needs_integrate,needs_retry,aborted --timeout 2h
346
+ spine wait --until completed,failed,needs_integrate,needs_retry,aborted --timeout 2h --interval 60
326
347
  ```
327
348
 
328
- Optional pi watchdog: `LoopCreate` every 2m, `readOnly: true`, `maxFires: 50` — see pi-async-orchestration.
349
+ Optional pi watchdog: `LoopCreate` **only** when no MonitorCreate covers the batch — every 15m, `readOnly: true`, `maxFires: 8` — see pi-async-orchestration. Each fire is a full agent turn; a 2-minute loop over a 4-hour wave costs up to 120 turns of nothing.
329
350
 
330
351
  > **Wait progress (SP-754):** human-mode `spine wait` is not silent until exit — it prints a start banner, a `Wait progress:` line per poll (diagnosis, phase, wave, elapsed), and a terminal `Wait matched:` (stdout) or `Wait timed out` (stderr) headline. Quiet output between progress lines means the wait is between polls, not hung. Use `--json` when a machine parses the result.
331
352
 
@@ -439,7 +460,7 @@ spine preflight
439
460
  git status
440
461
  ```
441
462
 
442
- **pi async (preferred):** `MonitorCreate` with `npm run release:check 2>&1 | tee /tmp/pi-spine-release-check.log`, `timeout: 900000`, `onDone` to read **full log** and verify exit 0 — not log tail alone.
463
+ **pi async (preferred):** `MonitorCreate` with `npm run release:check 2>&1 | tee /tmp/pi-spine-release-check.log`, `timeout: 900000`, `onDone` to verify exit 0 from monitor metadata — not log tail alone. On failure, extract failures with `rg -n '^not ok|^ℹ fail|Error' /tmp/pi-spine-release-check.log` instead of reading the whole log into context.
443
464
 
444
465
  **Foreground fallback:**
445
466
 
@@ -567,52 +588,9 @@ Tag push + green **CI** (`ci.yml`) alone is **not** enough — `ci.yml` does not
567
588
 
568
589
  ### Publish failure recovery (HARD STOP — do not retag)
569
590
 
570
- When `release.yml` fails, diagnose with the failed job log before any recovery:
571
-
572
- ```bash
573
- gh run view <run-id> --log-failed
574
- ```
575
-
576
- | Symptom | Meaning | Action |
577
- |---------|---------|--------|
578
- | OIDC / trusted publisher mismatch / `ENEEDAUTH` | Trusted Publisher config wrong (workflow name, Environment name set while job has none, stage permission missing) | Fix npm Trusted Publisher; re-dispatch same tag — do **not** `npm version` again |
579
- | Legacy `E404` on PUT with `NPMSECRET` | Old token path still in use or secret bad | Prefer OIDC; emergency: rotate `NPMSECRET` only if workflow still uses token |
580
- | Validation steps failed (typecheck / lint / coverage / CLI smoke) | Tagged commit not release-safe | Fix on `main`, create a **new** patch version + tag; do not force-publish a broken tag |
581
- | CI gate failed for tagged commit | Pre-tag CI was red or missing | Fix `main` / re-run `ci.yml`; new tag if the old tag pointed at a bad commit |
582
- | Stage green but install missing version | Not approved yet | Approve with 2FA; do not retag |
583
- | GitHub Release step failed after stage succeeded | Notes/release page only | Create release manually; do not double-stage the same version without rejecting the prior stage first |
584
-
585
- **Re-dispatch existing tag** (after Trusted Publisher / transient registry fix):
586
-
587
- ```bash
588
- # Tag must already exist; this re-runs checkout → gate → stage → gh release
589
- # workflow_dispatch uses the workflow file from the branch you select (usually main)
590
- gh workflow run release.yml -f tag=v{VERSION}
591
- gh run list --workflow release.yml --limit 3
592
- gh run watch --exit-status <new-run-id>
593
- ```
594
-
595
- UI equivalent: **Actions → Release → Run workflow** → enter `v{VERSION}`.
596
-
597
- **Do not** delete/retag/`npm version` again when the only failure was auth/OIDC — package.json and the `v*` tag are already correct.
598
-
599
- Distinguish **stage auth failures** (table above) from **post-approve install E404/ETARGET** (registry lag F9 — smoke section below) and from **pre-approve missing version** (approve pending).
600
-
601
- Post-publish smoke per `docs/release/npm-publish.md` — **only after stage success and 2FA approve**. **Retry on registry lag (F9, [#247](https://github.com/beettlle/pi-spine/issues/247)):** the first `npm install -g` right after approve can fail with `ETARGET` / "No matching version found" while the registry propagates, even when `npm view` already lists the version. Prefer the bounded wrapper:
602
-
603
- ```bash
604
- scripts/post-publish-smoke.sh <version>
605
- ```
606
-
607
- Manual equivalent (bounded retries on `ETARGET`/404-class errors only — 5s/10s/20s backoff capped at 60s, max 6 attempts; non-lag install errors fail immediately and exhausted retries fail closed, never masked as lag):
608
-
609
- ```bash
610
- npm install -g pi-spine@<version>
611
- spine version
612
- spine doctor
613
- ```
591
+ When `release.yml` fails: `gh run view <run-id> --log-failed`, then follow the symptom table in [references/publish-recovery.md](references/publish-recovery.md). Auth/OIDC failures → fix Trusted Publisher and `gh workflow run release.yml -f tag=v{VERSION}` on the **existing** tag; never `npm version` or retag for auth-only failures.
614
592
 
615
- If retries exhaust, **STOP** — treat it as a real missing-version failure and investigate the publish; do not keep waiting silently.
593
+ Post-publish smoke (**only after stage success and 2FA approve**): `scripts/post-publish-smoke.sh <version>` — bounded retry on registry lag (F9, [#247](https://github.com/beettlle/pi-spine/issues/247)). If retries exhaust, **STOP** and investigate; manual steps in [references/publish-recovery.md](references/publish-recovery.md#post-publish-smoke).
616
594
 
617
595
  Update `spine-tasks/CONTEXT.md` release note (version + date).
618
596
 
@@ -644,6 +622,7 @@ Include the published version/tag in the close comment when closing at Phase 6 (
644
622
  8. **Verification** — paste `spine preflight` tail, **`npm run release:check` output** (or log path), test/coverage output
645
623
  9. **Publish** — version bumped (Y/N), tag pushed (Y/N), `release.yml` URL + conclusion, stage approved (Y/N), `npm view pi-spine version`, or "awaiting operator approval" / "blocked on Trusted Publisher" / "awaiting stage approve"
646
624
  10. **Issue tracker hygiene** — confirm every release-scoped `Closes #NNN` is CLOSED (paste `gh issue view` states or list)
625
+ 11. **Spend** — per wave from `spine metrics show --batch <batchId>`: tasks, attempts (retries), failed-attempt wall time, reviewer-infrastructure failures, quota fallbacks. Include token/cost totals once populated ([#338](https://github.com/beettlle/pi-spine/issues/338)); until then write "tokens: not recorded"
647
626
 
648
627
  ---
649
628
 
@@ -8,7 +8,7 @@ Repo: `beettlle/pi-spine`
8
8
 
9
9
  ```bash
10
10
  gh issue list --repo beettlle/pi-spine --state open --limit 100 \
11
- --json number,title,labels,body
11
+ --json number,title,labels
12
12
 
13
13
  gh issue list --repo beettlle/pi-spine --state open --label documentation \
14
14
  --json number,title,labels
@@ -20,6 +20,8 @@ gh issue list --repo beettlle/pi-spine --state open --label enhancement \
20
20
  --json number,title,labels
21
21
  ```
22
22
 
23
+ Read bodies only for shortlisted candidates: `gh issue view NNN --repo beettlle/pi-spine --json number,title,labels,body`.
24
+
23
25
  ## Label taxonomy
24
26
 
25
27
  | Label | Release bucket | Priority notes |
@@ -20,9 +20,12 @@ Use in **pi sessions** when long-running shell work would waste the agent contex
20
20
 
21
21
  ```text
22
22
  Monitor for wave N completed. Run spine status --diagnose.
23
- - needs_integrate: inspect .spine/runtime/<batchId>/evidence/ → gate approve → integrate → npm install → batch complete.
23
+ - needs_integrate: read .spine/runtime/<batchId>/evidence/summary.md (~2 KB) and
24
+ rg -n '^ℹ (tests|pass|fail)|^not ok' .spine/runtime/<batchId>/evidence/test-output.txt
25
+ → gate approve → integrate → npm install → batch complete.
26
+ Never read test-output.txt or coverage-output.txt in full (hundreds of KB).
24
27
  - needs_retry / failed / aborted: follow recovery table; do not start next wave.
25
- - running: optional LoopCreate watchdog (below) or spine watch.
28
+ - running: one blocking `spine wait --until … --interval 60`; LoopCreate watchdog only if no Monitor covers the batch.
26
29
  Paste diagnosis headline and exit evidence. Do not claim success without CLI output.
27
30
  ```
28
31
 
@@ -30,29 +33,30 @@ Paste diagnosis headline and exit evidence. Do not claim success without CLI out
30
33
 
31
34
  ```text
32
35
  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.
34
36
  If exit 0: present pre-publish checklist from docs/release/npm-publish.md.
35
- If non-zero: STOP; summarize first failing step; do not bump version.
37
+ If non-zero: rg -n '^not ok|^ℹ fail|Error' /tmp/pi-spine-release-check.log — read only those
38
+ hits plus surrounding lines (rg -C 5) for the first failure; do not load the whole log.
39
+ STOP; summarize first failing step; do not bump version.
36
40
  ```
37
41
 
38
42
  ---
39
43
 
40
44
  ## When to use LoopCreate (watchdog only)
41
45
 
42
- Use when MonitorCreate's completion wake is insufficient or you need lightweight status polling without blocking the session.
46
+ Use **only** when no MonitorCreate covers the command (for example, a batch started from another shell). Every fire is a full agent turn, so a fast loop over a multi-hour wave spends tokens on "still running".
43
47
 
44
48
  ```text
45
49
  LoopCreate:
46
- trigger: "2m"
50
+ trigger: "15m"
47
51
  readOnly: true
48
- maxFires: 50
52
+ maxFires: 8
49
53
  prompt: |
50
54
  Check spine status --diagnose for batch <batchId>.
51
55
  If diagnosis is terminal (needs_integrate, failed, aborted, needs_retry): LoopDelete this loop and run onDone actions.
52
- If still running: do nothing.
56
+ If still running: reply "running" only — do not read logs or evidence.
53
57
  ```
54
58
 
55
- Prefer Monitor's built-in completion wake over LoopCreate when MonitorCreate was used for the same command.
59
+ `maxFires: 8` × 15m covers a 2-hour wave; recreate the loop if the wave runs longer. When MonitorCreate already wraps the command, its completion wake replaces the loop — do not run both.
56
60
 
57
61
  ---
58
62
 
@@ -34,7 +34,14 @@ npm run release:check
34
34
  echo "release:check exit: $?"
35
35
  ```
36
36
 
37
- **If exit is non-zero:** STOP. Fix on `main`, commit, re-run gate. Do not start the next wave, push, or tag.
37
+ **If exit is non-zero:** STOP. Find the failures without loading the whole log (the full-suite log is hundreds of KB):
38
+
39
+ ```bash
40
+ rg -n '^not ok|^ℹ fail|Error' /tmp/pi-spine-post-integrate-wave-${WAVE:-main}.log
41
+ rg -n -C 5 '^not ok' /tmp/pi-spine-post-integrate-wave-${WAVE:-main}.log # context for the first failures
42
+ ```
43
+
44
+ Fix on `main`, commit, re-run gate. Do not start the next wave, push, or tag.
38
45
 
39
46
  ---
40
47
 
@@ -0,0 +1,62 @@
1
+ # Publish failure recovery and post-publish smoke
2
+
3
+ Read this only when `release.yml` fails or post-approve smoke fails. The happy path lives in [SKILL.md](../SKILL.md) Phase 6.
4
+
5
+ ---
6
+
7
+ ## Publish failure recovery (HARD STOP — do not retag)
8
+
9
+ When `release.yml` fails, diagnose with the failed job log before any recovery:
10
+
11
+ ```bash
12
+ gh run view <run-id> --log-failed
13
+ ```
14
+
15
+ | Symptom | Meaning | Action |
16
+ |---------|---------|--------|
17
+ | OIDC / trusted publisher mismatch / `ENEEDAUTH` | Trusted Publisher config wrong (workflow name, Environment name set while job has none, stage permission missing) | Fix npm Trusted Publisher; re-dispatch same tag — do **not** `npm version` again |
18
+ | Legacy `E404` on PUT with `NPMSECRET` | Old token path still in use or secret bad | Prefer OIDC; emergency: rotate `NPMSECRET` only if workflow still uses token |
19
+ | Validation steps failed (typecheck / lint / coverage / CLI smoke) | Tagged commit not release-safe | Fix on `main`, create a **new** patch version + tag; do not force-publish a broken tag |
20
+ | CI gate failed for tagged commit | Pre-tag CI was red or missing | Fix `main` / re-run `ci.yml`; new tag if the old tag pointed at a bad commit |
21
+ | Stage green but install missing version | Not approved yet | Approve with 2FA; do not retag |
22
+ | GitHub Release step failed after stage succeeded | Notes/release page only | Create release manually; do not double-stage the same version without rejecting the prior stage first |
23
+
24
+ ### Re-dispatch existing tag
25
+
26
+ After a Trusted Publisher or transient registry fix:
27
+
28
+ ```bash
29
+ # Tag must already exist; this re-runs checkout → gate → stage → gh release
30
+ # workflow_dispatch uses the workflow file from the branch you select (usually main)
31
+ gh workflow run release.yml -f tag=v{VERSION}
32
+ gh run list --workflow release.yml --limit 3
33
+ gh run watch --exit-status <new-run-id>
34
+ ```
35
+
36
+ UI equivalent: **Actions → Release → Run workflow** → enter `v{VERSION}`.
37
+
38
+ **Do not** delete/retag/`npm version` again when the only failure was auth/OIDC — `package.json` and the `v*` tag are already correct.
39
+
40
+ Distinguish **stage auth failures** (table above) from **post-approve install E404/ETARGET** (registry lag F9 — below) and from **pre-approve missing version** (approve pending).
41
+
42
+ ---
43
+
44
+ ## Post-publish smoke
45
+
46
+ Run per `docs/release/npm-publish.md` — **only after stage success and 2FA approve**.
47
+
48
+ **Retry on registry lag (F9, [#247](https://github.com/beettlle/pi-spine/issues/247)):** the first `npm install -g` right after approve can fail with `ETARGET` / "No matching version found" while the registry propagates, even when `npm view` already lists the version. Prefer the bounded wrapper:
49
+
50
+ ```bash
51
+ scripts/post-publish-smoke.sh <version>
52
+ ```
53
+
54
+ Manual equivalent (bounded retries on `ETARGET`/404-class errors only — 5s/10s/20s backoff capped at 60s, max 6 attempts; non-lag install errors fail immediately and exhausted retries fail closed, never masked as lag):
55
+
56
+ ```bash
57
+ npm install -g pi-spine@<version>
58
+ spine version
59
+ spine doctor
60
+ ```
61
+
62
+ If retries exhaust, **STOP** — treat it as a real missing-version failure and investigate the publish; do not keep waiting silently.
@@ -2,18 +2,25 @@
2
2
  * Alternative operator commands per diagnosis (extracted for module size budget).
3
3
  */
4
4
  import { buildWorkerDoneMissingAlternatives } from "./diagnosis-worker-done-missing.mjs";
5
+ import { isReviewInfraExitReason } from "./diagnosis-review-infra.mjs";
5
6
 
6
7
  /**
7
8
  * @param {string} diagnosis
8
9
  * @param {object} [ctx]
9
10
  * @param {string|null} [ctx.failedTaskId]
10
11
  * @param {string|null} [ctx.batchId]
12
+ * @param {string|null} [ctx.exitReason]
11
13
  * @param {object[]} [ctx.pendingLaneLandTasks]
12
14
  */
13
15
  export function buildAlternatives(diagnosis, ctx = {}) {
14
16
  const common = ["spine status --diagnose"];
15
17
 
16
- if ((ctx.pendingLaneLandTasks?.length ?? 0) > 0) {
18
+ // SP-821 / #334: needs_retry caused by a review-infrastructure exit reason
19
+ // must take the labeled salvage-dry-run path below, even when the task also
20
+ // sits in the pending-lane set — salvage --integrate stays forbidden there.
21
+ const reviewInfraNeedsRetry = diagnosis === "needs_retry" && isReviewInfraExitReason(ctx.exitReason);
22
+
23
+ if ((ctx.pendingLaneLandTasks?.length ?? 0) > 0 && !reviewInfraNeedsRetry) {
17
24
  return [
18
25
  ctx.batchId
19
26
  ? `spine batch salvage --batch ${ctx.batchId} --dry-run`
@@ -43,6 +50,14 @@ export function buildAlternatives(diagnosis, ctx = {}) {
43
50
  case "integrate_isolated_ok":
44
51
  return ["git pull", "spine batch complete", ...common];
45
52
  case "needs_retry":
53
+ if (isReviewInfraExitReason(ctx.exitReason)) {
54
+ // SP-821 / #334: salvage stays available as a dry-run inspection only,
55
+ // explicitly labeled as landing unreviewed work.
56
+ const salvageDryRun = ctx.batchId
57
+ ? `spine batch salvage --batch ${ctx.batchId} --dry-run (lands unreviewed work)`
58
+ : "spine batch salvage --batch <batchId> --dry-run (lands unreviewed work)";
59
+ return [salvageDryRun, "spine batch abort", ...common];
60
+ }
46
61
  return ["spine batch abort", "/spine-skip-task", "/spine-resume --force", ...common];
47
62
  case "worker_orphaned":
48
63
  return ["spine batch abort", "spine batch resume --force", ...common];
@@ -5,6 +5,10 @@
5
5
 
6
6
  import { isEngineProcessAlive } from "../process/liveness.mjs";
7
7
  import { readBatchEnginePid, readBatchEngineStartedAt } from "./state-guards.mjs";
8
+ import {
9
+ REVIEW_INFRASTRUCTURE_EXIT_REASONS,
10
+ resolveTaskPrimaryFailureExitReason,
11
+ } from "./diagnosis-review-infra.mjs";
8
12
 
9
13
  /**
10
14
  * Tasks with lane `.DONE` but not on main — lane commits never landed (#201 / SP-645).
@@ -54,6 +58,20 @@ export function shouldDiagnosePendingLaneLand(signals, deps = {}) {
54
58
  if (isLiveEngineMidTask(signals?.raw, deps)) return false;
55
59
  const pending = findPendingLaneLandTasks(signals.tasks);
56
60
  if (pending.length === 0) return false;
61
+ // SP-821 / #334: when every pending-lane task's primary failure exit reason
62
+ // is a review-infrastructure reason (spawn failure / timeout / provider
63
+ // error), no verdict was ever produced. Re-run the review — never
64
+ // salvage-integrate unreviewed code. Any other reason (or no failure at
65
+ // all) keeps today's salvage guidance.
66
+ if (
67
+ pending.every((task) =>
68
+ REVIEW_INFRASTRUCTURE_EXIT_REASONS.has(
69
+ String(resolveTaskPrimaryFailureExitReason(task, signals) ?? ""),
70
+ ),
71
+ )
72
+ ) {
73
+ return false;
74
+ }
57
75
  // Only when orch already appears merged — otherwise healthy pre-integrate
58
76
  // waves (doneInLane, awaiting integrate) must stay needs_integrate / settled.
59
77
  if (signals.git?.orchMergedToBase !== true) return false;
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Review-infrastructure exit reasons and failure-exit-reason resolution shared
3
+ * by `reconcile-diagnosis.mjs` and `diagnosis-pending-lane.mjs` (SP-821/#334).
4
+ * Leaf module — importing it from anywhere in `src/batch/` keeps the import
5
+ * graph acyclic (checked by tests/arch/import-cycles.test.mjs).
6
+ */
7
+
8
+ /**
9
+ * Exit reasons where reviewer *infrastructure* failed: the reviewer failed to
10
+ * spawn, timed out, or hit a provider error, so no verdict was produced. The
11
+ * implementation itself is not the failure (#291 / SP-718). Covers all three
12
+ * engine review types; the provider-error variants were added by SP-820.
13
+ *
14
+ * @type {ReadonlySet<string>}
15
+ */
16
+ export const REVIEW_INFRASTRUCTURE_EXIT_REASONS = new Set([
17
+ "plan_review_spawn_failed",
18
+ "plan_review_timeout",
19
+ "plan_review_provider_error",
20
+ "code_review_spawn_failed",
21
+ "code_review_timeout",
22
+ "code_review_provider_error",
23
+ "final_review_spawn_failed",
24
+ "final_review_timeout",
25
+ "final_review_provider_error",
26
+ ]);
27
+
28
+ /**
29
+ * @param {string|null|undefined} exitReason
30
+ * @returns {boolean}
31
+ */
32
+ export function isReviewInfraExitReason(exitReason) {
33
+ return REVIEW_INFRASTRUCTURE_EXIT_REASONS.has(String(exitReason ?? ""));
34
+ }
35
+
36
+ /**
37
+ * Review type ("plan" | "code" | "final") for a review-infra exit reason.
38
+ *
39
+ * @param {string|null|undefined} exitReason
40
+ * @returns {string|null}
41
+ */
42
+ export function resolveReviewInfraType(exitReason) {
43
+ const match = String(exitReason ?? "").match(/^(plan|code|final)_review_(?:spawn_failed|timeout|provider_error)$/);
44
+ return match ? (match[1] ?? null) : null;
45
+ }
46
+
47
+ /**
48
+ * @param {string|null|undefined} exitReason
49
+ * @returns {boolean}
50
+ */
51
+ export function isReviewInfraProviderError(exitReason) {
52
+ return String(exitReason ?? "").endsWith("_provider_error");
53
+ }
54
+
55
+ /**
56
+ * @param {unknown} rawTasks
57
+ * @param {string|null} failedTaskId
58
+ * @returns {string|null}
59
+ */
60
+ export function resolveFailedExitReason(rawTasks, failedTaskId) {
61
+ if (!failedTaskId || !Array.isArray(rawTasks)) return null;
62
+ const match = rawTasks.find((/** @type {any} */ entry) => {
63
+ if (!entry || typeof entry !== "object") return false;
64
+ return String(entry.taskId ?? entry.id ?? "") === failedTaskId;
65
+ });
66
+ if (!match || typeof match !== "object") return null;
67
+ const exitReason = /** @type {{ exitReason?: unknown }} */ (match).exitReason;
68
+ return typeof exitReason === "string" && exitReason ? exitReason : null;
69
+ }
70
+
71
+ /**
72
+ * @param {string|null} failedTaskId
73
+ * @param {Record<string, any>} signals
74
+ * @returns {string|null}
75
+ */
76
+ export function resolvePrimaryFailureExitReason(failedTaskId, signals) {
77
+ const fromTask = resolveFailedExitReason(signals.raw?.tasks, failedTaskId);
78
+ if (fromTask) return fromTask;
79
+ if (!failedTaskId) return null;
80
+ if (Array.isArray(signals.segments)) {
81
+ const segment = signals.segments.find((/** @type {any} */ entry) => entry?.taskId === failedTaskId);
82
+ const classification = segment?.classification;
83
+ if (
84
+ typeof classification === "string" &&
85
+ classification &&
86
+ classification !== "terminal-failure"
87
+ ) {
88
+ return classification;
89
+ }
90
+ }
91
+ if (Array.isArray(signals.journalEvents)) {
92
+ for (let index = signals.journalEvents.length - 1; index >= 0; index -= 1) {
93
+ const event = signals.journalEvents[index];
94
+ if (event.type !== "task.failed") continue;
95
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
96
+ if (eventTaskId !== failedTaskId) continue;
97
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
98
+ const reason = payload.exitReason ?? payload.classification;
99
+ if (typeof reason === "string" && reason) return reason;
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * Exit reason for a classified task entry: the entry's own `exitReason` when
107
+ * present, else the primary failure resolution (raw state → segments →
108
+ * journal `task.failed`). Parsed batch-state tasks drop `exitReason`
109
+ * (normalizeTasks), so the fallback keeps journal-only timelines working.
110
+ *
111
+ * @param {Record<string, any>|null|undefined} task
112
+ * @param {Record<string, any>} signals
113
+ * @returns {string|null}
114
+ */
115
+ export function resolveTaskPrimaryFailureExitReason(task, signals) {
116
+ const fromTask = task?.exitReason;
117
+ if (typeof fromTask === "string" && fromTask) return fromTask;
118
+ return resolvePrimaryFailureExitReason(String(task?.taskId ?? ""), signals);
119
+ }
120
+
121
+ /**
122
+ * Headline for a needs_retry diagnosis caused by a review-infrastructure exit
123
+ * reason: the reviewer produced no verdict, so the review should re-run —
124
+ * not salvage-integrate unreviewed code (SP-821/#334, reversing SP-762).
125
+ * Provider-error variants point at `spine doctor` for launch diagnosis.
126
+ *
127
+ * @param {string} batchLabel
128
+ * @param {object} ctx
129
+ * @param {string|null} [ctx.exitReason]
130
+ * @param {string|null} [ctx.failedTaskId]
131
+ * @returns {string|null} null when `ctx.exitReason` is not a review-infra reason
132
+ */
133
+ export function buildReviewInfraHeadline(batchLabel, ctx = {}) {
134
+ const exitReason = ctx.exitReason ?? "";
135
+ if (!isReviewInfraExitReason(exitReason)) return null;
136
+ const reviewType = resolveReviewInfraType(exitReason) ?? "review";
137
+ const providerError = isReviewInfraProviderError(exitReason);
138
+ const problem = providerError
139
+ ? `${reviewType} review hit a provider error`
140
+ : `${reviewType} review produced no verdict`;
141
+ const taskSuffix = ctx.failedTaskId ? ` for task ${ctx.failedTaskId}` : "";
142
+ const doctorSuffix = providerError ? " — run spine doctor" : "";
143
+ return `${batchLabel} ${problem}${taskSuffix} (lane work is done) — re-run the review${doctorSuffix}`;
144
+ }
@@ -19,6 +19,7 @@ import { buildPrimaryFailureSuggestedCommand } from "./diagnosis-primary-failure
19
19
  import { buildEngineOrphanParentExitSuggestedCommand } from "./diagnosis-parent-exit.mjs";
20
20
  import { sanitizeRetrySuggestedCommand } from "./diagnosis-retry-command.mjs";
21
21
  import { buildPendingLaneLandSuggestedCommand } from "./diagnosis-pending-lane.mjs";
22
+ import { isReviewInfraExitReason } from "./diagnosis-review-infra.mjs";
22
23
 
23
24
  /**
24
25
  * @param {string} diagnosis
@@ -89,6 +90,14 @@ export function buildSuggestedCommand(diagnosis, ctx = {}) {
89
90
  if (ctx.launchFailureKind === "worktree_unhealthy") {
90
91
  return "spine doctor";
91
92
  }
93
+ // SP-821 / #334: review-infrastructure failures must re-run the review —
94
+ // `spine batch retry` resumes at the review (runWorker no-ops on the
95
+ // existing lane .DONE). Never a salvage command for these reasons.
96
+ if (isReviewInfraExitReason(ctx.exitReason)) {
97
+ return ctx.failedTaskId
98
+ ? `spine batch retry ${ctx.failedTaskId}`
99
+ : "spine status --diagnose";
100
+ }
92
101
  if (ctx.salvageRetryCommand) {
93
102
  return sanitizeRetrySuggestedCommand(ctx.salvageRetryCommand, ctx.failedTaskId);
94
103
  }
@@ -67,6 +67,17 @@ export {
67
67
  findPendingLaneLandTasks,
68
68
  shouldDiagnosePendingLaneLand,
69
69
  } from "./diagnosis-pending-lane.mjs";
70
+ import {
71
+ buildReviewInfraHeadline,
72
+ isReviewInfraExitReason,
73
+ } from "./diagnosis-review-infra.mjs";
74
+ export {
75
+ buildReviewInfraHeadline,
76
+ isReviewInfraExitReason,
77
+ isReviewInfraProviderError,
78
+ REVIEW_INFRASTRUCTURE_EXIT_REASONS,
79
+ resolveReviewInfraType,
80
+ } from "./diagnosis-review-infra.mjs";
70
81
  export { buildSuggestedCommand } from "./diagnosis-suggested-command.mjs";
71
82
  import { buildSuggestedCommand } from "./diagnosis-suggested-command.mjs";
72
83
  export { buildBackground, buildAssessmentReason } from "./diagnosis-handoff-packet.mjs";
@@ -102,12 +113,6 @@ const NO_PAUSE_DIAGNOSES = new Set([
102
113
  "integrate_isolated_ok",
103
114
  "engine_still_running",
104
115
  ]);
105
- const REVIEW_SPAWN_FAILURE_EXIT_REASONS = new Set([
106
- "code_review_spawn_failed",
107
- "code_review_timeout",
108
- "final_review_spawn_failed",
109
- "final_review_timeout",
110
- ]);
111
116
 
112
117
  /**
113
118
  * @param {string} diagnosis
@@ -176,20 +181,14 @@ export function buildHeadline(diagnosis, ctx = {}) {
176
181
  if (ctx.launchFailureKind === "worktree_unhealthy") {
177
182
  return `${batchLabel} failed at worker launch — repair lane worktree git, then retry`;
178
183
  }
179
- if (REVIEW_SPAWN_FAILURE_EXIT_REASONS.has(ctx.exitReason ?? "")) {
180
- const isFinal = ctx.exitReason.startsWith("final_review");
181
- const isTimeout = ctx.exitReason.endsWith("_timeout");
182
- const reviewKind = isFinal ? "final review" : "code review";
183
-
184
- if (isTimeout) {
185
- return ctx.failedTaskId
186
- ? `${batchLabel} ${reviewKind} timed out for task ${ctx.failedTaskId} — retry or increase SPINE_REVIEW_TIMEOUT_MS`
187
- : `${batchLabel} reviewer spawn timed out — retry`;
188
- }
189
-
190
- return ctx.failedTaskId
191
- ? `${batchLabel} ${reviewKind} spawn failed for task ${ctx.failedTaskId} — retry`
192
- : `${batchLabel} reviewer spawn failed — retry`;
184
+ if (isReviewInfraExitReason(ctx.exitReason)) {
185
+ // SP-821 / #334: reviewer infrastructure failed (spawn failure /
186
+ // timeout / provider error, plan+code+final) — no verdict was produced,
187
+ // so re-run the review rather than salvage-integrating unreviewed code.
188
+ return (
189
+ buildReviewInfraHeadline(batchLabel, ctx) ??
190
+ `${batchLabel} review produced no verdict — re-run the review`
191
+ );
193
192
  }
194
193
  if (ctx.salvageChangedFileCount > 0 && ctx.failedTaskId) {
195
194
  return `${batchLabel} failed (${ctx.failedTaskId}): ${ctx.salvageChangedFileCount} uncommitted file(s) in scope`;
@@ -490,14 +490,6 @@ export function tryAutoResolveMergeConflicts(projectRoot, options = {}) {
490
490
  };
491
491
  }
492
492
 
493
- /**
494
- * @deprecated use tryAutoResolveMergeConflicts
495
- * @param {string} projectRoot
496
- */
497
- export function tryAutoResolveRulesManifestMergeConflict(projectRoot) {
498
- return tryAutoResolveMergeConflicts(projectRoot, {});
499
- }
500
-
501
493
  /**
502
494
  * @param {string} projectRoot
503
495
  * @param {string[]} args
@@ -23,6 +23,7 @@ import {
23
23
  shouldEmitReviewResumed,
24
24
  } from "../review.mjs";
25
25
  import { shouldUseReviewStub } from "./review-stub.mjs";
26
+ import { REVIEW_PROVIDER_ERROR_REASON } from "../reviewer-provider-error.mjs";
26
27
 
27
28
  /**
28
29
  * @param {string} taskFolder
@@ -329,7 +330,9 @@ export async function runReviewPollLoop({
329
330
  const spawnExitReason =
330
331
  reviewResult.reason === REVIEW_TIMEOUT_REASON
331
332
  ? `${reviewType}_review_timeout`
332
- : `${reviewType}_review_spawn_failed`;
333
+ : reviewResult.reason === REVIEW_PROVIDER_ERROR_REASON
334
+ ? `${reviewType}_review_provider_error`
335
+ : `${reviewType}_review_spawn_failed`;
333
336
  recordReviewTaskFailure({
334
337
  projectRoot,
335
338
  state,