pi-spine 1.3.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.
Files changed (38) hide show
  1. package/bin/spine-cli/verify.mjs +3 -0
  2. package/bin/spine-deps.mjs +0 -2
  3. package/bin/spine-rules.mjs +0 -2
  4. package/bin/spine-settings.mjs +0 -2
  5. package/bin/spine.mjs +2 -5
  6. package/package.json +2 -2
  7. package/skills/create-spine-tasks/SKILL.md +13 -1
  8. package/skills/create-spine-tasks/references/contract-template.md +6 -3
  9. package/skills/create-spine-tasks/references/requirements-checklist-template.md +1 -0
  10. package/src/batch/attached-engine-handoff.mjs +0 -1
  11. package/src/batch/attached-runner.mjs +1 -1
  12. package/src/batch/contract-verify.mjs +133 -14
  13. package/src/batch/diagnosis-retry-limbo.mjs +1 -1
  14. package/src/batch/diagnosis.mjs +0 -1
  15. package/src/batch/engine-lanes/commit.mjs +6 -0
  16. package/src/batch/engine-lanes/merge.mjs +1 -2
  17. package/src/batch/engine-lanes/review.mjs +57 -34
  18. package/src/batch/engine-lanes.mjs +0 -2
  19. package/src/batch/engine.mjs +0 -1
  20. package/src/batch/evidence.mjs +1 -2
  21. package/src/batch/git-exec.mjs +5 -2
  22. package/src/batch/journal-rebuild.mjs +110 -1
  23. package/src/batch/lane-commit.mjs +6 -5
  24. package/src/batch/lane-dirty-check.mjs +196 -1
  25. package/src/batch/reconcile.mjs +0 -1
  26. package/src/batch/resume-multi.mjs +1 -1
  27. package/src/batch/resume.mjs +0 -3
  28. package/src/batch/review-spawn.mjs +1 -1
  29. package/src/batch/review.mjs +0 -4
  30. package/src/batch/sequence-waves.mjs +221 -0
  31. package/src/batch/sequence.mjs +117 -4
  32. package/src/batch/worker-host.mjs +13 -5
  33. package/src/cli/deps.mjs +0 -2
  34. package/src/config/contract.mjs +10 -0
  35. package/src/dashboard/public/dashboard.css +8 -0
  36. package/src/dashboard/public/dashboard.js +22 -6
  37. package/src/dashboard/snapshot.mjs +0 -1
  38. package/src/tasks/packet/validate-prompt.mjs +0 -1
@@ -23,6 +23,9 @@ export const PHASE23_GRANDFATHERED_OVER_500 = [
23
23
  "src/batch/resume-multi-lanes.mjs",
24
24
  "src/batch/resume.mjs",
25
25
  "src/batch/sequence.mjs",
26
+ "src/batch/contract-verify.mjs",
27
+ "src/batch/journal-rebuild.mjs",
28
+ "src/batch/lane-dirty-check.mjs",
26
29
  ];
27
30
 
28
31
  const PHASE23_ENGINE_LANES_MAX = 500;
@@ -5,8 +5,6 @@
5
5
  * Inspect task dependency graph without running a full batch plan.
6
6
  */
7
7
 
8
- import path from 'node:path';
9
-
10
8
  import { isCliEntrypoint } from './spine-cli/shared.mjs';
11
9
  import { loadSpineConfig } from './spine-config.mjs';
12
10
  import { buildDepsReport, formatDepsHuman } from '../src/cli/deps.mjs';
@@ -8,8 +8,6 @@
8
8
  * spine rules sync [--json]
9
9
  */
10
10
 
11
- import path from "node:path";
12
-
13
11
  import { isCliEntrypoint } from "./spine-cli/shared.mjs";
14
12
  import { printRulesHelp, runSpineRules } from "../src/cli/rules.mjs";
15
13
 
@@ -8,8 +8,6 @@
8
8
  * spine settings set <path> <value> [--dry-run] [--json]
9
9
  */
10
10
 
11
- import path from "node:path";
12
-
13
11
  import { isCliEntrypoint } from "./spine-cli/shared.mjs";
