Metadata-Version: 2.5
Name: claw-forge
Version: 1.59.0
Summary: Multi-provider autonomous coding agent harness with API rotation pool
Project-URL: Homepage, https://github.com/clawinfra/claw-forge
Project-URL: Repository, https://github.com/clawinfra/claw-forge
Project-URL: Issues, https://github.com/clawinfra/claw-forge/issues
Author-email: ClawInfra <alex.chen31337@gmail.com>
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: agent,ai,claude,coding,llm,multi-provider
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Code Generators
Requires-Python: >=3.11
Requires-Dist: aiosqlite<1,>=0.20
Requires-Dist: anthropic<1,>=0.40
Requires-Dist: anyio>=4.14.2
Requires-Dist: claude-agent-sdk<1,>=0.2.157
Requires-Dist: cryptography>=50.0.0
Requires-Dist: fastapi<1,>=0.115
Requires-Dist: httpx<1,>=0.27
Requires-Dist: idna>=3.15
Requires-Dist: openai<2,>=1.50
Requires-Dist: packaging>=23
Requires-Dist: pyasn1>=0.6.4
Requires-Dist: pydantic-settings<3,>=2
Requires-Dist: pydantic<3,>=2
Requires-Dist: pygments>=2.20.0
Requires-Dist: pyjwt>=2.14.0
Requires-Dist: python-multipart>=0.0.27
Requires-Dist: pyyaml<7,>=6
Requires-Dist: requests>=2.33.0
Requires-Dist: rich<14,>=13
Requires-Dist: sqlalchemy[asyncio]<3,>=2
Requires-Dist: sse-starlette<3,>=2
Requires-Dist: starlette<2,>=1.0.1
Requires-Dist: typer<1,>=0.16
Requires-Dist: urllib3>=2.8.0
Requires-Dist: uvicorn[standard]<1,>=0.30
Requires-Dist: websockets<14,>=12
Provides-Extra: all-providers
Requires-Dist: anthropic[bedrock]<1,>=0.40; extra == 'all-providers'
Requires-Dist: anthropic[vertex]<1,>=0.40; extra == 'all-providers'
Requires-Dist: azure-identity<2,>=1.17; extra == 'all-providers'
Requires-Dist: boto3<2,>=1.35; extra == 'all-providers'
Requires-Dist: google-auth<3,>=2; extra == 'all-providers'
Requires-Dist: openai<2,>=1.50; extra == 'all-providers'
Provides-Extra: azure
Requires-Dist: azure-identity<2,>=1.17; extra == 'azure'
Requires-Dist: openai<2,>=1.50; extra == 'azure'
Provides-Extra: bedrock
Requires-Dist: anthropic[bedrock]<1,>=0.40; extra == 'bedrock'
Requires-Dist: boto3<2,>=1.35; extra == 'bedrock'
Provides-Extra: dev
Requires-Dist: click>=8.1; extra == 'dev'
Requires-Dist: mypy<2,>=1.11; extra == 'dev'
Requires-Dist: playwright<2,>=1.40; extra == 'dev'
Requires-Dist: pytest-asyncio<2,>=1; extra == 'dev'
Requires-Dist: pytest-cov<8,>=7; extra == 'dev'
Requires-Dist: pytest<10,>=9; extra == 'dev'
Requires-Dist: ruff<1,>=0.6; extra == 'dev'
Requires-Dist: types-pyyaml<7,>=6; extra == 'dev'
Provides-Extra: vertex
Requires-Dist: anthropic[vertex]<1,>=0.40; extra == 'vertex'
Requires-Dist: google-auth<3,>=2; extra == 'vertex'
Description-Content-Type: text/markdown

<p align="center">
  <img src="docs/banner.png" width="760" alt="claw-forge — autonomous coding agents, in parallel; one trunk, many branches">
</p>

# claw-forge

**Autonomous coding agent harness for serious Python projects.**

Multi-provider API rotation · Claude Agent SDK core · 21 pre-installed skills · Pure asyncio · Zero Node.js

