pi-spine 2.1.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 (49) hide show
  1. package/bin/spine-batch.mjs +74 -5
  2. package/bin/spine-cli/verify.mjs +2 -18
  3. package/package.json +1 -1
  4. package/src/batch/attached-runner-promote.mjs +370 -0
  5. package/src/batch/attached-runner-reconcile.mjs +291 -0
  6. package/src/batch/attached-runner.mjs +24 -634
  7. package/src/batch/batch-guards.mjs +69 -0
  8. package/src/batch/contract-exec.mjs +483 -0
  9. package/src/batch/contract-parse.mjs +243 -0
  10. package/src/batch/contract-verify.mjs +32 -707
  11. package/src/batch/detached-diagnostics.mjs +255 -0
  12. package/src/batch/detached-run.mjs +326 -0
  13. package/src/batch/detached-start.mjs +18 -894
  14. package/src/batch/detached-wait.mjs +346 -0
  15. package/src/batch/engine-lanes/merge.mjs +25 -0
  16. package/src/batch/engine.mjs +8 -67
  17. package/src/batch/integrate-git.mjs +21 -0
  18. package/src/batch/integrate.mjs +5 -15
  19. package/src/batch/journal-rebuild-structural.mjs +352 -0
  20. package/src/batch/journal-rebuild.mjs +94 -347
  21. package/src/batch/lane-dirty-check-commit.mjs +361 -0
  22. package/src/batch/lane-dirty-check-git.mjs +298 -0
  23. package/src/batch/lane-dirty-check.mjs +31 -297
  24. package/src/batch/reconcile-batch.mjs +483 -0
  25. package/src/batch/reconcile-classify.mjs +433 -0
  26. package/src/batch/reconcile-diagnosis.mjs +459 -0
  27. package/src/batch/reconcile-light-cache.mjs +61 -0
  28. package/src/batch/reconcile-orphan.mjs +198 -0
  29. package/src/batch/reconcile.mjs +19 -1693
  30. package/src/batch/resume-multi-lanes.mjs +44 -149
  31. package/src/batch/resume-multi-queue.mjs +159 -0
  32. package/src/batch/resume-single-validate.mjs +25 -0
  33. package/src/batch/resume.mjs +3 -20
  34. package/src/batch/review-artifacts.mjs +419 -0
  35. package/src/batch/review-step-run.mjs +383 -0
  36. package/src/batch/review-step.mjs +451 -0
  37. package/src/batch/review.mjs +32 -1199
  38. package/src/batch/salvage-batch-list.mjs +291 -0
  39. package/src/batch/salvage-batch.mjs +417 -0
  40. package/src/batch/sequence-plan.mjs +234 -0
  41. package/src/batch/sequence-run.mjs +418 -0
  42. package/src/batch/sequence-wait.mjs +167 -0
  43. package/src/batch/sequence.mjs +22 -783
  44. package/src/batch/state-guards.mjs +284 -0
  45. package/src/batch/state-io.mjs +135 -0
  46. package/src/batch/state.mjs +27 -396
  47. package/src/batch/worker-heartbeat.mjs +375 -0
  48. package/src/batch/worker-host.mjs +50 -541
  49. package/src/batch/worker-spawn.mjs +315 -0
@@ -1,791 +1,30 @@
1
1
  /**
2
2
  * Planner wave sequence runner (GitHub #54 Tier 2 SP-C).
3
- * Chains separate batch starts through gate → integrate → complete per planner wave.
3
+ * Re-export shim — plan in sequence-plan.mjs, wait/land in sequence-wait.mjs, run in sequence-run.mjs (SP-607 / #192).
4
4
  */
5
5
 
6
- import { loadSpineConfig } from "../config/spine-config-load.mjs";
7
- import {
8
- DEFAULT_SEQUENCE_POLL_MS,
9
- resolveSequencePollMs,
10
- } from "../config/spine-config-schema.mjs";
11
- import {
12
- formatPreflightHuman,
13
- runBatchPreflight,
14
- resolveTasksRoot,
15
- } from "../config/spine-preflight-lib.mjs";
16
- import { filterPendingTaskIds } from "../planner/pending.mjs";
17
- import { buildPlan } from "../planner/index.mjs";
18
6
  import { resolveWaveTaskIds } from "../planner/wave-scope.mjs";
19
- import { discoverTasks } from "../tasks/packet/discover.mjs";
20
7
 
21
8
  export { resolveWaveTaskIds };
