pi-spine 2.2.0 → 2.3.1

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 (56) hide show
  1. package/bin/spine-cli/verify.mjs +15 -46
  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/diagnosis.mjs +35 -4
  15. package/src/batch/engine-lanes/orch-sync.mjs +126 -0
  16. package/src/batch/engine-lanes.mjs +69 -0
  17. package/src/batch/engine.mjs +8 -67
  18. package/src/batch/integrate-git.mjs +21 -0
  19. package/src/batch/integrate.mjs +5 -15
  20. package/src/batch/journal-rebuild-structural.mjs +352 -0
  21. package/src/batch/journal-rebuild.mjs +16 -348
  22. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  23. package/src/batch/lane-dirty-check-git.mjs +298 -0
  24. package/src/batch/lane-dirty-check.mjs +31 -297
  25. package/src/batch/reconcile-batch.mjs +495 -0
  26. package/src/batch/reconcile-classify.mjs +433 -0
  27. package/src/batch/reconcile-diagnosis.mjs +459 -0
  28. package/src/batch/reconcile-light-cache.mjs +61 -0
  29. package/src/batch/reconcile-orphan.mjs +198 -0
  30. package/src/batch/reconcile.mjs +19 -1693
  31. package/src/batch/resume-multi-lanes.mjs +6 -148
  32. package/src/batch/resume-multi-queue.mjs +159 -0
  33. package/src/batch/resume-single-validate.mjs +25 -0
  34. package/src/batch/resume.mjs +3 -20
  35. package/src/batch/review-artifacts.mjs +419 -0
  36. package/src/batch/review-step-run.mjs +383 -0
  37. package/src/batch/review-step.mjs +451 -0
  38. package/src/batch/review.mjs +32 -1199
  39. package/src/batch/salvage-batch-list.mjs +291 -0
  40. package/src/batch/salvage-batch.mjs +10 -284
  41. package/src/batch/sequence-plan.mjs +234 -0
  42. package/src/batch/sequence-run.mjs +418 -0
  43. package/src/batch/sequence-wait.mjs +167 -0
  44. package/src/batch/sequence.mjs +22 -783
  45. package/src/batch/state-guards.mjs +284 -0
  46. package/src/batch/state-io.mjs +135 -0
  47. package/src/batch/state.mjs +27 -396
  48. package/src/batch/worker-heartbeat.mjs +382 -0
  49. package/src/batch/worker-host.mjs +56 -548
  50. package/src/batch/worker-spawn.mjs +326 -0
  51. package/src/batch/worktree.mjs +68 -0
  52. package/src/config/preflight/integrate-plan.mjs +6 -1
  53. package/src/config/preflight/loc-capstone.mjs +274 -0
  54. package/src/config/spine-preflight-lib.mjs +14 -0
  55. package/src/planner/index.mjs +14 -3
  56. package/src/process/terminate-tree.mjs +154 -0
