cclaw-cli 6.12.0 → 6.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/artifact-linter/plan.js +60 -2
  2. package/dist/artifact-linter/shared.d.ts +9 -0
  3. package/dist/artifact-linter/spec.js +14 -0
  4. package/dist/artifact-linter/tdd.d.ts +19 -6
  5. package/dist/artifact-linter/tdd.js +225 -47
  6. package/dist/artifact-linter.js +10 -1
  7. package/dist/content/hooks.js +88 -1
  8. package/dist/content/skills.js +17 -10
  9. package/dist/content/stages/plan.js +2 -1
  10. package/dist/content/stages/spec.js +2 -2
  11. package/dist/content/stages/tdd.js +7 -6
  12. package/dist/content/start-command.js +6 -3
  13. package/dist/content/templates.js +10 -4
  14. package/dist/delegation.d.ts +82 -3
  15. package/dist/delegation.js +244 -6
  16. package/dist/flow-state.d.ts +20 -0
  17. package/dist/flow-state.js +7 -0
  18. package/dist/gate-evidence.d.ts +5 -0
  19. package/dist/gate-evidence.js +58 -1
  20. package/dist/install.js +90 -2
  21. package/dist/integration-fanin.d.ts +44 -0
  22. package/dist/integration-fanin.js +180 -0
  23. package/dist/internal/advance-stage/advance.js +16 -1
  24. package/dist/internal/advance-stage/start-flow.js +3 -1
  25. package/dist/internal/advance-stage.js +13 -4
  26. package/dist/internal/plan-split-waves.d.ts +85 -1
  27. package/dist/internal/plan-split-waves.js +409 -6
  28. package/dist/internal/set-worktree-mode.d.ts +10 -0
  29. package/dist/internal/set-worktree-mode.js +28 -0
  30. package/dist/managed-resources.js +2 -0
  31. package/dist/run-persistence.js +9 -0
  32. package/dist/worktree-manager.d.ts +50 -0
  33. package/dist/worktree-manager.js +136 -0
  34. package/dist/worktree-types.d.ts +36 -0
  35. package/dist/worktree-types.js +6 -0
  36. package/package.json +1 -1
@@ -4,6 +4,7 @@ import { FLOW_STAGES } from "../types.js";
4
4
  import { behaviorAnchorFor, stageExamples } from "./examples.js";
5
5
  import { INVESTIGATION_DISCIPLINE_BLOCK } from "./templates.js";
6
6
  import { reviewStackAwareRoutes, reviewStackAwareRoutingSummary, stageAutoSubagentDispatch, stageSchema, stageTrackRenderContext } from "./stage-schema.js";
7
+ import { renderTrackTerminology } from "./track-render-context.js";
7
8
  import { referencePatternsForStage } from "./reference-patterns.js";
8
9
  import { harnessDelegationRecipes } from "../harness-adapters.js";
9
10
  const VERIFICATION_STAGES = ["tdd", "review", "ship"];
