pi-spine 2.9.0 → 2.11.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,8 @@ import { loadSpineConfig } from "../config/spine-config-load.mjs";
8
8
  import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
9
9
  import { filterPorcelain } from "./lane-commit.mjs";
10
10
  import { runWorktreeSetupHook } from "./worktree.mjs";
11
+ import { execFileSync } from "node:child_process";
12
+ import { matchesContractPattern } from "./contract-parse.mjs";
11
13
 
12
14
  /**
13
15
  * Path segments that identify generated coverage report artifacts.
@@ -296,3 +298,64 @@ export function filterOutOfScopeCoveragePorcelain(porcelain, fileScopePaths, ign
296
298
  }
297
299
  return kept.length === 0 ? "" : kept.join("\n");
298
300
  }
301
+
302
+ /**
303
+ * Stages untracked files matching fileScopeMustChange patterns so workers are not penalized
304
+ * for forgetting to `git add` new files before contract verification (SP-668 / #219).
305
+ *
306
+ * @param {string} worktreePath
307
+ * @param {string[]} fileScopeMustChange
308
+ * @returns {{ stagedCount: number, error?: string }}
309
+ */
310
+ export function stageUntrackedScopeFiles(worktreePath, fileScopeMustChange = []) {
311
+ if (!Array.isArray(fileScopeMustChange) || fileScopeMustChange.length === 0) {
312
+ return { stagedCount: 0 };
313
+ }
314
+
315
+ let porcelain;
316
+ try {
317
+ porcelain = execFileSync("git", ["status", "--porcelain", "-uall"], {
318
+ cwd: worktreePath,
319
+ encoding: "utf-8",
320
+ stdio: ["ignore", "pipe", "pipe"]
321
+ });
322
+ } catch (error) {
323
+ return { stagedCount: 0, error: `git status failed: ${error.message}` };
324
+ }
325
+
326
+ const toStage = [];
327
+ for (const line of porcelain.split("\n")) {
328
+ if (!line.trim()) continue;
329
+ const status = line.slice(0, 2);
330
+ if (status !== "??") continue;
331
+
332
+ let filePath = extractPorcelainPath(line);
333
+ if (!filePath) continue;
334
+ if (filePath.startsWith('"') && filePath.endsWith('"')) {
335
+ filePath = filePath.slice(1, -1);
336
+ }
337
+
338
+ const matched = fileScopeMustChange.some((pattern) =>
339
+ pattern.endsWith("/") ? filePath.startsWith(pattern) : matchesContractPattern(filePath, pattern)
340
+ );
341
+
342
+ if (matched) {
343
+ toStage.push(filePath);
344
+ }
345
+ }
346
+
347
+ if (toStage.length === 0) {
348
+ return { stagedCount: 0 };
349
+ }
350
+
351
+ try {
352
+ execFileSync("git", ["add", "--", ...toStage], {
353
+ cwd: worktreePath,
354
+ encoding: "utf-8",
355
+ stdio: ["ignore", "pipe", "pipe"]
356
+ });
357
+ return { stagedCount: toStage.length };
358
+ } catch (error) {
359
+ return { stagedCount: 0, error: `git add failed: ${error.message}` };
360
+ }
361
+ }
@@ -0,0 +1,119 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Usage rollup helpers for run-metrics.jsonl.
4
+ *
5
+ * Aggregates numeric usage fields (`tokensIn`, `tokensOut`, `estimatedUsd`) by
6
+ * batch, model, and agent role. Only task-style records with finite usage
7
+ * contribute; groups with no usage are omitted so totals stay clean.
8
+ */
9
+
10
+ const USAGE_FIELDS = ["tokensIn", "tokensOut", "estimatedUsd"];
11
+
12
+ /**
13
+ * @param {object[]} lines
14
+ * @returns {{ byBatch: Record<string, object>, byModel: Record<string, object>, byRole: Record<string, object> } | null}
15
+ */
16
+ export function rollupMetrics(lines) {
17
+ /** @type {Record<string, Record<string, number>>} */
18
+ const byBatch = {};
19
+ /** @type {Record<string, Record<string, number>>} */
20
+ const byModel = {};
21
+ /** @type {Record<string, Record<string, number>>} */
22
+ const byRole = {};
23
+
24
+ let anyUsage = false;
25
+ for (const line of lines) {
26
+ if (!line || typeof line !== "object") continue;
27
+ // Call each bucket independently — `||` would skip model/role after batch hits.
28
+ const hitBatch = addUsage(byBatch, line.batchId ?? "—", line);
29
+ const hitModel = addUsage(byModel, line.model ?? "—", line);
30
+ const hitRole = addUsage(byRole, line.role ?? line.agentRole ?? "—", line);
31
+ if (hitBatch || hitModel || hitRole) anyUsage = true;
32
+ }
33
+
34
+ if (!anyUsage) return null;
35
+ return { byBatch, byModel, byRole };
36
+ }
37
+
38
+ /**
39
+ * Accumulate finite usage fields into a single bucket, creating the bucket
40
+ * only when the line actually carries usage data.
41
+ *
42
+ * @param {Record<string, Record<string, number>>} store
43
+ * @param {string} key
44
+ * @param {object} line
45
+ * @returns {boolean} true when the line contributed at least one usage field
46
+ */
47
+ function addUsage(store, key, line) {
48
+ let contributed = false;
49
+ for (const field of USAGE_FIELDS) {
50
+ const value = line[field];
51
+ if (Number.isFinite(value)) {
52
+ store[key] ??= {};
53
+ store[key][field] = (store[key][field] ?? 0) + value;
54
+ contributed = true;
55
+ }
56
+ }
57
+ if (contributed) {
58
+ store[key] ??= {};
59
+ store[key].count = (store[key].count ?? 0) + 1;
60
+ }
61
+ return contributed;
62
+ }
63
+
64
+ /**
65
+ * Format rollups as a short human-readable section with one table per grouping.
66
+ *
67
+ * @param {{ byBatch: Record<string, object>, byModel: Record<string, object>, byRole: Record<string, object> }} rollups
68
+ * @returns {string}
69
+ */
70
+ export function formatMetricsRollups(rollups) {
71
+ if (!rollups) return "";
72
+
73
+ const sections = [
74
+ formatRollupTable("Usage by batch", rollups.byBatch),
75
+ formatRollupTable("Usage by model", rollups.byModel),
76
+ formatRollupTable("Usage by role", rollups.byRole),
77
+ ];
78
+ const body = sections.filter(Boolean).join("\n");
79
+ if (!body) return "";
80
+ return `\n${body}`;
81
+ }
82
+
83
+ /**
84
+ * @param {string} title
85
+ * @param {Record<string, object>} groups
86
+ * @returns {string}
87
+ */
88
+ function formatRollupTable(title, groups) {
89
+ const entries = Object.entries(groups);
90
+ if (entries.length === 0) return "";
91
+
92
+ const header = ["Group", "Tokens In", "Tokens Out", "Est. USD", "Records"];
93
+ const rows = entries.map(([key, bucket]) => [
94
+ key,
95
+ formatNumber(bucket.tokensIn),
96
+ formatNumber(bucket.tokensOut),
97
+ formatNumber(bucket.estimatedUsd),
98
+ formatNumber(bucket.count),
99
+ ]);
100
+
101
+ const widths = header.map((col, index) =>
102
+ Math.max(col.length, ...rows.map((row) => String(row[index]).length)),
103
+ );
104
+
105
+ const formatRow = (row) =>
106
+ row.map((cell, index) => String(cell).padStart(widths[index])).join(" ");
107
+
108
+ return `${title}:\n${[formatRow(header), ...rows.map(formatRow)].join("\n")}`;
109
+ }
110
+
111
+ /**
112
+ * @param {number | undefined} value
113
+ * @returns {string}
114
+ */
115
+ function formatNumber(value) {
116
+ if (value == null || !Number.isFinite(value)) return "—";
117
+ if (Number.isInteger(value)) return String(value);
118
+ return value.toFixed(4);
119
+ }
@@ -10,6 +10,7 @@ import { METRICS_DEFAULTS } from "../config/defaults.mjs";
10
10
  import { readReviewLevel } from "./review.mjs";
