pi-spine 1.4.0 → 1.5.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -188,12 +188,23 @@ Run **after Step A.5 — Clarify** and **before Step B — Slice**. Authoring-on
188
188
  |------|----------|
189
189
  | **Size** | Target **M** (2–4 h). **L** → split when possible. **XL** → **must** split into multiple S/M tasks with dependencies. |
190
190
  | **Steps** | Max **4** implementation steps per task (exclude Testing & Verification / Documentation & Delivery). More steps → split. |
191
+ | **Two-deliverable test** | If your Steps can be grouped into two clusters with no data dependency between them, split into separate tasks even if the step count is ≤4. The #1 sizing mistake is bundling two independent deliverables in one M task. |
191
192
  | **Parallel waves** | Prefer **≤4** M-sized tasks per wave; 8-task mega-waves stall pi workers (see Phase 15 / SP-086–088). |
192
193
  | **Scope** | One deliverable per task; disjoint **File Scope** when tasks can run in parallel. |
193
194
  | **IDs** | Use `Next Task ID` from CONTEXT.md; increment after each new task. Greenfield spine projects typically use `SP-###`; Taskplane migrants may keep `TP-###`. |
194
195
  | **Waves** | Order via `## Dependencies` and `{tasksRoot}/dependencies.json`. |
195
196
  | **Review** | Score complexity (below). Do not default to Level 0 for implementation work. |
196
197
 
198
+ **Two-deliverable split evidence (Phase 55):** Every superseded composite task split into exactly two children because it bundled independent deliverables:
199
+
200
+ | Superseded | Split into |
201
+ |------------|------------|
202
+ | SP-419 | SP-466, SP-467 |
203
+ | SP-428 | SP-468, SP-469 |
204
+ | SP-430 | SP-470, SP-471 |
205
+ | SP-436 | SP-474, SP-475 |
206
+ | SP-461 | SP-478, SP-479 |
207
+
197
208
  ### Step C.5: Analyze (optional — LLM structural review after slice)
198
209
 
199
210
  Run **after** Step B and **before** Step C when using **full** authoring mode and the operator wants an LLM-authored structural review of drafted packets. Authoring-only — `spine tasks validate` does **not** require analyze artifacts.
@@ -285,7 +296,7 @@ Use [references/prompt-template.md](references/prompt-template.md). Spine-specif
285
296
  - **Worker tools** — when Review Level > 0, steps must note `spine_review_step` after each step
286
297
  - **Testing step (required for all tasks)** — every packet MUST include `### Step N: Testing & Verification` inside `## Steps`, placed **before** `## Completion Criteria`. This applies to **docs-only Review Level 0 tasks** as well — omitting the step causes `prompt_parse_failed` at batch launch (SP-075). Docs-only tasks still run the full test suite; they may omit the coverage-gate checkbox when no application code changes.
287
298
  - **Coverage gate** — when the task changes application code, add a coverage verification checkbox in the Testing step using `testing.testWithCoverage` (≥77% line coverage policy)
