pi-spine 2.30.0 → 2.32.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.
@@ -8,6 +8,7 @@
8
8
  import fs from "node:fs";
9
9
  import path from "node:path";
10
10
  import { writeJsonAtomic } from "../fs/atomic-write.mjs";
11
+ import { withBatchStateLock } from "./batch-state-lock.mjs";
11
12
  import { GATE_CATEGORIES } from "./gate-posture-defaults.mjs";
12
13
 
13
14
  /** @typedef {import("./gate-posture-defaults.mjs").GateCategory} GateCategory */
@@ -33,6 +34,33 @@ export const GATE_POSTURE_STREAK_REL = path.join(
33
34
 
34
35
  const CATEGORY_SET = new Set(/** @type {string[]} */ ([...GATE_CATEGORIES]));
35
36
 
37
+ /**
38
+ * SP-868 / #314 — serialize streak read-modify-write across processes.
39
+ *
40
+ * The streak store is project-wide JSON under `.spine/runtime/` while approve /
41
+ * reject / auto-approve decisions run in separate processes (CLI, engine,
42
+ * supervisor). Without a lock, a concurrent increment and reset can both read
43
+ * the same prev count and the last writer wins whole-file — a lost reset leaves
44
+ * a stale high streak that unlocks auto-approve early.
45
+ *
46
+ * Uses the same project-local lock primitive as the batch-state writers
47
+ * (`withBatchStateLock`: exclusive lock file published via temp + `linkSync`,
48
+ * PID-liveness stale breaking, token-gated release, per-process re-entrancy).
49
+ * Sharing that lock file also serializes streak RMWs against batch-state
50
+ * writers, and any caller already inside a batch-state critical section
51
+ * composes re-entrantly instead of deadlocking. Streak critical sections never
52
+ * acquire the resume handoff lock, so the SP-722 lock-ordering rules hold.
53
+ *
54
+ * @template T
55
+ * @param {string} projectRoot
56
+ * @param {() => T} fn synchronous critical section
57
+ * @param {{ timeoutMs?: number }} [options]
58
+ * @returns {T} `fn`'s return value
59
+ */
60
+ export function withGatePostureStreakLock(projectRoot, fn, options = {}) {
61
+ return /** @type {T} */ (withBatchStateLock(projectRoot, fn, options));
62
+ }
63
+
36
64
  /**
37
65
  * Absolute path to the streak JSON file.
38
66
  * @param {string} projectRoot
@@ -182,23 +210,27 @@ export function getKindStreak(projectRoot, kind) {
182
210
 
183
211
  /**
184
212
  * Increment category streak after an approval. Returns the new count.
213
+ * Read-modify-write runs under the streak lock (SP-868 / #314).
185
214
  * @param {string} projectRoot
186
215
  * @param {GateCategory | string} category
187
216
  * @returns {number}
188
217
  */
189
218
  export function incrementCategoryStreak(projectRoot, category) {
190
- const state = loadGatePostureStreaks(projectRoot);
191
- const prevRaw = state.categories[category];
192
- const prev =
193
- typeof prevRaw === "number" && Number.isInteger(prevRaw) && prevRaw >= 0 ? prevRaw : 0;
194
- const next = prev + 1;
195
- state.categories[category] = next;
196
- saveGatePostureStreaks(projectRoot, state);
197
- return next;
219
+ return withGatePostureStreakLock(projectRoot, () => {
220
+ const state = loadGatePostureStreaks(projectRoot);
221
+ const prevRaw = state.categories[category];
222
+ const prev =
223
+ typeof prevRaw === "number" && Number.isInteger(prevRaw) && prevRaw >= 0 ? prevRaw : 0;
224
+ const next = prev + 1;
225
+ state.categories[category] = next;
226
+ saveGatePostureStreaks(projectRoot, state);
227
+ return next;
228
+ });
198
229
  }
199
230
 
200
231
  /**
201
232
  * Increment kind streak after an approval. Returns the new count.
233
+ * Read-modify-write runs under the streak lock (SP-868 / #314).
202
234
  * @param {string} projectRoot
203
235
  * @param {string} kind
204
236
  * @returns {number}
@@ -207,40 +239,48 @@ export function incrementKindStreak(projectRoot, kind) {
207
239
  if (typeof kind !== "string" || kind.trim() === "") {
208
240
  throw new Error("gate posture kind streak key must be a non-empty string");
209
241
  }
210
- const state = loadGatePostureStreaks(projectRoot);
211
- const prevRaw = state.kinds[kind];
212
- const prev =
213
- typeof prevRaw === "number" && Number.isInteger(prevRaw) && prevRaw >= 0 ? prevRaw : 0;
214
- const next = prev + 1;
215
- state.kinds[kind] = next;
216
- saveGatePostureStreaks(projectRoot, state);
217
- return next;
242
+ return withGatePostureStreakLock(projectRoot, () => {
243
+ const state = loadGatePostureStreaks(projectRoot);
244
+ const prevRaw = state.kinds[kind];
245
+ const prev =
246
+ typeof prevRaw === "number" && Number.isInteger(prevRaw) && prevRaw >= 0 ? prevRaw : 0;
247
+ const next = prev + 1;
248
+ state.kinds[kind] = next;
249
+ saveGatePostureStreaks(projectRoot, state);
250
+ return next;
251
+ });
218
252
  }
219
253
 
220
254
  /**
221
255
  * Reset category streak on reject or manual break.
256
+ * Read-modify-write runs under the streak lock (SP-868 / #314).
222
257
  * @param {string} projectRoot
223
258
  * @param {GateCategory | string} category
224
259
  * @returns {number} Always 0 after reset
225
260
  */
226
261
  export function resetCategoryStreak(projectRoot, category) {
227
- const state = loadGatePostureStreaks(projectRoot);
228
- state.categories[category] = 0;
229
- saveGatePostureStreaks(projectRoot, state);
230
- return 0;
262
+ return withGatePostureStreakLock(projectRoot, () => {
263
+ const state = loadGatePostureStreaks(projectRoot);
264
+ state.categories[category] = 0;
265
+ saveGatePostureStreaks(projectRoot, state);
266
+ return 0;
267
+ });
231
268
  }
232
269
 
233
270
  /**
234
271
  * Reset kind streak on reject or manual break.
272
+ * Read-modify-write runs under the streak lock (SP-868 / #314).
235
273
  * @param {string} projectRoot
236
274
  * @param {string} kind
237
275
  * @returns {number} Always 0 after reset
238
276
  */
239
277
  export function resetKindStreak(projectRoot, kind) {
240
- const state = loadGatePostureStreaks(projectRoot);
241
- state.kinds[kind] = 0;
242
- saveGatePostureStreaks(projectRoot, state);
243
- return 0;
278
+ return withGatePostureStreakLock(projectRoot, () => {
279
+ const state = loadGatePostureStreaks(projectRoot);
280
+ state.kinds[kind] = 0;
281
+ saveGatePostureStreaks(projectRoot, state);
282
+ return 0;
283
+ });
244
284
  }
245
285
 
246
286
  /**
@@ -249,7 +289,11 @@ export function resetKindStreak(projectRoot, kind) {
249
289
  * @returns {GatePostureStreakState}
250
290
  */
251
291
  export function resetAllStreaks(projectRoot) {
252
- return saveGatePostureStreaks(projectRoot, emptyStreakState());
292
+ // Locked so a concurrent locked increment's read cannot straddle this whole
293
+ // store replacement and resurrect a stale-high count over it (SP-868 / #314).
294
+ return withGatePostureStreakLock(projectRoot, () =>
295
+ saveGatePostureStreaks(projectRoot, emptyStreakState()),
296
+ );
253
297
  }
254
298
 
255
299
  /**
@@ -13,14 +13,24 @@ import { countCommitsAhead } from "./lane-commit.mjs";
13
13
  * @param {string|null} ctx.orchBranch
14
14
  * @param {boolean} ctx.mergeResultsEmpty
15
15
  * @param {boolean} ctx.orchMergedToBase
16
+ * @param {boolean} [ctx.salvageLanded] salvage integrate landed every task's work on base (SP-862 / #374)
16
17
  */
17
18
  export function assertOrchIntegratable(projectRoot, ctx) {
18
- const { baseBranch, orchBranch, mergeResultsEmpty, orchMergedToBase } = ctx;
19
+ const { baseBranch, orchBranch, mergeResultsEmpty, orchMergedToBase, salvageLanded } = ctx;
19
20
 
20
21
  if (orchMergedToBase) {
21
22
  return { ok: true, reason: "orch_merged_to_base" };
22
23
  }
23
24
 
25
+ // SP-862 / #374: salvage integrate merged the lane task branches onto base —
26
+ // the work complete's merge gate cares about is on base even though the
27
+ // batch orch branch never merged. Only set when the salvage heal left zero
28
+ // unresolved tasks (fail-closed). Lifecycle complete is the only caller that
29
+ // passes this.
30
+ if (salvageLanded) {
31
+ return { ok: true, reason: "salvage_landed_to_base" };
32
+ }
33
+
24
34
  if (mergeResultsEmpty) {
25
35
  return { ok: true, reason: "no_merge_claimed" };
26
36
  }
@@ -422,6 +422,7 @@ export function integrateOrchToBase(ctx) {
422
422
  mergeCommit,
423
423
  commitsAhead,
424
424
  gateRequired: gateCheck.required ?? false,
425
+ gateForced: gateCheck.forced ?? false,
425
426
  headline: `Integrated ${orchBranch} into ${baseBranch}`,
426
427
  suggestedCommand: waiting?.suggestedCommand ?? "spine batch complete",
427
428
  alternatives: waiting
@@ -170,6 +170,27 @@ export function clearCompletedBatchState(projectRoot, batchStatePath, batchId) {
170
170
  clearActiveBatchStateIfMatches(batchStatePath, batchId, projectRoot);
171
171
  }
172
172
 
173
+ /**
174
+ * True when reconcile signals show live lane activity (running/pending tasks,
175
+ * or a lane whose status is running/active) — dismiss treats this as a live
176
+ * batch and requires --force.
177
+ *
178
+ * @param {object} signals
179
+ * @returns {boolean}
180
+ */
181
+ export function hasLiveLanes(signals) {
182
+ if (!signals) return false;
183
+ if (signals.hasRunningTasks || signals.hasPendingTasks) return true;
184
+ const lanes = signals.lanes;
185
+ return (
186
+ Array.isArray(lanes) &&
187
+ lanes.some((lane) => {
188
+ const status = String(lane?.status ?? "").toLowerCase();
189
+ return status === "running" || status === "active";
190
+ })
191
+ );
192
+ }
193
+
173
194
  /**
174
195
  * @param {object|null|undefined} config
175
196
  */
@@ -12,6 +12,7 @@ import {
12
12
  import {
13
13
  archiveBatchState,
14
14
  clearCompletedBatchState,
15
+ hasLiveLanes,
15
16
  reloadStateForTerminalWrite,
16
17
  } from "./lifecycle-archive.mjs";
17
18
  export { archiveBatchStatePath } from "./lifecycle-archive.mjs";
@@ -86,22 +87,6 @@ export function recordMergeBlocked({
86
87
  };
87
88
  }
88
89
 
89
- /**
90
- * @param {object} signals
91
- */
92
- function hasLiveLanes(signals) {
93
- if (!signals) return false;
94
- if (signals.hasRunningTasks || signals.hasPendingTasks) return true;
95
- const lanes = signals.lanes;
96
- return (
97
- Array.isArray(lanes) &&
98
- lanes.some((lane) => {
99
- const status = String(lane?.status ?? "").toLowerCase();
100
- return status === "running" || status === "active";
101
- })
102
- );
103
- }
104
-
105
90
  /**
106
91
  * @param {object} ctx
107
92
  * @param {string} ctx.projectRoot
@@ -177,7 +162,13 @@ export function dismissBatch(ctx) {
177
162
  };
178
163
  }
179
164
 
180
- if (diagnosis && !DISMISS_ALLOWED.has(diagnosis) && !force) {
165
+ // SP-862 / #374: needs_merge/needs_integrate after a full salvage heal is the
166
+ // empty batch shell (orch land loop never ran) — dismiss without --force.
167
+ const salvageCompleted =
168
+ Boolean(reconciliation.signals?.raw?.salvageLandedAllTasks) &&
169
+ Boolean(reconciliation.signals?.allTasksTerminalSuccess);
170
+
171
+ if (diagnosis && !DISMISS_ALLOWED.has(diagnosis) && !force && !salvageCompleted) {
181
172
  const output = buildDiagnosisOutput(diagnosis, {
182
173
  batchId,
183
174
  phase: reconciliation.phase,
@@ -323,7 +314,13 @@ export function completeBatch(ctx) {
323
314
  const diagnosis = reconciliation.diagnosis;
324
315
  const batchId = reconciliation.batchId ?? String(loaded.raw.batchId ?? loaded.raw.id ?? "");
325
316
  const signals = reconciliation.signals ?? {};
326
- const mergeSatisfied = !signals.mergeResultsEmpty || Boolean(signals.git?.orchMergedToBase);
317
+ // SP-862 / #374: salvage merges lane branches onto base (not orch) — after a
318
+ // full heal the salvage land is the merge evidence (fail-closed: evidence is
319
+ // only written when the heal left zero unresolved tasks, and allSuccess below
320
+ // still applies).
321
+ const salvageSatisfied = Boolean(signals.raw?.salvageLandedAllTasks);
322
+ const mergeSatisfied =
323
+ !signals.mergeResultsEmpty || Boolean(signals.git?.orchMergedToBase) || salvageSatisfied;
327
324
  const manualMergeOk =
328
325
  detectManualMerge &&
329
326
  (diagnosis === "completed_manual" || Boolean(signals.git?.orchMergedToBase));
@@ -372,6 +369,7 @@ export function completeBatch(ctx) {
372
369
  orchBranch: batch?.orchBranch ?? loaded.raw.orchBranch ?? null,
373
370
  mergeResultsEmpty: signals.mergeResultsEmpty,
374
371
  orchMergedToBase: Boolean(signals.git?.orchMergedToBase),
372
+ salvageLanded: salvageSatisfied,
375
373
  });
376
374
 
377
375
  if (!integratable.ok && !manualMergeOk) {
@@ -6,6 +6,7 @@ import { execFileSync } from "node:child_process";
6
6
  import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { parsePrompt } from "../tasks/packet/parse-prompt.mjs";
9
+ import { validateReviewBaseline } from "./batch-id.mjs";
9
10
 
10
11
  /**
11
12
  * Paths excluded from reviewer glob scope (runtime artifacts, not product code).
@@ -73,6 +74,8 @@ export function resolvePlanReviewScopePaths(taskFolder) {
73
74
  * @returns {string[]}
74
75
  */
75
76
  export function resolveCodeReviewScopePaths(worktreePath, baseline, runGit = defaultRunGit) {
77
+ // SP-869 (#313): fail closed on unsafe baselines before git argv use.
78
+ if (baseline) validateReviewBaseline(baseline);
76
79
  const args = baseline ? ["diff", "--name-only", `${baseline}..HEAD`] : ["diff", "--name-only"];
77
80
  try {
78
81
  const output = runGit("git", args, worktreePath);
@@ -11,6 +11,7 @@ import { appendJournalEvent } from "./journal.mjs";
11
11
  import { loadSpineBatchState } from "./state.mjs";
12
12
  import { buildReviewerContext } from "../config/reviewer-context.mjs";
13
13
  import { resolveReviewScopePaths } from "./review-scope.mjs";
14
+ import { validateReviewBaseline } from "./batch-id.mjs";
14
15
  import { commandExists as pathCommandExists } from "../util/command-exists.mjs";
15
16
  import {
16
17
  ARTIFACT_READY_HONOR_REASON,
@@ -161,6 +162,8 @@ export function buildReviewRequest({
161
162
  ].join("\n");
162
163
  }
163
164
 
165
+ // SP-869 (#313): fail closed on unsafe baselines before prompt interpolation.
166
+ if (baseline) validateReviewBaseline(baseline);
164
167
  const diffNamesCmd = baseline ? `git diff ${baseline}..HEAD --name-only` : "git diff --name-only";
165
168
  const diffCmd = baseline ? `git diff ${baseline}..HEAD` : "git diff";
166
169
 
@@ -16,6 +16,17 @@
16
16
  * Tasks outside the salvage set are never touched: non-salvageable failures
17
17
  * (contract/review failures) and evidence-less worker deaths remain failed and
18
18
  * keep blocking complete (SP-763 completion criteria).
19
+ *
20
+ * SP-862 / #374: when the heal leaves zero non-terminal tasks, the batch has no
21
+ * unresolved failure left, so the state also records `salvageLandedAllTasks`
22
+ * evidence (+ a `batch.salvage_landed_all_tasks` journal event). `complete` and
23
+ * `dismiss` use it to accept the salvage land as the batch's merge evidence —
24
+ * salvage merges lane task branches onto base, not the batch orch branch, so
25
+ * the orch-based merge gates (`mergeSatisfied`, needs_merge dismiss gate) would
26
+ * otherwise keep refusing and force `dismiss --force`. Fail-closed: the
27
+ * evidence alone never opens a gate — complete/dismiss still require every
28
+ * task terminal-success at gate time, so a later retry that re-opens tasks
29
+ * re-arms the refusal.
19
30
  */
20
31
 
21
32
  import { loadBatchStateFile } from "./batch-state-io.mjs";
@@ -107,6 +118,21 @@ export function healSalvagedTasksAfterIntegrate(projectRoot, batchId, options =
107
118
  return { ok: true, healedTaskIds, reason: "nothing_to_heal", error: null };
108
119
  }
109
120
 
121
+ // SP-862 / #374: no unresolved task remains after this heal — record the
122
+ // salvage land as batch-level merge evidence so complete/dismiss can accept
123
+ // it without --force (see module docstring for the fail-closed contract).
124
+ if (allTasksTerminalSuccess(loaded.raw)) {
125
+ loaded.raw.salvageLandedAllTasks = {
126
+ at: Date.now(),
127
+ mergeCommit: mergeCommit ?? null,
128
+ tasks: [...healedTaskIds],
129
+ };
130
+ appendJournalEvent(projectRoot, batchId, "batch.salvage_landed_all_tasks", {
131
+ mergeCommit: mergeCommit ?? null,
132
+ healedTaskIds: [...healedTaskIds],
133
+ });
134
+ }
135
+
110
136
  saveSpineBatchState(projectRoot, loaded.raw);
111
137
  return { ok: true, healedTaskIds, reason: null, error: null };
112
138
  } catch (err) {
@@ -114,3 +140,21 @@ export function healSalvagedTasksAfterIntegrate(projectRoot, batchId, options =
114
140
  return { ok: false, healedTaskIds: [], reason: "heal_threw", error: message };
115
141
  }
116
142
  }
143
+
144
+ /**
145
+ * True when every task in the raw batch state is terminal-success
146
+ * (`succeeded` / `skipped`) — i.e. no unresolved failure is left after the
147
+ * salvage heal. Unknown/missing statuses fail closed.
148
+ *
149
+ * @param {object} raw
150
+ * @returns {boolean}
151
+ */
152
+ function allTasksTerminalSuccess(raw) {
153
+ const tasks = Array.isArray(raw?.tasks) ? raw.tasks : [];
154
+ if (tasks.length === 0) return false;
155
+ return tasks.every((task) => {
156
+ if (!task || typeof task !== "object") return false;
157
+ const status = String(task.status ?? "").toLowerCase();
158
+ return status === "succeeded" || status === "skipped";
159
+ });
160
+ }
@@ -62,6 +62,14 @@ export function isBatchArchived(projectRoot, batchId) {
62
62
  * engine writers cannot be blocked by their own recorded PID; resurrection
63
63
  * protection always runs.
64
64
  *
65
+ * A live recorded PID does not reject writes to a **paused** batch (SP-861 / #376):
66
+ * a confirmed operator pause is an ownership handoff — the engine acknowledged the
67
+ * pause (persisted phase: paused + journaled `engine.pause_observed`) and stopped
68
+ * driving the batch, so its lingering process is not a writer owner. Refusing
69
+ * operator retry/skip recovery writes there dead-ends pause → retry → resume
70
+ * recovery. Engine-driven phases (`running`/`planning`) still refuse for any
71
+ * live foreign PID.
72
+ *
65
73
  * @param {string} projectRoot
66
74
  * @param {Record<string, any>} state
67
75
  * @param {{ skipOwnerCheck?: boolean, allowArchivedResurrection?: boolean }} [options]
@@ -92,7 +100,8 @@ export function evaluateBatchStateWriteGuard(projectRoot, state, options = {}) {
92
100
  !options.skipOwnerCheck &&
93
101
  ownerPid &&
94
102
  ownerPid !== process.pid &&
95
- isEngineProcessAlive(ownerPid, ownerStartedAt)
103
+ isEngineProcessAlive(ownerPid, ownerStartedAt) &&
104
+ onDiskPhase !== "paused"
96
105
  ) {
97
106
  return { allowed: false, reason: "stale_engine_pid" };
98
107
  }
@@ -20,6 +20,7 @@ import {
20
20
  import { redactSecretsDeep, redactTextSecrets } from "../util/secret-redact.mjs";
21
21
  import { computePendingTasks } from "../batch/resume-multi-validate.mjs";
22
22
  import { formatJournalTailEntry } from "../dashboard/snapshot.mjs";
23
+ import { batchIdRejectionReason } from "../batch/batch-id.mjs";
23
24
 
24
25
  const JOURNAL_TAIL_LIMIT = 10;
25
26
 
@@ -429,7 +430,9 @@ export function parseHandoffArgs(argv) {
429
430
  const args = { batchId: null, json: false };
430
431
  for (let i = 0; i < argv.length; i++) {
431
432
  const arg = argv[i];
432
- if (arg === "--batch") args.batchId = argv[++i] ?? null;
433
+ // SP-869 (#313): a bare `--batch` (flag without a value) is captured as ""
434
+ // so the validator below rejects it instead of falling back silently.
435
+ if (arg === "--batch") args.batchId = argv[++i] ?? "";
433
436
  else if (arg === "--json") args.json = true;
434
437
  }
435
438
  return args;
@@ -443,6 +446,16 @@ export function parseHandoffArgs(argv) {
443
446
  export function runSpineHandoff(options) {
444
447
  const { projectRoot, args: argv = [] } = options;
445
448
  const args = parseHandoffArgs(argv);
449
+ // SP-869 (#313): reject unsafe --batch IDs before archive path joins.
450
+ if (args.batchId != null) {
451
+ const reason = batchIdRejectionReason(args.batchId);
452
+ if (reason) {
453
+ return {
454
+ exitCode: 1,
455
+ output: `Invalid batch ID ${JSON.stringify(String(args.batchId))}: ${reason}\n`,
456
+ };
457
+ }
458
+ }
446
459
  const data = assembleHandoffData(projectRoot, args.batchId ?? undefined);
447
460
  const handoffPath = path.resolve(projectRoot, data.handoffPath ?? resolveHandoffPath(projectRoot));
448
461
  const markdown = renderHandoffMarkdown(data);
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import { DIAGNOSIS_TAXONOMY } from "../batch/diagnosis.mjs";
6
+ import { RUNNING_PHASES } from "../batch/reconcile-light-cache.mjs";
6
7
 
7
8
  /** Operator-facing wait targets not in reconcile diagnosis taxonomy. */
8
9
  export const WAIT_UNTIL_PSEUDO_DIAGNOSES = [
@@ -96,12 +97,52 @@ export function diagnosisMatchesUntil(diagnosis, untilDiagnoses) {
96
97
  }
97
98
 
98
99
  /**
100
+ * Partial-failure diagnoses that reconcile can report while sibling lane
101
+ * workers are still running (#375). All three derive from reconcile's
102
+ * `hasFailedTasks` branch, which fires on the first terminal-failure task —
103
+ * even mid-batch — so waking a land loop on them while a sibling lane is
104
+ * still live would pause/salvage/kill healthy lanes.
105
+ *
106
+ * @type {ReadonlySet<string>}
107
+ */
108
+ export const WAIT_LIVE_SIBLING_GATED_DIAGNOSES = new Set([
109
+ "needs_retry",
110
+ "worker_done_missing",
111
+ "needs_replan",
112
+ ]);
113
+
114
+ /**
115
+ * Whether any in-scope lane task is still live (#375). Prefers
116
+ * `signals.hasRunningTasks` — the per-task running classification reconcile
117
+ * itself derives — and only falls back to the batch phase when the result
118
+ * carries no signals block (injected reconcile fns, non-verbose results):
119
+ * the engine holds the phase in a live run state while lane workers are
120
+ * active and transitions to failed/completed only after lanes settle.
121
+ *
122
+ * @param {import("../batch/reconcile.mjs").ReconciliationResult & Record<string, unknown>} result
123
+ * @returns {boolean}
124
+ */
125
+ export function hasLiveSiblingLaneWorker(result) {
126
+ const signals = /** @type {Record<string, unknown> | null | undefined} */ (result?.signals);
127
+ if (signals != null && typeof signals === "object") {
128
+ return signals.hasRunningTasks === true;
129
+ }
130
+ return RUNNING_PHASES.has(String(result?.phase ?? ""));
131
+ }
132
+
133
+ /**
134
+ * Resolve which `--until` entry (taxonomy diagnosis, `failed` phase alias, or
135
+ * land-loop pseudo) a reconcile result matches; null when nothing matches.
136
+ * Single source of truth for match order — `describeMatchedDiagnosis` in the
137
+ * wait poll names the matched token through this helper.
138
+ *
99
139
  * @param {import("../batch/reconcile.mjs").ReconciliationResult & Record<string, unknown>} result
100
140
  * @param {Set<string>} untilDiagnoses
141
+ * @returns {string | null}
101
142
  */
102
- export function reconciliationMatchesUntil(result, untilDiagnoses) {
143
+ export function matchReconciliationUntil(result, untilDiagnoses) {
103
144
  if (diagnosisMatchesUntil(result.diagnosis ?? null, untilDiagnoses)) {
104
- return true;
145
+ return result.diagnosis;
105
146
  }
106
147
 
107
148
  // `--until failed` must wake on terminal batch failure even when reconcile
@@ -109,14 +150,35 @@ export function reconciliationMatchesUntil(result, untilDiagnoses) {
109
150
  // engine_orphaned) instead of the literal "failed" token (#252). Explicit
110
151
  // diagnosis tokens still match directly via the check above.
111
152
  if (untilDiagnoses.has("failed") && result.phase === "failed") {
112
- return true;
153
+ return "failed";
113
154
  }
114
155
 
115
156
  for (const pseudo of deriveWaitPseudoDiagnoses(result)) {
116
157
  if (untilDiagnoses.has(pseudo)) {
117
- return true;
158
+ return pseudo;
118
159
  }
119
160
  }
120
161
 
121
- return false;
162
+ return null;
163
+ }
164
+
165
+ /**
166
+ * @param {import("../batch/reconcile.mjs").ReconciliationResult & Record<string, unknown>} result
167
+ * @param {Set<string>} untilDiagnoses
168
+ */
169
+ export function reconciliationMatchesUntil(result, untilDiagnoses) {
170
+ const matched = matchReconciliationUntil(result, untilDiagnoses);
171
+ if (matched == null) {
172
+ return false;
173
+ }
174
+ // Partial-failure hold (#375): needs_retry / worker_done_missing /
175
+ // needs_replan fire on the first failed task even while sibling lane
176
+ // workers are still running. Hold the match until the live siblings
177
+ // settle; terminal aliases (`failed`), success/integrate diagnoses, and
178
+ // gate pseudos keep their current behavior so a fully terminal batch
179
+ // never waits on imaginary siblings.
180
+ if (WAIT_LIVE_SIBLING_GATED_DIAGNOSES.has(matched) && hasLiveSiblingLaneWorker(result)) {
181
+ return false;
182
+ }
183
+ return true;
122
184
  }
package/src/cli/wait.mjs CHANGED
@@ -12,9 +12,8 @@ import path from "node:path";
12
12
 
13
13
  import { reconcileBatch } from "../batch/reconcile.mjs";
14
14
  import {
15
- deriveWaitPseudoDiagnoses,
16
- diagnosisMatchesUntil,
17
15
  parseUntilDiagnoses,
16
+ matchReconciliationUntil,
18
17
  reconciliationMatchesUntil,
19
18
  } from "./spine-wait.mjs";
20
19
  import {
@@ -132,19 +131,7 @@ function formatWaitElapsed(ms) {
132
131
  * @returns {string}
133
132
  */
134
133
  function describeMatchedDiagnosis(result, untilDiagnoses) {
135
- const diagnosis = result.diagnosis ?? null;
136
- if (diagnosisMatchesUntil(diagnosis, untilDiagnoses)) {
137
- return diagnosis;
138
- }
139
- if (untilDiagnoses.has("failed") && result.phase === "failed") {
140
- return "failed";
141
- }
142
- for (const pseudo of deriveWaitPseudoDiagnoses(result)) {
143
- if (untilDiagnoses.has(pseudo)) {
144
- return pseudo;
145
- }
146
- }
147
- return diagnosis ?? "matched";
134
+ return matchReconciliationUntil(result, untilDiagnoses) ?? result.diagnosis ?? "matched";
148
135
  }
149
136
 
150
137
  /**
@@ -341,7 +328,11 @@ export async function runSpineWait(options) {
341
328
 
342
329
  try {
343
330
  while (running) {
344
- const result = reconcileFn({ projectRoot });
331
+ // verbose: true (#375) — exposes signals.hasRunningTasks so the
332
+ // partial-failure match gate uses reconcile's own live-task
333
+ // classification instead of the phase fallback. buildWatchSnapshot
334
+ // picks explicit fields, so signals never leak into --json output.
335
+ const result = reconcileFn({ projectRoot, verbose: true });
345
336
  if (!scopedBatchIdCaptured) {
346
337
  const candidate = result.batchId ?? null;
347
338
  if (candidate != null) {
@@ -39,11 +39,16 @@ export const RULES_PROFILE_REL_PATH = ".spine/rules-profile.json";
39
39
  * @property {RulesProfileDiscovery} discovery
40
40
  */
41
41
 
42
- /** Built-in profile when `.spine/rules-profile.json` is missing. */
42
+ /**
43
+ * Built-in profile when `.spine/rules-profile.json` is missing.
44
+ * SP-872: worker `alwaysInclude` is empty — spine-native workers get their
45
+ * context from `alwaysApply` rules + glob matching. Taskplane rules are opt-in
46
+ * via an explicit `alwaysInclude` in the project profile (#344).
47
+ */
43
48
  export const DEFAULT_RULES_PROFILE = Object.freeze({
44
49
  profileVersion: 1,
45
50
  worker: Object.freeze({
46
- alwaysInclude: Object.freeze(["taskplane-worker-cursor.mdc"]),
51
+ alwaysInclude: Object.freeze([]),
47
52
  neverInclude: Object.freeze([]),
48
53
  globMatch: true,
49
54
  }),
@@ -15,13 +15,16 @@ import {
15
15
  import { loadRulesProfile } from "./cursor-rules/profile.mjs";
16
16
  import { selectRulesForWorker } from "./cursor-rules/select.mjs";
17
17
 
18
- /** Default injected standards for pi-spine / JS-CLI projects (matches bootstrap checklist). */
18
+ /**
19
+ * Default injected standards for pi-spine / JS-CLI projects (matches bootstrap
20
+ * checklist). SP-872: Taskplane authoring/worker rules removed — spine-native
21
+ * defaults only; projects needing Taskplane opt in via `config.standards`
22
+ * (SP-093 superseded init seeding of this list; kept for static-context users).
23
+ */
19
24
  export const DEFAULT_SPINE_INIT_STANDARDS = [
20
25
  ".cursor/rules/javascript-3-development-standards.mdc",
21
26
  ".cursor/rules/general-llm-anti-patterns.mdc",
22
27
  ".cursor/rules/critical-rules-quick-reference.mdc",
23
- ".cursor/rules/taskplane-task-authoring.mdc",
24
- ".cursor/rules/taskplane-worker-cursor.mdc",
25
28
  ];
26
29
 
27
30
  export const DEFAULT_WORKER_CONTEXT_BYTE_CAP = 32_768;