pi-spine 1.1.0 → 1.2.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 (102) hide show
  1. package/bin/spine-batch.mjs +160 -53
  2. package/bin/spine-cli/batch.mjs +3 -3
  3. package/bin/spine-cli/lane-logs.mjs +24 -0
  4. package/bin/spine-cli/scenarios.mjs +298 -0
  5. package/bin/spine-cli/wait.mjs +30 -0
  6. package/bin/spine-cli/watch.mjs +27 -0
  7. package/bin/spine-issue.mjs +196 -0
  8. package/bin/spine-journal.mjs +1 -0
  9. package/bin/spine-run.mjs +30 -0
  10. package/bin/spine-status.mjs +19 -1
  11. package/bin/spine-tasks.mjs +16 -2
  12. package/bin/spine-worker-runner.mjs +10 -10
  13. package/bin/spine.mjs +49 -1
  14. package/package.json +1 -1
  15. package/skills/create-spine-tasks/references/contract-template.md +19 -0
  16. package/src/batch/abort.mjs +2 -11
  17. package/src/batch/agent-session-worker.mjs +45 -5
  18. package/src/batch/attached-engine-handoff.mjs +188 -0
  19. package/src/batch/attached-runner.mjs +312 -0
  20. package/src/batch/contract-prelanded.mjs +180 -0
  21. package/src/batch/contract-verify.mjs +140 -2
  22. package/src/batch/detached-start.mjs +66 -2
  23. package/src/batch/diagnosis-alternatives.mjs +46 -0
  24. package/src/batch/diagnosis-merge-failure.mjs +79 -0
  25. package/src/batch/diagnosis-retry-limbo.mjs +34 -0
  26. package/src/batch/diagnosis-stub.mjs +109 -0
  27. package/src/batch/diagnosis-task-done.mjs +110 -0
  28. package/src/batch/diagnosis-worker-done-missing.mjs +96 -0
  29. package/src/batch/diagnosis.mjs +135 -68
  30. package/src/batch/engine-lanes/merge.mjs +110 -82
  31. package/src/batch/engine-lanes/queue.mjs +4 -1
  32. package/src/batch/engine-lanes/watch.mjs +29 -0
  33. package/src/batch/engine-lanes.mjs +1 -0
  34. package/src/batch/engine-scope.mjs +11 -1
  35. package/src/batch/engine.mjs +79 -24
  36. package/src/batch/evidence.mjs +78 -15
  37. package/src/batch/gate.mjs +43 -14
  38. package/src/batch/git-helpers.mjs +96 -0
  39. package/src/batch/heartbeat.mjs +73 -7
  40. package/src/batch/integrate.mjs +2 -4
  41. package/src/batch/journal.mjs +3 -0
  42. package/src/batch/lane-commit.mjs +90 -5
  43. package/src/batch/lifecycle.mjs +130 -3
  44. package/src/batch/macro-phase.mjs +226 -0
  45. package/src/batch/merge/adoption-doc-merge.mjs +93 -10
  46. package/src/batch/merge/wave-merge-state.mjs +3 -0
  47. package/src/batch/metrics.mjs +74 -5
  48. package/src/batch/orphan-detect.mjs +74 -0
  49. package/src/batch/pause.mjs +223 -0
  50. package/src/batch/post-merge-limbo.mjs +264 -8
  51. package/src/batch/reconcile.mjs +429 -54
  52. package/src/batch/resume-common.mjs +5 -1
  53. package/src/batch/resume-lane-reviews.mjs +16 -0
  54. package/src/batch/resume-multi-lanes.mjs +56 -1
  55. package/src/batch/resume-multi-validate.mjs +67 -6
  56. package/src/batch/resume-multi.mjs +9 -4
  57. package/src/batch/resume.mjs +52 -45
  58. package/src/batch/retry.mjs +56 -5
  59. package/src/batch/review-spawn.mjs +8 -2
  60. package/src/batch/rules-manifest-drift.mjs +157 -0
  61. package/src/batch/salvage.mjs +2 -1
  62. package/src/batch/sequence.mjs +454 -0
  63. package/src/batch/state.mjs +18 -3
  64. package/src/batch/status-json.mjs +67 -0
  65. package/src/batch/task-stall-budget.mjs +22 -10
  66. package/src/batch/worker-host.mjs +95 -7
  67. package/src/batch/worker-output.mjs +196 -3
  68. package/src/cli/issue-draft.mjs +180 -0
  69. package/src/cli/journal-follow.mjs +239 -0
  70. package/src/cli/lane-logs.mjs +291 -0
  71. package/src/cli/sequence.mjs +108 -0
  72. package/src/cli/settings-set.mjs +2 -21
  73. package/src/cli/wait.mjs +187 -0
  74. package/src/cli/watch.mjs +160 -0
  75. package/src/config/agent-model-resolve.mjs +48 -0
  76. package/src/config/cursor-rules/discover.mjs +3 -21
  77. package/src/config/defaults.mjs +7 -1
  78. package/src/config/settings-fields.mjs +48 -0
  79. package/src/config/spine-init-constants.mjs +1 -0
  80. package/src/config/spine-preflight-lib.mjs +471 -16
  81. package/src/dashboard/lane-throughput.mjs +351 -0
  82. package/src/dashboard/public/dashboard.css +25 -1
  83. package/src/dashboard/public/dashboard.js +223 -18
  84. package/src/dashboard/public/index.html +14 -2
  85. package/src/dashboard/server.mjs +4 -0
  86. package/src/dashboard/snapshot.mjs +215 -1
  87. package/src/dashboard/view.mjs +170 -17
  88. package/src/doctor/agent-model-inherit.mjs +61 -6
  89. package/src/doctor/run-doctor-checks.mjs +26 -1
  90. package/src/doctor/sequence-safety.mjs +57 -0
  91. package/src/doctor/stale-worktrees.mjs +102 -0
  92. package/src/fixtures/scenario-registry.mjs +194 -0
  93. package/src/fs/atomic-write.mjs +49 -0
  94. package/src/planner/file-scope.mjs +246 -0
  95. package/src/planner/format-plan.mjs +9 -7
  96. package/src/planner/index.mjs +6 -2
  97. package/src/planner/wave-scope.mjs +136 -0
  98. package/src/planner/waves.mjs +133 -0
  99. package/src/tasks/packet/index.mjs +1 -0
  100. package/src/tasks/packet/parse-prompt.mjs +42 -1
  101. package/src/tasks/packet/validate-prompt.mjs +124 -0
  102. package/templates/spine-config.json +8 -1
