pi-spine 2.2.0 → 2.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 (47) hide show
  1. package/bin/spine-cli/verify.mjs +2 -19
  2. package/package.json +1 -1
  3. package/src/batch/attached-runner-promote.mjs +370 -0
  4. package/src/batch/attached-runner-reconcile.mjs +291 -0
  5. package/src/batch/attached-runner.mjs +24 -645
  6. package/src/batch/batch-guards.mjs +69 -0
  7. package/src/batch/contract-exec.mjs +483 -0
  8. package/src/batch/contract-parse.mjs +243 -0
  9. package/src/batch/contract-verify.mjs +32 -707
  10. package/src/batch/detached-diagnostics.mjs +255 -0
  11. package/src/batch/detached-run.mjs +326 -0
  12. package/src/batch/detached-start.mjs +18 -894
  13. package/src/batch/detached-wait.mjs +346 -0
  14. package/src/batch/engine.mjs +8 -67
  15. package/src/batch/integrate-git.mjs +21 -0
  16. package/src/batch/integrate.mjs +5 -15
  17. package/src/batch/journal-rebuild-structural.mjs +352 -0
  18. package/src/batch/journal-rebuild.mjs +16 -348
  19. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  20. package/src/batch/lane-dirty-check-git.mjs +298 -0
  21. package/src/batch/lane-dirty-check.mjs +31 -297
  22. package/src/batch/reconcile-batch.mjs +483 -0
  23. package/src/batch/reconcile-classify.mjs +433 -0
  24. package/src/batch/reconcile-diagnosis.mjs +459 -0
  25. package/src/batch/reconcile-light-cache.mjs +61 -0
  26. package/src/batch/reconcile-orphan.mjs +198 -0
  27. package/src/batch/reconcile.mjs +19 -1693
  28. package/src/batch/resume-multi-lanes.mjs +6 -148
  29. package/src/batch/resume-multi-queue.mjs +159 -0
  30. package/src/batch/resume-single-validate.mjs +25 -0
  31. package/src/batch/resume.mjs +3 -20
  32. package/src/batch/review-artifacts.mjs +419 -0
  33. package/src/batch/review-step-run.mjs +383 -0
  34. package/src/batch/review-step.mjs +451 -0
  35. package/src/batch/review.mjs +32 -1199
  36. package/src/batch/salvage-batch-list.mjs +291 -0
  37. package/src/batch/salvage-batch.mjs +10 -284
  38. package/src/batch/sequence-plan.mjs +234 -0
  39. package/src/batch/sequence-run.mjs +418 -0
  40. package/src/batch/sequence-wait.mjs +167 -0
  41. package/src/batch/sequence.mjs +22 -783
  42. package/src/batch/state-guards.mjs +284 -0
  43. package/src/batch/state-io.mjs +135 -0
  44. package/src/batch/state.mjs +27 -396
  45. package/src/batch/worker-heartbeat.mjs +375 -0
  46. package/src/batch/worker-host.mjs +50 -541
  47. package/src/batch/worker-spawn.mjs +315 -0