@@ -0,0 +1,346 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Detached batch wait/poll helpers — state polling after spawn (SP-598).
4
+ */
5
+
6
+ import { loadSpineConfig } from "../config/spine-config-load.mjs";
7
+ import { runBatchPreflight } from "../config/spine-preflight-lib.mjs";
8
+ import { loadGateRecord } from "./gate.mjs";
9
+ import { reconcileBatch } from "./reconcile.mjs";
10
+ import { assessRunningPhaseResumeEligibility } from "./resume-multi-validate.mjs";
11
+ import { prepareOrphanResumeHandoff } from "./resume-engine.mjs";
12
+ import {
13
+ ACTIVE_PHASES,
14
+ loadSpineBatchState,
15
+ recordBatchEnginePid,
16
+ saveSpineBatchState,
17
+ TERMINAL_BATCH_PHASES,
18
+ } from "./state.mjs";
19
+
20
+ /** Diagnoses that benefit from blocking until resume engine reaches terminal phase. */
21
+ const RESUME_WAIT_TERMINAL_DIAGNOSES = new Set([
22
+ "engine_orphaned",
23
+ "worker_orphaned",
24
+ "state_drift",
25
+ "needs_integrate",
26
+ ]);
27
+
28
+ /**
29
+ * Default detached resume to --wait-terminal after orphan/drift diagnoses.
30
+ *
31
+ * @param {string} projectRoot
32
+ * @param {boolean} explicitWaitTerminal
33
+ * @param {boolean} noWaitTerminal
34
+ */
35
+ export function resolveDefaultResumeWaitTerminal(
36
+ projectRoot,
37
+ explicitWaitTerminal,
38
+ noWaitTerminal = false,
39
+ ) {
40
+ if (explicitWaitTerminal) return true;
41
+ if (noWaitTerminal) return false;
42
+ const reconciliation = reconcileBatch({ projectRoot });
43
+ const diagnosis = reconciliation.diagnosis;
44
+ if (diagnosis && RESUME_WAIT_TERMINAL_DIAGNOSES.has(diagnosis)) {
45
+ return true;
46
+ }
47
+ return false;
48
+ }
49
+
50
+ /** @type {ReadonlySet<string>} */
51
+ const TERMINAL_TASK_STATUSES = new Set(["succeeded", "failed", "skipped", "aborted"]);
52
+
53
+ /** Default wait when --wait-terminal blocks on orphan/drift resume (real workers exceed 30s). */
54
+ const DETACHED_WAIT_TERMINAL_TIMEOUT_MS = 2 * 60 * 60 * 1000;
55
+
56
+ /**
57
+ * @param {boolean} waitTerminal
58
+ * @param {number} [explicitTimeoutMs]
59
+ */
60
+ export function resolveDetachedWaitTimeoutMs(waitTerminal, explicitTimeoutMs) {
61
+ if (Number.isFinite(explicitTimeoutMs) && explicitTimeoutMs > 0) {
62
+ return explicitTimeoutMs;
63
+ }
64
+ return waitTerminal ? DETACHED_WAIT_TERMINAL_TIMEOUT_MS : 30_000;
65
+ }
66
+
67
+ /**
68
+ * @param {number} ms
69
+ */
70
+ function sleep(ms) {
71
+ return new Promise((resolve) => setTimeout(resolve, ms));
72
+ }
73
+
74
+ /**
75
+ * @param {object|null|undefined} raw
76
+ * @param {string|null|undefined} taskId
77
+ */
78
+ function resumedTaskReachedTerminal(raw, taskId) {
79
+ if (!taskId || !raw || !Array.isArray(raw.tasks)) return false;
80
+ const task = raw.tasks.find((entry) => entry?.taskId === taskId);
81
+ return Boolean(task && TERMINAL_TASK_STATUSES.has(String(task.status ?? "")));
82
+ }
83
+
84
+ /**
85
+ * @param {string} projectRoot
86
+ * @param {object|null|undefined} raw
87
+ */
88
+ function detachedResumeRequiresIntegrateGate(projectRoot, raw) {
89
+ if (!raw?.batchId || String(raw.phase ?? "") !== "completed") {
90
+ return false;
91
+ }
92
+ if (!raw.orchBranch) {
93
+ return false;
94
+ }
95
+ const config = loadSpineConfig(projectRoot).config ?? {};
96
+ return config.gates?.requireBeforeIntegrate === true;
97
+ }
98
+
99
+ /**
100
+ * @param {string} projectRoot
101
+ * @param {object|null|undefined} raw
102
+ */
103
+ function detachedResumeIntegrateGateReady(projectRoot, raw) {
104
+ if (!detachedResumeRequiresIntegrateGate(projectRoot, raw)) {
105
+ return true;
106
+ }
107
+ return Boolean(loadGateRecord(projectRoot, String(raw.batchId)));
108
+ }
109
+
110
+ /**
111
+ * @param {object|null|undefined} raw
112
+ * @param {string|null|undefined} taskId
113
+ * @param {number} updatedAtBefore
114
+ */
115
+ function evaluateDetachedResumeWait(raw, taskId, updatedAtBefore) {
116
+ if (!raw?.batchId) return null;
117
+ const updatedAt = Number(raw.updatedAt ?? 0);
118
+ if (updatedAt <= updatedAtBefore) return null;
119
+
120
+ if (TERMINAL_BATCH_PHASES.has(String(raw.phase ?? ""))) {
121
+ return {
122
+ ok: true,
123
+ status: "resume_completed",
124
+ batchId: raw.batchId,
125
+ phase: raw.phase,
126
+ };
127
+ }
128
+
129
+ if (resumedTaskReachedTerminal(raw, taskId)) {
130
+ return {
131
+ ok: true,
132
+ status: "resume_completed",
133
+ batchId: raw.batchId,
134
+ phase: raw.phase,
135
+ };
136
+ }
137
+
138
+ return null;
139
+ }
140
+
141
+ /**
142
+ * @param {string} projectRoot
143
+ * @param {number|null} enginePid
144
+ */
145
+ export function persistDetachedEnginePid(projectRoot, enginePid) {
146
+ const pid = Number(enginePid);
147
+ if (!Number.isFinite(pid) || pid <= 0) return;
148
+ const { raw } = loadSpineBatchState(projectRoot);
149
+ if (!raw) return;
150
+ recordBatchEnginePid(raw, pid);
151
+ saveSpineBatchState(projectRoot, raw);
152
+ }
153
+
154
+ /**
155
+ * Kill a stale detached engine and persist cleared PID before spawning resume engine (SP-254).
156
+ * Resume child records its own PID after terminateStaleDetachedEngine runs in-process.
157
+ * Running-phase orphan resume (SP-296) clears a dead engine PID without requiring pause first.
158
+ *
159
+ * @param {string} projectRoot
160
+ */
161
+ export function prepareDetachedResumeEngineHandoff(projectRoot) {
162
+ const loaded = loadSpineBatchState(projectRoot);
163
+ if (!loaded.raw) {
164
+ return { ok: false, reason: "no_active_batch" };
165
+ }
166
+
167
+ const state = loaded.raw;
168
+ const batchId = String(state.batchId ?? "");
169
+ const fromPhase = String(state.phase ?? "");
170
+ const orphanEligibility =
171
+ fromPhase === "running"
172
+ ? assessRunningPhaseResumeEligibility({ projectRoot, state })
173
+ : { engineConfirmedDead: false, allowOrphanResume: false };
174
+ const handoff = prepareOrphanResumeHandoff({
175
+ projectRoot,
176
+ state,
177
+ batchId,
178
+ fromPhase,
179
+ orphanResume: orphanEligibility.allowOrphanResume,
180
+ engineConfirmedDead: orphanEligibility.engineConfirmedDead,
181
+ });
182
+ saveSpineBatchState(projectRoot, state, { bypassWriteGuard: true });
183
+
184
+ return {
185
+ ok: true,
186
+ batchId,
187
+ fromPhase,
188
+ terminateResult: handoff.terminateResult,
189
+ orphanResume: orphanEligibility.allowOrphanResume,
190
+ };
191
+ }
192
+
193
+ /**
194
+ * @param {object} params
195
+ * @param {string} params.projectRoot
196
+ * @param {boolean} [params.skipPreflight]
197
+ */
198
+ export function runDetachedStartPreflight({ projectRoot, skipPreflight = false }) {
199
+ if (skipPreflight) {
200
+ return { ok: true };
201
+ }
202
+ const preflight = runBatchPreflight({ projectRoot, skipDoctor: false });
203
+ if (!preflight.ok) {
204
+ return {
205
+ ok: false,
206
+ exitCode: preflight.exitCode ?? 1,
207
+ error: "preflight_failed",
208
+ output: preflight.output,
209
+ };
210
+ }
211
+ return { ok: true };
212
+ }
213
+
214
+ /**
215
+ * @param {object} params
216
+ * @param {string} params.projectRoot
217
+ * @param {string | null} [params.previousBatchId]
218
+ * @param {number} [params.timeoutMs]
219
+ * @param {boolean} [params.waitTerminal]
220
+ */
221
+ export async function waitForDetachedBatchStart({
222
+ projectRoot,
223
+ previousBatchId = null,
224
+ timeoutMs = 30_000,
225
+ waitTerminal = false,
226
+ }) {
227
+ const deadline = Date.now() + timeoutMs;
228
+ /** @type {string|null} */
229
+ let startedBatchId = null;
230
+
231
+ while (Date.now() < deadline) {
232
+ const { raw } = loadSpineBatchState(projectRoot);
233
+ const batchId = raw?.batchId ?? null;
234
+ if (batchId && batchId !== previousBatchId) {
235
+ if (raw.phase === "failed" || raw.phase === "aborted") {
236
+ return {
237
+ ok: false,
238
+ error: "batch_engine_failed",
239
+ batchId,
240
+ phase: raw.phase,
241
+ lastError: raw.lastError ?? null,
242
+ };
243
+ }
244
+
245
+ if (TERMINAL_BATCH_PHASES.has(String(raw.phase ?? "")) || raw.phase === "paused") {
246
+ return {
247
+ ok: true,
248
+ status: "start_completed",
249
+ batchId,
250
+ phase: raw.phase,
251
+ };
252
+ }
253
+
254
+ if (ACTIVE_PHASES.has(raw.phase)) {
255
+ startedBatchId = batchId;
256
+ if (!waitTerminal) {
257
+ return {
258
+ ok: true,
259
+ status: "engine_started",
260
+ batchId,
261
+ phase: raw.phase,
262
+ };
263
+ }
264
+ }
265
+ }
266
+ await sleep(200);
267
+ }
268
+
269
+ if (startedBatchId) {
270
+ return {
271
+ ok: false,
272
+ error: "timeout_waiting_for_batch",
273
+ batchId: startedBatchId,
274
+ status: "engine_started",
275
+ };
276
+ }
277
+
278
+ return { ok: false, error: "timeout_waiting_for_batch" };
279
+ }
280
+
281
+ /**
282
+ * @param {object} params
283
+ * @param {string} params.projectRoot
284
+ * @param {string} params.batchId
285
+ * @param {number} params.updatedAtBefore
286
+ * @param {string|null|undefined} [params.taskId]
287
+ * @param {number} [params.timeoutMs]
288
+ * @param {boolean} [params.waitTerminal]
289
+ */
290
+ export async function waitForDetachedBatchResume({
291
+ projectRoot,
292
+ batchId,
293
+ updatedAtBefore,
294
+ taskId = null,
295
+ timeoutMs = 30_000,
296
+ waitTerminal = false,
297
+ }) {
298
+ const deadline = Date.now() + timeoutMs;
299
+ /** @type {boolean} */
300
+ let engineStarted = false;
301
+
302
+ while (Date.now() < deadline) {
303
+ const { raw } = loadSpineBatchState(projectRoot);
304
+ if (raw?.batchId !== batchId) {
305
+ await sleep(200);
306
+ continue;
307
+ }
308
+
309
+ if (raw.phase === "failed" || raw.phase === "aborted") {
310
+ return {
311
+ ok: false,
312
+ error: "batch_engine_failed",
313
+ batchId,
314
+ phase: raw.phase,
315
+ lastError: raw.lastError ?? null,
316
+ };
317
+ }
318
+
319
+ const updatedAt = Number(raw.updatedAt ?? 0);
320
+ if (raw.phase === "running" && updatedAt > updatedAtBefore) {
321
+ engineStarted = true;
322
+ if (!waitTerminal) {
323
+ return {
324
+ ok: true,
325
+ status: "engine_started",
326
+ batchId,
327
+ phase: raw.phase,
328
+ };
329
+ }
330
+ }
331
+
332
+ const completed = evaluateDetachedResumeWait(raw, taskId, updatedAtBefore);
333
+ if (completed && detachedResumeIntegrateGateReady(projectRoot, raw)) {
334
+ return completed;
335
+ }
336
+
337
+ await sleep(200);
338
+ }
339
+
340
+ return {
341
+ ok: false,
342
+ error: "timeout_waiting_for_resume",
343
+ batchId,
344
+ engineStarted,
345
+ };
346
+ }
@@ -56,6 +56,25 @@ export { inferLaunchFailureFromWorkerOutputTail, inferLaunchFailureKind } from "
56
56
 
