pi-spine 1.1.0 → 1.3.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.
Files changed (126) hide show
  1. package/README.md +4 -4
  2. package/bin/spine-batch.mjs +160 -53
  3. package/bin/spine-cli/batch.mjs +3 -3
  4. package/bin/spine-cli/lane-logs.mjs +24 -0
  5. package/bin/spine-cli/scenarios.mjs +298 -0
  6. package/bin/spine-cli/verify.mjs +3 -0
  7. package/bin/spine-cli/wait.mjs +30 -0
  8. package/bin/spine-cli/watch.mjs +27 -0
  9. package/bin/spine-issue.mjs +196 -0
  10. package/bin/spine-journal.mjs +1 -0
  11. package/bin/spine-plan.mjs +49 -1
  12. package/bin/spine-run.mjs +30 -0
  13. package/bin/spine-status.mjs +19 -1
  14. package/bin/spine-tasks.mjs +16 -2
  15. package/bin/spine-worker-runner.mjs +144 -12
  16. package/bin/spine.mjs +49 -1
  17. package/package.json +1 -1
  18. package/skills/create-spine-tasks/SKILL.md +7 -2
  19. package/skills/create-spine-tasks/references/contract-template.md +114 -3
  20. package/src/batch/abort.mjs +2 -11
  21. package/src/batch/agent-session-worker.mjs +45 -5
  22. package/src/batch/attached-engine-handoff.mjs +188 -0
  23. package/src/batch/attached-runner.mjs +388 -0
  24. package/src/batch/contract-prelanded.mjs +180 -0
  25. package/src/batch/contract-stub-delivery.mjs +110 -0
  26. package/src/batch/contract-task-start.mjs +204 -0
  27. package/src/batch/contract-verify.mjs +195 -10
  28. package/src/batch/detached-start.mjs +137 -3
  29. package/src/batch/diagnosis-alternatives.mjs +46 -0
  30. package/src/batch/diagnosis-launch-failure.mjs +114 -0
  31. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  32. package/src/batch/diagnosis-primary-failure.mjs +89 -0
  33. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  34. package/src/batch/diagnosis-stub.mjs +109 -0
  35. package/src/batch/diagnosis-tail-state.mjs +57 -0
  36. package/src/batch/diagnosis-task-done.mjs +110 -0
  37. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  38. package/src/batch/diagnosis.mjs +140 -164
  39. package/src/batch/engine-lanes/commit.mjs +145 -0
  40. package/src/batch/engine-lanes/merge.mjs +110 -82
  41. package/src/batch/engine-lanes/queue.mjs +4 -1
  42. package/src/batch/engine-lanes/review.mjs +67 -87
  43. package/src/batch/engine-lanes/watch.mjs +29 -0
  44. package/src/batch/engine-lanes.mjs +21 -78
  45. package/src/batch/engine-scope.mjs +11 -1
  46. package/src/batch/engine.mjs +125 -24
  47. package/src/batch/evidence.mjs +78 -15
  48. package/src/batch/gate.mjs +43 -14
  49. package/src/batch/git-helpers.mjs +96 -0
  50. package/src/batch/heartbeat.mjs +75 -9
  51. package/src/batch/integrate-assert.mjs +69 -0
  52. package/src/batch/integrate-worktree.mjs +354 -0
  53. package/src/batch/integrate.mjs +193 -102
  54. package/src/batch/journal-rebuild.mjs +48 -2
  55. package/src/batch/journal.mjs +66 -0
  56. package/src/batch/lane-commit.mjs +90 -5
  57. package/src/batch/lane-dirty-check.mjs +437 -0
  58. package/src/batch/lifecycle.mjs +130 -3
  59. package/src/batch/limbo-detect.mjs +34 -0
  60. package/src/batch/macro-phase.mjs +302 -0
  61. package/src/batch/merge/adoption-doc-merge.mjs +93 -10
  62. package/src/batch/merge/wave-merge-state.mjs +3 -0
  63. package/src/batch/metrics.mjs +76 -5
  64. package/src/batch/orphan-detect.mjs +74 -0
  65. package/src/batch/pause.mjs +234 -0
  66. package/src/batch/post-merge-limbo.mjs +259 -28
  67. package/src/batch/reconcile.mjs +508 -63
  68. package/src/batch/resume-common.mjs +32 -1
  69. package/src/batch/resume-lane-reviews.mjs +16 -0
  70. package/src/batch/resume-multi-lanes.mjs +67 -1
  71. package/src/batch/resume-multi-validate.mjs +67 -6
  72. package/src/batch/resume-multi.mjs +11 -4
  73. package/src/batch/resume.mjs +59 -45
  74. package/src/batch/retry.mjs +97 -15
  75. package/src/batch/review-spawn.mjs +8 -2
  76. package/src/batch/rules-manifest-drift.mjs +198 -0
  77. package/src/batch/salvage.mjs +2 -1
  78. package/src/batch/sequence-state.mjs +290 -0
  79. package/src/batch/sequence.mjs +516 -0
  80. package/src/batch/state.mjs +34 -3
  81. package/src/batch/status-json.mjs +67 -0
  82. package/src/batch/task-stall-budget.mjs +22 -10
  83. package/src/batch/worker-host.mjs +96 -7
  84. package/src/batch/worker-output.mjs +196 -3
  85. package/src/cli/issue-draft.mjs +180 -0
  86. package/src/cli/journal-follow.mjs +239 -0
  87. package/src/cli/lane-logs.mjs +291 -0
  88. package/src/cli/sequence.mjs +121 -0
  89. package/src/cli/settings-set.mjs +35 -24
  90. package/src/cli/wait.mjs +187 -0
  91. package/src/cli/watch.mjs +160 -0
  92. package/src/config/agent-model-resolve.mjs +48 -0
  93. package/src/config/cursor-rules/discover.mjs +3 -21
  94. package/src/config/defaults.mjs +7 -1
  95. package/src/config/model-id.mjs +103 -0
  96. package/src/config/settings-fields.mjs +48 -0
  97. package/src/config/spine-init-constants.mjs +2 -0
  98. package/src/config/spine-preflight-lib.mjs +494 -17
  99. package/src/dashboard/lane-throughput.mjs +351 -0
  100. package/src/dashboard/public/dashboard.css +25 -1
  101. package/src/dashboard/public/dashboard.js +234 -18
  102. package/src/dashboard/public/index.html +14 -2
  103. package/src/dashboard/running-tail-state.mjs +31 -0
  104. package/src/dashboard/server.mjs +8 -0
  105. package/src/dashboard/snapshot.mjs +472 -26
  106. package/src/dashboard/view.mjs +282 -19
  107. package/src/doctor/agent-model-inherit.mjs +61 -6
  108. package/src/doctor/agent-models.mjs +53 -0
  109. package/src/doctor/batch-size-guidance.mjs +30 -2
  110. package/src/doctor/pi-extension-conflict.mjs +169 -0
  111. package/src/doctor/run-doctor-checks.mjs +32 -1
  112. package/src/doctor/sequence-safety.mjs +57 -0
  113. package/src/doctor/stale-worktrees.mjs +102 -0
  114. package/src/fixtures/scenario-registry.mjs +194 -0
  115. package/src/fs/atomic-write.mjs +49 -0
  116. package/src/planner/file-scope.mjs +246 -0
  117. package/src/planner/format-plan.mjs +9 -7
  118. package/src/planner/index.mjs +6 -2
  119. package/src/planner/scope.mjs +5 -1
  120. package/src/planner/wave-scope.mjs +136 -0
  121. package/src/planner/waves.mjs +133 -0
  122. package/src/tasks/packet/index.mjs +1 -0
  123. package/src/tasks/packet/parse-prompt.mjs +73 -2
  124. package/src/tasks/packet/validate-contract.mjs +108 -0
  125. package/src/tasks/packet/validate-prompt.mjs +124 -0
  126. package/templates/spine-config.json +8 -1
