pi-spine 2.26.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 (63) hide show
  1. package/README.md +1 -1
  2. package/bin/spine-review-step.mjs +8 -1
  3. package/bin/spine-worker-runner.mjs +15 -1
  4. package/package.json +3 -3
  5. package/skills/create-spine-tasks/SKILL.md +60 -33
  6. package/skills/create-spine-tasks/references/authoring-evidence.md +58 -0
  7. package/skills/create-spine-tasks/references/contract-template.md +52 -7
  8. package/skills/create-spine-tasks/references/prompt-template.md +72 -8
  9. package/skills/spine-release-operator/SKILL.md +33 -51
  10. package/skills/spine-release-operator/references/issue-intake-checklist.md +3 -1
  11. package/skills/spine-release-operator/references/pi-async-orchestration.md +13 -9
  12. package/skills/spine-release-operator/references/post-integrate-regression-gate.md +8 -1
  13. package/skills/spine-release-operator/references/publish-recovery.md +62 -0
  14. package/src/batch/batch-meta-reconstruct.mjs +3 -0
  15. package/src/batch/contract-exec.mjs +2 -2
  16. package/src/batch/contract-parse.mjs +2 -2
  17. package/src/batch/contract-prelanded.mjs +2 -2
  18. package/src/batch/diagnosis-alternatives.mjs +16 -1
  19. package/src/batch/diagnosis-handoff-packet.mjs +74 -0
  20. package/src/batch/diagnosis-pending-lane.mjs +52 -1
  21. package/src/batch/diagnosis-review-infra.mjs +144 -0
  22. package/src/batch/diagnosis-suggested-command.mjs +9 -0
  23. package/src/batch/diagnosis.mjs +19 -20
  24. package/src/batch/engine-lanes/merge.mjs +0 -8
  25. package/src/batch/engine-lanes/quota-fallback-run.mjs +153 -0
  26. package/src/batch/engine-lanes/quota-fallback-state.mjs +202 -0
  27. package/src/batch/engine-lanes/review-code.mjs +1 -0
  28. package/src/batch/engine-lanes/review-final.mjs +83 -46
  29. package/src/batch/engine-lanes/review-plan.mjs +22 -2
  30. package/src/batch/engine-lanes/review-poll.mjs +51 -2
  31. package/src/batch/engine-lanes.mjs +6 -8
  32. package/src/batch/gate-posture-approve.mjs +154 -15
  33. package/src/batch/integrate-path-delete.mjs +85 -0
  34. package/src/batch/integrate-worktree.mjs +20 -27
  35. package/src/batch/journal.mjs +15 -0
  36. package/src/batch/metrics.mjs +13 -1
  37. package/src/batch/provider-quota.mjs +220 -0
  38. package/src/batch/quota-fallback.mjs +319 -0
  39. package/src/batch/reconcile-diagnosis-context.mjs +22 -0
  40. package/src/batch/reconcile-diagnosis.mjs +24 -77
  41. package/src/batch/resume-multi-queue.mjs +25 -10
  42. package/src/batch/review-artifacts.mjs +96 -17
  43. package/src/batch/review-level-effective.mjs +19 -0
  44. package/src/batch/review-spawn-retry.mjs +106 -0
  45. package/src/batch/review-spawn.mjs +60 -3
  46. package/src/batch/review-step-run.mjs +110 -8
  47. package/src/batch/reviewer-output.mjs +162 -0
  48. package/src/batch/reviewer-provider-error.mjs +153 -0
  49. package/src/batch/worker-host.mjs +49 -3
  50. package/src/batch/worker-prompt.mjs +5 -2
  51. package/src/config/cursor-rules/discover.mjs +40 -3
  52. package/src/config/cursor-rules/match-globs.mjs +6 -4
  53. package/src/config/env-overrides.mjs +41 -4
  54. package/src/config/settings-fields.mjs +11 -0
  55. package/src/config/spine-config-schema.mjs +62 -0
  56. package/src/doctor/pi-extension-hooks.mjs +322 -0
  57. package/src/doctor/quota-risk.mjs +45 -0
  58. package/src/doctor/run-doctor-checks.mjs +14 -1
  59. package/src/planner/file-scope.mjs +6 -6
  60. package/src/tasks/packet/validate-contract.mjs +3 -3
  61. package/src/tasks/packet/validate-prompt.mjs +11 -1
  62. package/src/tasks/validate-contract-warn.mjs +16 -0
  63. 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