@@ -15,19 +15,25 @@ import {
15
15
  computeStallDeadline,
16
16
  recordCheckpointWarning,
17
17
  recordLaneHeartbeat,
18
+ recordLaneProgressSnapshot,
18
19
  recordStallWarning,
19
20
  resolveHeartbeatKind,
20
21
  shouldEmitCheckpointWarning,
22
+ shouldEmitProgressSnapshot,
23
+ buildProgressSnapshotPayload,
24
+ progressSnapshotPayloadChanged,
21
25
  } from "./heartbeat.mjs";
22
26
  import {
23
27
  resolveStallConfigForTask,
24
28
  resolveWorkerPiTimeoutMs,
25
29
  parseTaskSizeFromFolder,
26
30
  } from "./task-stall-budget.mjs";
31
+ import { parseContract } from "../tasks/packet/parse-prompt.mjs";
27
32
  import { appendJournalEvent } from "./journal.mjs";
28
33
  import { assertReviewToolAvailable } from "./review.mjs";
29
34
  import { startAgentSessionWorker } from "./agent-session-worker.mjs";
30
- import { finalizeWorkerOutput } from "./worker-output.mjs";
35
+ import { finalizeWorkerOutput, createWorkerLiveLogWriter } from "./worker-output.mjs";
36
+ import { nextStallAnchorAt } from "./engine-lanes/watch.mjs";
31
37
  import { resolveWorkerBackend } from "../config/worker-backend.mjs";
32
38
  import { commandExists } from "../util/command-exists.mjs";
33
39
  import { resolvePiSpineRoot } from "../config/pi-spine-root.mjs";
