pi-spine 2.28.0 → 2.28.1

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.
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Shared CLI argument guards (#368): `--help` must never run a mutating
3
+ * subcommand, and mutating subcommands reject flags they do not know.
4
+ */
5
+
6
+ const HELP_FLAGS = new Set(["--help", "-h"]);
7
+
8
+ /** Commands whose runners parse `--help` / `-h` themselves and print richer usage. */
9
+ const SELF_HELP_COMMANDS = new Set(["batch", "gate", "integrate", "issue", "rules", "settings"]);
10
+
11
+ const ANSI_PATTERN = /\x1b\[[0-9;]*m/g;
12
+
13
+ /**
14
+ * @param {string[]} args
15
+ */
16
+ export function hasHelpFlag(args) {
17
+ return args.some((arg) => HELP_FLAGS.has(arg));
18
+ }
19
+
20
+ /**
21
+ * True when the top-level dispatcher must print help instead of running `command`.
22
+ *
23
+ * @param {string} command
24
+ * @param {string[]} args
25
+ */
26
+ export function shouldInterceptSubcommandHelp(command, args) {
27
+ if (SELF_HELP_COMMANDS.has(command)) return false;
28
+ return hasHelpFlag(args);
29
+ }
30
+
31
+ /**
32
+ * Build per-command help from the top-level help text: the command's summary
33
+ * row plus every `spine <command> …` example line.
34
+ *
35
+ * @param {string} command
36
+ * @param {string} helpText Top-level `spine help` output (may contain ANSI codes).
37
+ */
38
+ export function formatSubcommandHelp(command, helpText) {
39
+ const plain = helpText.replace(ANSI_PATTERN, "").split("\n");
40
+ const prefix = `spine ${command}`;
41
+ const summaryPattern = new RegExp(`^\\s+${command.replace(/[-]/g, "\\-")}\\s{2,}(\\S.*)$`);
42
+ const summaryLine = plain.find((line) => summaryPattern.test(line));
43
+ const summary = summaryLine ? summaryLine.replace(summaryPattern, "$1").trim() : null;
44
+ const examples = plain.filter((line) => {
45
+ const trimmed = line.trim();
46
+ return trimmed === prefix || trimmed.startsWith(`${prefix} `);
47
+ });
48
+
49
+ const lines = ["", summary ? `${prefix} — ${summary}` : prefix];
50
+ if (examples.length > 0) {
51
+ lines.push("", "Usage:", ...examples.map((line) => ` ${line.trim()}`));
52
+ }
53
+ lines.push("", "Run `spine help` for all commands.", "");
54
+ return lines.join("\n");
55
+ }
56
+
57
+ /**
58
+ * Strict flag parser for mutating subcommands. Valued flags consume the next
59
+ * token, so their values never leak into positionals.
60
+ *
61
+ * @param {string[]} args
62
+ * @param {{ valued?: string[], boolean?: string[] }} spec
63
+ * @returns {{ help: boolean, positional: string[], values: Map<string, string>, flags: Set<string>, unknown: string[], missingValue: string[] }}
64
+ */
65
+ export function parseStrictArgs(args, spec) {
66
+ const valued = new Set(spec.valued ?? []);
67
+ const booleans = new Set(spec.boolean ?? []);
68
+ /** @type {string[]} */
69
+ const positional = [];
70
+ /** @type {Map<string, string>} */
71
+ const values = new Map();
72
+ /** @type {Set<string>} */
73
+ const flags = new Set();
74
+ /** @type {string[]} */
75
+ const unknown = [];
76
+ /** @type {string[]} */
77
+ const missingValue = [];
78
+ let help = false;
79
+
80
+ for (let index = 0; index < args.length; index += 1) {
81
+ const arg = args[index];
82
+ if (HELP_FLAGS.has(arg)) {
83
+ help = true;
84
+ } else if (valued.has(arg)) {
85
+ const value = args[index + 1];
86
+ if (value === undefined || value.startsWith("-")) {
87
+ missingValue.push(arg);
88
+ } else {
89
+ values.set(arg, value);
90
+ index += 1;
91
+ }
92
+ } else if (booleans.has(arg)) {
93
+ flags.add(arg);
94
+ } else if (arg.startsWith("-")) {
95
+ unknown.push(arg);
96
+ } else {
97
+ positional.push(arg);
98
+ }
99
+ }
100
+
101
+ return { help, positional, values, flags, unknown, missingValue };
102
+ }
103
+
104
+ /**
105
+ * Usage error for unknown or value-less flags, or null when the args are clean.
106
+ *
107
+ * @param {ReturnType<typeof parseStrictArgs>} parsed
108
+ */
109
+ export function strictArgsError(parsed) {
110
+ if (parsed.unknown.length > 0) {
111
+ return `Unknown option(s): ${parsed.unknown.join(", ")}`;
112
+ }
113
+ if (parsed.missingValue.length > 0) {
114
+ return `Missing value for: ${parsed.missingValue.join(", ")}`;
115
+ }
116
+ return null;
117
+ }
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import { isCliEntrypoint } from "./spine-cli/shared.mjs";
8
+ import { parseStrictArgs, strictArgsError } from "./spine-cli/cli-args.mjs";
8
9
  import { loadBatchStateFile } from "../src/batch/reconcile.mjs";
9
10
  import {
10
11
  approveIntegrateGate,
@@ -13,6 +14,22 @@ import {
13
14
  reopenIntegrateGateForCompletedBatch,
14
15
  } from "../src/batch/gate.mjs";
15
16
 
17
+ const GATE_USAGE = `
18
+ Usage: spine gate [approve|reject|status|reopen] [options]
19
+
20
+ approve Approve the pending integrate gate
21
+ reject Reject the pending integrate gate
22
+ status Show the integrate gate (default)
23
+ reopen Re-open the gate for a completed batch
24
+
25
+ Options:
26
+ --batch ID Target batch (default: active batch)
27
+ --reason TEXT Rejection reason (reject)
28
+ --synthesis TEXT Operator readback recorded on the gate
29
+ --json Machine-readable output
30
+ --help, -h Show this help without changing state
31
+ `;
32
+
16
33
  /**
17
34
  * @param {object} result
18
35
  * @param {boolean} json
@@ -75,29 +92,19 @@ function resolveActiveBatchId(projectRoot, batchId) {
75
92
  */
76
93
  export function runSpineGate(options) {
77
94
  const { projectRoot, args } = options;
78
- const flags = new Set(args.filter((a) => a.startsWith("--")));
79
- const positional = args.filter((a) => !a.startsWith("--"));
80
- const action = positional[0] ?? "status";
81
-
82
- let batchId = null;
83
- const batchIdx = args.indexOf("--batch");
84
- if (batchIdx >= 0 && args[batchIdx + 1]) {
85
- batchId = args[batchIdx + 1];
95
+ const parsed = parseStrictArgs(args, { valued: ["--batch", "--reason", "--synthesis"], boolean: ["--json"] });
96
+ const flags = parsed.flags;
97
+ if (parsed.help) {
98
+ return { exitCode: 0, output: GATE_USAGE, result: { ok: true, help: true } };
86
99
  }
87
-
88
- let reason = null;
89
- const reasonIdx = args.indexOf("--reason");
90
- if (reasonIdx >= 0 && args[reasonIdx + 1]) {
91
- reason = args[reasonIdx + 1];
92
- }
93
-
94
- let synthesis = null;
95
- const synthesisIdx = args.indexOf("--synthesis");
96
- if (synthesisIdx >= 0 && args[synthesisIdx + 1]) {
97
- synthesis = args[synthesisIdx + 1];
100
+ const usageError = strictArgsError(parsed);
101
+ if (usageError) {
102
+ return { exitCode: 2, output: `${usageError}\n${GATE_USAGE}`, result: { ok: false, error: usageError } };
98
103
  }
99
-
100
- batchId = resolveActiveBatchId(projectRoot, batchId);
104
+ const action = parsed.positional[0] ?? "status";
105
+ const reason = parsed.values.get("--reason") ?? null;
106
+ const synthesis = parsed.values.get("--synthesis") ?? null;
107
+ const batchId = resolveActiveBatchId(projectRoot, parsed.values.get("--batch") ?? null);
101
108
  if (!batchId) {
102
109
  const result = {
103
110
  ok: false,
@@ -1,4 +1,18 @@
1
1
  import { integrateOrchToBase } from "../src/batch/integrate.mjs";
2
+ import { parseStrictArgs, strictArgsError } from "./spine-cli/cli-args.mjs";
3
+
4
+ const INTEGRATE_USAGE = `
5
+ Usage: spine integrate [options]
6
+
7
+ Merge the batch orch branch into the base branch (requires an approved gate).
8
+
9
+ Options:
10
+ --batch ID Target batch (default: active batch)
11
+ --dry-run Show the merge plan without changing anything
12
+ --force-integrate Bypass the gate (requires SPINE_ALLOW_FORCE=1)
13
+ --json Machine-readable output
14
+ --help, -h Show this help without changing state
15
+ `;
2
16
 
3
17
  /**
4
18
  * @param {object} result
@@ -54,18 +68,25 @@ export function formatIntegrateHuman(result, json = false) {
54
68
  */
55
69
  export function runSpineIntegrate(options) {
56
70
  const { projectRoot, args } = options;
57
- const flags = new Set(args.filter((a) => a.startsWith("--")));
58
-
59
- let batchId = null;
60
- const batchIdx = args.indexOf("--batch");
61
- if (batchIdx >= 0 && args[batchIdx + 1]) {
62
- batchId = args[batchIdx + 1];
71
+ const parsed = parseStrictArgs(args, {
72
+ valued: ["--batch"],
73
+ boolean: ["--dry-run", "--force-integrate", "--json"],
74
+ });
75
+ const flags = parsed.flags;
76
+ if (parsed.help) {
77
+ return { exitCode: 0, output: INTEGRATE_USAGE, result: { ok: true, help: true } };
78
+ }
79
+ const usageError =
80
+ strictArgsError(parsed) ??
81
+ (parsed.positional.length > 0 ? `Unexpected argument(s): ${parsed.positional.join(" ")}` : null);
82
+ if (usageError) {
83
+ return { exitCode: 2, output: `${usageError}\n${INTEGRATE_USAGE}`, result: { ok: false, error: usageError } };
63
84
  }
64
85
 
65
86
  const result = integrateOrchToBase({
66
87
  projectRoot,
67
88
  dryRun: flags.has("--dry-run"),
68
- batchId,
89
+ batchId: parsed.values.get("--batch") ?? null,
69
90
  forceIntegrate: flags.has("--force-integrate"),
70
91
  });
71
92
 
@@ -11,6 +11,7 @@ import { spawnSync } from "node:child_process";
11
11
  import { buildIssueDraftBody } from "../src/cli/issue-draft.mjs";
12
12
  import { commandExists } from "../src/util/command-exists.mjs";
13
13
  import { c, die, isCliEntrypoint } from "./spine-cli/shared.mjs";
14
+ import { hasHelpFlag } from "./spine-cli/cli-args.mjs";
14
15
 
15
16
  const DEFAULT_OUT_PATH = ".spine/issue-draft.md";
16
17
 
@@ -178,7 +179,7 @@ export function runSpineIssue(options) {
178
179
  const sub = argv[0];
179
180
  if (sub !== "draft") {
180
181
  return {
181
- exitCode: 1,
182
+ exitCode: hasHelpFlag(argv) ? 0 : 1,
182
183
  output:
183
184
  `Usage: spine issue draft [--type bug|enhancement|question] [--title TITLE] [--json] [--out PATH] [--create]\n`,
184
185
  };
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { isCliEntrypoint } from "./spine-cli/shared.mjs";
12
+ import { hasHelpFlag } from "./spine-cli/cli-args.mjs";
12
13
  import { loadSpineConfig, loadSpineConfigFile } from "./spine-config.mjs";
13
14
  import { formatSettingsShow } from "../src/cli/settings-show.mjs";
14
15
  import {
@@ -134,6 +135,9 @@ export function runSpineSettingsSet({ projectRoot, args }) {
134
135
  * @param {string[]} options.args
135
136
  */
136
137
  export function runSpineSettings({ projectRoot, args }) {
138
+ if (hasHelpFlag(args)) {
139
+ return { exitCode: 0, output: settingsHelpText() };
140
+ }
137
141
  const sub = args[0];
138
142
 
139
143
  if (sub === "show" || sub === undefined) {
@@ -151,8 +155,8 @@ export function runSpineSettings({ projectRoot, args }) {
151
155
  };
152
156
  }
153
157
 
154
- function printSettingsHelp() {
155
- console.log(`
158
+ function settingsHelpText() {
159
+ return `
156
160
  Usage:
157
161
  spine settings show [path] [--json]
158
162
  spine settings set <path> <value> [--dry-run] [--json]
@@ -161,17 +165,11 @@ Show editable spine-config fields and their current values.
161
165
  With path, print a single registered setting value.
162
166
 
163
167
  Set updates one registered field after validation; use --dry-run to preview without writing.
164
- `);
168
+ `;
165
169
  }
166
170
 
167
171
  async function main() {
168
172
  const argv = process.argv.slice(2);
169
-
170
- if (argv.includes("--help") || argv.includes("-h")) {
171
- printSettingsHelp();
172
- return;
173
- }
174
-
175
173
  const result = runSpineSettings({ projectRoot: process.cwd(), args: argv });
176
174
  process.stdout.write(result.output);
177
175
  if (result.exitCode !== 0) {
@@ -405,12 +405,12 @@ async function runWorkerRunner() {
405
405
  if (hangMs > 0 || process.env.SPINE_WORKER_STUB_SAT020 === "1") {
406
406
  const effectiveHang =
407
407
  hangMs > 0 ? hangMs : Number(process.env.SPINE_WORKER_STUB_SAT020_HANG_MS || 25_000);
408
+ // Wall-clock deadline: summing slice lengths ignores per-spawn overhead, which
409
+ // stretched a 6s hang past 30s on loaded hosts and flipped stall-budget tests.
408
410
  const step = 100;
409
- let elapsed = 0;
410
- while (elapsed < effectiveHang) {
411
- const slice = Math.min(step, effectiveHang - elapsed);
412
- spawnSync("sleep", [String(slice / 1000)], { stdio: "ignore" });
413
- elapsed += slice;
411
+ const hangDeadline = Date.now() + effectiveHang;
412
+ for (let remaining = effectiveHang; remaining > 0; remaining = hangDeadline - Date.now()) {
413
+ spawnSync("sleep", [String(Math.min(step, remaining) / 1000)], { stdio: "ignore" });
414
414
  }
415
415
  console.error("stub worker hang finished without .DONE");
416
416
  process.exit(1);
package/bin/spine.mjs CHANGED
@@ -22,6 +22,7 @@ import { handleBatch, handleNext, handleRun } from "./spine-cli/batch.mjs";
22
22
  import { handleGate } from "./spine-cli/gate.mjs";
23
23
  import { handleIntegrate } from "./spine-cli/integrate.mjs";
24
24
  import { handlePlan } from "./spine-cli/plan.mjs";
25
+ import { formatSubcommandHelp, shouldInterceptSubcommandHelp } from "./spine-cli/cli-args.mjs";
25
26
  import {
26
27
  c,
27
28
  die,
@@ -278,8 +279,10 @@ function cmdVersion() {
278
279
  console.log();
279
280
  }
280
281
 
281
- function printHelp() {
282
- console.log(`
282
+ const printHelp = () => console.log(helpText());
283
+
284
+ function helpText() {
285
+ return `
283
286
  ${c.bold}pi-spine${c.reset} — orchestration spine for long-running pi development
284
287
 
285
288
  ${c.bold}Usage:${c.reset}
@@ -384,7 +387,7 @@ ${c.bold}Examples:${c.reset}
384
387
  spine scenarios show orphan-running-resume # show one scenario entry
385
388
  spine scenarios materialize orphan-running-resume --target . # write batch-state + journal
386
389
  spine version # show package and environment info
387
- `);
390
+ `;
388
391
  }
389
392
 
390
393
  if (isCliEntrypoint(import.meta.url)) {
@@ -394,6 +397,10 @@ if (isCliEntrypoint(import.meta.url)) {
394
397
  const [command = "help", ...args] = process.argv.slice(2);
395
398
 
396
399
  const runCli = async () => {
400
+ if (command !== "help" && shouldInterceptSubcommandHelp(command, args)) {
401
+ process.stdout.write(formatSubcommandHelp(command, helpText()));
402
+ return;
403
+ }
397
404
  switch (command) {
398
405
  case "init":
399
406
  cmdInit(args);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "2.28.0",
3
+ "version": "2.28.1",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -302,9 +302,8 @@ export function prepareContractVerifyEnvironment(worktreePath, parsedContract, c
302
302
  * @param {string} [config.batchId] Batch ID for journal events (optional).
303
303
  * @param {string} [config.taskId] Task ID for journal events (optional).
304
304
  * @param {string} [config.taskFolder] Task folder path for writing failure logs to .reviews/ (optional).
305
- * @param {{ testRetries?: number, testRetryDelayMs?: number }} [config.contract] Retry tuning for testCommand attempts.
305
+ * @param {{ testRetries?: number, testRetryDelayMs?: number, testTimeoutMs?: number }} [config.contract] Retry and per-attempt timeout tuning (#369).
306
306
  * @param {number} [config.contractTestMaxBuffer] stdout/stderr capture limit override.
307
- * @param {number} [config.contractTestTimeoutMs] Wall-clock timeout override for testCommand attempts.
308
307
  * @param {{ test?: string, testWithCoverage?: string }} [config.testing] Coverage command selection.
309
308
  * @returns {Promise<{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number }>}
310
309
  */
@@ -338,7 +337,7 @@ export async function verifyContract(worktreePath, parsedContract, config = {})
338
337
  for (let attempt = 1; attempt <= totalAttempts; attempt++) {
339
338
  lastResult = await runContractTestCommand(worktreePath, parsedContract.testCommand, {
340
339
  maxBuffer: config?.contractTestMaxBuffer,
341
- timeoutMs: config?.contractTestTimeoutMs,
340
+ timeoutMs: config?.contract?.testTimeoutMs,
342
341
  });
343
342
 
344
343
  if (lastResult.ok) {
@@ -14,6 +14,31 @@ export const PRIMARY_TASK_FAILURE_EXIT_REASONS = new Set([
14
14
 
15
15
  const LANE_COMMIT_EXIT_REASONS = new Set(["DirtyWorktree", "lane_commit_failed"]);
16
16
 
17
+ /** Suggested `contract.testTimeoutMs` after a timeout: double the 10-minute default. */
18
+ const CONTRACT_TIMEOUT_SUGGESTED_MS = 20 * 60 * 1000;
19
+
20
+ /**
21
+ * True when the latest contract verification for `taskId` failed because its
22
+ * testCommand timed out (#369), so diagnosis can name the timeout instead of
23
+ * pointing at PROMPT.md scope.
24
+ *
25
+ * @param {Array<{ type?: string, payload?: Record<string, any> }>} journalEvents
26
+ * @param {string|null|undefined} taskId
27
+ */
28
+ export function isContractTimeoutFailure(journalEvents, taskId) {
29
+ if (!taskId || !Array.isArray(journalEvents)) return false;
30
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
31
+ const event = journalEvents[index];
32
+ if (event?.type !== "contract.verified" && event?.type !== "contract.failed") continue;
33
+ if (event.payload?.taskId !== taskId) continue;
34
+ const checks = Array.isArray(event.payload?.checks) ? event.payload.checks : [];
35
+ return checks.some(
36
+ (check) => check?.field === "testCommand" && check.ok === false && /timed out after/.test(String(check.message ?? "")),
37
+ );
38
+ }
39
+ return false;
40
+ }
41
+
17
42
  /**
18
43
  * @param {string|null|undefined} exitReason
19
44
  */
@@ -27,6 +52,7 @@ export function isPrimaryTaskFailureExitReason(exitReason) {
27
52
  * @param {string|null} [ctx.exitReason]
28
53
  * @param {string|null} [ctx.failedTaskId]
29
54
  * @param {boolean} [ctx.mergeGitignoredFailure]
55
+ * @param {boolean} [ctx.contractTimedOut]
30
56
  */
31
57
  export function buildPrimaryFailureHeadline(batchLabel, ctx = {}) {
32
58
  if (LANE_COMMIT_EXIT_REASONS.has(ctx.exitReason ?? "")) {
@@ -49,6 +75,10 @@ export function buildPrimaryFailureHeadline(batchLabel, ctx = {}) {
49
75
  ? `${batchLabel} task ${ctx.failedTaskId} exhausted final review attempts — fix scope or implementation, then retry`
50
76
  : `${batchLabel} review attempts exhausted — fix scope or implementation, then retry`;
51
77
  }
78
+ if (ctx.exitReason === "contract_failed" && ctx.contractTimedOut) {
79
+ const subject = ctx.failedTaskId ? `task ${ctx.failedTaskId} contract testCommand` : "contract testCommand";
80
+ return `${batchLabel} ${subject} timed out — raise contract.testTimeoutMs or speed up the command, then retry`;
81
+ }
52
82
  if (ctx.exitReason === "contract_failed") {
53
83
  return ctx.failedTaskId
54
84
  ? `${batchLabel} task ${ctx.failedTaskId} failed contract verification — fix PROMPT.md scope, then retry`
@@ -95,6 +125,7 @@ export function buildDirtyWorktreeSuggestedCommand(ctx = {}) {
95
125
  * @param {string|null} [ctx.exitReason]
96
126
  * @param {string|null} [ctx.failedTaskId]
97
127
  * @param {string} [ctx.tasksRoot]
128
+ * @param {boolean} [ctx.contractTimedOut]
98
129
  */
99
130
  export function buildPrimaryFailureSuggestedCommand(ctx = {}) {
100
131
  if (LANE_COMMIT_EXIT_REASONS.has(ctx.exitReason ?? "")) {
@@ -110,6 +141,10 @@ export function buildPrimaryFailureSuggestedCommand(ctx = {}) {
110
141
  ? `spine batch retry ${ctx.failedTaskId}`
111
142
  : "spine status --diagnose";
112
143
  }
144
+ if (ctx.exitReason === "contract_failed" && ctx.contractTimedOut) {
145
+ const retry = ctx.failedTaskId ? `spine batch retry ${ctx.failedTaskId}` : "spine batch resume";
146
+ return `spine settings set contract.testTimeoutMs ${CONTRACT_TIMEOUT_SUGGESTED_MS} && ${retry}`;
147
+ }
113
148
  if (ctx.exitReason === "contract_failed") {
114
149
  const tasksRoot = ctx.tasksRoot ?? "spine-tasks";
115
150
  return ctx.failedTaskId
@@ -322,6 +322,8 @@ export async function runMatrixSubLane({
322
322
  const verify = await verifyContract(worktreePath, contract, {
323
323
  matrixRow: values,
324
324
  baseBranch,
325
+ contract: config?.contract,
326
+ contractTestMaxBuffer: config?.contractTestMaxBuffer,
325
327
  });
326
328
  if (verify.ok) {
327
329
  result = {
@@ -5,9 +5,9 @@
5
5
  */
6
6
 
7
7
  import path from "node:path";
8
- import { execFileSync } from "node:child_process";
9
8
  import { validateWorkerLaunchScriptPath } from "../config/worker-launch-script.mjs";
10
9
  import { EvidenceCommandError } from "./evidence-command-error.mjs";
10
+ import { EVIDENCE_DEFAULT_MAX_BYTES, runEvidenceArgvToFile } from "./evidence-exec.mjs";
11
11
  import {
12
12
  expandEvidencePathEntries,
13
13
  isAllowedEvidencePathEntry,
@@ -376,8 +376,8 @@ function collectEvidencePathPrefixEntries(command) {
376
376
  * @param {string} command
377
377
  * @param {number} [maxBytes]
378
378
  */
379
- export function runEvidenceCommand(projectRoot, command, maxBytes = 256 * 1024) {
380
- if (!command) return { ok: false, skipped: true, output: "" };
379
+ export function runEvidenceCommand(projectRoot, command, maxBytes = EVIDENCE_DEFAULT_MAX_BYTES) {
380
+ if (!command) return { ok: false, skipped: true, output: "", truncated: false };
381
381
 
382
382
  try {
383
383
  const chain = parseEvidenceCommandChain(command);
@@ -393,35 +393,32 @@ export function runEvidenceCommand(projectRoot, command, maxBytes = 256 * 1024)
393
393
  }
394
394
  /** @type {string[]} */
395
395
  const outputs = [];
396
+ let truncated = false;
396
397
  for (const argv of chain) {
397
398
  const execArgv = resolveEvidenceScriptsArgv(projectRoot, argv);
398
- const output = execFileSync(execArgv[0], execArgv.slice(1), {
399
- cwd: projectRoot,
400
- encoding: "utf-8",
401
- stdio: ["ignore", "pipe", "pipe"],
402
- timeout: 10 * 60 * 1000,
403
- maxBuffer: maxBytes,
404
- ...(env ? { env } : {}),
405
- });
406
- outputs.push(String(output ?? ""));
399
+ const step = runEvidenceArgvToFile({ projectRoot, argv: execArgv, env, maxBytes });
400
+ outputs.push(step.output);
401
+ truncated = truncated || step.truncated;
402
+ if (!step.ok) {
403
+ return {
404
+ ok: false,
405
+ skipped: false,
406
+ output: `${outputs.join("")}\n[exit] ${step.exitDetail}`.trim(),
407
+ truncated,
408
+ };
409
+ }
407
410
  }
408
- return { ok: true, skipped: false, output: outputs.join("") };
411
+ return { ok: true, skipped: false, output: outputs.join(""), truncated };
409
412
  } catch (err) {
410
413
  if (err instanceof EvidenceCommandError) {
411
414
  return {
412
415
  ok: false,
413
416
  skipped: false,
414
417
  output: `[rejected] ${err.message}`,
418
+ truncated: false,
415
419
  };
416
420
  }
417
-
418
- const stdout = err && typeof err === "object" && "stdout" in err ? String(err.stdout ?? "") : "";
419
- const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr ?? "") : "";
420
421
  const message = err instanceof Error ? err.message : String(err);
421
- return {
422
- ok: false,
423
- skipped: false,
424
- output: `${stdout}${stderr}\n[exit] ${message}`.trim(),
425
- };
422
+ return { ok: false, skipped: false, output: `[exit] ${message}`, truncated: false };
426
423
  }
427
424
  }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Run one validated evidence argv with stdout+stderr streamed to a temp file.
3
+ * Pipe buffers (execFileSync maxBuffer) kill the child with ENOBUFS on large
4
+ * test logs and lose the exit status; a file sink keeps the true exit status
5
+ * and lets us retain only the tail, which is where test failures summarize.
6
+ */
7
+
8
+ import fs from "node:fs";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import { spawnSync } from "node:child_process";
12
+
13
+ export const EVIDENCE_TIMEOUT_MS = 10 * 60 * 1000;
14
+ export const EVIDENCE_DEFAULT_MAX_BYTES = 256 * 1024;
15
+
16
+ /**
17
+ * @param {string} filePath
18
+ * @param {number} maxBytes
19
+ * @returns {{ text: string, totalBytes: number, truncated: boolean }}
20
+ */
21
+ function readFileTail(filePath, maxBytes) {
22
+ const totalBytes = fs.statSync(filePath).size;
23
+ if (totalBytes <= maxBytes) {
24
+ return { text: fs.readFileSync(filePath, "utf-8"), totalBytes, truncated: false };
25
+ }
26
+ const fd = fs.openSync(filePath, "r");
27
+ try {
28
+ const buffer = Buffer.alloc(maxBytes);
29
+ fs.readSync(fd, buffer, 0, maxBytes, totalBytes - maxBytes);
30
+ return { text: buffer.toString("utf-8"), totalBytes, truncated: true };
31
+ } finally {
32
+ fs.closeSync(fd);
33
+ }
34
+ }
35
+
36
+ /**
37
+ * @param {object} opts
38
+ * @param {string} opts.projectRoot
39
+ * @param {string[]} opts.argv
40
+ * @param {NodeJS.ProcessEnv | undefined} opts.env
41
+ * @param {number} opts.maxBytes Tail bytes retained from combined output.
42
+ * @param {number} [opts.timeoutMs]
43
+ * @returns {{ ok: boolean, output: string, truncated: boolean, exitDetail: string|null }}
44
+ */
45
+ export function runEvidenceArgvToFile({ projectRoot, argv, env, maxBytes, timeoutMs = EVIDENCE_TIMEOUT_MS }) {
46
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "spine-evidence-"));
47
+ const outPath = path.join(dir, "output.log");
48
+ const fd = fs.openSync(outPath, "w");
49
+ let fdOpen = true;
50
+ try {
51
+ const result = spawnSync(argv[0], argv.slice(1), {
52
+ cwd: projectRoot,
53
+ stdio: ["ignore", fd, fd],
54
+ timeout: timeoutMs,
55
+ ...(env ? { env } : {}),
56
+ });
57
+ fs.closeSync(fd);
58
+ fdOpen = false;
59
+ const tail = readFileTail(outPath, maxBytes);
60
+ const marker = tail.truncated
61
+ ? `[evidence truncated: kept last ${maxBytes} of ${tail.totalBytes} bytes]\n`
62
+ : "";
63
+ const output = `${marker}${tail.text}`;
64
+ if (result.error) {
65
+ return { ok: false, output, truncated: tail.truncated, exitDetail: result.error.message };
66
+ }
67
+ if (result.status === 0) {
68
+ return { ok: true, output, truncated: tail.truncated, exitDetail: null };
69
+ }
70
+ const exitDetail =
71
+ result.signal !== null
72
+ ? `Command terminated by ${result.signal}: ${argv.join(" ")}`
73
+ : `Command failed with exit code ${result.status}: ${argv.join(" ")}`;
74
+ return { ok: false, output, truncated: tail.truncated, exitDetail };
75
+ } finally {
76
+ if (fdOpen) fs.closeSync(fd);
77
+ fs.rmSync(dir, { recursive: true, force: true });
78
+ }
79
+ }
@@ -180,6 +180,9 @@ function extractResetAtRaw(message) {
180
180
  return match[1].trim().replace(/[.!]+$/, "");
181
181
  }
182
182
 
183
+ /** Kimi's flat-body `type` for the weekly (7-day) usage limit (#367). */
184
+ const KIMI_WEEKLY_QUOTA_TYPE = "exceeded_current_quota_error";
185
+
183
186
  /** Google retry hints below this many seconds mean a short (per-minute) window. */
184
187
  const GOOGLE_TRANSIENT_RETRY_SECONDS = 120;
185
188
 
@@ -229,6 +232,8 @@ function readGoogleQuotaDetails(details) {
229
232
  * Rules (#329):
230
233
  * - z.ai 429, top-level `code` "1308" (5-hour window) or "1310"
231
234
  * (weekly/monthly) → quota_exhausted.
235
+ * - Kimi 429, flat top-level `type` "exceeded_current_quota_error"
236
+ * (weekly 7-day limit) → quota_exhausted (#367).
232
237
  * - Kimi 403, `error.type` "permission_error", message mentions
233
238
  * "usage limit" (billing-cycle exhaustion) → quota_exhausted.
234
239
  * - Kimi 429, `error.type` "rate_limit_error", message mentions
@@ -257,6 +262,20 @@ function classifyPayload(httpStatus, payload) {
257
262
  };
258
263
  }
259
264
 
265
+ // Kimi weekly (7-day) limit: flat `{"message":"...","type":"exceeded_current_quota_error"}` (#367).
266
+ if (
267
+ httpStatus === 429 &&
268
+ payload.type === KIMI_WEEKLY_QUOTA_TYPE &&
269
+ typeof payload.message === "string"
270
+ ) {
271
+ return {
272
+ kind: "quota_exhausted",
273
+ providerCode: KIMI_WEEKLY_QUOTA_TYPE,
274
+ resetAtRaw: null,
275
+ message: truncateMessage(payload.message),
276
+ };
277
+ }
278
+
260
279
  // Kimi: nested error envelope `{"error":{"type":...,"message":...}}`.
261
280
  const error = payload.error && typeof payload.error === "object" ? payload.error : null;
262
281
  const errorMessage = typeof error?.message === "string" ? error.message : null;
@@ -299,6 +299,30 @@ export function listHumanOnlyPaths(projectRoot, snapshot, humanHead, orchBranch)
299
299
  }
300
300
  }
301
301
 
302
+ /**
303
+ * Paths touched on both sides only overlap when their contents differ: the same
304
+ * template sync landing on main and orch is not a divergence. One `git diff`
305
+ * call covers every candidate; a git failure keeps all candidates (fail closed).
306
+ *
307
+ * @param {string} projectRoot @param {string} humanRef @param {string} orchRef @param {string[]} candidatePaths
308
+ * @returns {string[]}
309
+ */
310
+ function keepPathsWithDifferentContent(projectRoot, humanRef, orchRef, candidatePaths) {
311
+ if (candidatePaths.length === 0 || !orchRef) return candidatePaths;
312
+ try {
313
+ const output = execFileSync("git", ["diff", "--name-only", humanRef, orchRef, "--", ...candidatePaths], {
314
+ cwd: projectRoot,
315
+ encoding: "utf-8",
316
+ stdio: ["ignore", "pipe", "pipe"],
317
+ timeout: 5000,
318
+ });
319
+ const differing = new Set(output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
320
+ return candidatePaths.filter((filePath) => differing.has(filePath));
321
+ } catch {
322
+ return candidatePaths;
323
+ }
324
+ }
325
+
302
326
  /** @param {string} projectRoot @param {string} ref @param {string} filePath */
303
327
  function pathExistsAtRef(projectRoot, ref, filePath) {
304
328
  try {
@@ -382,7 +406,10 @@ export function inspectHumanBaseSync(ctx) {
382
406
  resolvedOrch && gitRefExists(projectRoot, resolvedOrch)
383
407
  ? listGitChangedPaths(projectRoot, snapshot, resolvedOrch)
384
408
  : landPaths;
385
- const overlapPaths = humanPaths.filter((filePath) => orchPaths.includes(filePath));
409
+ const orchPathSet = new Set(orchPaths);
410
+ const touchedByBoth = humanPaths.filter((filePath) => orchPathSet.has(filePath));
411
+ const orchContentRef = resolvedOrch ?? baseTip;
412
+ const overlapPaths = keepPathsWithDifferentContent(projectRoot, humanHead, orchContentRef, touchedByBoth);
386
413
 
387
414
  if (overlapPaths.length > 0) {
388
415
  return {
@@ -1,6 +1,7 @@
1
1
  /** Diagnosis output context after reconcile signal enrichment (#201 / SP-645). */
2
2
 
3
3
  import { findPendingLaneLandTasks } from "./diagnosis-pending-lane.mjs";
4
+ import { isContractTimeoutFailure } from "./diagnosis-primary-failure.mjs";
4
5
 
5
6
  /**
6
7
  * @param {Record<string, any>} params
@@ -73,6 +74,7 @@ export function buildReconcileDiagnosisContext(params) {
73
74
  lastQuotaExhausted,
74
75
  driftTaskStatus,
75
76
  exitReason,
77
+ contractTimedOut: exitReason === "contract_failed" && isContractTimeoutFailure(journalEvents, failedTaskId),
76
78
  launchFailureKind: resolvedLaunchFailureKind,
77
79
  gitMerged: git.orchMergedToBase,
78
80
  pendingTaskCount,
@@ -58,14 +58,16 @@ export async function waitForSequenceBatchTerminal({
58
58
  stallMs = DEFAULT_SEQUENCE_STALL_MS,
59
59
  enginePid = null,
60
60
  reconcileFn = reconcileBatch,
61
+ now = Date.now,
62
+ sleepFn = sleep,
61
63
  }) {
62
- const startedAt = Date.now();
64
+ const startedAt = now();
63
65
  const deadline = startedAt + timeoutMs;
64
66
  const hardCap = startedAt + maxWaitMs;
65
67
  let lastProgressAt = startedAt;
66
68
  let useLightReconcile = false;
67
- while (Date.now() < deadline || isEngineStillRunning(enginePid, projectRoot)) {
68
- if (Date.now() >= hardCap) {
69
+ while (now() < deadline || isEngineStillRunning(enginePid, projectRoot)) {
70
+ if (now() >= hardCap) {
69
71
  const reconciliation = reconcileFn({ projectRoot });
70
72
  return {
71
73
  ok: false,
@@ -100,7 +102,7 @@ export async function waitForSequenceBatchTerminal({
100
102
  if (progressAt != null && progressAt > lastProgressAt) {
101
103
  lastProgressAt = progressAt;
102
104
  }
103
- if (Date.now() - lastProgressAt >= stallMs) {
105
+ if (now() - lastProgressAt >= stallMs) {
104
106
  return {
105
107
  ok: false,
106
108
  error: "engine_stalled",
@@ -110,7 +112,7 @@ export async function waitForSequenceBatchTerminal({
110
112
  suggestedCommand: "spine status --diagnose",
111
113
  };
112
114
  }
113
- await sleep(pollIntervalMs);
115
+ await sleepFn(pollIntervalMs);
114
116
  }
115
117
  const reconciliation = reconcileFn({ projectRoot });
116
118
  return {
@@ -10,6 +10,7 @@ import { withBatchStateLock } from "./batch-state-lock.mjs";
10
10
  import {
11
11
  clearBatchEnginePid,
12
12
  evaluateBatchStateWriteGuard,
13
+ readBatchEnginePid,
13
14
  TERMINAL_BATCH_PHASES,
14
15
  } from "./state-guards.mjs";
15
16
 
@@ -53,29 +54,54 @@ function archivedBatchStatePath(projectRoot, batchId) {
53
54
  return path.join(projectRoot, ".spine", "runtime", batchId, "archive", "batch-state.json");
54
55
  }
55
56
 
57
+ /**
58
+ * Rejection counts per `projectRoot|batchId|reason|ownerPid`. A non-engine writer
59
+ * can hit the guard dozens of times during one contract/merge (28 in v2.28 Batch B);
60
+ * one report per key, plus a count at each power of ten, keeps the signal without
61
+ * the noise.
62
+ *
63
+ * @type {Map<string, number>}
64
+ */
65
+ const rejectedWriteCounts = new Map();
66
+
67
+ /** @param {number} count */
68
+ function isRejectionReportMilestone(count) {
69
+ return count === 1 || (count >= 10 && Number.isInteger(Math.log10(count)));
70
+ }
71
+
56
72
  /**
57
73
  * Make a rejected batch-state write visible instead of silent (#293 / SP-790):
58
74
  * journal `batch.state_write_rejected` (when the incoming state carries a batchId)
59
75
  * and print one `[spine]` line to stderr so a swallowed late write is diagnosable.
76
+ * Repeats of the same rejection are counted and reported at 10, 100, 1000, …
60
77
  *
61
78
  * @param {string} projectRoot
62
79
  * @param {Record<string, any>} state
63
80
  * @param {string} reason
81
+ * @param {number|null} ownerPid Engine PID recorded on disk when the write was refused.
64
82
  */
65
- function reportRejectedBatchStateWrite(projectRoot, state, reason) {
83
+ function reportRejectedBatchStateWrite(projectRoot, state, reason, ownerPid) {
66
84
  const batchId = String(state?.batchId ?? "");
85
+ const key = `${projectRoot}|${batchId}|${reason}|${ownerPid ?? ""}`;
86
+ const count = (rejectedWriteCounts.get(key) ?? 0) + 1;
87
+ rejectedWriteCounts.set(key, count);
88
+ if (!isRejectionReportMilestone(count)) return;
89
+
67
90
  if (batchId) {
68
91
  try {
69
92
  appendJournalEvent(projectRoot, batchId, "batch.state_write_rejected", {
70
93
  reason,
71
94
  incomingPhase: String(state.phase ?? ""),
95
+ ownerPid,
96
+ rejectedCount: count,
72
97
  });
73
98
  } catch {
74
99
  /* journal failure must not turn a guarded no-op into a crash */
75
100
  }
76
101
  }
102
+ const repeat = count > 1 ? ` (${count} rejections so far)` : "";
77
103
  console.error(
78
- `[spine] refused batch-state write (${reason}) for batch ${batchId || "unknown"} — keeping on-disk state`,
104
+ `[spine] refused batch-state write (${reason}) for batch ${batchId || "unknown"} — keeping on-disk state${repeat}`,
79
105
  );
80
106
  }
81
107
 
@@ -101,8 +127,8 @@ function persistSpineBatchStateGuarded(projectRoot, state, options) {
101
127
  });
102
128
  if (!guard.allowed) {
103
129
  const reason = String(guard.reason ?? "unknown");
104
- reportRejectedBatchStateWrite(projectRoot, state, reason);
105
130
  const loaded = loadSpineBatchState(projectRoot);
131
+ reportRejectedBatchStateWrite(projectRoot, state, reason, loaded.raw ? readBatchEnginePid(loaded.raw) : null);
106
132
  return { ok: false, reason, state: loaded.raw ?? state };
107
133
  }
108
134
 
@@ -6,6 +6,10 @@
6
6
  /** @type {readonly string[]} */
7
7
  export const CONTRACT_MODES = Object.freeze(["required", "optional", "legacy"]);
8
8
 
9
+ /** Bounds for `contract.testTimeoutMs` (#369): 1 second to 4 hours. */
10
+ export const CONTRACT_TEST_TIMEOUT_MIN_MS = 1000;
11
+ export const CONTRACT_TEST_TIMEOUT_MAX_MS = 4 * 60 * 60 * 1000;
12
+
9
13
  /**
10
14
  * @param {unknown} config
11
15
  * @returns {{ code: string, message: string, suggestedCommand: string } | null}
@@ -44,6 +48,22 @@ export function validateContractConfig(config) {
44
48
  }
45
49
  }
46
50
 
51
+ if (contract.testTimeoutMs != null) {
52
+ const timeoutMs = contract.testTimeoutMs;
53
+ const isValid =
54
+ typeof timeoutMs === "number" &&
55
+ Number.isInteger(timeoutMs) &&
56
+ timeoutMs >= CONTRACT_TEST_TIMEOUT_MIN_MS &&
57
+ timeoutMs <= CONTRACT_TEST_TIMEOUT_MAX_MS;
58
+ if (!isValid) {
59
+ return {
60
+ code: "CONFIG_CONTRACT_TEST_TIMEOUT_INVALID",
61
+ message: `contract.testTimeoutMs must be an integer between ${CONTRACT_TEST_TIMEOUT_MIN_MS} and ${CONTRACT_TEST_TIMEOUT_MAX_MS} when set`,
62
+ suggestedCommand: "spine settings set contract.testTimeoutMs 1200000",
63
+ };
64
+ }
65
+ }
66
+
47
67
  if (contract.legacyTaskIdPrefixes != null) {
48
68
  if (!Array.isArray(contract.legacyTaskIdPrefixes)) {
49
69
  return {
@@ -8,6 +8,8 @@
8
8
  * Only `lanes.maxParallel` is editable via `spine settings set`; tasks root is env/file only.
9
9
  */
10
10
 
11
+ import { CONTRACT_TEST_TIMEOUT_MAX_MS, CONTRACT_TEST_TIMEOUT_MIN_MS } from "./contract.mjs";
12
+
11
13
  /** @typedef {"boolean" | "number" | "string" | "enum"} SettingFieldType */
12
14
 
13
15
  /**
@@ -62,6 +64,13 @@ export const SETTINGS_FIELDS = Object.freeze([
62
64
  min: 1,
63
65
  max: 10,
64
66
  },
67
+ {
68
+ path: "contract.testTimeoutMs",
69
+ label: "Contract testCommand timeout per attempt (ms; default 600000)",
70
+ type: "number",
71
+ min: CONTRACT_TEST_TIMEOUT_MIN_MS,
72
+ max: CONTRACT_TEST_TIMEOUT_MAX_MS,
73
+ },
65
74
  {
66
75
  path: "agents.worker.model",
67
76
  label: "Worker model",
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Agent prompt drift check: `.spine/agents/*.md` vs the packaged
3
+ * `templates/agents/*.md` the CLI ships.
4
+ *
5
+ * Workers, reviewers and the supervisor read the project copy, not the template.
6
+ * FR-WORK-08 lets a project append overrides after the base template, so a copy
7
+ * is current when it starts with the template text; anything else means template
8
+ * fixes (for example the final PASS/REVISE/REPLAN verdict shape) never reach the
9
+ * agents. Advisory only: the operator decides how to merge local edits.
10
+ */
11
+
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+
15
+ import { AGENT_STUB_FILES, TEMPLATE_PATHS } from "../config/spine-init-constants.mjs";
16
+
17
+ /** @param {string} text */
18
+ function normalizeAgentText(text) {
19
+ return text.replace(/\r\n/g, "\n").trimEnd();
20
+ }
21
+
22
+ /**
23
+ * @param {object} params
24
+ * @param {string} params.projectRoot
25
+ * @param {Array<{ templateKey: string, destName: string }>} [params.agentFiles]
26
+ * @param {Record<string, string>} [params.templatePaths] templateKey → absolute template path
27
+ * @returns {{ label: string, ok: boolean, warning?: boolean, detail: string, suggestedCommand?: string }}
28
+ */
29
+ export function buildAgentTemplateDriftDoctorCheck({
30
+ projectRoot,
31
+ agentFiles = AGENT_STUB_FILES,
32
+ templatePaths = TEMPLATE_PATHS.agents,
33
+ }) {
34
+ /** @type {string[]} */
35
+ const drifted = [];
36
+ let compared = 0;
37
+
38
+ for (const { templateKey, destName } of agentFiles) {
39
+ const projectPath = path.join(projectRoot, ".spine", "agents", destName);
40
+ const templatePath = templatePaths[templateKey];
41
+ if (!templatePath || !fs.existsSync(projectPath) || !fs.existsSync(templatePath)) continue;
42
+ compared += 1;
43
+ const projectText = normalizeAgentText(fs.readFileSync(projectPath, "utf-8"));
44
+ const templateText = normalizeAgentText(fs.readFileSync(templatePath, "utf-8"));
45
+ if (!projectText.startsWith(templateText)) {
46
+ drifted.push(`.spine/agents/${destName}`);
47
+ }
48
+ }
49
+
50
+ if (drifted.length === 0) {
51
+ return {
52
+ label: "agent prompts match templates",
53
+ ok: true,
54
+ detail: compared === 0 ? "no agent files to compare" : `${compared} agent file(s) start with the packaged template`,
55
+ };
56
+ }
57
+
58
+ return {
59
+ label: "agent prompts match templates",
60
+ ok: true,
61
+ warning: true,
62
+ detail: `${drifted.join(", ")} no longer start with the packaged template; template fixes do not reach these agents`,
63
+ suggestedCommand: `diff templates/agents/<file> .spine/agents/<file> — rebase local edits after the template (or spine init --force to reset)`,
64
+ };
65
+ }
@@ -23,6 +23,8 @@ import {
23
23
  buildStallConfigDoctorCheck,
24
24
  } from "./stall-config.mjs";
25
25
  import { buildRulesManifestDoctorCheck } from "./rules-manifest.mjs";
26
+ import { buildAgentTemplateDriftDoctorCheck } from "./agent-template-drift.mjs";
27
+ import { buildStetCapacityDoctorCheck } from "./stet-capacity.mjs";
26
28
  import { buildWorktreeHealthDoctorCheck } from "./worktree-health.mjs";
27
29
  import { buildGitignoredPubspecAssetsDoctorCheck } from "../config/worktree-setup-hook.mjs";
28
30
  import { buildStaleWorktreesDoctorCheck } from "./stale-worktrees.mjs";
@@ -536,6 +538,8 @@ export function runDoctorChecks(projectRoot = process.cwd()) {
536
538
  suggestedCommand: "spine init",
537
539
  });
538
540
  }
541
+ checks.push(buildAgentTemplateDriftDoctorCheck({ projectRoot }));
542
+ checks.push(buildStetCapacityDoctorCheck());
539
543
 
540
544
  const tasksRootPath = resolveTasksRoot(projectRoot, configResult);
541
545
  const metricsPath = path.join(
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Advisory host-capacity preflight for stet-backed contract review. Local LLM
3
+ * review competes with batch workers for RAM; the v2.28 release stalled when a
4
+ * second stet session and a 16 GB model ran with swap nearly exhausted.
5
+ */
6
+
7
+ import { execFileSync } from "node:child_process";
8
+ import fs from "node:fs";
9
+ import os from "node:os";
10
+
11
+ const PROBE_TIMEOUT_MS = 3000;
12
+ const BYTES_PER_MIB = 1024 * 1024;
13
+ export const SWAP_FREE_WARN_BYTES = 2 * 1024 * BYTES_PER_MIB;
14
+ /** Loaded local-model bytes above this share of physical RAM leave too little for lanes. */
15
+ export const LOADED_MODEL_RAM_SHARE_WARN = 0.5;
16
+
17
+ const STET_SESSION_PATTERN = "stet (start|run|rerun)( |$)";
18
+ const SPINE_BATCH_PATTERN = "spine(\\.mjs)? batch (start|resume)";
19
+
20
+ /**
21
+ * @param {string} file
22
+ * @param {string[]} args
23
+ * @param {number|null} [emptyExitStatus] Exit status meaning "ran fine, no results".
24
+ * @returns {string|null} stdout, or null when the probe is unavailable.
25
+ */
26
+ function tryExec(file, args, emptyExitStatus = null) {
27
+ try {
28
+ return execFileSync(file, args, {
29
+ encoding: "utf-8",
30
+ stdio: ["ignore", "pipe", "ignore"],
31
+ timeout: PROBE_TIMEOUT_MS,
32
+ });
33
+ } catch (err) {
34
+ const status = err && typeof err === "object" && "status" in err ? err.status : null;
35
+ return emptyExitStatus !== null && status === emptyExitStatus ? "" : null;
36
+ }
37
+ }
38
+
39
+ /** @param {string} pattern @returns {number[]|null} */
40
+ function pgrepPids(pattern) {
41
+ const PGREP_NO_MATCH_STATUS = 1;
42
+ const out = tryExec("pgrep", ["-f", pattern], PGREP_NO_MATCH_STATUS);
43
+ if (out === null) return null;
44
+ return out
45
+ .split("\n")
46
+ .map((line) => Number.parseInt(line, 10))
47
+ .filter((pid) => Number.isInteger(pid) && pid !== process.pid);
48
+ }
49
+
50
+ /**
51
+ * @param {string} text `sysctl vm.swapusage` output
52
+ * @returns {number|null}
53
+ */
54
+ export function parseDarwinSwapFreeBytes(text) {
55
+ const match = /free\s*=\s*([\d.]+)M/.exec(text);
56
+ return match ? Math.round(Number.parseFloat(match[1]) * BYTES_PER_MIB) : null;
57
+ }
58
+
59
+ /**
60
+ * @param {string} text /proc/meminfo contents
61
+ * @returns {number|null} null when the host has no swap configured.
62
+ */
63
+ export function parseLinuxSwapFreeBytes(text) {
64
+ const total = /^SwapTotal:\s+(\d+) kB/m.exec(text);
65
+ const free = /^SwapFree:\s+(\d+) kB/m.exec(text);
66
+ if (!total || !free || Number(total[1]) === 0) return null;
67
+ return Number(free[1]) * 1024;
68
+ }
69
+
70
+ /** @returns {number|null} */
71
+ function probeSwapFreeBytes() {
72
+ if (process.platform === "darwin") {
73
+ const out = tryExec("sysctl", ["vm.swapusage"]);
74
+ return out === null ? null : parseDarwinSwapFreeBytes(out);
75
+ }
76
+ if (process.platform === "linux") {
77
+ try {
78
+ return parseLinuxSwapFreeBytes(fs.readFileSync("/proc/meminfo", "utf-8"));
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+ return null;
84
+ }
85
+
86
+ /**
87
+ * @param {string} text `lms ps --json` output
88
+ * @returns {{ id: string, sizeBytes: number }[]|null}
89
+ */
90
+ export function parseLmsLoadedModels(text) {
91
+ try {
92
+ const parsed = JSON.parse(text);
93
+ if (!Array.isArray(parsed)) return null;
94
+ return parsed
95
+ .filter((m) => m && typeof m.sizeBytes === "number")
96
+ .map((m) => ({ id: String(m.identifier ?? m.modelKey ?? "unknown"), sizeBytes: m.sizeBytes }));
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+
102
+ /** @returns {{ id: string, sizeBytes: number }[]|null} */
103
+ function probeLoadedModels() {
104
+ const out = tryExec("lms", ["ps", "--json"]);
105
+ return out === null ? null : parseLmsLoadedModels(out);
106
+ }
107
+
108
+ export const DEFAULT_STET_CAPACITY_PROBES = {
109
+ stetOnPath: () => tryExec("stet", ["--version"]) !== null,
110
+ stetSessionPids: () => pgrepPids(STET_SESSION_PATTERN),
111
+ spineBatchPids: () => pgrepPids(SPINE_BATCH_PATTERN),
112
+ swapFreeBytes: probeSwapFreeBytes,
113
+ loadedModels: probeLoadedModels,
114
+ totalMemBytes: () => os.totalmem(),
115
+ };
116
+
117
+ /** @param {number} bytes */
118
+ const gib = (bytes) => `${(bytes / (1024 * BYTES_PER_MIB)).toFixed(1)} GiB`;
119
+
120
+ /**
121
+ * @param {{ probes?: Partial<typeof DEFAULT_STET_CAPACITY_PROBES> }} [opts]
122
+ */
123
+ export function buildStetCapacityDoctorCheck(opts = {}) {
124
+ const probes = { ...DEFAULT_STET_CAPACITY_PROBES, ...opts.probes };
125
+ const label = "stet review capacity";
126
+ if (!probes.stetOnPath()) {
127
+ return { label, ok: true, detail: "stet not on PATH (skipped)" };
128
+ }
129
+
130
+ /** @type {string[]} */
131
+ const warnings = [];
132
+ /** @type {string[]} */
133
+ const unknown = [];
134
+
135
+ const stetPids = probes.stetSessionPids();
136
+ if (stetPids === null) unknown.push("stet processes");
137
+ else if (stetPids.length > 0) warnings.push(`stet review already running (pid ${stetPids.join(", ")})`);
138
+
139
+ const batchPids = probes.spineBatchPids();
140
+ if (batchPids === null) unknown.push("spine batches");
141
+ else if (batchPids.length > 0) warnings.push(`other spine batch running (pid ${batchPids.join(", ")})`);
142
+
143
+ const swapFree = probes.swapFreeBytes();
144
+ if (swapFree !== null && swapFree < SWAP_FREE_WARN_BYTES) {
145
+ warnings.push(`swap nearly exhausted (${gib(swapFree)} free)`);
146
+ }
147
+
148
+ const models = probes.loadedModels();
149
+ if (models === null) {
150
+ unknown.push("LM Studio models");
151
+ } else {
152
+ const loadedBytes = models.reduce((sum, m) => sum + m.sizeBytes, 0);
153
+ const totalMem = probes.totalMemBytes();
154
+ if (loadedBytes > totalMem * LOADED_MODEL_RAM_SHARE_WARN) {
155
+ const ids = models.map((m) => m.id).join(", ");
156
+ warnings.push(`LM Studio models use ${gib(loadedBytes)} of ${gib(totalMem)} RAM (${ids})`);
157
+ }
158
+ }
159
+
160
+ const unknownNote = unknown.length > 0 ? `; not probed: ${unknown.join(", ")}` : "";
161
+ if (warnings.length === 0) {
162
+ return { label, ok: true, detail: `host has headroom for stet review${unknownNote}` };
163
+ }
164
+ return {
165
+ label,
166
+ ok: true,
167
+ warning: true,
168
+ detail: `${warnings.join("; ")}${unknownNote}`,
169
+ suggestedCommand: "lms unload --all # or wait for the other stet/spine run to finish",
170
+ };
171
+ }