[![CI](https://github.com/clawinfra/claw-forge/actions/workflows/ci.yml/badge.svg)](https://github.com/clawinfra/claw-forge/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/claw-forge)](https://pypi.org/project/claw-forge/)
[![Python](https://img.shields.io/pypi/pyversions/claw-forge)](https://pypi.org/project/claw-forge/)
[![Coverage](https://img.shields.io/badge/coverage-%E2%89%A594%25-brightgreen)](https://github.com/clawinfra/claw-forge/actions)
[![Mypy](https://img.shields.io/badge/mypy-clean-brightgreen)](https://github.com/clawinfra/claw-forge/actions)
[![ClawHub](https://img.shields.io/badge/clawhub-claw--forge--cli-blue)](https://clawhub.com/skills/claw-forge-cli)
[![Benchmark](https://img.shields.io/badge/claw--forge--bench-Config%20E%20100%25%20%28unreproduced%29-gold)](https://github.com/clawinfra/claw-forge-bench)

---

## What it does

claw-forge runs autonomous coding agents that implement features, fix bugs, write tests, and review code — in parallel, across multiple AI providers, with live progress tracked in a Kanban UI.

It is built on the [Claude Agent SDK](https://pypi.org/project/claude-agent-sdk/) as its execution engine, with a provider pool layer on top for API key rotation, circuit breaking, and cost tracking.

---

## 📖 New here? Read the Handbook

**[The Claw Forge Handbook](handbook/README.md)** — a book for humans, in English and
简体中文, covering everything from your first run to production fleets.

| | |
|---|---|
| 🇬🇧 **English** | **[handbook/en/index.md](handbook/en/index.md)** |
| 🇨🇳 **简体中文** | **[handbook/zh/index.md](handbook/zh/index.md)** |

Its reference chapters are regenerated from the source code on every build and
checked in CI, so they describe the version you actually installed. If this
README and the handbook ever disagree, **believe the handbook** — it is the one
with a test.


---

## Quick Start

```bash
# 1. Install
pip install --pre claw-forge   # or: uv tool install claw-forge --prerelease allow
# Already installed? claw-forge prints a one-line notice when a newer release
# is available, and `claw-forge upgrade` installs it.

# 2. Bootstrap your project (scaffolds .claude/, CLAUDE.md, config, and app_spec.example.xml)
mkdir my-api && cd my-api
claw-forge init
# Output:
# ✓ Created claw-forge.yaml   (edit providers/API keys)
# ✓ Created .env.example      (copy to .env and fill keys)
# ✓ Created .claude/ with settings.json
# ✓ Scaffolded 14 slash commands → .claude/commands/
# ✓ Scaffolded 4 workflow skills → .claude/skills/
# ✓ Created app_spec.example.xml  (XML format reference)
# ✓ Created bug_spec.example.xml  (reference format for a bug spec)

# 3. Add your API key
cp .env.example .env
echo "ANTHROPIC_API_KEY=sk-ant-..." >> .env

# 4. Create your spec — three options:
#   Option A: Open Claude Code in this dir and run /create-spec
#   Option B: Paste your PRD into Claude with this prompt:
#     "Convert this PRD to claw-forge XML. Use app_spec.example.xml as the template.
#      Write the result to app_spec.txt."
#   Option C (non-interactive): resolve the decisions first, then synthesize
#     claw-forge brief init --tier standard
#     claw-forge brief extract docs/prd.md
#     /create-spec   # sees spec_brief.yaml → asks nothing it already answers

# 5. Validate spec quality (structural + shape + LLM checks)
#    Strict shape validation is on by default since v0.8.46
#    Pass --soft-shape during migration on-ramp to keep promotable
#    Layer 4 warnings at WARNING severity.
claw-forge validate-spec app_spec.txt

# 6. Parse spec → feature DAG. Offline and deterministic: no model call, no API key.
claw-forge plan app_spec.txt
# Output:
# ✅ Spec parsed: my-api
# ┌──────────────────────┬───────┐
# │ Authentication       │    8  │
# │ Task Management      │   22  │
# │ Total                │   30  │
# └──────────────────────┴───────┘
# Dependency waves: 3
# Estimated run time: at least ~12 minutes (at concurrency=5) — a floor, not a forecast
# Next steps: claw-forge run --project . --concurrency 5

# 6. Run agents
claw-forge run --concurrency 5

# 7. Open the Kanban board
claw-forge ui
```

### Claude Code routes through claw-forge automatically

`claw-forge init` also installs four routing skills into `.claude/skills/`:
`claw-forge-feature`, `claw-forge-bug`, `claw-forge-ops`, and
`claw-forge-verify`. Once they're installed, a Claude Code session working in
this project recognizes feature and bug work on its own — "add a settings
page" or "fix this failing test" — and routes it through the spec → validate →
plan → run pipeline instead of editing code by hand, so parallel work stays
safe under the file-claim locks and merge-gating described below.
`claw-forge-verify` is the follow-up: after a run it checks each user journey
of the finished app in a real browser and turns failures into bug specs.

It always asks before running `claw-forge run` — a run spawns parallel
agents, writes to git, and consumes provider tokens for potentially hours, so
the skills report what would be dispatched and wait for an explicit yes.
Already-scaffolded projects pick these up via `claw-forge init --refresh`.

---

---

## Writing a Project Spec

The spec is the single input that drives everything. The initializer agent reads it, breaks it
into atomic tasks, infers dependencies, and creates an execution plan. **The quality of your
spec directly determines the quality of what gets built.**

claw-forge supports **two spec formats**:

| Format | When to use | Command |
|--------|-------------|---------|
| Plain text (`app_spec.txt`) | Quick greenfield projects | `claw-forge plan app_spec.txt` |
| XML (`app_spec.xml`) | Richer greenfield specs with phases, DB schema, API summary | `claw-forge plan app_spec.xml` |
| Brownfield XML (`additions_spec.xml`) | Adding features to an existing codebase | `claw-forge plan additions_spec.xml` |

The `/create-spec` slash command generates whichever format is appropriate — it **auto-detects**
whether you're in a greenfield or brownfield project and runs the matching conversational flow.

### Ways to create a spec

**Option 1 — Write it yourself** (best control)

```
Project: my-api
Stack:   Python 3.12, FastAPI, SQLAlchemy, pytest

Features:

1. User authentication
   Description: JWT-based register/login/logout using bcrypt; access tokens expire in 1h, refresh tokens in 7d; use python-jose for JWT and passlib for bcrypt.
   - POST /auth/register creates user, returns 201 with user_id
   - POST /auth/login returns {access_token, refresh_token, expires_in}
   - POST /auth/refresh exchanges refresh_token for new access_token
   - POST /auth/logout invalidates the refresh token
   - Passwords hashed with bcrypt (cost factor 12)
   - 15 unit tests, all passing

2. Task CRUD
   Description: Full CRUD for tasks with title, description, status (todo/in_progress/done), priority (1–5), due_date, and tags.
   - POST /tasks — create, returns 201
   - GET /tasks  — list with pagination (?page=1&per_page=20)
   - PATCH /tasks/{id} — partial update
   - DELETE /tasks/{id} — soft delete (sets deleted_at)
   - All endpoints require valid JWT (401 if missing)
   - Users can only access their own tasks (403 otherwise)
   Depends on: 1

3. Integration test suite
   Description: End-to-end API tests using pytest + httpx AsyncClient, against in-memory SQLite with no external dependencies.
   - Coverage ≥ 90% across all modules
   - Tests cover auth flow, CRUD, and error cases
   - All tests pass: pytest tests/ -v
   Depends on: 1, 2
```

Each numbered item is one task. The `- ` bullets under it are that task's steps — write them as
the acceptance criteria. Keep `Description:` on one line: a wrapped second line is dropped. A
line that is only a word and a colon (`Acceptance criteria:`) is read as a *section header*, not
a field: every bullet under it would become its own task and the `Depends on:` line after it
would be lost.

**Option 2 — XML spec** (recommended for complex projects)

XML gives you richer structure: implementation phases, DB schema, API endpoint summary, design
system, and success criteria. Each `<feature>` becomes one task in the DAG.

```xml
<!-- app_spec.xml -->
<project_specification>
  <project_name>my-api</project_name>
  <overview>A REST API for task management with JWT auth.</overview>
  <technology_stack>Python 3.12, FastAPI, SQLAlchemy, PostgreSQL, pytest</technology_stack>

  <core_features>
    <category name="Authentication">
      <feature index="1" shape="plugin" plugin="auth">
        <description>User can register with email and password</description>
      </feature>
      <feature index="2" shape="plugin" plugin="auth">
        <description>System validates email format and enforces password strength</description>
      </feature>
      <feature index="3" shape="plugin" plugin="auth">
        <description>User can log in and receive JWT access + refresh tokens</description>
      </feature>
    </category>
    <category name="Tasks">
      <feature index="4" shape="plugin" plugin="tasks">
        <description>User can create tasks with title, description, status, and priority</description>
      </feature>
      <feature index="5" shape="plugin" plugin="tasks">
        <description>User can list their tasks with pagination</description>
      </feature>
    </category>
    <category name="API Layer">
      <feature index="6" shape="core"
               touches_files="src/api/middleware/jwt_auth.py">
        <description>All endpoints validate JWT and return 401 on missing/expired tokens</description>
      </feature>
    </category>
  </core_features>

  <database_schema>
    Users: id, email, password_hash, created_at
    Tasks: id, owner_id, title, description, status, priority, created_at
  </database_schema>

  <implementation_steps>
    <phase name="Auth">User registration, login, JWT tokens</phase>
    <phase name="Tasks">Task CRUD endpoints</phase>
    <phase name="Tests">Integration test suite, coverage ≥ 90%</phase>
  </implementation_steps>

  <success_criteria>
    All endpoints tested, coverage ≥ 90%, ruff + mypy clean
  </success_criteria>
</project_specification>
```

```bash
claw-forge plan app_spec.xml
```

Use `app_spec.example.xml` as your starting point — `claw-forge init` copies it into your project automatically.

**Stack layouts** — by default `plugin="auth"` expands to `src/plugins/auth/**` (single-package layout). For stacks with their own workspace conventions — pnpm/turbo monorepos with a decoupled UI and API, uv workspaces, Go services — declare a `<layout>` and plugin footprints expand into that stack's directories instead (one glob per root: a UI/API feature is a single vertical slice spanning `apps/web/src/features/auth/**` **and** `apps/api/src/modules/auth/**`). Polyglot apps (Python API + TS web) compose per-subtree zones plus a regenerated API-client contract:

```xml
<layout profile="pnpm-monorepo"/>                    <!-- TS full-stack monorepo -->

<layout>                                             <!-- or: Python API + TS web -->
  <zone root="apps/api" profile="uv-workspace"/>
  <zone root="apps/web" profile="pnpm-single-app"/>
  <contract path="packages/api-client/**" regen="pnpm --filter api-client generate"/>
</layout>
```

Built-in profiles: `single-package` (default) · `pnpm-monorepo` · `pnpm-single-app` · `uv-workspace` · `go-service` · `maven-single-module`. Each profile also teaches the harness the stack's collision seams (turbo.json, workspace manifests, module loaders) — validated at plan time, auto-resolved or serialized at merge time, and explained to every agent in its prompt. See `docs/commands.md → claw-forge plan → Stack layout`.

**Option 3 — Brownfield XML spec** (adding features to an existing project)

When you want to add a set of related features to an existing codebase, use
`additions_spec.xml`. The `mode="brownfield"` attribute tells claw-forge to load
`brownfield_manifest.json` and inject existing conventions into agent context.

```xml
<!-- additions_spec.xml -->
<project_specification mode="brownfield">
  <project_name>my-api — Stripe Integration</project_name>
  <addition_summary>Add Stripe payment processing to the existing FastAPI app.</addition_summary>

  <existing_context>
    <!-- Auto-populated by /create-spec when brownfield_manifest.json exists -->
    <stack>Python / FastAPI / PostgreSQL</stack>
    <test_baseline>47 tests passing, 87% coverage</test_baseline>
    <conventions>snake_case, async handlers, pydantic v2 models</conventions>
  </existing_context>

  <features_to_add>
    <category name="Payments">
      <feature index="1" shape="plugin" plugin="payments">
        <description>User can add a payment method via Stripe Elements</description>
      </feature>
      <feature index="2" shape="plugin" plugin="payments" depends_on="1">
        <description>System charges stored payment method on subscription creation</description>
      </feature>
      <feature index="3" shape="plugin" plugin="payments">
        <description>Admin can issue refunds from the dashboard</description>
      </feature>
    </category>
    <category name="Cross-cutting">
      <feature index="4" shape="core"
               touches_files="src/core/db/models/user.py">
        <description>Extend User model with stripe_customer_id field</description>
      </feature>
    </category>
  </features_to_add>

  <integration_points>
    Extends User model with stripe_customer_id field
    Adds /payments router alongside existing /auth and /tasks routers
  </integration_points>

  <constraints>
    Must not modify existing auth flow
    All 47 existing tests must stay green
    Follow existing async handler pattern in routers/
  </constraints>

  <implementation_steps>
    <phase name="Stripe Setup">Stripe client, webhook handler, config</phase>
    <phase name="Payment Methods">Add/remove cards, default card</phase>
    <phase name="Subscriptions">Create, cancel, webhook events</phase>
  </implementation_steps>
</project_specification>
```

```bash
claw-forge validate-spec additions_spec.xml --project-root .
claw-forge plan additions_spec.xml
claw-forge run --concurrency 3
```

Use `templates/app_spec.brownfield.template.xml` as a starting point.

**Option 4 — Interactive with `/create-spec`** (easiest)

Open Claude Code in your project directory and type `/create-spec`. It picks one of **three
modes**, checked in this order:

| Mode | Selected when | Behavior | Outputs |
|---|---|---|---|
| **Brief-Driven** (non-interactive) | `spec_brief.yaml` exists | Resolves every judgment call from the brief and asks nothing it already answers | `app_spec.txt` + `claw-forge.yaml` + `spec_decisions.jsonl` |
| **Greenfield** | no brief, no `brownfield_manifest.json` | Conversational: project name, stack, features, DB schema, API endpoints | `app_spec.txt` (XML format) + `claw-forge.yaml` |
| **Brownfield** | no brief, `brownfield_manifest.json` exists | Pre-populates `<existing_context>` from the manifest, asks what to add and what constraints apply | `additions_spec.xml` |

```bash
# In Claude Code (greenfield — new project):
/create-spec

# In Claude Code (brownfield — manifest present):
/create-spec           # detects manifest → runs brownfield flow automatically

# Non-interactive, from a decision record:
claw-forge brief init --tier standard
/create-spec           # detects spec_brief.yaml → Brief-Driven Mode
```

**No brief means nothing changes.** Without `spec_brief.yaml` on disk, `/create-spec` runs
every interactive phase exactly as it always has. This back-compat floor mirrors `<layout>`:
a spec that declares none gets the default layout and byte-identical legacy behavior.

**Option 5 — From an existing doc**

Paste a PRD, Notion export, or detailed README into Claude and ask:

> "Convert this into a claw-forge `app_spec.txt`. Break each requirement into a concrete feature with acceptance criteria and `Depends on:` links."

**Option 6 — Import from BMAD / Linear / Jira** (automated)

If your team already has stories in a 3rd-party tool, `claw-forge import` converts them to
`app_spec.txt` (or `additions_spec.xml` for brownfield projects) automatically — no manual
rewriting.

```bash
# Import from a BMAD workspace (detects prd.md + epic-* structure)
claw-forge import ./docs/prd --project my-api

# Import from a Linear JSON export
claw-forge import linear-export.json --project my-api

# Import from a Jira XML/CSV export
claw-forge import jira-export.xml --project my-api
```

Supported formats: **BMAD** (`prd.md` + `docs/stories/` layout), **Linear** (JSON issues
export), **Jira** (XML RSS or CSV export), **Generic** (any Markdown with `#`/`##`/`###`
headings). The `/import-spec` slash command runs the same pipeline interactively with
section-by-section review before writing the file.

### The spec brief — resolve decisions before synthesis

`/create-spec` conflates two different jobs: **acquisition** (getting intent out of you) and
**resolution** (settling every decision the synthesizer needs). The brief splits them, so spec
authoring can follow the rule the rest of the harness already follows — *a judgment call must
never halt an unattended run; default conservatively and record it.*

`spec_brief.yaml` is a typed decision record. It holds **decisions, never content**: competency
questions, constraints, stack, and policies live in the brief; feature bullets live in the spec.

```bash
# 1. Draft it from the filesystem alone — deterministic, offline, no API key
claw-forge brief init --tier standard --name my-api --domain saas-b2b

# 2. Raise its confidence from documents you already have
claw-forge brief extract docs/prd.md docs/architecture.md

# 3. Validate the brief itself, before it becomes 300 lines of spec
claw-forge brief check

# 4. See only what a human still has to confirm
claw-forge brief gate

# 5. Synthesize — Brief-Driven Mode asks nothing the brief answers
/create-spec
```

Every value records **how it arrived**, and its confidence follows from that — never from a
model's opinion of itself:

| Provenance | Meaning | Confidence |
|---|---|---|
| `elicited` | you said so | 1.0 |
| `detected` | read off the filesystem | 1.0 |
| `extracted` | pulled from a document, verbatim span verified | 0.9 |
| `extracted` | pulled from a document, paraphrased | 0.6 |
| `inferred` | filled from a domain template | the template's prior |
| `defaulted` | the policy fallback | 0.0 |

Higher provenance wins on merge (`elicited` > `detected` > `extracted` > `inferred` >
`defaulted`), so re-running `brief extract` can never overwrite something you supplied
yourself. Anything below the brief's `confidence_floor` (default 0.75) shows up in
`claw-forge brief gate` — that, and nothing else, is what you review.

Three quality tiers set the policy defaults, `confidence_floor` among them:
`--tier minimal` (0.5) · `--tier standard` (0.75, the default) · `--tier strict` (0.9).

Everything here degrades rather than failing. No Anthropic credential —
`ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` or `CLAUDE_CODE_OAUTH_TOKEN` — leaves the brief
untouched and exits 0; one failed extraction pass costs only its own fields; an unrecognized field falls
through to the policy default and is recorded as a `defaulted` decision. Full flag and
exit-code reference: [docs/commands.md](docs/commands.md#claw-forge-brief).

`/fix-spec --autonomous` reads the same brief. Where it would normally stop on a Manual Review
block, it applies the brief's policy, records the call in `deferred_decisions.yaml`, and keeps
going — so an unattended repair finishes and leaves you a queue instead of a halt.

### Spec format reference

**Plain text fields:**

| Field | Required | Description |
|---|---|---|
| `Project:` | ✅ | Project name |
| `Stack:` | ✅ | Languages, frameworks, databases |
| `Features:` | ✅ | Section header; the features are the numbered items (`1. Name`) under it |
| `Description:` | optional | Per feature — the line directly under the numbered item |
| `- bullet` | optional | Per feature — a step; write each as a verifiable acceptance condition |
| `Depends on:` | optional | Per feature — comma-separated numbers of the features it needs |

Nothing else is a field. Library preferences and constraints go in the `Description:` line.
`Description:` is one line; a wrapped continuation is dropped.

**XML elements (greenfield `app_spec.xml`):**

| Element | Required | Description |
|---|---|---|
| `<project_name>` | ✅ | Project name |
| `<overview>` | ✅ | One paragraph summary |
| `<technology_stack>` | ✅ | Languages, frameworks, databases |
| `<core_features>` | ✅ | One feature per line, action-verb format |
| `<database_schema>` | optional | Table definitions |
| `<api_endpoints_summary>` | optional | Route list |
| `<ui_layout>` | optional | Page/component structure |
| `<implementation_steps>` | optional | `<phase name="...">` blocks — a dependency **barrier**: a feature that omits `depends_on` waits for every feature of the previous phase, even with disjoint `touches_files`; `depends_on=""` opts it out |
| `<success_criteria>` | optional | Done conditions |

**XML elements (brownfield `additions_spec.xml`, `mode="brownfield"`):**

| Element | Required | Description |
|---|---|---|
| `<project_name>` | ✅ | Project + addition name |
| `<addition_summary>` | ✅ | What you're adding and why |
| `<existing_context>` | optional | `<stack>`, `<test_baseline>`, `<conventions>` — auto-populated by `/create-spec` |
| `<features_to_add>` | ✅ | One feature per line (same format as `<core_features>`) |
| `<integration_points>` | optional | Where new code hooks into existing code |
| `<constraints>` | optional | What must NOT change |
| `<implementation_steps>` | optional | `<phase name="...">` blocks — a dependency **barrier**: a feature that omits `depends_on` waits for every feature of the previous phase, even with disjoint `touches_files`; `depends_on=""` opts it out |

### Acceptance criteria: tests the coding agent did not write

A `<feature>` may carry an `<acceptance>` child, one observable criterion per `- ` bullet:

```xml
<feature index="2" depends_on="1" shape="plugin" plugin="auth">
  <description>User can register with email and password (POST /api/auth/register)</description>
  <acceptance>
    - POST /api/auth/register with a valid email and password returns 201 and a user id
    - Registering the same email twice returns 409
  </acceptance>
</feature>
```

`plan` then synthesizes one **acceptance task** per such feature. An independent agent writes
executable tests for the criteria in `acceptance/<slug>/` (outside every default test
discovery, so the target never goes red) plus an `acceptance.json` naming the command that runs
them. The harness requires those tests to **fail** before the feature exists, denies the coding
agent writes to that directory, and requires them to **pass** before the feature is accepted,
whether or not the full-suite acceptance gate is on. Put criteria on a feature that depends on
the project's scaffolding feature (`depends_on`), not on a root: the tests are written before any
test framework would otherwise exist. `agent.acceptance_criteria: enforce | off` (default
`enforce`).

### Tips for a good spec

- **One feature = one atomic unit of work.** If it would take >2 hours to implement, split it.
- **Acceptance criteria are tests.** Write them as if the agent must tick each one before marking done.
- **Use `Depends on:` for real hard dependencies.** Features with no dependencies run in parallel in Wave 1.
- **Start with 5–10 features.** Add more with `/expand-project` once the first wave is running.
- **Be specific about libraries.** "Use python-jose for JWT" beats "implement JWT".
- **Include test count targets.** "15 unit tests" gives the agent a concrete goal.

### Architectural shape (parallel-safety hint)

Add a `shape` attribute to each `<feature>` so the dispatcher knows
how to schedule it for parallel-safe execution:

```xml
<feature index="14" shape="plugin" plugin="auth">
  <description>User can register with email and password</description>
</feature>
<feature index="20" shape="core"
         touches_files="src/core/middleware/auth.py">
  <description>All endpoints validate JWT</description>
</feature>
```

Plugin-shape features can run in parallel (their files don't overlap by
construction).  Core-shape features are scheduled by footprint: disjoint
`touches_files` run in parallel, overlapping ones serialize.  Only
`shape="integration"` runs alone.  See
[`docs/commands.md` → claw-forge plan](docs/commands.md) for details.

Use `<feature shape="plugin" plugin="auth">` to opt into shape-aware scheduling
(plugin features dispatch in parallel; core features serialize only where their footprints overlap). `claw-forge
validate-spec` checks shape annotations strictly by default. It **errors** on a
brownfield spec whose `touches_files` entries match no real file in the project
(Gap 10) — an empty claim silently disables file-claim locking, the most common
cause of parallel-agent collisions — and Gap 10 has no opt-out. `--soft-shape`
relaxes the promotable shape findings (gaps 3, 5 and 9) from errors to warnings
during a migration on-ramp.

A feature that brings **new** files into existence declares them with
`creates="path, ..."` instead of forcing them into `touches_files=` — the
parser unions them into the footprint (so file-claim locking still covers the
new paths), and Gap 10 skips exactly those entries instead of erroring on a
path that does not exist yet. Same attribute as `bug_spec.xml`'s `creates=`.

### Adding features to a running project

`claw-forge plan` **reconciles by default** — it matches spec features against existing tasks by description, keeps completed/pending/failed tasks untouched, and only inserts new features as pending tasks. Dependencies are wired correctly across old and new tasks.

```bash
# Option A — /expand-project slash command in Claude Code
/expand-project
# Claude lists current features, asks what to add, POSTs them atomically

# Option B — edit spec and re-plan (only new features are added)
echo "
4. Email reminders
   Description: Send due-date reminders 24h before via SendGrid.
   Acceptance criteria:
   - Celery task runs hourly, finds tasks due in next 24h
   - Sends email via SendGrid with task title and due date
   - Emails only sent once per task per due date
   Depends on: 2
" >> app_spec.txt
claw-forge plan app_spec.txt --project my-api
# Output:
# Reconciled with existing session:
#   3 completed  (kept)
#   1 new        (added)

# Use --fresh to ignore existing state and start from scratch
claw-forge plan app_spec.txt --project my-api --fresh
```

---

## Provider Pool

Never hit a rate limit again. Configure multiple providers with automatic failover:

```yaml
# claw-forge.yaml
providers:
  # Run `claude setup-token`, then put the token in your env — no API key needed.
  # claw-forge uses this token as-is; it never reads ~/.claude/.credentials.json,
  # so each OAuth provider can carry a distinct account for real rotation.
  claude-oauth:
    type: anthropic_oauth
    oauth_token: ${CLAUDE_OAUTH_TOKEN}
    priority: 1

  # Direct API key as primary fallback
  anthropic-primary:
    type: anthropic
    api_key: ${ANTHROPIC_KEY_1}
    priority: 2

  # Second API key for burst capacity
  anthropic-secondary:
    type: anthropic
    api_key: ${ANTHROPIC_KEY_2}
    priority: 2

  # Cloud providers (pool.execute() only — not used to run agents, see below)
  aws-bedrock:
    type: bedrock
    region: us-east-1
    priority: 3

  azure-ai:
    type: azure
    endpoint: https://my-resource.openai.azure.com
    api_key: ${AZURE_KEY}
    priority: 4

  # OpenAI-shaped endpoints (pool.execute() only)
  groq-free:
    type: openai_compat
    base_url: https://api.groq.com/openai/v1
    api_key: ${GROQ_KEY}
    priority: 5

  # Local model via Ollama (pool.execute() only)
  local-ollama:
    type: ollama
    base_url: http://localhost:11434
    model: qwen2.5-coder
    priority: 6
```

The pool automatically:
- Picks the provider for each dispatch by the configured strategy (default `quality_ranked` — measured gate-pass rate first, degrading to priority order until ranks exist)
- Rotates to the next provider on rate-limit, 5xx, network and rejected-credential errors; a rejected credential is quarantined for the rest of the run
- Opens per-provider circuit breakers on persistent failures (`pool.failure_threshold`, `pool.recovery_timeout`)
- Falls through the entire chain before giving up; when every credential is exhausted the run pauses and leaves the remaining work `pending` instead of failing it

**Only three provider types can run an agent.** `claw-forge run` drives the Claude CLI, which speaks the Anthropic wire and authenticates with an API key or bearer token — so `anthropic`, `anthropic_oauth` and `anthropic_compat` providers are the ones picked to run a coding agent. `bedrock`, `azure`, `vertex`, `openai_compat` and `ollama` providers stay in the pool for direct `ProviderPoolManager.execute()` requests and are never picked for an agent (a warning names them when the pool is built). In the example above, only `claude-oauth`, `anthropic-primary` and `anthropic-secondary` would run agents.

**What the pool tracks depends on the path.** Cost, latency and requests-per-minute tracking, `max_rpm` throttling and `Retry-After` back-off belong to `ProviderPoolManager.execute()`, the path used when no `claude` CLI is available. When the Claude CLI runs the agent (the normal case) the pool only chooses the credential, `base_url` and `model` for each dispatch; per-provider token usage is metered from the agent's own reports and shown by `claw-forge status`. See [Provider Pools and Cost](handbook/en/14-provider-pools.md).

**4 routing strategies:** `quality_ranked` (default — ranks enabled providers by measured gate-pass rate from this project's own `state.db`) · `priority` · `round_robin` · `weighted_random`. `least_cost`/`least_latency` are retired: an old config naming either still runs, routed onto `quality_ranked` with one warning.

**Per-machine overrides:** drop a gitignored `claw-forge.local.yaml` next to your config to override anything for just this machine — it's deep-merged on top of the committed base before `${ENV}` expansion (providers merge by name; other sections recurse). The Kanban UI's provider enable/disable "persist" writes here, so toggling a provider never dirties the shared `claw-forge.yaml`. Run with `--no-local` to ignore the overlay (reproducible / CI runs).

### Anthropic-compatible model providers (Kimi, DeepSeek, GLM, Qwen, MiniMax, MiMo)

Several frontier labs expose a native **Anthropic Messages** endpoint, so you can put them straight into the pool as `type: anthropic_compat` and the coding agent talks to them directly — `base_url` and `model` travel with the token per dispatch, so you can even mix them with a Claude provider as fallback tiers. They authenticate with a **Bearer token**, so use `oauth_token:` (injected as `ANTHROPIC_AUTH_TOKEN`), not `api_key:`. Model ids change often — verify the current id in each provider's Claude Code doc.

| Provider | `base_url` (international) | Example `model` |
|---|---|---|
| Moonshot **Kimi** | `https://api.moonshot.ai/anthropic` | `kimi-k3` |
| **DeepSeek** | `https://api.deepseek.com/anthropic` | `deepseek-chat` |
| **GLM** (Z.ai / Zhipu) | `https://api.z.ai/api/anthropic` | `glm-4.6` |
| **Qwen3-Coder** (DashScope) | `https://dashscope-intl.aliyuncs.com/api/v2/apps/claude-code-proxy` | `qwen3-coder-plus` |
| **MiniMax** | `https://api.minimax.io/anthropic` | `MiniMax-M2` |
| **MiMo** (Xiaomi) | `https://api.xiaomimimo.com/anthropic` | `mimo-v2.5-pro` |

```yaml
providers:
  glm:
    type: anthropic_compat
    oauth_token: ${ZAI_API_KEY}          # Bearer token → ANTHROPIC_AUTH_TOKEN
    base_url: https://api.z.ai/api/anthropic
    model: glm-4.6
    priority: 3                          # a fallback tier below your primary Claude provider
```

Most of these also publish a **China-mainland** host on a different domain (e.g. MiniMax `api.minimaxi.com`, GLM `open.bigmodel.cn`, DashScope `dashscope.aliyuncs.com`) with separate keys — see the commented templates in `claw-forge.yaml`. Note: these are provider-documented integrations, not Anthropic-endorsed, and some (e.g. MiMo) may need extended thinking disabled if agentic runs return HTTP 400s.

---

## Supported Providers

| Provider | Type | Auth | Runs agents under `claw-forge run` |
|---|---|---|---|
| Anthropic direct | `anthropic` | API key | ✅ |
| Claude OAuth | `anthropic_oauth` | `oauth_token` (run `claude setup-token`) | ✅ |
| Anthropic-format proxy / model provider (Kimi, DeepSeek, GLM, Qwen, MiniMax, MiMo) | `anthropic_compat` | `x-api-key` (`api_key`), Bearer (`oauth_token`), or none (internal proxies) | ✅ |
| AWS Bedrock | `bedrock` | IAM / instance role | — |
| Azure AI Foundry | `azure` | API key | — |
| Google Vertex AI | `vertex` | Application Default Credentials | — |
| Groq / Cerebras | `openai_compat` | API key | — |
| Any OpenAI-compat endpoint | `openai_compat` | Optional API key | — |
| Ollama (local) | `ollama` | Optional (usually none) | — |

---

## Agent Runtime

claw-forge uses the Claude Agent SDK for all agent execution. The SDK handles the tool-use loop, MCP server connections, permission hooks, streaming — claw-forge adds the orchestration, state management, and provider rotation layer on top.

### Bidirectional sessions

```python
from pathlib import Path
from claw_forge.agent import AgentSession
from claw_forge.agent.thinking import ADAPTIVE_THINKING
from claude_agent_sdk import ClaudeAgentOptions

options = ClaudeAgentOptions(
    model="claude-sonnet-5-5",
    cwd=Path("./my-project"),
    thinking=ADAPTIVE_THINKING,                 # the one thinking config claw-forge ships
    max_budget_usd=1.00,                        # hard cost cap
    betas=["context-1m-2025-08-07"],            # 1M token context
    enable_file_checkpointing=True,             # session.rewind() needs this
)

async with AgentSession(options) as session:
    # Primary task
    async for msg in session.run("Implement the OAuth2 login flow"):
        handle_message(msg)

    # Tests failed — guide without restarting the session
    async for msg in session.follow_up("Focus on fixing test_auth.py first"):
        handle_message(msg)

    # Refactor went wrong — rewind files to before the last step
    await session.rewind(steps_back=1)

    # Escalate to Opus for the hard security review
    await session.switch_model("claude-opus-5-5")
```

### One-shot queries

```python
from claw_forge.agent import collect_result, collect_structured_result

# Simple text result
result = await collect_result(
    "Write unit tests for src/auth.py",
    cwd=Path("./my-project"),
    agent_type="testing",   # gets correct tool list + max_turns
)

# Structured JSON output (schema enforced)
review = await collect_structured_result(
    "Review the PR diff for security issues",
    cwd=Path("./my-project"),
    agent_type="reviewer",
    output_format=CODE_REVIEW_SCHEMA,
)
# review = {"verdict": "request_changes", "blockers": [...], "security_issues": [...]}
```

### Provider pool + agent

```python
from pathlib import Path
from claw_forge.agent import collect_result
from claw_forge.pool import ProviderPoolManager
from claw_forge.pool.providers.base import ProviderConfig, ProviderType

pool = ProviderPoolManager([
    ProviderConfig(name="primary", provider_type=ProviderType.ANTHROPIC,
                   api_key="sk-ant-...", priority=1),
    ProviderConfig(name="backup", provider_type=ProviderType.ANTHROPIC,
                   api_key="sk-ant-...", priority=2),
])
provider = pool.next_provider_for_dispatch()   # the selection `claw-forge run` makes per task

result = await collect_result(
    "Fix the failing integration tests",
    cwd=Path("./project"),
    provider_config=provider.config if provider else None,  # that provider's credential and base_url
)
```

`ProviderPoolManager.from_config(configs, cfg)` builds the same pool from a parsed
`claw-forge.yaml` (`configs` from `load_configs_from_yaml(cfg)`), reading its `pool:` section.

---

## Advanced SDK Features

[`docs/sdk-api-guide.md`](docs/sdk-api-guide.md) walks through 20 Claude Agent SDK APIs with claw-forge examples. The ones claw-forge wires in:

| Feature | API | Use case |
|---|---|---|
| File undo | `enable_file_checkpointing` + `AgentSession.rewind()` | Roll back bad refactors |
| Cost cap | `max_budget_usd` | Hard limit per session |
| Structured output | `output_format` schema | Typed review verdicts |
| Reasoning depth | `effort` (`low` … `max`) | `claw-forge run` sets it per agent type: `max` for the initializer and integration tasks, `xhigh` for coding, bugfix and reviewer, `low` for testing |
| OS sandbox | `SandboxSettings` | The SDK's own bash sandbox — used only where Layer 4 and Layer 5 (below) are not active |
| Model fallback | `fallback_model` | Auto-retry on model error |

---

## Security

Seven layers of defence against agent leakage into the target branch (the `main` worktree the dispatcher protects), plus a per-plugin fence and a forensic safety net.  See [`docs/container-isolation.md`](docs/container-isolation.md) for opt-in container setup and `CLAUDE.md` → "Worktree-Leakage Defenses" for the full design rationale.

| Layer | Catches | Default |
|---|---|---|
| 1. **File-tool path sandbox** | Accidental Write/Edit/Glob/Grep escapes outside the worktree | always on |
| 2. **Exempt-command jail check** | `git -C <jail>`, `python <jail>/script.py`, `--git-dir=<jail>/.git` — escape via dev-toolchain commands the file sandbox would otherwise exempt | always on (v0.8.16) |
| 3. **Workspace boundary directive** | Patterns no static check can intercept (`python -c "open('/abs', ...)"`); information-hiding so the agent never sees the parent project's path | always on (v0.8.16, hardened v0.8.18) |
| 4. **OS-level filesystem jail** | Every escape at the syscall level — `open(2)` outside the worktree returns `EACCES` (macOS) / `EROFS` (Linux) | always on; macOS via `sandbox-exec` (v0.8.18), Linux via `bwrap` (v0.8.21) |
| 5. **Container isolation** | Parent project absent from the agent's filesystem namespace entirely; escapes return `ENOENT` (no such path) | opt-in via `agent.isolation: container` in `claw-forge.yaml` (v0.8.19) |
| 6. **Supply-chain hardening** | npm lifecycle scripts, writes into protected parts of the agent's home directory, and container network egress | on by default: `agent.npm_ignore_scripts`, `agent.sandbox.home_protection`, `agent.container.network`. Egress from the non-container sandbox is **not** constrained |
| 7. **Vanished-worktree fail-closed** | A worktree deleted mid-task drops the agent's shell into `$HOME` while relative paths still look allowed | always on — every Bash and file-tool call is denied once the worktree is gone, and the task fails `worktree_vanished:` as an infrastructure failure |
| 4b. **Per-plugin fence** | Narrows Layer 4's writable set for a `shape="plugin"` task down to its `touches_files` dirs (+ `.claw-forge` scratch); out-of-footprint writes fail with `EACCES`/`EROFS` | opt-in via `agent.sandbox.fence_to_touches_files: true` (requires plugin auto-discovery; validate-spec Gap 11 flags shared-file edits). The always-on post-merge **footprint audit** records each merged task's conformance as `footprint_audit:` activity-log events — the field data that decides when this fence can default on |
| Forensic | **Snapshot-rollback** captures any leak that slips through to a `claw-forge-leak-<task_id>-<ts>` stash; `project_path` restored to HEAD-clean before squash-merge | always on (v0.8.17) |

Plus the foundational defences:

- **`CanUseTool` callback** — Python function runs before every tool; blocks dangerous commands, restricts writes to project directory, can mutate tool inputs.
- **Bash security hook** — a **denylist**: a hardcoded set of blocked commands (`sudo`, `dd`, `shutdown`, ...) plus argument-aware checks for recursive `rm` of protected roots, host-wide `kill`/`pkill` and system package managers. A command that matches none of them is allowed; there is no per-project command list.
- **`SandboxSettings`** — the Claude SDK's own per-Bash sandbox. claw-forge turns it **off** whenever Layer 4 or Layer 5 is active, because macOS forbids a sandbox nested inside a sandbox (`sandbox-exec` exits 71 and every Bash call fails); it is the only bash isolation on a platform with neither.
- **One dispatcher per session** — `claw-forge run` refuses to start (exit 1) when another dispatcher is live on the session, unless `--allow-concurrent`. This is a check against the state service, not a lock file.

Inspect captured leaks: `claw-forge stash list` (and `claw-forge stash show <ref>`).  Recover work: `claw-forge stash apply <ref>`.  Drop with `claw-forge stash drop <ref>`.

---

## Telemetry

**claw-forge is automatically opted in to anonymous usage telemetry** — see the
usage agreement in [PRIVACY.md](PRIVACY.md). Turn it off with
`claw-forge telemetry disable`, `telemetry.enabled: false`, `DO_NOT_TRACK=1`, or
`CLAW_FORGE_TELEMETRY=0`; CI is always excluded. It
records counts, durations, task outcomes, and feature *domains* — never code,
paths, project names, or error text.

Disable it anywhere, unconditionally:

```bash
export CLAW_FORGE_TELEMETRY=0   # or DO_NOT_TRACK=1
```

See [PRIVACY.md](PRIVACY.md), or run `claw-forge telemetry preview` to see the
exact bytes that would be sent.

---

## Commands

### CLI Commands

| Command | Description | Key flags |
|---------|-------------|-----------|
| `claw-forge init` | Bootstrap project — scaffold `.claude/`, config, `app_spec.example.xml` | `--project`, `--config` |
| `claw-forge plan` | Parse spec → feature DAG in state DB. Offline and deterministic — no model call, no API key. Reconciles with the existing session by default | `spec` (positional), `--project`, `--concurrency`, `--fresh` |
| `claw-forge run` | Start agent pool, dispatch features in parallel. Refuses to start (exit 1) when another dispatcher is already live on the session | `--concurrency`, `--model`, `--yolo`, `--edit-mode`, `--loop-detect-threshold`, `--verify-on-exit`, `--push-after-merge`, `--allow-concurrent` |
| `claw-forge add` | **Registers no work.** The plain form prints a suggested branch name; `--spec` parses a brownfield spec and prints the agent context. Use `claw-forge plan <spec>` to turn a spec into tasks | `--spec`, `--branch/--no-branch` |
| `claw-forge fix` | Queue **one** bug as a bugfix task, from a description or a `bug_report.md` — a thin wrapper over the bug-spec path; the agent reproduces first, then fixes. Plans only; `claw-forge run` dispatches | `--report`, `--model`, `--project` |
| `claw-forge validate-bug-spec` | Validate a bug spec's shapes, footprints and lineage; exits non-zero on ERROR | `--project`, `--json` |
| `claw-forge plan-bugs` | Plan a bug spec into the project's **existing** session as bugfix tasks — several fixes dispatch in parallel | `spec_file` (positional), `--project`, `--config` |
| `claw-forge pr-feedback` | Turn a delivered PR's review into bug tasks: each unresolved review thread and each standing "changes requested" review, from owners, org members and collaborators, becomes one bug, dispatched under a classify-first review protocol. Writes a draft spec to review; `--plan` plans it. Re-running plans only new comments (an edited comment is not planned twice) | `pr` (positional, default: the `delivery.branch` PR), `--plan`, `--allow-author`, `--project` |
| `claw-forge status` | Project progress, phase bars, active agents, completed/running task counts broken down by provider · model, measured per-provider token consumption, next action | `--config` |
| `claw-forge config` | Print the fully-resolved config (base + local overlay + `${ENV}`), credentials redacted | `--config`, `--no-local`, `--show-secrets` |
| `claw-forge ui` | Launch real-time Kanban board (React + WebSocket) | `--port`, `--session`, `--dev` |
| `claw-forge dev` | Start API (hot-reload) + UI (Vite HMR) for local development; add `--run` to also launch the agent orchestrator | `--state-port`, `--ui-port`, `--project`, `--run` |
| `claw-forge pool-status` | The pool as **configured** (it cannot show a live run's roster) plus the per-provider token usage actually measured | `--config` |
| `claw-forge pause` | Drain mode — finish in-flight agents, start no new ones. **Use this (or Stop All in the UI) to stop a wedged run — never a second `claw-forge run`** | — |
| `claw-forge skip` | Mark planned task(s) `skipped` — an honest "do not run this" for work superseded by a later spec. Releases file claims, strands dependents visibly, never salvaged; undo with `claw-forge reset --status skipped` | `task_refs` (positional), `--reason`, `--project` |
| `claw-forge satisfy` | Record a task as delivered by another commit (a sibling already merged its behaviour): `completed` + merged with a `delivered_by` marker, so dependants run while `status`, `evidence` and the success rate know no agent built it. Verifies the commit is on the target and the task's acceptance tests pass there, else needs `--unverified`; carries the feature's acceptance author along; undo with `claw-forge reset --status completed --delivered-by` | `task_ref` (positional), `--by`, `--reason`, `--unverified`, `--target`, `--project` |
| `claw-forge widen` | Add paths/globs to a planned task's `touches_files` so its agent may edit outside the footprint its spec declared (e.g. a feature that legitimately breaks a completed feature's tests). `pending`/`failed`/`paused`/`needs_human` only; recorded in a `task.widened` event, kept across re-plans; a live run sees it at its next wave boundary; `--remove` takes back only widened entries | `task_ref` (positional), `--path` (repeatable), `--reason`, `--remove`, `--project` |
| `claw-forge resume` | Resume a paused project | — |
| `claw-forge input` | Answer human-input questions from blocked agents | — |
| `claw-forge state` | Start the state service REST API (port 8420) | `--port`, `--host`, `--reload` |
| `claw-forge import` | Import BMAD / Linear / Jira exports → `app_spec.txt` or `additions_spec.xml` | `--project`, `--model`, `--yes`, `--out` |
| `claw-forge evidence` | Print the run evidence report (Markdown) for a session: verdict, per-feature gate/acceptance verdicts, unverified merges, undelivered tasks with their recovery command, token cost. Offline and read-only; pipe it into a PR body | `session` (positional), `--project` |
| `claw-forge export` | Export session/task data from `state.db` to CSV (flat or split), SQL dump, or JSON | `--format`, `--scope`, `--csv-mode`, `--session`, `--out` |
| `claw-forge analyze` | Offline, read-only structural verdict on an existing repo — `compatible` / `fixable` / `rebuild` / `inconclusive` — from a file-level import graph. Writes only under `.claw-forge/analyze/` (self-ignoring); exits 0 for every verdict | `path` (positional), `--json`, `--tests`, `--commits`, `--refresh`, `--validate-manifest` |
| `claw-forge rebuild` | Rebuild path for a `rebuild` verdict: `init-docs` · `check` (every claim line cited) · `approve` (hashes the docs) · `start NEW_DIR` · `parity` (journey parity with the old app) | `--project`, `--old`, `--new`, `--strict`, `--json` |
| `claw-forge boundaries audit` | Read-only: score files on dispatch density, churn, and centrality → `boundaries_report.md` | `--project`, `--min-score`, `--out` |
| `claw-forge boundaries apply` | Per-hotspot subagent refactor on a feature branch, gated by tests; squash-merges on green | `--project`, `--test-command`, `--hotspot`, `--auto`, `--report` |
| `claw-forge boundaries status` | Show the most recent audit's hotspot list | `--project` |
| `claw-forge worktrees list` | Inspect feature-branch worktrees under `.claw-forge/worktrees/` (branches + commit counts) | `--project`, `--target`, `--prefix` |
| `claw-forge worktrees prune` | Squash-merge worktree branches with commits to target then remove the dirs; `--discard` skips salvage and force-removes; safe to run mid-session — live agents' worktrees are skipped (override with `--force`) | `--project`, `--target`, `--prefix`, `--discard`, `--force` |
| `claw-forge stash list` | Show harness-managed git stashes (`auto`/`manual`/`leak`/`boot` kinds) — startup cleanup, mid-run leak captures, snapshot-rollback boot baselines | `--project` |
| `claw-forge stash drop` | Drop a specific harness-managed stash by ref (`stash@{N}` or bare `N`); refuses operator-personal stashes | `--project`, `--yes` |

The same cleanup machinery can run automatically at `claw-forge run` startup via `git.cleanup_orphan_worktrees: smart` in `claw-forge.yaml` — task-state-aware preserve/salvage/remove decisions per-worktree. Optional LLM advisor (`git.llm_conflict_proposals: true`) drafts a `CONFLICT_PROPOSAL.md` when salvage hits a conflict the user must resolve. See `docs/commands.md` for the decision matrix.

### Slash Commands (Claude Code)

| Command | When to use | What it produces |
|---------|-------------|-----------------|
| `/create-spec` | Starting a new project or adding features | `app_spec.txt` or `additions_spec.xml` |
| `/expand-project` | Adding features mid-sprint | New tasks in state DB |
| `/check-code` | Pre-PR quality gate | Ruff + mypy + pytest report |
| `/checkpoint` | Saving progress at a known-good state | Git commit + JSON snapshot + CHECKPOINT.md |
| `/review-pr` | Code review before merge | Structured verdict (APPROVE / REQUEST CHANGES) |
| `/pool-status` | Diagnosing slow agents or cost spikes | The configured pool plus measured per-provider usage |
| `/create-bug-report` | Structured bug reporting before fix | `bug_report.md` → offers to run `claw-forge fix --report` |
| `/create-bug-spec` | Several bugs at once, or a fix that must be ordered relative to another | `bug_spec.xml` → `claw-forge plan-bugs` |
| `/claw-forge-status` | Re-entry after leaving a session | Full project status card |
| `/import-spec` | Import 3rd-party tool export interactively with section-by-section review | `app_spec.txt` or `additions_spec.xml` |
| `/rebuild-extract` | `claw-forge analyze` said `rebuild` | Journey contract + cited PRD / architecture / design docs under `.claw-forge/rebuild/` |
| `/fix-spec` | `validate-spec` reports errors or warnings | The spec with only the offending bullets rewritten, until it validates clean; `--autonomous` records Manual Review items in `deferred_decisions.yaml` instead of stopping |
| `/verify-journeys` | A run just completed and you want to know the app really works | Journey files and browser screenshots under `.claw-forge/journeys/`; failures become bug specs or spec features |
| `/handbook-sync` | A change touched a command, flag, config key, API route or documented behaviour | Regenerated reference chapters and the drift report worked through, English and 简体中文 |

> 📚 Full details: [`docs/commands.md`](docs/commands.md) · End-to-end workflows: [`docs/workflows.md`](docs/workflows.md)

---

## Quick Workflow Cheatsheet

**New project:**
```
claw-forge init → /create-spec → claw-forge plan → claw-forge run
```

**Add features to existing app:**
```
/create-spec → claw-forge validate-spec → claw-forge plan → claw-forge run
```

**Import from BMAD / Linear / Jira:**
```
claw-forge import ./export → claw-forge validate-spec → claw-forge plan → claw-forge run
```

**Fix a bug:**
```
/create-bug-report → claw-forge fix → claw-forge run
```

**Fix several bugs in parallel:**
```
/create-bug-spec → claw-forge validate-bug-spec → claw-forge plan-bugs → claw-forge run
```

**Check health:**
```
claw-forge status → /pool-status → /check-code
```

**Save progress:**
```
/checkpoint → /review-pr → git push
```

---

## Workflow Features

| Feature | Command / Flag |
|---|---|
| YOLO mode | `claw-forge run --yolo` |
| Fix a bug (one-liner) | `claw-forge fix "description"` → `claw-forge run` |
| Fix a bug from report | `claw-forge fix --report report.md` → `claw-forge run` |
| Fix several bugs in parallel | `/create-bug-spec` → `claw-forge plan-bugs bug_spec.xml` |
| Pause (drain) | `claw-forge pause` (a project directory, project name or session id may be given) |
| Resume | `claw-forge resume` |
| Human input | `claw-forge input` — lists pending questions and prompts for each answer |
| Project status | `claw-forge status` |
| Dry run | `claw-forge run --dry-run` — prints the tasks in dependency order and dispatches nothing |
| Pool configuration and measured usage | `claw-forge pool-status` |
| Parallel-safe agents (file-claim locks) | `touches_files` on a spec feature, or `claw-forge fix --touches <path>` |
| Reset failed tasks in bulk | `claw-forge reset`, or the "Reset All" button on the Failed column header (Kanban UI) |
| Resume-conflict surfacing | automatic — failed task lists conflicting files; recover with `cd .claw-forge/worktrees/<slug>` + `git merge <target>` |

---

## Delivering as a pull request

By default a run squash-merges each feature straight into `git.target_branch`. For a team
that wants a review point, set `delivery.mode: pr`:

```yaml
delivery:
  mode: pr          # merge (default) | pr
  branch: null      # integration branch; default "claw-forge/delivery"
  base: null        # PR base; default = the run's target branch
  draft: true       # open the PR as a draft
```

The run creates the integration branch from `base` (no checkout) and uses it as its target,
so features — and merge-gated dependents — merge **there**. After the first squash your
checkout is on the integration branch (a squash switches to its target); switch back with
`git switch <base>` once the run ends. A re-run reuses the branch and never resets it. At run
end, if the branch has commits ahead of `base`, it is pushed (never `--force`) and `gh` opens a
PR into `base`, or updates the title and body of an open PR for that branch, with the
session's evidence as its body. A head that a merged or closed PR already carried is not
re-delivered. Push and `gh` failures are one warning plus the exact commands to finish by hand; they
never change the exit code. Needs `git.enabled: true` and `git.merge_strategy: auto`, and
the push remote must be the PR's base repository (fork workflows are not supported).

Every run, in every mode, also writes `.claw-forge/evidence/<session-id>.md` — why the
merged work should be trusted — and the summary prints its path. `claw-forge evidence`
renders the same report from `state.db` at any time. See
[`docs/commands.md`](docs/commands.md#claw-forge-evidence).

---

## Kanban UI

Real-time board tracking feature progress across all agents. Cards flow across the board's columns as agents work — with live provider health, cost tracking, and regression status in the header.

![claw-forge Kanban board — light mode with 18 features across Pending, In Progress, Passing, Failed, and Blocked columns](website/assets/screenshots/kanban-overview.png)

### Dark mode

![claw-forge Kanban board — dark mode](website/assets/screenshots/kanban-dark.png)

```bash
claw-forge dev               # API (:8420, hot-reload) + UI (:5173, HMR) in one command
# or separately:
claw-forge state --reload &  # start REST + WebSocket server on :8420 with hot-reload
claw-forge ui --dev          # http://localhost:5173/?session=<uuid>
```

**Columns:** Pending · In Progress · Passing · Failed · Blocked — the last is kept for compatibility: nothing in the current harness moves a task there. A task whose dependency failed stays in Pending, and `claw-forge status` reports it as stranded.

**Header:** provider health dots (green/yellow/red per provider) · progress bar (X/Y passing) · live agent count · cost sparkline · regression health bar

**Real-time:** WebSocket pushes feature status changes, agent streaming logs, provider health, and cost updates. Drag-and-drop cards to retry failed tasks.

---

## Claude Commands

Slash commands in `.claude/commands/` for use inside Claude Code. Automatically scaffolded by `claw-forge init`. See [`docs/commands.md`](docs/commands.md) for full reference with real-world examples, and [`docs/workflows.md`](docs/workflows.md) for end-to-end walkthroughs.

| Command | Purpose | When to use |
|---|---|---|
| `/create-spec` | Interactive spec creation — auto-detects greenfield vs brownfield, outputs XML | Starting a new project or adding features |
| `/expand-project` | Add features to an existing project | Mid-run when you think of more features |
| `/check-code` | Run ruff + mypy + pytest and report | After agent completes a batch of features |
| `/checkpoint` | Commit + DB snapshot + session summary | Before stepping away or at phase boundaries |
| `/review-pr` | Structured PR review with verdict | Before merging any agent-generated branch |
| `/pool-status` | The configured provider pool, plus the usage that was actually measured | When you suspect rate limits or cost spikes |
| `/claw-forge-status` | Project progress, phase bars, agent state, next action | Quick health check at any time |
| `/create-bug-report` | Guided 6-phase bug report creation → runs fix | When a bug is reported and you need a proper fix |
| `/create-bug-spec` | Interview for N bugs; derives each one's shape, footprint and dependency edges → `bug_spec.xml` | Several bugs at once, or when one fix must land before another |
| `/fix-spec` | Repair a spec until `validate-spec` is clean | After `validate-spec` reports errors or warnings |
| `/verify-journeys` | Check each user journey of the built app in a real browser, with screenshots | After a run completes |
| `/rebuild-extract` | Verify the old app's journeys, write cited PRD / architecture / design docs, run `rebuild check` until clean, then stop for your review | After `claw-forge analyze` returns `rebuild` |
| `/import-spec` | Convert a BMAD / Linear / Jira export section by section | When the stories already exist in another tool |
| `/handbook-sync` | Bring `handbook/` back in line with the code, in both languages | After a change to a command, flag, config key, route or documented behaviour |

The built-in agent roles (`coding`, `testing`, `reviewer`, `initializer`, `bugfix`) are plugins registered in `pyproject.toml`; `init` scaffolds no agent-definition files. See [Plugin System](#plugin-system).

---

## Quick Workflow Cheatsheet

| Goal | Command chain |
|------|--------------|
| **New project** | `claw-forge init` → `/create-spec` → `claw-forge plan` → `claw-forge run` |
| **Add features to existing app** | `/create-spec` (brownfield) → `claw-forge plan` → `claw-forge run` |
| **Fix a bug (TDD)** | `/create-bug-report` → `claw-forge fix` → `claw-forge run` → `/review-pr` |
| **Fix several bugs (parallel)** | `/create-bug-spec` → `claw-forge validate-bug-spec` → `claw-forge plan-bugs` → `claw-forge run` |
| **Quality check** | `/check-code` → `/review-pr` |
| **Save progress** | `/checkpoint` → `git push` |
| **Monitor providers** | `/pool-status` |
| **Resume after crash** | `claw-forge status` → `claw-forge run` |

📖 Full workflow guides: [docs/workflows.md](docs/workflows.md)
📖 Command reference: [docs/commands.md](docs/commands.md)

---

## Pre-installed Skills (21) + Templates

All 21 skills ship as **one** Claude Code plugin (`agent_plugin/`), and every agent session is handed that plugin. There is no per-language, per-agent-role or per-keyword selection: Claude Code already loads only each skill's short description into context and reads the body when the skill is invoked, so hiding skills would save nothing. (`run_agent()` still accepts `auto_inject_skills` and `auto_detect_lsp` so older callers keep working; both are ignored.)

One nudge, not a selection: a task whose `touches_files` names web-UI files (`.tsx`, `.vue`, `.css`, `components/`, `pages/`, …) is told in its prompt to invoke `claw-forge:apple-design` and `claw-forge:modern-web-guidance`. A task with no footprint gets no nudge, and no skill is withheld from any task.

**Diagnostics skills (7):** pyright · gopls · rust-analyzer · typescript-lsp · clangd · solidity-lsp · java-lsp

**Process skills (6):** systematic-debug · verification-gate · parallel-dispatch · test-driven · code-review · web-research

**Integration skills (6):** git-workflow · api-client · docker · security-audit · performance · database

**UI skills (2):** apple-design · modern-web-guidance

The diagnostics skills drive each language's own command-line tooling (`pyright`, `gopls`, `cargo check` / `clippy`, `tsc`, `clangd --check`, `solc` + Slither, and the Java build tool) rather than a long-lived language-server session.

**Templates:** `templates/bug_report.template.md` — structured bug report template for use with `claw-forge fix --report` and `/create-bug-spec`

---

## Brownfield Projects

claw-forge works on **existing codebases** — not just greenfield projects. The path
that works is the ordinary one: `plan`, not `add`, is what turns a spec into tasks.

```bash
# 0. Judge the structure first (offline, read-only, seconds)
claw-forge analyze

# 1. Mark the spec brownfield:  <project_specification mode="brownfield">
claw-forge validate-spec additions_spec.xml --project-root .

# 2. Turn it into tasks
claw-forge plan additions_spec.xml

# 3. Run
claw-forge run --concurrency 3
```

Bug fixes have their own command, which does work end to end:

```bash
claw-forge fix "Login fails when email contains uppercase letters"
```

`claw-forge analyze` gives one verdict: `compatible` → write the spec with
`/create-spec`; `fixable` → run the printed `boundaries apply --report …` commands
and analyse again; `rebuild` → `/rebuild-extract`, then `claw-forge rebuild`
(approve → start → parity), where the rebuild is done when it passes the old app's
user journeys. It also writes a `brownfield_manifest.json` under
`.claw-forge/analyze/`; a hand-written root file still wins.

> [!IMPORTANT]
> **`claw-forge add` does not register work.** The plain form prints a suggested
> branch name and `Feature addition not yet integrated`. The `--spec` form parses
> the spec and prints the agent context it built, then stops without writing any
> tasks. Use `claw-forge plan <spec>` — it is also what persists a brownfield
> spec's `<constraints>` so the agents actually receive them.
> Full detail: [Working in an Existing Codebase](handbook/en/17-existing-codebases.md).

### Fixing bugs

**Quick fix** (one-liner):
```bash
claw-forge fix "users get 500 when uploading files > 5MB"
```

**Structured fix** (recommended for complex bugs):
```bash
# Generate a structured bug report interactively
/create-bug-report

# Or copy the template and fill it in
cp templates/bug_report.template.md bug_report.md
# edit bug_report.md...

# Run the fix
claw-forge fix --report bug_report.md
```

The bug-fix agent follows a strict **RED → GREEN** protocol:
1. Writes a failing regression test first (RED)
2. Locates root cause using systematic-debug skill
3. Makes surgical fix — touches only what's needed
4. Confirms regression test passes (GREEN)
5. Runs full test suite — must be 100% green
6. Commits with `fix: <title>\n\nRegression test: <test_name>`

> **Status:** `fix` is implemented. `add` is a scaffold-only stub that registers
> nothing. `analyze` judges structure; it does not write a spec. The workflow that
> works is `analyze` → `/create-spec` → `plan` → `run`; see
> [Working in an Existing Codebase](handbook/en/17-existing-codebases.md).

---

## Plugin System

The agent roles are Python classes, registered as entry points in `pyproject.toml` under the `claw_forge.plugins` group:

| Entry point | Plugin | Role |
|---|---|---|
| `initializer` | `InitializerPlugin` | Parse spec, create feature DAG (`claw-forge plan` calls it directly) |
| `coding` | `CodingPlugin` | TDD-first feature implementation |
| `testing` | `TestingPlugin` | Run regression tests, report failures |
| `reviewer` | `ReviewerPlugin` | Structured code review with verdict |
| `bugfix` | `BugFixPlugin` | Reproduce-first bug fix: RED→GREEN protocol |

Each is a `BasePlugin` subclass with `get_system_prompt(context)` and `execute(context)`, and `claw_forge.plugins.base.discover_plugins()` lists whatever is installed under that entry-point group.

**Registering a plugin does not extend `claw-forge run`.** Nothing in a run calls `discover_plugins()`, and the dispatcher never calls a plugin's `execute()`: it uses a task's `plugin_name` only as a label — which role's reasoning effort, prompt directive and gates apply — and drives the agent itself. A plugin of your own is a class you instantiate and call from your own code:

```python
import asyncio
from pathlib import Path

from claw_forge.agent import collect_result
from claw_forge.plugins.base import BasePlugin, PluginContext, PluginResult


class MyAgentPlugin(BasePlugin):
    name = "my_agent"
    description = "Does something custom"
    version = "1.0.0"

    def get_system_prompt(self, context: PluginContext) -> str:
        return "You are a specialist in ..."

    async def execute(self, context: PluginContext) -> PluginResult:
        result = await collect_result(
            self.get_system_prompt(context),
            cwd=Path(context.project_path),
            agent_type="coding",
        )
        return PluginResult(success=True, output=result)


context = PluginContext(project_path=".", session_id="demo", task_id="1")
outcome = asyncio.run(MyAgentPlugin().execute(context))
```

---

## White-labelling

claw-forge can ship under another organisation's name, command, config files and endpoints
without a fork: install a *brand pack* (a `claw_forge.brand` entry point on a small
distribution, or a YAML file named by `CLAW_FORGE_BRAND`) and the CLI, help text, state and
config names, env prefix, commit identity, telemetry and update source all follow it. With no
brand installed, behaviour is unchanged. See
[White-Labelling Claw Forge](handbook/en/32-white-labelling.md); `claw-forge brand new <id>` scaffolds a
partner distribution and `claw-forge brand check` validates a pack offline. The Apache-2.0
[`LICENSE`](LICENSE) and [`NOTICE`](NOTICE) must travel with any redistribution.

---

## Development

### Prerequisites

- Python 3.11+
- [uv](https://docs.astral.sh/uv/) package manager
- Node.js 18+ (for the Kanban UI)

### Setup

```bash
git clone https://github.com/clawinfra/claw-forge.git
cd claw-forge
uv sync --extra dev          # install Python deps (including dev tools)
npm install --prefix ui      # install UI deps
```

### Local Dev (API + UI with hot-reload)

The fastest way to develop locally — one command starts both servers with automatic reload on file changes:

```bash
claw-forge dev
```

This starts:
- **State API** on `http://localhost:8420` — uvicorn with `--reload`, restarts on any Python file change under `claw_forge/`
- **Kanban UI** on `http://localhost:5173` — Vite dev server with HMR, instant updates on React/TypeScript changes. An occupied 5173 advances to the next free port; the console names the one it landed on.

Options:

```bash
claw-forge dev --state-port 9000    # custom API port
claw-forge dev --ui-port 3000       # custom UI port
claw-forge dev --project /path/to/app  # point at a different project directory
claw-forge dev --no-open            # don't auto-open the browser
```

Press `Ctrl+C` to stop both servers.

### Running servers separately

If you prefer separate terminals (useful for cleaner log output):

```bash
# Terminal 1 — API with hot-reload
claw-forge state --reload

# Terminal 2 — UI with Vite HMR
claw-forge ui --dev
```

The `--reload` flag on `state` enables uvicorn file watching. The `--dev` flag on `ui` runs Vite instead of serving the pre-built static bundle.

### Running Vite directly (without the CLI)

If you want to run `npm run dev` from the `ui/` directory without going through `claw-forge ui --dev`, set the proxy target port via environment variables:

```bash
cd ui
VITE_API_PORT=8420 npm run dev
```

Or create `ui/.env.local`:

```env
VITE_API_PORT=8420
VITE_WS_PORT=8420
```

### Tests & linting

```bash
uv run pytest tests/ -q                                          # full test suite
uv run pytest tests/path/to/test.py::Class::test_name -v         # single test
uv run pytest tests/ -q --cov=claw_forge --cov-report=term-missing  # with coverage (must reach 94%, branch — the CI gate)
uv run ruff check claw_forge/ tests/                             # lint
uv run ruff check claw_forge/ tests/ --fix                       # auto-fix
uv run mypy claw_forge/ --ignore-missing-imports                 # type check
```

Tests run with internal invariants set to `raise` (see CLAUDE.md → "Invariants
are declared, not remembered" under Landmines) — a newly-failing unrelated
test is a real signal, not flakiness.

---

## Documentation

| Document | Contents |
|---|---|
| [Frequently Asked Questions](handbook/en/27-faq.md) | The questions people ask first — cost and time, fit, safety, parallelism, control |
| [`ARCHITECTURE.md`](ARCHITECTURE.md) | System design, data flow, component details |
| [`docs/commands.md`](docs/commands.md) | Full CLI command reference with options and examples |
| [`docs/workflows.md`](docs/workflows.md) | End-to-end workflow walkthroughs |
| [`docs/sdk-api-guide.md`](docs/sdk-api-guide.md) | 20 Claude Agent SDK APIs with claw-forge examples |
| [`docs/bmad-integration.md`](docs/bmad-integration.md) | Using claw-forge with BMAD Method — convert epics/stories to spec |
| [`docs/brownfield.md`](docs/brownfield.md) | Brownfield **design notes** (partly unbuilt; `analyze` and `rebuild` are documented in [`docs/commands.md`](docs/commands.md)); read [handbook ch.17](handbook/en/17-existing-codebases.md) for what works and [Judging and Rebuilding a Codebase](handbook/en/17b-judging-and-rebuilding.md) for `analyze`/`rebuild` |
| [`docs/agent-skill.md`](docs/agent-skill.md) | OpenClaw agent skill — install via `clawhub install claw-forge-cli` |
| [`PRIVACY.md`](PRIVACY.md) | What anonymous usage telemetry collects, and what it never does |
| [`docs/middleware/pre-completion-checklist.md`](docs/middleware/pre-completion-checklist.md) | Design doc: PreCompletionChecklistMiddleware (issue #4) |
| [`docs/middleware/loop-detection.md`](docs/middleware/loop-detection.md) | Design doc: LoopDetectionMiddleware (issue #5) |
| [`docs/benchmarks/terminal-bench.md`](docs/benchmarks/terminal-bench.md) | Terminal Bench 2.0 evaluation harness design (issue #6) |
| [`claw-forge.yaml`](claw-forge.yaml) | Annotated configuration reference |
| [`website/tutorial.html`](website/tutorial.html) | End-to-end getting started guide |
| [`website/features.html`](website/features.html) | Full feature list |

---

---

## Harness Design Patterns

`claw_forge.harness` is a small library implementing three patterns from Anthropic's research on long-running agent applications: **context resets**, **adversarial review**, and **strategic pivot**.

> [!IMPORTANT]
> **The library is not wired into `claw-forge run`.** Nothing in a run imports it, no `run` flag or config key turns any of these patterns on, and a run never resets a context, scores work adversarially, or makes a pivot decision. Use it from your own orchestration code, around agents you start yourself. The library calls no model: it holds the rules, you run the builder and reviewer agents and feed their output in.

What a run does instead: a retried task's prompt carries the previous attempt's commit subjects and error, plus the text of a `HANDOFF.md` in its worktree if the agent wrote one (read as plain text — `HandoffArtifact` is not involved). Verification in a run is the acceptance gate — see [Quality Gates](handbook/en/16-quality-gates.md).

### Context Resets

**Problem:** A long agent session eventually degrades on its own accumulated history ("context anxiety"), and may wrap up early to avoid losing context.

**Solution:** Count the builder's tool calls with `ContextResetManager`. When `record_tool_call()` returns `True`, save a structured `HANDOFF.md` and start a fresh builder from it. Starting that builder is yours to do.

```python
import tempfile
from pathlib import Path

from claw_forge.harness import ContextResetManager, HandoffArtifact

project = Path(tempfile.mkdtemp())
reset_mgr = ContextResetManager(project, threshold=80)   # a threshold below 10 is raised to 10

for call in range(1, 200):                  # one pass per tool call your agent makes
    if reset_mgr.record_tool_call():        # True once 80 calls have been recorded
        reset_mgr.save_handoff(
            HandoffArtifact(
                completed=["feat: auth (abc123)", "feat: database (def456)"],
                state=["src/auth.py — 150 lines", "tests/ — 85% coverage"],
                next_steps=["Add rate limiting", "Write API docs"],
                decisions_made=["Using SQLite for local dev"],
                quality_bar="6.5/10 — needs error handling",
            )
        )
        break

handoff = ContextResetManager(project).load_handoff()
print(call, handoff.next_steps)
```

Output:

```text
80 ['Add rate limiting', 'Write API docs']
```

**HANDOFF.md schema:**
- `## Completed` — Items done (with commit hashes for traceability)
- `## State` — Current codebase structure, test coverage, file counts
- `## Next Steps` — Ordered action items for the next builder
- `## Decisions Made` — Architectural decisions to avoid revisiting
- `## Quality Bar` — Current evaluator score, what needs improvement

### Adversarial Review

**Problem:** Agents are overly optimistic about their own work. Self-evaluation scores are inflated and vague praise ("looks good!") gives the next iteration nothing to act on.

**Solution:** Separate the generator from the evaluator. `AdversarialEvaluator` builds a skeptical, evidence-based reviewer prompt and turns the reviewer's JSON reply into a weighted verdict:

| Dimension | Weight | Focus |
|-----------|--------|-------|
| Correctness | ×3 | Bugs, edge cases, error handling |
| Completeness | ×3 | Missing features, unimplemented specs |
| Quality | ×2 | Maintainability, duplication, architecture |
| Originality | ×1 | Novel approaches, design choices |

```python
from claw_forge.harness import AdversarialEvaluator, GradingDimension

evaluator = AdversarialEvaluator(approval_threshold=7.0, dimensions=list(GradingDimension))
system_prompt = evaluator.get_system_prompt()   # hand this to YOUR reviewer agent

# The reviewer's reply is a JSON object of per-dimension scores, findings and a summary.
reply = (
    '{"dimensions": ['
    '{"dimension": "correctness", "score": 7, "reasoning": "bare except at src/auth.py:142"},'
    '{"dimension": "completeness", "score": 4, "reasoning": "rate limiting is missing"},'
    '{"dimension": "quality", "score": 7, "reasoning": "clean structure"},'
    '{"dimension": "originality", "score": 6, "reasoning": "standard OAuth2 flow"}],'
    ' "findings": ["BLOCKING: rate limiting missing"], "summary": "Incomplete."}'
)
result = evaluator.parse_llm_response(reply, iteration=1)
print(f"{result.overall_score:.1f}/10 -> {result.verdict}")
```

Output:

```text
5.9/10 -> request_changes
```

The prompt's features: "assume the code has bugs until proven otherwise", every score needs specific evidence (file names, line numbers, test names), generic praise is rejected, and a good and a bad example review calibrate the reviewer.

### Strategic Pivot

**Problem:** Agents can iterate endlessly on an approach that is not converging. Declining scores over several iterations signal that the direction is flawed.

**Solution:** `PivotTracker.decide()` records each evaluator score and applies three rules, in this order:

- **Score ≥ threshold (7.0)** → `APPROVE` — work meets the quality bar
- **The last 2 score changes are both declines** → `PIVOT` — abandon the approach, try something different
- **Anything else** (improving, or flat below the threshold) → `REFINE` — iterate with the evaluator's feedback

```python
from claw_forge.harness.pivot_decision import PivotAction, PivotTracker

tracker = PivotTracker(forced_pivot_streak=2, approval_threshold=7.0)

for iteration, score in enumerate([5.5, 6.2, 5.8, 5.1], start=1):
    decision = tracker.decide(score, iteration=iteration)
    print(iteration, score, decision.action.name)

print(decision.action == PivotAction.PIVOT)   # PivotAction lives in claw_forge.harness.pivot_decision
```

Output:

```text
1 5.5 REFINE
2 6.2 REFINE
3 5.8 REFINE
4 5.1 PIVOT
True
```

`tracker.log_to_plan("PLAN.md")` appends a `## Pivot Decision Log` section, one entry per iteration, with the score, the trend and the reasoning.

See [`docs/harness-patterns.md`](docs/harness-patterns.md) for the whole API, the `HANDOFF.md` and pivot-log formats, and an example that combines all three patterns, and the [`claw_forge.harness`](claw_forge/harness/) source.

---

## Benchmark Results

Ablation study on [claw-forge-bench](https://github.com/clawinfra/claw-forge-bench) — 30 Python coding tasks (easy / medium / hard), model: `claude-opus-4-6`.

> **An unreproduced historical claim.** Recorded 2026-03-13 (30 tasks × 5 configs, one model). The suite and its runner live in the external claw-forge-bench repository; this repository holds neither the runner nor a results file, so the numbers below cannot be checked from here and do not measure the current code. For whole-app measurement of claw-forge itself, see [AppBench](docs/benchmarks/appbench.md).

| Config | Middleware | Pass Rate | Δ vs Baseline |
|--------|-----------|----------:|---------------|
| A — baseline | none | 96.7% | — |
| B — hashline | hashline edit mode | 96.7% | +0.0pp |
| C — loop | loop detection | 96.7% | +0.0pp |
| D — verify | verify-on-exit | 96.7% | +0.0pp |
| **E — full stack** | **hashline + loop + verify** | **100%** | **+3.3pp** |

**Finding:** Individual middleware layers show no uplift in isolation. The combination of all three reaches **100%** — an interaction effect where each layer compensates for the others' blind spots.

**Recommended production stack:**
```bash
claw-forge run --edit-mode hashline --loop-detect-threshold 5 --verify-on-exit
```

→ [Full results + methodology](docs/benchmarks/results.md) · [Benchmark repo](https://github.com/clawinfra/claw-forge-bench)

---

## OpenClaw Agent Skill

claw-forge is available as an installable **OpenClaw agent skill** on [ClawHub](https://clawhub.com/skills/claw-forge-cli).
Any AI agent running on OpenClaw can use it to run the full claw-forge workflow autonomously.

```bash
clawhub install claw-forge-cli
```

See [`docs/agent-skill.md`](docs/agent-skill.md) for details on `--edit-mode hashline`,
the middleware stack, the claw-forge-bench ablation numbers, and how the skill integrates with OpenClaw.

---

## Frequently Asked Questions

**What happens if an agent fails mid-run?**
The task is re-queued under a budget that depends on why it failed: up to twice for an agent failure (`agent.agent_retry_attempts`, default 2), up to twice for an infrastructure failure such as a rate limit or a broken box (`agent.infra_retry_attempts`, default 2), and up to three times for a merge conflict (`git.merge_retry_attempts`, default 3). Each retry carries the previous error in its prompt. Other tasks in the same wave keep running — a single failure never halts the project. When a task's budget is spent it ends `failed`; tasks that depend on it are not dispatched and stay `pending` (nothing writes a `blocked` status), and `claw-forge status` reports them as stranded. Requeue with `claw-forge reset` or the Kanban UI's Reset All.

**Is my codebase safe with agents running on it?**
Several independent layers (see [Security](#security)) enforce safety. Each agent works in its own git worktree, never your main checkout. A `CanUseTool` callback confines every file tool to that worktree, and the Bash hook is a **denylist** — it blocks `sudo`, `dd`, `shutdown` and similar, recursive `rm` of protected roots, and host-wide `kill`/`pkill`, while a command that matches none of those is allowed. An OS-level jail (macOS `sandbox-exec`, Linux `bwrap`) backs the checks up at the syscall level. Note that `WebFetch` and `WebSearch` do not filter URLs — for network-restricted deployments, run claw-forge inside a container with egress rules.

**Can I use providers other than Anthropic?**
Yes, with one limit. The provider pool supports eight provider types — Anthropic, Claude OAuth, Anthropic-compatible third parties (Kimi, DeepSeek, GLM, …), AWS Bedrock, Azure AI, Google Vertex, any OpenAI-compatible endpoint, and local Ollama models — configure as many as you like in `claw-forge.yaml`; the pool rotates across them with automatic failover and per-provider circuit breaking. But `claw-forge run` drives the Claude CLI, so only `anthropic`, `anthropic_oauth` and `anthropic_compat` providers are picked to run an agent; the others serve direct pool requests only (see [Provider Pool](#provider-pool)).

**Can I add new features while a run is in progress?**
`claw-forge plan` (or `/expand-project` in Claude Code) reconciles new spec features against the existing session without touching completed tasks. New features land as `pending` and are picked up on the next run.

**Does it work with PostgreSQL?**
No — SQLite only. All state lives in one file, `.claw-forge/state.db` inside your project, and `plan`, `status`, `evidence` and `export` open that file directly, so the state service cannot be pointed at another database.

→ [Full FAQ — cost and time, fit, safety, parallelism, control](handbook/en/27-faq.md)

---

## License

Apache-2.0 · Built by [ClawInfra](https://github.com/clawinfra)