@@ -39,6 +45,34 @@ const PACKAGE_ROOT = path.resolve(__dirname, "../..");
39
45
  const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
40
46
  const POST_DONE_KILL_BACKOFF_MS = 5_000;
41
47
 
48
+ /**
49
+ * Force-terminate lane worker processes tracked in batch state.
50
+ *
51
+ * @param {unknown[]} lanes
52
+ * @param {{ hard?: boolean }} [options]
53
+ * @returns {Array<{ laneNumber: number, workerPid: number, signal: NodeJS.Signals }>}
54
+ */
55
+ export function terminateLaneWorkers(lanes, { hard = true } = {}) {
56
+ const signal = hard ? "SIGKILL" : "SIGTERM";
57
+ /** @type {Array<{ laneNumber: number, workerPid: number, signal: NodeJS.Signals }>} */
58
+ const terminated = [];
59
+ for (const lane of lanes ?? []) {
60
+ if (!lane || typeof lane !== "object") continue;
61
+ const workerPid = Number(/** @type {{ workerPid?: number }} */ (lane).workerPid);
62
+ if (!Number.isFinite(workerPid) || workerPid <= 0) continue;
63
+ const laneNumber = Number(
64
+ /** @type {{ laneNumber?: number }} */ (lane).laneNumber ?? 1,
65
+ );
66
+ try {
67
+ process.kill(workerPid, signal);
68
+ terminated.push({ laneNumber, workerPid, signal });
69
+ } catch {
70
+ // process may already be gone
71
+ }
72
+ }
73
+ return terminated;
74
+ }
75
+
42
76
  /** @typedef {"launching" | "pi" | "verify" | "unknown"} WorkerPhase */
43
77
 
44
78
  /**
@@ -105,6 +139,7 @@ export function buildWorkerChildEnv({
105
139
  PI_SPINE_ROOT: resolvePiSpineRoot(config, projectRoot ?? process.cwd()),
106
140
  };
107
141
  if (projectRoot) env.SPINE_PROJECT_ROOT = projectRoot;
142
+ if (worktreePath) env.SPINE_RULES_PROJECT_ROOT = worktreePath;
108
143
  if (batchId) {
109
144
  env.SPINE_BATCH_ID = batchId;
110
145
  env.SPINE_JOURNAL_ATTACH = "1";
@@ -294,8 +329,9 @@ async function terminateHungWorkerChild(child, childDone) {
294
329
 
295
330
  /**
296
331
  * @param {WorkerChildHandle} child
332
+ * @param {{ append: (rawChunk: string) => void } | null} [liveLogWriter]
297
333
  */