14
12
  import { loadSpineConfig, loadSpineConfigFile } from "./spine-config.mjs";
15
13
  import { formatSettingsShow } from "../src/cli/settings-show.mjs";
package/bin/spine.mjs CHANGED
@@ -25,12 +25,9 @@ import { handlePlan } from "./spine-cli/plan.mjs";
25
25
  import {
26
26
  c,
27
27
  die,
28
- FAIL,
29
28
  getPackageVersion,
30
29
  isCliEntrypoint,
31
- OK,
32
30
  PACKAGE_ROOT,
33
- WARN,
34
31
  } from "./spine-cli/shared.mjs";
35
32
  import { handleStatus } from "./spine-cli/status.mjs";
36
33
  import { handleLane } from "./spine-cli/lane-logs.mjs";
@@ -38,9 +35,9 @@ import { handleWatch } from "./spine-cli/watch.mjs";
38
35
  import { handleWait } from "./spine-cli/wait.mjs";
39
36
  import { handleScenarios } from "./spine-cli/scenarios.mjs";
40
37
  import { loadSpineConfig } from "./spine-config.mjs";
41
- import { cmdInit, SPINE_GITIGNORE_ENTRIES } from "./spine-init.mjs";
38
+ import { cmdInit } from "./spine-init.mjs";
42
39
  import { cmdMigrateFromTaskplane } from "./spine-migrate-from-taskplane.mjs";
43
- import { runDoctorChecks, cmdDoctor } from "./spine-doctor.mjs";
40
+ import { cmdDoctor } from "./spine-doctor.mjs";
44
41
 
45
42
  export { runDoctorChecks } from "./spine-doctor.mjs";
46
43
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-spine",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "description": "Orchestration spine for long-running pi development",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "scripts": {
30
30
  "doctor": "node bin/spine.mjs doctor",
31
- "lint": "eslint src bin tests scripts",
31
+ "lint": "eslint --max-warnings 0 src bin tests scripts",
32
32
  "typecheck": "tsc --project tsconfig.json --noEmit && tsc --project tsconfig.batch.json --noEmit",
33
33
  "test": "SPINE_SUPPRESS_JOURNAL_ATTACH=1 node --experimental-strip-types --test tests/*.test.mjs tests/cli/*.test.mjs tests/compat/*.test.mjs tests/tasks/*.test.mjs tests/config/*.test.mjs tests/config/cursor-rules/*.test.mjs tests/planner/*.test.mjs tests/batch/*.test.mjs tests/agents/*.test.mjs tests/adoption/*.test.mjs tests/dashboard/*.test.mjs tests/doctor/*.test.mjs tests/migrate/*.test.mjs tests/worker-tools/*.test.mjs tests/coverage/*.test.mjs tests/extensions/*.test.mjs",
34
34
  "test:batch": "SPINE_SUPPRESS_JOURNAL_ATTACH=1 node --experimental-strip-types --test tests/batch/*.test.mjs",