@@ -196,16 +197,20 @@ ONE slice = THREE dispatches, in this order. Do not skip, do not collapse.
196
197
  The file-overlap scheduler auto-allows parallel dispatch because \`claimedPaths\` are disjoint. Fire BOTH calls in the same message — never serialize independent work.
197
198
  4. **REFACTOR** — \`Task("slice-implementer --slice S-<id> --phase refactor")\` OR \`--phase refactor-deferred --refactor-rationale '<why>'\`.
198
199
 
200
+ **Rule 1 (v6.13.1):** Before any slice-routing question, read \`<artifacts-dir>/05-plan.md\` (managed \`## Parallel Execution Plan\`) **and** list \`<artifacts-dir>/wave-plans/wave-NN.md\`. Merge mentally: Parallel Execution Plan first, wave files second; duplicate slices with conflicting wave membership are invalid. If the merged plan shows a wave with **two or more** scheduler-ready slices, issue **exactly one** \`AskQuestion\`: \`Launch wave W-NN with N parallel lanes (S-a, S-b, ...)?\` with default option **launch wave** and alternate **single-slice instead**. Do not ask "which slice next?" when that question is redundant (single ready slice or no wave). After **launch wave** confirmation, execute RED checkpoint → parallel GREEN+DOC → per-lane REFACTOR without further routing asks. After **single-slice instead**, fall back to the legacy single-slice ritual. **Wave dispatch resume:** if part of the wave is already done, parallelize only the remaining members.
201
+
199
202
  **FORBIDDEN:**
200
203
  - Controller writing GREEN production code. ALL GREEN goes through \`slice-implementer\` — linter rule \`tdd_slice_implementer_missing\` blocks the gate.
201
204
  - Controller writing per-slice prose into legacy \`06-tdd.md\` sections (Test Discovery / RED Evidence / GREEN Evidence / Watched-RED Proof / Vertical Slice Cycle / Per-Slice Review / Failure Analysis / Acceptance Mapping). \`slice-documenter\` owns \`tdd-slices/S-<id>.md\` — \`tdd_slice_documenter_missing\` blocks the gate.
202
205
  - Hand-editing auto-render blocks between \`auto-start: tdd-slice-summary\` / \`auto-start: slices-index\` markers — overwritten every lint.
203
206
 
204
- Delegation-record signature: \`node .cclaw/hooks/delegation-record.mjs --stage=tdd --agent=<agent> --mode=mandatory --status=<...> --span-id=<id> --dispatch-id=<id> --dispatch-surface=<surface> --agent-definition-path=<path> --slice=S-<id> --phase=<red|green|refactor|refactor-deferred|doc> [--paths=<csv>] [--refactor-rationale=<why>] [--ack-ts=<iso>] [--evidence-ref=<ref>] --json\`.
207
+ Delegation-record signature (extend with lane metadata for every GREEN row in \`worktree-first\`):
208
+
209
+ \`node .cclaw/hooks/delegation-record.mjs --stage=tdd --agent=slice-implementer --mode=mandatory --status=scheduled --span-id=<id> --dispatch-id=<id> --dispatch-surface=<surface> --agent-definition-path=<path> --slice=S-1 --phase=green --paths=src/a.ts --claim-token=<opaque> --lane-id=<lane> --lease-until=<iso8601> --json\`
205
210
 
206
- ## Wave Batch Mode (v6.12.0+)
211
+ ## Wave Batch Mode (v6.13.1+)
207
212
 
208
- Trigger: any \`<artifacts-dir>/wave-plans/wave-NN.md\` exists, OR 2+ slices have disjoint \`claimedPaths\`. Cap = 5 \`slice-implementer\` lanes (10 subagents incl. paired documenters) via \`MAX_PARALLEL_SLICE_IMPLEMENTERS\`.
213
+ **Triggers:** managed \`## Parallel Execution Plan\` in \`05-plan.md\` **or** any \`<artifacts-dir>/wave-plans/wave-NN.md\`, OR 2+ slices with disjoint \`claimedPaths\`. Cap = 5 \`slice-implementer\` lanes (10 subagents incl. paired documenters) via \`MAX_PARALLEL_SLICE_IMPLEMENTERS\`. **Preconditions:** Load both sources before routing. Worktree-first: every GREEN delegation-record MUST include \`--claim-token\`, \`--lane-id\`, \`--lease-until\` (hook exits \`2\`, \`dispatch_lane_metadata_missing\` otherwise).
209
214
 
210
215
  **Phase A — RED checkpoint** — ONE message, all test-authors:
211
216
  \`\`\`
@@ -215,16 +220,18 @@ Task("test-author --slice S-3 --phase red")
215
220
  \`\`\`
216
221
  Wait for ALL Phase A REDs to land with non-empty \`evidenceRefs\` before Phase B. Linter \`tdd_red_checkpoint_violation\` (required: true) blocks any wave where a \`phase=green\` \`completedTs\` precedes the wave's last \`phase=red\` \`completedTs\`.
217
222
 
218
- **Phase B — GREEN+DOC fan-out** — ONE message, paired implementer+documenter Tasks per slice:
223
+ **Phase B — GREEN+DOC fan-out** — ONE message; pair per slice (repeat for each lane, flags unique per lane):
224
+
219
225
  \`\`\`
220
- Task("slice-implementer --slice S-1 --phase green --paths <S-1 prod>")
226
+ Task("slice-implementer --slice S-1 --phase green --paths <prod> --claim-token=<t> --lane-id=<lane-1> --lease-until=<iso>")
221
227
  Task("slice-documenter --slice S-1 --phase doc --paths <artifacts-dir>/tdd-slices/S-1.md")
222
- Task("slice-implementer --slice S-2 --phase green --paths <S-2 prod>")
223
- Task("slice-documenter --slice S-2 --phase doc --paths <artifacts-dir>/tdd-slices/S-2.md")
224
228
  \`\`\`
225
- Launch ALL Phase B pairs in ONE message. **Never serialize independent work.**
226
229
 
227
- **Fan-in** when 2+ \`slice-implementer\` rows complete in a wave, dispatch \`integration-overseer\` to verify cohesion contract (shared types, touchpoints, invariants, integration tests).
230
+ Launch every slice's pair in that same message. **Never serialize independent work.**
231
+
232
+ **Phase C — REFACTOR per slice** — after GREEN+DOC lands, dispatch refactor/refactor-deferred per slice. **Fan-in (worktree-first):** echo claim/lane/lease on completed GREEN rows; stage-complete runs deterministic \`git apply --3way\` (no \`-X ours/theirs\`). Conflicts: \`slice-implementer --phase resolve-conflict\`. With 2+ lanes, still dispatch \`integration-overseer\` before review.
233
+
234
+ **slice-documenter:** record the \`phase=doc\` row in the same message as GREEN; write a **provisional** row in \`tdd-slices/S-<id>.md\` immediately at dispatch, then **finalize** that file after the matching \`slice-implementer\` \`phase=green\` event lands (evidence-backed prose, not guesswork before GREEN exists).
228
235
 
229
236
  `;
