Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(harness): task-planned loop with checkpoint commits, self-chunking doer, and rescue branches (#1064)

Brad Barbine5ba1210e013
diff --git a/.ai/docs/loop-system.md b/.ai/docs/loop-system.md
index 3a84ba418a..01aaf20942 100644
--- a/.ai/docs/loop-system.md
+++ b/.ai/docs/loop-system.md
@@ -9,15 +9,36 @@ outer-loop (OpenClaw cron → Claude Code headless)
└─ synthesizes a Binding from an assigned issue
└─ dispatches: crbn up --minimal --run 'pnpm --filter @carbon/harness loop <binding> --cwd <worktree>' --volumes
└─ harness runLoop (pure function, side effects via deps)
- ├─ doer (claude -p) — makes changes in the worktree
- ├─ floor gates — lint, conformance, clobbers
- ├─ per-package typecheck — only touched packages
- ├─ behavior gate — UI verification (unit test > visual > CLI proof)
- ├─ correctness gate — doer's testCommand
- ├─ judge (claude -p) — binary decomposition of acceptance criteria
- └─ keep / revert → next iteration or terminate
+ ├─ planner (claude -p) — decomposes the binding into small ordered
+ │ tasks (skipped for ≤2 criteria; falls back to one task)
+ └─ per task, up to taskMaxAttempts FAILED attempts:
+ ├─ doer (claude -p) — one focused session on THIS task;
+ │ may end early at a coherent SLICE (reports `remaining`)
+ ├─ CHECKPOINT — commit + push BEFORE gates (work preserved first)
+ ├─ floor gates — lint, conformance, clobbers
+ ├─ per-package typecheck — only touched packages
+ ├─ behavior gate — UI verification (passed | failed | unverified)
+ ├─ correctness gate — doer's testCommand
+ ├─ judge (claude -p) — reviews THIS task's diff (startSha..HEAD);
+ │ skipped for slices (nothing complete to approve yet)
+ └─ done → next task · slice → next session continues (not a failure)
+ not done → fix forward on the checkpoint
+ failed attempts exhausted → rescue branch + reset → end (salvage PR)
```
+**The doer chunks its own work too.** Its prompt tells it: if the task won't fit
+in one budgeted session, stop early at a coherent, committable slice and report
+`remaining` — a clean partial slice is success; racing the turn/budget cap to a
+broken finish is failure. Gate-green slices are checkpointed and pushed, skip
+the judge, reset the failure counter, and hand the next session the remaining
+work — so no session ever needs to be bigger than what it can finish cleanly.
+
+**Nothing is ever thrown away.** Every doer pass is committed and force-with-lease
+pushed to the loop branch before gates run; failed attempts stay on the branch as
+checkpoints that the next attempt fixes forward; a failed task's attempts are
+pushed to `loop-rescue/<id>/t<k>` before the branch resets to the last green
+checkpoint; a crashed process loses at most one uncommitted edit.
+
**Design docs:**
- `.ai/docs/outer-loop.md` — orchestrator architecture, wake loop, safety
- `.ai/skills/conductor/SKILL.md` — the inner-loop skill (what Claude Code follows during a build)
@@ -90,31 +111,38 @@ Plus **per-package typecheck** for each package the doer touched.
| Setting | Value | Notes |
|---------|-------|-------|
-| `plateauAfter` | 2 | consecutive no-progress iterations before stopping |
-| `maxIterations` | 8 | hard ceiling on total iterations |
+| `taskMaxAttempts` | 3 | doer attempts per plan task before rescue+reset |
+| `maxIterations` | 16 | hard ceiling on total iterations across all tasks |
+| `plannerMaxTurns` | 25 | |
+| `plannerMaxBudgetUsd` | $2 | |
| `doerMaxTurns` | 60 | |
| `doerMaxBudgetUsd` | $5 | |
-| `judgeMaxTurns` | 20 | |
-| `judgeMaxBudgetUsd` | $2 | |
+| `judgeMaxTurns` | 30 | per-task judge sessions are small — see #1063 for overrides |
+| `judgeMaxBudgetUsd` | $5 | |
| `behaviorMaxTurns` | 300 | raised from 40 in #961 |
| `behaviorMaxBudgetUsd` | $15 | raised from $3 in #961 |
+(`plateauAfter` is gone — progress control is per-task attempts now, not a
+global no-progress counter.)
+
## Terminal States
`LoopOutcome.state` is one of:
| State | Meaning |
|-------|---------|
-| `shipped` | green committed state, PR opened (or updated) — possibly flagged `unverified` |
-| `blocked` | doer reported a hard blocker (impossibility, never a question of preference) |
-| `plateau` | `plateauAfter` consecutive iterations with no kept change |
-| `error` | unexpected failure |
+| `shipped` | all plan tasks concluded, PR opened (or updated) — possibly flagged `unverified` |
+| `blocked` | doer reported a hard blocker, or the judge went silent on 2 consecutive tasks |
+| `plateau` | a task failed after `taskMaxAttempts` (attempts on its rescue branch), or `maxIterations` hit |
+| `error` | unexpected failure (tree checkpointed + pushed first) |
`LoopOutcome` also carries:
-- **`unverified?: string[]`** — proof gaps on kept work: the behavior gate could not verify **either way** (missing test data it couldn't construct, capped session, stack down). Absence of proof is *not* disproof — the work still ships, as a **draft PR** labeled `agent:needs-verification` whose body names exactly what a human must verify. Only a gate that *reached the state and saw the change not work* (`verdict: "failed"`) reverts the iteration.
+- **`unverified?: string[]`** — proof gaps on kept work: the behavior gate could not verify **either way** (missing test data it couldn't construct, capped session, stack down). Absence of proof is *not* disproof — the work still ships, as a **draft PR** labeled `agent:needs-verification` whose body names exactly what a human must verify. Only a gate that *reached the state and saw the change not work* (`verdict: "failed"`) counts as a red gate — and even then the checkpoint stays for the next attempt to fix forward.
- **`questions?: string[]`** — product questions raised mid-loop: acceptance criteria the judge *disputed* (wrong premise / needs a product decision — excluded from `unmet` so the loop doesn't churn on them) plus assumptions the doer made instead of blocking. The outer loop posts these back to the issue so grooming resolves them before any re-dispatch.
-- **`prUrl?`** — set for shipped runs *and* for **salvage PRs**: when a run ends `plateau`/`blocked` but kept (gate-green, judge-approved) commits exist, `run-loop` still opens a draft PR marked `[partial]` (`Related to #<n>`, never `Closes`) instead of letting the worktree GC discard paid-for work.
+- **`plan?`** — the task list and each task's status (`done` / `flagged` / `failed` / `pending`); rendered as a checklist in the PR body.
+- **Judge no-verdict handling** — a judge session that produces no parseable JSON (capped budget/turns, garbled output) is **absence of review, not rejection**. The loop retries the judge once with a fresh session; if the verdict is still missing, the task concludes **`flagged`** — kept and pushed, marked "kept without judge review" — rather than reverted. Two consecutive verdict-less tasks end the run `blocked`, with all kept work already on the branch. (Issue #1031 lost ~$8.5 of correct doer work to the old revert-on-no-verdict behavior.)
+- **`prUrl?`** — set for shipped runs *and* for **salvage PRs**: when a run ends `plateau`/`blocked`/`error` but committed work exists (any `keep` or `checkpoint` ledger entry), `run-loop` still opens a draft PR marked `[partial]` (`Related to #<n>`, never `Closes`) instead of letting the worktree GC discard paid-for work. Since every checkpoint is pushed, the branch survives even if PR creation itself fails.
The outer loop reads `outcome.json` to decide next steps (report, label, escalate).
diff --git a/.ai/docs/outer-loop.md b/.ai/docs/outer-loop.md
index 6e1fcfdd97..c7c716150d 100644
--- a/.ai/docs/outer-loop.md
+++ b/.ai/docs/outer-loop.md
@@ -21,12 +21,12 @@ OpenClaw runtime (heartbeat · webhooks · cron · sandbox · SQLite)
## Wake Loop (every 30 min)
-1. **Reconcile leases** — `agent:working` issues with no live build → stale → recover
+1. **Reconcile leases** — `agent:working` issues with no live build → stale → follow the Crash Recovery protocol below (never delete the branch)
2. **PR feedback** (highest priority) — unresolved review comments → re-enter inner loop on same branch
3. **Assigned work** — pick top issue by priority → run the pre-dispatch gate (below) → synthesize Binding → dispatch conductor
4. **Slack ingest** — tagged in a thread → read context, create issue, self-assign
5. **Idle** → groom one backlog issue (comment spec + acceptance criteria, never build)
-6. **GC** — prune worktrees, Docker volumes, loop runs — **never a branch with an open PR**
+6. **GC** — prune worktrees, Docker volumes, loop runs — **never `loop/*` or `loop-rescue/*` branches on origin** (worktrees are disposable; branches are the work)
## Grooming Contract — questions die here, not in the loop
@@ -53,6 +53,13 @@ we are avoiding — the loop either builds or returns; it never waits on a perso
4. **The binding body carries all grooming answers** — resolved questions,
repro steps, test-data hints, precedent pointers. The harness feeds it to
the doer, judge, and behavior gate.
+5. **The binding is loop-sized: at most ~8 acceptance criteria.** The harness
+ now chunks internally (its planner decomposes any >2-criteria binding into
+ small tasks, each with its own doer session, judge review, and checkpoint
+ commit), so moderate bindings are safe to dispatch as-is. But a binding
+ whose criteria span multiple modules or need >6 tasks is an epic wearing a
+ binding's clothes (#1031: 13 criteria) — label `agent:needs-decomposition`,
+ propose the split, and dispatch the pieces as separate issues.
**After a run**, any `questions` in `outcome.json` (disputed criteria, doer
assumptions) get posted to the issue. A human answers; the next grooming pass
@@ -79,12 +86,33 @@ crbn up --minimal --run 'pnpm --filter @carbon/harness loop <binding-path> --cwd
|---|---|---|
| `state: shipped`, no `unverified` | Fully proven, PR open | Comment PR link on issue, drop `agent:working` |
| `state: shipped` + `unverified` | Work kept & judge-approved; behavior proof was impossible (test data, environment). PR is a **draft** labeled `agent:needs-verification` | Comment PR link + the `unverified` gaps on the issue; label issue `agent:needs-verification`, **not** `agent:blocked` |
-| `state: plateau/blocked` + `prUrl` | Partial salvage draft PR (`[partial]`, `Related to #<n>`) — kept commits survived | Comment PR link + reason; label `agent:blocked`; the branch/PR carry the work forward |
-| `state: plateau/blocked`, no `prUrl` | Nothing worth keeping was produced | Label `agent:blocked` with the reason |
+| `state: plateau/blocked/error` + `prUrl` | Partial salvage draft PR (`[partial]`, `Related to #<n>`) — committed work survived | Comment PR link + reason; label `agent:blocked`; the branch/PR carry the work forward |
+| `state: plateau/blocked/error`, no `prUrl` | No committed work was produced (or PR creation failed — the pushed branch still exists) | Label `agent:blocked` with the reason; mention the branch if it exists on origin |
| any outcome with `questions` | Product questions surfaced (disputed criteria, doer assumptions) | Post them as an issue comment; a human answer + re-groom (fold answers into the binding body) precedes any re-dispatch |
+| any outcome with `plan` | Task plan + statuses (`done`/`flagged`/`failed`/`pending`) | Include in the issue comment; `failed` tasks name a `loop-rescue/<id>/t<k>` branch holding the attempts |
**"We couldn't prove it" ≠ "it doesn't work."** Kept work always ships in a PR — flagged, draft, never auto-merged — rather than being reverted and GC'd with the worktree.
+### Crash Recovery — a mechanical protocol, no judgment required
+
+The harness commits and pushes every doer pass to `loop/<id>` as it goes, so a
+dead PID loses at most one uncommitted edit. When a lease is stale (process
+dead, no `outcome.json`):
+
+1. **Never delete the branch.** GC may remove the *worktree* and Docker
+ volumes; branches on origin (`loop/<id>`, `loop-rescue/<id>/*`) are the
+ work — they stay until their PR closes.
+2. Check origin: `git ls-remote origin "refs/heads/loop/<id>"`.
+ - **Branch exists** → re-dispatch the SAME binding in a worktree based on
+ it: `crbn new loop/<id> --base origin/loop/<id> --yes`, then the normal
+ harness command. The loop re-plans, sees the committed progress, and
+ continues from where it died. `openPr` is idempotent — same branch, same PR.
+ - **No branch** → nothing was produced; re-dispatch fresh (base `origin/main`).
+3. Before re-dispatching after a second consecutive crash, capture evidence
+ instead of retrying blind: post the tail (~50 lines) of the dispatch
+ process's stdout/stderr and `.ai/runs/<id>/run.log.jsonl` (if the worktree
+ survives) as an issue comment, label `agent:blocked`.
+
### Agent Labels
| Label | Meaning |
diff --git a/.ai/skills/conductor/SKILL.md b/.ai/skills/conductor/SKILL.md
index 6ed2f3d39f..e1ab2a97e8 100644
--- a/.ai/skills/conductor/SKILL.md
+++ b/.ai/skills/conductor/SKILL.md
@@ -43,11 +43,23 @@ judge, and behavior gate: resolved questions, repro steps, test-data hints,
precedent pointers. Ambiguities should be settled there — at grooming time,
on the issue — before the loop ever starts, not asked mid-loop.
-## Step 2: The cycle (repeat until acceptance met or the human stops)
+## Step 2: Plan — chunk the work before building
-### 2.1 Doer
+If the binding has more than a couple of criteria, decompose it into **2–6
+small, ordered, independently-committable tasks** (schema first, then services,
+then UI), each mapped to the criteria it advances. Each task must be small
+enough for one focused session to build and one short review to verify. Record
+the plan; every commit and ledger entry names its task. (Headless, the harness
+does this itself — `runner/plan.ts`.)
-Make the **smallest change toward the weakest-covered acceptance criterion**.
+## Step 3: The cycle (per task, repeat until its criteria are met or the human stops)
+
+### 3.1 Doer
+
+Make the **smallest change that completes the current task** — other tasks are
+not this session's job. If the task won't fit in one focused session, stop at a
+**coherent, committable slice** (compiles, lint-clean) and record what remains
+— a clean partial slice is progress; a broken "complete" sprint is failure.
Never batch unrelated changes. Domain rules:
- **UI work**: FIRST find the nearest existing screen/component and copy its
@@ -58,7 +70,12 @@ Never batch unrelated changes. Domain rules:
typechecking (stale types make typecheck a false green).
- **Module code**: one `{module}.service.ts` + one `{module}.models.ts`.
-### 2.2 Gate
+### 3.2 Checkpoint, then gate
+
+**Commit the doer's work immediately** — `wip`-style checkpoint commits, pushed
+to the loop branch before any gate runs. Commit early, commit often: a failed
+gate is feedback for the next attempt, never a reason to discard work with
+`git checkout -- .`.
Run in order; every applicable gate must be green:
@@ -90,22 +107,25 @@ b. **Behavior gate — mandatory for ANY user-facing change.** Choose the
- **Proved** — you saw the behavior work. The gate is green.
- **Disproved** — you reached the relevant state and the behavior is still
- wrong. The gate is red: fix or revert this iteration.
+ wrong. The gate is red: fix forward on the next attempt.
- **Unverifiable** — you could not reach the state either way (test data you
can't construct at reasonable cost, stack won't boot, login/environment
failure). This is **absence of proof, not disproof** — do NOT revert
working, judge-approved code over it. Record exactly what proof is missing
and what a human would need to do, keep going, and ship the PR **flagged
- for human verification** (draft + `agent:needs-verification`, see Step 4).
+ for human verification** (draft + `agent:needs-verification`, see Step 5).
Never spend the whole behavior budget grinding on test-data generation —
stop early and mark it unverifiable.
c. **Correctness (bug fixes)** — reproduce→fix→same-path: the test (or recorded
browser playbook) that failed on the bug must pass after the fix.
-Any gate fails → fix it or revert this iteration's change.
+Any gate fails → the checkpoint STAYS; record why in the ledger and fix forward
+on the next attempt. After ~3 failed attempts on the same task, park the
+attempts on a rescue branch (`loop-rescue/<id>/t<k>`), reset to the last green
+checkpoint, and surface it — never delete the attempts.
-### 2.3 Judge — a separate subagent, never yourself
+### 3.3 Judge — a separate subagent, never yourself
Dispatch a review subagent to check the diff against the acceptance criteria
and design rules. Do not grade your own homework, and do not accept a holistic
@@ -130,27 +150,31 @@ and design rules. Do not grade your own homework, and do not accept a holistic
from the unmet set, and surface the question on the PR/issue. Iterating
cannot answer a product question; grooming can.
-### 2.4 Decide + ledger
+### 3.4 Decide + ledger
-Keep the change iff **every gate is green AND the judge approves**; otherwise
-revert it. An *unverifiable* behavior proof does not make the gate red — the
-change is kept (if the judge approves) and the proof gap travels with it to the
-PR as a needs-verification flag. Append one entry per iteration:
+The task is **done** iff every gate is green AND the judge approves AND none of
+the task's criteria remain unmet; otherwise the checkpoint stays and the next
+attempt fixes forward. An *unverifiable* behavior proof does not make the gate
+red — the change is kept and the proof gap travels with it to the PR as a
+needs-verification flag. A judge that produces no verdict (after one retry) is
+absence of review, not rejection: conclude the task *flagged* for human review.
+Append one entry per iteration:
```bash
-pnpm --filter @carbon/harness exec tsx -e "import {appendLedger} from '@carbon/harness'; appendLedger('.ai/runs/<id>/ledger.jsonl', {iteration: <n>, change: '<summary>', gates: {<gate>: <bool>}, decision: '<keep|revert>', reason: '<why>', at: new Date().toISOString()})"
+pnpm --filter @carbon/harness exec tsx -e "import {appendLedger} from '@carbon/harness'; appendLedger('.ai/runs/<id>/ledger.jsonl', {iteration: <n>, change: '<summary>', gates: {<gate>: <bool>}, decision: '<keep|checkpoint|revert>', reason: '<why>', task: '<k/N: title>', at: new Date().toISOString()})"
```
(The harness has no clock — you supply `at`.)
-### 2.5 Terminate?
+### 3.5 Terminate?
-All criteria met (disputed ones excluded, unverifiable proofs flagged) → Step 3.
-No progress across iterations (plateau) or the human stops → stop and report
-honestly — **but never discard kept work**: if any iteration was kept
-(gate-green + judge-approved), still open the PR per Step 4, marked *partial*.
+All tasks concluded (disputed criteria excluded, unverifiable proofs and
+judge-less tasks flagged) → Step 4. A task exhausts its attempts or the human
+stops → stop and report honestly — **but never discard committed work**: the
+checkpoints are already on the pushed branch; open the PR per Step 5, marked
+*partial*, and name any rescue branches.
-## Step 3: Post-build freshness audit
+## Step 4: Post-build freshness audit
Before opening the PR:
@@ -162,7 +186,7 @@ Before opening the PR:
3. New pitfall discovered? Append it to `.ai/lessons.md`
(`Context → Problem → Rule → Applies to`).
-## Step 4: Finish — land a gated PR
+## Step 5: Finish — land a gated PR
1. Final pass: run `/check-and-commit` on the branch state (biome + gates), so
the PR goes up clean.
@@ -193,6 +217,9 @@ Before opening the PR:
record the assumption, surface it on the PR. Reserve BLOCKED for hard
impossibilities (missing credentials, destructive/production actions,
a premise the code flatly contradicts).
+- Commit early, push often. Never discard uncommitted work with
+ `git checkout -- .` / `git clean` / `git reset --hard` without first parking
+ it on a commit that is pushed somewhere (the loop branch or a rescue branch).
- Never auto-merge; never run on `main`; never background or fan out — this is
the supervised loop.
- If blocked, say BLOCKED and why — and still salvage kept iterations as a
diff --git a/packages/harness/AGENTS.md b/packages/harness/AGENTS.md
index 5a12c5039a..ed7ddbdef8 100644
--- a/packages/harness/AGENTS.md
+++ b/packages/harness/AGENTS.md
@@ -5,9 +5,12 @@ AI agent harness — binding parsing, gate execution, the conductor loop, ledger
## Always
- **Parse bindings from `.loop.md` frontmatter** — `parseBinding(md)` extracts `id`, `kind`, `risk`, `title`, `acceptance[]`, and optional `issue` number
-- **Run floor gates before accepting changes** — `FLOOR_GATES` (lint, conformance, clobbers) are the minimum quality bar; the loop reverts on gate failure
-- **Append to the JSONL ledger after every iteration** — `appendLedger(path, entry)` records iteration, change, gates, decision (keep/revert), reason, timestamp, and any `unverified`/`questions`/`assumptions`
+- **Commit early, push often** — every doer pass is checkpoint-committed and force-with-lease pushed BEFORE gates run; failures fix forward on the checkpoint, never `git checkout -- .`
+- **The doer self-chunks** — a session that can't finish its task stops at a coherent slice and reports `remaining`; gate-green slices checkpoint, skip the judge, don't count as failed attempts, and the next session continues from them
+- **Run floor gates on the committed state** — `FLOOR_GATES` (lint, conformance, clobbers) are the minimum quality bar; a red gate means the next attempt fixes forward, and exhausted tasks park their attempts on `loop-rescue/<id>/t<k>` before resetting
+- **Append to the JSONL ledger after every iteration** — `appendLedger(path, entry)` records iteration, task, change, gates, decision (keep/checkpoint/revert), reason, timestamp, and any `unverified`/`questions`/`assumptions`
- **Distinguish disproof from absence of proof** — a behavior gate that reached the state and saw the change fail reverts the iteration; a gate that could not verify either way (`unverified`) keeps judge-approved work and ships it as a draft PR labeled `agent:needs-verification`
+- **A missing judge verdict is not a rejection** — no parseable JSON from the judge triggers one retry; still missing ⇒ gate-green work is kept flagged for human review (never reverted, never shipped-as-met); 2 consecutive verdict-less iterations ⇒ `blocked` + salvage PR
- **Never discard kept work** — non-shipped outcomes (plateau/blocked) with kept commits still open a `[partial]` salvage draft PR via `run-loop`
- **Never merge from the harness** — the loop ships PRs; merging is the human gate
@@ -34,9 +37,10 @@ pnpm --filter @carbon/harness gc # prune old run directories
## Key Patterns
-- **Binding**: `src/binding.ts` — YAML-ish frontmatter parser; `LoopKind = "bug" | "feature" | "usability" | "copy"`; the markdown body is captured as `notes` (grooming context injected into all three prompts)
+- **Binding**: `src/binding.ts` — YAML-ish frontmatter parser; `LoopKind = "bug" | "feature" | "usability" | "copy"`; the markdown body is captured as `notes` (grooming context injected into all prompts)
+- **Plan**: `src/runner/plan.ts` — `buildPlan(binding, config, deps)` decomposes a >2-criteria binding into 2–6 small ordered `PlanTask`s (planner session; falls back to one whole-binding task, coverage completed by construction)
- **Gates**: `src/gates.ts` — `FLOOR_GATES[]` + `runGates(gates, exec)` → `GateResult[]`
-- **Loop**: `src/runner/loop.ts` — `runLoop(binding, config, deps)` drives one work item through doer → behavior → judge → gates → keep/revert; collects `unverified` (proof gaps on kept work) and `questions` (judge-disputed criteria + doer assumptions) onto `LoopOutcome`
+- **Loop**: `src/runner/loop.ts` — `runLoop(binding, config, deps)` drives the plan task-by-task through doer → checkpoint(commit+push) → gates → behavior → judge(per-task diff) → done/fix-forward; collects `unverified`, `questions`, and `plan` statuses onto `LoopOutcome`
- **Behavior verdicts**: `src/runner/behavior.ts` — three-way `passed | failed | unverified`; stack-down, capped sessions, and unbuildable test data are `unverified`, never `failed`
- **Ledger**: `src/ledger.ts` — append-only JSONL log of iteration outcomes
- **PR**: `src/runner/pr.ts` — `openPr(binding, ledgerPath, shell, cwd, flags)`; `Closes #<issue>` when binding has `issue` (`Related to` on partial PRs); `flags.unverified`/`flags.partial` → draft + `agent:needs-verification` label
diff --git a/packages/harness/src/index.ts b/packages/harness/src/index.ts
index 9c9d2dbc86..c4ff51b788 100644
--- a/packages/harness/src/index.ts
+++ b/packages/harness/src/index.ts
@@ -24,12 +24,18 @@ export {
reachable
} from "./runner/behavior";
export { runLoop } from "./runner/loop";
+export {
+ buildPlan,
+ buildPlannerPrompt,
+ parsePlanResult
+} from "./runner/plan";
export {
buildDoerPrompt,
buildJudgePrompt,
extractJson,
parseDoerResult,
- parseJudgeResult
+ parseJudgeResult,
+ type TaskContext
} from "./runner/prompts";
export {
type BehaviorResult,
@@ -39,9 +45,11 @@ export {
type DoerResult,
type JudgeResult,
type LoopOutcome,
+ type PlanTask,
type RunnerConfig,
type RunnerDeps,
type Shell,
+ type TaskStatus,
type TerminalState
} from "./runner/types";
export {
diff --git a/packages/harness/src/ledger.ts b/packages/harness/src/ledger.ts
index 023414d256..394bc7abc5 100644
--- a/packages/harness/src/ledger.ts
+++ b/packages/harness/src/ledger.ts
@@ -5,8 +5,16 @@ export type LedgerEntry = {
iteration: number;
change: string;
gates: Record<string, boolean>;
- decision: "keep" | "revert";
+ /**
+ * `keep` = task-approved commit on the branch. `checkpoint` = committed and
+ * pushed (work preserved) but the task isn't approved yet — a later attempt
+ * fixes forward on top of it. `revert` = removed from the branch (attempts
+ * are still preserved on a rescue branch before any reset).
+ */
+ decision: "keep" | "revert" | "checkpoint";
reason: string;
+ /** The plan task this iteration worked on, as "k/N: title". */
+ task?: string;
/** Proof gaps this iteration — behavior gate could not verify either way. */
unverified?: string[];
/** Product questions the judge raised (disputed acceptance criteria). */
diff --git a/packages/harness/src/runner/loop.test.ts b/packages/harness/src/runner/loop.test.ts
index 1bf2d078b4..0e198dee11 100644
--- a/packages/harness/src/runner/loop.test.ts
+++ b/packages/harness/src/runner/loop.test.ts
@@ -19,6 +19,7 @@ const BINDING: Binding = {
kind: "bug",
title: "off-by-one in total",
risk: "low",
+ // ≤2 criteria ⇒ the planner session is skipped (single whole-binding task).
acceptance: ["total is correct", "a test covers it"]
};
@@ -63,8 +64,10 @@ function makeConfig(over: Partial<RunnerConfig> = {}): RunnerConfig {
return {
cwd: dir,
ledgerPath,
- plateauAfter: 2,
+ taskMaxAttempts: 2,
maxIterations: 8,
+ plannerMaxTurns: 5,
+ plannerMaxBudgetUsd: 1,
doerMaxTurns: 10,
doerMaxBudgetUsd: 1,
judgeMaxTurns: 5,
@@ -75,34 +78,54 @@ function makeConfig(over: Partial<RunnerConfig> = {}): RunnerConfig {
};
}
-/** Queue doer/judge responses; route by which prompt the loop sent. */
-function scriptedClaude(doers: string[], judges: string[]) {
+/** Queue planner/doer/judge responses; route by which prompt the loop sent. */
+function scriptedClaude(
+ doers: string[],
+ judges: string[],
+ planners: string[] = []
+) {
const d = [...doers];
const j = [...judges];
+ const p = [...planners];
return (req: ClaudeRequest): ClaudeResult => {
- const isDoer = req.prompt.includes("You are the DOER");
- const text = (isDoer ? d.shift() : j.shift()) ?? jsonText({});
- return { text, costUsd: 0, sessionId: "s" };
+ const text = req.prompt.includes("You are the DOER")
+ ? d.shift()
+ : req.prompt.includes("You are the PLANNER")
+ ? p.shift()
+ : j.shift();
+ return { text: text ?? jsonText({}), costUsd: 0, sessionId: "s" };
};
}
/** Dirty tree by default; named commands can be forced to fail. */
function dirtyShell(fail: string[] = []): RunnerDeps["shell"] {
return (cmd: string) => {
- if (cmd === "git diff --quiet") return { ok: false, output: "" }; // dirty
+ if (cmd === "git status --porcelain") return { ok: true, output: " M x" };
if (fail.some((f) => cmd.includes(f))) return { ok: false, output: "fail" };
return { ok: true, output: "" };
};
}
+/** dirtyShell that also records commit/push commands. */
+function recordingShell(fail: string[] = []): {
+ shell: RunnerDeps["shell"];
+ commits: string[];
+ pushes: string[];
+} {
+ const commits: string[] = [];
+ const pushes: string[] = [];
+ const base = dirtyShell(fail);
+ const shell: RunnerDeps["shell"] = (cmd, opts) => {
+ if (cmd.startsWith("git commit")) commits.push(cmd);
+ if (cmd.startsWith("git push")) pushes.push(cmd);
+ return base(cmd, opts);
+ };
+ return { shell, commits, pushes };
+}
+
describe("runLoop", () => {
- it("ships when gates pass and the judge approves with nothing unmet", () => {
- const committed: string[] = [];
- const shell: RunnerDeps["shell"] = (cmd) => {
- if (cmd === "git diff --quiet") return { ok: false, output: "" };
- if (cmd.startsWith("git commit")) committed.push(cmd);
- return { ok: true, output: "" };
- };
+ it("ships when gates pass and the judge approves — committed AND pushed", () => {
+ const { shell, commits, pushes } = recordingShell();
const deps = makeDeps({
claude: scriptedClaude(
[doer({ testCommand: "vitest run" })],
@@ -115,12 +138,81 @@ describe("runLoop", () => {
expect(out.state).toBe("shipped");
expect(out.iterations).toBe(1);
- expect(committed).toHaveLength(1);
+ expect(commits).toHaveLength(1);
+ // Commit early, push often — the checkpoint hit origin before gates ran.
+ expect(pushes.some((p) => p.includes("--force-with-lease"))).toBe(true);
+ expect(out.plan).toEqual([{ title: BINDING.title, status: "done" }]);
+ expect(readLedger(ledgerPath).at(-1)?.decision).toBe("keep");
+ });
+
+ it("checkpoints doer slices without a judge session, and slices don't burn attempts", () => {
+ let judgeCalls = 0;
+ const claude = (req: ClaudeRequest): ClaudeResult => {
+ if (req.prompt.includes("You are the DOER")) {
+ return { text: "", costUsd: 0, sessionId: "s" };
+ }
+ judgeCalls++;
+ return {
+ text: judge({ approved: true, unmet: [] }),
+ costUsd: 0,
+ sessionId: "s"
+ };
+ };
+ const doers = [
+ doer({ change: "models", remaining: "wire the service" }),
+ doer({ change: "service", remaining: "wire the UI" }),
+ doer({ change: "ui" }) // complete — only now does the judge run
+ ];
+ const scripted = (req: ClaudeRequest): ClaudeResult =>
+ req.prompt.includes("You are the DOER")
+ ? { text: doers.shift() ?? "", costUsd: 0, sessionId: "s" }
+ : claude(req);
+ const deps = makeDeps({
+ claude: scripted,
+ shell: dirtyShell()
+ });
+
+ // 3 slices with taskMaxAttempts=2: slices are progress, not failures.
+ const out = runLoop(BINDING, makeConfig({ taskMaxAttempts: 2 }), deps);
+
+ expect(out.state).toBe("shipped");
+ expect(out.iterations).toBe(3);
+ expect(judgeCalls).toBe(1);
const ledger = readLedger(ledgerPath);
- expect(ledger.at(-1)?.decision).toBe("keep");
+ expect(ledger.map((e) => e.decision)).toEqual([
+ "checkpoint",
+ "checkpoint",
+ "keep"
+ ]);
+ expect(ledger[0]?.reason).toBe(
+ "slice complete; remaining: wire the service"
+ );
});
- it("makes progress then ships once unmet is empty", () => {
+ it("counts a no-op 'remaining' session as a failed attempt (no infinite slicing)", () => {
+ const cleanShell: RunnerDeps["shell"] = (cmd) => {
+ if (cmd === "git status --porcelain") return { ok: true, output: "" };
+ return { ok: true, output: "" };
+ };
+ const deps = makeDeps({
+ claude: scriptedClaude(
+ [doer({ remaining: "everything" }), doer({ remaining: "everything" })],
+ []
+ ),
+ shell: cleanShell
+ });
+
+ const out = runLoop(BINDING, makeConfig({ taskMaxAttempts: 2 }), deps);
+
+ expect(out.state).toBe("plateau");
+ expect(
+ readLedger(ledgerPath).every((e) =>
+ e.reason.includes("no committable slice")
+ )
+ ).toBe(true);
+ });
+
+ it("fixes forward (checkpoint, not revert) when criteria remain, then ships", () => {
const deps = makeDeps({
claude: scriptedClaude(
[doer({}), doer({})],
@@ -136,39 +228,76 @@ describe("runLoop", () => {
expect(out.state).toBe("shipped");
expect(out.iterations).toBe(2);
- expect(
- readLedger(ledgerPath).filter((e) => e.decision === "keep")
- ).toHaveLength(2);
+ const ledger = readLedger(ledgerPath);
+ expect(ledger.map((e) => e.decision)).toEqual(["checkpoint", "keep"]);
+ expect(ledger[0]?.reason).toContain("criteria still unmet: 1");
});
- it("reverts on a failed gate and plateaus after plateauAfter dry iterations", () => {
+ it("checkpoints failed-gate attempts (work preserved) and ends plateau after taskMaxAttempts", () => {
const deps = makeDeps({
claude: scriptedClaude([doer({}), doer({})], []), // judge never reached — gates fail
shell: dirtyShell(["@carbon/checks test"]) // conformance gate fails
});
- const out = runLoop(BINDING, makeConfig({ plateauAfter: 2 }), deps);
+ const out = runLoop(BINDING, makeConfig({ taskMaxAttempts: 2 }), deps);
expect(out.state).toBe("plateau");
- expect(out.iterations).toBe(2);
+ expect(out.reason).toContain("failed after 2 attempts");
+ expect(out.plan?.[0]?.status).toBe("failed");
const ledger = readLedger(ledgerPath);
- expect(ledger.every((e) => e.decision === "revert")).toBe(true);
+ // No `git checkout -- .` discards — every attempt is a checkpoint commit.
+ expect(ledger.every((e) => e.decision === "checkpoint")).toBe(true);
expect(ledger.at(-1)?.gates.conformance).toBe(false);
});
- it("blocks when the doer reports it cannot proceed", () => {
+ it("rescues exhausted attempts to a branch and resets to the task start", () => {
+ let revParse = 0;
+ const base = dirtyShell(["@carbon/checks test"]);
+ const calls: string[] = [];
+ const shell: RunnerDeps["shell"] = (cmd, opts) => {
+ calls.push(cmd);
+ if (cmd === "git rev-parse HEAD") {
+ revParse++;
+ return { ok: true, output: revParse === 1 ? "startsha" : "tipsha" };
+ }
+ return base(cmd, opts);
+ };
+ const deps = makeDeps({
+ claude: scriptedClaude([doer({}), doer({})], []),
+ shell
+ });
+
+ const out = runLoop(BINDING, makeConfig({ taskMaxAttempts: 2 }), deps);
+
+ expect(out.state).toBe("plateau");
+ expect(
+ calls.some((c) =>
+ c.includes("git push origin HEAD:refs/heads/loop-rescue/bug-1/t1")
+ )
+ ).toBe(true);
+ expect(calls.some((c) => c === "git reset --hard startsha")).toBe(true);
+ const last = readLedger(ledgerPath).at(-1);
+ expect(last?.decision).toBe("revert");
+ expect(last?.reason).toContain("loop-rescue/bug-1/t1");
+ });
+
+ it("blocks when the doer reports it cannot proceed — after checkpointing its work", () => {
+ const { shell, commits } = recordingShell();
const deps = makeDeps({
claude: scriptedClaude(
[doer({ blocked: "need a product decision" })],
[]
),
- shell: dirtyShell()
+ shell
});
const out = runLoop(BINDING, makeConfig(), deps);
expect(out.state).toBe("blocked");
expect(out.reason).toContain("need a product decision");
+ // The dirty tree was committed before blocking — nothing thrown away.
+ expect(commits).toHaveLength(1);
+ expect(readLedger(ledgerPath).at(-1)?.decision).toBe("checkpoint");
});
it("blocks a UI change when no behavior gate is wired (milestone 1)", () => {
@@ -184,12 +313,7 @@ describe("runLoop", () => {
});
it("ships flagged (not reverted) when the behavior gate cannot verify either way", () => {
- const committed: string[] = [];
- const shell: RunnerDeps["shell"] = (cmd) => {
- if (cmd === "git diff --quiet") return { ok: false, output: "" };
- if (cmd.startsWith("git commit")) committed.push(cmd);
- return { ok: true, output: "" };
- };
+ const { shell, commits } = recordingShell();
const deps = makeDeps({
claude: scriptedClaude(
[doer({ touchedUI: true })],
@@ -211,17 +335,14 @@ describe("runLoop", () => {
"could not construct a PO with two receipts"
]);
expect(out.reason).toContain("needs human verification");
- expect(committed).toHaveLength(1);
+ expect(commits).toHaveLength(1);
const last = readLedger(ledgerPath).at(-1);
expect(last?.decision).toBe("keep");
- expect(last?.unverified).toEqual([
- "could not construct a PO with two receipts"
- ]);
// The behavior gate must not be recorded as failed — proof was unavailable.
expect(last?.gates.behavior).toBeUndefined();
});
- it("reverts when the behavior gate DISPROVES the change (reached the state, still broken)", () => {
+ it("checkpoints (never discards) when the behavior gate DISPROVES the change", () => {
const deps = makeDeps({
claude: scriptedClaude(
[doer({ touchedUI: true }), doer({ touchedUI: true })],
@@ -235,14 +356,53 @@ describe("runLoop", () => {
})
});
- const out = runLoop(BINDING, makeConfig({ plateauAfter: 2 }), deps);
+ const out = runLoop(BINDING, makeConfig({ taskMaxAttempts: 2 }), deps);
expect(out.state).toBe("plateau");
const ledger = readLedger(ledgerPath);
- expect(ledger.every((e) => e.decision === "revert")).toBe(true);
+ expect(ledger.every((e) => e.decision === "checkpoint")).toBe(true);
expect(ledger.at(-1)?.gates.behavior).toBe(false);
});
+ it("retries the judge once when it returns no verdict, then ships on the retry", () => {
+ const deps = makeDeps({
+ claude: scriptedClaude(
+ [doer({})],
+ [
+ "…budget ran out mid-review, no json…",
+ judge({ approved: true, unmet: [] })
+ ]
+ ),
+ shell: dirtyShell()
+ });
+
+ const out = runLoop(BINDING, makeConfig(), deps);
+
+ expect(out.state).toBe("shipped");
+ expect(out.iterations).toBe(1);
+ expect(readLedger(ledgerPath).at(-1)?.decision).toBe("keep");
+ });
+
+ it("concludes a task FLAGGED (kept, never reverted) when the judge has no verdict after retry", () => {
+ const { shell, commits } = recordingShell();
+ const noVerdict = "…no json at all…";
+ const deps = makeDeps({
+ claude: scriptedClaude([doer({})], [noVerdict, noVerdict]),
+ shell
+ });
+
+ const out = runLoop(BINDING, makeConfig(), deps);
+
+ expect(out.state).toBe("shipped");
+ expect(out.plan).toEqual([{ title: BINDING.title, status: "flagged" }]);
+ expect(out.unverified?.[0]).toContain("WITHOUT judge review");
+ expect(commits).toHaveLength(1);
+ expect(readLedger(ledgerPath).at(-1)?.decision).toBe("keep");
+ expect(readLedger(ledgerPath).at(-1)?.reason).toContain(
+ "pending human review"
+ );
+ });
+
it("ships with open questions when the judge disputes a criterion instead of churning", () => {
const deps = makeDeps({
claude: scriptedClaude(
@@ -267,24 +427,66 @@ describe("runLoop", () => {
]);
});
- it("runs the behavior gate for UI changes when wired", () => {
- let called = 0;
- const deps = makeDeps({
- claude: scriptedClaude(
- [doer({ touchedUI: true })],
- [judge({ approved: true, unmet: [] })]
- ),
- shell: dirtyShell(),
- behaviorGate: () => {
- called++;
- return { passed: true, screenshots: ["a.png"], notes: "ok" };
- }
+ describe("with a planner-decomposed binding", () => {
+ const BIG: Binding = {
+ id: "feat-1",
+ kind: "feature",
+ title: "period close",
+ risk: "med",
+ acceptance: ["migration exists", "service posts", "UI shows status"]
+ };
+ const plan = jsonText({
+ tasks: [
+ { title: "migration", detail: "…", criteria: [0] },
+ { title: "service + UI", detail: "…", criteria: [1, 2] }
+ ]
});
- const out = runLoop(BINDING, makeConfig(), deps);
+ it("drives tasks in order, one judge per task, and ships", () => {
+ const deps = makeDeps({
+ claude: scriptedClaude(
+ [doer({ change: "migration" }), doer({ change: "service+ui" })],
+ [
+ judge({ approved: true, unmet: [1, 2] }), // task 1: its criterion [0] met
+ judge({ approved: true, unmet: [] })
+ ],
+ [plan]
+ ),
+ shell: dirtyShell()
+ });
+
+ const out = runLoop(BIG, makeConfig(), deps);
+
+ expect(out.state).toBe("shipped");
+ expect(out.plan).toEqual([
+ { title: "migration", status: "done" },
+ { title: "service + UI", status: "done" }
+ ]);
+ const ledger = readLedger(ledgerPath);
+ expect(ledger.map((e) => e.decision)).toEqual(["keep", "keep"]);
+ expect(ledger[0]?.task).toBe("1/2: migration");
+ });
- expect(called).toBe(1);
- expect(out.state).toBe("shipped");
- expect(readLedger(ledgerPath).at(-1)?.gates.behavior).toBe(true);
+ it("blocks after 2 consecutive judge-less tasks, keeping both", () => {
+ const noVerdict = "…no json…";
+ const deps = makeDeps({
+ claude: scriptedClaude(
+ [doer({}), doer({})],
+ // 2 tasks × (ask + retry), all verdict-less
+ [noVerdict, noVerdict, noVerdict, noVerdict],
+ [plan]
+ ),
+ shell: dirtyShell()
+ });
+
+ const out = runLoop(BIG, makeConfig(), deps);
+
+ expect(out.state).toBe("blocked");
+ expect(out.reason).toContain("judge produced no verdict");
+ expect(out.plan?.map((t) => t.status)).toEqual(["flagged", "flagged"]);
+ expect(readLedger(ledgerPath).every((e) => e.decision === "keep")).toBe(
+ true
+ );
+ });
});
});
diff --git a/packages/harness/src/runner/loop.ts b/packages/harness/src/runner/loop.ts
index 57b215ec1f..e3eb3756ea 100644
--- a/packages/harness/src/runner/loop.ts
+++ b/packages/harness/src/runner/loop.ts
@@ -1,11 +1,13 @@
import type { Binding } from "../binding";
import { FLOOR_GATES, runGates } from "../gates";
import { appendLedger, readLedger } from "../ledger";
+import { buildPlan } from "./plan";
import {
buildDoerPrompt,
buildJudgePrompt,
parseDoerResult,
- parseJudgeResult
+ parseJudgeResult,
+ type TaskContext
} from "./prompts";
import { sq } from "./shell";
import type {
@@ -13,12 +15,13 @@ import type {
LoopOutcome,
RunnerConfig,
RunnerDeps,
- Shell
+ Shell,
+ TaskStatus
} from "./types";
-/** Is the working tree dirty? `git diff --quiet` exits non-zero when it is. */
+/** Anything uncommitted — tracked modifications AND untracked files. */
function isDirty(shell: Shell, cwd: string): boolean {
- return !shell("git diff --quiet", { cwd }).ok;
+ return shell("git status --porcelain", { cwd }).output.trim().length > 0;
}
function commit(shell: Shell, cwd: string, message: string): void {
@@ -27,10 +30,23 @@ function commit(shell: Shell, cwd: string, message: string): void {
shell(`git commit -m ${sq(message)}`, { cwd });
}
-/** Discard the current iteration's uncommitted work. Ignored files (the ledger) survive. */
-function revert(shell: Shell, cwd: string): void {
- shell("git checkout -- .", { cwd });
- shell("git clean -fd", { cwd });
+/**
+ * Best-effort push after every commit — commit early, push often. A crashed
+ * process (the #1031 / #1005 failure mode) then loses at most one uncommitted
+ * edit; everything else is already on origin. Failure (offline, no remote) is
+ * logged and ignored — never fatal.
+ */
+function push(shell: Shell, cwd: string, log: RunnerDeps["log"]): void {
+ // force-with-lease: after a task rescue the shipping branch resets behind
+ // origin — force-updating it is safe because the rescue branch already
+ // preserved those commits, and the run mutex makes this branch's only writer
+ // this loop.
+ const r = shell("git push --force-with-lease -u origin HEAD", { cwd });
+ if (!r.ok) log({ event: "push:failed", output: r.output.slice(0, 500) });
+}
+
+function headSha(shell: Shell, cwd: string): string {
+ return shell("git rev-parse HEAD", { cwd }).output.trim();
}
function revertReason(
@@ -42,19 +58,28 @@ function revertReason(
.map(([id]) => id);
if (failed.length > 0) return `gates failed: ${failed.join(", ")}`;
if (!judge.approved) return `judge rejected: ${judge.feedback}`;
- return "reverted";
+ return "not approved";
}
/**
* Drive ONE work item through the conductor cycle to a green committed state,
* fully unattended. This is the deterministic spine of the conductor skill,
- * promoted out of prose into code: the loop owns worktree state, gate execution,
- * keep/revert, the ledger, and the terminal-state machine; the model is invoked
- * only for the three judgment steps (doer, behavior, judge).
+ * promoted out of prose into code — and out of the (possibly weak) outer-loop
+ * model's judgment. The harness owns:
+ *
+ * - CHUNKING: a planner phase decomposes the binding into small ordered tasks
+ * (deterministic fallback: one whole-binding task). Each task is one
+ * doer-session-sized unit with its own judge review.
+ * - CHECKPOINTS: every doer pass is committed AND pushed before gates run.
+ * Failures fix forward on top of the checkpoint; nothing is ever discarded
+ * by `git checkout -- .`.
+ * - RESCUE: a task that exhausts its attempts pushes them to a rescue branch
+ * before resetting to the last green checkpoint — preserved, reviewable,
+ * out of the shipping branch.
*
* Pure w.r.t. the outside world — every side effect goes through `deps`. The
- * caller (the script) creates the worktree and, on a `shipped` outcome, opens
- * the PR. This function never merges and never runs on `main`.
+ * caller (the script) creates the worktree and opens the PR. This function
+ * never merges and never runs on `main`.
*/
export function runLoop(
binding: Binding,
@@ -64,25 +89,28 @@ export function runLoop(
const { claude, shell, now, log } = deps;
const { cwd, ledgerPath } = config;
let iteration = 0;
- let sinceKeep = 0;
// Proof gaps on KEPT work and product questions raised along the way — both
// ride the outcome so the PR/issue gets flagged instead of the work vanishing.
const unverified: string[] = [];
const questions: string[] = [];
+ // Consecutive tasks concluded without any judge verdict (even after retries)
+ // — a persistent judge outage shouldn't keep burning doer budget.
+ let judgeMissingStreak = 0;
+
+ // Phase 0: PLAN — systematic chunking, in code not in model judgment.
+ const tasks = buildPlan(binding, config, deps);
+ const status: TaskStatus[] = tasks.map(() => "pending");
const end = (state: LoopOutcome["state"], reason: string): LoopOutcome => {
- log({
- event: "loop:end",
- state,
- reason,
- iterations: iteration,
- unverified: unverified.length,
- questions: questions.length
- });
+ log({ event: "loop:end", state, reason, iterations: iteration });
return {
state,
iterations: iteration,
reason,
+ plan: tasks.map((t, i) => ({
+ title: t.title,
+ status: status[i] ?? "pending"
+ })),
...(unverified.length > 0
? { unverified: [...new Set(unverified)] }
: {}),
@@ -90,184 +118,343 @@ export function runLoop(
};
};
- while (iteration < config.maxIterations) {
- iteration++;
- try {
- const ledger = readLedger(ledgerPath);
- log({ event: "iteration:start", iteration });
-
- // 1. DOER — smallest change toward the weakest criterion.
- const doerRes = claude({
- prompt: buildDoerPrompt(binding, ledger),
- cwd,
- maxTurns: config.doerMaxTurns,
- maxBudgetUsd: config.doerMaxBudgetUsd
- });
- const doer = parseDoerResult(doerRes.text);
- log({
- event: "doer",
- iteration,
- change: doer.change,
- cost: doerRes.costUsd
- });
+ for (let k = 0; k < tasks.length; k++) {
+ const task = tasks[k];
+ if (!task) continue;
+ const taskLabel = `${k + 1}/${tasks.length}: ${task.title}`;
+ const startSha = headSha(shell, cwd);
+ const ctx: TaskContext = {
+ task,
+ index: k + 1,
+ total: tasks.length,
+ ...(startSha ? { startSha } : {})
+ };
+ // The doer chunks its own work too: a gate-green SLICE (doer reports
+ // `remaining`) is progress — it resets the failure counter and skips the
+ // judge. Only failures (red gates, judge rejection, no-op sessions) count
+ // toward taskMaxAttempts. `maxIterations` bounds everything globally.
+ let failed = 0;
+ let slice = 0;
- if (doer.blocked) {
- revert(shell, cwd);
- return end("blocked", `doer blocked: ${doer.blocked}`);
+ while (failed < config.taskMaxAttempts) {
+ if (iteration >= config.maxIterations) {
+ return end(
+ "plateau",
+ `hit max iterations (${config.maxIterations}) during task ${taskLabel}`
+ );
}
+ iteration++;
+ slice++;
+ try {
+ const ledger = readLedger(ledgerPath);
+ log({ event: "iteration:start", iteration, task: taskLabel, slice });
- // The doer may have decided nothing was needed. If the tree is clean, the
- // only question left is "are we done?" — let the judge confirm.
- const dirty = isDirty(shell, cwd);
+ // 1. DOER — one focused session on the current task, fixing forward.
+ const doerRes = claude({
+ prompt: buildDoerPrompt(binding, ledger, ctx),
+ cwd,
+ maxTurns: config.doerMaxTurns,
+ maxBudgetUsd: config.doerMaxBudgetUsd
+ });
+ const doer = parseDoerResult(doerRes.text);
+ log({
+ event: "doer",
+ iteration,
+ task: taskLabel,
+ change: doer.change,
+ cost: doerRes.costUsd
+ });
- const gates: Record<string, boolean> = {};
- // Proof gaps THIS iteration (behavior gate couldn't verify either way).
- const iterUnverified: string[] = [];
- if (dirty) {
- // 2. FLOOR GATES (lint + conformance + clobbers) and per-package typecheck.
- const floor = config.gates ?? FLOOR_GATES;
- for (const r of runGates(floor, (cmd) => shell(cmd, { cwd }))) {
- gates[r.id] = r.passed;
+ // 2. CHECKPOINT — commit early, push often. The work is preserved
+ // BEFORE anything gets a chance to fail.
+ const dirty = isDirty(shell, cwd);
+ if (dirty) {
+ commit(
+ shell,
+ cwd,
+ `loop(${binding.id}): [t${k + 1}.s${slice}] ${doer.change}`
+ );
+ push(shell, cwd, log);
}
- for (const pkg of doer.packages) {
- gates[`typecheck:${pkg}`] = shell(`pnpm --filter ${pkg} typecheck`, {
- cwd
- }).ok;
+
+ if (doer.blocked) {
+ // The checkpoint above already preserved anything it left behind.
+ if (dirty) {
+ appendLedger(ledgerPath, {
+ iteration,
+ change: doer.change,
+ gates: {},
+ decision: "checkpoint",
+ reason: `doer blocked: ${doer.blocked}`,
+ task: taskLabel,
+ at: now()
+ });
+ }
+ return end("blocked", `doer blocked: ${doer.blocked}`);
}
- // 3. BEHAVIOR GATE — UI changes are not done until seen working in the app.
- if (doer.touchedUI) {
- if (!deps.behaviorGate) {
- revert(shell, cwd);
- return end(
- "blocked",
- "change touches UI but the headless behavior gate is not available (milestone 2)"
- );
+ // 3. FLOOR GATES (lint + conformance + clobbers) and per-package
+ // typecheck — on the committed state.
+ const gates: Record<string, boolean> = {};
+ const iterUnverified: string[] = [];
+ if (dirty) {
+ const floor = config.gates ?? FLOOR_GATES;
+ for (const r of runGates(floor, (cmd) => shell(cmd, { cwd }))) {
+ gates[r.id] = r.passed;
}
- const b = deps.behaviorGate(binding, config, deps);
- if (b.unverified) {
- // Absence of proof is not disproof. Don't fail the gate — record
- // the gap; if the judge approves, the work ships as a draft PR
- // flagged for human verification instead of being reverted.
- iterUnverified.push(b.unverified);
- } else {
- gates.behavior = b.passed;
+ for (const pkg of doer.packages) {
+ gates[`typecheck:${pkg}`] = shell(
+ `pnpm --filter ${pkg} typecheck`,
+ {
+ cwd
+ }
+ ).ok;
}
- log({
- event: "behavior",
+
+ // 4. BEHAVIOR GATE — UI changes are not done until seen working.
+ if (doer.touchedUI) {
+ if (!deps.behaviorGate) {
+ return end(
+ "blocked",
+ "change touches UI but the headless behavior gate is not available (milestone 2)"
+ );
+ }
+ const b = deps.behaviorGate(binding, config, deps);
+ if (b.unverified) {
+ // Absence of proof is not disproof — record the gap; the work
+ // ships flagged for human verification.
+ iterUnverified.push(b.unverified);
+ } else {
+ gates.behavior = b.passed;
+ }
+ log({
+ event: "behavior",
+ iteration,
+ passed: b.passed,
+ ...(b.unverified ? { unverified: b.unverified } : {}),
+ shots: b.screenshots.length,
+ notes: b.notes
+ });
+ }
+
+ // 5. CORRECTNESS GATE — the reproduce→fix→same-path test.
+ if (doer.testCommand) {
+ gates.correctness = shell(doer.testCommand, { cwd }).ok;
+ }
+ }
+ const gatesGreen = Object.values(gates).every(Boolean);
+
+ // 6a. SLICE — the doer chunked itself: a gate-green, committed slice
+ // with work remaining is progress. Checkpoint it, skip the judge
+ // (nothing complete to approve yet), reset the failure counter, and
+ // hand the next session the remaining work.
+ if (doer.remaining && gatesGreen && dirty) {
+ failed = 0;
+ appendLedger(ledgerPath, {
iteration,
- passed: b.passed,
- ...(b.unverified ? { unverified: b.unverified } : {}),
- shots: b.screenshots.length,
- notes: b.notes
+ change: doer.change,
+ gates,
+ decision: "checkpoint",
+ reason: `slice complete; remaining: ${doer.remaining}`,
+ task: taskLabel,
+ ...(iterUnverified.length > 0
+ ? { unverified: iterUnverified }
+ : {}),
+ at: now()
});
+ continue;
}
- // 4. CORRECTNESS GATE — the reproduce→fix→same-path test.
- if (doer.testCommand) {
- gates.correctness = shell(doer.testCommand, { cwd }).ok;
+ // 6b. JUDGE — only worth a session when the doer says the task is
+ // complete and the objective gates pass.
+ let judge: JudgeResult = {
+ approved: false,
+ unmet: [],
+ feedback: doer.remaining
+ ? "session ended incomplete with no committable slice"
+ : "gates failed"
+ };
+ if (gatesGreen && !doer.remaining) {
+ const askJudge = () =>
+ claude({
+ prompt: buildJudgePrompt(binding, ctx),
+ cwd,
+ maxTurns: config.judgeMaxTurns,
+ maxBudgetUsd: config.judgeMaxBudgetUsd
+ });
+ let judgeRes = askJudge();
+ judge = parseJudgeResult(judgeRes.text);
+ // No verdict (capped session / garbled output) ⇒ one fresh retry —
+ // cheap next to the doer work a false "rejection" would discard.
+ if (judge.verdictMissing) {
+ log({
+ event: "judge:retry",
+ iteration,
+ cost: judgeRes.costUsd,
+ stopReason: judgeRes.stopReason
+ });
+ judgeRes = askJudge();
+ judge = parseJudgeResult(judgeRes.text);
+ }
+ log({
+ event: "judge",
+ iteration,
+ approved: judge.approved,
+ unmet: judge.unmet,
+ cost: judgeRes.costUsd,
+ ...(judgeRes.stopReason ? { stopReason: judgeRes.stopReason } : {}),
+ ...(judge.verdictMissing ? { verdictMissing: true } : {}),
+ ...(judge.disputed ? { disputed: judge.disputed } : {})
+ });
}
- }
- const gatesGreen = Object.values(gates).every(Boolean);
+ // Disputed criteria are product questions, not build targets — they
+ // reach the PR/issue and stop counting as unmet.
+ const disputedIdx = new Set((judge.disputed ?? []).map((d) => d.index));
+ questions.push(
+ ...(judge.disputed ?? []).map(
+ (d) =>
+ `Acceptance [${d.index}] "${binding.acceptance[d.index] ?? "?"}": ${d.question}`
+ )
+ );
- // 5. JUDGE — only worth a session when the objective gates already pass.
- let judge: JudgeResult = {
- approved: false,
- unmet: [],
- feedback: "gates failed"
- };
- if (gatesGreen) {
- const judgeRes = claude({
- prompt: buildJudgePrompt(binding),
- cwd,
- maxTurns: config.judgeMaxTurns,
- maxBudgetUsd: config.judgeMaxBudgetUsd
+ // 7. DECIDE. The task is DONE when gates are green, the judge approved,
+ // and none of ITS criteria remain unmet (disputed ones excluded). A
+ // judge with no verdict after retry concludes the task FLAGGED — kept
+ // for human review, never reverted, never silently shipped-as-met.
+ const judgeUnavailable = gatesGreen && judge.verdictMissing === true;
+ const taskUnmet = judge.unmet.filter(
+ (i) => task.criteria.includes(i) && !disputedIdx.has(i)
+ );
+ const taskDone = gatesGreen && judge.approved && taskUnmet.length === 0;
+
+ if (taskDone || judgeUnavailable) {
+ if (judgeUnavailable) {
+ iterUnverified.push(
+ `task ${taskLabel} kept WITHOUT judge review (no verdict after retry) — needs human code review`
+ );
+ judgeMissingStreak++;
+ } else {
+ judgeMissingStreak = 0;
+ }
+ status[k] = judgeUnavailable ? "flagged" : "done";
+ unverified.push(...iterUnverified);
+ questions.push(
+ ...(doer.assumptions ?? []).map((a) => `Assumption: ${a}`)
+ );
+ appendLedger(ledgerPath, {
+ iteration,
+ change: doer.change,
+ gates,
+ decision: "keep",
+ reason: judgeUnavailable
+ ? "gates green; kept without judge verdict — pending human review"
+ : iterUnverified.length > 0
+ ? "gates green; judge approved (behavior proof incomplete)"
+ : "gates green; judge approved",
+ task: taskLabel,
+ ...(iterUnverified.length > 0
+ ? { unverified: iterUnverified }
+ : {}),
+ ...(doer.assumptions && doer.assumptions.length > 0
+ ? { assumptions: doer.assumptions }
+ : {}),
+ at: now()
+ });
+ if (judgeMissingStreak >= 2) {
+ return end(
+ "blocked",
+ "judge produced no verdict on 2 consecutive tasks (even after retries) — kept work needs human review"
+ );
+ }
+ break; // next task
+ }
+
+ // Not done: the checkpoint STAYS on the branch (fix forward) — the
+ // next attempt improves on it with the failure reason in the ledger.
+ // This is the only path that counts toward taskMaxAttempts.
+ failed++;
+ appendLedger(ledgerPath, {
+ iteration,
+ change: doer.change,
+ gates,
+ decision: "checkpoint",
+ reason: `fixing forward: ${
+ gatesGreen && taskUnmet.length > 0 && judge.approved
+ ? `criteria still unmet: ${taskUnmet.join(", ")}`
+ : revertReason(gates, judge)
+ }`,
+ task: taskLabel,
+ ...(iterUnverified.length > 0 ? { unverified: iterUnverified } : {}),
+ at: now()
});
- judge = parseJudgeResult(judgeRes.text);
- log({
- event: "judge",
+ } catch (err) {
+ // Unexpected failure (claude spawn error, git/fs error): preserve
+ // whatever is in the tree as a checkpoint, record, end cleanly.
+ const message = err instanceof Error ? err.message : String(err);
+ try {
+ if (isDirty(shell, cwd)) {
+ commit(shell, cwd, `loop(${binding.id}): [error salvage] wip`);
+ push(shell, cwd, log);
+ }
+ } catch {
+ /* best-effort */
+ }
+ appendLedger(ledgerPath, {
iteration,
- approved: judge.approved,
- unmet: judge.unmet,
- ...(judge.disputed ? { disputed: judge.disputed } : {})
+ change: "(error)",
+ gates: {},
+ decision: "checkpoint",
+ reason: `loop error: ${message}`,
+ task: taskLabel,
+ at: now()
});
+ return end("error", message);
}
+ }
- // Disputed criteria are product questions, not build targets — surface
- // them (they reach the PR/issue) whether or not this change is kept.
- const disputedQs = (judge.disputed ?? []).map(
- (d) =>
- `Acceptance [${d.index}] "${binding.acceptance[d.index] ?? "?"}": ${d.question}`
- );
- questions.push(...disputedQs);
-
- // 6. DECIDE + LEDGER. Keep iff every gate is green AND the judge approves.
- const keep = gatesGreen && judge.approved;
- if (dirty) {
- if (keep) commit(shell, cwd, `loop(${binding.id}): ${doer.change}`);
- else revert(shell, cwd);
- }
- if (keep) {
- unverified.push(...iterUnverified);
- questions.push(
- ...(doer.assumptions ?? []).map((a) => `Assumption: ${a}`)
- );
- }
- appendLedger(ledgerPath, {
- iteration,
- change: doer.change,
- gates,
- decision: keep ? "keep" : "revert",
- reason: keep
- ? iterUnverified.length > 0
- ? "gates green; judge approved (behavior proof incomplete)"
- : "all gates green; judge approved"
- : revertReason(gates, judge),
- ...(iterUnverified.length > 0 ? { unverified: iterUnverified } : {}),
- ...(disputedQs.length > 0 ? { questions: disputedQs } : {}),
- ...(doer.assumptions && doer.assumptions.length > 0
- ? { assumptions: doer.assumptions }
- : {}),
- at: now()
- });
-
- // 7. TERMINATE?
- if (keep && judge.unmet.length === 0) {
- return end(
- "shipped",
- unverified.length > 0
- ? "acceptance met per judge; behavior proof incomplete — needs human verification"
- : "all acceptance criteria met and provable"
- );
- }
- // Progress = a real change was committed. A clean no-op never counts.
- if (keep && dirty) sinceKeep = 0;
- else sinceKeep++;
- if (sinceKeep >= config.plateauAfter) {
- return end("plateau", `no progress across ${sinceKeep} iterations`);
- }
- } catch (err) {
- // Any unexpected failure (e.g. claude returned no JSON at all, git/fs
- // error) is recorded and ends the run cleanly — never an uncaught crash
- // that loses the worktree state and writes no ledger.
- const message = err instanceof Error ? err.message : String(err);
- try {
- revert(shell, cwd);
- } catch {
- /* best-effort */
+ // Attempts exhausted without approval: RESCUE the attempts to a branch,
+ // then reset the shipping branch to the task's start. Nothing is lost —
+ // it's just not on the branch a human is asked to merge.
+ if (status[k] === "pending") {
+ status[k] = "failed";
+ const rescue = `loop-rescue/${binding.id}/t${k + 1}`;
+ const tip = headSha(shell, cwd);
+ if (tip && tip !== startSha) {
+ const pushed = shell(`git push origin HEAD:refs/heads/${rescue}`, {
+ cwd
+ });
+ log({ event: "rescue", branch: rescue, pushed: pushed.ok });
+ if (startSha) {
+ shell(`git reset --hard ${startSha}`, { cwd });
+ shell("git clean -fd", { cwd });
+ push(shell, cwd, log); // won't move origin backwards; best-effort
+ }
+ appendLedger(ledgerPath, {
+ iteration,
+ change: `task ${taskLabel} attempts reset`,
+ gates: {},
+ decision: "revert",
+ reason: `task failed after ${config.taskMaxAttempts} attempts; attempts preserved on ${
+ pushed.ok ? rescue : `local history (rescue push failed)`
+ }`,
+ task: taskLabel,
+ at: now()
+ });
}
- appendLedger(ledgerPath, {
- iteration,
- change: "(error)",
- gates: {},
- decision: "revert",
- reason: `loop error: ${message}`,
- at: now()
- });
- return end("error", message);
+ return end(
+ "plateau",
+ `task ${taskLabel} failed after ${config.taskMaxAttempts} attempts — attempts preserved on ${rescue}`
+ );
}
}
- return end("plateau", `hit max iterations (${config.maxIterations})`);
+ // Every task concluded (done or flagged).
+ const flagged = status.filter((s) => s === "flagged").length;
+ return end(
+ "shipped",
+ flagged > 0 || unverified.length > 0
+ ? "all tasks concluded — needs human verification of the flagged parts"
+ : "all acceptance criteria met and provable"
+ );
}
diff --git a/packages/harness/src/runner/plan.test.ts b/packages/harness/src/runner/plan.test.ts
new file mode 100644
index 0000000000..5794128640
--- /dev/null
+++ b/packages/harness/src/runner/plan.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from "vitest";
+import type { Binding } from "../binding";
+import { buildPlan, parsePlanResult } from "./plan";
+import type { ClaudeResult, RunnerConfig, RunnerDeps } from "./types";
+
+const BINDING: Binding = {
+ id: "feat-1",
+ kind: "feature",
+ title: "period close",
+ risk: "med",
+ acceptance: ["migration", "service", "UI", "docs"]
+};
+
+const SMALL: Binding = { ...BINDING, acceptance: ["one", "two"] };
+
+function json(obj: unknown): string {
+ return `\`\`\`json\n${JSON.stringify(obj)}\n\`\`\``;
+}
+
+function deps(claude: () => ClaudeResult): RunnerDeps {
+ return {
+ claude,
+ shell: () => ({ ok: true, output: "" }),
+ now: () => "t",
+ log: () => undefined
+ };
+}
+
+const config = {
+ cwd: "/tmp",
+ ledgerPath: "/tmp/l.jsonl",
+ taskMaxAttempts: 3,
+ maxIterations: 16,
+ plannerMaxTurns: 5,
+ plannerMaxBudgetUsd: 1,
+ doerMaxTurns: 1,
+ doerMaxBudgetUsd: 1,
+ judgeMaxTurns: 1,
+ judgeMaxBudgetUsd: 1,
+ behaviorMaxTurns: 1,
+ behaviorMaxBudgetUsd: 1
+} satisfies RunnerConfig;
+
+describe("parsePlanResult", () => {
+ it("parses tasks and appends a catch-all for uncovered criteria", () => {
+ const tasks = parsePlanResult(
+ json({
+ tasks: [
+ { title: "migration", detail: "d", criteria: [0] },
+ { title: "service", detail: "d", criteria: [1, 2] }
+ ]
+ }),
+ BINDING
+ );
+ expect(tasks.map((t) => t.title)).toEqual([
+ "migration",
+ "service",
+ "Remaining acceptance criteria"
+ ]);
+ expect(tasks.at(-1)?.criteria).toEqual([3]);
+ });
+
+ it("drops out-of-range criteria and junk entries", () => {
+ const tasks = parsePlanResult(
+ json({
+ tasks: [
+ { title: "ok", detail: "d", criteria: [0, 99, -1, 1, 2, 3] },
+ { detail: "no title" },
+ "garbage"
+ ]
+ }),
+ BINDING
+ );
+ expect(tasks).toHaveLength(1);
+ expect(tasks[0]?.criteria).toEqual([0, 1, 2, 3]);
+ });
+
+ it("degrades to one whole-binding task when the planner output is unusable", () => {
+ for (const text of ["no json here", json({ tasks: [] }), json({})]) {
+ const tasks = parsePlanResult(text, BINDING);
+ expect(tasks).toHaveLength(1);
+ expect(tasks[0]?.criteria).toEqual([0, 1, 2, 3]);
+ }
+ });
+});
+
+describe("buildPlan", () => {
+ it("skips the planner session entirely for loop-sized bindings (≤2 criteria)", () => {
+ let called = 0;
+ const tasks = buildPlan(
+ SMALL,
+ config,
+ deps(() => {
+ called++;
+ return { text: "", costUsd: 0, sessionId: "s" };
+ })
+ );
+ expect(called).toBe(0);
+ expect(tasks).toHaveLength(1);
+ });
+
+ it("never lets a planner crash kill the run — falls back to one task", () => {
+ const tasks = buildPlan(
+ BINDING,
+ config,
+ deps(() => {
+ throw new Error("claude failed to spawn");
+ })
+ );
+ expect(tasks).toHaveLength(1);
+ expect(tasks[0]?.criteria).toEqual([0, 1, 2, 3]);
+ });
+});
diff --git a/packages/harness/src/runner/plan.ts b/packages/harness/src/runner/plan.ts
new file mode 100644
index 0000000000..7049139878
--- /dev/null
+++ b/packages/harness/src/runner/plan.ts
@@ -0,0 +1,125 @@
+import type { Binding } from "../binding";
+import { groomingNotes, tryExtractJson } from "./prompts";
+import type { PlanTask, RunnerConfig, RunnerDeps } from "./types";
+
+/**
+ * Systematic chunking, owned by the harness — not by the groomer, not by the
+ * outer-loop model. A binding with more than a couple of criteria is decomposed
+ * into small, ordered, independently-committable tasks; each task is one
+ * doer-session-sized unit with its own judge review and its own checkpoint
+ * commit. Parsing is defensive: any planner failure degrades to a single
+ * whole-binding task (the pre-plan behavior), and criteria the planner missed
+ * are appended as a catch-all task so coverage is guaranteed by construction.
+ */
+
+/** One task covering the whole binding — the degenerate (and fallback) plan. */
+function wholeTask(binding: Binding): PlanTask {
+ return {
+ title: binding.title,
+ detail: "The complete work item (no decomposition).",
+ criteria: binding.acceptance.map((_, i) => i)
+ };
+}
+
+export function buildPlannerPrompt(binding: Binding): string {
+ return `You are the PLANNER in an unattended conductor loop. Decompose the work item into small, ordered tasks. There is NO human; never ask a question. Do NOT change any files — read the codebase as needed, then answer.
+
+Work item (${binding.kind}, risk ${binding.risk}): ${binding.title}
+
+Acceptance criteria:
+${binding.acceptance.map((c, i) => ` [${i}] ${c}`).join("\n")}
+${groomingNotes(binding)}
+Rules for the plan:
+- 2 to 6 tasks, in dependency order (schema/migration first, then services, then UI, then tests/polish).
+- Each task must be SMALL: completable by one focused coding session and reviewable by one short review session. One migration, one service function + test, one component — that scale.
+- Each task must be independently committable: after it lands, the branch builds and passes lint/typecheck on its own.
+- Each task lists the acceptance criterion indices it advances. Cover every index across the plan.
+
+End your reply with EXACTLY one fenced json block, no prose after it:
+\`\`\`json
+{
+ "tasks": [
+ { "title": "<short imperative title>", "detail": "<2-3 sentences: what to build and where>", "criteria": [<acceptance indices this task advances>] }
+ ]
+}
+\`\`\``;
+}
+
+const MAX_TASKS = 8;
+
+export function parsePlanResult(text: string, binding: Binding): PlanTask[] {
+ const raw = tryExtractJson<{ tasks?: unknown }>(text);
+ const list = Array.isArray(raw?.tasks) ? raw.tasks : [];
+ const valid = binding.acceptance.length;
+ const tasks: PlanTask[] = [];
+ for (const t of list.slice(0, MAX_TASKS)) {
+ if (typeof t !== "object" || t === null) continue;
+ const { title, detail, criteria } = t as Partial<PlanTask>;
+ if (typeof title !== "string" || title === "") continue;
+ tasks.push({
+ title,
+ detail: typeof detail === "string" ? detail : "",
+ criteria: Array.isArray(criteria)
+ ? criteria.filter(
+ (i): i is number =>
+ typeof i === "number" &&
+ Number.isInteger(i) &&
+ i >= 0 &&
+ i < valid
+ )
+ : []
+ });
+ }
+ // Planner produced nothing usable ⇒ degrade to the whole binding as one task.
+ if (tasks.length === 0) return [wholeTask(binding)];
+ // Coverage by construction: criteria the planner missed become a final task.
+ const covered = new Set(tasks.flatMap((t) => t.criteria));
+ const missed = binding.acceptance
+ .map((_, i) => i)
+ .filter((i) => !covered.has(i));
+ if (missed.length > 0) {
+ tasks.push({
+ title: "Remaining acceptance criteria",
+ detail: "Criteria not covered by the planned tasks.",
+ criteria: missed
+ });
+ }
+ return tasks;
+}
+
+/**
+ * Produce the task plan for a binding. Loop-sized bindings (≤2 criteria) skip
+ * the planner session entirely — deterministic, free. Anything larger gets one
+ * bounded planner session; its output is validated and coverage-completed.
+ */
+export function buildPlan(
+ binding: Binding,
+ config: RunnerConfig,
+ deps: RunnerDeps
+): PlanTask[] {
+ if (binding.acceptance.length <= 2) return [wholeTask(binding)];
+ try {
+ const res = deps.claude({
+ prompt: buildPlannerPrompt(binding),
+ cwd: config.cwd,
+ maxTurns: config.plannerMaxTurns,
+ maxBudgetUsd: config.plannerMaxBudgetUsd
+ });
+ const tasks = parsePlanResult(res.text, binding);
+ deps.log({
+ event: "plan",
+ tasks: tasks.map((t) => t.title),
+ cost: res.costUsd,
+ ...(res.stopReason ? { stopReason: res.stopReason } : {})
+ });
+ return tasks;
+ } catch (err) {
+ // A dead planner must never kill the run — fall back to the whole binding
+ // as a single task (the pre-plan behavior).
+ deps.log({
+ event: "plan:failed",
+ error: err instanceof Error ? err.message : String(err)
+ });
+ return [wholeTask(binding)];
+ }
+}
diff --git a/packages/harness/src/runner/pr.ts b/packages/harness/src/runner/pr.ts
index 09333d3131..67f0d6d9ce 100644
--- a/packages/harness/src/runner/pr.ts
+++ b/packages/harness/src/runner/pr.ts
@@ -5,7 +5,7 @@ import type { Binding } from "../binding";
import { hostedScreenshotPath, screenshotsDir } from "../layout";
import { readLedger } from "../ledger";
import { sq } from "./shell";
-import type { Shell } from "./types";
+import type { Shell, TaskStatus } from "./types";
/** Screenshot files the behavior gate captured for this loop, if any. */
function screenshots(dir: string): string[] {
@@ -139,12 +139,21 @@ export type PrFlags = {
unverified?: string[];
/** Product questions for the reviewer (disputed criteria, doer assumptions). */
questions?: string[];
+ /** The task plan and per-task outcome — rendered as a checklist. */
+ plan?: { title: string; status: TaskStatus }[];
/** Set when the loop ended WITHOUT meeting all criteria (plateau/blocked) but
- * kept, gate-green commits exist — salvage them as a draft PR rather than
- * losing the work with the worktree. */
+ * committed work exists — salvage it as a draft PR rather than losing the
+ * work with the worktree. */
partial?: { state: string; reason: string };
};
+const TASK_MARK: Record<TaskStatus, string> = {
+ done: "- [x]",
+ flagged: "- [x] ⚠️",
+ failed: "- [ ] ✗",
+ pending: "- [ ]"
+};
+
/**
* Push the loop branch and open a **gated** PR (never merged). The body carries
* the design rationale surface: acceptance checklist, embedded behavior-gate
@@ -187,7 +196,7 @@ export function openPr(
? [
`> [!WARNING]`,
`> **Partial work — the loop ended \`${flags.partial.state}\`:** ${flags.partial.reason}`,
- `> Every kept commit passed the floor gates and judge review; the remaining criteria are unfinished, not failing.`,
+ `> The ledger below records which commits passed gates and review. Remaining criteria are unfinished, not failing.`,
""
]
: []),
@@ -202,6 +211,16 @@ export function openPr(
"### Acceptance",
...binding.acceptance.map((c) => `- [${flags.partial ? " " : "x"}] ${c}`),
"",
+ ...(flags.plan && flags.plan.length > 0
+ ? [
+ "### Tasks",
+ ...flags.plan.map(
+ (t) =>
+ `${TASK_MARK[t.status]} ${t.title}${t.status === "flagged" ? " _(kept without judge review)_" : t.status === "failed" ? " _(attempts on rescue branch)_" : ""}`
+ ),
+ ""
+ ]
+ : []),
...(questions.length > 0
? ["### Open questions", ...questions.map((q) => `- ${q}`), ""]
: []),
diff --git a/packages/harness/src/runner/prompts.ts b/packages/harness/src/runner/prompts.ts
index 7de6b3ad93..005fd1eb5e 100644
--- a/packages/harness/src/runner/prompts.ts
+++ b/packages/harness/src/runner/prompts.ts
@@ -1,6 +1,32 @@
import type { Binding } from "../binding";
import type { LedgerEntry } from "../ledger";
-import type { DoerResult, JudgeResult } from "./types";
+import type { DoerResult, JudgeResult, PlanTask } from "./types";
+
+/** Task context threaded into the doer/judge prompts by the loop. */
+export type TaskContext = {
+ task: PlanTask;
+ /** 1-based position and plan size, for orientation ("task 2 of 5"). */
+ index: number;
+ total: number;
+ /** SHA at task start — the judge diffs `<sha>..HEAD` to see the task's work. */
+ startSha?: string;
+};
+
+function taskSection(binding: Binding, ctx: TaskContext | undefined): string {
+ if (!ctx) return "";
+ const criteria =
+ ctx.task.criteria.length > 0
+ ? ctx.task.criteria
+ .map((i) => ` [${i}] ${binding.acceptance[i] ?? "?"}`)
+ .join("\n")
+ : " (none mapped)";
+ return `
+YOUR CURRENT TASK (${ctx.index} of ${ctx.total} in the plan): ${ctx.task.title}
+${ctx.task.detail}
+This task advances these acceptance criteria (work on THESE only):
+${criteria}
+`;
+}
/** Pull the last fenced ```json block out of model text. Throws if none parses. */
export function extractJson<T>(text: string): T {
@@ -47,7 +73,8 @@ export function groomingNotes(binding: Binding): string {
*/
export function buildDoerPrompt(
binding: Binding,
- ledger: LedgerEntry[]
+ ledger: LedgerEntry[],
+ ctx?: TaskContext
): string {
return `You are the DOER in an unattended conductor loop. There is NO human watching — you may never ask a question; either make a change, or report \`blocked\`.
@@ -55,18 +82,23 @@ Work item (${binding.kind}, risk ${binding.risk}): ${binding.title}
Acceptance criteria (each is a definition of done):
${acceptanceList(binding)}
-${groomingNotes(binding)}
-Prior iterations:
+${groomingNotes(binding)}${taskSection(binding, ctx)}
+Prior iterations (fix forward — earlier attempts are already committed; improve on them, don't start over):
${ledgerSummary(ledger)}
Your job THIS iteration:
-- Make the SMALLEST change toward the weakest-covered acceptance criterion. Do not batch unrelated changes.
+- ${ctx ? "Complete YOUR CURRENT TASK above — nothing more. Other tasks in the plan are not your job this session." : "Make the SMALLEST change toward the weakest-covered acceptance criterion."} Do not batch unrelated changes.
- UI work: FIRST copy the nearest existing screen/component (precedent), don't design from concepts.
- ERP-domain logic (accounting, costing, tax, inventory valuation, RMAs): ground it in how real ERPs work; don't invent domain logic.
- Schema/migration changes: run \`pnpm run generate:types\` BEFORE any typecheck (stale types = false green).
- Module code: keep ONE \`<module>.service.ts\` and ONE \`<module>.models.ts\`; never scatter new ones.
- Correctness: write a test that FAILS on the bug/missing-feature and PASSES after your change. Report its exact command.
+Chunk your own work — you have a hard turn/budget cap:
+- If the task will not fit comfortably in this session, STOP EARLY at a COHERENT SLICE: code that compiles, is lint-clean, and is safe to commit as-is. Report what's left in \`remaining\` — the loop checkpoints your slice and gives a fresh session this context to continue.
+- A clean partial slice is SUCCESS; a complete-but-broken sprint to the buzzer is failure. Never race your limits, and never leave the tree half-edited at the end of your session.
+- Prior slices are already committed — build on them, don't redo them.
+
Questions vs blockers — questions belong to GROOMING, not to this loop:
- NEVER block on a question of interpretation, preference, or an ambiguous acceptance criterion. Choose the most reasonable interpretation (prefer matching existing app behavior/precedent) and record it in \`assumptions\` — it will be surfaced on the PR for a human to confirm.
- Reserve \`blocked\` for hard impossibilities: missing credentials/secrets, the work requires a destructive or production-side action, or the issue's premise contradicts the code so completely that ANY change would be a guess.
@@ -80,6 +112,7 @@ End your reply with EXACTLY one fenced json block, no prose after it:
"packages": ["@carbon/<pkg>", "..."],
"testCommand": "<command that fails before / passes after, or \\"\\">",
"touchedUI": <true if any user-facing UI changed, else false>,
+ "remaining": "<omit when the task is COMPLETE; otherwise one line: what a fresh session should do next>",
"assumptions": ["<interpretation you chose instead of asking>", "..."],
"blocked": "<omit unless truly impossible without a human; then explain why>"
}
@@ -90,19 +123,23 @@ End your reply with EXACTLY one fenced json block, no prose after it:
* The judge reviews the uncommitted working tree against acceptance + design
* rules. A SEPARATE session — never the doer grading itself.
*/
-export function buildJudgePrompt(binding: Binding): string {
- return `You are the JUDGE in an unattended conductor loop. Review the current UNCOMMITTED change against the acceptance criteria and Carbon's design rules. Be skeptical — do not rubber-stamp.
+export function buildJudgePrompt(binding: Binding, ctx?: TaskContext): string {
+ const inspect = ctx?.startSha
+ ? `Inspect the change yourself: run \`git diff ${ctx.startSha}..HEAD\` (the task's committed work) plus \`git status\` in the worktree.`
+ : "Inspect the change yourself: run `git diff` (and `git status`) in the worktree.";
+ return `You are the JUDGE in an unattended conductor loop. Review the ${ctx ? "current task's committed work" : "current UNCOMMITTED change"} against the acceptance criteria and Carbon's design rules. Be skeptical — do not rubber-stamp.
Work item (${binding.kind}, risk ${binding.risk}): ${binding.title}
Acceptance criteria:
${acceptanceList(binding)}
-${groomingNotes(binding)}
-Inspect the change yourself: run \`git diff\` (and \`git status\`) in the worktree. Check:
+${groomingNotes(binding)}${taskSection(binding, ctx)}
+${inspect} Check:
- Does the change actually advance the weakest criterion, with a real reproduce→fix→pass test?
- Does it follow Carbon conventions (module layout, RLS/migration rules, existing components over ad-hoc styles)?
- Is the scope minimal — no unrelated edits?
- For each acceptance criterion, is it now MET and provable?
+${ctx ? "- `approved` judges THIS task's work; `unmet` lists ALL acceptance indices still unsatisfied across the whole work item (later tasks will cover theirs — that's expected)." : ""}
Disputed criteria — do NOT hold the loop hostage to a wrong spec:
- If a criterion rests on a premise the code contradicts (the mechanism it describes does not exist), or hinges on a product decision no agent can make, put it in \`disputed\` with a one-line question for the human and leave it OUT of \`unmet\`. Iterating cannot resolve a product question — it goes back to the issue instead.
@@ -138,11 +175,14 @@ export function parseDoerResult(text: string): DoerResult {
(a): a is string => typeof a === "string" && a !== ""
)
: [];
+ const remaining =
+ typeof raw.remaining === "string" ? raw.remaining.trim() : "";
return {
change: raw.change ?? "(no summary)",
packages: Array.isArray(raw.packages) ? raw.packages : [],
testCommand: raw.testCommand ?? "",
touchedUI: raw.touchedUI === true,
+ ...(remaining ? { remaining } : {}),
...(assumptions.length > 0 ? { assumptions } : {}),
...(raw.blocked ? { blocked: raw.blocked } : {})
};
@@ -154,6 +194,7 @@ export function parseJudgeResult(text: string): JudgeResult {
return {
approved: false,
unmet: [],
+ verdictMissing: true,
feedback: "judge returned no JSON verdict"
};
const disputed = Array.isArray(raw.disputed)
diff --git a/packages/harness/src/runner/types.ts b/packages/harness/src/runner/types.ts
index e7b341b63f..dac9d6d0da 100644
--- a/packages/harness/src/runner/types.ts
+++ b/packages/harness/src/runner/types.ts
@@ -4,6 +4,21 @@ import type { Gate } from "../gates";
/** How a run ends. `shipped` = green committed state ready for a PR. */
export type TerminalState = "shipped" | "blocked" | "plateau" | "error";
+/**
+ * One unit of the harness-owned plan: small enough for one doer session to
+ * complete and one judge session to review, independently committable, and
+ * mapped to the acceptance criteria it advances.
+ */
+export type PlanTask = {
+ title: string;
+ detail: string;
+ /** Indices into `binding.acceptance` this task advances. */
+ criteria: number[];
+};
+
+/** Where a plan task ended up. `flagged` = kept without judge review. */
+export type TaskStatus = "done" | "flagged" | "failed" | "pending";
+
export type LoopOutcome = {
state: TerminalState;
iterations: number;
@@ -23,6 +38,8 @@ export type LoopOutcome = {
* grooming resolves them BEFORE the next dispatch.
*/
questions?: string[];
+ /** The task plan and where each task ended up — the PR renders this. */
+ plan?: { title: string; status: TaskStatus }[];
};
/**
@@ -38,6 +55,13 @@ export type DoerResult = {
testCommand: string;
/** True if the change touches UI / user-facing surface (needs the behavior gate). */
touchedUI: boolean;
+ /**
+ * Set when the doer chunked its own work: this session finished a coherent,
+ * committable SLICE of the task and this is what's left. The loop
+ * checkpoints the slice, skips the judge (nothing to approve yet), doesn't
+ * count it as a failed attempt, and gives the next session this context.
+ */
+ remaining?: string;
/**
* Interpretation calls the doer made instead of asking a human (ambiguous
* criterion, unstated default…). Kept assumptions surface on the PR as open
@@ -61,6 +85,14 @@ export type JudgeResult = {
* questions ride the PR/issue instead.
*/
disputed?: { index: number; question: string }[];
+ /**
+ * Set when the judge produced NO parseable verdict (capped session, garbled
+ * output). Absence of a verdict is not a rejection: the loop retries once,
+ * and if still missing, KEEPS gate-green work flagged for human review
+ * instead of silently reverting it — a missing verdict must never discard
+ * real doer work (issue #1031 lost ~$8.5 of correct migration work to this).
+ */
+ verdictMissing?: true;
feedback: string;
};
@@ -131,12 +163,15 @@ export type RunnerConfig = {
cwd: string;
/** Where to append the ledger (e.g. .ai/runs/<id>/ledger.jsonl). */
ledgerPath: string;
- /** Stop after this many consecutive iterations with no kept change. */
- plateauAfter: number;
- /** Hard ceiling on total iterations. */
+ /** Doer attempts per plan task before the task is failed (attempts are
+ * preserved on a rescue branch, never discarded). */
+ taskMaxAttempts: number;
+ /** Hard ceiling on total iterations across all tasks. */
maxIterations: number;
/** The floor gates to run each dirty iteration. Defaults to Carbon's FLOOR_GATES. */
gates?: Gate[];
+ plannerMaxTurns: number;
+ plannerMaxBudgetUsd: number;
doerMaxTurns: number;
doerMaxBudgetUsd: number;
judgeMaxTurns: number;
@@ -146,8 +181,10 @@ export type RunnerConfig = {
};
export const DEFAULT_CONFIG: Omit<RunnerConfig, "cwd" | "ledgerPath"> = {
- plateauAfter: 2,
- maxIterations: 8,
+ taskMaxAttempts: 3,
+ maxIterations: 16,
+ plannerMaxTurns: 25,
+ plannerMaxBudgetUsd: 2,
doerMaxTurns: 60,
doerMaxBudgetUsd: 5,
judgeMaxTurns: 30,
diff --git a/packages/harness/src/scripts/run-loop.ts b/packages/harness/src/scripts/run-loop.ts
index 02be274535..637f574b61 100644
--- a/packages/harness/src/scripts/run-loop.ts
+++ b/packages/harness/src/scripts/run-loop.ts
@@ -15,7 +15,8 @@ import { openPr } from "../runner/pr";
import { shell } from "../runner/shell";
import { DEFAULT_CONFIG, type RunnerConfig } from "../runner/types";
-// Usage: tsx src/scripts/run-loop.ts <binding.loop.md> [--cwd <worktree>] [--no-pr] [--doer-budget <usd>] [--judge-budget <usd>] [--judge-turns <n>]
+// Usage: tsx src/scripts/run-loop.ts <binding.loop.md> [--cwd <worktree>] [--no-pr]
+// [--doer-budget <usd>] [--judge-budget <usd>] [--judge-turns <n>]
//
// Milestone 1: run inside a worktree you already created (`crbn new` + `crbn up`)
// and pass it via --cwd. Drives one binding to a gated PR, fully unattended.
@@ -35,18 +36,15 @@ const cwd = resolve(
);
const noPr = argv.includes("--no-pr");
-// Optional budget/turn overrides (e.g. --doer-budget 10 for complex features, --judge-budget 5 for many criteria)
-const doerBudgetIdx = argv.indexOf("--doer-budget");
-const doerBudgetOverride =
- doerBudgetIdx >= 0 ? parseFloat(argv[doerBudgetIdx + 1] ?? "") : NaN;
-
-const judgeBudgetIdx = argv.indexOf("--judge-budget");
-const judgeBudgetOverride =
- judgeBudgetIdx >= 0 ? parseFloat(argv[judgeBudgetIdx + 1] ?? "") : NaN;
-
-const judgeTurnsIdx = argv.indexOf("--judge-turns");
-const judgeTurnsOverride =
- judgeTurnsIdx >= 0 ? parseInt(argv[judgeTurnsIdx + 1] ?? "", 10) : NaN;
+// Optional budget/turn overrides for per-dispatch tuning (#1063) — e.g.
+// --doer-budget 10 for complex features, --judge-budget 5 for many criteria.
+const numFlag = (name: string): number => {
+ const idx = argv.indexOf(name);
+ return idx >= 0 ? Number.parseFloat(argv[idx + 1] ?? "") : Number.NaN;
+};
+const doerBudgetOverride = numFlag("--doer-budget");
+const judgeBudgetOverride = numFlag("--judge-budget");
+const judgeTurnsOverride = numFlag("--judge-turns");
const bindingMd = readFileSync(resolve(bindingPath), "utf8");
const binding = parseBinding(bindingMd);
@@ -80,7 +78,7 @@ const config: RunnerConfig = {
? { judgeMaxBudgetUsd: judgeBudgetOverride }
: {}),
...(Number.isFinite(judgeTurnsOverride)
- ? { judgeMaxTurns: judgeTurnsOverride }
+ ? { judgeMaxTurns: Math.trunc(judgeTurnsOverride) }
: {})
};
@@ -92,22 +90,34 @@ const outcome = runLoop(binding, config, {
behaviorGate
});
-// Open a PR whenever there is kept, gate-green work — shipped runs always, and
-// non-shipped runs (plateau/blocked) as a SALVAGE draft. Kept commits already
-// passed every floor gate and judge review; discarding them with the worktree
-// wastes the spend. Unproven work goes up flagged, never silently dropped.
-const keptCommits = readLedger(ledgerPath).some((e) => e.decision === "keep");
-if (!noPr && (outcome.state === "shipped" || keptCommits)) {
- const url = openPr(binding, ledgerPath, shell, cwd, {
- ...(outcome.unverified ? { unverified: outcome.unverified } : {}),
- ...(outcome.questions ? { questions: outcome.questions } : {}),
- ...(outcome.state !== "shipped"
- ? { partial: { state: outcome.state, reason: outcome.reason } }
- : {})
- });
- outcome.prUrl = url;
- log({ event: "pr", url, partial: outcome.state !== "shipped" });
- console.log(`\nPR: ${url}`);
+// Open a PR whenever there is committed work — shipped runs always, and
+// non-shipped runs (plateau/blocked/error) as a SALVAGE draft. Checkpoint and
+// kept commits are already on the branch (and pushed); discarding them with
+// the worktree wastes the spend. Unproven work goes up flagged, never
+// silently dropped. Salvage failures (e.g. branch equals base after a full
+// rescue-reset) are logged, never fatal — the outcome still gets written.
+const committedWork = readLedger(ledgerPath).some(
+ (e) => e.decision === "keep" || e.decision === "checkpoint"
+);
+if (!noPr && (outcome.state === "shipped" || committedWork)) {
+ try {
+ const url = openPr(binding, ledgerPath, shell, cwd, {
+ ...(outcome.unverified ? { unverified: outcome.unverified } : {}),
+ ...(outcome.questions ? { questions: outcome.questions } : {}),
+ ...(outcome.plan ? { plan: outcome.plan } : {}),
+ ...(outcome.state !== "shipped"
+ ? { partial: { state: outcome.state, reason: outcome.reason } }
+ : {})
+ });
+ outcome.prUrl = url;
+ log({ event: "pr", url, partial: outcome.state !== "shipped" });
+ console.log(`\nPR: ${url}`);
+ } catch (err) {
+ log({
+ event: "pr:failed",
+ error: err instanceof Error ? err.message : String(err)
+ });
+ }
}
log({ event: "outcome", ...outcome });