pi-spine 2.27.1 → 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.
Files changed (64) hide show
  1. package/bin/spine-batch.mjs +46 -4
  2. package/bin/spine-cli/cli-args.mjs +117 -0
  3. package/bin/spine-gate.mjs +28 -21
  4. package/bin/spine-integrate.mjs +28 -7
  5. package/bin/spine-issue.mjs +2 -1
  6. package/bin/spine-settings.mjs +7 -9
  7. package/bin/spine-tasks.mjs +1 -0
  8. package/bin/spine-worker-runner.mjs +21 -8
  9. package/bin/spine.mjs +10 -3
  10. package/package.json +1 -1
  11. package/skills/create-spine-tasks/references/prompt-template.md +5 -0
  12. package/skills/spine-release-operator/SKILL.md +14 -2
  13. package/src/batch/contract-exec.mjs +2 -3
  14. package/src/batch/contract-task-start.mjs +23 -1
  15. package/src/batch/diagnosis-handoff-packet.mjs +18 -0
  16. package/src/batch/diagnosis-primary-failure.mjs +35 -0
  17. package/src/batch/engine-lanes/matrix-run.mjs +2 -0
  18. package/src/batch/engine-lanes/quota-fallback-run.mjs +11 -0
  19. package/src/batch/engine-lanes/quota-fallback-state.mjs +155 -8
  20. package/src/batch/engine-lanes/review-code.mjs +20 -0
  21. package/src/batch/engine-lanes/review-final.mjs +10 -2
  22. package/src/batch/engine-lanes/review-poll.mjs +33 -0
  23. package/src/batch/engine-lanes/task-agent-profile.mjs +324 -0
  24. package/src/batch/engine-lanes.mjs +18 -17
  25. package/src/batch/evidence-command.mjs +18 -21
  26. package/src/batch/evidence-exec.mjs +79 -0
  27. package/src/batch/journal.mjs +5 -3
  28. package/src/batch/metrics-rollup.mjs +98 -4
  29. package/src/batch/metrics.mjs +134 -9
  30. package/src/batch/provider-quota.mjs +174 -6
  31. package/src/batch/quota-fallback.mjs +87 -6
  32. package/src/batch/reconcile-classify.mjs +28 -1
  33. package/src/batch/reconcile-diagnosis-context.mjs +2 -0
  34. package/src/batch/resume-lane-reviews.mjs +11 -10
  35. package/src/batch/retry-profile.mjs +77 -0
  36. package/src/batch/retry.mjs +32 -1
  37. package/src/batch/review-step-run.mjs +4 -0
  38. package/src/batch/review-step.mjs +1 -0
  39. package/src/batch/sequence-wait.mjs +7 -5
  40. package/src/batch/state-io.mjs +29 -3
  41. package/src/batch/worker-heartbeat.mjs +10 -2
  42. package/src/batch/worker-host.mjs +1 -1
  43. package/src/batch/worker-prompt.mjs +4 -5
  44. package/src/cli/deps.mjs +3 -2
  45. package/src/config/agent-model-resolve.mjs +144 -8
  46. package/src/config/contract.mjs +20 -0
  47. package/src/config/model-family.mjs +60 -0
  48. package/src/config/preflight/discovery.mjs +1 -0
  49. package/src/config/settings-fields.mjs +15 -0
  50. package/src/config/spine-config-schema.mjs +49 -0
  51. package/src/doctor/agent-model-inherit.mjs +78 -1
  52. package/src/doctor/agent-template-drift.mjs +65 -0
  53. package/src/doctor/run-doctor-checks.mjs +8 -1
  54. package/src/doctor/stet-capacity.mjs +171 -0
  55. package/src/metrics/quota-cli.mjs +16 -0
  56. package/src/metrics/quota-probes.mjs +228 -31
  57. package/src/metrics/quota-snapshot.mjs +21 -2
  58. package/src/planner/graph.mjs +7 -5
  59. package/src/planner/pending.mjs +2 -2
  60. package/src/planner/scope.mjs +3 -3
  61. package/src/tasks/packet/parse-prompt.mjs +47 -0
  62. package/src/tasks/packet/validate-prompt.mjs +156 -1
  63. package/templates/agents/reviewer.md +3 -1
  64. package/templates/agents/worker.md +15 -19
@@ -13,6 +13,7 @@ import { forceMergeWave, startBatch } from "../src/batch/engine.mjs";
13
13
  import { parseBatchStartWaveFilter } from "../src/planner/wave-scope.mjs";
