pi-spine 1.0.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 (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +563 -0
  3. package/bin/get-version.mjs +35 -0
  4. package/bin/spine-batch.mjs +425 -0
  5. package/bin/spine-cli/batch.mjs +47 -0
  6. package/bin/spine-cli/gate.mjs +10 -0
  7. package/bin/spine-cli/integrate.mjs +10 -0
  8. package/bin/spine-cli/plan.mjs +12 -0
  9. package/bin/spine-cli/shared.mjs +73 -0
  10. package/bin/spine-cli/status.mjs +18 -0
  11. package/bin/spine-cli/verify.mjs +199 -0
  12. package/bin/spine-config.mjs +212 -0
  13. package/bin/spine-dashboard.mjs +178 -0
  14. package/bin/spine-deps.mjs +69 -0
  15. package/bin/spine-doctor.mjs +468 -0
  16. package/bin/spine-gate.mjs +137 -0
  17. package/bin/spine-init.mjs +398 -0
  18. package/bin/spine-integrate.mjs +77 -0
  19. package/bin/spine-journal.mjs +198 -0
  20. package/bin/spine-migrate-from-taskplane.mjs +136 -0
  21. package/bin/spine-plan.mjs +83 -0
  22. package/bin/spine-preflight.mjs +700 -0
  23. package/bin/spine-report-progress.d.mts +28 -0
  24. package/bin/spine-report-progress.mjs +126 -0
  25. package/bin/spine-review-step.d.mts +24 -0
  26. package/bin/spine-review-step.mjs +124 -0
  27. package/bin/spine-rules.mjs +35 -0
  28. package/bin/spine-settings.mjs +186 -0
  29. package/bin/spine-state.mjs +110 -0
  30. package/bin/spine-status.mjs +79 -0
  31. package/bin/spine-tasks.mjs +293 -0
  32. package/bin/spine-worker-runner.mjs +314 -0
  33. package/bin/spine.mjs +404 -0
  34. package/extensions/spine/settings-slash.ts +20 -0
  35. package/extensions/spine/slash-commands.ts +806 -0
  36. package/extensions/spine/worker-tools.ts +279 -0
  37. package/extensions/spine-orchestrator.ts +12 -0
  38. package/package.json +72 -0
  39. package/skills/.gitkeep +0 -0
  40. package/skills/create-spine-tasks/SKILL.md +375 -0
  41. package/skills/create-spine-tasks/references/context-template.md +25 -0
  42. package/skills/create-spine-tasks/references/contract-template.md +98 -0
  43. package/skills/create-spine-tasks/references/explore-template.md +63 -0
  44. package/skills/create-spine-tasks/references/prompt-template.md +276 -0
  45. package/src/batch/abort.mjs +272 -0
  46. package/src/batch/agent-session-worker.mjs +297 -0
  47. package/src/batch/batch-state-io.mjs +53 -0
  48. package/src/batch/contract-verify.mjs +310 -0
  49. package/src/batch/detached-start.mjs +778 -0
  50. package/src/batch/diagnosis.mjs +378 -0
  51. package/src/batch/engine-lanes/merge.mjs +632 -0
  52. package/src/batch/engine-lanes/queue.mjs +208 -0
  53. package/src/batch/engine-lanes/review.mjs +970 -0
  54. package/src/batch/engine-lanes.mjs +388 -0
  55. package/src/batch/engine-scope.mjs +251 -0
  56. package/src/batch/engine.mjs +445 -0
  57. package/src/batch/evidence-command.mjs +157 -0
  58. package/src/batch/evidence.mjs +203 -0
  59. package/src/batch/gate.mjs +359 -0
  60. package/src/batch/git-commit-env.mjs +46 -0
  61. package/src/batch/git-exec.mjs +26 -0
  62. package/src/batch/heartbeat.mjs +430 -0
  63. package/src/batch/integrate.mjs +414 -0
  64. package/src/batch/journal-rebuild.mjs +388 -0
  65. package/src/batch/journal.mjs +373 -0
  66. package/src/batch/lane-commit.mjs +153 -0
  67. package/src/batch/lifecycle.mjs +364 -0
  68. package/src/batch/metrics.mjs +265 -0
  69. package/src/batch/orphan-detect.mjs +210 -0
  70. package/src/batch/post-merge-limbo.mjs +80 -0
  71. package/src/batch/postmortem.mjs +296 -0
  72. package/src/batch/readers/spine-state.mjs +95 -0
  73. package/src/batch/readers/taskplane-state.mjs +136 -0
  74. package/src/batch/reconcile.mjs +729 -0
  75. package/src/batch/resume-common.mjs +104 -0
  76. package/src/batch/resume-engine.mjs +66 -0
  77. package/src/batch/resume-multi-lanes.mjs +479 -0
  78. package/src/batch/resume-multi-validate.mjs +187 -0
  79. package/src/batch/resume-multi.mjs +254 -0
  80. package/src/batch/resume.mjs +475 -0
  81. package/src/batch/retry.mjs +257 -0
  82. package/src/batch/review-scope.mjs +136 -0
  83. package/src/batch/review.mjs +1045 -0
  84. package/src/batch/salvage.mjs +332 -0
  85. package/src/batch/state.mjs +680 -0
  86. package/src/batch/task-stall-budget.mjs +88 -0
  87. package/src/batch/worker-host.mjs +683 -0
  88. package/src/batch/worker-output.mjs +253 -0
  89. package/src/batch/worker-prompt.mjs +84 -0
  90. package/src/batch/worktree.mjs +290 -0
  91. package/src/cli/deps.mjs +141 -0
  92. package/src/cli/handoff.mjs +364 -0
  93. package/src/cli/rules.mjs +429 -0
  94. package/src/cli/settings-set.mjs +171 -0
  95. package/src/cli/settings-show.mjs +140 -0
  96. package/src/cli/settings-slash.mjs +107 -0
  97. package/src/config/contract.mjs +56 -0
  98. package/src/config/cursor-rules/discover.mjs +416 -0
  99. package/src/config/cursor-rules/index.mjs +39 -0
  100. package/src/config/cursor-rules/match-globs.mjs +132 -0
  101. package/src/config/cursor-rules/parse-frontmatter.mjs +222 -0
  102. package/src/config/cursor-rules/priority.mjs +26 -0
  103. package/src/config/cursor-rules/profile.mjs +403 -0
  104. package/src/config/cursor-rules/select.mjs +259 -0
  105. package/src/config/defaults.mjs +36 -0
  106. package/src/config/env-overrides.mjs +207 -0
  107. package/src/config/merge-defaults.mjs +47 -0
  108. package/src/config/pi-spine-root.mjs +93 -0
  109. package/src/config/reviewer-context.mjs +243 -0
  110. package/src/config/settings-fields.mjs +265 -0
  111. package/src/config/worker-backend.mjs +116 -0
  112. package/src/config/worker-context.mjs +402 -0
  113. package/src/config/worker-launch-script.mjs +130 -0
  114. package/src/config/worktree-setup-hook.mjs +122 -0
  115. package/src/dashboard/public/dashboard.css +77 -0
  116. package/src/dashboard/public/dashboard.js +349 -0
  117. package/src/dashboard/public/index.html +80 -0
  118. package/src/dashboard/server.mjs +155 -0
  119. package/src/dashboard/snapshot.mjs +414 -0
  120. package/src/dashboard/sse.mjs +15 -0
  121. package/src/dashboard/view.mjs +292 -0
  122. package/src/doctor/agent-model-inherit.mjs +101 -0
  123. package/src/doctor/batch-size-guidance.mjs +72 -0
  124. package/src/doctor/coexistence.mjs +312 -0
  125. package/src/doctor/rules-manifest.mjs +133 -0
  126. package/src/doctor/stale-path.mjs +156 -0
  127. package/src/doctor/stall-config.mjs +108 -0
  128. package/src/doctor/suggest-max-parallel.mjs +53 -0
  129. package/src/doctor/task-packet-size.mjs +110 -0
  130. package/src/doctor/worktree-health.mjs +71 -0
  131. package/src/migrate/taskplane-config.mjs +116 -0
  132. package/src/planner/cycles.mjs +63 -0
  133. package/src/planner/format-plan.mjs +132 -0
  134. package/src/planner/graph.mjs +99 -0
  135. package/src/planner/index.mjs +125 -0
  136. package/src/planner/lanes.mjs +111 -0
  137. package/src/planner/pending.mjs +39 -0
  138. package/src/planner/scope.mjs +142 -0
  139. package/src/process/liveness.mjs +21 -0
  140. package/src/tasks/packet/discover.mjs +40 -0
  141. package/src/tasks/packet/index.mjs +81 -0
  142. package/src/tasks/packet/merge-deps.mjs +79 -0
  143. package/src/tasks/packet/parse-prompt.mjs +445 -0
  144. package/src/tasks/packet/parse-status.mjs +118 -0
  145. package/src/tasks/packet/validate-contract.mjs +115 -0
  146. package/src/tasks/packet/validate-prompt.mjs +99 -0
  147. package/src/worker-tools/report-progress.d.mts +18 -0
  148. package/src/worker-tools/report-progress.mjs +59 -0
  149. package/src/worker-tools/request-gate.d.mts +17 -0
  150. package/src/worker-tools/request-gate.mjs +54 -0
  151. package/templates/agents/reviewer.md +123 -0
  152. package/templates/agents/supervisor.md +59 -0
  153. package/templates/agents/worker.md +122 -0
  154. package/templates/rules-profile.json +27 -0
  155. package/templates/spine-config.json +64 -0
  156. package/templates/tasks/CONTEXT.md +30 -0
@@ -0,0 +1,373 @@
1
+ /**
2
+ * Append-only orchestration journal (FR-JRN, PRD §11).
3
+ */
4
+
5
+ import crypto from "node:crypto";
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+
9
+ export const JOURNAL_SCHEMA_VERSION = 1;
10
+ export const MAX_PAYLOAD_BYTES = 32 * 1024;
11
+
12
+ /**
13
+ * Batch-state fields rebuildable from journal without cache seed (FR-SHIP-10, PRD §11.4 v2.2).
14
+ * Other schema fields (e.g. taskFolder, resilience) may still fall back to cache or filesystem.
15
+ */
16
+ export const JOURNAL_DERIVED_STRUCTURAL_FIELDS = Object.freeze([
17
+ "batchId",
18
+ "baseBranch",
19
+ "orchBranch",
20
+ "startedAt",
21
+ "wavePlan",
22
+ "totalWaves",
23
+ "lanes",
24
+ "tasks",
25
+ "segments",
26
+ "totalTasks",
27
+ "mergeResults",
28
+ ]);
29
+
30
+ /** Journal event types scanned when deriving structural batch-state rows. */
31
+ export const STRUCTURAL_JOURNAL_EVENT_TYPES = Object.freeze(
32
+ new Set([
33
+ "batch.started",
34
+ "batch.resumed",
35
+ "lane.provisioned",
36
+ "lane.tasks_serialized",
37
+ "task.started",
38
+ "task.skipped_done_on_disk",
39
+ "batch.merge_started",
40
+ "batch.merge_completed",
41
+ "lane.committed",
42
+ ]),
43
+ );
44
+
45
+ const META_KEYS = new Set(["correlationId", "laneId", "laneNumber", "taskId", "payload"]);
46
+
47
+ const REDACT_KEY_PATTERN = /key|token|secret|password/i;
48
+
49
+ /**
50
+ * @param {string} projectRoot
51
+ * @param {string} batchId
52
+ */
53
+ export function journalPath(projectRoot, batchId) {
54
+ return path.join(projectRoot, ".spine", "runtime", batchId, "journal", "events.jsonl");
55
+ }
56
+
57
+ /**
58
+ * @param {unknown} value
59
+ * @returns {unknown}
60
+ */
61
+ export function redactSecrets(value) {
62
+ if (value == null || typeof value !== "object") return value;
63
+
64
+ if (Array.isArray(value)) {
65
+ return value.map((entry) => redactSecrets(entry));
66
+ }
67
+
68
+ /** @type {Record<string, unknown>} */
69
+ const out = {};
70
+ for (const [key, entry] of Object.entries(/** @type {Record<string, unknown>} */ (value))) {
71
+ if (REDACT_KEY_PATTERN.test(key)) {
72
+ out[key] = "[REDACTED]";
73
+ } else if (entry && typeof entry === "object") {
74
+ out[key] = redactSecrets(entry);
75
+ } else {
76
+ out[key] = entry;
77
+ }
78
+ }
79
+ return out;
80
+ }
81
+
82
+ /**
83
+ * @param {Record<string, unknown>} payload
84
+ */
85
+ export function capPayloadSize(payload) {
86
+ let serialized = JSON.stringify(payload);
87
+ if (Buffer.byteLength(serialized, "utf-8") <= MAX_PAYLOAD_BYTES) {
88
+ return payload;
89
+ }
90
+
91
+ const truncated = {
92
+ _truncated: true,
93
+ _originalBytes: Buffer.byteLength(serialized, "utf-8"),
94
+ _maxBytes: MAX_PAYLOAD_BYTES,
95
+ preview: serialized.slice(0, MAX_PAYLOAD_BYTES - 256),
96
+ };
97
+ return truncated;
98
+ }
99
+
100
+ /**
101
+ * @param {Record<string, unknown>} options
102
+ */
103
+ function extractPayload(options) {
104
+ if (options.payload && typeof options.payload === "object" && !Array.isArray(options.payload)) {
105
+ return { .../** @type {Record<string, unknown>} */ (options.payload) };
106
+ }
107
+
108
+ /** @type {Record<string, unknown>} */
109
+ const payload = {};
110
+ for (const [key, value] of Object.entries(options)) {
111
+ if (!META_KEYS.has(key)) payload[key] = value;
112
+ }
113
+ return payload;
114
+ }
115
+
116
+ /**
117
+ * @param {Record<string, unknown>} options
118
+ */
119
+ function resolveLaneId(options) {
120
+ if (typeof options.laneId === "string" && options.laneId) return options.laneId;
121
+ if (options.laneNumber != null) return `lane-${options.laneNumber}`;
122
+ return undefined;
123
+ }
124
+
125
+ /**
126
+ * @param {object} line
127
+ * @returns {object}
128
+ */
129
+ export function normalizeJournalEvent(line) {
130
+ if (!line || typeof line !== "object") return line;
131
+
132
+ if (line.schemaVersion === JOURNAL_SCHEMA_VERSION) {
133
+ return line;
134
+ }
135
+
136
+ /** @type {Record<string, unknown>} */
137
+ const legacy = /** @type {Record<string, unknown>} */ (line);
138
+ const { type, batchId, timestamp, correlationId, laneId, taskId, ...rest } = legacy;
139
+
140
+ let isoTimestamp;
141
+ if (typeof timestamp === "number") {
142
+ isoTimestamp = new Date(timestamp).toISOString();
143
+ } else if (typeof timestamp === "string") {
144
+ isoTimestamp = timestamp;
145
+ } else {
146
+ isoTimestamp = new Date().toISOString();
147
+ }
148
+
149
+ return {
150
+ schemaVersion: JOURNAL_SCHEMA_VERSION,
151
+ eventId: typeof legacy.eventId === "string" ? legacy.eventId : `legacy-${isoTimestamp}`,
152
+ type,
153
+ timestamp: isoTimestamp,
154
+ batchId,
155
+ correlationId: typeof correlationId === "string" ? correlationId : undefined,
156
+ laneId: typeof laneId === "string" ? laneId : resolveLaneId(legacy),
157
+ taskId: typeof taskId === "string" ? taskId : undefined,
158
+ payload: rest,
159
+ _legacy: true,
160
+ };
161
+ }
162
+
163
+ /**
164
+ * @param {string} projectRoot
165
+ * @param {string} batchId
166
+ * @param {string} type
167
+ * @param {Record<string, unknown>} [options]
168
+ */
169
+ export function appendJournalEvent(projectRoot, batchId, type, options = {}) {
170
+ const filePath = journalPath(projectRoot, batchId);
171
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
172
+
173
+ const rawPayload = extractPayload(options);
174
+ const payload = capPayloadSize(redactSecrets(rawPayload));
175
+
176
+ const entry = {
177
+ schemaVersion: JOURNAL_SCHEMA_VERSION,
178
+ eventId: crypto.randomUUID(),
179
+ type,
180
+ timestamp: new Date().toISOString(),
181
+ batchId,
182
+ payload,
183
+ };
184
+
185
+ const correlationId = options.correlationId;
186
+ if (typeof correlationId === "string" && correlationId) {
187
+ entry.correlationId = correlationId;
188
+ }
189
+
190
+ const laneId = resolveLaneId(options);
191
+ if (laneId) entry.laneId = laneId;
192
+
193
+ const taskId = options.taskId;
194
+ if (typeof taskId === "string" && taskId) entry.taskId = taskId;
195
+
196
+ const line = `${JSON.stringify(entry)}\n`;
197
+ fs.appendFileSync(filePath, line, "utf-8");
198
+
199
+ const fd = fs.openSync(filePath, "r+");
200
+ try {
201
+ fs.fsyncSync(fd);
202
+ } finally {
203
+ fs.closeSync(fd);
204
+ }
205
+
206
+ return entry;
207
+ }
208
+
209
+ /**
210
+ * @param {string} projectRoot
211
+ * @param {string} batchId
212
+ * @param {{ handoffPath: string, diagnosis: string, batchId?: string }} payload
213
+ */
214
+ export function recordHandoffWritten(projectRoot, batchId, payload) {
215
+ return appendJournalEvent(projectRoot, batchId, "handoff.written", payload);
216
+ }
217
+
218
+ /**
219
+ * @param {string} projectRoot
220
+ * @param {string} batchId
221
+ * @returns {string|null} Raw jsonl journal content, or null when the file is missing.
222
+ */
223
+ export function exportJournalJsonl(projectRoot, batchId) {
224
+ const filePath = journalPath(projectRoot, batchId);
225
+ if (!fs.existsSync(filePath)) return null;
226
+ return fs.readFileSync(filePath, "utf-8");
227
+ }
228
+
229
+ /**
230
+ * @param {string} projectRoot
231
+ * @param {string} batchId
232
+ * @returns {object[]}
233
+ */
234
+ export function readJournalEvents(projectRoot, batchId) {
235
+ const filePath = journalPath(projectRoot, batchId);
236
+ if (!fs.existsSync(filePath)) return [];
237
+
238
+ return fs
239
+ .readFileSync(filePath, "utf-8")
240
+ .split("\n")
241
+ .filter(Boolean)
242
+ .map((line) => normalizeJournalEvent(JSON.parse(line)));
243
+ }
244
+
245
+ /**
246
+ * @param {object[]} events
247
+ * @param {number} [limit]
248
+ */
249
+ export function readJournalTail(events, limit = 50) {
250
+ if (events.length <= limit) return events;
251
+ return events.slice(-limit);
252
+ }
253
+
254
+ /**
255
+ * @param {string} projectRoot
256
+ * @param {string} batchId
257
+ * @returns {object|null}
258
+ */
259
+ export function readLastTaskFailedEvent(projectRoot, batchId) {
260
+ const events = readJournalEvents(projectRoot, batchId);
261
+ for (let index = events.length - 1; index >= 0; index -= 1) {
262
+ if (events[index].type === "task.failed") return events[index];
263
+ }
264
+ return null;
265
+ }
266
+
267
+ /**
268
+ * @param {object} event
269
+ */
270
+ export function summarizeJournalEvent(event) {
271
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
272
+ const parts = [];
273
+
274
+ if (payload.reason) parts.push(String(payload.reason));
275
+ if (payload.error) parts.push(String(payload.error).slice(0, 80));
276
+ if (payload.classification) parts.push(String(payload.classification));
277
+ if (payload.workerPhase) parts.push(`phase ${payload.workerPhase}`);
278
+ if (payload.workerOutputLogRef) parts.push(`→ ${payload.workerOutputLogRef}`);
279
+ if (payload.exitReason) parts.push(String(payload.exitReason));
280
+ if (payload.mergeCommit) parts.push(`merge ${String(payload.mergeCommit).slice(0, 8)}`);
281
+ if (payload.baseBranch && payload.orchBranch) {
282
+ parts.push(`${payload.baseBranch} → ${payload.orchBranch}`);
283
+ }
284
+ if (payload.worktreePath) parts.push(String(payload.worktreePath).split("/").slice(-2).join("/"));
285
+ if (payload.verdict) parts.push(String(payload.verdict));
286
+ if (payload.reviewType) parts.push(`${payload.reviewType} review`);
287
+ if (payload.diagnosis) parts.push(String(payload.diagnosis));
288
+ if (payload.stallDeadline) parts.push(`stall deadline ${payload.stallDeadline}`);
289
+ if (payload.logPath) parts.push(`→ ${payload.logPath}`);
290
+ if (payload.changedFileCount != null) {
291
+ parts.push(`${payload.changedFileCount} scoped file(s)`);
292
+ }
293
+ if (payload.commitSha) parts.push(`commit ${String(payload.commitSha).slice(0, 8)}`);
294
+ if (payload.reason && payload.refused) parts.push(`refused: ${payload.reason}`);
295
+ if (payload.retryCommand) parts.push(String(payload.retryCommand));
296
+ if (payload.recommendedAction && !payload.retryCommand) {
297
+ parts.push(String(payload.recommendedAction));
298
+ }
299
+ if (Array.isArray(payload.dirtyPaths) && payload.dirtyPaths.length > 0) {
300
+ const listed = payload.dirtyPaths.slice(0, 3).join(", ");
301
+ const more =
302
+ payload.dirtyPaths.length > 3 ? ` (+${payload.dirtyPaths.length - 3} more)` : "";
303
+ parts.push(`dirty: ${listed}${more}`);
304
+ }
305
+ if (payload.suggestion) parts.push(String(payload.suggestion).slice(0, 80));
306
+ if (payload.mode === "auto" || payload.mode === "static") {
307
+ const count = payload.pathCount ?? payload.paths?.length;
308
+ if (count != null) parts.push(`${count} rule path(s)`);
309
+ if (payload.manifestSource) parts.push(`manifest ${payload.manifestSource}`);
310
+ }
311
+ if (payload.capped) parts.push("selection capped");
312
+
313
+ if (parts.length === 0 && Object.keys(payload).length > 0) {
314
+ const preview = JSON.stringify(payload);
315
+ return preview.length > 60 ? `${preview.slice(0, 57)}…` : preview;
316
+ }
317
+
318
+ return parts.join("; ") || "—";
319
+ }
320
+
321
+ /**
322
+ * @param {object[]} events
323
+ */
324
+ const JOURNAL_HINT_RECENT_MS = 30 * 60 * 1000;
325
+
326
+ /**
327
+ * @param {string|undefined} timestamp
328
+ */
329
+ function isRecentJournalHint(timestamp) {
330
+ if (!timestamp) return false;
331
+ const ts = Date.parse(timestamp);
332
+ if (Number.isNaN(ts)) return false;
333
+ return Date.now() - ts < JOURNAL_HINT_RECENT_MS;
334
+ }
335
+
336
+ /**
337
+ * @param {object[]} events
338
+ */
339
+ export function extractJournalDiagnosisHints(events) {
340
+ const tail = readJournalTail(events);
341
+ const hints = [];
342
+
343
+ const priority = [
344
+ "batch.failed",
345
+ "batch.merge_blocked",
346
+ "task.failed",
347
+ "lane.setup_hook.failed",
348
+ "lane.stall_killed",
349
+ "review.failed",
350
+ "lane.salvage_inspection",
351
+ "lane.salvage_commit",
352
+ "lane.checkpoint_warning",
353
+ "lane.stall_warning",
354
+ "lane.died",
355
+ ];
356
+ for (const type of priority) {
357
+ const match = [...tail].reverse().find((event) => {
358
+ if (event.type !== type) return false;
359
+ if (type === "lane.checkpoint_warning") return isRecentJournalHint(event.timestamp);
360
+ return true;
361
+ });
362
+ if (match) {
363
+ hints.push({
364
+ type: match.type,
365
+ timestamp: match.timestamp,
366
+ summary: summarizeJournalEvent(match),
367
+ eventId: match.eventId,
368
+ });
369
+ }
370
+ }
371
+
372
+ return hints;
373
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Auto-commit lane worktree before merge (TP-015, FR-WORK-02/03).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { execFileSync } from "node:child_process";
8
+ import { gitExec } from "./git-exec.mjs";
9
+
10
+ /**
11
+ * @param {string} worktreePath
12
+ * @param {string[]} args
13
+ * @param {string} [projectRoot]
14
+ */
15
+ function git(worktreePath, args, projectRoot) {
16
+ return gitExec(worktreePath, args, { projectRoot: projectRoot ?? worktreePath });
17
+ }
18
+
19
+ /**
20
+ * @param {string} worktreePath
21
+ */
22
+ export function gitPorcelain(worktreePath) {
23
+ if (process.env.SPINE_TEST_GIT_PORCELAIN_THROW === "after_commit") {
24
+ process.env.SPINE_TEST_GIT_PORCELAIN_THROW = "throw";
25
+ return "";
26
+ }
27
+ if (process.env.SPINE_TEST_GIT_PORCELAIN_THROW === "throw") {
28
+ throw new Error("git status failure: not a git repository");
29
+ }
30
+
31
+ return execFileSync("git", ["status", "--porcelain"], {
32
+ cwd: worktreePath,
33
+ encoding: "utf-8",
34
+ stdio: ["ignore", "pipe", "pipe"],
35
+ }).trim();
36
+ }
37
+
38
+ /**
39
+ * @param {string} line
40
+ * @returns {string | null}
41
+ */
42
+ function extractPorcelainPath(line) {
43
+ if (!line.trim()) return null;
44
+ let filePath = line.length > 2 && line[2] === " " ? line.slice(3) : line.slice(2);
45
+ filePath = filePath.trim();
46
+ if (!filePath) return null;
47
+ if (filePath.includes(" -> ")) {
48
+ return filePath.split(" -> ").pop()?.trim() ?? null;
49
+ }
50
+ return filePath;
51
+ }
52
+
53
+ /**
54
+ * @param {string} filePath
55
+ * @param {string} pattern
56
+ */
57
+ function pathMatchesIgnorePattern(filePath, pattern) {
58
+ if (!pattern || typeof pattern !== "string") return false;
59
+ const normalizedPattern = pattern.replace(/\\/g, "/");
60
+ const normalizedPath = filePath.replace(/\\/g, "/");
61
+ if (normalizedPath === normalizedPattern) return true;
62
+ return path.posix.basename(normalizedPath) === normalizedPattern;
63
+ }
64
+
65
+ /**
66
+ * Drop porcelain lines whose path matches any ignore pattern (basename or full path).
67
+ *
68
+ * @param {string} porcelain
69
+ * @param {string[]} ignorePatterns
70
+ */
71
+ export function filterPorcelain(porcelain, ignorePatterns) {
72
+ if (!porcelain?.trim()) return "";
73
+ if (!Array.isArray(ignorePatterns) || ignorePatterns.length === 0) {
74
+ return porcelain;
75
+ }
76
+
77
+ const kept = [];
78
+ for (const line of porcelain.split("\n")) {
79
+ if (!line.trim()) continue;
80
+ const filePath = extractPorcelainPath(line);
81
+ if (!filePath) {
82
+ kept.push(line);
83
+ continue;
84
+ }
85
+ const ignored = ignorePatterns.some((pattern) => pathMatchesIgnorePattern(filePath, pattern));
86
+ if (!ignored) kept.push(line);
87
+ }
88
+ return kept.length === 0 ? "" : kept.join("\n");
89
+ }
90
+
91
+ /**
92
+ * Commits on `headRef` not reachable from `baseRef`.
93
+ *
94
+ * @param {string} projectRoot
95
+ * @param {string} baseRef
96
+ * @param {string} headRef
97
+ */
98
+ export function countCommitsAhead(projectRoot, baseRef, headRef) {
99
+ const count = execFileSync("git", ["rev-list", "--count", `${baseRef}..${headRef}`], {
100
+ cwd: projectRoot,
101
+ encoding: "utf-8",
102
+ stdio: ["ignore", "pipe", "pipe"],
103
+ }).trim();
104
+ return Number.parseInt(count, 10) || 0;
105
+ }
106
+
107
+ /**
108
+ * Stage and commit uncommitted lane work when the worker left a `.DONE` marker.
109
+ *
110
+ * @param {object} params
111
+ * @param {string} params.worktreePath
112
+ * @param {string} params.taskBranch
113
+ * @param {string} params.taskId
114
+ * @param {string} params.batchId
115
+ * @param {string} params.taskFolder Absolute path to task folder (for `.DONE` check)
116
+ * @param {string} [params.projectRoot] Main repo root for git identity resolution
117
+ * @returns {{ ok: true, committed: boolean, commitSha?: string } | { ok: false, error: string, failureClass: string }}
118
+ */
119
+ export function commitLaneWorktree({ worktreePath, taskBranch, taskId, batchId, taskFolder, projectRoot }) {
120
+ const identityRoot = projectRoot ?? worktreePath;
121
+ try {
122
+ const porcelain = gitPorcelain(worktreePath);
123
+ if (!porcelain) {
124
+ return { ok: true, committed: false };
125
+ }
126
+
127
+ const donePath = path.join(taskFolder, ".DONE");
128
+ if (!fs.existsSync(donePath)) {
129
+ return {
130
+ ok: false,
131
+ error: `Lane worktree has uncommitted changes but ${path.basename(taskFolder)}/.DONE is missing — worker did not finish cleanly`,
132
+ failureClass: "DirtyWorktree",
133
+ };
134
+ }
135
+
136
+ const currentBranch = git(worktreePath, ["rev-parse", "--abbrev-ref", "HEAD"], identityRoot);
137
+ if (currentBranch !== taskBranch) {
138
+ git(worktreePath, ["checkout", taskBranch], identityRoot);
139
+ }
140
+ git(worktreePath, ["add", "-A"], identityRoot);
141
+ const message = `feat(${taskId}): batch ${batchId} worker completion`;
142
+ git(worktreePath, ["commit", "-m", message], identityRoot);
143
+ const commitSha = git(worktreePath, ["rev-parse", "HEAD"], identityRoot);
144
+ return { ok: true, committed: true, commitSha };
145
+ } catch (err) {
146
+ const message = err instanceof Error ? err.message : String(err);
147
+ return {
148
+ ok: false,
149
+ error: `Failed to commit lane worktree: ${message}`,
150
+ failureClass: "DirtyWorktree",
151
+ };
152
+ }
153
+ }