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.

Outer loop: design + harness dispatch contract (#957)

Brad Barbin509611e4a9f3
diff --git a/.claude/skills/conductor/SKILL.md b/.claude/skills/conductor/SKILL.md
index 2eec6af655..4c101f5041 100644
--- a/.claude/skills/conductor/SKILL.md
+++ b/.claude/skills/conductor/SKILL.md
@@ -20,7 +20,7 @@ This is the execution layer of the loop system. The deterministic helpers live i
- *(This assumes the loop system — `@carbon/harness` + `@carbon/checks` — is on `main`. Until that merges, the gate tooling only exists on the loop-system branch, so base off that branch instead.)*
## 1. Bind the work item
-- If given a binding path (`llm/loops/<id>.loop.md`), read it. Otherwise write one from the request (see `llm/loops/README.md` for the format) and save it to `llm/loops/<id>.loop.md`.
+- If given a binding path, read it. Otherwise write one from the request (see `llm/loops/README.md` for the format) and save it to `llm/loops/runs/<id>/binding.loop.md` (run-loop also persists the binding there automatically).
- Parse it to validate the shape:
`pnpm --filter @carbon/harness exec tsx -e "import {parseBinding} from '@carbon/harness'; import {readFileSync} from 'node:fs'; console.log(JSON.stringify(parseBinding(readFileSync('<path>','utf8'))))"`
- The binding has `id`, `kind` (bug|feature|usability|copy), `title`, `risk`, and an `acceptance` list. **Each acceptance criterion is the definition of done** — you are not finished until each is satisfied and provable.
@@ -43,8 +43,8 @@ For each iteration:
3. **Judge — dispatch a separate review subagent** (NOT yourself) to check the diff against the acceptance criteria and the design rules. It may send work back. Do not grade your own homework.
-4. **Decide + ledger.** Keep the change iff **every gate is green — including the behavior gate (§2b) for UI work, with before/after screenshots proving the fix** — AND the judge approves; otherwise revert it. Append one entry to `llm/loops/<id>/ledger.jsonl`:
- `pnpm --filter @carbon/harness exec tsx -e "import {appendLedger} from '@carbon/harness'; appendLedger('llm/loops/<id>/ledger.jsonl', {iteration: <n>, change: '<summary>', gates: {<gate>: <bool>}, decision: '<keep|revert>', reason: '<why>', at: new Date().toISOString()})"`
+4. **Decide + ledger.** Keep the change iff **every gate is green — including the behavior gate (§2b) for UI work, with before/after screenshots proving the fix** — AND the judge approves; otherwise revert it. Append one entry to `llm/loops/runs/<id>/ledger.jsonl`:
+ `pnpm --filter @carbon/harness exec tsx -e "import {appendLedger} from '@carbon/harness'; appendLedger('llm/loops/runs/<id>/ledger.jsonl', {iteration: <n>, change: '<summary>', gates: {<gate>: <bool>}, decision: '<keep|revert>', reason: '<why>', at: new Date().toISOString()})"`
(The harness has no clock — you supply `at`.)
5. **Terminate?** If every acceptance criterion is met and provable → go to Finish. If you plateau (no progress across iterations) or the human stops → stop and report.
@@ -57,7 +57,7 @@ For each iteration:
- embed the **before/after screenshots** for any UI change,
- summarize the **ledger** (iterations, what was kept/reverted and why).
- **Surface every design decision for the human to approve / comment / improve** — design is never shipped silently.
-- **Loop artifacts stay out of source.** `llm/loops/` (bindings, ledger, screenshots) is gitignored *runtime* — never commit it to the working branch. The **ledger summary goes in the PR body**, and **before/after screenshots are embedded in the PR body** from a shared, non-merging **`loop-artifacts`** branch (under `llm/loops/<id>/screenshots/`, referenced by raw URL) — never committed to the product tree. (`@carbon/harness`'s `openPr` does this hosting automatically.)
+- **Loop artifacts stay out of source.** `llm/loops/runs/` (bindings, ledger, outcome, screenshots) is gitignored *runtime* — never commit it to the working branch. The **ledger summary goes in the PR body**, and **before/after screenshots are embedded in the PR body** from a shared, non-merging **`loop-artifacts`** branch (under `llm/loops/runs/<id>/screenshots/`, referenced by raw URL) — never committed to the product tree. (`@carbon/harness`'s `openPr` does this hosting automatically.)
## Guardrails (non-negotiable)
- **A UI/user-facing change is never done without passing visual e2e verification in the running app (§2b).** If the stack can't boot, the loop is BLOCKED — stop and surface, not "done."
diff --git a/.github/scripts/setup-agent-labels.sh b/.github/scripts/setup-agent-labels.sh
new file mode 100755
index 0000000000..0799057a3d
--- /dev/null
+++ b/.github/scripts/setup-agent-labels.sh
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+#
+# Create/update the agent:* labels the outer loop (the OpenClaw orchestrator,
+# acting as the `carbon-agent` machine user) drives. These are the GitHub-side
+# state machine for autonomous work — see llm/outer-loop/01-openclaw-plan.md §4.
+#
+# Idempotent: `gh label create --force` updates an existing label's color and
+# description instead of erroring, so this is safe to re-run.
+#
+# Usage:
+# .github/scripts/setup-agent-labels.sh [owner/repo]
+# Defaults to the current repo. Requires `gh` authenticated with issues:write.
+set -euo pipefail
+
+REPO="${1:-}"
+repo_arg=()
+[ -n "$REPO" ] && repo_arg=(--repo "$REPO")
+
+create() {
+ gh label create "$1" --color "$2" --description "$3" --force "${repo_arg[@]}"
+}
+
+# name color description
+create "agent:working" "1d76db" "carbon-agent holds the lease on this issue (a loop is in flight)"
+create "agent:needs-grooming" "fbca04" "Candidate for the agent groomer to flesh into a buildable spec"
+create "agent:groomed" "0e8a16" "Spec + acceptance criteria proposed by the agent; safe to assign to carbon-agent"
+create "agent:needs-decomposition" "d93f0b" "Epic-sized; the agent proposed a breakdown — needs a human to split"
+create "agent:blocked" "b60205" "The loop returned blocked/error, or binding synthesis refused — needs a human"
+
+echo "agent:* labels synced."
diff --git a/.github/workflows/agent-labels.yml b/.github/workflows/agent-labels.yml
new file mode 100644
index 0000000000..6a26142952
--- /dev/null
+++ b/.github/workflows/agent-labels.yml
@@ -0,0 +1,24 @@
+name: Agent Labels
+
+# Create/update the agent:* labels the outer-loop orchestrator drives.
+# Manual trigger only — run once from the Actions tab (or after editing the
+# label set in .github/scripts/setup-agent-labels.sh). Not on push, to avoid noise.
+on:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ issues: write
+
+jobs:
+ sync:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ fetch-depth: 1
+ show-progress: false
+ - name: Sync agent:* labels
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: bash .github/scripts/setup-agent-labels.sh
diff --git a/.gitignore b/.gitignore
index 26baa9a7cb..e1f1149723 100644
--- a/.gitignore
+++ b/.gitignore
@@ -68,7 +68,12 @@ apps/*/portless.json
packages/database/supabase/snippets/**
.pr-review
-# Loop run artifacts (conductor bindings, ledgers, screenshots) — runtime, not source.
+# Loop run artifacts (bindings, ledgers, outcomes, screenshots) — runtime, not source.
+# All per-run output lives under llm/loops/runs/; everything else in llm/ is docs.
# The ledger summary goes in the PR body; screenshots are hosted on the PR.
-llm/loops/*
-!llm/loops/README.md
+llm/loops/runs/
+
+# Outer-loop scratch (design plans, the box's operating prompt) — kept out of the
+# product tree; the design lives in PR history and the prompt lives on the OpenClaw box.
+llm/outer-loop/*
+!llm/outer-loop/README.md
diff --git a/llm/loops/README.md b/llm/loops/README.md
index 86084c84c8..ab91207e1f 100644
--- a/llm/loops/README.md
+++ b/llm/loops/README.md
@@ -1,9 +1,33 @@
# llm/loops — loop bindings + ledgers
-Home for the `build` conductor skill's work items.
+Home for the conductor loop's work items.
-- **Binding:** `llm/loops/<id>.loop.md` — one work item. YAML-ish frontmatter parsed by `@carbon/harness` `parseBinding` (no YAML lib; scalars + an `acceptance` list).
-- **Ledger:** `llm/loops/<id>/ledger.jsonl` — append-only record of each loop iteration (change, gate results, keep/revert, reason). Written by `@carbon/harness` `appendLedger`.
+## Layout
+
+- **`llm/loops/`** — committed docs only (this README; design docs live in siblings like `llm/outer-loop/`).
+- **`llm/loops/runs/<id>/`** — **all** runtime artifacts for one loop run. Gitignored wholesale (`llm/loops/runs/`), so runtime can never leak into git and docs are tracked by default. The harness owns every path here via `@carbon/harness`'s `layout.ts` — nothing should hardcode these strings.
+
+Per run:
+
+| File | Written by | What |
+|------|-----------|------|
+| `binding.loop.md` | run-loop | the binding the run was driven from (persisted for inspection / re-entry) |
+| `ledger.jsonl` | `appendLedger` | append-only per-iteration record (change, gates, keep/revert, reason) |
+| `run.log.jsonl` | run-loop | full event log |
+| `outcome.json` | run-loop | the final `LoopOutcome` (incl. `prUrl`) — the machine-readable result an external orchestrator reads instead of scraping stdout |
+| `screenshots/` | behavior gate | before/after captures (hosted on the `loop-artifacts` branch for the PR) |
+
+## Lifecycle / GC
+
+Finished runs accumulate; prune them with:
+
+```
+pnpm --filter @carbon/harness run gc -- [--cwd <dir>] [--keep-last <n>] [--max-age-days <n>]
+```
+
+(Script is named `gc`, not `prune` — `pnpm prune` is a built-in pnpm command.)
+
+`pruneRuns` (and `listRuns` / `readOutcome`) are exported from `@carbon/harness` for the outer-loop janitor to call. **Unfinished runs (no `outcome.json`) are never pruned** — they may be in flight.
## Binding format
diff --git a/llm/outer-loop/README.md b/llm/outer-loop/README.md
new file mode 100644
index 0000000000..4cf390e90a
--- /dev/null
+++ b/llm/outer-loop/README.md
@@ -0,0 +1,18 @@
+# llm/outer-loop
+
+Scratch space for the **outer loop** — the autonomous "agentic employee" that watches GitHub, dispatches the conductor inner loop, and shepherds gated PRs through review. It runs on **OpenClaw** (the runtime) with a **headless Claude Code agent** (`claude -p --dangerously-skip-permissions`) doing the reasoning — *not* in this repo.
+
+**This folder is gitignored except this README** (like `llm/loops/`). The design plans and the box's operating prompt are intentionally kept out of the product tree, matching the loop system's "code + skill = source of truth" convention:
+
+- **Design history** (the full plan, repo-change list, box setup): in the PR that introduced this — [crbnos/carbon#957](https://github.com/crbnos/carbon/pull/957) and its commits.
+- **Operating prompt** (the literal prompt the box runs each wake): lives on the **OpenClaw box**, where it runs.
+
+## The one-sentence interface
+
+**Assign a GitHub issue to `carbon-agent` → it builds it. Assign nothing → it grooms the backlog so there's good work ready to assign.** OpenClaw is just the runtime (heartbeat, webhooks, cron, channels, state, sandbox); Claude Code is the agent — the same `claude -p` the inner loop already uses.
+
+## What's actually in this repo (the functional contract the outer loop consumes)
+
+- **`@carbon/harness`** — `crbn up --run 'pnpm --filter @carbon/harness loop <binding> --cwd .'` drives a `Binding` to a gated PR and writes `llm/loops/runs/<id>/outcome.json` (`{ state, prUrl, reason }`). `openPr` is idempotent (PR-feedback re-entry on the same branch); optional `Binding.issue` → `Closes #<n>`. GC stale runs with `pnpm --filter @carbon/harness run gc`.
+- **`crbn down --volumes`** / **`crbn up --run … --volumes`** — prune the stack's Docker volumes on teardown (headless boxes don't leak volumes).
+- **`.github/scripts/setup-agent-labels.sh`** + the **Agent Labels** workflow — the `agent:*` labels the orchestrator drives (`working`, `needs-grooming`, `groomed`, `needs-decomposition`, `blocked`).
diff --git a/packages/dev/src/commands/down.ts b/packages/dev/src/commands/down.ts
index 8fb79f2856..720626d55b 100644
--- a/packages/dev/src/commands/down.ts
+++ b/packages/dev/src/commands/down.ts
@@ -13,27 +13,30 @@ import {
// silent: post-SIGINT path. clack tasks/spinner would EIO via setRawMode on
// the freshly-interrupted stdin; fall back to plain printf progress.
-export async function down(opts: { silent?: boolean } = {}) {
+// volumes: also drop the stack's Docker volumes (data is wiped) — for headless
+// dispatch teardown where leftover volumes would accumulate on a long-lived box.
+export async function down(opts: { silent?: boolean; volumes?: boolean } = {}) {
const root = await getWorktreeRoot();
const slug = resolveSlug(root);
const project = projectName(slug);
+ const withVolumes = opts.volumes ?? false;
// Refuse to tear down a stack that another worktree owns (same slug, different
// path). Passes for our own stack and when nothing is running.
await ensureSlugAvailable(slug, root);
if (opts.silent) {
- return runPlain(root, slug, project);
+ return runPlain(root, slug, project, withVolumes);
}
intro("Carbon · dev down");
await tasks([
{
- title: `Stopping ${project} (volumes preserved)`,
+ title: `Stopping ${project} (${withVolumes ? "removing volumes" : "volumes preserved"})`,
task: async (msg) => {
- msg("docker compose stop");
- await stopStack(root, slug, false);
- return "stack stopped";
+ msg(withVolumes ? "docker compose down -v" : "docker compose stop");
+ await stopStack(root, slug, withVolumes);
+ return withVolumes ? "stack stopped, volumes removed" : "stack stopped";
}
},
{
@@ -56,15 +59,22 @@ export async function down(opts: { silent?: boolean } = {}) {
outro("stopped");
}
-async function runPlain(root: string, slug: string, project: string) {
+async function runPlain(
+ root: string,
+ slug: string,
+ project: string,
+ withVolumes: boolean
+) {
const step = (msg: string) =>
process.stderr.write(`${pc.cyan("•")} ${msg}…\n`);
const done = (msg: string) =>
process.stderr.write(`${pc.green("✓")} ${msg}\n`);
- step(`stopping ${project} (volumes preserved)`);
- await stopStack(root, slug, false);
- done("stack stopped");
+ step(
+ `stopping ${project} (${withVolumes ? "removing volumes" : "volumes preserved"})`
+ );
+ await stopStack(root, slug, withVolumes);
+ done(withVolumes ? "stack stopped, volumes removed" : "stack stopped");
step("unregistering portless aliases");
const branch = await currentBranch(root);
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index b6f96675cf..6d4788e0af 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -78,6 +78,9 @@ type UpOpts = {
* `crbn up` exits with the command's exit code. No detached daemon to reap.
*/
run?: string;
+ /** With --run, also remove Docker volumes on teardown (headless: don't leak
+ * data volumes across dispatches on a long-lived box). */
+ volumes?: boolean;
};
type Ctx = {
@@ -209,7 +212,8 @@ export async function up(opts: UpOpts = {}) {
ctx.ports,
portless,
opts.run,
- stripeChild
+ stripeChild,
+ opts.volumes ?? false
);
return;
}
@@ -614,7 +618,8 @@ async function runAppsThenCommand(
ports: PortMap,
portless: boolean,
command: string,
- stripeChild?: ExecaChildProcess
+ stripeChild?: ExecaChildProcess,
+ cleanVolumes = false
) {
const controller = new AbortController();
const appsDone = spawnApps({
@@ -642,7 +647,7 @@ async function runAppsThenCommand(
controller.abort(); // stop the app supervisors
await appsDone;
killStripe(stripeChild);
- await down({ silent: true });
+ await down({ silent: true, volumes: cleanVolumes });
detach();
}
process.exitCode = exitCode;
diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.ts
index ddcbee1f00..46a4d329fd 100644
--- a/packages/dev/src/main.ts
+++ b/packages/dev/src/main.ts
@@ -57,6 +57,12 @@ const main = defineCommand({
type: "string",
description:
"Boot apps, wait until reachable, run this command, then tear the stack down (scopes the stack's lifetime to the command — for headless/CI use)"
+ },
+ volumes: {
+ type: "boolean",
+ default: false,
+ description:
+ "With --run, also remove Docker volumes on teardown (headless: don't leak data volumes across dispatches)"
}
},
run: ({ args }) =>
@@ -67,12 +73,20 @@ const main = defineCommand({
pull: args.pull === true,
borrow: args.borrow === true,
portless: args.portless !== false,
- run: typeof args.run === "string" ? args.run : undefined
+ run: typeof args.run === "string" ? args.run : undefined,
+ volumes: args.volumes === true
})
}),
down: defineCommand({
meta: { description: "Stop the compose stack (volumes preserved)" },
- run: () => down()
+ args: {
+ volumes: {
+ type: "boolean",
+ default: false,
+ description: "Also remove Docker volumes (the stack's data is wiped)"
+ }
+ },
+ run: ({ args }) => down({ volumes: args.volumes === true })
}),
reset: defineCommand({
meta: { description: "Wipe volumes + flush redis db, then `up`" },
diff --git a/packages/harness/package.json b/packages/harness/package.json
index c4a72e2824..4b57cbec0a 100644
--- a/packages/harness/package.json
+++ b/packages/harness/package.json
@@ -12,7 +12,8 @@
"test": "vitest run",
"typecheck": "tsgo --noEmit",
"gates": "tsx src/scripts/run-gates.ts",
- "loop": "tsx src/scripts/run-loop.ts"
+ "loop": "tsx src/scripts/run-loop.ts",
+ "gc": "tsx src/scripts/prune-runs.ts"
},
"devDependencies": {
"@carbon/config": "workspace:*",
diff --git a/packages/harness/src/binding.test.ts b/packages/harness/src/binding.test.ts
index 871d14a46d..517e6fa7fc 100644
--- a/packages/harness/src/binding.test.ts
+++ b/packages/harness/src/binding.test.ts
@@ -29,6 +29,16 @@ describe("parseBinding", () => {
expect(() => parseBinding("---\nkind: bug\n---")).toThrow(/id/);
});
+ it("parses an optional numeric issue, omits it when absent or non-numeric", () => {
+ expect(parseBinding(`${MD}`).issue).toBeUndefined();
+ expect(parseBinding("---\nid: x\nkind: bug\nissue: 450\n---").issue).toBe(
+ 450
+ );
+ expect(
+ parseBinding("---\nid: x\nkind: bug\nissue: not-a-number\n---").issue
+ ).toBeUndefined();
+ });
+
it("strips surrounding quotes from scalars and acceptance items", () => {
const b = parseBinding(
`---\nid: "q-1"\nkind: 'bug'\ntitle: "Fix: the thing"\nacceptance:\n- "centers at <640px"\n---`
diff --git a/packages/harness/src/binding.ts b/packages/harness/src/binding.ts
index de2c534f3b..5bdda59ae8 100644
--- a/packages/harness/src/binding.ts
+++ b/packages/harness/src/binding.ts
@@ -6,6 +6,9 @@ export type Binding = {
title: string;
risk: "low" | "med" | "high";
acceptance: string[];
+ /** GitHub issue this loop addresses. When set, the PR body gets `Closes #<n>`
+ * so merging auto-closes the issue (the outer-loop state machine). */
+ issue?: number;
};
const KINDS: LoopKind[] = ["bug", "feature", "usability", "copy"];
@@ -46,11 +49,16 @@ export function parseBinding(md: string): Binding {
if (!kind || !KINDS.includes(kind as LoopKind)) {
throw new Error(`Binding kind must be one of ${KINDS.join("|")}`);
}
+ const issue =
+ scalars.issue && /^\d+$/.test(scalars.issue)
+ ? Number(scalars.issue)
+ : undefined;
return {
id,
kind: kind as LoopKind,
title: scalars.title ?? "",
risk: (scalars.risk as Binding["risk"]) ?? "low",
- acceptance
+ acceptance,
+ ...(issue !== undefined ? { issue } : {})
};
}
diff --git a/packages/harness/src/index.ts b/packages/harness/src/index.ts
index 6e0d309e2b..80dab46e71 100644
--- a/packages/harness/src/index.ts
+++ b/packages/harness/src/index.ts
@@ -6,6 +6,17 @@ export {
type GateResult,
runGates
} from "./gates";
+export {
+ bindingPath,
+ hostedScreenshotPath,
+ LOOPS_DIR,
+ ledgerPath,
+ logPath,
+ outcomePath,
+ RUNS_DIR,
+ runDir,
+ screenshotsDir
+} from "./layout";
export { appendLedger, type LedgerEntry, readLedger } from "./ledger";
export {
behaviorGate,
@@ -34,3 +45,10 @@ export {
type Shell,
type TerminalState
} from "./runner/types";
+export {
+ listRuns,
+ type PrunePolicy,
+ pruneRuns,
+ type RunSummary,
+ readOutcome
+} from "./runs";
diff --git a/packages/harness/src/layout.ts b/packages/harness/src/layout.ts
new file mode 100644
index 0000000000..c44ce6d5a2
--- /dev/null
+++ b/packages/harness/src/layout.ts
@@ -0,0 +1,62 @@
+import { join, resolve } from "node:path";
+
+/**
+ * The single owner of the loop artifact layout. Every loop path is constructed
+ * here — nothing else in the harness should hardcode `llm/loops/...`.
+ *
+ * llm/loops/ committed docs (README, design) — TRACKED
+ * llm/loops/runs/<id>/ one loop run's ephemeral artifacts — GITIGNORED
+ * binding.loop.md the binding the run was driven from
+ * ledger.jsonl append-only per-iteration record
+ * run.log.jsonl full event log
+ * outcome.json the final LoopOutcome (machine-readable result)
+ * screenshots/ behavior-gate captures
+ *
+ * Keeping all runtime under one wholesale-ignored `runs/` dir is what keeps the
+ * `llm/` tree clean: docs are tracked by default, runtime can't leak into git,
+ * and `pruneRuns` (see runs.ts) has one place to GC.
+ */
+
+/** Repo-relative root for committed loop docs. */
+export const LOOPS_DIR = "llm/loops";
+/** Repo-relative root for ephemeral per-run artifacts (gitignored wholesale). */
+export const RUNS_DIR = "llm/loops/runs";
+
+/** Absolute dir holding one run's artifacts. */
+export function runDir(cwd: string, id: string): string {
+ return resolve(cwd, RUNS_DIR, id);
+}
+
+/** The binding the run was driven from (persisted for inspection / re-entry). */
+export function bindingPath(cwd: string, id: string): string {
+ return join(runDir(cwd, id), "binding.loop.md");
+}
+
+/** Append-only per-iteration ledger. */
+export function ledgerPath(cwd: string, id: string): string {
+ return join(runDir(cwd, id), "ledger.jsonl");
+}
+
+/** Full event log (every stdout line, mirrored to disk). */
+export function logPath(cwd: string, id: string): string {
+ return join(runDir(cwd, id), "run.log.jsonl");
+}
+
+/** The final LoopOutcome — what an external orchestrator reads instead of stdout. */
+export function outcomePath(cwd: string, id: string): string {
+ return join(runDir(cwd, id), "outcome.json");
+}
+
+/** Local dir the behavior gate captures screenshots into. */
+export function screenshotsDir(cwd: string, id: string): string {
+ return join(runDir(cwd, id), "screenshots");
+}
+
+/**
+ * Repo-relative path a screenshot is hosted at on the shared `loop-artifacts`
+ * branch (NOT the product tree). Mirrors the runtime layout so the hosted path
+ * is stable and unique per run.
+ */
+export function hostedScreenshotPath(id: string, name: string): string {
+ return `${RUNS_DIR}/${id}/screenshots/${name}`;
+}
diff --git a/packages/harness/src/runner/behavior.ts b/packages/harness/src/runner/behavior.ts
index 9ab61b8a9d..6440e0cd40 100644
--- a/packages/harness/src/runner/behavior.ts
+++ b/packages/harness/src/runner/behavior.ts
@@ -1,6 +1,7 @@
import { mkdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import type { Binding } from "../binding";
+import { screenshotsDir } from "../layout";
import { tryExtractJson } from "./prompts";
import { sq } from "./shell";
import type { BehaviorResult, RunnerConfig, RunnerDeps, Shell } from "./types";
@@ -191,7 +192,7 @@ export function behaviorGate(
}
const email = readEnvVar(cfg.cwd, "DEV_BYPASS_EMAIL") ?? "[email protected]";
- const shotDir = join(cfg.cwd, `llm/loops/${binding.id}/screenshots`);
+ const shotDir = screenshotsDir(cfg.cwd, binding.id);
mkdirSync(shotDir, { recursive: true });
// BEFORE (best-effort): show the bug with the fix reverted, then restore it.
diff --git a/packages/harness/src/runner/pr.test.ts b/packages/harness/src/runner/pr.test.ts
new file mode 100644
index 0000000000..0f04ce264c
--- /dev/null
+++ b/packages/harness/src/runner/pr.test.ts
@@ -0,0 +1,68 @@
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import type { Binding } from "../binding";
+import { openPr } from "./pr";
+import type { Shell } from "./types";
+
+const BINDING: Binding = {
+ id: "bug-x",
+ kind: "bug",
+ title: "Fix the thing",
+ risk: "low",
+ acceptance: ["it works"]
+};
+
+/** A fake Shell that returns a canned response per substring match, recording calls. */
+function fakeShell(
+ responses: Array<[string, { ok: boolean; output: string }]>
+): { shell: Shell; calls: string[] } {
+ const calls: string[] = [];
+ const shell: Shell = (cmd) => {
+ calls.push(cmd);
+ for (const [needle, res] of responses) if (cmd.includes(needle)) return res;
+ return { ok: true, output: "" };
+ };
+ return { shell, calls };
+}
+
+function ledgerWithOneEntry(): string {
+ const dir = mkdtempSync(join(tmpdir(), "pr-led-"));
+ const path = join(dir, "ledger.jsonl");
+ writeFileSync(
+ path,
+ `${JSON.stringify({ iteration: 1, change: "x", gates: {}, decision: "keep", reason: "r", at: "t" })}\n`
+ );
+ return path;
+}
+
+describe("openPr idempotency", () => {
+ it("creates a PR when none exists, returns its URL", () => {
+ const url = "https://github.com/o/r/pull/1";
+ const { shell, calls } = fakeShell([
+ ["git push", { ok: true, output: "" }],
+ ["gh pr view", { ok: false, output: "no pull requests found" }],
+ ["gh pr create", { ok: true, output: `${url}\n` }]
+ ]);
+ const cwd = mkdtempSync(join(tmpdir(), "pr-cwd-"));
+
+ expect(openPr(BINDING, ledgerWithOneEntry(), shell, cwd)).toBe(url);
+ expect(calls.some((c) => c.includes("gh pr create"))).toBe(true);
+ expect(calls.some((c) => c.includes("gh pr edit"))).toBe(false);
+ });
+
+ it("updates the existing PR on re-entry instead of erroring", () => {
+ const url = "https://github.com/o/r/pull/7";
+ const { shell, calls } = fakeShell([
+ ["git push", { ok: true, output: "" }],
+ ["gh pr view", { ok: true, output: `${url}\n` }],
+ ["gh pr edit", { ok: true, output: "" }]
+ ]);
+ const cwd = mkdtempSync(join(tmpdir(), "pr-cwd-"));
+
+ expect(openPr(BINDING, ledgerWithOneEntry(), shell, cwd)).toBe(url);
+ expect(calls.some((c) => c.includes("gh pr edit"))).toBe(true);
+ expect(calls.some((c) => c.includes("gh pr create"))).toBe(false);
+ });
+});
diff --git a/packages/harness/src/runner/pr.ts b/packages/harness/src/runner/pr.ts
index d4e5e225ba..4f288fc975 100644
--- a/packages/harness/src/runner/pr.ts
+++ b/packages/harness/src/runner/pr.ts
@@ -1,15 +1,15 @@
import { mkdtempSync, readdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { dirname, join } from "node:path";
+import { join } from "node:path";
import type { Binding } from "../binding";
+import { hostedScreenshotPath, screenshotsDir } from "../layout";
import { readLedger } from "../ledger";
import { sq } from "./shell";
import type { Shell } from "./types";
/** Screenshot files the behavior gate captured for this loop, if any. */
-function screenshots(ledgerPath: string): string[] {
+function screenshots(dir: string): string[] {
try {
- const dir = join(dirname(ledgerPath), "screenshots");
return readdirSync(dir)
.filter((f) => /\.(png|jpe?g|gif)$/i.test(f))
.map((f) => join(dir, f))
@@ -25,7 +25,7 @@ const ARTIFACTS_BRANCH = "loop-artifacts";
* Host the loop's screenshots so they render inline in the PR. Loop artifacts
* must not pollute the product tree (the conductor guardrail), so they live on
* ONE shared, non-merging `loop-artifacts` branch (gh-pages style) under
- * `llm/loops/<id>/screenshots/` — appended via a temp index on the branch tip so
+ * `llm/loops/runs/<id>/screenshots/` — appended via a temp index on the branch tip so
* earlier loops' artifacts survive. All git plumbing, no checkout / working-tree
* change. Returns raw URLs GitHub renders, or null on any failure so the caller
* falls back to listing paths rather than failing the PR.
@@ -59,7 +59,7 @@ function hostScreenshots(
const h = shell(`git hash-object -w ${sq(path)}`, { cwd });
if (!h.ok || !h.output.trim()) return null;
const name = path.split("/").pop() ?? "shot.png";
- const repoPath = `llm/loops/${id}/screenshots/${name}`;
+ const repoPath = hostedScreenshotPath(id, name);
const add = withIdx(
`git update-index --add --cacheinfo 100644,${h.output.trim()},${repoPath}`
);
@@ -144,7 +144,7 @@ export function openPr(
): string {
const ledger = readLedger(ledgerPath);
const kept = ledger.filter((e) => e.decision === "keep").length;
- const shots = screenshots(ledgerPath);
+ const shots = screenshots(screenshotsDir(cwd, binding.id));
const hosted =
shots.length > 0 ? hostScreenshots(binding.id, shots, shell, cwd) : null;
@@ -153,6 +153,7 @@ export function openPr(
"",
`**Kind:** ${binding.kind} · **Risk:** ${binding.risk}`,
"",
+ ...(binding.issue ? [`Closes #${binding.issue}`, ""] : []),
"### Acceptance",
...binding.acceptance.map((c) => `- [x] ${c}`),
"",
@@ -172,6 +173,15 @@ export function openPr(
const push = shell("git push -u origin HEAD", { cwd });
if (!push.ok) throw new Error(`git push failed: ${push.output}`);
+ // Idempotent: a PR may already exist for this branch (re-entry — addressing
+ // review feedback in the same worktree). Update its body and return it rather
+ // than failing on `gh pr create`. `gh pr view` errors (ok:false) when none.
+ const existing = shell("gh pr view --json url --jq .url", { cwd });
+ if (existing.ok && existing.output.trim().startsWith("http")) {
+ shell(`gh pr edit --body-file ${sq(bodyFile)}`, { cwd });
+ return firstHttpUrl(existing.output);
+ }
+
const title = `loop(${binding.id}): ${binding.title}`;
const baseArg = base ? ` --base ${sq(base)}` : "";
const r = shell(
@@ -180,11 +190,16 @@ export function openPr(
);
if (!r.ok) throw new Error(`gh pr create failed: ${r.output}`);
+ return firstHttpUrl(r.output);
+}
+
+/** The last `http…` line in command output (gh prints the URL last). */
+function firstHttpUrl(output: string): string {
return (
- r.output
+ output
.split("\n")
.map((l) => l.trim())
.filter((l) => l.startsWith("http"))
- .at(-1) ?? r.output.trim()
+ .at(-1) ?? output.trim()
);
}
diff --git a/packages/harness/src/runs.test.ts b/packages/harness/src/runs.test.ts
new file mode 100644
index 0000000000..79a20b9c0e
--- /dev/null
+++ b/packages/harness/src/runs.test.ts
@@ -0,0 +1,82 @@
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ utimesSync,
+ writeFileSync
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import { bindingPath, outcomePath, runDir } from "./layout";
+import { listRuns, pruneRuns, readOutcome } from "./runs";
+
+const NOW = 1_700_000_000_000;
+const DAY = 24 * 60 * 60 * 1000;
+
+function tmpCwd(): string {
+ return mkdtempSync(join(tmpdir(), "runs-"));
+}
+
+/** A finished run (has outcome.json) aged `ageDays` old. */
+function finishedRun(cwd: string, id: string, ageDays: number) {
+ mkdirSync(runDir(cwd, id), { recursive: true });
+ writeFileSync(
+ outcomePath(cwd, id),
+ JSON.stringify({ state: "shipped", iterations: 1, reason: "ok" })
+ );
+ const t = (NOW - ageDays * DAY) / 1000;
+ utimesSync(runDir(cwd, id), t, t);
+}
+
+describe("listRuns / readOutcome", () => {
+ it("lists run dirs newest-first and parses outcomes", () => {
+ const cwd = tmpCwd();
+ finishedRun(cwd, "old", 10);
+ finishedRun(cwd, "new", 1);
+
+ const runs = listRuns(cwd);
+ expect(runs.map((r) => r.id)).toEqual(["new", "old"]);
+ expect(readOutcome(cwd, "new")?.state).toBe("shipped");
+ expect(readOutcome(cwd, "missing")).toBeNull();
+ });
+
+ it("returns [] when there is no runs/ dir", () => {
+ expect(listRuns(tmpCwd())).toEqual([]);
+ });
+});
+
+describe("pruneRuns", () => {
+ it("removes old finished runs beyond keepLast, keeps recent + unfinished", () => {
+ const cwd = tmpCwd();
+ finishedRun(cwd, "fresh", 1);
+ finishedRun(cwd, "old-a", 30);
+ finishedRun(cwd, "old-b", 40);
+ // Unfinished: a binding but no outcome.json — must NEVER be pruned.
+ mkdirSync(runDir(cwd, "in-flight"), { recursive: true });
+ writeFileSync(bindingPath(cwd, "in-flight"), "---\nid: in-flight\n---\n");
+ utimesSync(
+ runDir(cwd, "in-flight"),
+ (NOW - 50 * DAY) / 1000,
+ (NOW - 50 * DAY) / 1000
+ );
+
+ const result = pruneRuns(cwd, { keepLast: 1, maxAgeDays: 7, now: NOW });
+
+ expect(result.removed.sort()).toEqual(["old-a", "old-b"]);
+ expect(result.kept).toBe(1);
+ expect(existsSync(runDir(cwd, "fresh"))).toBe(true);
+ expect(existsSync(runDir(cwd, "in-flight"))).toBe(true);
+ expect(existsSync(runDir(cwd, "old-a"))).toBe(false);
+ });
+
+ it("keepLast protects recent runs from age-based pruning", () => {
+ const cwd = tmpCwd();
+ finishedRun(cwd, "a", 100);
+ finishedRun(cwd, "b", 90);
+
+ const result = pruneRuns(cwd, { keepLast: 5, maxAgeDays: 1, now: NOW });
+ expect(result.removed).toEqual([]);
+ expect(result.kept).toBe(2);
+ });
+});
diff --git a/packages/harness/src/runs.ts b/packages/harness/src/runs.ts
new file mode 100644
index 0000000000..552337791e
--- /dev/null
+++ b/packages/harness/src/runs.ts
@@ -0,0 +1,89 @@
+import { readdirSync, readFileSync, rmSync, statSync } from "node:fs";
+import { join } from "node:path";
+import { outcomePath, RUNS_DIR, runDir } from "./layout";
+import type { LoopOutcome } from "./runner/types";
+
+/** A run on disk: its id, dir, parsed outcome (null if unfinished), and age. */
+export type RunSummary = {
+ id: string;
+ dir: string;
+ /** The final outcome, or null if the run never finished (no outcome.json). */
+ outcome: LoopOutcome | null;
+ mtimeMs: number;
+};
+
+/** Read one run's outcome.json, or null if it's absent / unparseable. */
+export function readOutcome(cwd: string, id: string): LoopOutcome | null {
+ try {
+ return JSON.parse(
+ readFileSync(outcomePath(cwd, id), "utf8")
+ ) as LoopOutcome;
+ } catch {
+ return null;
+ }
+}
+
+/** Every run dir under `llm/loops/runs/`, newest first. */
+export function listRuns(cwd: string): RunSummary[] {
+ let names: string[];
+ try {
+ names = readdirSync(join(cwd, RUNS_DIR));
+ } catch {
+ return []; // no runs/ dir yet
+ }
+ const runs: RunSummary[] = [];
+ for (const name of names) {
+ const dir = runDir(cwd, name);
+ try {
+ const stat = statSync(dir);
+ if (!stat.isDirectory()) continue;
+ runs.push({
+ id: name,
+ dir,
+ outcome: readOutcome(cwd, name),
+ mtimeMs: stat.mtimeMs
+ });
+ } catch {
+ /* not a readable dir — skip */
+ }
+ }
+ return runs.sort((a, b) => b.mtimeMs - a.mtimeMs);
+}
+
+export type PrunePolicy = {
+ /** Always keep this many most-recent FINISHED runs regardless of age. */
+ keepLast?: number;
+ /** Prune finished runs older than this many days. */
+ maxAgeDays?: number;
+ /** Clock injection for tests; defaults to Date.now(). */
+ now?: number;
+};
+
+/**
+ * GC finished run dirs. **Unfinished runs (no outcome.json) are never pruned** —
+ * they may be in-flight. This is the lever the OpenClaw janitor calls each
+ * heartbeat to keep the box's disk from filling with stale loop artifacts.
+ */
+export function pruneRuns(
+ cwd: string,
+ policy: PrunePolicy = {}
+): { removed: string[]; kept: number } {
+ const keepLast = policy.keepLast ?? 20;
+ const maxAgeDays = policy.maxAgeDays ?? 14;
+ const now = policy.now ?? Date.now();
+ const cutoff = now - maxAgeDays * 24 * 60 * 60 * 1000;
+
+ const finished = listRuns(cwd).filter((r) => r.outcome !== null); // newest first
+ const removed: string[] = [];
+ finished.forEach((r, i) => {
+ if (i < keepLast) return; // within the keep-last window
+ if (r.mtimeMs > cutoff) return; // still recent
+ try {
+ rmSync(r.dir, { recursive: true, force: true });
+ removed.push(r.id);
+ } catch {
+ /* best-effort */
+ }
+ });
+ return { removed, kept: finished.length - removed.length };
+}
diff --git a/packages/harness/src/scripts/prune-runs.ts b/packages/harness/src/scripts/prune-runs.ts
new file mode 100644
index 0000000000..2377814d92
--- /dev/null
+++ b/packages/harness/src/scripts/prune-runs.ts
@@ -0,0 +1,24 @@
+import { resolve } from "node:path";
+import { pruneRuns } from "../runs";
+
+// Usage: tsx src/scripts/prune-runs.ts [--cwd <dir>] [--keep-last <n>] [--max-age-days <n>]
+//
+// GC finished loop runs under llm/loops/runs/. Unfinished runs (no outcome.json)
+// are never touched. The OpenClaw janitor calls this each heartbeat to keep the
+// box's disk from filling with stale loop artifacts. Prints the result as JSON.
+const argv = process.argv.slice(2);
+const opt = (name: string): string | undefined => {
+ const i = argv.indexOf(name);
+ return i >= 0 ? argv[i + 1] : undefined;
+};
+
+const cwd = resolve(opt("--cwd") ?? process.cwd());
+const keepLast = opt("--keep-last");
+const maxAgeDays = opt("--max-age-days");
+
+const result = pruneRuns(cwd, {
+ keepLast: keepLast ? Number(keepLast) : undefined,
+ maxAgeDays: maxAgeDays ? Number(maxAgeDays) : undefined
+});
+
+console.log(JSON.stringify(result, null, 2));
diff --git a/packages/harness/src/scripts/run-loop.ts b/packages/harness/src/scripts/run-loop.ts
index 1581d94fae..1d917e8a53 100644
--- a/packages/harness/src/scripts/run-loop.ts
+++ b/packages/harness/src/scripts/run-loop.ts
@@ -1,6 +1,12 @@
-import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
-import { dirname, resolve } from "node:path";
+import {
+ appendFileSync,
+ mkdirSync,
+ readFileSync,
+ writeFileSync
+} from "node:fs";
+import { resolve } from "node:path";
import { parseBinding } from "../binding";
+import * as layout from "../layout";
import { behaviorGate } from "../runner/behavior";
import { claude } from "../runner/claude";
import { runLoop } from "../runner/loop";
@@ -28,10 +34,16 @@ const cwd = resolve(
);
const noPr = argv.includes("--no-pr");
-const binding = parseBinding(readFileSync(resolve(bindingPath), "utf8"));
-const ledgerPath = resolve(cwd, `llm/loops/${binding.id}/ledger.jsonl`);
-const logPath = resolve(cwd, `llm/loops/${binding.id}/run.log.jsonl`);
-mkdirSync(dirname(logPath), { recursive: true });
+const bindingMd = readFileSync(resolve(bindingPath), "utf8");
+const binding = parseBinding(bindingMd);
+
+// All artifacts live under one gitignored, harness-owned run dir (see layout.ts).
+mkdirSync(layout.runDir(cwd, binding.id), { recursive: true });
+// Persist the binding so the run is self-describing (inspection / re-entry).
+writeFileSync(layout.bindingPath(cwd, binding.id), bindingMd);
+
+const ledgerPath = layout.ledgerPath(cwd, binding.id);
+const logPath = layout.logPath(cwd, binding.id);
const log = (event: Record<string, unknown>) => {
const line = JSON.stringify({ at: new Date().toISOString(), ...event });
@@ -52,12 +64,19 @@ const outcome = runLoop(binding, config, {
log,
behaviorGate
});
-log({ event: "outcome", ...outcome });
if (outcome.state === "shipped" && !noPr) {
const url = openPr(binding, ledgerPath, shell, cwd);
+ outcome.prUrl = url;
log({ event: "pr", url });
console.log(`\nPR: ${url}`);
}
+log({ event: "outcome", ...outcome });
+// Structured result an external orchestrator reads instead of scraping stdout.
+writeFileSync(
+ layout.outcomePath(cwd, binding.id),
+ `${JSON.stringify(outcome, null, 2)}\n`
+);
+
process.exit(outcome.state === "shipped" ? 0 : 1);