288
- - **Contract (required for new SP-\* tasks)** — add `## Contract` after `## File Scope` using [references/contract-template.md](references/contract-template.md). Include `testCommand` for code tasks; use `` `true` `` for docs-only S tasks. When using `fileScopeMustNotChange`, follow parallel-only semantics and never ban `spine-tasks/**` (see contract template and [File Scope and parallel batches](#file-scope-and-parallel-batches)). Legacy `TP-*` packets may omit Contract when `contract.legacyTaskIdPrefixes` includes `TP-`.
299
+ - **Contract (required for new SP-\* tasks)** — add `## Contract` after `## File Scope` using [references/contract-template.md](references/contract-template.md). Include `testCommand` for code tasks; use `` `true` `` for docs-only S tasks. When `testCommand` is `` `true` `` (docs-only), **always** include `fileScopeMustChange` listing at least one documentation deliverable path — without it, workers can pass contract by creating only `.DONE` (SP-214 batch `20260612T204048`, SP-457 batch `20260703T022335`). When using `fileScopeMustNotChange`, follow parallel-only semantics and never ban `spine-tasks/**` (see contract template and [File Scope and parallel batches](#file-scope-and-parallel-batches)). Legacy `TP-*` packets may omit Contract when `contract.legacyTaskIdPrefixes` includes `TP-`.
289
300
  - **Completion** — worker creates `{task-folder}/.DONE`; batch engine may auto-commit remaining work
290
301
 
291
302
  ### Step 5: Create STATUS.md
@@ -464,6 +475,7 @@ Before reporting launch commands:
464
475
  - [ ] Complexity scored; review level assigned (0–3)
465
476
  - [ ] Size S/M/L — split if XL
466
477
  - [ ] PROMPT.md from template: Mission, Dependencies, Context, File Scope, Contract (SP-\*), Steps, Do NOT, Git Commit Convention, Amendments
478
+ - [ ] If `testCommand` is `` `true` ``, `fileScopeMustChange` MUST list at least one deliverable path
467
479
  - [ ] `### Step N: Testing & Verification` present inside `## Steps` before `## Completion Criteria` (required even for docs-only Review Level 0)
468
480
  - [ ] STATUS.md with matching steps (hydration markers where needed)
469
481
  - [ ] `dependencies.json` updated when task has deps
@@ -36,8 +36,8 @@ Avoid `` `bin/a.mjs,bin/b.mjs` `` — `tasks validate` warns (or errors in requi
36
36
 
37
37
  | Field | When to include | Value format |
38
38
  |-------|-----------------|--------------|
39
- | `testCommand` | **Required** for code tasks (Review Level ≥ 1, Size M/L, or implementation steps) | Shell command in backticks; max 500 chars; no newlines. Use `` `true` `` for docs-only S tasks with no code changes. |
40
- | `fileScopeMustChange` | When you need proof specific paths were touched | Comma-separated paths/globs relative to repo root; **one backtick per path** (not `` `a.mjs,b.mjs` ``). Trailing `/` means directory prefix match (e.g. `src/domain/types/` matches any file under that directory). |
39
+ | `testCommand` | **Required** for code tasks (Review Level ≥ 1, Size M/L, or implementation steps) | Shell command in backticks; max 500 chars; no newlines. Use `` `true` `` for docs-only S tasks with no code changes. When `` `true` ``, **always** pair with `fileScopeMustChange` (see below). |
40
+ | `fileScopeMustChange` | When you need proof specific paths were touched; **required** when `testCommand` is `` `true` `` | Comma-separated paths/globs relative to repo root; **one backtick per path** (not `` `a.mjs,b.mjs` ``). Trailing `/` means directory prefix match (e.g. `src/domain/types/` matches any file under that directory). For docs-only tasks, list at least one documentation deliverable path — without it, workers can pass contract by creating only `.DONE` (SP-214 batch `20260612T204048`, SP-457 batch `20260703T022335`). |
41
41
  | `fileScopeMustNotChange` | When **parallel lanes** must not collide on product paths (see semantics below) | Comma-separated paths/globs relative to repo root; **one backtick per path** |
42
42
  | `minLineCoverage` | When task changes application code | Integer 0–100 (pi-spine policy: **77**) |
43
43
  | `artifactsMustExist` | When deliverables must exist on disk | Comma-separated file paths; **one backtick per path** |
@@ -118,12 +118,15 @@ Symptom in journal: `testCommand` passes but `fileScopeMustNotChange` fails with
118
118
 
119
119
  ### Docs-only Review Level 0 (no application code)
120
120
 
121
+ When `testCommand` is `` `true` ``, **always** include `fileScopeMustChange` listing at least one documentation file the task must modify. Without it, workers can pass contract by creating only `.DONE` — two batches were rejected for this reason (SP-214 batch `20260612T204048`, SP-457 batch `20260703T022335`).
122
+
121
123
  ```markdown
122
124
  ## Contract
123
125
 
124
126
  | Field | Value |
125
127
  |-------|-------|
126
128
  | testCommand | `true` |
129
+ | fileScopeMustChange | `docs/adoption/operator-runbook.md` |
127
130
  ```
128
131
 
129
132
  ### Scope guard for parallel wave
@@ -190,7 +193,7 @@ Reviewers spawn as **fresh sessions** with no memory of the worker session (FR-R
190
193
 
191
194
  | Task type | Recommended `testCommand` |
192
195
  |-----------|---------------------------|
193
- | Docs-only, no code changes | `` `true` `` |
196
+ | Docs-only, no code changes | `` `true` `` **and** `fileScopeMustChange` with at least one deliverable doc path |
194
197
  | Single module, targeted tests exist | `` `npm test -- tests/feature.test.mjs` `` or `` `flutter test test/unit/services/foo_test.dart` `` |
195
198
  | Full-suite safe in lane worktree | `` `npm run typecheck && SPINE_WORKER_STUB=1 npm test` `` |
196
199
  | Coverage gate required (pi-spine ≥77%) | `` `npm run coverage:check` `` |
@@ -47,6 +47,7 @@ Output path: `{tasksRoot}/_authoring/{slug}/checklist.md`
47
47
  - [ ] CHK030 — Is the project's test command identifiable for downstream tasks? [Testability]
48
48
  - [ ] CHK031 — Are verifiable behaviors separated from implementation details? [Clarity]
49
49
  - [ ] CHK032 — Can workers derive a Testing step from the requirements? [Completeness]
50
+ - [ ] CHK033 — If `testCommand` is `` `true` `` (docs-only), does Contract include `fileScopeMustChange` with at least one deliverable path? [Completeness, Gap]
50
51
 
51
52
  ## Non-functional requirements
52
53
 
@@ -25,6 +25,27 @@ export const CONTRACT_TEST_DEFAULT_RETRIES = 1;
25
25
  /** Default delay in ms between testCommand retry attempts. */
26
26
  export const CONTRACT_TEST_RETRY_DELAY_MS = 5000;
27
27
 
28
+ /**
29
+ * Worker-only env keys stripped from contract testCommand subprocesses so full-suite
30
+ * tests match operator re-run outside worker-host (SP-491, issue #155).
31
+ */
32
+ export const CONTRACT_TEST_WORKER_ENV_KEYS = ["SPINE_IS_WORKER"];
33
+
34
+ /**
35
+ * Build env for contract testCommand subprocess — omits worker-only keys inherited from
36
+ * worker-host.mjs that would false-fail batch-spawn integration tests (SP-482 guard).
37
+ *
38
+ * @param {NodeJS.ProcessEnv} [sourceEnv]
39
+ * @returns {NodeJS.ProcessEnv}
40
+ */
41
+ export function buildContractTestEnv(sourceEnv = process.env) {
42
+ const env = { ...sourceEnv };
43
+ for (const key of CONTRACT_TEST_WORKER_ENV_KEYS) {
44
+ delete env[key];
45
+ }
46
+ return env;
47
+ }
48
+
28
49
  /**
29
50
  * @param {string} taskId
30
51
  * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
@@ -324,6 +345,7 @@ export function runContractTestCommand(worktreePath, command, options = {}) {
324
345
  const shellFlag = process.platform === "win32" ? "/c" : "-c";
325
346
  const result = spawnSync(shell, [shellFlag, trimmed], {
326
347
  cwd: worktreePath,
348
+ env: buildContractTestEnv(),
327
349
  encoding: "utf-8",
328
350
  stdio: ["ignore", "pipe", "pipe"],
329
351
  timeout: 10 * 60 * 1000,
@@ -6,6 +6,7 @@ import { appendJournalEvent } from "../journal.mjs";
6
6
  import { commitLaneWorktree, gitPorcelain } from "../lane-commit.mjs";
7
7
  import {
8
8
  resolvePostLaneCommitPorcelain,
9
+ sanitizeGitignoredArtifactsBeforeLaneCommit,
9
10
  sanitizeOutOfScopeCoverageBeforeLaneCommit,
10
11
  } from "../lane-dirty-check.mjs";
11
12
  import {
@@ -53,6 +54,11 @@ export function commitLaneAndValidateWorktree({
53
54
  config,
54
55
  }) {
55
56
  const preCommitPorcelain = gitPorcelain(worktreePath);
57
+ sanitizeGitignoredArtifactsBeforeLaneCommit(worktreePath, {
58
+ projectRoot,
59
+ porcelain: preCommitPorcelain,
60
+ enabled: config?.lanes?.autoCleanGitignoredArtifacts !== false,
61
+ });
56
62
  sanitizeOutOfScopeCoverageBeforeLaneCommit(worktreePath, fileScopePaths, {
57
63
  projectRoot,
58
64
  porcelain: preCommitPorcelain,
@@ -16,6 +16,19 @@ import { runWorktreeSetupHook } from "./worktree.mjs";
16
16
  */
17
17
  export const COVERAGE_ARTIFACT_MARKERS = ["/coverage/", "coverage/"];
18
18
 
19
+ /**
20
+ * Path segments for gitignored build artifacts that npm test and similar tools
21
+ * regenerate in lane worktrees (SP-471 / #95).
22
+ */
23
+ export const GITIGNORED_ARTIFACT_MARKERS = [
24
+ "/node_modules/",
25
+ "node_modules/",
26
+ "/coverage/",
27
+ "coverage/",
28
+ "/__pycache__/",
29
+ "__pycache__/",
30
+ ];
31
+
19
32
  /**
20
33
  * @param {string} filePath
21
34
  * @returns {boolean}
@@ -359,6 +372,112 @@ export function resolveSetupHookSymlinkDriftPorcelain(
359
372
  * @param {string[]} gitignoredPaths
360
373
  * @returns {{ indexTracked: string[], worktreeOnly: string[] }}
361
374
  */
375
+ /**
376
+ * @param {string} filePath
377
+ * @returns {boolean}
378
+ */
379
+ export function isGitignoredArtifactPath(filePath) {
380
+ if (!filePath || typeof filePath !== "string") return false;
381
+ const normalized = filePath.replace(/\\/g, "/");
382
+ return GITIGNORED_ARTIFACT_MARKERS.some(
383
+ (marker) =>
384
+ normalized === marker.slice(0, -1) ||
385
+ normalized.startsWith(marker) ||
386
+ normalized.includes(marker),
387
+ );
388
+ }
389
+
390
+ /**
391
+ * @param {string} filePath
392
+ * @returns {string | null}
393
+ */
394
+ function gitignoredArtifactRootForPath(filePath) {
395
+ const normalized = filePath.replace(/\\/g, "/");
396
+ for (const marker of ["/node_modules/", "/coverage/", "/__pycache__/"]) {
397
+ const markerIdx = normalized.indexOf(marker);
398
+ if (markerIdx >= 0) {
399
+ return normalized.slice(0, markerIdx + marker.length - 1);
400
+ }
401
+ }
402
+ if (normalized === "node_modules" || normalized.startsWith("node_modules/")) {
403
+ return "node_modules";
404
+ }
405
+ if (normalized === "coverage" || normalized.startsWith("coverage/")) {
406
+ return "coverage";
407
+ }
408
+ if (normalized === "__pycache__" || normalized.startsWith("__pycache__/")) {
409
+ return "__pycache__";
410
+ }
411
+ return null;
412
+ }
413
+
414
+ /**
415
+ * @param {string[]} filePaths
416
+ * @returns {string[]}
417
+ */
418
+ export function listGitignoredArtifactRoots(filePaths) {
419
+ const roots = new Set();
420
+ for (const filePath of filePaths) {
421
+ if (!isGitignoredArtifactPath(filePath)) continue;
422
+ const root = gitignoredArtifactRootForPath(filePath);
423
+ if (root) roots.add(root);
424
+ }
425
+ return [...roots].sort();
426
+ }
427
+
428
+ /**
429
+ * @param {string} worktreePath
430
+ * @returns {string[]}
431
+ */
432
+ function listIgnoredUntrackedPaths(worktreePath) {
433
+ let output = "";
434
+ try {
435
+ output = execFileSync("git", ["ls-files", "-o", "-i", "--exclude-standard"], {
436
+ cwd: worktreePath,
437
+ encoding: "utf-8",
438
+ stdio: ["ignore", "pipe", "pipe"],
439
+ }).trim();
440
+ } catch {
441
+ return [];
442
+ }
443
+ if (!output) return [];
444
+ return output.split("\n").map((line) => line.trim()).filter(Boolean);
445
+ }
446
+
447
+ /**
448
+ * Auto-clean worktree-only gitignored artifacts under known dirs before lane dirty gate.
449
+ *
450
+ * @param {string} worktreePath
451
+ * @param {{ projectRoot?: string, porcelain?: string, enabled?: boolean }} [options]
452
+ * @returns {{ cleanedRoots: string[] }}
453
+ */
454
+ export function sanitizeGitignoredArtifactsBeforeLaneCommit(
455
+ worktreePath,
456
+ { projectRoot, porcelain, enabled = true } = {},
457
+ ) {
458
+ if (!enabled) return { cleanedRoots: [] };
459
+
460
+ const identityRoot = projectRoot ?? worktreePath;
461
+ const rawPorcelain = typeof porcelain === "string" ? porcelain : "";
462
+ const dirtyPaths = listPorcelainPaths(rawPorcelain);
463
+ const ignoredUntrackedPaths = listIgnoredUntrackedPaths(worktreePath);
464
+ const gitignoredCandidates = [...new Set([...dirtyPaths, ...ignoredUntrackedPaths])];
465
+ if (gitignoredCandidates.length === 0) {
466
+ return { cleanedRoots: [] };
467
+ }
468
+
469
+ const { worktreeOnly } = classifyGitignoredPaths(worktreePath, gitignoredCandidates);
470
+ const artifactRoots = listGitignoredArtifactRoots(worktreeOnly);
471
+ for (const root of artifactRoots) {
472
+ gitExec(worktreePath, ["clean", "-fdX", "--", root], {
473
+ projectRoot: identityRoot,
474
+ throwOnError: false,
475
+ });
476
+ }
477
+
478
+ return { cleanedRoots: artifactRoots };
479
+ }
480
+
362
481
  export function classifyGitignoredPaths(worktreePath, gitignoredPaths) {
363
482
  if (!Array.isArray(gitignoredPaths) || gitignoredPaths.length === 0) {
364
483
  return { indexTracked: [], worktreeOnly: [] };
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Planner sequence wave policy after merge_blocked (GitHub #82, SP-437).
3
+ * Evaluates whether later waves can run per dependencies.json / plan.tasks deps.
4
+ */
5
+
6
+ /**
7
+ * @param {object|null|undefined} batchState
8
+ * @returns {{ succeeded: string[], failed: string[], skipped: string[], pending: string[] }}
9
+ */
10
+ export function collectWaveTaskOutcomes(batchState) {
11
+ const tasks = batchState?.tasks ?? [];
12
+ /** @type {string[]} */
13
+ const succeeded = [];
14
+ /** @type {string[]} */
15
+ const failed = [];
16
+ /** @type {string[]} */
17
+ const skipped = [];
18
+ /** @type {string[]} */
19
+ const pending = [];
20
+
21
+ for (const task of tasks) {
22
+ const taskId = String(task?.taskId ?? "");
23
+ if (!taskId) continue;
24
+ const status = String(task?.status ?? "");
25
+ if (status === "succeeded") succeeded.push(taskId);
26
+ else if (status === "failed") failed.push(taskId);
27
+ else if (status === "skipped") skipped.push(taskId);
28
+ else if (status === "pending" || status === "running") pending.push(taskId);
29
+ }
30
+
31
+ return { succeeded, failed, skipped, pending };
32
+ }
33
+
34
+ /**
35
+ * @param {object} [params]
36
+ * @param {object|null} [params.startResult]
37
+ * @param {object|null} [params.reconciliation]
38
+ */
39
+ export function isMergeBlockedBatchOutcome({ startResult = null, reconciliation = null } = {}) {
40
+ if (startResult?.error === "mixed_outcome_merge_blocked") return true;
41
+ const phase = reconciliation?.phase ?? reconciliation?.signals?.raw?.phase ?? null;
42
+ if (phase === "merge_blocked") return true;
43
+ const lastError = String(reconciliation?.signals?.raw?.lastError ?? "");
44
+ if (phase === "failed" && lastError.includes("§17.4")) return true;
45
+ return false;
46
+ }
47
+
48
+ /**
49
+ * @param {Iterable<string>} doneOnMainTaskIds
50
+ * @param {Array<{ succeeded?: string[], skipped?: string[] }>} priorOutcomes
51
+ */
52
+ export function buildSequenceSatisfiedTaskIds(doneOnMainTaskIds = [], priorOutcomes = []) {
53
+ const satisfied = new Set(doneOnMainTaskIds);
54
+ for (const outcome of priorOutcomes) {
55
+ for (const taskId of outcome.succeeded ?? []) satisfied.add(taskId);
56
+ for (const taskId of outcome.skipped ?? []) satisfied.add(taskId);
57
+ }
58
+ return satisfied;
59
+ }
60
+
61
+ /**
62
+ * @param {object} params
63
+ * @param {object} params.plan
64
+ * @param {string[]} params.waveTaskIds
65
+ * @param {Set<string>} params.satisfiedTaskIds
66
+ */
67
+ export function evaluateWaveTaskDependencies({ plan, waveTaskIds, satisfiedTaskIds }) {
68
+ const tasks = plan?.tasks ?? {};
69
+ /** @type {string[]} */
70
+ const runnable = [];
71
+ /** @type {Array<{ taskId: string, unsatisfiedDeps: string[] }>} */
72
+ const blocked = [];
73
+
74
+ for (const taskId of waveTaskIds) {
75
+ const deps = tasks[taskId]?.dependencies ?? [];
76
+ const unsatisfiedDeps = deps.filter((depId) => !satisfiedTaskIds.has(depId));
77
+ if (unsatisfiedDeps.length === 0) {
78
+ runnable.push(taskId);
79
+ } else {
80
+ blocked.push({ taskId, unsatisfiedDeps });
81
+ }
82
+ }
83
+
84
+ return { runnable, blocked };
85
+ }
86
+
87
+ /**
88
+ * @param {object} params
89
+ * @param {number} params.waveIndex
90
+ * @param {Array<{ taskId: string, unsatisfiedDeps: string[] }>} params.blocked
91
+ * @param {number} params.mergeBlockedWaveIndex
92
+ * @param {string[]} [params.failedTaskIds]
93
+ * @param {string[]} [params.succeededTaskIds]
94
+ */
95
+ export function formatSequenceWaveSkipMessage({
96
+ waveIndex,
97
+ blocked,
98
+ mergeBlockedWaveIndex,
99
+ failedTaskIds = [],
100
+ succeededTaskIds = [],
101
+ }) {
102
+ const lines = [
103
+ `Sequence wave ${waveIndex} skipped (§17.4 mixed-outcome policy — wave ${mergeBlockedWaveIndex} merge blocked).`,
104
+ ];
105
+
106
+ if (succeededTaskIds.length > 0) {
107
+ lines.push(`Prior wave succeeded task(s): ${succeededTaskIds.join(", ")}.`);
108
+ }
109
+ if (failedTaskIds.length > 0) {
110
+ lines.push(`Prior wave failed task(s): ${failedTaskIds.join(", ")}.`);
111
+ }
112
+
113
+ for (const entry of blocked) {
114
+ lines.push(
115
+ ` ${entry.taskId}: blocked by unsatisfied dependencies ${entry.unsatisfiedDeps.join(", ")}.`,
116
+ );
117
+ }
118
+
119
+ if (blocked.length === 0) {
120
+ lines.push(` No runnable tasks in wave ${waveIndex}.`);
121
+ }
122
+
123
+ lines.push(
124
+ "Retry or skip failed tasks on the blocked wave, or land succeeded lanes before dependencies unblock.",
125
+ );
126
+ return lines.join("\n");
127
+ }
128
+
129
+ /**
130
+ * @param {object} params
131
+ * @param {object} params.plan
132
+ * @param {number} params.waveIndex
133
+ * @param {string[]} params.waveTaskIds
134
+ * @param {Set<string>} params.satisfiedTaskIds
135
+ * @param {number} params.mergeBlockedWaveIndex
136
+ * @param {string[]} [params.failedTaskIds]
137
+ * @param {string[]} [params.succeededTaskIds]
138
+ */
139
+ export function resolveWaveAfterMergeBlocked({
140
+ plan,
141
+ waveIndex,
142
+ waveTaskIds,
143
+ satisfiedTaskIds,
144
+ mergeBlockedWaveIndex,
145
+ failedTaskIds = [],
146
+ succeededTaskIds = [],
147
+ }) {
148
+ const { runnable, blocked } = evaluateWaveTaskDependencies({
149
+ plan,
150
+ waveTaskIds,
151
+ satisfiedTaskIds,
152
+ });
153
+
154
+ if (runnable.length === 0) {
155
+ return {
156
+ action: "skip",
157
+ runnableTaskIds: [],
158
+ blocked,
159
+ message: formatSequenceWaveSkipMessage({
160
+ waveIndex,
161
+ blocked,
162
+ mergeBlockedWaveIndex,
163
+ failedTaskIds,
164
+ succeededTaskIds,
165
+ }),
166
+ };
167
+ }
168
+
169
+ return {
170
+ action: "continue",
171
+ runnableTaskIds: runnable,
172
+ blocked,
173
+ skippedTaskIds: blocked.map((entry) => entry.taskId),
174
+ message:
175
+ blocked.length > 0
176
+ ? formatSequenceWaveSkipMessage({
177
+ waveIndex,
178
+ blocked,
179
+ mergeBlockedWaveIndex,
180
+ failedTaskIds,
181
+ succeededTaskIds,
182
+ })
183
+ : null,
184
+ };
185
+ }
186
+
187
+ /**
188
+ * @param {object} params
189
+ * @param {object} params.plan
190
+ * @param {number} params.waveIndex
191
+ * @param {string[]} params.waveTaskIds
192
+ * @param {Set<string>} params.satisfiedTaskIds
193
+ */
194
+ export function planSequenceWaveTasks({ plan, waveIndex, waveTaskIds, satisfiedTaskIds }) {
195
+ const { runnable, blocked } = evaluateWaveTaskDependencies({
196
+ plan,
197
+ waveTaskIds,
198
+ satisfiedTaskIds,
199
+ });
200
+
201
+ if (runnable.length === 0) {
202
+ return {
203
+ action: "skip",
204
+ runnableTaskIds: [],
205
+ blocked,
206
+ message: `Sequence wave ${waveIndex} skipped — no tasks with satisfied dependencies.`,
207
+ };
208
+ }
209
+
210
+ return {
211
+ action: "continue",
212
+ runnableTaskIds: runnable,
213
+ blocked,
214
+ partialSkipMessage:
215
+ blocked.length > 0
216
+ ? `Sequence wave ${waveIndex}: skipping tasks with unsatisfied dependencies: ${blocked
217
+ .map((entry) => entry.taskId)
218
+ .join(", ")}.`
219
+ : null,
220
+ };
221
+ }
@@ -9,8 +9,10 @@ import {
9
9
  runBatchPreflight,
10
10
  resolveTasksRoot,
11
11
  } from "../config/spine-preflight-lib.mjs";
12
+ import { filterPendingTaskIds } from "../planner/pending.mjs";
12
13
  import { buildPlan } from "../planner/index.mjs";
13
14
  import { resolveWaveTaskIds } from "../planner/wave-scope.mjs";
15
+ import { discoverTasks } from "../tasks/packet/discover.mjs";
14
16
 
15
17
  export { resolveWaveTaskIds };
16
18
  import { startBatch } from "./engine.mjs";
@@ -22,6 +24,13 @@ import { completeBatch } from "./lifecycle.mjs";
22
24
  import { reconcileBatch } from "./reconcile.mjs";
23
25
  import { loadSpineBatchState } from "./state.mjs";
24
26
  import { validateSequenceAutoApproveGate } from "../doctor/sequence-safety.mjs";
27
+ import {
28
+ buildSequenceSatisfiedTaskIds,
29
+ collectWaveTaskOutcomes,
30
+ isMergeBlockedBatchOutcome,
31
+ planSequenceWaveTasks,
32
+ resolveWaveAfterMergeBlocked,
33
+ } from "./sequence-waves.mjs";
25
34
  import {
26
35
  buildSequenceStateSnapshot,
27
36
  finalizeSequenceState,
@@ -379,8 +388,81 @@ export async function runSequence(ctx) {
379
388
  /** @type {Array<{ waveIndex: number, batchId: string|null, diagnosis: string|null }>} */
380
389
  const completedWaves = [...persistedCompletedWaves];
381
390
 
391
+ const tasksRoot = plan?.metadata?.tasksRoot ?? null;
392
+ const discoveredTasks = tasksRoot ? discoverTasks(tasksRoot) : [];
393
+ const pendingTaskIds = tasksRoot ? filterPendingTaskIds(discoveredTasks, tasksRoot) : [];
394
+ const doneOnMainTaskIds = discoveredTasks
395
+ .map((task) => task.taskId)
396
+ .filter((taskId) => !pendingTaskIds.includes(taskId));
397
+ /** @type {Array<{ succeeded?: string[], skipped?: string[], failed?: string[] }>} */
398
+ const priorMergeOutcomes = [];
399
+ let satisfiedTaskIds = buildSequenceSatisfiedTaskIds(doneOnMainTaskIds, priorMergeOutcomes);
400
+ let mergeBlockedWaveIndex = null;
401
+ let sequenceHadMergeBlocked = false;
402
+ /** @type {string[]} */
403
+ const sequenceOutputLines = [];
404
+ /** @type {Array<{ waveIndex: number, message: string }>} */
405
+ const skippedWaves = [];
406
+
407
+ /**
408
+ * @param {number} waveIndex
409
+ * @param {string[]} waveTaskIds
410
+ */
411
+ function resolveRunnableWaveTasks(waveIndex, waveTaskIds) {
412
+ if (mergeBlockedWaveIndex != null && waveIndex > mergeBlockedWaveIndex) {
413
+ const lastOutcome = priorMergeOutcomes[priorMergeOutcomes.length - 1] ?? {};
414
+ return resolveWaveAfterMergeBlocked({
415
+ plan,
416
+ waveIndex,
417
+ waveTaskIds,
418
+ satisfiedTaskIds,
419
+ mergeBlockedWaveIndex,
420
+ failedTaskIds: lastOutcome.failed ?? [],
421
+ succeededTaskIds: lastOutcome.succeeded ?? [],
422
+ });
423
+ }
424
+ return planSequenceWaveTasks({ plan, waveIndex, waveTaskIds, satisfiedTaskIds });
425
+ }
426
+
427
+ /**
428
+ * @param {number} waveIndex
429
+ * @param {object|null} batchState
430
+ * @param {string} [fallbackMessage]
431
+ */
432
+ function absorbMergeBlockedWave(waveIndex, batchState, fallbackMessage = "") {
433
+ const outcomes = collectWaveTaskOutcomes(batchState);
434
+ priorMergeOutcomes.push(outcomes);
435
+ satisfiedTaskIds = buildSequenceSatisfiedTaskIds(doneOnMainTaskIds, priorMergeOutcomes);
436
+ mergeBlockedWaveIndex = waveIndex;
437
+ sequenceHadMergeBlocked = true;
438
+ const message =
439
+ String(fallbackMessage ?? "").trim() ||
440
+ String(batchState?.lastError ?? "").trim() ||
441
+ `Wave merge blocked (§17.4 mixed-outcome policy) at wave ${waveIndex}.`;
442
+ sequenceOutputLines.push(message);
443
+ }
444
+
382
445
  for (const wave of wavePlan.waves) {
383
- const taskScope = wave.taskIds.join(" ");
446
+ const wavePlanResolution = resolveRunnableWaveTasks(wave.waveIndex, wave.taskIds);
447
+ if (wavePlanResolution.action === "skip") {
448
+ skippedWaves.push({
449
+ waveIndex: wave.waveIndex,
450
+ message: wavePlanResolution.message ?? `Sequence wave ${wave.waveIndex} skipped.`,
451
+ });
452
+ sequenceOutputLines.push(
453
+ wavePlanResolution.message ?? `Sequence wave ${wave.waveIndex} skipped.`,
454
+ );
455
+ continue;
456
+ }
457
+ if (wavePlanResolution.message) {
458
+ sequenceOutputLines.push(wavePlanResolution.message);
459
+ } else if (wavePlanResolution.partialSkipMessage) {
460
+ sequenceOutputLines.push(wavePlanResolution.partialSkipMessage);
461
+ }
462
+
463
+ const taskScope = wavePlanResolution.runnableTaskIds.join(" ");
464
+ if (!taskScope) continue;
465
+
384
466
  let batchId = null;
385
467
  let detachedEnginePid = null;
386
468
 
@@ -391,6 +473,15 @@ export async function runSequence(ctx) {
391
473
  skipPreflight: true,
392
474
  });
393
475
  if (!startResult.ok) {
476
+ const reconciliation = reconcileBatch({ projectRoot });
477
+ if (isMergeBlockedBatchOutcome({ startResult, reconciliation })) {
478
+ absorbMergeBlockedWave(
479
+ wave.waveIndex,
480
+ loadSpineBatchState(projectRoot).raw,
481
+ startResult.output ?? "",
482
+ );
483
+ continue;
484
+ }
394
485
  if (!stopOnFailure) continue;
395
486
  return haltSequenceAndPersist(
396
487
  projectRoot,
@@ -457,6 +548,15 @@ export async function runSequence(ctx) {
457
548
  : await waitForSequenceBatchTerminal({ projectRoot, pollIntervalMs, timeoutMs, enginePid: detachedEnginePid ?? null });
458
549
 
459
550
  if (!wait.ok || isSequenceBatchFailure(wait.diagnosis)) {
551
+ const reconciliation = wait.reconciliation ?? reconcileBatch({ projectRoot });
552
+ if (isMergeBlockedBatchOutcome({ reconciliation })) {
553
+ absorbMergeBlockedWave(
554
+ wave.waveIndex,
555
+ reconciliation.signals?.raw ?? loadSpineBatchState(projectRoot).raw,
556
+ reconciliation.headline ?? "",
557
+ );
558
+ continue;
559
+ }
460
560
  if (!stopOnFailure) continue;
461
561
  return haltSequenceAndPersist(projectRoot, sequenceState, completedWaves, {
462
562
  waveIndex: wave.waveIndex,
@@ -492,6 +592,10 @@ export async function runSequence(ctx) {
492
592
  };
493
593
  completedWaves.push(waveResult);
494
594
 
595
+ for (const taskId of wavePlanResolution.runnableTaskIds) {
596
+ satisfiedTaskIds.add(taskId);
597
+ }
598
+
495
599
  if (sequenceState) {
496
600
  const lastBatchId = waveResult.batchId ?? sequenceState.lastBatchId ?? null;
497
601
  sequenceState = buildSequenceStateSnapshot(sequenceState, {
@@ -505,12 +609,21 @@ export async function runSequence(ctx) {
505
609
 
506
610
  finalizeSequenceState(projectRoot, sequenceState, completedWaves, plan);
507
611
 
612
+ if (completedWaves.length > 0) {
613
+ sequenceOutputLines.push(`Sequence completed ${completedWaves.length} wave(s).`);
614
+ }
615
+
616
+ const partialMergeBlocked = sequenceHadMergeBlocked && completedWaves.length < wavePlan.waves.length;
617
+
508
618
  return {
509
- ok: true,
510
- exitCode: 0,
619
+ ok: !sequenceHadMergeBlocked,
620
+ exitCode: sequenceHadMergeBlocked ? 1 : 0,
511
621
  completedWaves,
622
+ skippedWaves,
623
+ mergeBlocked: sequenceHadMergeBlocked,
624
+ partial: partialMergeBlocked,
512
625
  waveCount: wavePlan.waves.length,
513
626
  resumed: resume,
514
- output: `Sequence completed ${completedWaves.length} wave(s).\n`,
627
+ output: `${sequenceOutputLines.join("\n")}\n`,
515
628
  };
516
629
  }