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,433 @@
1
+ // @ts-nocheck
2
+ /** Task classification and git inspection for batch reconciliation (SP-578). */
3
+
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { execFileSync } from "node:child_process";
7
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
8
+ import { resolveTasksRootPath } from "../config/env-overrides.mjs";
9
+ import { resolveCurrentGitBranch } from "../config/spine-preflight-lib.mjs";
10
+ import { classifyTaskDoneSemantics } from "./diagnosis.mjs";
11
+ import { countCommitsAhead } from "./lane-commit.mjs";
12
+ import { parseBatchState } from "./batch-state-io.mjs";
13
+ import { saveSpineBatchState } from "./state.mjs";
14
+
15
+ /** @param {string} projectRoot @param {ReturnType<typeof loadSpineConfig>} [configResult] */
16
+ export function resolveTasksRoot(projectRoot, configResult) {
17
+ const loaded = configResult ?? loadSpineConfig(projectRoot);
18
+ if (!loaded.config) {
19
+ return null;
20
+ }
21
+ return resolveTasksRootPath(projectRoot, loaded.config);
22
+ }
23
+
24
+ /** Align classification with batch-state status (SP-516 / #166, SP-512). @param {object} classified */
25
+ export function alignTaskClassificationWithStatus(classified) {
26
+ const status = String(classified.status ?? "").toLowerCase();
27
+ let classification = classified.classification;
28
+
29
+ if (status === "succeeded" || status === "skipped") {
30
+ classification = "terminal-success";
31
+ } else if (status === "failed") {
32
+ classification = "terminal-failure";
33
+ } else if (status === "running") {
34
+ if (classified.doneOnMain || classified.doneInLane || classified.doneFileFound) {
35
+ classification = "terminal-success";
36
+ } else {
37
+ classification = "running";
38
+ }
39
+ } else {
40
+ classification = "pending";
41
+ }
42
+
43
+ return { ...classified, classification };
44
+ }
45
+
46
+ /** @param {object} batch @param {string|null} tasksRoot @param {string} [projectRoot] */
47
+ export function classifyTasks(batch, tasksRoot, projectRoot = "") {
48
+ return batch.tasks.map((task) =>
49
+ alignTaskClassificationWithStatus(
50
+ classifyTaskDoneSemantics(task, {
51
+ tasksRoot,
52
+ projectRoot,
53
+ batchId: batch.batchId,
54
+ lanes: batch.lanes,
55
+ }),
56
+ ),
57
+ );
58
+ }
59
+
60
+ /** @param {{ projectRoot: string, state: object }} params @returns {{ changed: boolean }} */
61
+ export function syncPersistedClassifications({ projectRoot, state }) {
62
+ if (!state || typeof state !== "object") {
63
+ return { changed: false };
64
+ }
65
+
66
+ const batch = parseBatchState(state, "");
67
+ if (!batch) {
68
+ return { changed: false };
69
+ }
70
+
71
+ const tasksRoot = resolveTasksRoot(projectRoot);
72
+ const classified = classifyTasks(batch, tasksRoot, projectRoot);
73
+ const alignedById = new Map(classified.map((task) => [String(task.taskId), task]));
74
+ let changed = false;
75
+
76
+ for (const task of state.tasks ?? []) {
77
+ if (!task?.taskId) continue;
78
+ const aligned = alignedById.get(String(task.taskId));
79
+ if (!aligned) continue;
80
+
81
+ const status = String(task.status ?? "").toLowerCase();
82
+ if (status === "succeeded" || status === "skipped") {
83
+ if ("classification" in task) {
84
+ delete task.classification;
85
+ changed = true;
86
+ }
87
+ continue;
88
+ }
89
+
90
+ if (!("classification" in task)) continue;
91
+
92
+ const persisted = String(task.classification ?? "");
93
+ if (persisted === aligned.classification) continue;
94
+
95
+ if (status === "failed" || status === "pending") {
96
+ delete task.classification;
97
+ changed = true;
98
+ }
99
+ }
100
+
101
+ for (const segment of state.segments ?? []) {
102
+ if (!segment?.taskId || !("classification" in segment)) continue;
103
+ const aligned = alignedById.get(String(segment.taskId));
104
+ if (!aligned) continue;
105
+ const segmentStatus = String(segment.status ?? "").toLowerCase();
106
+ if (segmentStatus === "failed" || segmentStatus === "pending") {
107
+ delete segment.classification;
108
+ changed = true;
109
+ }
110
+ }
111
+
112
+ if (changed) {
113
+ saveSpineBatchState(projectRoot, state);
114
+ }
115
+
116
+ return { changed };
117
+ }
118
+
119
+ function isInsideGitRepo(projectRoot) {
120
+ try {
121
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
122
+ cwd: projectRoot,
123
+ stdio: ["ignore", "pipe", "pipe"],
124
+ timeout: 5000,
125
+ });
126
+ return true;
127
+ } catch {
128
+ return false;
129
+ }
130
+ }
131
+
132
+ function gitRefExists(projectRoot, ref) {
133
+ try {
134
+ execFileSync("git", ["rev-parse", "--verify", ref], {
135
+ cwd: projectRoot,
136
+ stdio: ["ignore", "pipe", "pipe"],
137
+ timeout: 5000,
138
+ });
139
+ return true;
140
+ } catch {
141
+ return false;
142
+ }
143
+ }
144
+
145
+ function gitIsAncestor(projectRoot, ancestor, descendant) {
146
+ try {
147
+ execFileSync("git", ["merge-base", "--is-ancestor", ancestor, descendant], {
148
+ cwd: projectRoot,
149
+ stdio: ["ignore", "pipe", "pipe"],
150
+ timeout: 5000,
151
+ });
152
+ return true;
153
+ } catch {
154
+ return false;
155
+ }
156
+ }
157
+
158
+ function recordGitInspectionError(result, err, context) {
159
+ const message = err instanceof Error ? err.message : String(err);
160
+ const detail = `${context}: ${message}`;
161
+ result.gitInspectionError = result.gitInspectionError
162
+ ? `${result.gitInspectionError}; ${detail}`
163
+ : detail;
164
+ }
165
+
166
+ function listOrchBranches(projectRoot, batchId) {
167
+ try {
168
+ const output = execFileSync("git", ["branch", "-a", "--list", "*orch*"], {
169
+ cwd: projectRoot,
170
+ encoding: "utf-8",
171
+ timeout: 5000,
172
+ });
173
+
174
+ return output
175
+ .split(/\r?\n/)
176
+ .map((line) => line.trim().replace(/^\*?\s+/, "").replace(/^remotes\/[^/]+\//, ""))
177
+ .filter(Boolean)
178
+ .filter((branch) => branch.includes(batchId));
179
+ } catch {
180
+ return [];
181
+ }
182
+ }
183
+
184
+ /** @param {{ projectRoot: string, batchId: string, baseBranch: string, orchBranch: string|null }} ctx */
185
+ export function inspectGitState(ctx) {
186
+ const { projectRoot, batchId, baseBranch, orchBranch } = ctx;
187
+ const result = {
188
+ inGitRepo: isInsideGitRepo(projectRoot),
189
+ baseBranch,
190
+ orchBranch,
191
+ orchBranches: [],
192
+ orchBranchExists: false,
193
+ orchMergedToBase: false,
194
+ mergedOrchBranch: null,
195
+ orchCommitsAhead: null,
196
+ gitInspectionError: null,
197
+ };
198
+
199
+ if (!result.inGitRepo) return result;
200
+
201
+ if (process.env.SPINE_TEST_GIT_INSPECTION_THROW) {
202
+ result.gitInspectionError = `simulated: ${process.env.SPINE_TEST_GIT_INSPECTION_THROW}`;
203
+ return result;
204
+ }
205
+
206
+ const candidates = new Set(listOrchBranches(projectRoot, batchId));
207
+ if (orchBranch) candidates.add(orchBranch);
208
+ candidates.add(`orch/cdelgado-${batchId}`);
209
+ candidates.add(`orch/spine-*-${batchId}`.replace("*", "operator"));
210
+
211
+ result.orchBranches = [...candidates].filter((branch) => !branch.includes("*"));
212
+
213
+ for (const branch of result.orchBranches) {
214
+ if (!gitRefExists(projectRoot, branch)) continue;
215
+ result.orchBranchExists = true;
216
+ if (gitIsAncestor(projectRoot, branch, baseBranch)) {
217
+ result.orchMergedToBase = true;
218
+ result.mergedOrchBranch = branch;
219
+ break;
220
+ }
221
+ }
222
+
223
+ const resolvedOrch = orchBranch && gitRefExists(projectRoot, orchBranch) ? orchBranch : result.mergedOrchBranch;
224
+ if (resolvedOrch && gitRefExists(projectRoot, resolvedOrch) && !result.orchMergedToBase) {
225
+ try {
226
+ result.orchCommitsAhead = countCommitsAhead(projectRoot, baseBranch, resolvedOrch);
227
+ } catch (err) {
228
+ result.orchCommitsAhead = null;
229
+ recordGitInspectionError(result, err, "count_commits_ahead");
230
+ }
231
+ }
232
+
233
+ if (!result.orchMergedToBase) {
234
+ try {
235
+ const merged = execFileSync("git", ["branch", "--merged", baseBranch], {
236
+ cwd: projectRoot,
237
+ encoding: "utf-8",
238
+ timeout: 5000,
239
+ });
240
+ const mergedOrch = merged
241
+ .split(/\r?\n/)
242
+ .map((line) => line.trim().replace(/^\*?\s+/, ""))
243
+ .filter((branch) => branch.includes("orch") && branch.includes(batchId));
244
+ if (mergedOrch.length > 0) {
245
+ result.orchMergedToBase = true;
246
+ result.mergedOrchBranch = mergedOrch[0];
247
+ result.orchBranchExists = true;
248
+ }
249
+ } catch (err) {
250
+ recordGitInspectionError(result, err, "list_merged_branches");
251
+ }
252
+ }
253
+
254
+ return result;
255
+ }
256
+
257
+ /** @param {string} projectRoot @param {string} refA @param {string} refB @returns {string[]} */
258
+ export function listGitChangedPaths(projectRoot, refA, refB) {
259
+ if (!refA || !refB || refA === refB) return [];
260
+ try {
261
+ const output = execFileSync("git", ["diff", "--name-only", `${refA}..${refB}`], {
262
+ cwd: projectRoot,
263
+ encoding: "utf-8",
264
+ stdio: ["ignore", "pipe", "pipe"],
265
+ timeout: 5000,
266
+ });
267
+ return output
268
+ .split(/\r?\n/)
269
+ .map((line) => line.trim())
270
+ .filter(Boolean);
271
+ } catch {
272
+ return [];
273
+ }
274
+ }
275
+
276
+ /** Paths from human commits since snapshot, excluding orch ancestry. */
277
+ export function listHumanOnlyPaths(projectRoot, snapshot, humanHead, orchBranch) {
278
+ if (!snapshot || !humanHead || snapshot === humanHead) return [];
279
+ const args = ["log", "--name-only", "--pretty=format:", `${snapshot}..${humanHead}`];
280
+ if (orchBranch && gitRefExists(projectRoot, orchBranch)) {
281
+ args.push("--not", orchBranch);
282
+ }
283
+ try {
284
+ const output = execFileSync("git", args, {
285
+ cwd: projectRoot,
286
+ encoding: "utf-8",
287
+ stdio: ["ignore", "pipe", "pipe"],
288
+ timeout: 5000,
289
+ });
290
+ return [...new Set(output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean))];
291
+ } catch {
292
+ return [];
293
+ }
294
+ }
295
+
296
+ function pathExistsAtRef(projectRoot, ref, filePath) {
297
+ try {
298
+ execFileSync("git", ["cat-file", "-e", `${ref}:${filePath}`], {
299
+ cwd: projectRoot,
300
+ stdio: ["ignore", "pipe", "pipe"],
301
+ timeout: 5000,
302
+ });
303
+ return true;
304
+ } catch {
305
+ return false;
306
+ }
307
+ }
308
+
309
+ function humanCheckoutNeedsPathSync(projectRoot, baseTip, snapshot) {
310
+ const landPaths = listGitChangedPaths(projectRoot, snapshot, baseTip);
311
+ for (const filePath of landPaths) {
312
+ if (!pathExistsAtRef(projectRoot, baseTip, filePath)) continue;
313
+ if (!fs.existsSync(path.join(projectRoot, filePath))) {
314
+ return true;
315
+ }
316
+ }
317
+ return false;
318
+ }
319
+
320
+ /** Human/base divergence or post-isolated-integrate sync (FR-WT-08 / #91). */
321
+ export function inspectHumanBaseSync(ctx) {
322
+ const { projectRoot, baseBranch, baseBranchHeadAtStart, orchBranch, git, journalEvents } = ctx;
323
+ if (!git?.inGitRepo) return null;
324
+
325
+ const snapshot = String(baseBranchHeadAtStart ?? "").trim();
326
+ if (!snapshot) return null;
327
+
328
+ let baseTip = "";
329
+ let humanHead = "";
330
+ try {
331
+ baseTip = execFileSync("git", ["rev-parse", baseBranch], {
332
+ cwd: projectRoot,
333
+ encoding: "utf-8",
334
+ timeout: 5000,
335
+ }).trim();
336
+ humanHead = execFileSync("git", ["rev-parse", "HEAD"], {
337
+ cwd: projectRoot,
338
+ encoding: "utf-8",
339
+ timeout: 5000,
340
+ }).trim();
341
+ } catch {
342
+ return null;
343
+ }
344
+
345
+ const integrateCompleted = Array.isArray(journalEvents)
346
+ ? journalEvents.some((event) => event.type === "integrate.completed")
347
+ : false;
348
+ const landSucceeded =
349
+ git.orchMergedToBase ||
350
+ integrateCompleted ||
351
+ (baseTip !== snapshot && gitIsAncestor(projectRoot, snapshot, baseTip));
352
+
353
+ const resolvedOrch =
354
+ orchBranch && gitRefExists(projectRoot, orchBranch)
355
+ ? orchBranch
356
+ : git.mergedOrchBranch && gitRefExists(projectRoot, git.mergedOrchBranch)
357
+ ? git.mergedOrchBranch
358
+ : null;
359
+
360
+ const branchResult = resolveCurrentGitBranch(projectRoot);
361
+ const onBaseBranch = branchResult.branch === baseBranch;
362
+
363
+ const humanSinceSnapshot =
364
+ onBaseBranch &&
365
+ gitIsAncestor(projectRoot, snapshot, humanHead) &&
366
+ humanHead !== snapshot;
367
+ const humanPaths = humanSinceSnapshot
368
+ ? listHumanOnlyPaths(projectRoot, snapshot, humanHead, resolvedOrch)
369
+ : [];
370
+ const landPaths = landSucceeded ? listGitChangedPaths(projectRoot, snapshot, baseTip) : [];
371
+ const orchPaths =
372
+ resolvedOrch && gitRefExists(projectRoot, resolvedOrch)
373
+ ? listGitChangedPaths(projectRoot, snapshot, resolvedOrch)
374
+ : landPaths;
375
+ const overlapPaths = humanPaths.filter((filePath) => orchPaths.includes(filePath));
376
+
377
+ if (overlapPaths.length > 0) {
378
+ return {
379
+ diagnosis: "human_base_diverged",
380
+ headline: onBaseBranch
381
+ ? `Human commits on ${baseBranch} overlap orch land (${overlapPaths.length} path(s))`
382
+ : `Human commits overlap orch land (${overlapPaths.length} path(s))`,
383
+ overlapPaths,
384
+ humanHead,
385
+ baseTip,
386
+ orchBranch: resolvedOrch,
387
+ preIntegrate: !landSucceeded,
388
+ };
389
+ }
390
+
391
+ if (!landSucceeded) return null;
392
+
393
+ const needsCommitSync =
394
+ humanHead !== baseTip && onBaseBranch && gitIsAncestor(projectRoot, humanHead, baseTip);
395
+ const needsPathSync =
396
+ onBaseBranch && humanHead === baseTip && humanCheckoutNeedsPathSync(projectRoot, baseTip, snapshot);
397
+
398
+ if (!needsCommitSync && !needsPathSync) {
399
+ if (!onBaseBranch) {
400
+ const mergeBase = (() => {
401
+ try {
402
+ return execFileSync("git", ["merge-base", humanHead, baseTip], {
403
+ cwd: projectRoot,
404
+ encoding: "utf-8",
405
+ timeout: 5000,
406
+ }).trim();
407
+ } catch {
408
+ return "";
409
+ }
410
+ })();
411
+ if (mergeBase && mergeBase !== baseTip && gitIsAncestor(projectRoot, mergeBase, baseTip)) {
412
+ return {
413
+ diagnosis: "integrate_isolated_ok",
414
+ headline: `${baseBranch} advanced during batch; feature branch needs sync`,
415
+ humanHead,
416
+ baseTip,
417
+ orchBranch: resolvedOrch,
418
+ };
419
+ }
420
+ }
421
+ return null;
422
+ }
423
+
424
+ return {
425
+ diagnosis: "integrate_isolated_ok",
426
+ headline: needsPathSync
427
+ ? `Isolated integrate landed on ${baseBranch}; working tree needs path sync`
428
+ : `Isolated integrate landed on ${baseBranch}; checkout needs sync`,
429
+ humanHead,
430
+ baseTip,
431
+ orchBranch: resolvedOrch,
432
+ };
433
+ }