@@ -0,0 +1,419 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Review artifact discovery, level parsing, and honor-signal helpers.
4
+ * SP-579 extraction from review.mjs; spawn wiring stays in review.mjs (SP-597).
5
+ */
6
+
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { detectOrphanedReviewStarted } from "./journal-rebuild.mjs";
10
+ import { NESTED_REVIEW_SPAWN_REASON } from "./review-spawn.mjs";
11
+ import { normalizeVerdict, parseReviewLevel, parseReviewVerdict } from "./review-shared.mjs";
12
+
13
+ /**
14
+ * @param {string} taskFolder
15
+ */
16
+ export function readReviewLevel(taskFolder) {
17
+ const promptPath = path.join(taskFolder, "PROMPT.md");
18
+ if (!fs.existsSync(promptPath)) return 0;
19
+ return parseReviewLevel(fs.readFileSync(promptPath, "utf-8"));
20
+ }
21
+
22
+ /**
23
+ * Highest numbered ### Step N heading in PROMPT.md (defaults to 1).
24
+ * @param {string} taskFolder
25
+ */
26
+ export function findFinalReviewStepNumber(taskFolder) {
27
+ const promptPath = path.join(taskFolder, "PROMPT.md");
28
+ if (!fs.existsSync(promptPath)) return 1;
29
+ const content = fs.readFileSync(promptPath, "utf-8");
30
+ const matches = [...content.matchAll(/###\s+Step\s+(\d+)/g)];
31
+ if (matches.length === 0) return 1;
32
+ return Math.max(...matches.map((match) => Number(match[1])));
33
+ }
34
+
35
+ /**
36
+ * Step number containing a code review checkpoint blockquote, else highest step.
37
+ * @param {string} taskFolder
38
+ */
39
+ export function findCodeReviewStepNumber(taskFolder) {
40
+ const promptPath = path.join(taskFolder, "PROMPT.md");
41
+ if (!fs.existsSync(promptPath)) return findFinalReviewStepNumber(taskFolder);
42
+ const content = fs.readFileSync(promptPath, "utf-8");
43
+ const stepBlocks = [...content.matchAll(/###\s+Step\s+(\d+)[:\s][\s\S]*?(?=###\s+Step\s+\d+|$)/g)];
44
+ for (const match of stepBlocks) {
45
+ if (/code\s+review\s+checkpoint/i.test(match[0])) {
46
+ return Number(match[1]);
47
+ }
48
+ }
49
+ return findFinalReviewStepNumber(taskFolder);
50
+ }
51
+
52
+ /**
53
+ * Latest `.reviews/{stepNumber}-*.md` by mtime, if any.
54
+ * @param {string} taskFolder
55
+ * @param {number} stepNumber
56
+ * @returns {{ artifactPath: string, mtimeMs: number }|null}
57
+ */
58
+ export function findLatestStepReviewArtifact(taskFolder, stepNumber) {
59
+ const reviewsDir = path.join(taskFolder, ".reviews");
60
+ if (!fs.existsSync(reviewsDir)) return null;
61
+ const prefix = `${stepNumber}-`;
62
+ const candidates = fs
63
+ .readdirSync(reviewsDir)
64
+ .filter((name) => name.startsWith(prefix) && name.endsWith(".md"))
65
+ .map((name) => {
66
+ const artifactPath = path.join(reviewsDir, name);
67
+ return { artifactPath, mtimeMs: fs.statSync(artifactPath).mtimeMs };
68
+ })
69
+ .sort((left, right) => right.mtimeMs - left.mtimeMs);
70
+ return candidates[0] ?? null;
71
+ }
72
+
73
+ /**
74
+ * Resolve an existing worker or lane code review from journal and/or artifacts.
75
+ *
76
+ * @param {object} params
77
+ * @param {string} params.taskFolder
78
+ * @param {object[]} [params.journalEvents]
79
+ * @param {string} [params.taskId]
80
+ * @returns {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
81
+ */
82
+ export function findCompletedCodeReview({ taskFolder, journalEvents = [], taskId }) {
83
+ /** @type {{ verdict: "APPROVE"|"REVISE", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
84
+ let journalMatch = null;
85
+ for (let index = 0; index < journalEvents.length; index += 1) {
86
+ const event = journalEvents[index];
87
+ if (taskId && event.taskId !== taskId) continue;
88
+ if (event.type !== "review.completed") continue;
89
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
90
+ if (payload.reviewType !== "code") continue;
91
+ const verdict = normalizeVerdict(payload.verdict, "code");
92
+ if (!verdict) continue;
93
+ journalMatch = {
94
+ verdict,
95
+ feedback: typeof payload.feedback === "string" ? payload.feedback : "",
96
+ artifactPath: typeof payload.artifactPath === "string" ? payload.artifactPath : "",
97
+ source: "journal",
98
+ seq: index,
99
+ };
100
+ }
101
+
102
+ if (journalMatch?.verdict === "APPROVE") {
103
+ const { seq: _seq, ...result } = journalMatch;
104
+ return result;
105
+ }
106
+
107
+ const stepNumber = findCodeReviewStepNumber(taskFolder);
108
+ const latestArtifact = findLatestStepReviewArtifact(taskFolder, stepNumber);
109
+ if (latestArtifact) {
110
+ const reviewContent = fs.readFileSync(latestArtifact.artifactPath, "utf-8");
111
+ const { verdict, feedback } = parseReviewVerdict(reviewContent, { reviewType: "code" });
112
+ if (verdict) {
113
+ const artifactMatch = {
114
+ verdict,
115
+ feedback,
116
+ artifactPath: latestArtifact.artifactPath,
117
+ source: /** @type {"artifact"} */ ("artifact"),
118
+ };
119
+ if (verdict === "APPROVE") return artifactMatch;
120
+ if (!journalMatch) return artifactMatch;
121
+ }
122
+ }
123
+
124
+ if (!journalMatch) return null;
125
+ const { seq: _seq, ...result } = journalMatch;
126
+ return result;
127
+ }
128
+
129
+ /** Journal honor events emitted when honoring a completed review artifact. */
130
+ export const REVIEW_HONOR_JOURNAL_EVENTS = {
131
+ crashRecovered: "review.crash_recovered",
132
+ skippedFreshArtifact: "review.skipped_fresh_artifact",
133
+ resumed: "review.resumed",
134
+ };
135
+
136
+ /**
137
+ * True when operator retry or reconcile re-enters review with a still-valid prior verdict.
138
+ *
139
+ * @param {object} params
140
+ * @param {object[]} params.journalEvents
141
+ * @param {string} params.taskId
142
+ * @param {"code"|"final"} params.reviewType
143
+ * @param {"journal"|"artifact"} [params.honorSource]
144
+ */
145
+ export function isRetryReconcileFreshReview({
146
+ journalEvents = [],
147
+ taskId,
148
+ reviewType,
149
+ honorSource,
150
+ }) {
151
+ let lastReviewCompletedIndex = -1;
152
+ let lastRetryIndex = -1;
153
+ let lastReconciledCompleteIndex = -1;
154
+
155
+ for (let index = 0; index < journalEvents.length; index += 1) {
156
+ const event = journalEvents[index];
157
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
158
+ const eventTaskId = event.taskId ?? payload.taskId;
159
+ if (eventTaskId !== taskId) continue;
160
+
161
+ if (event.type === "review.completed" && payload.reviewType === reviewType) {
162
+ lastReviewCompletedIndex = index;
163
+ }
164
+ if (event.type === "task.retry_requested") {
165
+ lastRetryIndex = index;
166
+ }
167
+ if (
168
+ event.type === "task.completed" &&
169
+ (payload.reconcileReason === "done_in_lane_terminal" || payload.reconciled === true)
170
+ ) {
171
+ lastReconciledCompleteIndex = index;
172
+ }
173
+ }
174
+
175
+ if (lastReviewCompletedIndex < 0) {
176
+ return false;
177
+ }
178
+ if (lastRetryIndex > lastReviewCompletedIndex) {
179
+ return true;
180
+ }
181
+ if (honorSource === "journal" && lastReconciledCompleteIndex > lastReviewCompletedIndex) {
182
+ return true;
183
+ }
184
+ return false;
185
+ }
186
+
187
+ /**
188
+ * True when journal shows a review spawn crash/failure that warrants crash_recovered.
189
+ *
190
+ * @param {object} params
191
+ * @param {object[]} params.journalEvents
192
+ * @param {string} params.taskId
193
+ * @param {"code"|"final"} params.reviewType
194
+ */
195
+ export function hasReviewSpawnFailureForHonor({ journalEvents = [], taskId, reviewType }) {
196
+ const orphaned = detectOrphanedReviewStarted(journalEvents);
197
+ for (const event of orphaned) {
198
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
199
+ const eventTaskId = event.taskId ?? payload.taskId;
200
+ if (eventTaskId === taskId && payload.reviewType === reviewType) {
201
+ return true;
202
+ }
203
+ }
204
+
205
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
206
+ const event = journalEvents[index];
207
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
208
+ const eventTaskId = event.taskId ?? payload.taskId;
209
+ if (eventTaskId !== taskId) continue;
210
+
211
+ if (event.type === "review.failed") {
212
+ if (payload.reviewType !== reviewType) continue;
213
+ if (payload.reason === NESTED_REVIEW_SPAWN_REASON) continue;
214
+ return true;
215
+ }
216
+ if (event.type === "review.completed" && payload.reviewType === reviewType) {
217
+ break;
218
+ }
219
+ }
220
+ return false;
221
+ }
222
+
223
+ /**
224
+ * Resolve explicit journal event for honoring a completed review artifact.
225
+ *
226
+ * @param {object} params
227
+ * @param {object[]} params.journalEvents
228
+ * @param {string} params.taskId
229
+ * @param {"code"|"final"} params.reviewType
230
+ * @param {"journal"|"artifact"} [params.honorSource]
231
+ * @param {number} [params.reviewAttempt]
232
+ * @returns {"review.crash_recovered"|"review.skipped_fresh_artifact"|null}
233
+ */
234
+ export function resolveReviewHonorJournalEvent({
235
+ journalEvents = [],
236
+ taskId,
237
+ reviewType,
238
+ honorSource,
239
+ reviewAttempt = 0,
240
+ }) {
241
+ if (
242
+ isRetryReconcileFreshReview({ journalEvents, taskId, reviewType, honorSource }) &&
243
+ !hasReviewSpawnFailureForHonor({ journalEvents, taskId, reviewType })
244
+ ) {
245
+ return REVIEW_HONOR_JOURNAL_EVENTS.skippedFreshArtifact;
246
+ }
247
+ if (hasReviewSpawnFailureForHonor({ journalEvents, taskId, reviewType })) {
248
+ return REVIEW_HONOR_JOURNAL_EVENTS.crashRecovered;
249
+ }
250
+ if (reviewAttempt > 0) {
251
+ return REVIEW_HONOR_JOURNAL_EVENTS.crashRecovered;
252
+ }
253
+ return null;
254
+ }
255
+
256
+ /**
257
+ * Map honor journal event to task.verdict_recorded reviewPassKind.
258
+ *
259
+ * @param {"review.crash_recovered"|"review.skipped_fresh_artifact"|null} honorJournalEvent
260
+ * @returns {"recovered"|"fresh_skip"|"normal"}
261
+ */
262
+ export function resolveReviewPassKind(honorJournalEvent) {
263
+ if (honorJournalEvent === REVIEW_HONOR_JOURNAL_EVENTS.crashRecovered) {
264
+ return "recovered";
265
+ }
266
+ if (honorJournalEvent === REVIEW_HONOR_JOURNAL_EVENTS.skippedFreshArtifact) {
267
+ return "fresh_skip";
268
+ }
269
+ return "normal";
270
+ }
271
+
272
+ /**
273
+ * True when review should emit review.resumed before spawning after operator retry.
274
+ *
275
+ * @param {object} params
276
+ * @param {object[]} params.journalEvents
277
+ * @param {string} params.taskId
278
+ */
279
+ export function shouldEmitReviewResumed({ journalEvents = [], taskId }) {
280
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
281
+ const event = journalEvents[index];
282
+ if (event.type !== "task.retry_requested") continue;
283
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
284
+ const eventTaskId = event.taskId ?? payload.taskId;
285
+ if (eventTaskId === taskId) {
286
+ return true;
287
+ }
288
+ }
289
+ return false;
290
+ }
291
+
292
+ /**
293
+ * Latest review honor/resume signal for diagnose and dashboard surfaces.
294
+ *
295
+ * @param {object[]} journalEvents
296
+ * @param {string|null} [activeTaskId]
297
+ * @returns {{ taskId: string, reviewType: string, kind: string, honorSource?: string, reviewPassKind?: string }|null}
298
+ */
299
+ export function findLatestReviewHonorSignal(journalEvents, activeTaskId = null) {
300
+ const honorTypes = new Set([
301
+ REVIEW_HONOR_JOURNAL_EVENTS.crashRecovered,
302
+ REVIEW_HONOR_JOURNAL_EVENTS.skippedFreshArtifact,
303
+ REVIEW_HONOR_JOURNAL_EVENTS.resumed,
304
+ ]);
305
+
306
+ for (let index = journalEvents.length - 1; index >= 0; index -= 1) {
307
+ const event = journalEvents[index];
308
+ if (!honorTypes.has(event.type)) continue;
309
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
310
+ const taskId = event.taskId ?? payload.taskId;
311
+ if (!taskId) continue;
312
+ if (activeTaskId && taskId !== activeTaskId) continue;
313
+ return {
314
+ taskId,
315
+ reviewType: payload.reviewType,
316
+ kind: event.type,
317
+ honorSource: payload.honorSource,
318
+ reviewPassKind: payload.reviewPassKind,
319
+ };
320
+ }
321
+ return null;
322
+ }
323
+
324
+ /**
325
+ * @param {object|null|undefined} reviewHonorSignal
326
+ * @returns {string|null}
327
+ */
328
+ export function buildReviewHonorHeadlineSuffix(reviewHonorSignal) {
329
+ if (!reviewHonorSignal?.kind) return null;
330
+ const reviewLabel =
331
+ reviewHonorSignal.reviewType === "final" ? "final review" : "code review";
332
+ if (reviewHonorSignal.kind === "review.crash_recovered") {
333
+ return `recovered ${reviewLabel} crash — prior verdict honored from ${reviewHonorSignal.honorSource ?? "artifact"}`;
334
+ }
335
+ if (reviewHonorSignal.kind === "review.skipped_fresh_artifact") {
336
+ return `skipped redundant ${reviewLabel} — fresh artifact honored`;
337
+ }
338
+ if (reviewHonorSignal.kind === "review.resumed") {
339
+ return `${reviewLabel} resumed after operator retry`;
340
+ }
341
+ return null;
342
+ }
343
+
344
+ /**
345
+ * Latest `.reviews/final-*.md` by mtime, if any.
346
+ * @param {string} taskFolder
347
+ * @returns {{ artifactPath: string, mtimeMs: number }|null}
348
+ */
349
+ export function findLatestFinalReviewArtifact(taskFolder) {
350
+ const reviewsDir = path.join(taskFolder, ".reviews");
351
+ if (!fs.existsSync(reviewsDir)) return null;
352
+
353
+ const candidates = fs
354
+ .readdirSync(reviewsDir)
355
+ .filter((name) => name.startsWith("final-") && name.endsWith(".md"))
356
+ .map((name) => {
357
+ const artifactPath = path.join(reviewsDir, name);
358
+ return { artifactPath, mtimeMs: fs.statSync(artifactPath).mtimeMs };
359
+ })
360
+ .sort((left, right) => right.mtimeMs - left.mtimeMs);
361
+
362
+ return candidates[0] ?? null;
363
+ }
364
+
365
+ /**
366
+ * Resolve an existing worker or lane final review from journal and/or artifacts.
367
+ * Honors PASS from journal `review.completed` or latest final artifact.
368
+ *
369
+ * @param {object} params
370
+ * @param {string} params.taskFolder
371
+ * @param {object[]} [params.journalEvents]
372
+ * @param {string} [params.taskId]
373
+ * @returns {{ verdict: "PASS"|"REVISE"|"REPLAN", feedback: string, artifactPath: string, source: "journal"|"artifact" }|null}
374
+ */
375
+ export function findCompletedFinalReview({ taskFolder, journalEvents = [], taskId }) {
376
+ /** @type {{ verdict: "PASS"|"REVISE"|"REPLAN", feedback: string, artifactPath: string, source: "journal"|"artifact", seq: number }|null} */
377
+ let journalMatch = null;
378
+ for (let index = 0; index < journalEvents.length; index += 1) {
379
+ const event = journalEvents[index];
380
+ if (taskId && event.taskId !== taskId) continue;
381
+ if (event.type !== "review.completed") continue;
382
+ const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
383
+ if (payload.reviewType !== "final") continue;
384
+ const verdict = normalizeVerdict(payload.verdict, "final");
385
+ if (!verdict) continue;
386
+ journalMatch = {
387
+ verdict,
388
+ feedback: typeof payload.feedback === "string" ? payload.feedback : "",
389
+ artifactPath: typeof payload.artifactPath === "string" ? payload.artifactPath : "",
390
+ source: "journal",
391
+ seq: index,
392
+ };
393
+ }
394
+
395
+ if (journalMatch?.verdict === "PASS") {
396
+ const { seq: _seq, ...result } = journalMatch;
397
+ return result;
398
+ }
399
+
400
+ const latestArtifact = findLatestFinalReviewArtifact(taskFolder);
401
+ if (latestArtifact) {
402
+ const reviewContent = fs.readFileSync(latestArtifact.artifactPath, "utf-8");
403
+ const { verdict, feedback } = parseReviewVerdict(reviewContent, { reviewType: "final" });
404
+ if (verdict) {
405
+ const artifactMatch = {
406
+ verdict,
407
+ feedback,
408
+ artifactPath: latestArtifact.artifactPath,
409
+ source: /** @type {"artifact"} */ ("artifact"),
410
+ };
411
+ if (verdict === "PASS") return artifactMatch;
412
+ if (!journalMatch) return artifactMatch;
413
+ }
414
+ }
415
+
416
+ if (!journalMatch) return null;
417
+ const { seq: _seq, ...result } = journalMatch;
418
+ return result;
419
+ }