@@ -2,14 +2,22 @@
2
2
  * spine settings set — validate, merge, and persist editable spine-config fields (FR-CFG-03).
3
3
  */
4
4
 
5
- import fs from "node:fs";
6
5
  import path from "node:path";
7
- import { randomBytes } from "node:crypto";
8
6
 
7
+ import { writeJsonAtomic } from "../fs/atomic-write.mjs";
8
+ import { normalizeModelId } from "../config/model-id.mjs";
9
9
  import { parseSettingPath, validateSettingValue } from "../config/settings-fields.mjs";
10
10
  import { validateSpineConfig } from "../config/spine-config-load.mjs";
11
11
  import { getValueAtPath } from "./settings-show.mjs";
12
12
 
13
+ const MODEL_FIELD_PATHS = new Set([
14
+ "agents.worker.model",
15
+ "agents.reviewer.model",
16
+ "agents.reviewer.plan.model",
17
+ "agents.reviewer.code.model",
18
+ "agents.reviewer.final.model",
19
+ ]);
20
+
13
21
  /**
14
22
  * @param {object} config
15
23
  * @param {string} dottedPath
@@ -40,25 +48,7 @@ export function applySetting(config, dottedPath, value) {
40
48
  */
41
49
  export function writeSpineConfigAtomic(projectRoot, config) {
42
50
  const configPath = path.join(projectRoot, ".spine", "spine-config.json");
43
- const dir = path.dirname(configPath);
44
- fs.mkdirSync(dir, { recursive: true });
45
-
46
- const tmpPath = `${configPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
47
- const content = `${JSON.stringify(config, null, 2)}\n`;
48
-
49
- try {
50
- fs.writeFileSync(tmpPath, content, "utf-8");
51
- fs.renameSync(tmpPath, configPath);
52
- } catch (err) {
53
- try {
54
- if (fs.existsSync(tmpPath)) {
55
- fs.unlinkSync(tmpPath);
56
- }
57
- } catch {
58
- // ignore cleanup failure
59
- }
60
- throw err;
61
- }
51
+ writeJsonAtomic(configPath, config);
62
52
  }
63
53
 
64
54
  /**
@@ -112,8 +102,29 @@ export function runSettingsSetOperation(config, { path, rawValue, dryRun = false
112
102
  };
113
103
  }
114
104
 
105
+ let settingValue = validated.normalizedValue;
106
+ if (MODEL_FIELD_PATHS.has(parsed.path) && typeof settingValue === "string" && settingValue !== "") {
107
+ const modelResult = normalizeModelId(settingValue);
108
+ if (!modelResult.ok) {
109
+ const message = modelResult.error;
110
+ if (json) {
111
+ return {
112
+ exitCode: 1,
113
+ output: `${JSON.stringify({ error: message }, null, 2)}\n`,
114
+ error: message,
115
+ };
116
+ }
117
+ return {
118
+ exitCode: 1,
119
+ output: `Error: ${message}\n`,
120
+ error: message,
121
+ };
122
+ }
123
+ settingValue = modelResult.value;
124
+ }
125
+
115
126
  const previousValue = getValueAtPath(config, parsed.path);
116
- const nextConfig = applySetting(config, parsed.path, validated.normalizedValue);
127
+ const nextConfig = applySetting(config, parsed.path, settingValue);
117
128
  const validationError = validateSpineConfig(nextConfig);
118
129
  if (validationError) {
119
130
  const message = validationError.message;
@@ -137,7 +148,7 @@ export function runSettingsSetOperation(config, { path, rawValue, dryRun = false
137
148
  const payload = {
138
149
  path: parsed.path,
139
150
  previousValue,
140
- newValue: validated.normalizedValue,
151
+ newValue: settingValue,
141
152
  dryRun,
142
153
  wrote,
143
154
  };
@@ -153,7 +164,7 @@ export function runSettingsSetOperation(config, { path, rawValue, dryRun = false
153
164
 
154
165
  return {
155
166
  exitCode: 0,
156
- output: `Updated ${parsed.path}: ${formatValue(previousValue)} → ${formatValue(validated.normalizedValue)}${dryRun ? " (dry run)" : ""}\n`,
167
+ output: `Updated ${parsed.path}: ${formatValue(previousValue)} → ${formatValue(settingValue)}${dryRun ? " (dry run)" : ""}\n`,
157
168
  ...payload,
158
169
  config: nextConfig,
159
170
  };
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Block until reconcile diagnosis reaches a target set (issue #46, SP-362).
3
+ */
4
+
5
+ import { DIAGNOSIS_TAXONOMY } from "../batch/diagnosis.mjs";
6
+ import { reconcileBatch } from "../batch/reconcile.mjs";
7
+ import {
8
+ buildWatchSnapshot,
9
+ DEFAULT_WATCH_INTERVAL_SEC,
10
+ } from "./watch.mjs";
11
+
12
+ /** @type {ReadonlySet<string>} */
13
+ const VALID_UNTIL_DIAGNOSES = new Set(DIAGNOSIS_TAXONOMY);
14
+
15
+ /**
16
+ * @param {string} raw
17
+ * @returns {number}
18
+ */
19
+ export function parseDurationMs(raw) {
20
+ const trimmed = String(raw).trim();
21
+ if (trimmed.length === 0) {
22
+ throw new Error("--timeout requires a duration (e.g. 30s, 5m, 2h, or seconds)");
23
+ }
24
+
25
+ if (/^\d+$/.test(trimmed)) {
26
+ const seconds = Number(trimmed);
27
+ if (!Number.isFinite(seconds) || seconds <= 0) {
28
+ throw new Error("--timeout requires a positive duration");
29
+ }
30
+ return seconds * 1000;
31
+ }
32
+
33
+ const match = trimmed.match(/^(\d+(?:\.\d+)?)([smh])$/i);
34
+ if (!match) {
35
+ throw new Error("--timeout requires a duration like 30s, 5m, 2h, or plain seconds");
36
+ }
37
+
38
+ const value = Number(match[1]);
39
+ const unit = match[2].toLowerCase();
40
+ if (!Number.isFinite(value) || value <= 0) {
41
+ throw new Error("--timeout requires a positive duration");
42
+ }
43
+
44
+ const multipliers = { s: 1000, m: 60_000, h: 3_600_000 };
45
+ return value * multipliers[unit];
46
+ }
47
+
48
+ /**
49
+ * @param {string} raw
50
+ * @returns {Set<string>}
51
+ */
52
+ export function parseUntilDiagnoses(raw) {
53
+ const trimmed = String(raw).trim();
54
+ if (trimmed.length === 0) {
55
+ throw new Error("--until requires a comma-separated diagnosis list");
56
+ }
57
+
58
+ /** @type {Set<string>} */
59
+ const diagnoses = new Set();
60
+ for (const part of trimmed.split(",")) {
61
+ const diagnosis = part.trim();
62
+ if (diagnosis.length === 0) {
63
+ throw new Error("--until contains an empty diagnosis entry");
64
+ }
65
+ if (!VALID_UNTIL_DIAGNOSES.has(diagnosis)) {
66
+ throw new Error(
67
+ `Unknown diagnosis in --until: ${diagnosis} (valid: ${DIAGNOSIS_TAXONOMY.join(", ")})`,
68
+ );
69
+ }
70
+ diagnoses.add(diagnosis);
71
+ }
72
+
73
+ return diagnoses;
74
+ }
75
+
76
+ /**
77
+ * @param {string[]} argv
78
+ */
79
+ export function parseWaitArgs(argv) {
80
+ /** @type {{ until: Set<string> | null, timeoutMs: number | null, intervalSec: number, json: boolean }} */
81
+ const args = {
82
+ until: null,
83
+ timeoutMs: null,
84
+ intervalSec: DEFAULT_WATCH_INTERVAL_SEC,
85
+ json: false,
86
+ };
87
+
88
+ for (let i = 0; i < argv.length; i++) {
89
+ const arg = argv[i];
90
+ if (arg === "--until") {
91
+ args.until = parseUntilDiagnoses(argv[++i] ?? "");
92
+ } else if (arg === "--timeout") {
93
+ args.timeoutMs = parseDurationMs(argv[++i] ?? "");
94
+ } else if (arg === "--interval") {
95
+ const raw = argv[++i];
96
+ const value = Number(raw);
97
+ if (!Number.isFinite(value) || value <= 0) {
98
+ throw new Error("--interval requires a positive number of seconds");
99
+ }
100
+ args.intervalSec = value;
101
+ } else if (arg === "--json") {
102
+ args.json = true;
103
+ } else if (arg.startsWith("-")) {
104
+ throw new Error(`Unknown wait option: ${arg}`);
105
+ }
106
+ }
107
+
108
+ if (!args.until || args.until.size === 0) {
109
+ throw new Error("--until is required (comma-separated diagnoses)");
110
+ }
111
+
112
+ return args;
113
+ }
114
+
115
+ /**
116
+ * @param {string | null | undefined} diagnosis
117
+ * @param {Set<string>} untilDiagnoses
118
+ */
119
+ export function diagnosisMatchesUntil(diagnosis, untilDiagnoses) {
120
+ if (diagnosis == null) {
121
+ return false;
122
+ }
123
+ return untilDiagnoses.has(diagnosis);
124
+ }
125
+
126
+ /**
127
+ * @param {object} options
128
+ * @param {string} options.projectRoot
129
+ * @param {Set<string>} options.untilDiagnoses
130
+ * @param {number} [options.intervalSec]
131
+ * @param {number | null} [options.timeoutMs]
132
+ * @param {boolean} [options.json]
133
+ * @param {(ctx: { projectRoot: string }) => import("../batch/reconcile.mjs").ReconciliationResult} [options.reconcileFn]
134
+ * @param {(ms: number) => Promise<void>} [options.sleepFn]
135
+ * @param {() => number} [options.nowFn]
136
+ * @param {(text: string) => void} [options.writeStdout]
137
+ */
138
+ export async function runSpineWait(options) {
139
+ const {
140
+ projectRoot,
141
+ untilDiagnoses,
142
+ intervalSec = DEFAULT_WATCH_INTERVAL_SEC,
143
+ timeoutMs = null,
144
+ json = false,
145
+ reconcileFn = reconcileBatch,
146
+ sleepFn = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
147
+ nowFn = () => Date.now(),
148
+ writeStdout = (text) => process.stdout.write(text),
149
+ } = options;
150
+
151
+ const startedAt = nowFn();
152
+ const deadline = timeoutMs != null ? startedAt + timeoutMs : null;
153
+
154
+ /** @type {boolean} */
155
+ let running = true;
156
+ const onSigInt = () => {
157
+ running = false;
158
+ };
159
+ process.on("SIGINT", onSigInt);
160
+
161
+ try {
162
+ while (running) {
163
+ const result = reconcileFn({ projectRoot });
164
+ const diagnosis = result.diagnosis ?? null;
165
+
166
+ if (diagnosisMatchesUntil(diagnosis, untilDiagnoses)) {
167
+ if (json) {
168
+ writeStdout(`${JSON.stringify(buildWatchSnapshot(result, nowFn()))}\n`);
169
+ }
170
+ return { exitCode: 0, matched: true, diagnosis, timedOut: false };
171
+ }
172
+
173
+ if (deadline != null && nowFn() >= deadline) {
174
+ if (json) {
175
+ writeStdout(`${JSON.stringify(buildWatchSnapshot(result, nowFn()))}\n`);
176
+ }
177
+ return { exitCode: 1, matched: false, diagnosis, timedOut: true };
178
+ }
179
+
180
+ await sleepFn(intervalSec * 1000);
181
+ }
182
+
183
+ return { exitCode: 130, matched: false, diagnosis: null, timedOut: false, interrupted: true };
184
+ } finally {
185
+ process.off("SIGINT", onSigInt);
186
+ }
187
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Foreground poll loop over reconcileBatch (issue #44, SP-360).
3
+ */
4
+
5
+ import { reconcileBatch } from "../batch/reconcile.mjs";
6
+
7
+ export const DEFAULT_WATCH_INTERVAL_SEC = 5;
8
+
9
+ const PROGRESS_FIELD_NAMES = [
10
+ "succeededTasks",
11
+ "pendingTasks",
12
+ "totalTasks",
13
+ "currentWaveIndex",
14
+ "waveCount",
15
+ ];
16
+
17
+ /**
18
+ * @param {string[]} argv
19
+ */
20
+ export function parseWatchArgs(argv) {
21
+ /** @type {{ intervalSec: number, json: boolean, once: boolean }} */
22
+ const args = {
23
+ intervalSec: DEFAULT_WATCH_INTERVAL_SEC,
24
+ json: false,
25
+ once: false,
26
+ };
27
+
28
+ for (let i = 0; i < argv.length; i++) {
29
+ const arg = argv[i];
30
+ if (arg === "--interval") {
31
+ const raw = argv[++i];
32
+ const value = Number(raw);
33
+ if (!Number.isFinite(value) || value <= 0) {
34
+ throw new Error("--interval requires a positive number of seconds");
35
+ }
36
+ args.intervalSec = value;
37
+ } else if (arg === "--json") {
38
+ args.json = true;
39
+ } else if (arg === "--once") {
40
+ args.once = true;
41
+ } else if (arg.startsWith("-")) {
42
+ throw new Error(`Unknown watch option: ${arg}`);
43
+ }
44
+ }
45
+
46
+ return args;
47
+ }
48
+
49
+ /**
50
+ * @param {import("../batch/reconcile.mjs").ReconciliationResult & Record<string, unknown>} reconcileResult
51
+ */
52
+ export function formatWatchHumanLine(reconcileResult) {
53
+ const diagnosis = reconcileResult.diagnosis ?? "idle";
54
+ const batchId = reconcileResult.batchId ?? "—";
55
+ const macroPhase =
56
+ reconcileResult.macroPhaseLabel ?? reconcileResult.macroPhase ?? "—";
57
+ const headline = reconcileResult.headline ?? "";
58
+ return `${diagnosis} | ${batchId} | ${macroPhase} | ${headline}`;
59
+ }
60
+
61
+ /**
62
+ * Stable NDJSON snapshot for `spine watch --json`.
63
+ *
64
+ * @param {import("../batch/reconcile.mjs").ReconciliationResult & Record<string, unknown>} reconcileResult
65
+ * @param {number} [observedAt]
66
+ */
67
+ export function buildWatchSnapshot(reconcileResult, observedAt = Date.now()) {
68
+ /** @type {Record<string, unknown>} */
69
+ const snapshot = {
70
+ observedAt,
71
+ diagnosis: reconcileResult.diagnosis ?? null,
72
+ batchId: reconcileResult.batchId ?? null,
73
+ phase: reconcileResult.phase ?? null,
74
+ macroPhase: reconcileResult.macroPhase ?? null,
75
+ macroPhaseLabel: reconcileResult.macroPhaseLabel ?? null,
76
+ headline: reconcileResult.headline,
77
+ suggestedCommand: reconcileResult.suggestedCommand,
78
+ };
79
+
80
+ if (reconcileResult.progress != null && typeof reconcileResult.progress === "object") {
81
+ snapshot.progress = reconcileResult.progress;
82
+ } else {
83
+ /** @type {Record<string, unknown>} */
84
+ const progress = {};
85
+ for (const field of PROGRESS_FIELD_NAMES) {
86
+ if (reconcileResult[field] != null) {
87
+ progress[field] = reconcileResult[field];
88
+ }
89
+ }
90
+ if (Object.keys(progress).length > 0) {
91
+ snapshot.progress = progress;
92
+ }
93
+ }
94
+
95
+ return snapshot;
96
+ }
97
+
98
+ /**
99
+ * @param {object} options
100
+ * @param {string} options.projectRoot
101
+ * @param {number} [options.intervalSec]
102
+ * @param {boolean} [options.json]
103
+ * @param {boolean} [options.once]
104
+ * @param {(ctx: { projectRoot: string }) => import("../batch/reconcile.mjs").ReconciliationResult} [options.reconcileFn]
105
+ * @param {(ms: number) => Promise<void>} [options.sleepFn]
106
+ * @param {() => number} [options.nowFn]
107
+ * @param {(text: string) => void} [options.writeStdout]
108
+ * @param {boolean} [options.isTTY]
109
+ */
110
+ export async function runSpineWatch(options) {
111
+ const {
112
+ projectRoot,
113
+ intervalSec = DEFAULT_WATCH_INTERVAL_SEC,
114
+ json = false,
115
+ once = false,
116
+ reconcileFn = reconcileBatch,
117
+ sleepFn = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
118
+ nowFn = () => Date.now(),
119
+ writeStdout = (text) => process.stdout.write(text),
120
+ isTTY = process.stdout.isTTY,
121
+ } = options;
122
+
123
+ let running = true;
124
+ const onSigInt = () => {
125
+ running = false;
126
+ };
127
+ process.on("SIGINT", onSigInt);
128
+
129
+ try {
130
+ do {
131
+ const result = reconcileFn({ projectRoot });
132
+ const snapshot = buildWatchSnapshot(result, nowFn());
133
+
134
+ if (json) {
135
+ writeStdout(`${JSON.stringify(snapshot)}\n`);
136
+ } else {
137
+ const line = formatWatchHumanLine(result);
138
+ if (isTTY && !once) {
139
+ writeStdout(`\r\x1b[K${line}`);
140
+ } else {
141
+ writeStdout(`${line}\n`);
142
+ }
143
+ }
144
+
145
+ if (once || !running) {
146
+ break;
147
+ }
148
+
149
+ await sleepFn(intervalSec * 1000);
150
+ } while (running);
151
+
152
+ if (!json && isTTY && !once) {
153
+ writeStdout("\n");
154
+ }
155
+
156
+ return { exitCode: 0 };
157
+ } finally {
158
+ process.off("SIGINT", onSigInt);
159
+ }
160
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Agent model/thinking pin resolution for reviewer spawns (issue #53 / SP-369).
3
+ */
4
+
5
+ /**
6
+ * @param {object} config
7
+ * @param {"plan"|"code"|"final"} reviewType
8
+ * @returns {string|null} Pin value or null to omit `--model`
9
+ */
10
+ export function resolveReviewerModelPin(config, reviewType) {
11
+ const reviewer = config?.agents?.reviewer;
12
+ if (!reviewer) return null;
13
+
14
+ const typePin = reviewer[reviewType]?.model;
15
+ if (typeof typePin === "string" && typePin.length > 0 && typePin !== "inherit") {
16
+ return typePin;
17
+ }
18
+
19
+ const topPin = reviewer.model;
20
+ if (typeof topPin === "string" && topPin.length > 0 && topPin !== "inherit") {
21
+ return topPin;
22
+ }
23
+
24
+ return null;
25
+ }
26
+
27
+ /**
28
+ * @param {object} config
29
+ * @param {"plan"|"code"|"final"} reviewType
30
+ * @returns {string|null} Pin value or null to omit `--thinking`
31
+ */
32
+ export function resolveReviewerThinkingPin(config, reviewType) {
33
+ const reviewer = config?.agents?.reviewer;
34
+ if (!reviewer) return null;
35
+
36
+ const typePin = reviewer[reviewType]?.thinking;
37
+ if (typeof typePin === "string" && typePin.length > 0) {
38
+ if (typePin === "off") return null;
39
+ if (typePin !== "inherit") return typePin;
40
+ }
41
+
42
+ const topPin = reviewer.thinking;
43
+ if (typeof topPin === "string" && topPin.length > 0 && topPin !== "inherit" && topPin !== "off") {
44
+ return topPin;
45
+ }
46
+
47
+ return null;
48
+ }
@@ -5,10 +5,11 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { execFileSync } from "node:child_process";
8
- import { randomBytes } from "node:crypto";
9
8
 
10
9
  import micromatch from "micromatch";
11
10
 
11
+ import { writeJsonAtomic } from "../../fs/atomic-write.mjs";
12
+
12
13
  import { parseCursorRuleFrontmatter } from "./parse-frontmatter.mjs";
13
14
  import { DEFAULT_RULES_PROFILE, loadRulesProfile } from "./profile.mjs";
14
15
 
@@ -175,26 +176,7 @@ function collectRuleFiles(rulesRootAbs, currentAbs = rulesRootAbs) {
175
176
  */
176
177
  export function writeRulesManifestAtomic(projectRoot, manifest) {
177
178
  const manifestPath = path.join(projectRoot, RULES_MANIFEST_REL_PATH);
178
- const dir = path.dirname(manifestPath);
179
- fs.mkdirSync(dir, { recursive: true });
180
-
181
- const tmpPath = `${manifestPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
182
- const content = `${JSON.stringify(manifest, null, 2)}\n`;
183
-
184
- try {
185
- fs.writeFileSync(tmpPath, content, "utf-8");
186
- fs.renameSync(tmpPath, manifestPath);
187
- } catch (err) {
188
- try {
189
- if (fs.existsSync(tmpPath)) {
190
- fs.unlinkSync(tmpPath);
191
- }
192
- } catch {
193
- // ignore cleanup failure
194
- }
195
- throw err;
196
- }
197
-
179
+ writeJsonAtomic(manifestPath, manifest);
198
180
  return manifestPath;
199
181
  }
200
182
 
@@ -27,10 +27,16 @@ export const CONTRACT_DEFAULTS = Object.freeze({
27
27
  legacyTaskIdPrefixes: Object.freeze(["TP-"]),
28
28
  });
29
29
 
30
- /** @type {Readonly<{ review: typeof REVIEW_DEFAULTS; handoff: typeof HANDOFF_DEFAULTS; metrics: typeof METRICS_DEFAULTS; contract: typeof CONTRACT_DEFAULTS }>} */
30
+ /** @type {Readonly<{ cleanupWorktreesOnComplete: boolean }>} */
31
+ export const LANES_DEFAULTS = Object.freeze({
32
+ cleanupWorktreesOnComplete: true,
33
+ });
34
+
35
+ /** @type {Readonly<{ review: typeof REVIEW_DEFAULTS; handoff: typeof HANDOFF_DEFAULTS; metrics: typeof METRICS_DEFAULTS; contract: typeof CONTRACT_DEFAULTS; lanes: typeof LANES_DEFAULTS }>} */
31
36
  export const CONFIG_V2_SECTION_DEFAULTS = Object.freeze({
32
37
  review: REVIEW_DEFAULTS,
33
38
  handoff: HANDOFF_DEFAULTS,
34
39
  metrics: METRICS_DEFAULTS,
35
40
  contract: CONTRACT_DEFAULTS,
41
+ lanes: LANES_DEFAULTS,
36
42
  });
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Model id validation and normalization (SP-422 / #76).
3
+ * Canonical pi model id format: `provider/model` (e.g. `google/gemini-3.1-pro-preview`).
4
+ * Pi TUI display labels use `model [provider]` (e.g. `gemini-3.1-pro-preview [google]`).
5
+ */
6
+
7
+ const DISPLAY_LABEL_RE = /^([a-z0-9][a-z0-9._-]*)\s+\[([a-z0-9][a-z0-9._-]*)\]$/i;
8
+ const CANONICAL_RE = /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/i;
9
+ const SPECIAL_VALUES = new Set(["inherit", ""]);
10
+
11
+ /**
12
+ * @param {string} value
13
+ * @returns {boolean}
14
+ */
15
+ export function isDisplayLabel(value) {
16
+ if (typeof value !== "string") return false;
17
+ return DISPLAY_LABEL_RE.test(value.trim());
18
+ }
19
+
20
+ /**
21
+ * Convert a pi TUI display label (`model [provider]`) to canonical `provider/model`.
22
+ * Returns null when the input does not match the display label pattern.
23
+ *
24
+ * @param {string} value
25
+ * @returns {string|null}
26
+ */
27
+ export function displayLabelToCanonical(value) {
28
+ if (typeof value !== "string") return null;
29
+ const match = value.trim().match(DISPLAY_LABEL_RE);
30
+ if (!match) return null;
31
+ return `${match[2]}/${match[1]}`;
32
+ }
33
+
34
+ /**
35
+ * @param {string} value
36
+ * @returns {boolean}
37
+ */
38
+ export function isCanonicalModelId(value) {
39
+ if (typeof value !== "string") return false;
40
+ return CANONICAL_RE.test(value.trim());
41
+ }
42
+
43
+ /**
44
+ * Normalize a model id for `spine settings set`.
45
+ * Display labels are converted to canonical form; canonical ids pass through;
46
+ * special values (`inherit`, empty) pass through.
47
+ *
48
+ * @param {string} value
49
+ * @returns {{ ok: true, value: string } | { ok: false, error: string }}
50
+ */
51
+ export function normalizeModelId(value) {
52
+ if (typeof value !== "string") {
53
+ return { ok: false, error: "Model id must be a string" };
54
+ }
55
+
56
+ const trimmed = value.trim();
57
+ if (SPECIAL_VALUES.has(trimmed)) {
58
+ return { ok: true, value: trimmed };
59
+ }
60
+
61
+ if (isCanonicalModelId(trimmed)) {
62
+ return { ok: true, value: trimmed };
63
+ }
64
+
65
+ const canonical = displayLabelToCanonical(trimmed);
66
+ if (canonical) {
67
+ return { ok: true, value: canonical };
68
+ }
69
+
70
+ return {
71
+ ok: false,
72
+ error: `Invalid model id "${trimmed}". Use canonical provider/model format (e.g. google/gemini-3.1-pro-preview). Run \`pi --list-models\` for available ids.`,
73
+ };
74
+ }
75
+
76
+ /**
77
+ * Validate that a model id already stored in config is canonical.
78
+ * Used by doctor checks — flags display labels and unrecognized formats.
79
+ *
80
+ * @param {string} value
81
+ * @returns {{ ok: true } | { ok: false, error: string, canonical?: string, suggestedCommand?: string }}
82
+ */
83
+ export function validateModelIdFormat(value) {
84
+ if (typeof value !== "string") return { ok: true };
85
+ const trimmed = value.trim();
86
+ if (SPECIAL_VALUES.has(trimmed)) return { ok: true };
87
+
88
+ if (isCanonicalModelId(trimmed)) return { ok: true };
89
+
90
+ const canonical = displayLabelToCanonical(trimmed);
91
+ if (canonical) {
92
+ return {
93
+ ok: false,
94
+ error: `display label "${trimmed}" — use canonical id ${canonical}`,
95
+ canonical,
96
+ };
97
+ }
98
+
99
+ return {
100
+ ok: false,
101
+ error: `invalid model id "${trimmed}" — expected provider/model format`,
102
+ };
103
+ }