@@ -61,6 +62,7 @@ Invoke explicitly: `/skill:spine-release-operator` or "run a spine release cycle
61
62
  - **Do not** execute tasks outside the approved manifest scope
62
63
  - **Never** start Phase 4 (execute) without **recorded scope approval** — the release manifest must show `Operator approved scope: yes` from the Phase 2 gate. Refuse the first wave when approval is missing or `no` (F1, [#249](https://github.com/beettlle/pi-spine/issues/249))
63
64
  - **Never** mid-release-edit `.spine/spine-config.json` agent pins (`agents.worker.model` / `agents.reviewer.model`) while a batch is running or integrated work is still unpublished. Pin **one worker** per release; escalate models **only** on content/contract failure — never on quota/403 or launch storms, which make releases worse (F7, [#248](https://github.com/beettlle/pi-spine/issues/248)). To override mid-release, first record the reason and date in the release manifest
65
+ - **Distinguish quota fallback from escalation** ([#329](https://github.com/beettlle/pi-spine/issues/329), v2.27.0): `agents.quotaFallbackProfile` is **provider failover, not escalation** — it switches the batch to a fallback profile on a **different provider pool**, not to a stronger model. It is single-hop per batch, sticky once applied, journaled (`batch.quota_fallback_applied`), and never edits `.spine/spine-config.json`. Because it changes pool, not model strength, it is **allowed mid-release** and does not violate the #248 rule above — that rule still bans escalating models on quota/403 or launch storms. After a fallback fires, paste the `Agent pin override: yes (<date>, auto quota fallback <pool> -> <profile>, batch <id>)` line shown by `spine status --diagnose` into the release manifest (the override record the #248 rule requires)
64
66
  - **Heed** the doctor/preflight **quota-risk advisory** ([#251](https://github.com/beettlle/pi-spine/issues/251)): `spine doctor` surfaces `ok: true, warning: true` when escalate/hard worker pins target quota-constrained pools without headroom evidence, or recent run-metrics show launch-storm / quota-abort patterns. It is advisory only — never fails preflight — and does not change the mid-release pin-thrash ban above
65
67
  - **Always** push/sync `main` to `origin` after each land loop once the post-integrate regression gate is green — do not let `main` drift far ahead of `origin` during a release (F8, [#249](https://github.com/beettlle/pi-spine/issues/249))
66
68
  - **Always** close GitHub issues linked as `Closes #NNN` / `Closes: #NNN` **as soon as that task's work is on `main`** (after integrate + post-integrate `release:check` green) — do **not** defer closing until Phase 6 publish. Leave `Partial #NNN` / `Partial: #NNN` open. Phase 6 is only a final sweep for any still-open `Closes` links (v2.15.0 left #257–#261, #263 open after ship — avoid that)
@@ -140,11 +142,17 @@ skills/spine-release-operator/scripts/collect-release-intake.sh {TARGET}
140
142
 
141
143
  ```bash
142
144
  gh issue list --repo beettlle/pi-spine --state open --limit 100 \
143
- --json number,title,labels,body
145
+ --json number,title,labels
144
146
  gh issue list --repo beettlle/pi-spine --state open --label documentation --json number,title,labels
145
147
  gh issue list --repo beettlle/pi-spine --state open --label bug --json number,title,labels
146
148
  ```
147
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
+
148
156
  **Pending tasks:**
149
157
 
150
158
  ```bash
@@ -252,6 +260,12 @@ For every task in manifest scope:
252
260
  - [ ] Same-wave tasks have disjoint `fileScopeMustChange`
253
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)
254
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
+
255
269
  ```bash
256
270
  spine tasks validate <release-scope>
257
271
  spine tasks analyze <release-scope>
@@ -275,6 +289,10 @@ Before the first wave, confirm the release manifest records **`Operator approved
275
289
 
276
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).
277
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
+
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`.
295
+
278
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.
279
297
 
280
298
  **Scope:** manifest tasks only — build a comma-separated release scope ID list.
@@ -297,7 +315,7 @@ MonitorCreate:
297
315
  command: spine batch start <release-scope> --wave N # detached — omit --attached (#163)
298
316
  description: Release wave N
299
317
  timeout: 0
300
- 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
301
319
  ```
302
320
 
303
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)):
@@ -305,7 +323,13 @@ MonitorCreate:
305
323
  ```bash
306
324
  spine batch start <release-scope> --wave N
307
325
  spine status --diagnose
308
- 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
309
333
  ```
310
334
 
311
335
  **Foreground `--attached`** (persistent interactive human terminal only):
@@ -319,10 +343,10 @@ spine batch start <release-scope> --wave N --attached
319
343
  ```bash
320
344
  spine status --diagnose
321
345
  # or block:
322
- 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
323
347
  ```
324
348
 
325
- 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.
326
350
 
327
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.
328
352
 
@@ -436,7 +460,7 @@ spine preflight
436
460
  git status
437
461
  ```
438
462
 
439
- **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.
440
464
 
441
465
  **Foreground fallback:**
442
466
 
@@ -564,52 +588,9 @@ Tag push + green **CI** (`ci.yml`) alone is **not** enough — `ci.yml` does not
564
588
 
565
589
  ### Publish failure recovery (HARD STOP — do not retag)
566
590
 
567
- When `release.yml` fails, diagnose with the failed job log before any recovery:
568
-
569
- ```bash
570
- gh run view <run-id> --log-failed
571
- ```
572
-
573
- | Symptom | Meaning | Action |
574
- |---------|---------|--------|
575
- | 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 |
576
- | 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 |
577
- | 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 |
578
- | 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 |
579
- | Stage green but install missing version | Not approved yet | Approve with 2FA; do not retag |
580
- | 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 |
581
-
582
- **Re-dispatch existing tag** (after Trusted Publisher / transient registry fix):
583
-
584
- ```bash
585
- # Tag must already exist; this re-runs checkout → gate → stage → gh release
586
- # workflow_dispatch uses the workflow file from the branch you select (usually main)
587
- gh workflow run release.yml -f tag=v{VERSION}
588
- gh run list --workflow release.yml --limit 3
589
- gh run watch --exit-status <new-run-id>
590
- ```
591
-
592
- UI equivalent: **Actions → Release → Run workflow** → enter `v{VERSION}`.
593
-
594
- **Do not** delete/retag/`npm version` again when the only failure was auth/OIDC — package.json and the `v*` tag are already correct.
595
-
596
- 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).
597
-
598
- 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:
599
-
600
- ```bash
601
- scripts/post-publish-smoke.sh <version>
602
- ```
603
-
604
- 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):
605
-
606
- ```bash
607
- npm install -g pi-spine@<version>
608
- spine version
609
- spine doctor
610
- ```
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.
611
592
 
612
- 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).
613
594
 
614
595
  Update `spine-tasks/CONTEXT.md` release note (version + date).
615
596
 
@@ -641,6 +622,7 @@ Include the published version/tag in the close comment when closing at Phase 6 (
641
622
  8. **Verification** — paste `spine preflight` tail, **`npm run release:check` output** (or log path), test/coverage output
642
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"
643
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"
644
626
 
645
627
  ---
646
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.
@@ -321,6 +321,9 @@ export function reconstructBatchStateFromRuntime(projectRoot, options = {}) {
321
321
  ...(priorResilience.forceMergedWaves
322
322
  ? { forceMergedWaves: priorResilience.forceMergedWaves }
323
323
  : {}),
324
+ // SP-808 (#329): the sticky quota-fallback hop must survive force-resume
325
+ // reconstruct so every later worker spawn keeps the override.
326
+ ...(priorResilience.quotaFallback ? { quotaFallback: priorResilience.quotaFallback } : {}),
324
327
  };
325
328
  rebuilt.currentWaveIndex = findResumableWave(rebuilt, computePendingTasks(rebuilt));
326
329
  rebuilt.updatedAt = Date.now();
@@ -5,7 +5,7 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { setTimeout as sleep } from "node:timers/promises";
8
- import micromatch from "micromatch";
8
+ import picomatch from "picomatch";
9
9
  import { parseAggregateLineCoverage } from "../../scripts/coverage-parse.mjs";
10
10
  import {
11
11
  isBaseFileScopeSatisfied,
@@ -264,7 +264,7 @@ function findArtifactMatch(worktreePath, artifactPattern) {
264
264
  stack.push({ abs: entryAbs, rel: entryRel });
265
265
  continue;
266
266
  }
267
- if (micromatch.isMatch(entryRel, normalized)) {
267
+ if (picomatch(normalized, { dot: true })(entryRel)) {
268
268
  return { ok: true, matchedPath: entryRel };
269
269
  }
270
270
  }
@@ -5,7 +5,7 @@
5
5
 
6
6
  import fs from "node:fs";
7
7
  import { execFileSync } from "node:child_process";
8
- import micromatch from "micromatch";
8
+ import picomatch from "picomatch";
9
9
  import { resolveContractMode } from "../tasks/packet/validate-contract.mjs";
10
10
  import {
11
11
  isBaseScopeSatisfied,
@@ -199,7 +199,7 @@ export function listChangedFiles(worktreePath, baseBranch = "main", sinceCommit
199
199
  * @param {string} pattern
200
200
  */
201
201
  export function matchesContractPattern(file, pattern) {
202
- return micromatch.isMatch(file, pattern, { dot: true });
202
+ return picomatch(pattern, { dot: true })(file);
203
203
  }
204
204
 
205
205
  /**
@@ -5,7 +5,7 @@
5
5
 
6
6
  import path from "node:path";
7
7
  import { execFileSync } from "node:child_process";
8
- import micromatch from "micromatch";
8
+ import picomatch from "picomatch";
9
9
  import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
10
10
 
11
11
  /**
@@ -13,7 +13,7 @@ import { DEFAULT_TASKS_ROOT } from "../config/spine-init-constants.mjs";
13
13
  * @param {string} pattern
14
14
  */
15
15
  function matchesPattern(file, pattern) {
16
- return micromatch.isMatch(file, pattern, { dot: true });
16
+ return picomatch(pattern, { dot: true })(file);
17
17
  }
18
18
 
19
19
  /**
@@ -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];
@@ -4,6 +4,41 @@
4
4
  * Kept out of diagnosis.mjs so the parent stays under the phase23 LOC cap.
5
5
  */
6
6
 
7
+ /**
8
+ * True when the latest quota-exhaustion journal payload came from
9
+ * `batch.quota_fallback_exhausted` — the parallel arrays are unique to that
10
+ * event (SP-808), so a fallback hop that died too is distinguishable from a
11
+ * plain worker exhaustion without carrying the event type through the ctx.
12
+ *
13
+ * @param {object|null} lastQuotaExhausted
14
+ * @returns {boolean}
15
+ */
16
+ function isFallbackChainExhausted(lastQuotaExhausted) {
17
+ return Array.isArray(lastQuotaExhausted?.exhaustedPools);
18
+ }
19
+
20
+ /**
21
+ * Human-readable reset windows for the exhausted pool(s): a single
22
+ * "resets <raw>" for a worker exhaustion, or one per pool when the fallback
23
+ * chain died too (#329 wants the operator to see every window). Falls back to
24
+ * "reset time unknown" — the raw provider text carries no timezone, so it is
25
+ * shown verbatim rather than parsed into a wrong clock time.
26
+ *
27
+ * @param {object|null} lastQuotaExhausted
28
+ * @returns {string}
29
+ */
30
+ function quotaResetSummary(lastQuotaExhausted) {
31
+ if (isFallbackChainExhausted(lastQuotaExhausted)) {
32
+ const pools = /** @type {string[]} */ (lastQuotaExhausted.exhaustedPools);
33
+ const resets = Array.isArray(lastQuotaExhausted.resetAtRaw) ? lastQuotaExhausted.resetAtRaw : [];
34
+ return pools
35
+ .map((pool, index) => `${pool} resets ${resets[index] ?? "unknown"}`)
36
+ .join(", ");
37
+ }
38
+ const reset = lastQuotaExhausted?.resetAtRaw;
39
+ return typeof reset === "string" && reset ? `resets ${reset}` : "reset time unknown";
40
+ }
41
+
7
42
  /**
8
43
  * SBAR Background — short decision-relevant facts that explain the state the
9
44
  * assessment was derived from. Facts are additive; consumers that ignore
@@ -32,6 +67,27 @@ export function buildBackground(diagnosis, ctx = {}) {
32
67
  `Failed task: ${ctx.failedTaskId}${ctx.exitReason ? ` (exit: ${ctx.exitReason})` : ""}`,
33
68
  );
34
69
  }
70
+ // SP-810 (partial #329): when a fallback hop is active, operators must see
71
+ // which pool died, when it resets, and where the batch landed — plus the
72
+ // paste-ready manifest line the #248 pin policy requires them to record.
73
+ if (ctx.quotaFallback && typeof ctx.quotaFallback === "object" && ctx.quotaFallback.toProfile) {
74
+ const fallback = ctx.quotaFallback;
75
+ facts.push(
76
+ `Quota fallback active: ${fallback.exhaustedPool ?? "?"} exhausted (resets ${
77
+ fallback.resetAtRaw ?? "unknown"
78
+ }, provider local time) → ${fallback.toProfile} (${fallback.toModel ?? "?"}) since ${
79
+ fallback.at ?? "?"
80
+ }, triggered by ${fallback.triggerTaskId ?? "?"}`,
81
+ );
82
+ // Manifest text stays ASCII (`->`) exactly as operators paste it into the
83
+ // release manifest; the date is the YYYY-MM-DD slice of the hop timestamp.
84
+ const overrideDate = typeof fallback.at === "string" ? fallback.at.slice(0, 10) : "?";
85
+ facts.push(
86
+ `Agent pin override: yes (${overrideDate}, auto quota fallback ${
87
+ fallback.exhaustedPool ?? "?"
88
+ } -> ${fallback.toProfile}, batch ${ctx.batchId ?? "?"})`,
89
+ );
90
+ }
35
91
  if (ctx.launchFailureKind) {
36
92
  facts.push(`Launch failure kind: ${ctx.launchFailureKind}`);
37
93
  }
@@ -87,6 +143,24 @@ export function buildAssessmentReason(diagnosis, ctx = {}) {
87
143
  case "completed_manual":
88
144
  return "Work is already on the base branch while the batch record is still active — operator completed it manually";
89
145
  case "needs_retry":
146
+ // SP-810 (partial #329): a quota exhaustion with no fallback that can
147
+ // take over must not imply an immediate retry will work — show the
148
+ // reset window instead. Fallback is hopeless when no hop is persisted
149
+ // (unset/refused) or the fallback chain itself exhausted (stop event).
150
+ if (
151
+ ctx.failedTaskId &&
152
+ ctx.exitReason === "provider_quota_exhausted" &&
153
+ (ctx.quotaFallback == null || isFallbackChainExhausted(ctx.lastQuotaExhausted))
154
+ ) {
155
+ return `Task ${ctx.failedTaskId} exited "provider_quota_exhausted": provider quota is exhausted (${quotaResetSummary(
156
+ ctx.lastQuotaExhausted,
157
+ )}, provider local time) and no quota fallback can take over — an immediate retry hits the same quota limit`;
158
+ }
159
+ // Transient overload never falls back (#329) and clears on its own, so
160
+ // here a plain retry genuinely is the right move.
161
+ if (ctx.failedTaskId && ctx.exitReason === "provider_overloaded") {
162
+ return `Task ${ctx.failedTaskId} exited "provider_overloaded": transient provider overload — retry is reasonable`;
163
+ }
90
164
  if (ctx.failedTaskId && ctx.exitReason) {
91
165
  return `Task ${ctx.failedTaskId} exited "${ctx.exitReason}" without completing its contract, so the batch cannot proceed until it is retried`;
92
166
  }
@@ -3,6 +3,13 @@
3
3
  * Pending lane land diagnosis — lane `.DONE` without main land (#201 / SP-645).
4
4
  */
5
5
 
6
+ import { isEngineProcessAlive } from "../process/liveness.mjs";
7
+ import { readBatchEnginePid, readBatchEngineStartedAt } from "./state-guards.mjs";
8
+ import {
9
+ REVIEW_INFRASTRUCTURE_EXIT_REASONS,
10
+ resolveTaskPrimaryFailureExitReason,
11
+ } from "./diagnosis-review-infra.mjs";
12
+
6
13
  /**
7
14
  * Tasks with lane `.DONE` but not on main — lane commits never landed (#201 / SP-645).
8
15
  *
@@ -14,13 +21,57 @@ export function findPendingLaneLandTasks(tasks) {
14
21
  return tasks.filter((task) => task?.doneInLane === true && task?.doneOnMain !== true);
15
22
  }
16
23
 
24
+ /**
25
+ * Guard for #330 / SP-815: the batch engine is alive AND the raw batch state
26
+ * still shows live activity (phase "running" or a running task). Reconciled
27
+ * signals can already look terminal-success mid-wave because a lane `.DONE`
28
+ * is reconciled (`done_in_lane_terminal`) before the engine finishes code and
29
+ * final review — so salvage guidance must be suppressed until the engine
30
+ * exits or the state goes terminal. Both conditions must hold: a crashed
31
+ * engine with a stale running phase still deserves salvage guidance.
32
+ *
33
+ * @param {object|null|undefined} raw raw batch state (`signals.raw`)
34
+ * @param {object} [deps]
35
+ * @param {(raw: object) => boolean} [deps.isEngineAlive] injectable engine liveness probe
36
+ * @returns {boolean}
37
+ */
38
+ export function isLiveEngineMidTask(raw, deps = {}) {
39
+ if (!raw || typeof raw !== "object") return false;
40
+ const isEngineAlive =
41
+ deps.isEngineAlive ??
42
+ ((state) => isEngineProcessAlive(readBatchEnginePid(state), readBatchEngineStartedAt(state)));
43
+ if (!isEngineAlive(raw)) return false;
44
+ if (raw.phase === "running") return true;
45
+ const tasks = Array.isArray(raw.tasks) ? raw.tasks : [];
46
+ return tasks.some((task) => task?.status === "running");
47
+ }
48
+
17
49
  /**
18
50
  * @param {object} signals
51
+ * @param {object} [deps]
52
+ * @param {(raw: object) => boolean} [deps.isEngineAlive] injectable engine liveness probe
19
53
  * @returns {boolean}
20
54
  */
21
- export function shouldDiagnosePendingLaneLand(signals) {
55
+ export function shouldDiagnosePendingLaneLand(signals, deps = {}) {
56
+ // Live engine mid-task: the lane may be about to land under the engine
57
+ // itself — never suggest salvage while it is still running (#330 / SP-815).
58
+ if (isLiveEngineMidTask(signals?.raw, deps)) return false;
22
59
  const pending = findPendingLaneLandTasks(signals.tasks);
23
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
+ }
24
75
  // Only when orch already appears merged — otherwise healthy pre-integrate
25
76
  // waves (doneInLane, awaiting integrate) must stay needs_integrate / settled.
26
77
  if (signals.git?.orchMergedToBase !== true) return false;