22
- import { startBatch } from "./engine.mjs";
23
- import { startBatchDetached } from "./detached-start.mjs";
24
- import { isProcessAlive } from "../process/liveness.mjs";
25
- import { approveIntegrateGate, loadGateRecord } from "./gate.mjs";
26
- import { integrateOrchToBase } from "./integrate.mjs";
27
- import { completeBatch } from "./lifecycle.mjs";
28
- import { reconcileBatch } from "./reconcile.mjs";
29
- import { loadSpineBatchState } from "./state.mjs";
30
- import { validateSequenceAutoApproveGate } from "../doctor/sequence-safety.mjs";
31
- import {
32
- buildSequenceSatisfiedTaskIds,
33
- collectWaveTaskOutcomes,
34
- isMergeBlockedBatchOutcome,
35
- planSequenceWaveTasks,
36
- resolveWaveAfterMergeBlocked,
37
- } from "./sequence-waves.mjs";
38
- import {
39
- buildSequenceStateSnapshot,
40
- finalizeSequenceState,
41
- haltSequenceAndPersist,
42
- persistSequenceState,
43
- prepareSequenceRunState,
44
- } from "./sequence-state.mjs";
45
9
 
46
- /** Release sequence profile (FR-STA-25 / SP-536). See docs/release/manifest-v1.10.0-example.md. */
47
- export const SEQUENCE_RELEASE_PROFILE = {
48
- id: "release",
49
- /** Max parallel tasks per planner wave (release-profiles.md minor). */
50
- maxTasksPerWave: 4,
51
- /** Operator-only pause points between waves; sequence does not auto-approve these. */
52
- gateOnlyPausePoints: ["gate_approve"],
53
- /** Dry-run prints the wave land loop without starting batches. */
54
- dryRunSupported: true,
55
- manifestDocPath: "docs/release/manifest-v1.10.0-example.md",
56
- };
57
-
58
- /**
59
- * @param {string|null|undefined} scope
60
- * @returns {boolean}
61
- */
62
- export function isReleaseSequenceScope(scope) {
63
- const normalized = String(scope ?? "").trim();
64
- return normalized.includes(",");
65
- }
66
-
67
- /**
68
- * @param {object} [params]
69
- * @param {string|null|undefined} [params.scope]
70
- * @param {string|null|undefined} [params.profile]
71
- * @returns {typeof SEQUENCE_RELEASE_PROFILE|null}
72
- */
73
- export function resolveSequenceProfile({ scope, profile = null } = {}) {
74
- const normalized = String(profile ?? "")
75
- .trim()
76
- .toLowerCase();
77
- if (normalized === "release") {
78
- return SEQUENCE_RELEASE_PROFILE;
79
- }
80
- if (isReleaseSequenceScope(scope)) {
81
- return SEQUENCE_RELEASE_PROFILE;
82
- }
83
- return null;
84
- }
85
-
86
- /**
87
- * @param {object} plan
88
- * @param {typeof SEQUENCE_RELEASE_PROFILE} [profile]
89
- */
90
- export function validateReleaseSequenceWaveCaps(plan, profile = SEQUENCE_RELEASE_PROFILE) {
91
- const waves = plan?.waves ?? [];
92
- /** @type {Array<{ waveIndex: number, taskCount: number }>} */
93
- const violations = [];
94
-
95
- for (const wave of waves) {
96
- const waveIndex = wave.waveIndex ?? wave.index ?? 0;
97
- const taskCount = Array.isArray(wave.taskIds) ? wave.taskIds.length : 0;
98
- if (taskCount > profile.maxTasksPerWave) {
99
- violations.push({ waveIndex, taskCount });
100
- }
101
- }
102
-
103
- if (violations.length === 0) {
104
- return { ok: true };
105
- }
106
-
107
- const lines = [
108
- `Release sequence profile wave cap exceeded (max ${profile.maxTasksPerWave} tasks per wave):`,
109
- ];
110
- for (const { waveIndex, taskCount } of violations) {
111
- lines.push(` Wave ${waveIndex}: ${taskCount} tasks`);
112
- }
113
- lines.push(`See ${profile.manifestDocPath} and release-profiles.md to split waves.`);
114
-
115
- return {
116
- ok: false,
117
- error: "release_wave_cap_exceeded",
118
- violations,
119
- output: `${lines.join("\n")}\n`,
120
- };
121
- }
122
-
123
- /**
124
- * @param {typeof SEQUENCE_RELEASE_PROFILE} profile
125
- */
126
- export function buildReleaseSequenceDryRunHeader(profile = SEQUENCE_RELEASE_PROFILE) {
127
- const pausePoints = profile.gateOnlyPausePoints.join(", ");
128
- return [
129
- `# Release sequence profile (${profile.id})`,
130
- `# Manifest: ${profile.manifestDocPath}`,
131
- `# Operator pause points: ${pausePoints} (per wave; publish approval is manual)`,
132
- `# Wave cap: max ${profile.maxTasksPerWave} tasks per wave`,
133
- ];
134
- }
135
-
136
- const WAVE_BATCH_SETTLED_DIAGNOSES = new Set([
137
- "completed",
138
- "completed_manual",
139
- "needs_integrate",
140
- "limbo_stale",
141
- ]);
142
- const WAVE_BATCH_FAILURE_DIAGNOSES = new Set(["failed", "aborted"]);
143
- const WAVE_BATCH_WAITING_DIAGNOSES = new Set([
144
- "running",
145
- "paused",
146
- "needs_retry",
147
- "worker_orphaned",
148
- "engine_orphaned",
149
- "state_drift",
150
- "needs_merge",
151
- "needs_replan",
152
- ]);
153
-
154
- function sleep(ms) {
155
- return new Promise((resolve) => setTimeout(resolve, ms));
156
- }
157
-
158
- export function isSequenceBatchSettled(diagnosis) {
159
- return Boolean(diagnosis && WAVE_BATCH_SETTLED_DIAGNOSES.has(diagnosis));
160
- }
161
-
162
- export function isSequenceBatchFailure(diagnosis) {
163
- return Boolean(diagnosis && WAVE_BATCH_FAILURE_DIAGNOSES.has(diagnosis));
164
- }
165
-
166
- export function isSequenceBatchWaiting(diagnosis) {
167
- return Boolean(diagnosis && WAVE_BATCH_WAITING_DIAGNOSES.has(diagnosis));
168
- }
169
-
170
- export async function waitForSequenceBatchTerminal({
171
- projectRoot,
172
- pollIntervalMs = DEFAULT_SEQUENCE_POLL_MS,
173
- timeoutMs = 120_000,
174
- enginePid = null,
175
- reconcileFn = reconcileBatch,
176
- }) {
177
- const deadline = Date.now() + timeoutMs;
178
- let useLightReconcile = false;
179
- while (Date.now() < deadline || isEngineStillRunning(enginePid, projectRoot)) {
180
- const reconciliation = reconcileFn({ projectRoot, light: useLightReconcile });
181
- useLightReconcile = true;
182
- const diagnosis = reconciliation.diagnosis;
183
- if (isSequenceBatchFailure(diagnosis)) {
184
- return {
185
- ok: false,
186
- halted: true,
187
- diagnosis,
188
- reconciliation,
189
- batchId: reconciliation.batchId ?? null,
190
- };
191
- }
192
- if (isSequenceBatchSettled(diagnosis)) {
193
- return {
194
- ok: true,
195
- diagnosis,
196
- reconciliation,
197
- batchId: reconciliation.batchId ?? null,
198
- };
199
- }
200
- await sleep(pollIntervalMs);
201
- }
202
- const reconciliation = reconcileFn({ projectRoot });
203
- return {
204
- ok: false,
205
- error: "timeout_waiting_for_batch",
206
- diagnosis: reconciliation.diagnosis ?? null,
207
- reconciliation,
208
- batchId: reconciliation.batchId ?? null,
209
- };
210
- }
211
-
212
- /**
213
- * Returns true when a detached engine PID is alive or the batch phase is active,
214
- * preventing sequence timeout while work is still in progress.
215
- */
216
- function isEngineStillRunning(enginePid, projectRoot) {
217
- if (enginePid && isProcessAlive(enginePid)) return true;
218
- const { raw } = loadSpineBatchState(projectRoot);
219
- const pid = raw?.enginePid ?? null;
220
- if (pid && isProcessAlive(pid)) return true;
221
- return false;
222
- }
223
-
224
- /**
225
- * @param {object} plan
226
- * @param {object} [options]
227
- * @param {number} [options.fromWave]
228
- * @param {number|null} [options.throughWave]
229
- */
230
- export function resolveSequenceWaves(plan, { fromWave = 0, throughWave = null } = {}) {
231
- const waves = plan?.waves ?? [];
232
- if (waves.length === 0) {
233
- return { ok: false, error: "plan_has_no_waves", output: "Planner scope has no waves." };
234
- }
235
-
236
- const lastWave = throughWave ?? waves.length - 1;
237
- if (!Number.isInteger(fromWave) || fromWave < 0 || fromWave >= waves.length) {
238
- return {
239
- ok: false,
240
- error: "from_wave_out_of_range",
241
- fromWave,
242
- waveCount: waves.length,
243
- output: `--from-wave ${fromWave} is out of range (plan has ${waves.length} wave(s)).`,
244
- };
245
- }
246
- if (!Number.isInteger(lastWave) || lastWave < fromWave || lastWave >= waves.length) {
247
- return {
248
- ok: false,
249
- error: "through_wave_out_of_range",
250
- throughWave: lastWave,
251
- fromWave,
252
- waveCount: waves.length,
253
- output: `--through-wave ${lastWave} is invalid for plan with ${waves.length} wave(s) (from-wave=${fromWave}).`,
254
- };
255
- }
256
-
257
- /** @type {Array<{ waveIndex: number, taskIds: string[] }>} */
258
- const entries = [];
259
- for (let waveIndex = fromWave; waveIndex <= lastWave; waveIndex++) {
260
- const resolved = resolveWaveTaskIds(plan, waveIndex);
261
- if (!resolved.ok) return resolved;
262
- entries.push({ waveIndex, taskIds: resolved.taskIds });
263
- }
264
-
265
- return { ok: true, waves: entries, waveCount: waves.length, fromWave, throughWave: lastWave };
266
- }
267
-
268
- /**
269
- * @param {object} params
270
- * @param {number} params.waveIndex
271
- * @param {string[]} params.taskIds
272
- * @param {boolean} [params.autoApproveGate]
273
- * @param {typeof SEQUENCE_RELEASE_PROFILE|null} [params.profile]
274
- */
275
- export function buildSequenceWaveCommands({
276
- waveIndex,
277
- taskIds,
278
- autoApproveGate = false,
279
- profile = null,
280
- }) {
281
- const taskScope = taskIds.join(" ");
282
- const gateOnly =
283
- profile?.gateOnlyPausePoints?.includes("gate_approve") && !autoApproveGate;
284
- const gateLine = autoApproveGate
285
- ? "spine gate approve"
286
- : gateOnly
287
- ? "spine gate approve # GATE-ONLY: operator approval required (release profile)"
288
- : "spine gate approve # when integrate gate is open";
289
- return [
290
- `# Wave ${waveIndex}`,
291
- `spine batch start ${taskScope}`,
292
- "spine status --diagnose # wait for terminal batch phase",
293
- gateLine,
294
- "spine integrate",
295
- "spine batch complete",
296
- ];
297
- }
298
-
299
- /**
300
- * @param {object} params
301
- * @param {object} params.plan
302
- * @param {number} [params.fromWave]
303
- * @param {number|null} [params.throughWave]
304
- * @param {boolean} [params.autoApproveGate]
305
- * @param {typeof SEQUENCE_RELEASE_PROFILE|null} [params.profile]
306
- */
307
- export function buildSequenceDryRunPlan({
308
- plan,
309
- fromWave = 0,
310
- throughWave = null,
311
- autoApproveGate = false,
312
- profile = null,
313
- }) {
314
- const wavePlan = resolveSequenceWaves(plan, { fromWave, throughWave });
315
- if (!wavePlan.ok) return wavePlan;
316
-
317
- if (profile) {
318
- const capCheck = validateReleaseSequenceWaveCaps(plan, profile);
319
- if (!capCheck.ok) return capCheck;
320
- }
321
-
322
- const waveCommands = wavePlan.waves.flatMap((wave) =>
323
- buildSequenceWaveCommands({
324
- waveIndex: wave.waveIndex,
325
- taskIds: wave.taskIds,
326
- autoApproveGate,
327
- profile,
328
- }),
329
- );
330
- const header = profile ? buildReleaseSequenceDryRunHeader(profile) : [];
331
- const commands = [...header, ...waveCommands];
332
-
333
- return {
334
- ok: true,
335
- profile: profile?.id ?? null,
336
- waves: wavePlan.waves,
337
- waveCount: wavePlan.waveCount,
338
- fromWave: wavePlan.fromWave,
339
- throughWave: wavePlan.throughWave,
340
- commands,
341
- output: `${commands.join("\n")}\n`,
342
- };
343
- }
344
-
345
- /**
346
- * @param {string} projectRoot
347
- * @param {string} scope
348
- */
349
- export function buildSequencePlan(projectRoot, scope) {
350
- const configResult = loadSpineConfig(projectRoot);
351
- const config = configResult.config ?? {};
352
- const tasksRoot = resolveTasksRoot(projectRoot, configResult);
353
- if (!tasksRoot) {
354
- return { ok: false, error: "tasks_root_missing", output: "Tasks root is not configured.\n" };
355
- }
356
-
357
- return { ok: true, plan: buildPlan({ scope, config, tasksRoot }), config, tasksRoot };
358
- }
359
-
360
- /**
361
- * @param {object} params
362
- * @param {string} params.projectRoot
363
- * @param {string|null} params.batchId
364
- * @param {boolean} [params.autoApproveGate]
365
- */
366
- export function runSequenceWaveLandLoop({ projectRoot, batchId, autoApproveGate = false }) {
367
- const reconciliation = reconcileBatch({ projectRoot });
368
- const diagnosis = reconciliation.diagnosis;
369
- const activeBatchId =
370
- batchId ?? reconciliation.batchId ?? loadSpineBatchState(projectRoot).raw?.batchId ?? null;
371
-
372
- if (!isSequenceBatchSettled(diagnosis)) {
373
- return {
374
- ok: false,
375
- step: "land_loop",
376
- error: "batch_not_settled",
377
- diagnosis,
378
- batchId: activeBatchId,
379
- headline: `Cannot land wave — batch diagnosis is ${diagnosis ?? "unknown"}`,
380
- };
381
- }
382
-
383
- const config = loadSpineConfig(projectRoot).config ?? {};
384
- const gateRequired = config.gates?.requireBeforeIntegrate !== false;
385
- const gate = activeBatchId ? loadGateRecord(projectRoot, activeBatchId) : null;
386
-
387
- if (gateRequired && gate?.status === "pending") {
388
- if (!autoApproveGate) {
389
- return {
390
- ok: false,
391
- step: "gate_approve",
392
- error: "gate_approval_required",
393
- diagnosis,
394
- batchId: activeBatchId,
395
- headline: "Integrate gate requires approval — pass autoApproveGate or approve manually",
396
- suggestedCommand: "spine gate approve",
397
- };
398
- }
399
- const approve = approveIntegrateGate({ projectRoot, batchId: activeBatchId });
400
- if (!approve.ok) {
401
- return { ok: false, step: "gate_approve", diagnosis, batchId: activeBatchId, ...approve };
402
- }
403
- }
404
-
405
- const integrate = integrateOrchToBase({ projectRoot, batchId: activeBatchId });
406
- if (!integrate.ok) {
407
- return { ok: false, step: "integrate", diagnosis, batchId: activeBatchId, ...integrate };
408
- }
409
-
410
- const complete = completeBatch({ projectRoot, batchId: activeBatchId });
411
- if (!complete.ok) {
412
- return { ok: false, step: "complete", diagnosis, batchId: activeBatchId, ...complete };
413
- }
414
-
415
- return {
416
- ok: true,
417
- diagnosis,
418
- batchId: activeBatchId,
419
- headline: `Wave batch ${activeBatchId} landed on main`,
420
- };
421
- }
422
-
423
- /**
424
- * @param {object} ctx
425
- */
426
- export async function runSequence(ctx) {
427
- const {
428
- projectRoot,
429
- plan,
430
- scope = "pending",
431
- fromWave = 0,
432
- throughWave = null,
433
- resume = false,
434
- attached = false,
435
- autoApproveGate = false,
436
- force = false,
437
- stopOnFailure = true,
438
- dryRun = false,
439
- skipPreflight = false,
440
- profile: profileOverride = null,
441
- pollIntervalMs: pollIntervalMsOverride,
442
- timeoutMs = 120_000,
443
- spineBin = null,
444
- startBatchFn = startBatch,
445
- } = ctx;
446
-
447
- const sequenceProfile = resolveSequenceProfile({ scope, profile: profileOverride });
448
-
449
- const configResult = loadSpineConfig(projectRoot);
450
- const pollIntervalMs =
451
- pollIntervalMsOverride ??
452
- resolveSequencePollMs({ config: configResult.config ?? {} });
453
-
454
- let sequenceState = null;
455
- let effectiveFromWave = fromWave;
456
- /** @type {Array<{ waveIndex: number, batchId: string|null, diagnosis: string|null }>} */
457
- let persistedCompletedWaves = [];
458
-
459
- const prepared = prepareSequenceRunState(projectRoot, {
460
- resume,
461
- scope,
462
- fromWave,
463
- throughWave,
464
- dryRun,
465
- });
466
- if (!prepared.ok) {
467
- return { ok: false, exitCode: 1, error: prepared.error, output: prepared.output };
468
- }
469
- sequenceState = prepared.sequenceState;
470
- effectiveFromWave = prepared.effectiveFromWave;
471
- persistedCompletedWaves = prepared.persistedCompletedWaves;
472
-
473
- const wavePlan = resolveSequenceWaves(plan, { fromWave: effectiveFromWave, throughWave });
474
- if (!wavePlan.ok) {
475
- return { ok: false, exitCode: 1, error: wavePlan.error, output: wavePlan.output };
476
- }
477
-
478
- const autoApproveCheck = validateSequenceAutoApproveGate({
479
- autoApproveGate,
480
- force,
481
- profile: sequenceProfile,
482
- });
483
- if (!autoApproveCheck.ok) {
484
- return {
485
- ok: false,
486
- exitCode: 1,
487
- error: autoApproveCheck.error,
488
- output: autoApproveCheck.output,
489
- suggestedCommand: autoApproveCheck.suggestedCommand,
490
- };
491
- }
492
-
493
- if (sequenceProfile) {
494
- const capCheck = validateReleaseSequenceWaveCaps(plan, sequenceProfile);
495
- if (!capCheck.ok) {
496
- return {
497
- ok: false,
498
- exitCode: 1,
499
- error: capCheck.error,
500
- output: capCheck.output,
501
- violations: capCheck.violations,
502
- };
503
- }
504
- }
505
-
506
- if (dryRun) {
507
- const dryPlan = buildSequenceDryRunPlan({
508
- plan,
509
- fromWave: effectiveFromWave,
510
- throughWave,
511
- autoApproveGate,
512
- profile: sequenceProfile,
513
- });
514
- if (!dryPlan.ok) {
515
- return {
516
- ok: false,
517
- exitCode: 1,
518
- error: dryPlan.error,
519
- output: dryPlan.output,
520
- violations: dryPlan.violations,
521
- };
522
- }
523
- return {
524
- ok: true,
525
- exitCode: 0,
526
- dryRun: true,
527
- profile: dryPlan.profile,
528
- waves: dryPlan.waves,
529
- commands: dryPlan.commands,
530
- output: dryPlan.output,
531
- };
532
- }
533
-
534
- if (!skipPreflight) {
535
- const preflight = runBatchPreflight({ projectRoot, skipDoctor: false });
536
- if (!preflight.ok) {
537
- return {
538
- ok: false,
539
- exitCode: preflight.exitCode ?? 1,
540
- error: "preflight_failed",
541
- output: formatPreflightHuman(preflight),
542
- };
543
- }
544
- }
545
-
546
- if (sequenceState) {
547
- persistSequenceState(projectRoot, sequenceState, persistedCompletedWaves);
548
- }
549
-
550
- /** @type {Array<{ waveIndex: number, batchId: string|null, diagnosis: string|null }>} */
551
- const completedWaves = [...persistedCompletedWaves];
552
-
553
- const tasksRoot = plan?.metadata?.tasksRoot ?? null;
554
- const discoveredTasks = tasksRoot ? discoverTasks(tasksRoot) : [];
555
- const pendingTaskIds = tasksRoot ? filterPendingTaskIds(discoveredTasks, tasksRoot) : [];
556
- const doneOnMainTaskIds = discoveredTasks
557
- .map((task) => task.taskId)
558
- .filter((taskId) => !pendingTaskIds.includes(taskId));
559
- /** @type {Array<{ succeeded?: string[], skipped?: string[], failed?: string[] }>} */
560
- const priorMergeOutcomes = [];
561
- let satisfiedTaskIds = buildSequenceSatisfiedTaskIds(doneOnMainTaskIds, priorMergeOutcomes);
562
- let mergeBlockedWaveIndex = null;
563
- let sequenceHadMergeBlocked = false;
564
- /** @type {string[]} */
565
- const sequenceOutputLines = [];
566
- /** @type {Array<{ waveIndex: number, message: string }>} */
567
- const skippedWaves = [];
568
-
569
- /**
570
- * @param {number} waveIndex
571
- * @param {string[]} waveTaskIds
572
- */
573
- function resolveRunnableWaveTasks(waveIndex, waveTaskIds) {
574
- if (mergeBlockedWaveIndex != null && waveIndex > mergeBlockedWaveIndex) {
575
- const lastOutcome = priorMergeOutcomes[priorMergeOutcomes.length - 1] ?? {};
576
- return resolveWaveAfterMergeBlocked({
577
- plan,
578
- waveIndex,
579
- waveTaskIds,
580
- satisfiedTaskIds,
581
- mergeBlockedWaveIndex,
582
- failedTaskIds: lastOutcome.failed ?? [],
583
- succeededTaskIds: lastOutcome.succeeded ?? [],
584
- });
585
- }
586
- return planSequenceWaveTasks({ plan, waveIndex, waveTaskIds, satisfiedTaskIds });
587
- }
588
-
589
- /**
590
- * @param {number} waveIndex
591
- * @param {object|null} batchState
592
- * @param {string} [fallbackMessage]
593
- */
594
- function absorbMergeBlockedWave(waveIndex, batchState, fallbackMessage = "") {
595
- const outcomes = collectWaveTaskOutcomes(batchState);
596
- priorMergeOutcomes.push(outcomes);
597
- satisfiedTaskIds = buildSequenceSatisfiedTaskIds(doneOnMainTaskIds, priorMergeOutcomes);
598
- mergeBlockedWaveIndex = waveIndex;
599
- sequenceHadMergeBlocked = true;
600
- const message =
601
- String(fallbackMessage ?? "").trim() ||
602
- String(batchState?.lastError ?? "").trim() ||
603
- `Wave merge blocked (§17.4 mixed-outcome policy) at wave ${waveIndex}.`;
604
- sequenceOutputLines.push(message);
605
- }
606
-
607
- for (const wave of wavePlan.waves) {
608
- const wavePlanResolution = resolveRunnableWaveTasks(wave.waveIndex, wave.taskIds);
609
- if (wavePlanResolution.action === "skip") {
610
- skippedWaves.push({
611
- waveIndex: wave.waveIndex,
612
- message: wavePlanResolution.message ?? `Sequence wave ${wave.waveIndex} skipped.`,
613
- });
614
- sequenceOutputLines.push(
615
- wavePlanResolution.message ?? `Sequence wave ${wave.waveIndex} skipped.`,
616
- );
617
- continue;
618
- }
619
- if (wavePlanResolution.message) {
620
- sequenceOutputLines.push(wavePlanResolution.message);
621
- } else if (wavePlanResolution.partialSkipMessage) {
622
- sequenceOutputLines.push(wavePlanResolution.partialSkipMessage);
623
- }
624
-
625
- const taskScope = wavePlanResolution.runnableTaskIds.join(" ");
626
- if (!taskScope) continue;
627
-
628
- let batchId = null;
629
- let detachedEnginePid = null;
630
-
631
- if (attached) {
632
- const startResult = await startBatchFn({
633
- projectRoot,
634
- scope: taskScope,
635
- skipPreflight: true,
636
- });
637
- if (!startResult.ok) {
638
- const reconciliation = reconcileBatch({ projectRoot });
639
- if (isMergeBlockedBatchOutcome({ startResult, reconciliation })) {
640
- absorbMergeBlockedWave(
641
- wave.waveIndex,
642
- loadSpineBatchState(projectRoot).raw,
643
- startResult.output ?? "",
644
- );
645
- continue;
646
- }
647
- if (!stopOnFailure) continue;
648
- return haltSequenceAndPersist(
649
- projectRoot,
650
- sequenceState,
651
- completedWaves,
652
- {
653
- waveIndex: wave.waveIndex,
654
- error: startResult.error ?? "batch_start_failed",
655
- completedWaves,
656
- },
657
- { output: startResult.output },
658
- );
659
- }
660
- batchId = startResult.batchId ?? loadSpineBatchState(projectRoot).raw?.batchId ?? null;
661
- } else {
662
- if (!spineBin) {
663
- return {
664
- ok: false,
665
- exitCode: 1,
666
- error: "spine_bin_required",
667
- output: "Detached sequence runs require spineBin.\n",
668
- };
669
- }
670
- const detached = await startBatchDetached({
671
- projectRoot,
672
- spineBin,
673
- scope: taskScope,
674
- skipPreflight: true,
675
- waitTerminal: false,
676
- });
677
- detachedEnginePid = detached.result?.enginePid ?? null;
678
- if (!detached.ok) {
679
- const engineStartedButTimeout =
680
- detached.result?.status === "engine_started" &&
681
- detached.result?.batchId &&
682
- isProcessAlive(detachedEnginePid);
683
- if (engineStartedButTimeout) {
684
- batchId = detached.result.batchId;
685
- } else {
686
- if (!stopOnFailure) continue;
687
- return haltSequenceAndPersist(
688
- projectRoot,
689
- sequenceState,
690
- completedWaves,
691
- {
692
- waveIndex: wave.waveIndex,
693
- error: detached.result?.error ?? "batch_start_failed",
694
- completedWaves,
695
- },
696
- { output: detached.output },
697
- );
698
- }
699
- } else {
700
- batchId = detached.result?.batchId ?? null;
701
- }
702
- }
703
-
704
- const wait = attached
705
- ? {
706
- ok: true,
707
- batchId,
708
- diagnosis: reconcileBatch({ projectRoot }).diagnosis ?? null,
709
- }
710
- : await waitForSequenceBatchTerminal({ projectRoot, pollIntervalMs, timeoutMs, enginePid: detachedEnginePid ?? null });
711
-
712
- if (!wait.ok || isSequenceBatchFailure(wait.diagnosis)) {
713
- const reconciliation = wait.reconciliation ?? reconcileBatch({ projectRoot });
714
- if (isMergeBlockedBatchOutcome({ reconciliation })) {
715
- absorbMergeBlockedWave(
716
- wave.waveIndex,
717
- reconciliation.signals?.raw ?? loadSpineBatchState(projectRoot).raw,
718
- reconciliation.headline ?? "",
719
- );
720
- continue;
721
- }
722
- if (!stopOnFailure) continue;
723
- return haltSequenceAndPersist(projectRoot, sequenceState, completedWaves, {
724
- waveIndex: wave.waveIndex,
725
- error: wait.error ?? "batch_failed",
726
- diagnosis: wait.diagnosis ?? null,
727
- batchId: wait.batchId ?? batchId,
728
- completedWaves,
729
- });
730
- }
731
-
732
- const land = runSequenceWaveLandLoop({ projectRoot, batchId: wait.batchId ?? batchId, autoApproveGate });
733
- if (!land.ok) {
734
- if (!stopOnFailure) continue;
735
- return haltSequenceAndPersist(
736
- projectRoot,
737
- sequenceState,
738
- completedWaves,
739
- {
740
- waveIndex: wave.waveIndex,
741
- error: land.error ?? "land_loop_failed",
742
- diagnosis: land.diagnosis ?? wait.diagnosis ?? null,
743
- batchId: land.batchId ?? wait.batchId ?? batchId,
744
- completedWaves,
745
- },
746
- { step: land.step, headline: land.headline },
747
- );
748
- }
749
-
750
- const waveResult = {
751
- waveIndex: wave.waveIndex,
752
- batchId: land.batchId ?? wait.batchId ?? batchId,
753
- diagnosis: wait.diagnosis ?? null,
754
- };
755
- completedWaves.push(waveResult);
756
-
757
- for (const taskId of wavePlanResolution.runnableTaskIds) {
758
- satisfiedTaskIds.add(taskId);
759
- }
760
-
761
- if (sequenceState) {
762
- const lastBatchId = waveResult.batchId ?? sequenceState.lastBatchId ?? null;
763
- sequenceState = buildSequenceStateSnapshot(sequenceState, {
764
- completedWaves,
765
- lastBatchId,
766
- status: "active",
767
- });
768
- persistSequenceState(projectRoot, sequenceState, completedWaves, { lastBatchId });
769
- }
770
- }
771
-
772
- finalizeSequenceState(projectRoot, sequenceState, completedWaves, plan);
773
-
774
- if (completedWaves.length > 0) {
775
- sequenceOutputLines.push(`Sequence completed ${completedWaves.length} wave(s).`);
776
- }
777
-
778
- const partialMergeBlocked = sequenceHadMergeBlocked && completedWaves.length < wavePlan.waves.length;
779
-
780
- return {
781
- ok: !sequenceHadMergeBlocked,
782
- exitCode: sequenceHadMergeBlocked ? 1 : 0,
783
- completedWaves,
784
- skippedWaves,
785
- mergeBlocked: sequenceHadMergeBlocked,
786
- partial: partialMergeBlocked,
787
- waveCount: wavePlan.waves.length,
788
- resumed: resume,
789
- output: `${sequenceOutputLines.join("\n")}\n`,
790
- };
791
- }
10
+ export {
11
+ SEQUENCE_RELEASE_PROFILE,
12
+ buildReleaseSequenceDryRunHeader,
13
+ buildSequenceDryRunPlan,
14
+ buildSequencePlan,
15
+ buildSequenceWaveCommands,
16
+ isReleaseSequenceScope,
17
+ resolveSequenceProfile,
18
+ resolveSequenceWaves,
19
+ validateReleaseSequenceWaveCaps,
20
+ } from "./sequence-plan.mjs";
21
+
22
+ export {
23
+ isSequenceBatchFailure,
24
+ isSequenceBatchSettled,
25
+ isSequenceBatchWaiting,
26
+ runSequenceWaveLandLoop,
27
+ waitForSequenceBatchTerminal,
28
+ } from "./sequence-wait.mjs";
29
+
30
+ export { runSequence } from "./sequence-run.mjs";