pi-spine 2.10.0 → 2.12.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/bin/spine.mjs CHANGED
@@ -169,49 +169,62 @@ async function cmdIssue(args) {
169
169
 
170
170
  async function cmdMetrics(args) {
171
171
  const sub = args[0];
172
- if (sub !== "show") {
173
- die(`Unknown metrics subcommand: ${sub ?? "(none)"}\nRun ${c.cyan}spine metrics show${c.reset} for usage.`);
174
- }
172
+ if (sub === "show") {
173
+ const projectRoot = process.cwd();
174
+ const json = args.includes("--json");
175
+ let batchId = null;
176
+ let last = null;
177
+ for (let i = 1; i < args.length; i++) {
178
+ const arg = args[i];
179
+ if (arg === "--batch") batchId = args[++i] ?? null;
180
+ else if (arg === "--last") last = Number(args[++i]);
181
+ }
175
182
 
176
- const projectRoot = process.cwd();
177
- const json = args.includes("--json");
178
- let batchId = null;
179
- let last = null;
180
- for (let i = 1; i < args.length; i++) {
181
- const arg = args[i];
182
- if (arg === "--batch") batchId = args[++i] ?? null;
183
- else if (arg === "--last") last = Number(args[++i]);
184
- }
183
+ const configResult = loadSpineConfig(projectRoot);
184
+ const config = configResult.config ?? {};
185
+ const {
186
+ filterMetricsLines,
187
+ formatMetricsTable,
188
+ metricsFilePath,
189
+ readMetricsLines,
190
+ } = await import("../src/batch/metrics.mjs");
191
+ const { rollupMetrics, formatMetricsRollups } = await import("../src/batch/metrics-rollup.mjs");
192
+ const filePath = metricsFilePath(projectRoot, config);
193
+
194
+ if (!fs.existsSync(filePath)) {
195
+ if (json) {
196
+ process.stdout.write(`${JSON.stringify({ lines: [] }, null, 2)}\n`);
197
+ process.exit(1);
198
+ }
199
+ die(`Metrics file not found: ${path.relative(projectRoot, filePath)}\n`);
200
+ }
201
+
202
+ const lines = filterMetricsLines(readMetricsLines(filePath), {
203
+ batchId: batchId ?? undefined,
204
+ last: last ?? undefined,
205
+ });
206
+ const rollups = rollupMetrics(lines);
185
207
 
186
- const configResult = loadSpineConfig(projectRoot);
187
- const config = configResult.config ?? {};
188
- const {
189
- filterMetricsLines,
190
- formatMetricsTable,
191
- metricsFilePath,
192
- readMetricsLines,
193
- } = await import("../src/batch/metrics.mjs");
194
- const filePath = metricsFilePath(projectRoot, config);
195
-
196
- if (!fs.existsSync(filePath)) {
197
208
  if (json) {
198
- process.stdout.write(`${JSON.stringify({ lines: [] }, null, 2)}\n`);
199
- process.exit(1);
209
+ process.stdout.write(`${JSON.stringify({ lines, rollups }, null, 2)}\n`);
210
+ return;
200
211
  }
201
- die(`Metrics file not found: ${path.relative(projectRoot, filePath)}\n`);
202
- }
203
212
 
204
- const lines = filterMetricsLines(readMetricsLines(filePath), {
205
- batchId: batchId ?? undefined,
206
- last: last ?? undefined,
207
- });
213
+ process.stdout.write(formatMetricsTable(lines) + formatMetricsRollups(rollups));
214
+ return;
215
+ }
208
216
 
209
- if (json) {
210
- process.stdout.write(`${JSON.stringify({ lines }, null, 2)}\n`);
217
+ if (sub === "quota") {
218
+ const { runQuotaReport } = await import("../src/metrics/quota-cli.mjs");
219
+ const result = runQuotaReport({ projectRoot: process.cwd(), args: args.slice(1) });
220
+ process.stdout.write(result.output);
221
+ if (result.exitCode !== 0) process.exit(result.exitCode);
211
222
  return;
212
223
  }
213
224
 
214
- process.stdout.write(formatMetricsTable(lines));
225
+ die(
226
+ `Unknown metrics subcommand: ${sub ?? "(none)"}\nRun ${c.cyan}spine metrics show${c.reset} or ${c.cyan}spine metrics quota${c.reset} for usage.`,
227
+ );
215
228
  }
216
229
 
217
230
  async function cmdReport(args) {
@@ -288,7 +301,7 @@ ${c.bold}Commands:${c.reset}
288
301
  ${c.cyan}run${c.reset} Start batch or planner wave sequence (PRD §15.2, #54)
289
302
  ${c.cyan}handoff${c.reset} Write operator handoff note (FR-UXB-05)
290
303
  ${c.cyan}issue draft${c.reset} Build GitHub issue draft from project state (#60)
291
- ${c.cyan}metrics${c.reset} Show run metrics JSONL (FR-UXB-06)
304
+ ${c.cyan}metrics${c.reset} Show run metrics and quota snapshots (FR-UXB-06)
292
305
  ${c.cyan}review step${c.reset} Spawn reviewer for a task step (FR-REV)
293
306
  ${c.cyan}report progress${c.reset} Emit task.step_completed to batch journal (FR-WORK-09)
294
307
  ${c.cyan}gate${c.reset} Inspect or resolve integrate gate (FR-GATE)
@@ -347,7 +360,8 @@ ${c.bold}Examples:${c.reset}
347
360
  spine batch complete --detect-manual-merge # complete after manual git merge
348
361
  spine handoff [--batch ID] [--json] # operator handoff note
349
362
  spine issue draft [--type bug] [--json] # GitHub issue draft from diagnose state
350
- spine metrics show [--batch ID] [--last N] # read run-metrics.jsonl
363
+ spine metrics show [--batch ID] [--last N] # read run-metrics.jsonl (usage rollups when present)
364
+ spine metrics quota [--json] [--open] # write .spine/reports/quota-snapshot-*.json
351
365
  spine review step --step N [--type plan|code|final] # step or final review
352
366
  spine report progress --step N # journal step progress (worker shell-out)
353
367
  spine gate [approve|reject|status] # integrate gate FSM
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.10.0",
3
+ "version": "2.12.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -117,6 +117,8 @@ git push origin <baseBranch> # when remote sync desired
117
117
 
118
118
  Increment `WAVE` and repeat until `spine plan pending` shows no remaining waves.
119
119
 
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
+
120
122
  **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.
121
123
 
122
124
  Full reference: [references/outer-loop.md](references/outer-loop.md).
@@ -294,6 +294,8 @@ spine wait --until completed,failed,needs_integrate,needs_retry,aborted --timeou
294
294
 
295
295
  Optional pi watchdog: `LoopCreate` every 2m, `readOnly: true`, `maxFires: 50` — see pi-async-orchestration.
296
296
 
297
+ > **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.
298
+
297
299
  **Do not** start wave N+1 until wave N is integrated on `main`.
298
300
 
299
301
  Wave sizing: prefer ≤4 M-sized tasks per wave; serialize hot shared files.
@@ -232,10 +232,10 @@ export function buildSuggestedCommand(diagnosis, ctx = {}) {
232
232
  case "needs_merge":
233
233
  return "spine batch resume --force";
234
234
  case "needs_integrate":
235
+ if (ctx.integrateGateOpen) {
236
+ return "spine gate approve";
237
+ }
235
238
  if (ctx.postMergeLimbo && ctx.phase === "running") {
236
- if (ctx.integrateGateOpen) {
237
- return "spine gate approve";
238
- }
239
239
  if (ctx.stalePathSpine) {
240
240
  return "node bin/spine.mjs batch resume --attached";
241
241
  }
@@ -138,6 +138,12 @@ export function collectExtendedEvidenceBundle(ctx) {
138
138
  evidenceRefs.push("evidence/coverage-output.txt");
139
139
  }
140
140
 
141
+ if (testing.review) {
142
+ const result = runEvidenceCommand(projectRoot, testing.review);
143
+ writeTextAtomic(path.join(dir, "review-output.txt"), `${result.output}\n`);
144
+ evidenceRefs.push("evidence/review-output.txt");
145
+ }
146
+
141
147
  return { evidenceDir: dir, evidenceRefs };
142
148
  }
143
149
 
@@ -142,5 +142,7 @@ export function resolveTestingCommands(config, projectRoot) {
142
142
  (typeof spineTesting.testWithCoverage === "string" && spineTesting.testWithCoverage.trim()) ||
143
143
  (typeof taskplane.testWithCoverage === "string" && taskplane.testWithCoverage.trim()) ||
144
144
  "",
145
+ review:
146
+ (typeof spineTesting.review === "string" && spineTesting.review.trim()) || "",
145
147
  };
146
148
  }
@@ -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
  }
@@ -433,6 +433,21 @@ export function deriveDiagnosis(signals) {
433
433
  return withFailureContext("paused", null, signals);
434
434
  }
435
435
 
436
+ // Terminal-success land loop waiting for an integrate gate while the engine phase
437
+ // is still "running". Mark post-merge limbo so downstream suggestedCommand and
438
+ // macro-phase treat this as gate-ready rather than falling through to "running" (#221).
439
+ if (
440
+ RUNNING_PHASES.has(phase) &&
441
+ allTasksTerminalSuccess &&
442
+ git.orchBranchExists &&
443
+ !git.orchMergedToBase &&
444
+ !hasRunningTasks &&
445
+ !hasPendingTasks
446
+ ) {
447
+ signals.postMergeLimbo = true;
448
+ return withFailureContext("needs_integrate", null, signals);
449
+ }
450
+
436
451
  if (RUNNING_PHASES.has(phase) || hasRunningTasks || hasPendingTasks) {
437
452
  return withFailureContext("running", null, signals);
438
453
  }
@@ -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
+ }