230
237
  }
@@ -651,7 +658,7 @@ If you are about to violate the Iron Law, STOP. No amount of urgency, partial pr
651
658
 
652
659
  </EXTREMELY-IMPORTANT>
653
660
 
654
- ${tddTopOfSkillBlock(stage)}${quickStartBlock(stage, track)}
661
+ ${renderTrackTerminology(tddTopOfSkillBlock(stage), trackContext)}${quickStartBlock(stage, track)}
655
662
 
656
663
  ${STAGE_LANGUAGE_POLICY_POINTER}
657
664
  ## Philosophy
@@ -46,6 +46,7 @@ export const PLAN = {
46
46
  "Slice into vertical tasks — each task targets 2-5 minutes, produces one testable outcome, and touches one coherent area.",
47
47
  "Task Contract — every task has one coherent outcome, AC mapping, exact verification command/manual step, and expected evidence snippet or pass condition. Avoid vague `run tests` wording.",
48
48
  "Annotate slice-review metadata — task rows may carry `touchCount` (rough number of files expected to change), `touchPaths` (glob hints, e.g. `migrations/**`, `src/auth/**`), and optional `highRisk: true` to force a review pass. These fields feed the TDD stage's Per-Slice Review point.",
49
+ "For every `### Implementation Unit U-<n>`, declare v6.13.0 parallel metadata bullets: `id`, `dependsOn` (unit ids or `none`), `claimedPaths` (repo-relative), `parallelizable` (true|false), `riskTier` (low|standard|high), optional `lane` — used for conflict-aware wave plans and schedulers.",
49
50
  "Map scope Locked Decisions — every D-XX ID from scope is referenced by at least one plan task (or explicitly marked deferred with reason).",
50
51
  "Run anti-placeholder + anti-scope-reduction scans — block `TODO/TBD/...` and phrasing like `v1`, `for now`, `later` for locked boundaries.",
51
52
  "Define validation points — mark where progress must be checked before continuing, with concrete command and expected evidence.",
@@ -135,7 +136,7 @@ export const PLAN = {
135
136
  { section: "Locked Decision Coverage", required: false, validationRule: "Every locked decision ID (D-XX) from scope is listed with linked task IDs or explicit defer rationale." },
136
137
  { section: "Risk Assessment", required: false, validationRule: "If present: per-task or per-batch risk identification with likelihood, impact, and mitigation strategy." },
137
138
  { section: "Boundary Map", required: false, validationRule: "If present: per-batch or per-task interface contracts listing what each task produces (exports) and consumes (imports) from other tasks." },
138
- { section: "Implementation Units", required: false, validationRule: "If present: each `### Implementation Unit U-<n>` includes Goal, Files, Approach, Test scenarios, and Verification fields." },
139
+ { section: "Implementation Units", required: false, validationRule: "If present: each `### Implementation Unit U-<n>` includes Goal, Files, Approach, Test scenarios, Verification fields, plus v6.13.0 bullets (`id`, `dependsOn`, `claimedPaths`, `parallelizable`, `riskTier`, optional `lane`)." },
139
140
  { section: "Calibrated Findings", required: false, validationRule: "If present: either `None this stage` or one or more lines in `[P1|P2|P3] (confidence: <n>/10) <path>[:<line>] — <description>` format." },
140
141
  { section: "Regression Iron Rule", required: false, validationRule: "If present: includes `Iron rule acknowledged: yes`." },
141
142
  { section: "WAIT_FOR_CONFIRM", required: true, validationRule: "Explicit marker present. Status: pending until user approves." },
@@ -62,7 +62,7 @@ export const SPEC = {
62
62
  "Define measurable acceptance criteria.",
63
63
  "Capture constraints, assumptions, and edge cases.",
64
64
  "Review assumptions before finalization: source/confidence, validation path, and accepted/rejected/open disposition.",
65
- "Build Acceptance Mapping: AC -> design decision -> observable evidence -> verification method -> likely test level.",
65
+ "Annotate parallel-slice metadata on each acceptance criterion: `parallelSafe` (true|false) and `touchSurface` (repo-relative paths/modules expected to change) so downstream plan units and TDD lanes stay conflict-aware (v6.13.0).",
66
66
  "Confirm every verification method is concrete enough for plan/TDD to use later.",
67
67
  "Present acceptance criteria to the user in 3-5-item batches, pausing for explicit ACK between batches (see Interaction Protocol).",
68
68
  "Write spec artifact and request approval."
@@ -118,7 +118,7 @@ export const SPEC = {
118
118
  },
119
119
  artifactValidation: [
120
120
  { section: "Upstream Handoff", required: false, validationRule: "Summarizes scope/design decisions, constraints, open questions, and explicit drift before acceptance criteria." },
121
- { section: "Acceptance Criteria", required: true, validationRule: "Each criterion is observable, measurable, and falsifiable. Standard track should include Requirement Ref and Design Decision Ref columns; quick track may instead link each AC to the reproduction contract or bug slice. AC IDs (AC-1, AC-2…) are stable across revisions — dropped ACs stay with Priority `DROPPED`." },
121
+ { section: "Acceptance Criteria", required: true, validationRule: "Each criterion is observable, measurable, and falsifiable. Standard track should include Requirement Ref and Design Decision Ref columns; quick track may instead link each AC to the reproduction contract or bug slice. AC IDs (AC-1, AC-2…) are stable across revisions — dropped ACs stay with Priority `DROPPED`. v6.13.0: each AC declares `parallelSafe` (true|false) and `touchSurface` (paths/modules) for parallel slice planning." },
122
122
  { section: "Quick Reproduction Contract", required: false, validationRule: "Quick bug-fix specs own the reproduction contract: symptom, repro steps, expected RED test behavior, and acceptance criterion." },
123
123
  { section: "Edge Cases", required: true, validationRule: "At least one boundary and one error condition per criterion." },
124
124
  { section: "Constraints and Assumptions", required: false, validationRule: "Constraints are CARRIED FORWARD from scope's `## Scope Contract > Constraints` (cite with `See scope: <ref>` or copy with attribution). New spec-stage constraints (rare) get a citation to the spec-stage Q&A row that surfaced them. Assumptions are owned by `## Assumptions Before Finalization` — do NOT duplicate them here. Section may be `- See scope: 02-scope.md#constraints.` for the common case." },
@@ -37,28 +37,29 @@ export const TDD = {
37
37
  },
38
38
  executionModel: {
39
39
  checklist: [
40
- "Select vertical slice pick one source item from the active track (plan task on standard/medium, spec AC or bug reproduction slice on quick). Do not batch multiple tasks. Before starting, read `.cclaw/state/ralph-loop.json` (`loopIteration`, `acClosed[]`, `redOpenSlices[]`) so you skip cycles already closed. If `redOpenSlices[]` is non-empty, repair or explicitly park those slices before opening a new RED.",
40
+ "**Wave dispatch (v6.13.1):** Before routing, read the Parallel Execution Plan (managed block in the track planning artifact) and `<artifacts-dir>/wave-plans/`. Multi-ready waves: one AskQuestion (launch wave vs single-slice); then RED checkpoint, parallel GREEN+DOC with worktree-first flags, per-lane REFACTOR. Resume partial waves by parallelizing remaining members only (see top-of-skill `## Wave Batch Mode`).",
41
+ "Select vertical slice — the active wave plan (or single ready slice) defines work. Do not ask \"which slice next?\" when the plan already resolves it. Before starting, read `.cclaw/state/ralph-loop.json` (`loopIteration`, `acClosed[]`, `redOpenSlices[]`) so you skip cycles already closed. If `redOpenSlices[]` is non-empty, repair or explicitly park those slices before opening a new RED.",
41
42
  "Map to acceptance criterion — identify the specific spec criterion this test proves.",
42
43
  "Discover the test surface — inspect existing tests, fixtures, helpers, test commands, and nearby assertions before authoring RED. Reuse the local test style unless the slice genuinely needs a new pattern.",
43
44
  "Run a system-wide impact check — name callbacks, state transitions, interfaces, schemas, CLI/config/API contracts, persistence, or event boundaries that this slice can affect. Add RED coverage for each affected public contract or record why it is out of scope.",
44
45
  "Source/test preflight — before production edits, classify planned paths using test-path patterns; verify the RED touches a test path and the GREEN touches only source paths needed for the failing behavior.",
45
46
  "Use the mandatory `test-author` delegation for RED — after discovery and impact check, dispatch with `--slice S-<id> --phase red`. Produce failing behavior tests only (no production edits) and let the harness record the dispatch via the generated `delegation-record` hook. Set `CCLAW_ACTIVE_AGENT=tdd-red` when the harness supports phase labels.",
46
47
  "RED: do NOT hand-edit `## Watched-RED Proof`, `## Vertical Slice Cycle`, or `## RED Evidence` markdown tables. The linter auto-renders them from `delegation-events.jsonl` slice phase rows; manual edits inside the auto-render markers are overwritten on the next lint.",
47
- "Dispatch the `slice-implementer` for GREEN with `--slice S-<id> --phase green` and explicit `--paths` so the file-overlap scheduler can auto-allow parallel slices. Attach an evidence ref (test path, span ref, or pasted-output pointer) so the Vertical Slice Cycle row is well-formed. Set `CCLAW_ACTIVE_AGENT=tdd-green` when the harness supports phase labels.",
48
+ "Dispatch the `slice-implementer` for GREEN with `--slice S-<id> --phase green` and explicit `--paths` so the file-overlap scheduler can auto-allow parallel slices. When `flow-state.json::worktreeExecutionMode` is `worktree-first`, **mandatory** flags on every GREEN delegation-record row: `--claim-token=<opaque> --lane-id=<lane> --lease-until=<iso8601>`. Attach an evidence ref so the Vertical Slice Cycle row is well-formed. Set `CCLAW_ACTIVE_AGENT=tdd-green` when the harness supports phase labels.",
48
49
  "GREEN: Run full suite — execute ALL tests, not just the ones you wrote. The full suite must be GREEN.",
49
50
  "GREEN: Verify no regressions — if any existing test breaks, fix the regression before proceeding.",
50
51
  "Run verification-before-completion discipline for the slice — capture a fresh test command, explicit PASS/FAIL status, and a config-aware ref (commit SHA when VCS is present/required, or no-vcs attestation when allowed).",
51
52
  "REFACTOR: re-dispatch the `slice-implementer` (or `test-author`) with `--phase refactor` once GREEN holds, OR `--phase refactor-deferred --refactor-rationale \"<why>\"` to close the slice without a refactor pass. Both options are recorded as a delegation event; the linter accepts either as REFACTOR coverage. Set `CCLAW_ACTIVE_AGENT=tdd-refactor` when the harness supports phase labels.",
52
- "DOC (parallel, mandatory v6.12.0): dispatch `slice-documenter --slice S-<id> --phase doc --paths <artifacts-dir>/tdd-slices/S-<id>.md` IN PARALLEL with `slice-implementer --phase green` for the same slice — ONE message with TWO concurrent Task calls. The documenter only writes `tdd-slices/S-<id>.md`, so its `--paths` are disjoint from the implementer's production code and the file-overlap scheduler auto-allows the parallel dispatch. Linter rule `tdd_slice_documenter_missing` blocks the gate when the `phase=doc` event is absent (regardless of `discoveryMode`).",
53
+ "DOC (parallel, mandatory v6.12.0): dispatch `slice-documenter --slice S-<id> --phase doc --paths <artifacts-dir>/tdd-slices/S-<id>.md` IN PARALLEL with `slice-implementer --phase green` for the same slice — ONE message with TWO concurrent Task calls. The documenter only writes `tdd-slices/S-<id>.md`, so its `--paths` are disjoint from the implementer's production paths and the file-overlap scheduler auto-allows the parallel dispatch. **Provisional-then-finalize:** append a provisional row/section in `tdd-slices/S-<id>.md` at dispatch time, then finalize that artifact after the matching `phase=green` event records evidence (never treat guesses as final before GREEN lands). Linter rule `tdd_slice_documenter_missing` blocks the gate when the `phase=doc` event is absent (regardless of `discoveryMode`).",
53
54
  "**slice-documenter writes per-slice prose** (test discovery, system-wide impact check, RED/GREEN/REFACTOR notes, acceptance mapping, failure analysis) into `tdd-slices/S-<id>.md`. Controller does NOT touch this content. When logging a `green` row, attach the closed acceptance-criterion IDs in `acIds` so Ralph Loop status counts them.",
54
55
  "Annotate traceability — link to the active track's source: plan task ID + spec criterion on standard/medium, or spec acceptance item / bug reproduction slice on quick.",
55
56
  "**Boundary with review (do NOT escalate single-slice findings to whole-diff review).** `tdd.Per-Slice Review` OWNS severity-classified findings WITHIN one slice (correctness, edge cases, regression). `review` OWNS whole-diff Layer 1 (spec compliance) plus Layer 2 (cross-slice integration, security sweep, dependency/version audit, observability). When a single-slice finding genuinely needs whole-diff escalation, surface it in `06-tdd.md > Per-Slice Review` first; review will cite it (not re-classify) and the cross-artifact-duplication linter requires matching severity/disposition.",
56
57
  "Per-Slice Review (conditional) — if the slice meets any trigger (touchCount >= filesChangedThreshold, touchPaths match touchTriggers, or highRisk=true), append a `## Per-Slice Review` entry for this slice before moving on (see the dedicated section below).",
57
- "Repeat for each slice — return to step 1 for the next plan slice."
58
+ "Repeat for each slice — when not in multi-slice wave mode, return to wave-plan discovery; otherwise continue the active wave until members close.",
58
59
  ],
59
60
  interactionProtocol: [
60
- "Pick one vertical slice at a time: source item, RED test, GREEN implementation, REFACTOR, and verification evidence move together.",
61
- "Slice implementers are sequential by default. Parallel implementers are allowed only when (a) lanes touch non-overlapping files (the file-overlap scheduler auto-allows parallel when `--paths` are disjoint), and (b) an `integration-overseer` is dispatched after the parallel lanes and writes cohesion-evidence into the artifact before the gate is marked passed.",
61
+ "Pick one vertical slice at a time **only when** the merged wave plan leaves a single scheduler-ready slice or the operator chose single-slice mode. Parallel implementers are allowed when (a) lanes touch non-overlapping files (the file-overlap scheduler auto-allows parallel when `--paths` are disjoint), and (b) an `integration-overseer` is dispatched after the parallel lanes and writes cohesion-evidence into the artifact before the gate is marked passed.",
62
+ "Slice implementers are sequential only when the plan serializes work; prefer wave-parallel GREEN+DOC when the Parallel Execution Plan marks multiple ready members.",
62
63
  "Controller owns orchestration. For each slice S-<id>, dispatch in this order: (1) `test-author --slice S-<id> --phase red` (RED-only, no production edits), (2) `slice-implementer --slice S-<id> --phase green --paths <comma-separated>` for GREEN, (3) re-dispatch `--phase refactor` or `--phase refactor-deferred --refactor-rationale \"<why>\"` to close REFACTOR. Each dispatch records a row in `delegation-events.jsonl` and the linter auto-derives the Watched-RED + Vertical Slice Cycle tables from those rows. Do NOT hand-edit those tables.",
63
64
  "Before writing RED tests, discover relevant existing tests and commands so the new test extends the suite instead of fighting it.",
64
65
  "Before implementation, perform a system-wide impact check across callbacks, state, interfaces, schemas, and external contracts touched by the slice.",
@@ -115,6 +115,7 @@ If during any stage the agent discovers evidence that contradicts the initial Ph
115
115
  2. If flow state is missing → guide the user to run \`npx cclaw-cli init\` and stop.
116
116
  3. If flow state is only a fresh init placeholder (\`completedStages: []\`, all \`passed\` arrays empty, and no \`00-idea.md\`) → stop and ask for \`/cc <prompt>\` to start a tracked run. Do not create a brainstorm state implicitly.
117
117
  4. Otherwise check current stage gates, resume if incomplete, and advance if complete.
118
+ 5. **TDD wave dispatch (v6.13.1):** When \`currentStage\` is \`tdd\`, read \`${RUNTIME_ROOT}/artifacts/05-plan.md\` Parallel Execution Plan block and \`${RUNTIME_ROOT}/artifacts/wave-plans/\` **before** any slice-routing question. If an open wave still has multiple ready slices, resume parallel dispatch for the **remaining** members only (do not restart completed slices).
118
119
 
119
120
  ## Headless mode (CI/automation only)
120
121
 
@@ -207,9 +208,11 @@ Progress the tracked flow only when one exists:
207
208
  2. If missing, guide the user to run \`npx cclaw-cli init\` and stop.
208
209
  3. If it is only a fresh init placeholder (\`completedStages: []\`, no passed gates, and no \`${RUNTIME_ROOT}/artifacts/00-idea.md\`), stop and ask for \`/cc <prompt>\` to start a tracked run. Do not silently create a brainstorm run.
209
210
  4. Check gates for \`currentStage\`.
210
- 5. If incomplete load current stage skill and execute.
211
- 6. If complete advance to next stage and execute.
212
- 7. If flow is done report completion.
211
+ 5. **TDD (v6.13.1):** When \`currentStage\` is \`tdd\`, read \`${RUNTIME_ROOT}/artifacts/05-plan.md\` (managed \`## Parallel Execution Plan\` between \`parallel-exec-managed\` markers) and scan \`${RUNTIME_ROOT}/artifacts/wave-plans/wave-NN.md\` **before** asking which slice runs next. Merge sources in controller memory: Parallel Execution Plan first, wave files second; the same slice must not disagree across sources.
212
+ 6. **Wave dispatch resume:** If a wave is partially closed (some members already past GREEN/REFACTOR), continue with the remaining members in parallel; never redo finished lanes.
213
+ 7. If incomplete load current stage skill and execute.
214
+ 8. If complete → advance to next stage and execute.
215
+ 9. If flow is done → report completion.
213
216
 
214
217
  ## Public flow habit
215
218
 
@@ -739,11 +739,11 @@ ${renderBehaviorAnchorTemplateLine("spec")}
739
739
  - Drift from upstream (or \`None\`):
740
740
 
741
741
  ## Acceptance Criteria
742
- | ID | Requirement Ref (R#) | Criterion (observable/measurable/falsifiable) | Design Decision Ref (D-XX) |
743
- |---|---|---|---|
744
- | AC-1 | R1 | | |
742
+ | ID | Requirement Ref (R#) | Criterion (observable/measurable/falsifiable) | Design Decision Ref (D-XX) | parallelSafe (true/false) | touchSurface (paths/modules) |
743
+ |---|---|---|---|---|---|
744
+ | AC-1 | R1 | | | false | |
745
745
 
746
- > Standard ACs reference at least one \`R#\` from \`02-scope.md\`. Quick-track ACs may instead put \`Quick Reproduction Contract\` / bug-slice refs in the Requirement Ref column and \`N/A\` for Design Decision Ref. ACs are stable (never renumber): dropped ACs stay with Priority \`DROPPED\`; new ones append with the next free \`AC-#\`.
746
+ > Standard ACs reference at least one \`R#\` from \`02-scope.md\`. Quick-track ACs may instead put \`Quick Reproduction Contract\` / bug-slice refs in the Requirement Ref column and \`N/A\` for Design Decision Ref. ACs are stable (never renumber): dropped ACs stay with Priority \`DROPPED\`; new ones append with the next free \`AC-#\`. **v6.13.0:** \`parallelSafe\` states whether this AC can be proven in parallel with others; \`touchSurface\` lists repo-relative globs or modules this AC is expected to touch (scheduler + slice planning).
747
747
 
748
748
  ## Quick Reproduction Contract
749
749
  > Required for quick bug-fix specs; use \`N/A\` for non-bugfix or standard/medium tracks. TDD turns this contract into the RED reproduction test.
@@ -907,6 +907,12 @@ Execution rule: complete and verify each batch before starting the next batch.
907
907
  > Required structural form per implementation unit. Use ≥1 unit; bite-sized 2-5 minute steps inside each. The linter validates shape, not topic.
908
908
 
909
909
  ### Implementation Unit U-1
910
+ - **id:** U-1
911
+ - **dependsOn:** none
912
+ - **claimedPaths:** (repo-relative, comma-separated globs or files this unit expects to own)
913
+ - **parallelizable:** true
914
+ - **riskTier:** standard
915
+ - **lane:** (optional advisory lane tag for human-readable batching)
910
916
  - **Goal:**
911
917
  - **Requirements (from Spec):**
912
918
  - **Dependencies (other units):**
@@ -1,7 +1,8 @@
1
1
  import { type SubagentFallback } from "./harness-adapters.js";
2
2
  import { type MandatoryDelegationTaskClass } from "./content/stage-schema.js";
3
3
  import type { FlowStage } from "./types.js";
4
- import type { FlowState } from "./flow-state.js";
4
+ import { type FlowState } from "./flow-state.js";
5
+ import { type ParseImplementationUnitParallelOptions, type ParsedParallelWave } from "./internal/plan-split-waves.js";
5
6
  export type DelegationMode = "mandatory" | "proactive";
6
7
  export type DelegationStatus = "scheduled" | "launched" | "acknowledged" | "completed" | "failed" | "waived" | "stale";
7
8
  export declare const DELEGATION_DISPATCH_SURFACES: readonly ["claude-task", "cursor-task", "opencode-agent", "codex-agent", "generic-task", "role-switch", "manual"];
@@ -164,9 +165,26 @@ export type DelegationEntry = {
164
165
  * keep in sync with the inline copy in
165
166
  * `src/content/hooks.ts::delegationRecordScript`.
166
167
  */
167
- phase?: "red" | "green" | "refactor" | "refactor-deferred" | "doc";
168
+ phase?: "red" | "green" | "refactor" | "refactor-deferred" | "doc" | "resolve-conflict";
169
+ /**
170
+ * v6.13.0 — opaque token tying scheduled work to terminal lifecycle rows
171
+ * under worktree-first execution (mandatory on new schedules).
172
+ */
173
+ claimToken?: string;
174
+ /** v6.13.0 — lane / worktree id owning the slice checkout. */
175
+ ownerLaneId?: string;
176
+ /** v6.13.0 — ISO lease expiry for reclaim sweeps. */
177
+ leasedUntil?: string;
178
+ /** v6.13.0 — lease bookkeeping for audit + reclaim tooling. */
179
+ leaseState?: "claimed" | "expired" | "released" | "reclaimed";
180
+ /** v6.13.0 — plan unit dependency ids echoed for scheduler diagnostics. */
181
+ dependsOn?: string[];
182
+ /**
183
+ * v6.13.0 — integration branch merge status after deterministic fan-in.
184
+ */
185
+ integrationState?: "pending" | "applied" | "conflict" | "resolved" | "abandoned";
168
186
  };
169
- export declare const DELEGATION_PHASES: readonly ["red", "green", "refactor", "refactor-deferred", "doc"];
187
+ export declare const DELEGATION_PHASES: readonly ["red", "green", "refactor", "refactor-deferred", "doc", "resolve-conflict"];
170
188
  export type DelegationPhase = (typeof DELEGATION_PHASES)[number];
171
189
  export declare const DELEGATION_LEDGER_SCHEMA_VERSION: 3;
172
190
  export type DelegationLedger = {
@@ -191,9 +209,31 @@ export type DelegationEvent = DelegationEntry & {
191
209
  */
192
210
  export declare function isTrustBoundaryPath(filePath: string): boolean;
193
211
  export declare function readDelegationLedger(projectRoot: string): Promise<DelegationLedger>;
212
+ /** Parsed `cclaw_fanin_*` audit rows from `delegation-events.jsonl`. */
213
+ export interface FanInAuditRecord {
214
+ event: "cclaw_fanin_applied" | "cclaw_fanin_conflict" | "cclaw_fanin_resolved" | "cclaw_fanin_abandoned";
215
+ runId?: string;
216
+ laneId?: string;
217
+ sliceIds?: string[];
218
+ integrationBranch?: string;
219
+ details?: string;
220
+ ts: string;
221
+ }
222
+ /**
223
+ * Append a deterministic fan-in audit row (not a delegation lifecycle event).
224
+ */
225
+ export declare function recordCclawFanInAudit(projectRoot: string, params: {
226
+ kind: FanInAuditRecord["event"];
227
+ runId: string;
228
+ laneId: string;
229
+ sliceIds: string[];
230
+ integrationBranch: string;
231
+ details?: string;
232
+ }): Promise<void>;
194
233
  export declare function readDelegationEvents(projectRoot: string): Promise<{
195
234
  events: DelegationEvent[];
196
235
  corruptLines: number[];
236
+ fanInAudits: FanInAuditRecord[];
197
237
  }>;
198
238
  /**
199
239
  * Fold ledger entries to the latest row per `spanId` and keep only spans
@@ -319,12 +359,46 @@ export declare class DispatchCapError extends Error {
319
359
  };
320
360
  });
321
361
  }
362
+ /**
363
+ * v6.13.0 — claim / lease contract violation for worktree-first TDD rows.
364
+ */
365
+ export declare class DispatchClaimInvalidError extends Error {
366
+ constructor(message: string);
367
+ }
322
368
  /**
323
369
  * v6.10.0 (P2) — default cap on active `slice-implementer` spans in a
324
370
  * single TDD run. Aligned with evanflow's parallel cap. Override via
325
371
  * `CCLAW_MAX_PARALLEL_SLICE_IMPLEMENTERS=<int>` (validated `>=1`).
326
372
  */
327
373
  export declare const MAX_PARALLEL_SLICE_IMPLEMENTERS: 5;
374
+ export interface ReadySliceUnit {
375
+ unitId: string;
376
+ sliceId: string;
377
+ dependsOn: string[];
378
+ claimedPaths: string[];
379
+ parallelizable: boolean;
380
+ }
381
+ export interface SelectReadySlicesOptions {
382
+ cap: number;
383
+ completedUnitIds: ReadonlySet<string>;
384
+ activePathHolders: ReadonlyArray<{
385
+ paths: string[];
386
+ }>;
387
+ legacyContinuation: boolean;
388
+ }
389
+ /**
390
+ * Return up to `cap` slice units whose dependsOn are satisfied, avoiding
391
+ * `claimedPaths` intersections with already-selected units and active holders.
392
+ */
393
+ export declare function selectReadySlices(units: ReadySliceUnit[], opts: SelectReadySlicesOptions): ReadySliceUnit[];
394
+ /**
395
+ * v6.13.1 — build scheduler rows from merged parallel wave definitions + plan units.
396
+ */
397
+ export declare function readySliceUnitsFromMergedWaves(mergedWaves: ParsedParallelWave[], planMarkdown: string, options?: ParseImplementationUnitParallelOptions): ReadySliceUnit[];
398
+ /**
399
+ * v6.13.1 — load merged wave plan (Parallel Execution Plan block + wave-plans/) and map to `ReadySliceUnit[]`.
400
+ */
401
+ export declare function loadTddReadySlicePool(planMarkdown: string, artifactsDir: string, options?: ParseImplementationUnitParallelOptions): Promise<ReadySliceUnit[]>;
328
402
  /**
329
403
  * v6.10.0 (P1) — when scheduling a `slice-implementer` on a TDD stage,
330
404
  * compare `claimedPaths` against every currently active span on the
@@ -369,6 +443,11 @@ export declare function validateFanOutCap(stamped: DelegationEntry, activeEntrie
369
443
  */
370
444
  export declare function findActiveSpanForPair(stage: string, agent: string, runId: string, ledger: DelegationLedger): DelegationEntry | null;
371
445
  export declare function appendDelegation(projectRoot: string, entry: DelegationEntry): Promise<void>;
446
+ /**
447
+ * Scan delegation events for expired `leasedUntil` timestamps and append
448
+ * best-effort `cclaw_slice_lease_expired` audit rows (one per span/slice key).
449
+ */
450
+ export declare function reclaimExpiredDelegationClaims(projectRoot: string, now?: Date): Promise<number>;
372
451
  /**
373
452
  * Aggregate the fulfillment mode cclaw expects for the active harness set.
374
453
  * Priority native > generic-dispatch > role-switch > waiver — the best