pi-spine 2.20.0 → 2.22.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.
package/README.md CHANGED
@@ -43,11 +43,13 @@ Primary monitor surfaces: **`spine status --diagnose`**, **`spine dashboard`** /
43
43
 
44
44
  ## Prerequisites
45
45
 
46
- | Dependency | Required |
47
- |------------|----------|
48
- | [Node.js](https://nodejs.org/) ≥ 22 | Yes |
49
- | [pi](https://pi.dev) coding agent | Yes |
50
- | Git (worktree support) | Yes |
46
+ | Dependency | Minimum | Required |
47
+ |------------|---------|----------|
48
+ | [Node.js](https://nodejs.org/) | ≥ 22.19.0 (`engines.node`) | Yes |
49
+ | [pi](https://pi.dev) coding agent | ≥ 0.80.0 (`pi.minPiVersion`) | Yes |
50
+ | Git (worktree support) | — | Yes |
51
+
52
+ These are the Wave A floors ([#285](https://github.com/beettlle/pi-spine/issues/285)). `spine doctor` **warns** when the installed pi is below `pi.minPiVersion` ("pi version supported"). The optional peer `@earendil-works/pi-coding-agent` is developed and tested against `^0.87.0` (pinned in `devDependencies`; the `peerDependencies` range stays `*`).
51
53
 
52
54
  ## Install
53
55
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.20.0",
3
+ "version": "2.22.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -22,11 +22,11 @@
22
22
  "skills": [
23
23
  "./skills"
24
24
  ],
25
- "minPiVersion": "0.60.0"
25
+ "minPiVersion": "0.80.0"
26
26
  },
27
27
  "type": "module",
28
28
  "engines": {
29
- "node": ">=22.0.0"
29
+ "node": ">=22.19.0"
30
30
  },
31
31
  "scripts": {
32
32
  "doctor": "node bin/spine.mjs doctor",
@@ -72,12 +72,12 @@
72
72
  }
73
73
  },
74
74
  "devDependencies": {
75
- "@earendil-works/pi-coding-agent": "^0.80.3",
75
+ "@earendil-works/pi-coding-agent": "^0.87.0",
76
76
  "@types/node": "^22.19.18",
77
- "eslint": "^9.28.0",
78
- "globals": "^16.2.0",
79
- "typebox": "1.1.38",
80
- "typescript": "5.6.3"
77
+ "eslint": "^10.10.0",
78
+ "globals": "^17.12.0",
79
+ "typebox": "1.3.30",
80
+ "typescript": "6.0.3"
81
81
  },
82
82
  "license": "MIT",
83
83
  "dependencies": {
@@ -18,6 +18,8 @@ spine wait --until completed,needs_integrate,failed,aborted --timeout 4h # opt
18
18
 
19
19
  Detached start/resume returns when the engine **starts**, not when work completes.
20
20
 
21
+ > **Wait progress vs quiet-stdout hosts:** human-mode `spine wait` prints a start banner and a `Wait progress:` line per poll, but agent hosts that buffer stdout until process exit (MonitorCreate, non-TTY shells) only see the terminal line. For machine-readable output use `--json` — one JSON snapshot at the terminal state.
22
+
21
23
  ---
22
24
 
23
25
  ## Cursor Agent shell
@@ -119,6 +119,8 @@ Increment `WAVE` and repeat until `spine plan pending` shows no remaining waves.
119
119
 
120
120
  > **Wait recipe note:** With SP-683, gate-pending land loops report the taxonomy diagnosis `needs_integrate`, so the default `--until` list above wakes on that diagnosis. The operator runbook documents optional land-loop pseudo-diagnoses (`gate_open`, `needs_approval`, `post_merge_limbo`) as belt-and-suspenders waits when you need finer-grained blocking inside the land loop itself.
121
121
 
122
+ > **Wait liveness (SP-754):** human-mode `spine wait` shows liveness output — a start banner, a `Wait progress:` line per poll (diagnosis, phase, wave, elapsed), and a terminal `Wait matched:` / `Wait timed out` headline. A quiet wait between progress lines is alive, not hung; use `--json` for machine parsing.
123
+
122
124
  **Optional script template:** `spine run sequence pending --attached --dry-run` — execute each printed block with judgment; do **not** chain `--auto-approve-gate` with real pi workers.
123
125
 
124
126
  Full reference: [references/outer-loop.md](references/outer-loop.md).
@@ -47,6 +47,7 @@ Invoke explicitly: `/skill:spine-release-operator` or "run a spine release cycle
47
47
  - **Never** run `npm version` or `git push --tags` when `npm run release:check` exits non-zero on current `main` ([#175](https://github.com/beettlle/pi-spine/issues/175))
48
48
  - **Never** run `npm version` or `git push --tags` when the **CI** workflow is not green on current `HEAD` — release-safe profile: typecheck + lint + tests + coverage (parity with `ci.yml`) ([#156](https://github.com/beettlle/pi-spine/issues/156))
49
49
  - **Always** parse target version / bump type **before** task selection (Phase 2)
50
+ - **Always** record dependency drift in Phase 1 (`npm outdated` + `npm audit`) and apply include/defer thresholds — never auto-add a full “update all deps” task; see [issue-intake-checklist.md](references/issue-intake-checklist.md) § Dependency drift check
50
51
  - **Always** prioritize documentation issues over enhancements
51
52
  - **Always** run `spine gate approve` before `spine integrate`
52
53
  - **Always** run `npm install` on `main` after successful integrate
@@ -154,9 +155,18 @@ spine tasks analyze pending
154
155
  rg 'Closes #|Closes:|Partial #|Partial:' spine-tasks/*/PROMPT.md
155
156
  ```
156
157
 
158
+ **Dependency drift check** (every profile, including patch) — full thresholds in [issue-intake-checklist.md](references/issue-intake-checklist.md):
159
+
160
+ ```bash
161
+ npm outdated
162
+ npm audit
163
+ ```
164
+
165
+ Classify each signal as **include** or **defer** (security highs even in patch; peer ≥1-minor drift and toolchain majors for minor/major only). Prefer an existing open dep issue (e.g. title contains “Bump dependencies” / “pi-coding-agent”) over inventing a duplicate gap. Record a one-row summary in the intake output and the manifest **Dependency drift** section.
166
+
157
167
  Read `spine-tasks/CONTEXT.md` for `Next Task ID`.
158
168
 
159
- **Output:** intake table (issue #, labels, mapped SP-* or gap, bucket, profile fit).
169
+ **Output:** intake table (issue #, labels, mapped SP-* or gap, bucket, profile fit) **plus** deps mini-table (package, current, latest, include|defer).
160
170
 
161
171
  ---
162
172
 
@@ -173,9 +183,11 @@ Use [references/release-manifest-template.md](references/release-manifest-templa
173
183
  ### Selection order (strict)
174
184
 
175
185
  1. **Documentation first** — all feasible doc items before feature work
176
- 2. **Bug fixes** — target 3–5 with user impact
177
- 3. **Enhancements** — per profile (0 for patch, 1–2 for minor)
178
- 4. **Defer** everything else with one-line rationale
186
+ 2. **Bug fixes** — target 3–5 with user impact; include **security-high dep fixes** from the Phase 1 drift check here (hygiene, not a fourth unlimited bucket)
187
+ 3. **Enhancements** — per profile (0 for patch, 1–2 for minor); peer ≥1-minor drift / toolchain majors from the drift check consume an enh/hygiene slot when thresholds fire
188
+ 4. **Defer** everything else with one-line rationale (including “deps OK — deferred” when no threshold fires)
189
+
190
+ Dep hygiene from the drift check **inserts into** the bug or enh slot per [issue-intake-checklist.md](references/issue-intake-checklist.md) thresholds — it is not a separate uncapped bucket. Prefer one focused peer/security packet over “bump everything” when the enh slot is already full.
179
191
 
180
192
  ### Apply profile budgets
181
193
 
@@ -193,6 +205,7 @@ Present manifest summary:
193
205
 
194
206
  - Target version and profile
195
207
  - Selected SP-* / issues by bucket
208
+ - Dependency drift action (included SP-*/#NNN or deferred rationale)
196
209
  - Deferred count
197
210
  - Profile audit status
198
211
 
@@ -307,6 +320,8 @@ spine wait --until completed,failed,needs_integrate,needs_retry,aborted --timeou
307
320
 
308
321
  Optional pi watchdog: `LoopCreate` every 2m, `readOnly: true`, `maxFires: 50` — see pi-async-orchestration.
309
322
 
323
+ > **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.
324
+
310
325
  > **Wait recipe note:** With SP-683, gate-pending land loops report the taxonomy diagnosis `needs_integrate`, so the default `--until` lists above wake on that diagnosis. The operator runbook documents optional land-loop pseudo-diagnoses (`gate_open`, `needs_approval`, `post_merge_limbo`) as belt-and-suspenders waits when you need finer-grained blocking inside the land loop itself.
311
326
 
312
327
  **Do not** start wave N+1 until wave N is integrated on `main`.
@@ -551,12 +566,13 @@ Include the published version/tag in the close comment when closing at Phase 6 (
551
566
  1. **Release manifest** — path, target version, profile, composition table
552
567
  2. **Tasks completed** — SP-IDs, waves, issues closed (list `#NNN` CLOSED with close time or comment URL)
553
568
  3. **Deferred backlog** — count and top items for next release (issues left OPEN + rationale)
554
- 4. **Authoring changes** — new SP-* created, splits/fixes in Phase 3
555
- 5. **Issues filed** — pi-spine GitHub links or "none"
556
- 6. **Recovery actions** — aborts, retries, contract fixes
557
- 7. **Verification** — paste `spine preflight` tail, **`npm run release:check` output** (or log path), test/coverage output
558
- 8. **Publish** — version bumped (Y/N), tag pushed (Y/N), workflow URL, or "awaiting operator approval"
559
- 9. **Issue tracker hygiene** — confirm every release-scoped `Closes #NNN` is CLOSED (paste `gh issue view` states or list)
569
+ 4. **Dependency drift** — Phase 1 check outcome: included SP-*/#NNN or deferred rationale (and audit high/critical count)
570
+ 5. **Authoring changes** — new SP-* created, splits/fixes in Phase 3
571
+ 6. **Issues filed** — pi-spine GitHub links or "none"
572
+ 7. **Recovery actions** — aborts, retries, contract fixes
573
+ 8. **Verification** — paste `spine preflight` tail, **`npm run release:check` output** (or log path), test/coverage output
574
+ 9. **Publish** — version bumped (Y/N), tag pushed (Y/N), workflow URL, or "awaiting operator approval"
575
+ 10. **Issue tracker hygiene** — confirm every release-scoped `Closes #NNN` is CLOSED (paste `gh issue view` states or list)
560
576
 
561
577
  ---
562
578
 
@@ -86,6 +86,43 @@ Exclude when:
86
86
  - Disjoint `fileScopeMustChange` from bug tasks in same wave
87
87
  - P1/P2 over P3
88
88
 
89
+ ## Dependency drift check
90
+
91
+ Run during **Phase 1** for **every** profile (including patch). Always record results; only **include** a dep/hygiene task when a threshold fires — never auto-add “update all deps” to every minor.
92
+
93
+ ### Commands
94
+
95
+ ```bash
96
+ npm outdated
97
+ npm audit
98
+ ```
99
+
100
+ Optional: glance at GitHub Actions major pins in `.github/workflows/*.yml` (`actions/checkout`, `actions/setup-node`, `actions/upload-artifact`, `actions/github-script`) for toolchain major drift.
101
+
102
+ ### Include / defer thresholds
103
+
104
+ | Signal | Include in release? | Bucket |
105
+ |--------|---------------------|--------|
106
+ | `npm audit` high or critical | Yes — even **patch** if fix is S-sized | bug / hygiene |
107
+ | `@earendil-works/pi-coding-agent` behind by ≥1 0.x minor (e.g. 0.80 → 0.85) | Yes for **minor/major**; patch only if also audit-high | enh / hygiene (counts against enh budget on minor) |
108
+ | Same-major patch/minor drift only (eslint 9.x, `@types/node` 22.x) | Include only if enh budget has room **or** operator override; otherwise defer | hygiene |
109
+ | TypeScript / ESLint / Actions **major** | **minor/major** only — never default into patch | enh / hygiene |
110
+ | No overdue signal | Record “deps OK — deferred” in the manifest; **no new task** | — |
111
+
112
+ **Scope when included:** prefer one focused peer/security packet over “bump everything” when the enhancement slot is already full. Dep hygiene inserts into the bug or enh slot — it is not a fourth unlimited bucket.
113
+
114
+ ### Map before authoring a gap
115
+
116
+ Search open issues for an existing dep bump ticket before creating a new SP-*:
117
+
118
+ ```bash
119
+ gh issue list --repo beettlle/pi-spine --state open --limit 100 \
120
+ --json number,title,labels \
121
+ --jq '.[] | select(.title | test("dependenc|pi-coding-agent|npm audit|Bump dep"; "i"))'
122
+ ```
123
+
124
+ Prefer `Closes #NNN` on that issue over inventing duplicate work.
125
+
89
126
  ## Pending task inventory
90
127
 
91
128
  ```bash
@@ -105,3 +142,12 @@ Cross-reference pending SP-* with open issues. The release executes **manifest s
105
142
  |---------|--------|-------------|--------|-------------|-------|
106
143
  | #130 | bug | SP-483 | bug | patch ✓ | post-merge restore |
107
144
  | #90 | documentation | — (gap) | doc | minor ✓ | needs new SP-* |
145
+
146
+ ### Deps mini-table (required)
147
+
148
+ | Package | Current | Latest | Action |
149
+ |---------|---------|--------|--------|
150
+ | @earendil-works/pi-coding-agent | 0.80.3 | 0.85.1 | include (#285) / defer: … |
151
+ | (others from `npm outdated`) | … | … | include \| defer |
152
+
153
+ Also record: `npm audit` high/critical count and overall action for the manifest **Dependency drift** section.
@@ -24,6 +24,18 @@
24
24
 
25
25
  ---
26
26
 
27
+ ## Dependency drift
28
+
29
+ | Check | Result |
30
+ |-------|--------|
31
+ | `npm outdated` | (paste summary or path to intake snapshot) |
32
+ | `npm audit` highs/criticals | n |
33
+ | Action | include SP-### / #NNN \| deferred: {reason} |
34
+
35
+ Thresholds: [issue-intake-checklist.md](issue-intake-checklist.md) § Dependency drift check. Always record; include a task only when a threshold fires.
36
+
37
+ ---
38
+
27
39
  ## Selected tasks
28
40
 
29
41
  | SP-ID | Issue | Bucket | Size | Title | Notes |
@@ -72,8 +72,11 @@ Breaking changes and large migrations. Operator-defined epic scope.
72
72
  Apply in this order; stop when profile budget is full:
73
73
 
74
74
  1. **Documentation** — `label:documentation`, `skill:create-spine-tasks` doc issues, pending docs-only SP-* tasks
75
- 2. **Bug fixes** — open `label:bug` with user impact; prefer already-tasked or quick S
76
- 3. **Enhancements** — only if profile allows; one user-visible improvement per minor release
75
+ 2. **Bug fixes** — open `label:bug` with user impact; prefer already-tasked or quick S; **security-high dep fixes** from the Phase 1 drift check insert here before enhancements
76
+ 3. **Enhancements / dep hygiene** — only if profile allows; one user-visible improvement per minor release; peer ≥1-minor drift (`pi-coding-agent`) or toolchain majors from the drift check fill **one** enh/hygiene slot on minor/major when thresholds fire (see [issue-intake-checklist.md](issue-intake-checklist.md) § Dependency drift check)
77
+ 4. **Defer** the rest — including “deps OK — deferred” when no threshold fires
78
+
79
+ Never treat dependency updates as an uncapped fourth bucket. Prefer one focused peer/security packet over “bump everything” when the enh slot is already full.
77
80
 
78
81
  ## Profile audit (must pass before Phase 3)
79
82
 
@@ -86,6 +89,7 @@ Fill the composition audit table in the manifest. Fail or warn when:
86
89
  | Total tasks | >8 without override | >15 without override | — |
87
90
  | M/L tasks in patch | any without override | — | — |
88
91
  | Doc paths in File Scope | required for doc tasks (#144) | required | required |
92
+ | Dep drift check recorded | WARN if missing | **FAIL** without override if missing | **FAIL** without override if missing |
89
93
 
90
94
  Record `Profile audit: PASS` or `PASS with operator override` before proceeding.
91
95
 
@@ -67,5 +67,49 @@ else
67
67
  fi
68
68
  echo ""
69
69
 
70
+ echo "=== npm outdated ==="
71
+ # npm outdated exits 1 when updates exist — must not abort this script
72
+ npm outdated 2>/dev/null || true
73
+ echo ""
74
+
75
+ echo "=== npm audit (vulnerability counts) ==="
76
+ if command -v node >/dev/null 2>&1; then
77
+ # npm audit exits non-zero when vulns exist — capture JSON without aborting
78
+ AUDIT_JSON="$(npm audit --json 2>/dev/null || true)"
79
+ if [ -n "$AUDIT_JSON" ]; then
80
+ printf '%s' "$AUDIT_JSON" | node -e '
81
+ let s = "";
82
+ process.stdin.on("data", (c) => { s += c; });
83
+ process.stdin.on("end", () => {
84
+ try {
85
+ const d = JSON.parse(s || "{}");
86
+ const v = (d.metadata && d.metadata.vulnerabilities) || {};
87
+ const info = v.info || 0;
88
+ const low = v.low || 0;
89
+ const moderate = v.moderate || 0;
90
+ const high = v.high || 0;
91
+ const critical = v.critical || 0;
92
+ const total = v.total != null ? v.total : info + low + moderate + high + critical;
93
+ console.log(
94
+ "info=" + info +
95
+ " low=" + low +
96
+ " moderate=" + moderate +
97
+ " high=" + high +
98
+ " critical=" + critical +
99
+ " total=" + total
100
+ );
101
+ } catch {
102
+ console.log("(could not parse npm audit --json)");
103
+ }
104
+ });
105
+ '
106
+ else
107
+ echo "(npm audit --json produced no output)"
108
+ fi
109
+ else
110
+ npm audit 2>/dev/null || true
111
+ fi
112
+ echo ""
113
+
70
114
  echo "=== Next Task ID (from CONTEXT.md) ==="
71
115
  grep -E '^\*\*Next Task ID:\*\*' spine-tasks/CONTEXT.md 2>/dev/null || echo "(CONTEXT.md not found)"
@@ -57,6 +57,39 @@ export function buildPrimaryFailureHeadline(batchLabel, ctx = {}) {
57
57
  return null;
58
58
  }
59
59
 
60
+ // Keep the hint readable; the gitignored merge repair command uses the same cap (#288).
61
+ const DIRTY_WORKTREE_PATH_HINT_LIMIT = 5;
62
+
63
+ /**
64
+ * DirtyWorktree remediation hint built from the actual dirty set (#288).
65
+ * Prefers concrete dirty paths from the failure payload / lane dirty-check;
66
+ * falls back to a generic status inspection plus retry when paths are unknown.
67
+ * Never hardcodes coverage paths — they appear only when present in the dirty set.
68
+ *
69
+ * @param {object} ctx
70
+ * @param {string|null} [ctx.failedTaskId]
71
+ * @param {string[]|null} [ctx.dirtyPaths]
72
+ * @param {string|null} [ctx.laneWorktree]
73
+ * @returns {string}
74
+ */
75
+ export function buildDirtyWorktreeSuggestedCommand(ctx = {}) {
76
+ const dirtyPaths = (Array.isArray(ctx.dirtyPaths) ? ctx.dirtyPaths : []).filter(
77
+ (entry) => typeof entry === "string" && entry.trim().length > 0,
78
+ );
79
+ const retryHint = ctx.failedTaskId
80
+ ? `spine batch retry ${ctx.failedTaskId}`
81
+ : "spine batch retry";
82
+ if (dirtyPaths.length > 0) {
83
+ const pathHint = dirtyPaths.slice(0, DIRTY_WORKTREE_PATH_HINT_LIMIT).join(" ");
84
+ return `git checkout -- ${pathHint} && ${retryHint}`;
85
+ }
86
+ const worktreeHint =
87
+ typeof ctx.laneWorktree === "string" && ctx.laneWorktree.trim().length > 0
88
+ ? ctx.laneWorktree
89
+ : "<laneWorktree>";
90
+ return `git -C ${worktreeHint} status --porcelain && ${retryHint}`;
91
+ }
92
+
60
93
  /**
61
94
  * @param {object} ctx
62
95
  * @param {string|null} [ctx.exitReason]
@@ -66,9 +99,7 @@ export function buildPrimaryFailureHeadline(batchLabel, ctx = {}) {
66
99
  export function buildPrimaryFailureSuggestedCommand(ctx = {}) {
67
100
  if (LANE_COMMIT_EXIT_REASONS.has(ctx.exitReason ?? "")) {
68
101
  if (ctx.exitReason === "DirtyWorktree") {
69
- return ctx.failedTaskId
70
- ? `git checkout -- extension/coverage && spine batch retry ${ctx.failedTaskId}`
71
- : "git checkout -- extension/coverage && spine batch retry";
102
+ return buildDirtyWorktreeSuggestedCommand(ctx);
72
103
  }
73
104
  return ctx.failedTaskId
74
105
  ? `spine batch retry ${ctx.failedTaskId}`
@@ -32,6 +32,8 @@ import { buildPendingLaneLandSuggestedCommand } from "./diagnosis-pending-lane.m
32
32
  * @param {boolean} [ctx.mergeFailed]
33
33
  * @param {string|null} [ctx.taskBranch]
34
34
  * @param {string[]|null} [ctx.gitignoredPaths]
35
+ * @param {string[]|null} [ctx.dirtyPaths]
36
+ * @param {string|null} [ctx.laneWorktree]
35
37
  * @param {object[]} [ctx.pendingLaneLandTasks]
36
38
  */
37
39
  export function buildSuggestedCommand(diagnosis, ctx = {}) {
@@ -30,12 +30,15 @@ export const ALLOWED_EVIDENCE_EXECUTABLES = new Set([
30
30
  "npx",
31
31
  "cargo",
32
32
  "task",
33
+ "python3",
33
34
  ]);
34
35
 
35
36
  /**
36
- * Interpreter basenames allowed only as project-local relative paths under
37
+ * Interpreter basenames allowed as project-local relative paths under
37
38
  * `.venv/` or `venv/` (see {@link isAllowedProjectLocalInterpreter}).
38
- * Bare names (PATH lookup) and absolute/outside-project paths stay rejected.
39
+ * Within that venv rule, bare names (PATH lookup) and absolute/outside-project
40
+ * paths stay rejected. Bare `python3` PATH lookup is separately allowed for
41
+ * evidence via {@link ALLOWED_EVIDENCE_EXECUTABLES}; bare `python` is not.
39
42
  * @type {Set<string>}
40
43
  */
41
44
  export const ALLOWED_PROJECT_LOCAL_INTERPRETERS = new Set(["python", "python3"]);
@@ -60,9 +60,19 @@ function taskIdsOf(value) {
60
60
  return value.map((entry) => String(entry ?? "").trim()).filter(Boolean);
61
61
  }
62
62
 
63
+ /** Finite positive laneNumber, or null when the value is missing/garbage (#287). */
64
+ function finiteLaneNumber(value) {
65
+ const n = Number(value);
66
+ return Number.isFinite(n) && n > 0 ? n : null;
67
+ }
68
+
63
69
  function taskStub(map, taskId, hints = {}) {
64
70
  const row = map.get(taskId) ?? { taskId };
65
- if (hints.laneNumber != null) row.laneNumber = Number(hints.laneNumber) || row.laneNumber || 1;
71
+ // Only an explicit finite laneNumber from an event may assign a lane. Garbage
72
+ // hints (NaN/0) must not default the row to lane 1 — that defaulted value
73
+ // would shadow the seed's correct lane in finalizeTasks (#287).
74
+ const hintedLane = finiteLaneNumber(hints.laneNumber);
75
+ if (hintedLane != null) row.laneNumber = hintedLane;
66
76
  if (typeof hints.taskFolder === "string" && hints.taskFolder) row.taskFolder = hints.taskFolder;
67
77
  map.set(taskId, row);
68
78
  return row;
@@ -85,7 +95,8 @@ function finalizeTasks(tasksById, seedTasks) {
85
95
  const seed = seedById.get(taskId);
86
96
  return {
87
97
  taskId,
88
- laneNumber: Number(derived.laneNumber ?? seed?.laneNumber ?? 1) || 1,
98
+ // Journal-provided lane wins; seed fills the gap; 1 is the last resort (#287).
99
+ laneNumber: finiteLaneNumber(derived.laneNumber) ?? finiteLaneNumber(seed?.laneNumber) ?? 1,
89
100
  status: "pending",
90
101
  taskFolder: derived.taskFolder ?? seed?.taskFolder ?? null,
91
102
  sessionName: seed?.sessionName,
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Diagnosis enrichment helpers for reconcile.
3
+ * Extracted from reconcile-diagnosis.mjs to stay under the Phase 23 500 LOC cap.
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import { inferLaunchFailureFromWorkerOutputTail } from "./diagnosis.mjs";
8
+ import { workerOutputLogPath, workerOutputLogRef } from "./worker-output.mjs";
9
+
10
+ const WORKER_OUTPUT_TAIL_LINES = 20;
11
+
12
+ /**
13
+ * @typedef {{
14
+ * taskId: string,
15
+ * laneNumber?: number|null,
16
+ * classification?: string,
17
+ * }} DiagnosisTaskRow
18
+ */
19
+
20
+ /**
21
+ * @typedef {{
22
+ * workerOutputLogRef?: string|null,
23
+ * workerOutputLogPath?: string|null,
24
+ * output?: string|null,
25
+ * changedFileCount?: number|null,
26
+ * }} DoneMissingHint
27
+ */
28
+
29
+ /**
30
+ * @typedef {{
31
+ * type?: string,
32
+ * taskId?: string,
33
+ * payload?: {
34
+ * taskId?: string,
35
+ * gitignoredPaths?: unknown,
36
+ * },
37
+ * }} JournalEventLike
38
+ */
39
+
40
+ /**
41
+ * @param {string} filePath
42
+ * @param {number} [lineCount]
43
+ * @returns {string|null}
44
+ */
45
+ function readWorkerOutputLogTail(filePath, lineCount = WORKER_OUTPUT_TAIL_LINES) {
46
+ if (!fs.existsSync(filePath)) return null;
47
+ const content = fs.readFileSync(filePath, "utf-8");
48
+ const lines = content.split("\n");
49
+ if (lines.at(-1) === "") lines.pop();
50
+ if (lines.length === 0) return null;
51
+ return lines.slice(-lineCount).join("\n");
52
+ }
53
+
54
+ /**
55
+ * @param {string} projectRoot
56
+ * @param {string} batchId
57
+ * @param {string|null} failedTaskId
58
+ * @param {DiagnosisTaskRow[]} tasks
59
+ * @param {string|null} launchFailureKind
60
+ * @returns {string|null}
61
+ */
62
+ export function enrichLaunchFailureFromWorkerOutput(projectRoot, batchId, failedTaskId, tasks, launchFailureKind) {
63
+ if (launchFailureKind || !failedTaskId || !batchId) return launchFailureKind;
64
+ const task = tasks.find((entry) => entry.taskId === failedTaskId);
65
+ if (!task || task.laneNumber == null) return launchFailureKind;
66
+ const logPath = workerOutputLogPath(projectRoot, batchId, task.laneNumber, failedTaskId);
67
+ const tail = readWorkerOutputLogTail(logPath);
68
+ return inferLaunchFailureFromWorkerOutputTail(tail) ?? launchFailureKind;
69
+ }
70
+
71
+ /**
72
+ * @param {string} projectRoot
73
+ * @param {string} batchId
74
+ * @param {string|null} failedTaskId
75
+ * @param {DiagnosisTaskRow[]} tasks
76
+ * @param {DoneMissingHint|null|undefined} doneMissingHint
77
+ * @returns {{ workerOutputLogRef: string|null, workerOutputLogPath: string|null, workerOutputTail: string|null, workerOutputSnippet: string|null, changedFileCount: number|null }}
78
+ */
79
+ export function enrichWorkerDoneMissingContext(
80
+ projectRoot,
81
+ batchId,
82
+ failedTaskId,
83
+ tasks,
84
+ doneMissingHint,
85
+ ) {
86
+ const task = tasks.find((entry) => entry.taskId === failedTaskId);
87
+ const laneNumber = task?.laneNumber;
88
+ const logRef =
89
+ doneMissingHint?.workerOutputLogRef ??
90
+ (failedTaskId && laneNumber != null
91
+ ? workerOutputLogRef(batchId, laneNumber, failedTaskId)
92
+ : null);
93
+ const logPath =
94
+ doneMissingHint?.workerOutputLogPath ??
95
+ (failedTaskId && laneNumber != null
96
+ ? workerOutputLogPath(projectRoot, batchId, laneNumber, failedTaskId)
97
+ : null);
98
+ const tailFromDisk = logPath ? readWorkerOutputLogTail(logPath) : null;
99
+ const outputText = [doneMissingHint?.output, tailFromDisk].filter(Boolean).join("\n");
100
+ const snippet = outputText
101
+ ? outputText
102
+ .split("\n")
103
+ .filter(Boolean)
104
+ .slice(-3)
105
+ .join(" | ")
106
+ : null;
107
+
108
+ return {
109
+ workerOutputLogRef: logRef,
110
+ workerOutputLogPath: logPath,
111
+ workerOutputTail: tailFromDisk,
112
+ workerOutputSnippet: snippet,
113
+ changedFileCount:
114
+ doneMissingHint?.changedFileCount != null ? doneMissingHint.changedFileCount : null,
115
+ };
116
+ }
117
+
118
+ /**
119
+ * @param {DiagnosisTaskRow[]} tasks
120
+ * @param {string|null} failedTaskId
121
+ * @returns {boolean}
122
+ */
123
+ export function hasGhostRunningCluster(tasks, failedTaskId) {
124
+ if (!failedTaskId) return false;
125
+ const task = tasks.find((entry) => entry.taskId === failedTaskId);
126
+ if (!task || task.laneNumber == null) return false;
127
+ const laneNumber = Number(task.laneNumber);
128
+ return (
129
+ tasks.filter(
130
+ (entry) =>
131
+ entry.classification === "running" && Number(entry.laneNumber) === laneNumber,
132
+ ).length > 1
133
+ );
134
+ }
135
+
136
+ /**
137
+ * @param {JournalEventLike[]} journalEvents
138
+ * @param {string|null} failedTaskId
139
+ * @returns {string[]}
140
+ */
141
+ export function extractGitignoredPathsFromJournal(journalEvents, failedTaskId) {
142
+ if (!Array.isArray(journalEvents)) return [];
143
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
144
+ const event = journalEvents[index];
145
+ if (event.type !== "task.failed") continue;
146
+ const eventTaskId = event.taskId ?? event.payload?.taskId;
147
+ if (failedTaskId && eventTaskId && eventTaskId !== failedTaskId) continue;
148
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
149
+ if (Array.isArray(payload.gitignoredPaths)) {
150
+ return payload.gitignoredPaths.filter((entry) => typeof entry === "string");
151
+ }
152
+ }
153
+ return [];
154
+ }
155
+
156
+ /**
157
+ * @param {Record<string, unknown>|null|undefined} raw
158
+ * @param {string} batchId
159
+ * @param {string} taskId
160
+ * @returns {string|null}
161
+ */
162
+ export function laneTaskBranchForDiagnosis(raw, batchId, taskId) {
163
+ const tasks = raw?.tasks;
164
+ if (!Array.isArray(tasks)) return null;
165
+ const task = /** @type {DiagnosisTaskRow|undefined} */ (
166
+ tasks.find((entry) => {
167
+ if (!entry || typeof entry !== "object") return false;
168
+ return /** @type {{ taskId?: unknown }} */ (entry).taskId === taskId;
169
+ })
170
+ );
171
+ if (!task || task.laneNumber == null) return null;
172
+ return `task/spine-lane-${task.laneNumber}-${batchId}`;
173
+ }