14
14
  import { pauseBatch } from "../src/batch/pause.mjs";
15
15
  import { resumeBatch } from "../src/batch/resume.mjs";
16
+ import { clearQuotaFallbackByOperator } from "../src/batch/engine-lanes/quota-fallback-state.mjs";
16
17
  import { retryTask, skipTask } from "../src/batch/retry.mjs";
17
18
  import { retryTaskRow, skipTaskRow, parseMatrixRowRef } from "../src/batch/retry-row.mjs";
18
19
  import { reconcileBatch } from "../src/batch/reconcile.mjs";
@@ -32,6 +33,7 @@ const BATCH_FLAG_VALUE_TAKERS = new Set([
32
33
  "--batch",
33
34
  "--reason",
34
35
  "--lane",
36
+ "--profile",
35
37
  ]);
36
38
 
37
39
  /**
@@ -39,8 +41,11 @@ const BATCH_FLAG_VALUE_TAKERS = new Set([
39
41
  */
40
42
  export function printBatchHelp() {
41
43
  return (
42
- "Usage: spine batch start <scope>|pause|resume|retry <taskId|[rowId]>|skip <taskId|[rowId]>|force-merge [--wave N]|salvage|abort|dismiss|complete [--batch ID] [--lane N] [--integrate] [--yes] [--reason TEXT] [--hard] [--force] [--force-superseded] [--attached] [--dry-run] [--wave N] [--through-wave N] [--skip-preflight] [--detect-manual-merge] [--json]\n" +
44
+ "Usage: spine batch start <scope>|pause|resume|retry <taskId|[rowId]> [--profile NAME] [--no-escalate]|skip <taskId|[rowId]>|force-merge [--wave N]|salvage|quota-fallback clear|abort|dismiss|complete [--batch ID] [--lane N] [--integrate] [--yes] [--reason TEXT] [--hard] [--force] [--force-superseded] [--attached] [--dry-run] [--wave N] [--through-wave N] [--skip-preflight] [--detect-manual-merge] [--json]\n" +
43
45
  " Row identity: retry/skip 'SP-X[rowId]' targets one matrix row; plain SP-X targets the whole task.\n" +
46
+ " retry --profile NAME Retry on another agents.profiles entry (content/contract failures only; quota/infra failures use agents.quotaFallbackProfile)\n" +
47
+ " retry --no-escalate Skip agents.escalatePolicy for this retry\n" +
48
+ " quota-fallback clear Delete the active quota fallback hop so workers return to the primary profile (paused/failed batches only)\n" +
44
49
  " abort --dry-run Preview abort (reason/archive target); does not archive, journal, or clear live batch\n"
45
50
  );
46
51
  }
@@ -67,6 +72,7 @@ export function isBatchHelpRequest(args) {
67
72
  "skip",
68
73
  "force-merge",
69
74
  "salvage",
75
+ "quota-fallback",
70
76
  ].includes(token),
71
77
  );
