pi-spine 2.19.0 → 2.20.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.
@@ -18,6 +18,7 @@ import {
18
18
  const RETRY_ALLOWED_PHASES = new Set(["paused", "failed"]);
19
19
  const RETRY_BLOCKED_PHASES = new Set(["running", "planning"]);
20
20
 
21
+
21
22
  /**
22
23
  * Fail running tasks and clear dead engine/worker PIDs before retry/skip (#203 / SP-647).
23
24
  *
@@ -28,11 +29,93 @@ function reconcileOrphanBeforeTaskMutation(projectRoot, state) {
28
29
  return reconcileOrphanRunningState({ projectRoot, state });
29
30
  }
30
31
 
32
+ /**
33
+ * Shared preamble for task/row mutations: load batch state, reconcile orphan
34
+ * running state, reload. Returns the live state or a ready-to-return error.
35
+ *
36
+ * @param {string} projectRoot
37
+ * @returns {{ ok: true, state: object } | { ok: false, result: { ok: false, exitCode: number, error: string, output: string } }}
38
+ */
39
+ export function loadMutableBatch(projectRoot) {
40
+ const loaded = loadSpineBatchState(projectRoot);
41
+ if (!loaded.raw) {
42
+ return {
43
+ ok: false,
44
+ result: { ok: false, exitCode: 1, error: "no_active_batch", output: "No active pi-spine batch.\n" },
45
+ };
46
+ }
47
+
48
+ reconcileOrphanBeforeTaskMutation(projectRoot, loaded.raw);
49
+
50
+ const reloaded = loadSpineBatchState(projectRoot);
51
+ const state = reloaded.raw;
52
+ if (!state) {
53
+ return {
54
+ ok: false,
55
+ result: { ok: false, exitCode: 1, error: "no_active_batch", output: "No active pi-spine batch.\n" },
56
+ };
57
+ }
58
+ return { ok: true, state };
59
+ }
60
+
61
+ /**
62
+ * Phase guard shared by retry/skip at task and row scope. `operation` only
63
+ * shapes the error text ("retry" vs "skip"); the phase sets are shared.
64
+ *
65
+ * @param {object} params
66
+ * @param {string} params.phase
67
+ * @param {"retry" | "skip"} params.operation
68
+ * @returns {{ ok: true } | { ok: false, error: string, output: string, batchId?: string, phase: string }}
69
+ */
70
+ export function guardPhaseForMutation({ phase, operation }) {
71
+ const verb = operation === "skip" ? "skip" : "retry";
72
+ if (RETRY_BLOCKED_PHASES.has(phase)) {
73
+ return {
74
+ ok: false,
75
+ error: `cannot_${verb}`,
76
+ output: `Cannot ${verb} task while batch phase is ${phase}. Pause the batch first.\n`,
77
+ phase,
78
+ };
79
+ }
80
+ if (operation === "retry" && !RETRY_ALLOWED_PHASES.has(phase)) {
81
+ return {
82
+ ok: false,
83
+ error: "cannot_retry",
84
+ output: `Cannot retry task in batch phase ${phase}. Retry is allowed in paused or failed batches.\n`,
85
+ phase,
86
+ };
87
+ }
88
+ return { ok: true };
89
+ }
90
+
91
+ /**
92
+ * Flip a matrix task's `failed` rows back to `pending` for a whole-task retry
93
+ * while preserving `succeeded` rows (never re-executed — #230) and `canceled`
94
+ * rows (operator exclusion wins).
95
+ *
96
+ * @param {object} task
97
+ * @returns {string[]} Row ids reset for re-execution.
98
+ */
99
+ function resetMatrixRowsForRetry(task) {
100
+ const rows = Array.isArray(task?.matrixRows) ? task.matrixRows : [];
101
+ /** @type {string[]} */
102
+ const retried = [];
103
+ for (const row of rows) {
104
+ if (!row || typeof row !== "object") continue;
105
+ if (row.status === "failed") {
106
+ row.status = "pending";
107
+ row.exitCode = null;
108
+ retried.push(row.rowId);
109
+ }
110
+ }
111
+ return retried;
112
+ }
113
+
31
114
  /**
32
115
  * @param {object} state
33
116
  * @param {string} taskId
34
117
  */
35
- function findTask(state, taskId) {
118
+ export function findTask(state, taskId) {
36
119
  return (state.tasks ?? []).find(
37
120
  (task) => task && typeof task === "object" && task.taskId === taskId,
38
121
  );
@@ -120,37 +203,18 @@ export function detectSegmentDrift(state) {
120
203
  * @param {string} params.taskId
121
204
  */
122
205
  export function retryTask({ projectRoot, taskId }) {
123
- const loaded = loadSpineBatchState(projectRoot);
124
- if (!loaded.raw) {
125
- return { ok: false, exitCode: 1, error: "no_active_batch", output: "No active pi-spine batch.\n" };
126
- }
127
-
128
- reconcileOrphanBeforeTaskMutation(projectRoot, loaded.raw);
129
-
130
- const reloaded = loadSpineBatchState(projectRoot);
131
- const state = reloaded.raw;
132
- if (!state) {
133
- return { ok: false, exitCode: 1, error: "no_active_batch", output: "No active pi-spine batch.\n" };
134
- }
206
+ const loadedBatch = loadMutableBatch(projectRoot);
207
+ if (!loadedBatch.ok) return loadedBatch.result;
208
+ const state = loadedBatch.state;
135
209
  const phase = String(state.phase ?? "");
136
210
 
137
- if (RETRY_BLOCKED_PHASES.has(phase)) {
211
+ const guard = guardPhaseForMutation({ phase, operation: "retry" });
212
+ if (!guard.ok) {
138
213
  return {
139
214
  ok: false,
140
215
  exitCode: 1,
141
- error: "cannot_retry",
142
- output: `Cannot retry task while batch phase is ${phase}. Pause the batch first.\n`,
143
- batchId: state.batchId,
144
- phase,
145
- };
146
- }
147
-
148
- if (!RETRY_ALLOWED_PHASES.has(phase)) {
149
- return {
150
- ok: false,
151
- exitCode: 1,
152
- error: "cannot_retry",
153
- output: `Cannot retry task in batch phase ${phase}. Retry is allowed in paused or failed batches.\n`,
216
+ error: guard.error,
217
+ output: guard.output,
154
218
  batchId: state.batchId,
155
219
  phase,
156
220
  };
@@ -204,6 +268,10 @@ export function retryTask({ projectRoot, taskId }) {
204
268
  };
205
269
  }
206
270
 
271
+ // Matrix tasks (#230): succeeded rows carry over (never re-executed) and
272
+ // canceled rows stay excluded — only failed rows re-enter the sweep.
273
+ const retriedRowIds = resetMatrixRowsForRetry(task);
274
+
207
275
  const unblocked = unblockBatchAfterRetry(state);
208
276
  if (!unblocked) {
209
277
  state.phase = "failed";
@@ -216,7 +284,8 @@ export function retryTask({ projectRoot, taskId }) {
216
284
  state.resilience.retryCountByScope[taskId] = (state.resilience.retryCountByScope[taskId] ?? 0) + 1;
217
285
 
218
286
  const pendingSegments = countPendingSegments(state, taskId);
219
- const previousPhase = String(reloaded.raw?.phase ?? phase);
287
+ // The shared preamble already reloaded state, so the live phase is `phase`.
288
+ const previousPhase = phase;
220
289
  recordTaskTransition({
221
290
  projectRoot,
222
291
  state,
@@ -225,6 +294,7 @@ export function retryTask({ projectRoot, taskId }) {
225
294
  taskId,
226
295
  previousClassification: reset.previousClassification,
227
296
  pendingSegments,
297
+ ...(retriedRowIds.length > 0 ? { retriedRowIds } : {}),
228
298
  },
229
299
  });
230
300
 
@@ -243,6 +313,12 @@ export function retryTask({ projectRoot, taskId }) {
243
313
 
244
314
  const resumeHint = unblocked ? "spine batch resume" : "spine batch resume --force";
245
315
 
316
+ let output = `Task ${taskId} reset for retry (pendingSegments=${pendingSegments}).`;
317
+ if (retriedRowIds.length > 0) {
318
+ output += `\n Matrix rows re-running: ${retriedRowIds.join(", ")} (succeeded rows carry over).`;
319
+ }
320
+ output += `\n → ${resumeHint}\n`;
321
+
246
322
  return {
247
323
  ok: true,
248
324
  exitCode: 0,
@@ -250,7 +326,8 @@ export function retryTask({ projectRoot, taskId }) {
250
326
  taskId,
251
327
  pendingSegments,
252
328
  unblocked,
253
- output: `Task ${taskId} reset for retry (pendingSegments=${pendingSegments}).\n → ${resumeHint}\n`,
329
+ ...(retriedRowIds.length > 0 ? { retriedRowIds } : {}),
330
+ output,
254
331
  };
255
332
  }
256
333
 
@@ -260,26 +337,18 @@ export function retryTask({ projectRoot, taskId }) {
260
337
  * @param {string} params.taskId
261
338
  */
262
339
  export function skipTask({ projectRoot, taskId }) {
263
- const loaded = loadSpineBatchState(projectRoot);
264
- if (!loaded.raw) {
265
- return { ok: false, exitCode: 1, error: "no_active_batch", output: "No active pi-spine batch.\n" };
266
- }
267
-
268
- reconcileOrphanBeforeTaskMutation(projectRoot, loaded.raw);
269
-
270
- const reloaded = loadSpineBatchState(projectRoot);
271
- const state = reloaded.raw;
272
- if (!state) {
273
- return { ok: false, exitCode: 1, error: "no_active_batch", output: "No active pi-spine batch.\n" };
274
- }
340
+ const loadedBatch = loadMutableBatch(projectRoot);
341
+ if (!loadedBatch.ok) return loadedBatch.result;
342
+ const state = loadedBatch.state;
275
343
  const phase = String(state.phase ?? "");
276
344
 
277
- if (RETRY_BLOCKED_PHASES.has(phase)) {
345
+ const guard = guardPhaseForMutation({ phase, operation: "skip" });
346
+ if (!guard.ok) {
278
347
  return {
279
348
  ok: false,
280
349
  exitCode: 1,
281
- error: "cannot_skip",
282
- output: `Cannot skip task while batch phase is ${phase}. Pause the batch first.\n`,
350
+ error: guard.error,
351
+ output: guard.output,
283
352
  batchId: state.batchId,
284
353
  phase,
285
354
  };
@@ -354,3 +423,4 @@ export function skipTask({ projectRoot, taskId }) {
354
423
  : `Task ${taskId} skipped.\n → spine batch resume --force\n`,
355
424
  };
356
425
  }
426
+
@@ -1,4 +1,3 @@
1
- // @ts-nocheck
2
1
  /**
3
2
  * Batch-state write guards, engine PID tracking, and schema validation (SP-587 / FR-SHIP-02).
4
3
  */
@@ -39,7 +38,7 @@ function archivedBatchStatePath(projectRoot, batchId) {
39
38
  * Reject cache writes from non-owner engines or post-archive resurrection (SP-254).
40
39
  *
41
40
  * @param {string} projectRoot
42
- * @param {object} state
41
+ * @param {Record<string, any>} state
43
42
  * @returns {{ allowed: boolean, reason?: string }}
44
43
  */
45
44
  export function evaluateBatchStateWriteGuard(projectRoot, state) {
@@ -121,7 +120,7 @@ export function readBatchEngineStartedAt(raw) {
121
120
  }
122
121
 
123
122
  /**
124
- * @param {object} state
123
+ * @param {Record<string, any>} state
125
124
  * @param {number} enginePid
126
125
  */
127
126
  export function recordBatchEnginePid(state, enginePid) {
@@ -133,7 +132,7 @@ export function recordBatchEnginePid(state, enginePid) {
133
132
  }
134
133
 
135
134
  /**
136
- * @param {object} state
135
+ * @param {Record<string, any>} state
137
136
  */
138
137
  export function clearBatchEnginePid(state) {
139
138
  if (!state?.resilience || typeof state.resilience !== "object") return;
@@ -237,7 +236,7 @@ export function validateBatchState(state) {
237
236
  ? /** @type {{ taskIds?: string[] }} */ (lane).taskIds
238
237
  : [];
239
238
  for (const taskId of taskIds) {
240
- const found = (raw.tasks ?? []).some(
239
+ const found = (/** @type {unknown[]} */ (raw.tasks ?? [])).some(
241
240
  (task) =>
242
241
  task &&
243
242
  typeof task === "object" &&
@@ -1,4 +1,3 @@
1
- // @ts-nocheck
2
1
  /**
3
2
  * Batch-state read/write/archive I/O (SP-587 / FR-SHIP-02).
4
3
  */
@@ -26,6 +25,7 @@ export function spineBatchStatePath(projectRoot) {
26
25
 
27
26
  /**
28
27
  * @param {string} projectRoot
28
+ * @returns {{ path: string | null, raw: any, parseError: string | null }}
29
29
  */
30
30
  export function loadSpineBatchState(projectRoot) {
31
31
  const filePath = spineBatchStatePath(projectRoot);
@@ -60,7 +60,7 @@ function archivedBatchStatePath(projectRoot, batchId) {
60
60
  * (engine vs. CLI complete/resume/abort).
61
61
  *
62
62
  * @param {string} projectRoot
63
- * @param {object} state
63
+ * @param {Record<string, any>} state
64
64
  * @param {{ bypassWriteGuard?: boolean }} [options]
65
65
  */
66
66
  export function saveSpineBatchState(projectRoot, state, options = {}) {
@@ -155,6 +155,7 @@ function buildWorkerFailureResult({
155
155
  * @param {string[]} [params.fileScopePaths]
156
156
  * @param {number} [params.timeoutMs]
157
157
  * @param {object} [params.workerBackendDeps] Test-only injectables for agentSession backend
158
+ * @param {Record<string, string>} [params.extraEnv] Extra child env (matrix row identity, #229)
158
159
  */
159
160
  export async function runWorker({
160
161
  worktreePath,
@@ -171,6 +172,7 @@ export async function runWorker({
171
172
  fileScopePaths = [],
172
173
  timeoutMs: _timeoutMs = DEFAULT_TIMEOUT_MS,
173
174
  workerBackendDeps = {},
175
+ extraEnv,
174
176
  }) {
175
177
  const donePath = path.join(taskFolder, ".DONE");
176
178
  if (fs.existsSync(donePath)) {
@@ -250,6 +252,7 @@ export async function runWorker({
250
252
  fileScopePaths,
251
253
  config,
252
254
  workerBackendDeps,
255
+ extraEnv,
253
256
  });
254
257
  const workerChild = /** @type {WorkerChildHandle} */ (child);
255
258
  let childPastPreflight = isExecute ? true : !useLaunchScript;
@@ -60,6 +60,7 @@ export function resolveWorkerLaunchScript(projectRoot, config = {}) {
60
60
  * @param {string[]} [params.fileScopePaths]
61
61
  * @param {object} [params.config]
62
62
  * @param {number} [params.piTimeoutMs]
63
+ * @param {Record<string, string>} [params.extraEnv] Extra child env (matrix row identity, #229)
63
64
  */
64
65
  export function buildWorkerChildEnv({
65
66
  taskFolder,
@@ -72,6 +73,7 @@ export function buildWorkerChildEnv({
72
73
  fileScopePaths = [],
73
74
  config = {},
74
75
  piTimeoutMs,
76
+ extraEnv,
75
77
  }) {
76
78
  const runner = path.join(PACKAGE_ROOT, "bin", "spine-worker-runner.mjs");
77
79
  /** @type {NodeJS.ProcessEnv} */
@@ -104,6 +106,12 @@ export function buildWorkerChildEnv({
104
106
  process.env.SPINE_WORKER_PI_TIMEOUT_MS ?? piTimeoutMs,
105
107
  );
106
108
  }
109
+ // Optional caller-supplied additions (matrix row identity, #229). Assigned
110
+ // last so explicit extras win, and omitted entirely for existing callers so
111
+ // the env stays byte-identical to the pre-#229 behavior.
112
+ if (extraEnv && typeof extraEnv === "object") {
113
+ Object.assign(env, extraEnv);
114
+ }
107
115
  return env;
108
116
  }
109
117
 
@@ -121,6 +129,7 @@ export function buildWorkerChildEnv({
121
129
  * @param {string[]} [params.fileScopePaths]
122
130
  * @param {object} [params.config]
123
131
  * @param {number} [params.piTimeoutMs]
132
+ * @param {Record<string, string>} [params.extraEnv] Extra child env (matrix row identity, #229)
124
133
  */
125
134
  export function spawnWorkerChild({
126
135
  worktreePath,
@@ -135,6 +144,7 @@ export function spawnWorkerChild({
135
144
  fileScopePaths = [],
136
145
  config = {},
137
146
  piTimeoutMs,
147
+ extraEnv,
138
148
  }) {
139
149
  const runner = path.join(PACKAGE_ROOT, "bin", "spine-worker-runner.mjs");
140
150
  const env = buildWorkerChildEnv({
@@ -148,6 +158,7 @@ export function spawnWorkerChild({
148
158
  fileScopePaths,
149
159
  config,
150
160
  piTimeoutMs,
161
+ extraEnv,
151
162
  });
152
163
  const args = useStub ? ["--stub"] : ["--pi"];
153
164
 
@@ -316,6 +327,7 @@ export function collectChildOutput(child, liveLogWriter) {
316
327
  * @param {string[]} [params.fileScopePaths]
317
328
  * @param {object} [params.config]
318
329
  * @param {object} [params.workerBackendDeps]
330
+ * @param {Record<string, string>} [params.extraEnv] Extra child env (matrix row identity, #229)
319
331
  */
320
332
  export function spawnWorkerHandle({
321
333
  worktreePath,
@@ -331,6 +343,7 @@ export function spawnWorkerHandle({
331
343
  fileScopePaths = [],
332
344
  config,
333
345
  workerBackendDeps,
346
+ extraEnv,
334
347
  }) {
335
348
  const journal =
336
349
  projectRoot && batchId
@@ -370,6 +383,7 @@ export function spawnWorkerHandle({
370
383
  laneCorrelationId,
371
384
  fileScopePaths,
372
385
  config,
386
+ extraEnv,
373
387
  });
374
388
  }
375
389
 
@@ -20,6 +20,11 @@
20
20
  * (`sk-ant-api...`) are never sent to the Admin API. GitHub Copilot is only
21
21
  * probed when the auth entry carries a PAT plus an explicit org or enterprise
22
22
  * context; user-level entries without that scope degrade to `absent`.
23
+ *
24
+ * Google is permanently `absent` (SP-748): Google ships no public usage or
25
+ * quota endpoint that authenticates with the AI Studio API key class pi
26
+ * stores, and the AI Studio dashboards that show usage are HTML consoles
27
+ * this project never scrapes. See `probeGoogle` for the research conclusion.
23
28
  */
24
29
 
25
30
  import fs from "node:fs";
@@ -43,6 +48,7 @@ export const PROBE_POOLS = {
43
48
  cursor: "cursor",
44
49
  anthropic: "anthropic",
45
50
  githubCopilot: "github-copilot",
51
+ google: "google",
46
52
  };
47
53
 
48
54
  /**
@@ -432,6 +438,41 @@ async function probeGitHubCopilot(auth, fetch) {
432
438
  }
433
439
  }
434
440
 
441
+ /**
442
+ * Google probe — permanently `absent` (SP-748, closes #277 with a documented
443
+ * won't-scrape rationale).
444
+ *
445
+ * Research conclusion (verified 2026-09-05): Google publishes no public usage
446
+ * or quota endpoint that authenticates with the credential class pi stores in
447
+ * `auth.json` (`{ "google": { "type": "api_key", "key": "AIza..." } }`, an
448
+ * AI Studio standard API key):
449
+ *
450
+ * - The Generative Language API reference (ai.google.dev/api) documents only
451
+ * inference and platform endpoints (interactions, generateContent,
452
+ * batch, embeddings, files, caches, countTokens); there is no usage-report
453
+ * or quota resource.
454
+ * - Rate limits and usage are published solely through AI Studio HTML
455
+ * dashboards (aistudio.google.com/rate-limit), which this project never
456
+ * scrapes.
457
+ * - The programmatic alternatives (Cloud Monitoring `request_count` metrics,
458
+ * Service Usage `consumerQuotaMetrics`) require GCP OAuth credentials with
459
+ * cloud-platform scope — a different credential class — and expose quota
460
+ * limits, not current usage.
461
+ *
462
+ * The probe therefore fails closed without reading the credential or touching
463
+ * the network, so the `google` pool keeps its offline estimate. When Google
464
+ * ships a public usage/quota endpoint for this key class, implement it here
465
+ * following the Z.ai/Kimi adapter pattern: explicit fields only, never invent
466
+ * a limit or remaining percentage, and never include secrets in the result.
467
+ *
468
+ * @param {object | null} _auth
469
+ * @param {typeof globalThis.fetch} _fetch
470
+ * @returns {Promise<ProbeResult>}
471
+ */
472
+ async function probeGoogle(_auth, _fetch) {
473
+ return { poolId: "google", source: "absent" };
474
+ }
475
+
435
476
  /**
436
477
  * Run the optional provider probes and return a map keyed by pool id.
437
478
  *
@@ -450,6 +491,7 @@ export async function runQuotaProbes({
450
491
  PROBE_POOLS.cursor,
451
492
  PROBE_POOLS.anthropic,
452
493
  PROBE_POOLS.githubCopilot,
494
+ PROBE_POOLS.google,
453
495
  ],
454
496
  } = {}) {
455
497
  const auth = loadAuthCredentials(authPath);
@@ -467,6 +509,8 @@ export async function runQuotaProbes({
467
509
  results.anthropic = await probeAnthropic(auth, fetch);
468
510
  } else if (provider === PROBE_POOLS.githubCopilot) {
469
511
  results["github-copilot"] = await probeGitHubCopilot(auth, fetch);
512
+ } else if (provider === PROBE_POOLS.google) {
513
+ results.google = await probeGoogle(auth, fetch);
470
514
  }
471
515
  }
472
516
 
@@ -30,6 +30,7 @@ export const CONTRACT_FIELD_NAMES = Object.freeze([
30
30
  "artifactsMustExist",
31
31
  "stallTimeoutMinutes",
32
32
  "extendGraceOnFileScope",
33
+ "matrixMaxParallel",
33
34
  ]);
34
35
 
35
36
  const CONTRACT_KNOWN_FIELDS = new Set(CONTRACT_FIELD_NAMES);
@@ -286,6 +287,7 @@ function collectDuplicateStepNumberErrors(steps) {
286
287
  * artifactsMustExist: string[],
287
288
  * stallTimeoutMinutes: number | null,
288
289
  * extendGraceOnFileScope: boolean | null,
290
+ * matrixMaxParallel: number | null,
289
291
  * rawTableValid: boolean,
290
292
  * errors: string[],
291
293
  * unknownFields: string[],
@@ -309,6 +311,7 @@ export function parseContract(markdown) {
309
311
  artifactsMustExist: [],
310
312
  stallTimeoutMinutes: null,
311
313
  extendGraceOnFileScope: null,
314
+ matrixMaxParallel: null,
312
315
  rawTableValid: false,
313
316
  errors: [],
314
317
  unknownFields: [],
@@ -509,6 +512,20 @@ function applyContractField(parsed, field, rawValue) {
509
512
  parsed.errors.push("Contract extendGraceOnFileScope must be true or false");
510
513
  return;
511
514
  }
515
+ case "matrixMaxParallel": {
516
+ const rawParallel = parseContractScalar(value);
517
+ if (!/^\d+$/.test(rawParallel)) {
518
+ parsed.errors.push("Contract matrixMaxParallel must be a positive integer");
519
+ return;
520
+ }
521
+ const parallel = Number(rawParallel);
522
+ if (parallel < 1) {
523
+ parsed.errors.push("Contract matrixMaxParallel must be a positive integer");
524
+ return;
525
+ }
526
+ parsed.matrixMaxParallel = parallel;
527
+ return;
528
+ }
512
529
  default:
513
530
  return;
514
531
  }
@@ -219,6 +219,7 @@ function isContractTableEmpty(parsed) {
219
219
  parsed.fileScopeMustNotChange.length === 0 &&
220
220
  parsed.minLineCoverage === null &&
221
221
  parsed.artifactsMustExist.length === 0 &&
222
+ parsed.matrixMaxParallel === null &&
222
223
  (parsed.unknownFields?.length ?? 0) === 0
223
224
  );
224
225
  }