> ## Documentation Index
> Fetch the complete documentation index at: https://docs.trykode.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Automate Code Tasks with Kode Loop Mode

> Kode Loop runs the full Plan→Generate→Verify→Apply→Test pipeline end-to-end, with automatic rollback if tests fail and optional Ghost Branch parallel strategies.

`kode loop` is the highest-autonomy command in Kode's toolkit. Where `kode run` stops after applying verified patches, `kode loop` continues through a fifth stage: it executes your test suite, and if tests fail it atomically rolls back every change that was applied in that cycle. Optionally, you can ask Kode to explore the task across multiple parallel Ghost Branch worktrees and automatically merge the best-scoring strategy.

## What `kode loop` does differently from `kode run`

`kode run` covers three stages: Generate → Verify → Apply. `kode loop` adds two more:

| Stage                     | `kode run` | `kode loop`           |
| ------------------------- | ---------- | --------------------- |
| Generate patches via LLM  | ✓          | ✓                     |
| Verify hunks through gate | ✓          | ✓                     |
| Apply verified hunks      | ✓          | ✓                     |
| Run test suite            | —          | ✓                     |
| Rollback on test failure  | —          | ✓                     |
| Ghost Branch parallelism  | —          | ✓ (with `--branches`) |

If your test suite passes after apply, the run exits with status `PASS` and prints a JSON summary to stdout. If the tests fail, Kode restores the repository to the exact snapshot it took before applying — your working tree is left clean.

## Basic usage

```bash theme={null}
kode loop "implement user deletion endpoint"
```

Kode auto-detects your test command from the project root (Go → `go test ./...`, Node → `npm test`, Rust → `cargo test`). You can override this with `--test-command`.

## All flags

| Flag             | Description                                                              | Default                   |
| ---------------- | ------------------------------------------------------------------------ | ------------------------- |
| `--branches N`   | Spawn N parallel Ghost Branch worktrees, each using a different strategy | `1` (no Ghost mode)       |
| `--model`        | LLM model override                                                       | from `kode.json`          |
| `--context-file` | Path to context packet JSON from `kode plan --packet`                    | none                      |
| `--test-command` | Test command override                                                    | auto-detected             |
| `--project-dir`  | Project root directory                                                   | current working directory |

## Ghost Branch mode

When you pass `--branches` with a value greater than `1`, Kode forks the task across N isolated git worktrees running simultaneously. Each worktree applies a different generation strategy:

* **Alpha** — lightweight, minimal implementation (smallest surface area)
* **Beta** — robust, modular architecture (well-structured, dependency-aware)
* **Gamma** — performance-optimised, aggressive (throughput and latency first)

After all branches complete, Kode scores each result on three dimensions — blast radius (files touched), token cost, and wall-clock speed — then merges the winner into your working tree and discards the rest.

```bash theme={null}
kode loop --branches 3 "refactor the payment service"
```

Example output:

```
── Ghost Branch Mode ────────────────────────────────
  Task: refactor the payment service
  Branches: 3 strategies in parallel
  LLM: anthropic/claude-sonnet-4-6

  [+] alpha (Alpha) — PASS — Score: 0.87 — WINNER
  [x] beta  (Beta)  — PASS — Score: 0.74
  [!] gamma (Gamma) — FAIL — Score: 0.00
      Error: test failure: TestPaymentService/Refund

✓ Winner: alpha (Alpha) — score 0.87
  Total: 18.3s | $0.0042 token cost
```

<Note>
  Using `--branches 2` enables two-strategy mode (Alpha + Beta only). Three strategies (the maximum) give the broadest exploration but roughly triple token cost. Start with `--branches 2` and graduate to `--branches 3` for complex refactors.
</Note>

## Rollback behaviour

If the test suite fails after apply, Kode reverts all changes atomically before exiting. The revert is performed via the internal snapshot mechanism — it does not create a git commit or modify your git history. Your working tree is returned to exactly the state it was in before `kode loop` ran.

The JSON output on a failed run includes the test error message:

```json theme={null}
{
  "status": "FAIL",
  "task": "implement user deletion endpoint",
  "hunks_applied": 3,
  "test_error": "FAIL\tgithub.com/example/api [build failed]",
  "duration_seconds": 9.4
}
```

<Warning>
  Loop mode requires a clean git working tree before running. If you have uncommitted changes, Kode will refuse to start — it cannot safely snapshot a dirty tree. Stash or commit your work-in-progress first.
</Warning>

## Combining `kode plan` with `kode loop`

For large or complex tasks, pre-building the context packet with `kode plan --packet` separates the slow graph-construction step from the generation step. This is especially valuable in Ghost Branch mode, where all three branches would otherwise each build their own context independently.

```bash theme={null}
# Step 1: build the context packet once
kode plan --packet "refactor auth module" > context.json

# Step 2: run the loop with the pre-built context, 3 branches
kode loop --context-file context.json --branches 3 "refactor auth module"
```

The `--context-file` flag accepts the JSON output of `kode plan --packet`. Kode skips the plan stage entirely and passes the packet directly into the generate stage for every branch.

<Tip>
  You can inspect the context packet before using it with `cat context.json | jq '.nodes | length'` to see how many AST nodes were included. If the number is unexpectedly low, check that the files relevant to your task are tracked in git and that the 8 000-token budget (configurable with `kode plan --max-tokens`) was not exhausted too early.
</Tip>

## Configuring the test command

Kode auto-detects the right test command from your project root, but you should configure it explicitly in `kode.json` for reproducible results:

```json theme={null}
{
  "engine": {
    "test_command": "go test -race ./..."
  }
}
```

Or pass it per-invocation with `--test-command`:

```bash theme={null}
kode loop --test-command "make test-integration" "add rate limiting middleware"
```

## Next steps

<CardGroup cols={2}>
  <Card title="Code Golf" icon="gauge-high" href="/guides/code-golf">
    Pit three optimization strategies against each other in parallel and benchmark the winner automatically.
  </Card>

  <Card title="First Task" icon="rocket" href="/guides/first-task">
    New to Kode? Start here to initialize your project and run your first task.
  </Card>
</CardGroup>