11
11
 
12
12
  const REDACT_KEY_PATTERN = /key|token|secret|password|prompt/i;
13
+ const USAGE_KEYS = new Set(["tokensIn", "tokensOut", "estimatedUsd"]);
13
14
 
14
15
  /**
15
16
  * @param {object} config
@@ -91,7 +92,7 @@ function redactMetricValue(value) {
91
92
  /** @type {Record<string, unknown>} */
92
93
  const out = {};
93
94
  for (const [key, entry] of Object.entries(/** @type {Record<string, unknown>} */ (value))) {
94
- if (REDACT_KEY_PATTERN.test(key)) {
95
+ if (REDACT_KEY_PATTERN.test(key) && !USAGE_KEYS.has(key)) {
95
96
  out[key] = "[REDACTED]";
96
97
  } else if (entry && typeof entry === "object") {
97
98
  out[key] = redactMetricValue(entry);
@@ -172,6 +173,10 @@ export function buildTaskMetricRecord({ batchId, task, config = {}, taskFolder,
172
173
  if (task.finalAttempts != null) record.finalAttempts = task.finalAttempts;
173
174
  if (task.contractOk != null) record.contractOk = task.contractOk;
174
175
  if (task.stallKilled === true) record.stallKilled = true;
176
+ if (Number.isFinite(task.tokensIn)) record.tokensIn = task.tokensIn;
177
+ if (Number.isFinite(task.tokensOut)) record.tokensOut = task.tokensOut;
178
+ if (Number.isFinite(task.estimatedUsd)) record.estimatedUsd = task.estimatedUsd;
179
+ if (typeof task.role === "string") record.role = task.role;
175
180
 
176
181
  return sanitizeMetricRecord(record);
177
182
  }
@@ -10,7 +10,7 @@ import {
10
10
  resolveWorkerPiTimeoutMs,
11
11
  parseTaskSizeFromFolder,
12
12
  } from "./task-stall-budget.mjs";
13
- import { parseContract } from "../tasks/packet/parse-prompt.mjs";
13
+ import { parseContract, parsePrompt } from "../tasks/packet/parse-prompt.mjs";
14
14
  import { appendJournalEvent } from "./journal.mjs";
15
15
  import { assertReviewToolAvailable } from "./review.mjs";
16
16
  import { finalizeWorkerOutput, createWorkerLiveLogWriter } from "./worker-output.mjs";
@@ -22,6 +22,7 @@ import {
22
22
  resolveWorkerLaunchScript,
23
23
  resolveWorkerPhase,
24
24
  spawnWorkerHandle,
25
+ spawnExecutionOnlyHandle,
25
26
  terminateHungWorkerChild,
26
27
  CHILD_DONE_TIMEOUT_MS,
27
28
  } from "./worker-spawn.mjs";
@@ -203,32 +204,48 @@ export async function runWorker({
203
204
 
204
205
  const taskSize = parseTaskSizeFromFolder(taskFolder);
205
206
  const promptPath = path.join(taskFolder, "PROMPT.md");
206
- const contract = fs.existsSync(promptPath)
207
- ? parseContract(fs.readFileSync(promptPath, "utf-8"))
208
- : { stallTimeoutMinutes: null, extendGraceOnFileScope: null };
207
+ const promptText = fs.existsSync(promptPath) ? fs.readFileSync(promptPath, "utf-8") : "";
208
+ const parsedPrompt = promptText ? parsePrompt(promptText) : null;
209
+ const contract = promptText ? parseContract(promptText) : { stallTimeoutMinutes: null, extendGraceOnFileScope: null, runCommand: null, testCommand: null };
209
210
  const stallConfig = resolveStallConfigForTask({ config, taskSize, contract });
210
211
  const piTimeoutMs = resolveWorkerPiTimeoutMs({ config, taskSize, contract });
211
212
  const startedAt = Date.now();
212
213
 
213
- const child = spawnWorkerHandle({
214
- worktreePath,
215
- taskFolder,
216
- useStub,
217
- timeoutMs: piTimeoutMs,
218
- piTimeoutMs,
219
- projectRoot,
220
- batchId,
221
- laneNumber,
222
- taskId,
223
- laneCorrelationId,
224
- fileScopePaths,
225
- config,
226
- workerBackendDeps,
227
- });
214
+ const isExecute = parsedPrompt?.type === "execute";
215
+ const runCommand = contract.runCommand || contract.testCommand;
216
+
217
+ const child = isExecute
218
+ ? spawnExecutionOnlyHandle({
219
+ worktreePath,
220
+ taskFolder,
221
+ command: runCommand || "echo 'No runCommand or testCommand provided' && exit 1",
222
+ projectRoot,
223
+ batchId,
224
+ laneNumber,
225
+ taskId,
226
+ laneCorrelationId,
227
+ fileScopePaths,
228
+ config,
229
+ })
230
+ : spawnWorkerHandle({
231
+ worktreePath,
232
+ taskFolder,
233
+ useStub,
234
+ timeoutMs: piTimeoutMs,
235
+ piTimeoutMs,
236
+ projectRoot,
237
+ batchId,
238
+ laneNumber,
239
+ taskId,
240
+ laneCorrelationId,
241
+ fileScopePaths,
242
+ config,
243
+ workerBackendDeps,
244
+ });
228
245
  const workerChild = /** @type {WorkerChildHandle} */ (child);
229
- let childPastPreflight = !useLaunchScript;
246
+ let childPastPreflight = isExecute ? true : !useLaunchScript;
230
247
  /** @type {WorkerPhase} */
231
- const initialWorkerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
248
+ const initialWorkerPhase = isExecute ? "pi" : resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
232
249
  markChildPastPreflight(workerChild, () => {
233
250
  childPastPreflight = true;
234
251
  });
@@ -167,6 +167,55 @@ export function spawnWorkerChild({
167
167
  });
168
168
  }
169
169
 
170
+ /**
171
+ * @param {object} params
172
+ * @param {string} params.worktreePath
173
+ * @param {string} params.taskFolder
174
+ * @param {string} params.command
175
+ * @param {string} [params.projectRoot]
176
+ * @param {string} [params.batchId]
177
+ * @param {number} [params.laneNumber]
178
+ * @param {string} [params.taskId]
179
+ * @param {string} [params.laneCorrelationId]
180
+ * @param {string[]} [params.fileScopePaths]
181
+ * @param {object} [params.config]
182
+ */
183
+ export function spawnExecutionOnlyHandle({
184
+ worktreePath,
185
+ taskFolder,
186
+ command,
187
+ projectRoot,
188
+ batchId,
189
+ laneNumber,
190
+ taskId,
191
+ laneCorrelationId,
192
+ fileScopePaths = [],
193
+ config = {},
194
+ }) {
195
+ const env = buildWorkerChildEnv({
196
+ taskFolder,
197
+ worktreePath,
198
+ projectRoot,
199
+ batchId,
200
+ laneNumber,
201
+ taskId,
202
+ laneCorrelationId,
203
+ fileScopePaths,
204
+ config,
205
+ });
206
+
207
+ // Create a wrapper script that runs the command and then creates .DONE
208
+ // This matches the behavior expected by the heartbeat loop.
209
+ // We run `/bin/sh -c "<command> && touch .DONE"`
210
+ const script = `${command} && touch "${path.join(taskFolder, ".DONE")}"`;
211
+
212
+ return spawn("/bin/sh", ["-c", script], {
213
+ cwd: worktreePath,
214
+ env,
215
+ stdio: ["ignore", "pipe", "pipe"],
216
+ });
217
+ }
218
+
170
219
  /**
171
220
  * @param {WorkerChildHandle} child
172
221
  * @param {() => void} onPreflightComplete
@@ -0,0 +1,123 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * CLI entrypoint for `spine metrics quota`.
4
+ *
5
+ * Builds the SP-678 quota snapshot and either writes a timestamped JSON report
6
+ * under `.spine/reports/` with a human summary, or emits the snapshot as JSON
7
+ * to stdout when `--json` is requested. Secrets and prompt bodies are never
8
+ * written because the snapshot builder already excludes them.
9
+ *
10
+ * `--open` writes a self-contained HTML report beside the JSON snapshot
11
+ * (SP-680 renderer). Browser launch is left to the operator.
12
+ */
13
+
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+
17
+ import { buildQuotaSnapshot } from "./quota-snapshot.mjs";
18
+ import { renderQuotaHtml, writeHtmlBesideJson } from "./quota-html.mjs";
19
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
20
+
21
+ const REPORTS_DIR = ".spine/reports";
22
+
23
+ /**
24
+ * Format an ISO timestamp that is safe for filesystem paths.
25
+ *
26
+ * @param {number | string | Date} now
27
+ * @returns {string}
28
+ */
29
+ function formatReportFilename(now) {
30
+ const iso = new Date(now).toISOString().replace(/[:.]/g, "-");
31
+ return `quota-snapshot-${iso}.json`;
32
+ }
33
+
34
+ /**
35
+ * Format a short human-readable summary of the snapshot.
36
+ *
37
+ * @param {import("./quota-snapshot.mjs").QuotaSnapshot} snapshot
38
+ * @param {string | null} reportPath
39
+ * @returns {string}
40
+ */
41
+ function formatHumanSummary(snapshot, reportPath) {
42
+ const pools = Object.values(snapshot.pools ?? {});
43
+ const estimatePools = pools.filter((p) => p.source === "estimate").length;
44
+ const absentPools = pools.filter((p) => p.source === "absent").length;
45
+ const totalTasks = pools.reduce((sum, p) => sum + (p.usage?.taskCount ?? 0), 0);
46
+
47
+ const lines = [
48
+ `Quota snapshot: ${snapshot.generatedAt}`,
49
+ ` Source: ${snapshot.snapshotSource}`,
50
+ ` Pools: ${pools.length} (${estimatePools} with usage, ${absentPools} absent)`,
51
+ ` Total tasks observed: ${totalTasks}`,
52
+ ];
53
+
54
+ for (const pool of pools) {
55
+ const usage = pool.usage;
56
+ const parts = [`${pool.poolId}: ${usage.taskCount} tasks`];
57
+ if (usage.durationMs > 0) parts.push(`${usage.durationMs}ms`);
58
+ if (usage.tokensIn) parts.push(`${usage.tokensIn} in-tokens`);
59
+ if (usage.tokensOut) parts.push(`${usage.tokensOut} out-tokens`);
60
+ if (usage.estimatedUsd) parts.push(`$${usage.estimatedUsd.toFixed(4)} est`);
61
+ lines.push(` ${parts.join(", ")}`);
62
+ }
63
+
64
+ if (reportPath) {
65
+ lines.push(` Report: ${reportPath}`);
66
+ }
67
+
68
+ return lines.join("\n") + "\n";
69
+ }
70
+
71
+ /**
72
+ * Run the `spine metrics quota` command.
73
+ *
74
+ * @param {object} params
75
+ * @param {string} params.projectRoot
76
+ * @param {object} [params.config]
77
+ * @param {string[]} [params.args]
78
+ * @param {number | string | Date} [params.now]
79
+ * @returns {{ output: string, exitCode: number, reportPath: string | null }}
80
+ */
81
+ export function runQuotaReport({ projectRoot, config, args = [], now = Date.now(), metricsLines }) {
82
+ const json = args.includes("--json");
83
+ const open = args.includes("--open");
84
+
85
+ let resolvedConfig = config;
86
+ if (!resolvedConfig) {
87
+ const configResult = loadSpineConfig(projectRoot);
88
+ if (configResult.error) {
89
+ return {
90
+ output: `Error: ${configResult.error.message}\n`,
91
+ exitCode: 1,
92
+ reportPath: null,
93
+ };
94
+ }
95
+ resolvedConfig = configResult.config;
96
+ }
97
+
98
+ const snapshot = buildQuotaSnapshot({ projectRoot, config: resolvedConfig, metricsLines, now });
99
+
100
+ if (json) {
101
+ return {
102
+ output: JSON.stringify(snapshot, null, 2) + "\n",
103
+ exitCode: 0,
104
+ reportPath: null,
105
+ };
106
+ }
107
+
108
+ const reportsDir = path.join(projectRoot, REPORTS_DIR);
109
+ if (!fs.existsSync(reportsDir)) {
110
+ fs.mkdirSync(reportsDir, { recursive: true });
111
+ }
112
+
113
+ const reportPath = path.join(reportsDir, formatReportFilename(now));
114
+ fs.writeFileSync(reportPath, JSON.stringify(snapshot, null, 2) + "\n", "utf-8");
115
+
116
+ let summary = formatHumanSummary(snapshot, reportPath);
117
+ if (open) {
118
+ const htmlPath = writeHtmlBesideJson(reportPath, renderQuotaHtml(snapshot));
119
+ summary += ` HTML: ${htmlPath}\n`;
120
+ }
121
+
122
+ return { output: summary, exitCode: 0, reportPath };
123
+ }