57
57
  const INVALID_BARE_RETRY_FORCE = /^spine batch retry --force$/;
58
58
 
59
+ /**
60
+ * Gate-ready batches must not headline historical merge/gitignored blockers (#195 / FR-REL231-01).
61
+ *
62
+ * @param {string} diagnosis
63
+ * @param {object} [ctx]
64
+ * @param {boolean} [ctx.allTasksTerminalSuccess]
65
+ * @param {boolean} [ctx.integrateGateOpen]
66
+ * @returns {boolean}
67
+ */
68
+ export function isGateReadyHeadlineContext(diagnosis, ctx = {}) {
69
+ if (diagnosis === "needs_integrate") {
70
+ return true;
71
+ }
72
+ if (ctx.allTasksTerminalSuccess === true && ctx.integrateGateOpen === true) {
73
+ return true;
74
+ }
75
+ return false;
76
+ }
77
+
59
78
  /**
60
79
  * Retry suggestions must include a task id; journal salvage payloads may be stale.
61
80
  *
@@ -121,10 +140,16 @@ const REVIEW_SPAWN_FAILURE_EXIT_REASONS = new Set([
121
140
  * @param {string[]|null} [ctx.gitignoredPaths]
122
141
  */
123
142
  export function buildSuggestedCommand(diagnosis, ctx = {}) {
124
- if (ctx.mergeGitignoredFailure) {
143
+ const preferGateReady = isGateReadyHeadlineContext(diagnosis, ctx);
144
+ // Prefer gate-approve / land-loop next step over recovered merge/gitignored repair (#195).
145
+ if (ctx.mergeGitignoredFailure && !preferGateReady) {
125
146
  return buildGitignoredMergeRepairCommand(ctx.taskBranch, ctx.gitignoredPaths);
126
147
  }
127
- if (ctx.mergeFailed && (diagnosis === "failed" || diagnosis === "needs_retry")) {
148
+ if (
149
+ ctx.mergeFailed &&
150
+ !preferGateReady &&
151
+ (diagnosis === "failed" || diagnosis === "needs_retry")
152
+ ) {
128
153
  return "spine batch resume --force";
129
154
  }
130
155
  if (ctx.phase === "merge_blocked") {
@@ -263,12 +288,18 @@ export function buildSuggestedCommand(diagnosis, ctx = {}) {
263
288
  */
264
289
  export function buildHeadline(diagnosis, ctx = {}) {
265
290
  const batchLabel = ctx.batchId ? `Batch ${ctx.batchId}` : "Batch";
291
+ const preferGateReady = isGateReadyHeadlineContext(diagnosis, ctx);
266
292
 
267
- if (ctx.mergeGitignoredFailure) {
293
+ // Historical merge/gitignored signals stay in diagnose signals — not the primary headline (#195).
294
+ if (ctx.mergeGitignoredFailure && !preferGateReady) {
268
295
  return `${batchLabel} merge blocked by gitignored paths on a lane branch — drop cached ignored files, then resume`;
269
296
  }
270
297
 
271
- if (ctx.mergeFailed && (diagnosis === "failed" || diagnosis === "needs_retry")) {
298
+ if (
299
+ ctx.mergeFailed &&
300
+ !preferGateReady &&
301
+ (diagnosis === "failed" || diagnosis === "needs_retry")
302
+ ) {
272
303
  return buildMergeFailureHeadline(batchLabel, ctx);
273
304
  }
274
305
 
@@ -0,0 +1,126 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Orch→lane sync when satisfied deps share File Scope (FR-REL231-03 / #191).
4
+ */
5
+
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { resolveTasksRootPath } from "../../config/env-overrides.mjs";
9
+ import { discoverTasks, loadDependenciesJson } from "../../tasks/packet/index.mjs";
10
+ import { loadTaskFileScopePaths } from "./queue.mjs";
11
+ import { syncLaneWorktreeFromOrch } from "../worktree.mjs";
12
+
13
+ /**
14
+ * @param {string} projectRoot
15
+ * @param {object} [config]
16
+ */
17
+ function resolveBatchTasksRoot(projectRoot, config) {
18
+ return resolveTasksRootPath(projectRoot, config) ?? path.join(projectRoot, "spine-tasks");
19
+ }
20
+
21
+ /**
22
+ * @param {string} tasksRoot
23
+ * @param {string} taskId
24
+ * @param {object[]} [stateTasks]
25
+ */
26
+ function resolveTaskFolderPath(tasksRoot, taskId, stateTasks = []) {
27
+ const fromState = stateTasks.find((entry) => entry?.taskId === taskId)?.taskFolder;
28
+ if (typeof fromState === "string" && fromState.trim() && fs.existsSync(fromState)) {
29
+ return fromState;
30
+ }
31
+ if (!fs.existsSync(tasksRoot)) return null;
32
+ const match = discoverTasks(tasksRoot).find((entry) => entry.taskId === taskId);
33
+ return match?.folderPath ?? null;
34
+ }
35
+
36
+ /**
37
+ * Satisfied deps that share at least one File Scope path with the current task.
38
+ *
39
+ * @param {object} params
40
+ * @param {string} params.projectRoot
41
+ * @param {object} params.state
42
+ * @param {string} params.taskId
43
+ * @param {string[]} params.fileScopePaths
44
+ * @param {object} [params.config]
45
+ * @returns {Array<{ depId: string, overlap: string[] }>}
46
+ */
47
+ export function collectSharedScopeSatisfiedDeps({
48
+ projectRoot,
49
+ state,
50
+ taskId,
51
+ fileScopePaths,
52
+ config = {},
53
+ }) {
54
+ if (!Array.isArray(fileScopePaths) || fileScopePaths.length === 0) return [];
55
+
56
+ const tasksRoot = resolveBatchTasksRoot(projectRoot, config);
57
+ const deps = loadDependenciesJson(tasksRoot).tasks?.[taskId] ?? [];
58
+ if (!Array.isArray(deps) || deps.length === 0) return [];
59
+
60
+ const scopeSet = new Set(fileScopePaths);
61
+ const stateTasks = Array.isArray(state?.tasks) ? state.tasks : [];
62
+ /** @type {Array<{ depId: string, overlap: string[] }>} */
63
+ const shared = [];
64
+
65
+ for (const depId of deps) {
66
+ const depTask = stateTasks.find((entry) => entry?.taskId === depId);
67
+ if (!depTask || depTask.status !== "succeeded") continue;
68
+
69
+ const depFolder = resolveTaskFolderPath(tasksRoot, depId, stateTasks);
70
+ if (!depFolder) continue;
71
+
72
+ const scopeResult = loadTaskFileScopePaths(depFolder);
73
+ if (!scopeResult.ok) continue;
74
+
75
+ const overlap = (scopeResult.fileScopePaths ?? []).filter((filePath) =>
76
+ scopeSet.has(filePath),
77
+ );
78
+ if (overlap.length > 0) {
79
+ shared.push({ depId, overlap });
80
+ }
81
+ }
82
+
83
+ return shared;
84
+ }
85
+
86
+ /**
87
+ * @param {object} params
88
+ * @returns {{ ok: true, synced: boolean, skipped?: boolean, sharedDeps: Array<{ depId: string, overlap: string[] }>, headSha?: string } | { ok: false, error: string, sharedDeps: Array<{ depId: string, overlap: string[] }> }}
89
+ */
90
+ export function ensureLaneSyncedForSharedScopeDeps({
91
+ projectRoot,
92
+ state,
93
+ taskId,
94
+ fileScopePaths,
95
+ worktreePath,
96
+ config = {},
97
+ }) {
98
+ const sharedDeps = collectSharedScopeSatisfiedDeps({
99
+ projectRoot,
100
+ state,
101
+ taskId,
102
+ fileScopePaths,
103
+ config,
104
+ });
105
+ if (sharedDeps.length === 0) {
106
+ return { ok: true, synced: false, skipped: true, sharedDeps };
107
+ }
108
+
109
+ try {
110
+ const result = syncLaneWorktreeFromOrch({
111
+ worktreePath,
112
+ orchBranch: state?.orchBranch,
113
+ projectRoot,
114
+ });
115
+ return {
116
+ ok: true,
117
+ synced: !result.skipped,
118
+ skipped: result.skipped,
119
+ sharedDeps,
120
+ headSha: result.headSha,
121
+ };
122
+ } catch (err) {
123
+ const message = err instanceof Error ? err.message : String(err);
124
+ return { ok: false, error: message, sharedDeps };
125
+ }
126
+ }
@@ -22,6 +22,7 @@ import {
22
22
  } from "./state.mjs";
23
23
  import { runWorker } from "./worker-host.mjs";
24
24
  import { runCodeReviewPhase, runFinalReviewPhase } from "./engine-lanes/review.mjs";
25
+ import { ensureLaneSyncedForSharedScopeDeps } from "./engine-lanes/orch-sync.mjs";
25
26
 
26
27
  export {
27
28
  buildTasksAndLanesFromPlan,
@@ -46,6 +47,12 @@ export {
46
47
  tryAutoResolveRulesManifestMergeConflict,
47
48
  } from "./engine-lanes/merge.mjs";
48
49
 
50
+ export { syncLaneWorktreeFromOrch } from "./worktree.mjs";
51
+ export {
52
+ collectSharedScopeSatisfiedDeps,
53
+ ensureLaneSyncedForSharedScopeDeps,
54
+ } from "./engine-lanes/orch-sync.mjs";
55
+
49
56
  /**
50
57
  * @param {string} fromPhase
51
58
  * @param {string} toPhase
@@ -121,6 +128,68 @@ export async function runTaskOnLane({
121
128
  }
122
129
  const fileScopePaths = scopeResult.fileScopePaths;
123
130
 
131
+ const syncResult = ensureLaneSyncedForSharedScopeDeps({
132
+ projectRoot,
133
+ state,
134
+ taskId,
135
+ fileScopePaths,
136
+ worktreePath: wt,
137
+ config,
138
+ });
139
+ if (!syncResult.ok) {
140
+ task.status = "failed";
141
+ task.endedAt = Date.now();
142
+ task.exitReason = "orch_sync_failed";
143
+ if (!task.startedAt) task.startedAt = Date.now();
144
+ updateSegmentForTask(state, taskId, "failed");
145
+ recomputeTaskCounters(state);
146
+ saveEngineBatchState(projectRoot, state);
147
+ appendJournalEvent(projectRoot, batchId, "lane.orch_sync_failed", {
148
+ taskId,
149
+ laneNumber,
150
+ laneId: lane.laneId,
151
+ correlationId: laneCorrelationId,
152
+ error: syncResult.error,
153
+ sharedDeps: syncResult.sharedDeps,
154
+ });
155
+ appendJournalEvent(projectRoot, batchId, "task.failed", {
156
+ taskId,
157
+ laneNumber,
158
+ laneId: lane.laneId,
159
+ correlationId: laneCorrelationId,
160
+ classification: "orch_sync_failed",
161
+ exitCode: 1,
162
+ output: syncResult.error,
163
+ });
164
+ recordLaneTaskMetric({
165
+ projectRoot,
166
+ batchId,
167
+ task,
168
+ config,
169
+ taskFolder: taskFolderInWorktree,
170
+ });
171
+ return {
172
+ ok: false,
173
+ workerResult: {
174
+ ok: false,
175
+ classification: "orch_sync_failed",
176
+ output: syncResult.error,
177
+ exitCode: 1,
178
+ },
179
+ };
180
+ }
181
+ if (syncResult.synced) {
182
+ appendJournalEvent(projectRoot, batchId, "lane.orch_synced", {
183
+ taskId,
184
+ laneNumber,
185
+ laneId: lane.laneId,
186
+ correlationId: laneCorrelationId,
187
+ orchBranch: state.orchBranch,
188
+ headSha: syncResult.headSha,
189
+ sharedDeps: syncResult.sharedDeps,
190
+ });
191
+ }
192
+
124
193
  task.status = "running";
125
194
  if (!task.startedAt) task.startedAt = Date.now();
126
195
  updateSegmentForTask(state, taskId, "running");