pi-spine 2.28.0 → 2.29.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.
@@ -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.29.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -26,7 +26,12 @@ import {
26
26
  TEST_COMMAND_NPM_TEST_DASH_DASH_FIX_HINT,
27
27
  } from "../tasks/validate-contract-warn.mjs";
28
28
  import { formatRefusedContractMetacharMessage, isRefusedContractMetacharCommand } from "../tasks/packet/parse-prompt.mjs";
29
- import { runShellCommandAsync } from "./contract-spawn.mjs";
29
+ import { buildContractTestEnv, runShellCommandAsync } from "./contract-spawn.mjs";
30
+ import { runContractReviewStep } from "./contract-review.mjs";
31
+
32
+ // Worker env stripping + re-export moved to contract-spawn.mjs (SP-845 keeps
33
+ // contract-review.mjs cycle-free); the public surface is unchanged.
34
+ export { CONTRACT_TEST_WORKER_ENV_KEYS, buildContractTestEnv } from "./contract-spawn.mjs";
30
35
 
31
36
  // Shared pre-spawn refusal envelope for the npm-scope (#187) and metachar (#268) guards.
32
37
  function refusedBeforeSpawnResult(/** @type {string} */ summary) {
@@ -42,33 +47,6 @@ export const CONTRACT_TEST_DEFAULT_RETRIES = 1;
42
47
  /** Default delay in ms between testCommand retry attempts. */
43
48
  export const CONTRACT_TEST_RETRY_DELAY_MS = 5000;
44
49
 
45
- /**
46
- * Worker-only env keys stripped from contract testCommand subprocesses so full-suite
47
- * tests match operator re-run outside worker-host (SP-491, issue #155).
48
- */
49
- export const CONTRACT_TEST_WORKER_ENV_KEYS = ["SPINE_IS_WORKER"];
50
-
51
- /**
52
- * Build env for contract testCommand subprocess — omits worker-only keys inherited from
53
- * worker-host.mjs that would false-fail batch-spawn integration tests (SP-482 guard).
54
- * Preserves parent batch id as SPINE_PARENT_BATCH_ID so nested-spawn guard can block
55
- * live engines in lane worktrees while still allowing isolated fixture tests (#162).
56
- *
57
- * @param {NodeJS.ProcessEnv} [sourceEnv]
58
- * @returns {NodeJS.ProcessEnv}
59
- */
60
- export function buildContractTestEnv(sourceEnv = process.env) {
61
- const env = { ...sourceEnv };
62
- for (const key of CONTRACT_TEST_WORKER_ENV_KEYS) {
63
- delete env[key];
64
- }
65
- if (env.SPINE_BATCH_ID && !env.SPINE_PARENT_BATCH_ID) {
66
- env.SPINE_PARENT_BATCH_ID = env.SPINE_BATCH_ID;
67
- }
68
- delete env.SPINE_BATCH_ID;
69
- return env;
70
- }
71
-
72
50
  /**
73
51
  * @param {number} byteCount
74
52
  */
@@ -302,9 +280,8 @@ export function prepareContractVerifyEnvironment(worktreePath, parsedContract, c
302
280
  * @param {string} [config.batchId] Batch ID for journal events (optional).
303
281
  * @param {string} [config.taskId] Task ID for journal events (optional).
304
282
  * @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.
283
+ * @param {{ reviewPolicy?: "blocking" | "advisory", reviewTimeoutMs?: number, testRetries?: number, testRetryDelayMs?: number, testTimeoutMs?: number }} [config.contract] Retry/timeout tuning (#369) and review step policy (SP-845).
306
284
  * @param {number} [config.contractTestMaxBuffer] stdout/stderr capture limit override.
307
- * @param {number} [config.contractTestTimeoutMs] Wall-clock timeout override for testCommand attempts.
308
285
  * @param {{ test?: string, testWithCoverage?: string }} [config.testing] Coverage command selection.
309
286
  * @returns {Promise<{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number }>}
310
287
  */
@@ -338,7 +315,7 @@ export async function verifyContract(worktreePath, parsedContract, config = {})
338
315
  for (let attempt = 1; attempt <= totalAttempts; attempt++) {
339
316
  lastResult = await runContractTestCommand(worktreePath, parsedContract.testCommand, {
340
317
  maxBuffer: config?.contractTestMaxBuffer,
341
- timeoutMs: config?.contractTestTimeoutMs,
318
+ timeoutMs: config?.contract?.testTimeoutMs,
342
319
  });
343
320
 
344
321
  if (lastResult.ok) {
@@ -387,6 +364,13 @@ export async function verifyContract(worktreePath, parsedContract, config = {})
387
364
  });
388
365
  }
389
366
 
367
+ // SP-845: reviewCommand runs once, only when the test step passed (or is absent).
368
+ // Failures never retry — reviewers resume their own session.
369
+ if (parsedContract.reviewCommand && (!parsedContract.testCommand || testCommandOk)) {
370
+ const reviewCheck = await runContractReviewStep(worktreePath, parsedContract, config);
371
+ if (reviewCheck) checks.push(reviewCheck);
372
+ }
373
+
390
374
  for (const pattern of parsedContract.fileScopeMustChange ?? []) {
391
375
  const matched = changedFiles.some((file) =>
392
376
  pattern.endsWith("/") ? file.startsWith(pattern) : matchesContractPattern(file, pattern),