@@ -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` ``) |
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
 
@@ -14,7 +14,6 @@ import {
14
14
  import { loadGateRecord } from "./gate.mjs";
15
15
  import { appendJournalEvent } from "./journal.mjs";
16
16
  import {
17
- finalizeBatchForIntegrate,
18
17
  isPostMergeLimbo,
19
18
  tryFinalizePostMergeLimbo,
20
19
  } from "./post-merge-limbo.mjs";
@@ -218,7 +218,7 @@ export async function runAttachedBatchEngine({
218
218
  runEngine,
219
219
  write,
220
220
  spineBin,
221
- force = false,
221
+ _force = false,
222
222
  operation = "resume",
223
223
  }) {
224
224
  if (operation === "start") {
@@ -12,12 +12,40 @@ import {
12
12
  isPrelandedFileScopeSatisfied,
13
13
  isStubPrelandedFileScopeSatisfied,
14
14
  } from "./contract-prelanded.mjs";
15
+ import { appendJournalEvent } from "./journal.mjs";
15
16
 
16
17
  export { resolvePromptRelPath, isFileScopePatternPrelanded, hasSpineTaskDeliveryChanges } from "./contract-prelanded.mjs";
17
18
 
18
19
  /** Default stdout/stderr capture limit for contract testCommand (issue #86). */
19
20
  export const CONTRACT_TEST_COMMAND_MAX_BUFFER = 10 * 1024 * 1024;
20
21
 
22
+ /** Default number of retries for failed testCommand (SP-485, issue #136). */
23
+ export const CONTRACT_TEST_DEFAULT_RETRIES = 1;
24
+
25
+ /** Default delay in ms between testCommand retry attempts. */
26
+ export const CONTRACT_TEST_RETRY_DELAY_MS = 5000;
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
+
21
49
  /**
22
50
  * @param {string} taskId
23
51
  * @param {ReturnType<import("../tasks/packet/parse-prompt.mjs").parseContract>} parsedContract
@@ -181,7 +209,9 @@ export function verifyStubFileScopeMustChange(
181
209
  /** @type {string[]} */
182
210
  const failures = [];
183
211
  for (const pattern of patterns) {
184
- const matched = changedFiles.some((file) => matchesContractPattern(file, pattern));
212
+ const matched = changedFiles.some((file) =>
213
+ pattern.endsWith("/") ? file.startsWith(pattern) : matchesContractPattern(file, pattern),
214
+ );
185
215
  if (matched) {
186
216
  continue;
187
217
  }
@@ -257,6 +287,48 @@ function formatMaxBufferLabel(byteCount) {
257
287
  return `${byteCount}B`;
258
288
  }
259
289
 
290
+ /**
291
+ * Block the current thread for the given duration without busy-waiting.
292
+ * Safe for CLI/batch tools; not suitable for servers.
293
+ *
294
+ * @param {number} ms
295
+ */
296
+ function sleepSync(ms) {
297
+ if (ms <= 0) return;
298
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
299
+ }
300
+
301
+ /**
302
+ * Write a failure log for a contract testCommand attempt to the task's .reviews/ directory.
303
+ * Returns the written path, or null if taskFolder is not provided.
304
+ *
305
+ * @param {string | undefined} taskFolder
306
+ * @param {string} command
307
+ * @param {{ exitCode: number, output: string, bufferOverflow?: boolean }} result
308
+ * @param {number} attempt
309
+ * @param {number} totalAttempts
310
+ * @returns {string | null}
311
+ */
312
+ export function writeContractFailureLog(taskFolder, command, result, attempt, totalAttempts) {
313
+ if (!taskFolder) return null;
314
+ const reviewsDir = path.join(taskFolder, ".reviews");
315
+ fs.mkdirSync(reviewsDir, { recursive: true });
316
+ const ts = new Date().toISOString().replace(/[:.]/g, "-");
317
+ const logPath = path.join(reviewsDir, `contract-fail-${ts}.log`);
318
+ const header = [
319
+ "Contract testCommand failure log",
320
+ `Command: ${command}`,
321
+ `Exit code: ${result.exitCode}`,
322
+ `Attempt: ${attempt} of ${totalAttempts}`,
323
+ `Timestamp: ${new Date().toISOString()}`,
324
+ `Buffer overflow: ${result.bufferOverflow ? "yes" : "no"}`,
325
+ "---",
326
+ "",
327
+ ].join("\n");
328
+ fs.writeFileSync(logPath, header + (result.output ?? ""), "utf-8");
329
+ return logPath;
330
+ }
331
+
260
332
  /**
261
333
  * @param {string} worktreePath
262
334
  * @param {string} command
@@ -273,6 +345,7 @@ export function runContractTestCommand(worktreePath, command, options = {}) {
273
345
  const shellFlag = process.platform === "win32" ? "/c" : "-c";
274
346
  const result = spawnSync(shell, [shellFlag, trimmed], {
275
347
  cwd: worktreePath,
348
+ env: buildContractTestEnv(),
276
349
  encoding: "utf-8",
277
350
  stdio: ["ignore", "pipe", "pipe"],
278
351
  timeout: 10 * 60 * 1000,
@@ -384,7 +457,11 @@ function findArtifactMatch(worktreePath, artifactPattern) {
384
457
  * @param {string} [config.baseBranch]
385
458
  * @param {string} [config.sinceCommit] When set, scope file-scope checks to `sinceCommit..HEAD` (serialized lanes).
386
459
  * @param {string} [config.taskStartCommit] Alias for `sinceCommit` (SP-415 journal resolution).
387
- * @returns {{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }> }}
460
+ * @param {string} [config.projectRoot] Repo root for journal events (optional).
461
+ * @param {string} [config.batchId] Batch ID for journal events (optional).
462
+ * @param {string} [config.taskId] Task ID for journal events (optional).
463
+ * @param {string} [config.taskFolder] Task folder path for writing failure logs to .reviews/ (optional).
464
+ * @returns {{ ok: boolean, checks: Array<{ field: string, ok: boolean, message: string }>, retries?: number }}
388
465
  */
389
466
  export function verifyContract(worktreePath, parsedContract, config = {}) {
390
467
  /** @type {Array<{ field: string, ok: boolean, message: string }>} */
@@ -395,25 +472,66 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
395
472
 
396
473
  let testCommandOutput = "";
397
474
  let testCommandOk = true;
475
+ let retriedCount = 0;
398
476
  if (parsedContract.testCommand) {
399
- const result = runContractTestCommand(worktreePath, parsedContract.testCommand, {
400
- maxBuffer: config?.contractTestMaxBuffer,
401
- });
402
- testCommandOutput = result.output;
403
- testCommandOk = result.ok;
477
+ const maxRetries = config?.contract?.testRetries ?? CONTRACT_TEST_DEFAULT_RETRIES;
478
+ const retryDelayMs = config?.contract?.testRetryDelayMs ?? CONTRACT_TEST_RETRY_DELAY_MS;
479
+ const totalAttempts = maxRetries + 1;
480
+ let lastResult = null;
481
+ let successAttempt = 0;
482
+
483
+ for (let attempt = 1; attempt <= totalAttempts; attempt++) {
484
+ lastResult = runContractTestCommand(worktreePath, parsedContract.testCommand, {
485
+ maxBuffer: config?.contractTestMaxBuffer,
486
+ });
487
+
488
+ if (lastResult.ok) {
489
+ successAttempt = attempt;
490
+ break;
491
+ }
492
+
493
+ writeContractFailureLog(
494
+ config?.taskFolder,
495
+ parsedContract.testCommand,
496
+ lastResult,
497
+ attempt,
498
+ totalAttempts,
499
+ );
500
+
501
+ if (attempt < totalAttempts) {
502
+ retriedCount++;
503
+ if (config?.projectRoot && config?.batchId) {
504
+ appendJournalEvent(config.projectRoot, config.batchId, "contract.test_retry", {
505
+ taskId: config?.taskId,
506
+ attempt,
507
+ exitCode: lastResult.exitCode,
508
+ totalAttempts,
509
+ });
510
+ }
511
+ sleepSync(retryDelayMs);
512
+ }
513
+ }
514
+
515
+ testCommandOutput = lastResult.output;
516
+ testCommandOk = lastResult.ok;
517
+ const attemptLabel = successAttempt > 1
518
+ ? ` (passed on attempt ${successAttempt} of ${totalAttempts})`
519
+ : "";
404
520
  checks.push({
405
521
  field: "testCommand",
406
- ok: result.ok,
407
- message: result.ok
408
- ? "testCommand passed"
409
- : result.bufferOverflow
410
- ? `Contract ${result.summary}`
411
- : `Contract testCommand failed (exit ${result.exitCode}): ${result.summary || "(no output)"}`,
522
+ ok: lastResult.ok,
523
+ message: lastResult.ok
524
+ ? `testCommand passed${attemptLabel}`
525
+ : lastResult.bufferOverflow
526
+ ? `Contract ${lastResult.summary}`
527
+ : `Contract testCommand failed after ${totalAttempts} attempt(s) (exit ${lastResult.exitCode}): ${lastResult.summary || "(no output)"}`,
412
528
  });
413
529
  }
414
530
 
415
531
  for (const pattern of parsedContract.fileScopeMustChange ?? []) {
416
- const matched = changedFiles.some((file) => matchesContractPattern(file, pattern));
532
+ const matched = changedFiles.some((file) =>
533
+ pattern.endsWith("/") ? file.startsWith(pattern) : matchesContractPattern(file, pattern),
534
+ );
417
535
  const prelanded = !matched &&
418
536
  isPrelandedFileScopeSatisfied(
419
537
  worktreePath,
@@ -491,5 +609,6 @@ export function verifyContract(worktreePath, parsedContract, config = {}) {
491
609
  return {
492
610
  ok: checks.length === 0 || checks.every((check) => check.ok),
493
611
  checks,
612
+ ...(retriedCount > 0 ? { retries: retriedCount } : {}),
494
613
  };
495
614
  }
@@ -22,7 +22,7 @@ export function isFailedPhasePendingOnlyLimbo(ctx = {}) {
22
22
  * @param {string} batchLabel
23
23
  * @param {object} ctx
24
24
  */
25
- export function buildFailedPhasePendingOnlyHeadline(batchLabel, ctx = {}) {
25
+ export function buildFailedPhasePendingOnlyHeadline(batchLabel, _ctx = {}) {
26
26
  return `${batchLabel} failed with pending task(s) and no failed tasks — resume to continue`;
27
27
  }
28
28
 
@@ -14,7 +14,6 @@ import { buildAlternatives } from "./diagnosis-alternatives.mjs";
14
14
  export { buildAlternatives } from "./diagnosis-alternatives.mjs";
15
15
  import {
16
16
  buildMergeFailureHeadline,
17
- summarizeMergeFailures,
18
17
  } from "./diagnosis-merge-failure.mjs";
19
18
  export { buildMergeFailureHeadline, summarizeMergeFailures } from "./diagnosis-merge-failure.mjs";
20
19
  import { buildRunningTailHeadline } from "./diagnosis-tail-state.mjs";
@@ -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,
@@ -13,7 +13,6 @@ import {
13
13
  loadRulesManifest,
14
14
  fingerprintRulesManifest,
15
15
  } from "../../config/cursor-rules/discover.mjs";
16
- import { resolveRulesManifestIntegrateDrift } from "../rules-manifest-drift.mjs";
17
16
  import { matchesContractPattern } from "../contract-verify.mjs";
18
17
  import {
19
18
  formatAdoptionDocMergeFailure,
@@ -196,7 +195,7 @@ function tryAutoResolveOutOfScopeMergeConflict({
196
195
  projectRoot,
197
196
  filePath,
198
197
  laneFileScopePaths,
199
- laneChangedFiles,
198
+ _laneChangedFiles,
200
199
  }) {
201
200
  if (pathInLaneFileScope(filePath, laneFileScopePaths)) {
202
201
  return { ok: false, reason: "in_lane_file_scope" };
@@ -8,7 +8,7 @@ import { recordLaneTaskMetric } from "./queue.mjs";
8
8
  import { REVIEW_DEFAULTS } from "../../config/defaults.mjs";
9
9
  import { parseContract } from "../../tasks/packet/parse-prompt.mjs";
10
10
  import { resolveTaskStartCommit } from "../contract-task-start.mjs";
11
- import { shouldRunContractVerify, shouldRunContractVerifyForWorker, verifyContract } from "../contract-verify.mjs";
11
+ import { shouldRunContractVerifyForWorker, verifyContract } from "../contract-verify.mjs";
12
12
  import { appendJournalEvent, readJournalEvents } from "../journal.mjs";
13
13
  import {
14
14
  recomputeTaskCounters,
@@ -21,7 +21,6 @@ import {
21
21
  buildReviewArtifactPath,
22
22
  normalizeCodeVerdict,
23
23
  normalizeFinalVerdict,
24
- parseFinalReviewVerdict,
25
24
  shouldRunCodeReview,
26
25
  shouldRunFinalReview,
27
26
  } from "../review-shared.mjs";
@@ -427,30 +426,40 @@ async function runCodeReviewPhase({
427
426
  const maxCodeReviewAttempts = config?.review?.maxFinalAttempts ?? REVIEW_DEFAULTS.maxFinalAttempts;
428
427
  let codeReviewAttempt = task.codeReviewAttempts ?? 0;
429
428
 
430
- if (codeReviewAttempt === 0) {
431
- const honored = findCompletedCodeReview({
432
- taskFolder: taskFolderInWorktree,
433
- journalEvents: readJournalEvents(projectRoot, batchId),
434
- taskId,
435
- });
436
- if (honored?.verdict === "APPROVE") {
437
- appendJournalEvent(projectRoot, batchId, "task.verdict_recorded", {
429
+ const honored = findCompletedCodeReview({
430
+ taskFolder: taskFolderInWorktree,
431
+ journalEvents: readJournalEvents(projectRoot, batchId),
432
+ taskId,
433
+ });
434
+ if (honored?.verdict === "APPROVE") {
435
+ if (codeReviewAttempt > 0) {
436
+ appendJournalEvent(projectRoot, batchId, "review.crash_recovered", {
438
437
  taskId,
439
438
  laneNumber,
440
439
  laneId: lane.laneId,
441
440
  correlationId: laneCorrelationId,
442
441
  reviewType: "code",
443
- verdict: "APPROVE",
444
- feedback: honored.feedback,
442
+ codeReviewAttempt,
445
443
  artifactPath: honored.artifactPath,
446
- codeReviewAttempt: 1,
447
- honored: true,
448
444
  honorSource: honored.source,
449
445
  });
450
- task.codeReviewAttempts = 1;
451
- saveSpineBatchState(projectRoot, state);
452
- return { ok: true, verdict: "APPROVE", codeReviewAttempt: 1, honored: true };
453
446
  }
447
+ appendJournalEvent(projectRoot, batchId, "task.verdict_recorded", {
448
+ taskId,
449
+ laneNumber,
450
+ laneId: lane.laneId,
451
+ correlationId: laneCorrelationId,
452
+ reviewType: "code",
453
+ verdict: "APPROVE",
454
+ feedback: honored.feedback,
455
+ artifactPath: honored.artifactPath,
456
+ codeReviewAttempt: codeReviewAttempt + 1,
457
+ honored: true,
458
+ honorSource: honored.source,
459
+ });
460
+ task.codeReviewAttempts = codeReviewAttempt + 1;
461
+ saveSpineBatchState(projectRoot, state);
462
+ return { ok: true, verdict: "APPROVE", codeReviewAttempt: codeReviewAttempt + 1, honored: true };
454
463
  }
455
464
 
456
465
  const journal = {
@@ -648,30 +657,40 @@ async function runFinalReviewPhase({
648
657
  const maxFinalAttempts = config?.review?.maxFinalAttempts ?? REVIEW_DEFAULTS.maxFinalAttempts;
649
658
  let finalAttempt = task.finalAttempts ?? 0;
650
659
 
651
- if (finalAttempt === 0) {
652
- const honored = findCompletedFinalReview({
653
- taskFolder: taskFolderInWorktree,
654
- journalEvents: readJournalEvents(projectRoot, batchId),
655
- taskId,
656
- });
657
- if (honored?.verdict === "PASS") {
658
- appendJournalEvent(projectRoot, batchId, "task.verdict_recorded", {
660
+ const honoredFinal = findCompletedFinalReview({
661
+ taskFolder: taskFolderInWorktree,
662
+ journalEvents: readJournalEvents(projectRoot, batchId),
663
+ taskId,
664
+ });
665
+ if (honoredFinal?.verdict === "PASS") {
666
+ if (finalAttempt > 0) {
667
+ appendJournalEvent(projectRoot, batchId, "review.crash_recovered", {
659
668
  taskId,
660
669
  laneNumber,
661
670
  laneId: lane.laneId,
662
671
  correlationId: laneCorrelationId,
663
672
  reviewType: "final",
664
- verdict: "PASS",
665
- feedback: honored.feedback,
666
- artifactPath: honored.artifactPath,
667
- finalAttempt: 1,
668
- honored: true,
669
- honorSource: honored.source,
673
+ finalAttempt,
674
+ artifactPath: honoredFinal.artifactPath,
675
+ honorSource: honoredFinal.source,
670
676
  });
671
- task.finalAttempts = 1;
672
- saveSpineBatchState(projectRoot, state);
673
- return { ok: true, verdict: "PASS", finalAttempt: 1, honored: true };
674
677
  }
678
+ appendJournalEvent(projectRoot, batchId, "task.verdict_recorded", {
679
+ taskId,
680
+ laneNumber,
681
+ laneId: lane.laneId,
682
+ correlationId: laneCorrelationId,
683
+ reviewType: "final",
684
+ verdict: "PASS",
685
+ feedback: honoredFinal.feedback,
686
+ artifactPath: honoredFinal.artifactPath,
687
+ finalAttempt: finalAttempt + 1,
688
+ honored: true,
689
+ honorSource: honoredFinal.source,
690
+ });
691
+ task.finalAttempts = finalAttempt + 1;
692
+ saveSpineBatchState(projectRoot, state);
693
+ return { ok: true, verdict: "PASS", finalAttempt: finalAttempt + 1, honored: true };
675
694
  }
676
695
 
677
696
  const journal = {
@@ -699,6 +718,10 @@ async function runFinalReviewPhase({
699
718
  ...config,
700
719
  baseBranch,
701
720
  sinceCommit: sinceCommit ?? undefined,
721
+ projectRoot,
722
+ batchId,
723
+ taskId,
724
+ taskFolder: taskFolderInWorktree,
702
725
  });
703
726
  task.contractOk = contractVerifyResult.ok;
704
727
  saveSpineBatchState(projectRoot, state);
@@ -5,11 +5,9 @@
5
5
  import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import {
8
- buildTasksAndLanesFromPlan,
9
8
  loadTaskFileScopePaths,
10
9
  recordLaneTaskMetric,
11
10
  recordPromptParseFailure,
12
- skipTaskDoneOnDisk,
13
11
  } from "./engine-lanes/queue.mjs";
14
12
  import { appendJournalEvent } from "./journal.mjs";
15
13
  import { commitLaneAndValidateWorktree } from "./engine-lanes/commit.mjs";
@@ -32,7 +32,6 @@ import { resolveWorktreeSetupHook } from "../config/worktree-setup-hook.mjs";
32
32
  import {
33
33
  assessWaveMergeEligibility,
34
34
  canStartMultiTaskBatch,
35
- countPlanTasks,
36
35
  maxLaneNumberForPlan,
37
36
  resolveBatchStartScope,
38
37
  shouldAutoIntegrateAfterWave,
@@ -10,7 +10,6 @@ import { runEvidenceCommand } from "./evidence-command.mjs";
10
10
  import { readJournalEvents, readJournalTail } from "./journal.mjs";
11
11
  import { generateBatchPostMortem } from "./postmortem.mjs";
12
12
  import { reconcileBatch } from "./reconcile.mjs";
13
- import { loadSpineConfig } from "../config/spine-config-load.mjs";
14
13
 
15
14
  const TASKPLANE_CONFIG_PATH = ".pi/taskplane-config.json";
16
15
 
@@ -185,7 +184,7 @@ export function collectCoreEvidenceBundle(ctx) {
185
184
  * @param {string[]} [ctx.evidenceRefs]
186
185
  */
187
186
  export function collectExtendedEvidenceBundle(ctx) {
188
- const { projectRoot, batchId, batchState = null, config = null } = ctx;
187
+ const { projectRoot, batchId, config = null } = ctx;
189
188
  const dir = evidenceDir(projectRoot, batchId);
190
189
  fs.mkdirSync(dir, { recursive: true });
191
190