72
78
  if (subcommand && args.includes("help")) {
@@ -169,6 +175,12 @@ export function parseBatchArgs(args) {
169
175
  laneNumber = Number(args[laneIdx + 1]);
170
176
  }
171
177
 
178
+ let profile = null;
179
+ const profileIdx = args.indexOf("--profile");
180
+ if (profileIdx >= 0 && args[profileIdx + 1] && !args[profileIdx + 1].startsWith("--")) {
181
+ profile = args[profileIdx + 1];
182
+ }
183
+
172
184
  const subcommand =
173
185
  args.find(
174
186
  (t) =>
@@ -181,7 +193,8 @@ export function parseBatchArgs(args) {
181
193
  t === "retry" ||
182
194
  t === "skip" ||
183
195
  t === "force-merge" ||
184
- t === "salvage",
196
+ t === "salvage" ||
197
+ t === "quota-fallback",
185
198
  ) ?? null;
186
199
 
187
200
  let waveFilter = null;
@@ -218,6 +231,9 @@ export function parseBatchArgs(args) {
218
231
  forceSuperseded,
219
232
  integrate,
220
233
  yes,
234
+ profile,
235
+ profileFlag: flags.has("--profile"),
236
+ noEscalate: flags.has("--no-escalate"),
221
237
  batchId,
222
238
  reason,
223
239
  waveIndex,
@@ -351,13 +367,27 @@ export async function runSpineBatch(options) {
351
367
  if (!parsed.taskId) {
352
368
  return {
353
369
  exitCode: 1,
354
- output: "Usage: spine batch retry <taskId> | <taskId>[rowId] [--json]\n",
370
+ output: "Usage: spine batch retry <taskId> [--profile <name>] [--no-escalate] | <taskId>[rowId] [--json]\n",
355
371
  };
356
372
  }
373
+ if (parsed.profileFlag && !parsed.profile) {
374
+ return { exitCode: 1, output: "Usage: spine batch retry <taskId> --profile <name>\n" };
375
+ }
357
376
  const rowRef = parseMatrixRowRef(parsed.taskId);
377
+ if (rowRef && parsed.profileFlag) {
378
+ return {
379
+ exitCode: 1,
380
+ output: "--profile applies to whole-task retry; retry the task (SP-X) instead of a matrix row.\n",
381
+ };
382
+ }
358
383
  const result = rowRef
359
384
  ? retryTaskRow({ projectRoot, taskId: rowRef.taskId, rowId: rowRef.rowId })
360
- : retryTask({ projectRoot, taskId: parsed.taskId });
385
+ : retryTask({
386
+ projectRoot,
387
+ taskId: parsed.taskId,
388
+ profile: parsed.profile,
389
+ noEscalate: parsed.noEscalate,
390
+ });
361
391
  if (parsed.json) {
362
392
  return {
363
393
  exitCode: result.exitCode ?? (result.ok ? 0 : 1),
@@ -383,6 +413,18 @@ export async function runSpineBatch(options) {
383
413
  };
384
414
  }
385
415
 
416
+ if (parsed.subcommand === "quota-fallback") {
417
+ if (parsed.scope !== "clear") {
418
+ return { exitCode: 1, output: "Usage: spine batch quota-fallback clear [--json]\n" };
419
+ }
420
+ const result = clearQuotaFallbackByOperator({ projectRoot });
421
+ return {
422
+ exitCode: result.exitCode ?? (result.ok ? 0 : 1),
423
+ output: parsed.json ? `${JSON.stringify(result, null, 2)}\n` : result.output,
424
+ result,
425
+ };
426
+ }
427
+
386
428
  if (parsed.subcommand === "skip") {
387
429
  if (!parsed.taskId) {
388
430
  return {
@@ -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) {
@@ -217,6 +217,7 @@ export async function runSpineTasksValidate({
217
217
 
218
218
  const packet = loadTaskPacket(discoveredTask.folderPath, {
219
219
  contract: config.contract,
220
+ agents: config.agents,
220
221
  });
221
222
  const failure = collectPromptValidationFailure(packet, taskId);
222
223
  /** @type {string[]} */
@@ -42,7 +42,7 @@ import {
42
42
  isPiExtensionConflictOutput,
43
43
  shouldWorkerUsePiNoExtensions,
44
44
  } from "../src/doctor/pi-extension-conflict.mjs";
45
- import { parseContract, parsePrompt } from "../src/tasks/packet/parse-prompt.mjs";
45
+ import { PROMPT_THINKING_LEVELS, parseContract, parsePrompt } from "../src/tasks/packet/parse-prompt.mjs";
46
46
 
47
47
  /**
48
48
  * Actionable hint when pi worker spawn fails on duplicate extension tool registration.
@@ -66,13 +66,26 @@ function buildReviewJournal() {
66
66
 
67
67
  /**
68
68
  * Append worker model/thinking flags from spine-config (mirrors reviewer spawn in review.mjs).
69
+ * `SPINE_WORKER_THINKING_OVERRIDE` (per-task `**Thinking:**`, SP-835 / #340) wins over
70
+ * `agents.worker.thinking`; invalid values warn on stderr and are ignored.
69
71
  *
70
72
  * @param {string[]} piArgs
71
73
  * @param {object} [config]
74
+ * @param {Record<string, string|undefined>} [env] Defaults to `process.env`.
72
75
  */
73
- export function appendWorkerAgentModelArgs(piArgs, config = {}) {
76
+ export function appendWorkerAgentModelArgs(piArgs, config = {}, env = process.env) {
74
77
  const workerModel = config?.agents?.worker?.model;
75
- const workerThinking = config?.agents?.worker?.thinking;
78
+ let workerThinking = config?.agents?.worker?.thinking;
79
+ const thinkingOverride = env?.SPINE_WORKER_THINKING_OVERRIDE?.trim();
80
+ if (thinkingOverride) {
81
+ if (PROMPT_THINKING_LEVELS.includes(thinkingOverride)) {
82
+ workerThinking = thinkingOverride;
83
+ } else {
84
+ console.error(
85
+ `SPINE_WORKER_THINKING_OVERRIDE="${thinkingOverride}" ignored (expected ${PROMPT_THINKING_LEVELS.join("|")})`,
86
+ );
87
+ }
88
+ }
76
89
  if (workerModel && workerModel !== "inherit") {
77
90
  piArgs.push("--model", workerModel);
78
91
  }
@@ -392,12 +405,12 @@ async function runWorkerRunner() {
392
405
  if (hangMs > 0 || process.env.SPINE_WORKER_STUB_SAT020 === "1") {
393
406
  const effectiveHang =
394
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.
395
410
  const step = 100;
396
- let elapsed = 0;
397
- while (elapsed < effectiveHang) {
398
- const slice = Math.min(step, effectiveHang - elapsed);
399
- spawnSync("sleep", [String(slice / 1000)], { stdio: "ignore" });
400
- 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" });
401
414
  }
402
415
  console.error("stub worker hang finished without .DONE");
403
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.27.1",
3
+ "version": "2.28.1",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -14,6 +14,11 @@ Deterministic commands use the [execute-task variant](#execute-task-variant) ins
14
14
  **Created:** [YYYY-MM-DD]
15
15
  **Size:** [S | M | L]
16
16
  **Type:** [llm | execute]
17
+ **Profile:** [optional — worker profile name from `agents.profiles`]
18
+ **Thinking:** [optional — off | minimal | low | medium | high | xhigh]
19
+ **Reviewer Profile:** [optional — profile from `agents.profiles` whose `reviewer` block judges this task]
20
+
21
+ > **Agent header fields (#355):** All three are optional; omit them to use `agents.activeProfile`. Names allow `A-Z a-z 0-9 . _ -`. Engine reviews resolve the reviewer per task: `**Reviewer Profile:**` → `agents.profiles.<worker profile>.reviewerProfile` → `agents.reviewerProfile` → `agents.reviewer`, skipping any reviewer in the same model family as the worker. When no cross-family reviewer remains, the task fails with `review_blocked` before any reviewer spawns. `**Profile:**` feeds that resolution today; the worker spawn does not yet apply `**Profile:**` or `**Thinking:**`. See the operator runbook, "Reviewer profiles".
17
22
 
18
23
  ## Review Level: [0-2] ([None | Plan Only | Plan and Code])
19
24
 
@@ -10,6 +10,16 @@ You are the **pi-spine release operator**. Drive a **curated release cycle** fro
10
10
 
11
11
  Invoke explicitly: `/skill:spine-release-operator` or "run a spine release cycle for v1.5.1".
12
12
 
13
+ ## Spine CLI binary (repo checkout inside pi-spine only)
14
+
15
+ Every `spine …` command in this skill means the CLI from **this pi-spine checkout**, not the global install. The release cycle is the dogfood run for unreleased `main`; the global `spine` (npm `-g`, `pi install npm:pi-spine`) stays on the last published release because `main` can be unstable between releases. Other projects keep using the published global.
16
+
17
+ - Run `node bin/spine.mjs <args>` from the pi-spine repo root (batch start/resume/retry, wait, gate, integrate, doctor, preflight, plan, tasks validate, status).
18
+ - The engine resolves its worker runner and reviewer code from the package that launched it (`PACKAGE_ROOT`), so the binary you start a batch with decides which engine code runs.
19
+ - After each integrate, `npm install` on `main` (already required) keeps the checkout runnable; the next batch picks up the new engine automatically.
20
+ - Verify after a detached start: `ps -o command= -p <enginePid>` must show `<repo>/bin/spine.mjs`, not `/opt/homebrew/...` or `node_modules/pi-spine`.
21
+ - Never `npm link` the checkout or point the global at it; do not reinstall the global mid-release. Upgrade the global only after publish (Phase 6).
22
+
13
23
  **Not** for executing all pending tasks — use `spine-autonomous-operator` for that. This skill selects a **subset** fitting the release profile.
14
24
 
15
25
  ## Skill boundaries
@@ -62,7 +72,7 @@ Invoke explicitly: `/skill:spine-release-operator` or "run a spine release cycle
62
72
  - **Do not** execute tasks outside the approved manifest scope
63
73
  - **Never** start Phase 4 (execute) without **recorded scope approval** — the release manifest must show `Operator approved scope: yes` from the Phase 2 gate. Refuse the first wave when approval is missing or `no` (F1, [#249](https://github.com/beettlle/pi-spine/issues/249))
64
74
  - **Never** mid-release-edit `.spine/spine-config.json` agent pins (`agents.worker.model` / `agents.reviewer.model`) while a batch is running or integrated work is still unpublished. Pin **one worker** per release; escalate models **only** on content/contract failure — never on quota/403 or launch storms, which make releases worse (F7, [#248](https://github.com/beettlle/pi-spine/issues/248)). To override mid-release, first record the reason and date in the release manifest
65
- - **Distinguish quota fallback from escalation** ([#329](https://github.com/beettlle/pi-spine/issues/329), v2.27.0): `agents.quotaFallbackProfile` is **provider failover, not escalation** — it switches the batch to a fallback profile on a **different provider pool**, not to a stronger model. It is single-hop per batch, sticky once applied, journaled (`batch.quota_fallback_applied`), and never edits `.spine/spine-config.json`. Because it changes pool, not model strength, it is **allowed mid-release** and does not violate the #248 rule above — that rule still bans escalating models on quota/403 or launch storms. After a fallback fires, paste the `Agent pin override: yes (<date>, auto quota fallback <pool> -> <profile>, batch <id>)` line shown by `spine status --diagnose` into the release manifest (the override record the #248 rule requires)
75
+ - **Distinguish quota fallback from escalation** ([#329](https://github.com/beettlle/pi-spine/issues/329), v2.27.0): `agents.quotaFallbackProfile` is **provider failover, not escalation** — it switches the batch to a fallback profile on a **different provider pool**, not to a stronger model. It is single-hop, sticky once applied until it expires after the primary pool's parsed reset time or you run `spine batch quota-fallback clear` ([#350](https://github.com/beettlle/pi-spine/issues/350); journaled `batch.quota_fallback_cleared`), journaled (`batch.quota_fallback_applied`), and never edits `.spine/spine-config.json`. Because it changes pool, not model strength, it is **allowed mid-release** and does not violate the #248 rule above — that rule still bans escalating models on quota/403 or launch storms. After a fallback fires, paste the `Agent pin override: yes (<date>, auto quota fallback <pool> -> <profile>, batch <id>)` line shown by `spine status --diagnose` into the release manifest (the override record the #248 rule requires)
66
76
  - **Heed** the doctor/preflight **quota-risk advisory** ([#251](https://github.com/beettlle/pi-spine/issues/251)): `spine doctor` surfaces `ok: true, warning: true` when escalate/hard worker pins target quota-constrained pools without headroom evidence, or recent run-metrics show launch-storm / quota-abort patterns. It is advisory only — never fails preflight — and does not change the mid-release pin-thrash ban above
67
77
  - **Always** push/sync `main` to `origin` after each land loop once the post-integrate regression gate is green — do not let `main` drift far ahead of `origin` during a release (F8, [#249](https://github.com/beettlle/pi-spine/issues/249))
68
78
  - **Always** close GitHub issues linked as `Closes #NNN` / `Closes: #NNN` **as soon as that task's work is on `main`** (after integrate + post-integrate `release:check` green) — do **not** defer closing until Phase 6 publish. Leave `Partial #NNN` / `Partial: #NNN` open. Phase 6 is only a final sweep for any still-open `Closes` links (v2.15.0 left #257–#261, #263 open after ship — avoid that)
@@ -291,7 +301,7 @@ Before the first wave, confirm the release manifest records **`Operator approved
291
301
 
292
302
  **Reviewer isolation:** reviewers no longer load user extensions — they spawn with `pi -ne` by default (v2.27.1, [#334](https://github.com/beettlle/pi-spine/issues/334)), so extension overrides matter only when `agents.reviewer.loadUserExtensions` is `true`. If a review spawn or provider failure hits a task whose `.DONE` is already in the lane, recover by re-review (`spine batch retry <taskId>` → `spine batch resume`), not salvage — salvage lands unreviewed work and is a last resort.
293
303
 
294
- **Quota fallback is provider failover, not escalation** ([#329](https://github.com/beettlle/pi-spine/issues/329), v2.27.0): when `agents.quotaFallbackProfile` names a profile on a different provider pool, the engine moves the batch to that pool automatically — once per batch, sticky, journaled, without editing `.spine/spine-config.json` — and retries each quota-exhausted task once in its lane worktree. This is the sanctioned mid-release response to quota exhaustion; it does not count as a pin override under the rule above. When it fires, record it in the release manifest by pasting the `Agent pin override: yes (<date>, auto quota fallback <pool> -> <profile>, batch <id>)` line from `spine status --diagnose`.
304
+ **Quota fallback is provider failover, not escalation** ([#329](https://github.com/beettlle/pi-spine/issues/329), v2.27.0): when `agents.quotaFallbackProfile` names a profile on a different provider pool, the engine moves the batch to that pool automatically — once per batch, sticky until the primary pool's reset time passes or `spine batch quota-fallback clear` runs (#350), journaled, without editing `.spine/spine-config.json` — and retries each quota-exhausted task once in its lane worktree. This is the sanctioned mid-release response to quota exhaustion; it does not count as a pin override under the rule above. When it fires, record it in the release manifest by pasting the `Agent pin override: yes (<date>, auto quota fallback <pool> -> <profile>, batch <id>)` line from `spine status --diagnose`.
295
305
 
296
306
  **Detached-first:** See [agent-shell-batch-policy.md](../spine-autonomous-operator/references/agent-shell-batch-policy.md). Omit `--attached` for release waves unless the operator shell is a persistent interactive terminal that blocks until batch completion.
297
307
 
@@ -592,6 +602,8 @@ When `release.yml` fails: `gh run view <run-id> --log-failed`, then follow the s
592
602
 
593
603
  Post-publish smoke (**only after stage success and 2FA approve**): `scripts/post-publish-smoke.sh <version>` — bounded retry on registry lag (F9, [#247](https://github.com/beettlle/pi-spine/issues/247)). If retries exhaust, **STOP** and investigate; manual steps in [references/publish-recovery.md](references/publish-recovery.md#post-publish-smoke).
594
604
 
605
+ After smoke passes, upgrade the machine's global install to the new release (the only point the global changes): `npm install -g pi-spine@<version>`, then `spine --version` must print `<version>`. If pi loads the extension via `npm:pi-spine`, run `pi update` as well.
606
+
595
607
  Update `spine-tasks/CONTEXT.md` release note (version + date).
596
608
 
597
609
  ### Close remaining GitHub issues (final sweep)
@@ -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) {
@@ -5,6 +5,19 @@
5
5
 
6
6
  import { execFileSync } from "node:child_process";
7
7
 
8
+ const COMMIT_SHA_PATTERN = /^[0-9a-f]{7,40}$/i;
9
+
10
+ /**
11
+ * Hex-only commit SHA check (7-40 chars). Rejects option-like values (leading `-`)
12
+ * before they reach git argv or reviewer prompts (#313, #343).
13
+ *
14
+ * @param {unknown} value
15
+ * @returns {value is string}
16
+ */
17
+ export function isValidCommitSha(value) {
18
+ return typeof value === "string" && COMMIT_SHA_PATTERN.test(value);
19
+ }
20
+
8
21
  const PAYLOAD_COMMIT_KEYS = ["taskStartCommit", "startCommit", "commitSha", "headCommit", "laneBranchHead"];
9
22
 
10
23
  /**
@@ -178,7 +191,16 @@ function findFirstTaskStarted(journal, taskId, laneId, batchId) {
178
191
  * @param {{ journal: object[], taskId: string, laneId?: string|null, batchId?: string|null, worktreePath?: string|null }} options
179
192
  * @returns {string|null}
180
193
  */
181
- export function resolveTaskStartCommit({ journal, taskId, laneId, batchId, worktreePath }) {
194
+ export function resolveTaskStartCommit(options) {
195
+ const commit = resolveRawTaskStartCommit(options);
196
+ return isValidCommitSha(commit) ? commit : null;
197
+ }
198
+
199
+ /**
200
+ * @param {{ journal: object[], taskId: string, laneId?: string|null, batchId?: string|null, worktreePath?: string|null }} options
201
+ * @returns {string|null}
202
+ */
203
+ function resolveRawTaskStartCommit({ journal, taskId, laneId, batchId, worktreePath }) {
182
204
  if (!Array.isArray(journal) || !taskId) {
183
205
  return null;
184
206
  }