298
- function collectChildOutput(child) {
334
+ function collectChildOutput(child, liveLogWriter) {
299
335
  if ("wait" in child && typeof child.wait === "function") {
300
336
  return child.wait();
301
337
  }
@@ -303,10 +339,14 @@ function collectChildOutput(child) {
303
339
  let stdout = "";
304
340
  let stderr = "";
305
341
  child.stdout?.on("data", (/** @type {Buffer | string} */ chunk) => {
306
- stdout += chunk.toString();
342
+ const text = chunk.toString();
343
+ stdout += text;
344
+ liveLogWriter?.append(text);
307
345
  });
308
346
  child.stderr?.on("data", (/** @type {Buffer | string} */ chunk) => {
309
- stderr += chunk.toString();
347
+ const text = chunk.toString();
348
+ stderr += text;
349
+ liveLogWriter?.append(text);
310
350
  });
311
351
  child.on?.("close", (/** @type {number | null} */ code) => {
312
352
  resolve({ exitCode: code ?? 1, output: `${stdout}${stderr}` });
@@ -459,11 +499,18 @@ export async function runWorker({
459
499
  }
460
500
 
461
501
  const taskSize = parseTaskSizeFromFolder(taskFolder);
462
- const stallConfig = resolveStallConfigForTask({ config, taskSize });
463
- const piTimeoutMs = resolveWorkerPiTimeoutMs({ config, taskSize });
502
+ const promptPath = path.join(taskFolder, "PROMPT.md");
503
+ const contract = fs.existsSync(promptPath)
504
+ ? parseContract(fs.readFileSync(promptPath, "utf-8"))
505
+ : { stallTimeoutMinutes: null, extendGraceOnFileScope: null };
506
+ const stallConfig = resolveStallConfigForTask({ config, taskSize, contract });
507
+ const piTimeoutMs = resolveWorkerPiTimeoutMs({ config, taskSize, contract });
464
508
  const startedAt = Date.now();
509
+ let stallAnchorAt = startedAt;
465
510
  let lastCheckpointAt = startedAt;
466
511
  let lastHeartbeatAt = 0;
512
+ let lastProgressSnapshotAt = 0;
513
+ let lastSnapshotPayload = null;
467
514
  let lastSignals = null;
468
515
  let activitySinceCheckpoint = false;
469
516
  let checkpointWarningSent = false;
@@ -494,7 +541,14 @@ export async function runWorker({
494
541
  childPastPreflight = true;
495
542
  });
496
543
  onWorkerPid?.(workerChild.pid ?? 0);
497
- const childDone = collectChildOutput(workerChild);
544
+ const liveLogWriter = createWorkerLiveLogWriter({
545
+ projectRoot,
546
+ batchId,
547
+ laneNumber,
548
+ taskId,
549
+ config,
550
+ });
551
+ const childDone = collectChildOutput(workerChild, liveLogWriter);
498
552
 
499
553
  while (true) {
500
554
  const doneOnDisk = fs.existsSync(donePath);
@@ -562,10 +616,12 @@ export async function runWorker({
562
616
  }));
563
617
  const nextWorkerPhase = resolveWorkerPhase({ childPastPreflight, useStub, workerBackend });
564
618
  if (nextWorkerPhase !== "launching" && workerPhase === "launching") {
619
+ stallAnchorAt = now;
565
620
  lastCheckpointAt = now;
566
621
  activitySinceCheckpoint = false;
567
622
  checkpointWarningSent = false;
568
623
  lastSignals = null;
624
+ lastSnapshotPayload = null;
569
625
  }
570
626
  workerPhase = nextWorkerPhase;
571
627
 
@@ -612,6 +668,31 @@ export async function runWorker({
612
668
 
613
669
  lastSignals = signals;
614
670
 
671
+ if (
672
+ projectRoot &&
673
+ batchId &&
674
+ shouldEmitProgressSnapshot({
675
+ now,
676
+ lastEmittedAt: lastProgressSnapshotAt,
677
+ intervalMs: stallConfig.progressSnapshotIntervalMs,
678
+ })
679
+ ) {
680
+ const snapshotPayload = buildProgressSnapshotPayload(signals, workerPhase);
681
+ if (progressSnapshotPayloadChanged(lastSnapshotPayload, snapshotPayload)) {
682
+ recordLaneProgressSnapshot({
683
+ projectRoot,
684
+ batchId,
685
+ laneNumber,
686
+ taskId,
687
+ signals,
688
+ correlationId: laneCorrelationId,
689
+ workerPhase,
690
+ });
691
+ lastSnapshotPayload = snapshotPayload;
692
+ }
693
+ lastProgressSnapshotAt = now;
694
+ }
695
+
615
696
  if (
616
697
  projectRoot &&
617
698
  batchId &&
@@ -632,6 +713,12 @@ export async function runWorker({
632
713
  workerPhase,
633
714
  heartbeatKind,
634
715
  }));
716
+ stallAnchorAt = nextStallAnchorAt({
717
+ stallAnchorAt,
718
+ now,
719
+ workerPhase,
720
+ heartbeatKind,
721
+ });
635
722
  onHeartbeat?.(now);
636
723
  lastHeartbeatAt = now;
637
724
  }
@@ -639,6 +726,7 @@ export async function runWorker({
639
726
  const stallDeadline = computeStallDeadline({
640
727
  startedAt,
641
728
  lastProgressAt: lastCheckpointAt,
729
+ lastAliveAt: stallAnchorAt,
642
730
  stallConfig,
643
731
  });
644
732
 
@@ -4,9 +4,11 @@
4
4
 
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
+ import { writeJsonAtomic, writeTextAtomic } from "../fs/atomic-write.mjs";
7
8
  import { appendJournalEvent } from "./journal.mjs";
8
9
 
9
10
  const DEFAULT_MAX_BYTES = 262_144;
11
+ const DEFAULT_LIVE_LOG_MAX_BYTES = 262_144;
10
12
  const DEFAULT_TAIL_LINES = 200;
11
13
  const TRUNCATION_MARKER = "\n...[worker output truncated]...\n";
12
14
 
@@ -38,10 +40,17 @@ export function resolveWorkerOutputConfig(config = {}) {
38
40
  }
39
41
  }
40
42
 
43
+ const liveMaxBytes = Number(lanes.workerLiveLogMaxBytes);
44
+
41
45
  return {
42
46
  maxBytes: Number.isFinite(maxBytes) && maxBytes > 0 ? maxBytes : DEFAULT_MAX_BYTES,
43
47
  tailLines: Number.isFinite(tailLines) && tailLines > 0 ? tailLines : DEFAULT_TAIL_LINES,
44
48
  retainOnSuccess: lanes.retainWorkerOutputOnSuccess === true,
49
+ streamWorkerOutputLive: lanes.streamWorkerOutputLive === true,
50
+ workerLiveLogMaxBytes:
51
+ Number.isFinite(liveMaxBytes) && liveMaxBytes > 0
52
+ ? liveMaxBytes
53
+ : DEFAULT_LIVE_LOG_MAX_BYTES,
45
54
  denyPatterns,
46
55
  };
47
56
  }
@@ -134,6 +143,118 @@ export function workerOutputLogRef(batchId, laneNumber, taskId) {
134
143
  );
135
144
  }
136
145
 
146
+ /**
147
+ * @param {string} projectRoot
148
+ * @param {string} batchId
149
+ * @param {number} laneNumber
150
+ * @param {string} taskId
151
+ */
152
+ export function workerLiveLogPath(projectRoot, batchId, laneNumber, taskId) {
153
+ return path.join(
154
+ projectRoot,
155
+ ".spine",
156
+ "runtime",
157
+ batchId,
158
+ "lanes",
159
+ `lane-${laneNumber}`,
160
+ `worker-live-${taskId}.log`,
161
+ );
162
+ }
163
+
164
+ /**
165
+ * @param {string} batchId
166
+ * @param {number} laneNumber
167
+ * @param {string} taskId
168
+ */
169
+ export function workerLiveLogRef(batchId, laneNumber, taskId) {
170
+ return path.join(
171
+ ".spine",
172
+ "runtime",
173
+ batchId,
174
+ "lanes",
175
+ `lane-${laneNumber}`,
176
+ `worker-live-${taskId}.log`,
177
+ );
178
+ }
179
+
180
+ /**
181
+ * Byte-cap live log content with the same truncation marker as terminal capture.
182
+ *
183
+ * @param {string} text
184
+ * @param {number} maxBytes
185
+ */
186
+ export function truncateLiveLogBytes(text, maxBytes) {
187
+ if (!text) return "";
188
+
189
+ const encoded = Buffer.from(text, "utf-8");
190
+ if (encoded.byteLength <= maxBytes) {
191
+ return text;
192
+ }
193
+
194
+ const markerBytes = Buffer.byteLength(TRUNCATION_MARKER, "utf-8");
195
+ const budget = Math.max(0, maxBytes - markerBytes);
196
+ let slice = encoded.subarray(encoded.byteLength - budget).toString("utf-8");
197
+ const newline = slice.indexOf("\n");
198
+ if (newline >= 0 && newline < slice.length - 1) {
199
+ slice = slice.slice(newline + 1);
200
+ }
201
+ return `${TRUNCATION_MARKER}${slice}`;
202
+ }
203
+
204
+ /**
205
+ * Append redacted worker output to the live log with a rolling byte cap.
206
+ *
207
+ * @param {object} params
208
+ * @param {string} params.logPath
209
+ * @param {string} params.rawChunk
210
+ * @param {ReturnType<typeof resolveWorkerOutputConfig>} params.outputConfig
211
+ */
212
+ export function appendWorkerLiveLogChunk({ logPath, rawChunk, outputConfig }) {
213
+ if (!rawChunk) return;
214
+
215
+ const redacted = redactWorkerOutput(String(rawChunk), outputConfig);
216
+ if (!redacted) return;
217
+
218
+ const prior = fs.existsSync(logPath) ? fs.readFileSync(logPath, "utf-8") : "";
219
+ const combined = `${prior}${redacted}`;
220
+ const capped = truncateLiveLogBytes(combined, outputConfig.workerLiveLogMaxBytes);
221
+ if (!capped) return;
222
+
223
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
224
+ writeTextAtomic(logPath, capped);
225
+ }
226
+
227
+ /**
228
+ * Create an append-only live log writer when `lanes.streamWorkerOutputLive` is enabled.
229
+ *
230
+ * @param {object} params
231
+ * @param {string} [params.projectRoot]
232
+ * @param {string} [params.batchId]
233
+ * @param {number} [params.laneNumber]
234
+ * @param {string} [params.taskId]
235
+ * @param {object} [params.config]
236
+ * @returns {{ append: (rawChunk: string) => void; logPath: string } | null}
237
+ */
238
+ export function createWorkerLiveLogWriter({
239
+ projectRoot,
240
+ batchId,
241
+ laneNumber,
242
+ taskId,
243
+ config = {},
244
+ }) {
245
+ const outputConfig = resolveWorkerOutputConfig(config);
246
+ if (!outputConfig.streamWorkerOutputLive) return null;
247
+ if (!projectRoot || !batchId || laneNumber == null || !taskId) return null;
248
+
249
+ const logPath = workerLiveLogPath(projectRoot, batchId, laneNumber, taskId);
250
+ return {
251
+ logPath,
252
+ append(rawChunk) {
253
+ appendWorkerLiveLogChunk({ logPath, rawChunk, outputConfig });
254
+ },
255
+ };
256
+ }
257
+
137
258
  /**
138
259
  * @param {object} params
139
260
  */
@@ -150,8 +271,7 @@ export function persistWorkerOutputLog({
150
271
  if (!captured.trim()) return null;
151
272
 
152
273
  const logPath = workerOutputLogPath(projectRoot, batchId, laneNumber, taskId);
153
- fs.mkdirSync(path.dirname(logPath), { recursive: true });
154
- fs.writeFileSync(logPath, captured, "utf-8");
274
+ writeTextAtomic(logPath, captured);
155
275
 
156
276
  return {
157
277
  logPath,
@@ -250,4 +370,77 @@ export function finalizeWorkerOutput({
250
370
  };
251
371
  }
252
372
 
253
- export { TRUNCATION_MARKER, DEFAULT_MAX_BYTES, DEFAULT_TAIL_LINES };
373
+ /**
374
+ * Parse a `.DONE` marker body. Legacy empty/text markers remain valid (SP-321).
375
+ *
376
+ * @param {string} content
377
+ */
378
+ export function parseWorkerDoneMarker(content) {
379
+ const trimmed = String(content ?? "").trim();
380
+ if (!trimmed) {
381
+ return { valid: true, legacy: true, kind: "empty" };
382
+ }
383
+
384
+ if (trimmed.startsWith("{")) {
385
+ try {
386
+ const data = JSON.parse(trimmed);
387
+ if (
388
+ typeof data?.taskId === "string" &&
389
+ data.taskId.length > 0 &&
390
+ typeof data?.completedAt === "string" &&
391
+ data.completedAt.length > 0
392
+ ) {
393
+ return {
394
+ valid: true,
395
+ legacy: false,
396
+ kind: "json",
397
+ taskId: data.taskId,
398
+ completedAt: data.completedAt,
399
+ };
400
+ }
401
+ return { valid: false, legacy: false, kind: "json_partial", reason: "missing_fields" };
402
+ } catch {
403
+ return { valid: false, legacy: false, kind: "json_partial", reason: "parse_error" };
404
+ }
405
+ }
406
+
407
+ return { valid: true, legacy: true, kind: "text" };
408
+ }
409
+
410
+ /**
411
+ * @param {string} content
412
+ */
413
+ export function isWorkerDoneMarkerValid(content) {
414
+ return parseWorkerDoneMarker(content).valid;
415
+ }
416
+
417
+ /**
418
+ * @param {string} donePath
419
+ */
420
+ export function readWorkerDoneMarker(donePath) {
421
+ if (!fs.existsSync(donePath)) {
422
+ return { present: false, valid: false };
423
+ }
424
+ const parsed = parseWorkerDoneMarker(fs.readFileSync(donePath, "utf-8"));
425
+ return { present: true, ...parsed };
426
+ }
427
+
428
+ /**
429
+ * Atomically write a structured `.DONE` marker for engine validation.
430
+ *
431
+ * @param {string} donePath
432
+ * @param {{ taskId: string }} params
433
+ */
434
+ export function writeWorkerDoneMarker(donePath, { taskId }) {
435
+ writeJsonAtomic(donePath, {
436
+ taskId,
437
+ completedAt: new Date().toISOString(),
438
+ });
439
+ }
440
+
441
+ export {
442
+ TRUNCATION_MARKER,
443
+ DEFAULT_MAX_BYTES,
444
+ DEFAULT_LIVE_LOG_MAX_BYTES,
445
+ DEFAULT_TAIL_LINES,
446
+ };
@@ -0,0 +1,180 @@
1
+ /**
2
+ * GitHub issue draft body assembly (issue #60 Tier 1b).
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ import { reconcileBatch } from "../batch/reconcile.mjs";
9
+ import { runDoctorChecks } from "../doctor/run-doctor-checks.mjs";
10
+ import { PACKAGE_ROOT } from "../config/spine-init-constants.mjs";
11
+ import {
12
+ assembleHandoffData,
13
+ redactHandoffSecrets,
14
+ redactHandoffText,
15
+ } from "./handoff.mjs";
16
+
17
+ const VALID_ISSUE_TYPES = new Set(["bug", "enhancement", "question"]);
18
+
19
+ const ISSUE_TYPE_LABELS = {
20
+ bug: "bug",
21
+ enhancement: "enhancement",
22
+ question: "question",
23
+ };
24
+
25
+ /**
26
+ * @param {ReturnType<typeof runDoctorChecks>} doctorResult
27
+ */
28
+ function formatDoctorSummary(doctorResult) {
29
+ return doctorResult.checks
30
+ .map((check) => {
31
+ const status = check.warning ? "WARN" : check.ok ? "OK" : "FAIL";
32
+ const detail = check.detail ? ` (${check.detail})` : "";
33
+ return `- ${status} ${check.label}${detail}`;
34
+ })
35
+ .join("\n");
36
+ }
37
+
38
+ /**
39
+ * @param {ReturnType<typeof reconcileBatch>} reconciliation
40
+ */
41
+ function formatDiagnosisBlock(reconciliation) {
42
+ const lines = [
43
+ `- **Diagnosis:** ${reconciliation.diagnosis ?? "idle"}`,
44
+ `- **Headline:** ${reconciliation.headline ?? "—"}`,
45
+ `- **Suggested command:** ${reconciliation.suggestedCommand ?? "—"}`,
46
+ ];
47
+ if (reconciliation.batchId) {
48
+ lines.push(`- **Batch ID:** ${reconciliation.batchId}`);
49
+ }
50
+ if (reconciliation.phase) {
51
+ lines.push(`- **Phase:** ${reconciliation.phase}`);
52
+ }
53
+ return lines.join("\n");
54
+ }
55
+
56
+ /**
57
+ * @param {ReturnType<typeof assembleHandoffData>} handoff
58
+ */
59
+ function formatJournalExcerpt(handoff) {
60
+ if (!handoff.journalTail?.length) {
61
+ return "- (none)";
62
+ }
63
+ return handoff.journalTail
64
+ .map((entry) => {
65
+ const suffix = entry.taskId
66
+ ? ` ${entry.taskId}`
67
+ : entry.laneId
68
+ ? ` ${entry.laneId}`
69
+ : "";
70
+ return `- ${entry.timestamp} ${entry.type}${suffix}`;
71
+ })
72
+ .join("\n");
73
+ }
74
+
75
+ /**
76
+ * @param {ReturnType<typeof reconcileBatch>} reconciliation
77
+ */
78
+ function formatCommandsRun(reconciliation) {
79
+ const lines = [`- ${reconciliation.suggestedCommand ?? "spine preflight"}`];
80
+ for (const alt of reconciliation.alternatives ?? []) {
81
+ if (alt && !lines.includes(`- ${alt}`)) {
82
+ lines.push(`- ${alt}`);
83
+ }
84
+ }
85
+ return lines.join("\n");
86
+ }
87
+
88
+ function readPackageVersion() {
89
+ try {
90
+ const pkg = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, "package.json"), "utf-8"));
91
+ return pkg.version || "unknown";
92
+ } catch {
93
+ return "unknown";
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Render issue draft markdown sections for GitHub filing.
99
+ *
100
+ * @param {object} sections
101
+ * @param {string} sections.summary
102
+ * @param {string} sections.environment
103
+ * @param {string} sections.commandsRun
104
+ * @param {string} sections.diagnosis
105
+ * @param {string} sections.journalExcerpt
106
+ * @param {string} [sections.expected]
107
+ * @param {string} [sections.actual]
108
+ */
109
+ export function formatIssueDraftMarkdown(sections) {
110
+ const lines = [
111
+ "## Summary",
112
+ sections.summary,
113
+ "",
114
+ "## Environment",
115
+ sections.environment,
116
+ "",
117
+ "## Commands run",
118
+ sections.commandsRun,
119
+ "",
120
+ "## Diagnosis",
121
+ sections.diagnosis,
122
+ "",
123
+ "## Journal excerpt",
124
+ sections.journalExcerpt,
125
+ "",
126
+ "## Expected",
127
+ sections.expected ?? "(describe expected behavior)",
128
+ "",
129
+ "## Actual",
130
+ sections.actual ?? "(describe actual behavior)",
131
+ "",
132
+ ];
133
+ return redactHandoffText(lines.join("\n"));
134
+ }
135
+
136
+ /**
137
+ * Build a GitHub issue draft from live project state.
138
+ *
139
+ * @param {object} options
140
+ * @param {string} options.projectRoot
141
+ * @param {"bug"|"enhancement"|"question"} [options.issueType]
142
+ * @param {string} [options.title]
143
+ * @param {string} [options.batchId]
144
+ */
145
+ export function buildIssueDraftBody(options) {
146
+ const { projectRoot, issueType = "bug", title, batchId } = options;
147
+ if (!VALID_ISSUE_TYPES.has(issueType)) {
148
+ throw new Error(`Invalid issueType: ${issueType} (expected bug, enhancement, or question)`);
149
+ }
150
+
151
+ const reconciliation = reconcileBatch({ projectRoot, verbose: true });
152
+ const doctorResult = runDoctorChecks(projectRoot);
153
+ const handoff = assembleHandoffData(projectRoot, batchId ?? reconciliation.batchId ?? undefined);
154
+ const version = readPackageVersion();
155
+
156
+ const sections = redactHandoffSecrets({
157
+ summary: reconciliation.headline ?? "pi-spine operator issue draft",
158
+ environment: [
159
+ `- pi-spine version: ${version}`,
160
+ `- Node: v${process.versions.node}`,
161
+ "",
162
+ formatDoctorSummary(doctorResult),
163
+ ].join("\n"),
164
+ commandsRun: formatCommandsRun(reconciliation),
165
+ diagnosis: formatDiagnosisBlock(reconciliation),
166
+ journalExcerpt: formatJournalExcerpt(handoff),
167
+ expected: "(describe expected behavior)",
168
+ actual: "(describe actual behavior)",
169
+ });
170
+
171
+ const body = formatIssueDraftMarkdown(sections);
172
+ const resolvedTitle = redactHandoffText(title ?? reconciliation.headline ?? "pi-spine issue");
173
+ const labels = [ISSUE_TYPE_LABELS[issueType]];
174
+
175
+ return {
176
+ title: resolvedTitle,
177
+ body,
178
+ labels,
179
+ };
180
+ }