Skip to main content
Glama
README.md
# loop-engine

A deterministic loop engine for AI coding agents. It keeps a dependency-ordered milestone plan in a local `bun:sqlite` database, runs your project's gate commands (typecheck, tests, lint) as real subprocesses, and refuses to mark a milestone done until those gates pass. An MCP server exposes the engine to Claude Code, Cursor, Windsurf, or any other MCP client.

The engine makes no LLM calls and needs no API keys or network. Your coding agent does the planning and writes the code. The engine records what happened, runs commands, and enforces the rules.

## Why

An agent working alone does one pass and stops. It forgets everything between sessions and reports "the tests should pass" without running them. loop-engine adds the missing structure around the agent:

- **Milestones form a DAG.** By default each milestone depends on the one before it. Work on a milestone is refused while any prerequisite is unfinished.
- **Gates decide pass or fail, not the agent.** A gate is a shell command from `loop-engine.json`. Exit code 0 is a pass, anything else is a failure, and the real output is recorded.
- **`done` requires evidence.** A milestone can only be marked done when it has at least one recorded iteration, every blocking gate has run and passed on its latest run, and its `validateCommand` (if it has one) has passed. There is no override flag.
- **Iterations are capped.** When a milestone hits `maxIterations`, the engine tells the agent to stop and ask the human instead of retrying.
- **State survives sessions.** Everything lives in `.loop-engine/loop.db`, and `loop_resume` gives a fresh session the goal, progress, last failure, and recorded decisions.
- **Memory prevents rebuilds.** Finishing a milestone records a `built` memory, and `loop_preflight` searches those before new work starts.

## Milestone lifecycle

```
pending ──checkpoint──▶ active ──gates fail──▶ blocked
   │                      │  ▲                   │
   │                      │  └───gates pass──────┘
   │                      └──done (evidence)──▶ done
   └────────────skip (reason)─────────────────▶ skipped
```

A dependency counts as satisfied when it is `done` or `skipped`. Leaving out `dependsOn` means the milestone depends on the previous one in the plan. `dependsOn: []` marks a milestone as independent. Cycles are rejected when the plan is set.

## Packages

| Path | Package | Description |
|------|---------|-------------|
| `packages/loop-core` | `@loop-engine/core` | The engine: `LoopEngine`, `StateStore` (SQLite), gate runner, config loader |
| `apps/mcp` | `@loop-engine/mcp` | stdio MCP server (bin `loop-engine-mcp`) that exposes the engine as 14 tools |

## Requirements

- [Bun](https://bun.sh/) 1.3+. The engine uses `bun:sqlite` and runs on Bun only, not Node.

## Quickstart

```bash
git clone https://github.com/7vignesh/loop-engine.git
cd loop-engine
bun install
bun run build       # builds packages/loop-core, then apps/mcp
bun test            # all tests
```

Then add a `loop-engine.json` to the project you want an agent to work on:

```json
{
  "version": 1,
  "gates": {
    "typecheck": { "command": "npx tsc --noEmit", "order": 10 },
    "test": { "command": "npm test", "order": 20 },
    "lint": { "command": "npx eslint . --quiet", "order": 30, "blocking": false }
  },
  "maxIterations": 10
}
```

- A gate's value can be a bare command string (`"test": "npm test"`) or an object with `command`, `timeoutMs` (default 120000), `order` (default 100), and `blocking` (default `true`).
- Non-blocking gates are recorded but never stop a milestone from finishing.
- The config is found by walking up from the starting directory. Without a config, the engine runs with no gates. In that case `loop_gate` reports that nothing is configured, and only milestones with a `validateCommand` need proof before they can finish.

Add `.loop-engine/` to that project's `.gitignore` unless you want to commit loop state.

## MCP client setup

The server speaks MCP over stdio. It picks the project root from, in order: the `--project <dir>` flag, the `LOOP_ENGINE_PROJECT_ROOT` environment variable, then its working directory. Diagnostics go to stderr, because stdout carries the protocol.

**Claude Code**

```bash
claude mcp add loop-engine -- bun /abs/path/to/loop-engine/apps/mcp/dist/server.js --project /abs/path/to/your-project
```

**Cursor** (`.cursor/mcp.json`), **Windsurf**, and other clients that use the `mcpServers` format:

```json
{
  "mcpServers": {
    "loop-engine": {
      "command": "bun",
      "args": [
        "/abs/path/to/loop-engine/apps/mcp/dist/server.js",
        "--project",
        "/abs/path/to/your-project"
      ]
    }
  }
}
```

For development, you can run `apps/mcp/src/server.ts` instead of `dist/server.js` to skip the build step.

| Variable | Effect |
|----------|--------|
| `LOOP_ENGINE_PROJECT_ROOT` | Project root, used when `--project` is not passed |
| `LOOP_ENGINE_DB_PATH` | Overrides the database location (default `<project>/.loop-engine/loop.db`) |

## MCP tools

| Tool | Purpose |
|------|---------|
| `loop_start` | Start a loop for a goal, optionally with its milestone plan |
| `loop_plan` | Replace the plan. Refuses to drop milestones that already have recorded work |
| `loop_status` | Goal, milestones, current milestone, iteration count, gate state |
| `loop_resume` | Catch-up for a new session: goal, progress, last failure, decisions |
| `loop_preflight` | Search recorded work for names you are about to create: `UNBUILT`, `PARTIAL`, or `BUILT` |
| `loop_checkpoint` | Record one pass of work. Enforces dependencies and the iteration cap |
| `loop_gate` | Run configured gates (optionally a subset) and record exit codes and output |
| `loop_validate` | Run the milestone's own `validateCommand` |
| `loop_done` | Mark a milestone done. Refused without evidence |
| `loop_skip` | Skip a milestone, with a recorded reason |
| `loop_remember` | Store a decision, fact, pattern, built capability, or gotcha |
| `loop_recall` | Full-text search over stored memories |
| `loop_history` | Iteration log and gate-run history for a milestone |
| `loop_pause` | Pause the active loop and keep its state |

No tool accepts a shell command. Callers can only name gates that already exist in `loop-engine.json`, so a prompt-injected agent cannot use the server to run arbitrary commands.

## Benchmarks

`bun run bench` runs `bench/loop-bench.ts` offline against real WAL-mode SQLite files. It times the state layer only. Gate commands are recorded as results without being spawned, so your own typecheck and test time is not included. Raw data, including the environment, is in [`bench/results/loop-bench.json`](./bench/results/loop-bench.json).

One run on win32 10.0.26300 · x64 · 11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz (8 threads) · Bun 1.3.0, SQLite 3.50.4, at 2026-11-29T12:01:25.782Z:

| Measurement | n | p50 (ms) | p95 (ms) | mean (ms) |
|---|---:|---:|---:|---:|
| Checkpoint (iteration commit) | 500 | 3.587 | 5.761 | 3.790 |
| Gate-run record | 500 | 0.869 | 1.503 | 0.946 |
| markDone (evidence check + commit + memory) | 500 | 2.854 | 5.008 | 3.175 |
| **Full milestone transition** | 500 | 7.440 | 11.538 | 7.910 |
| resolveDependencies (50 milestones, 76 edges) | 500 | 0.091 | 0.147 | 0.095 |
| Topological sort (50 milestones) | 500 | 0.070 | 0.113 | 0.070 |
| Next-milestone query (on disk) | 50 | 0.224 | 0.366 | 0.229 |
| Cold open + migrate | 100 | 0.646 | 1.152 | 0.695 |
| resume() | 100 | 6.030 | 9.860 | 6.693 |
| **Cold crash-recovery resume (total)** | 100 | 6.704 | 10.932 | 7.387 |

DAG scheduling throughput (resolve + topological sort): 6045 schedules/s. Persisting the 50-milestone plan: 2.886 ms.

What each row measures:

- **Full milestone transition** is `checkpoint`, then a gate-run record, then `markDone`, measured for each of 50 milestones over 10 complete runs of the plan. Every step is a durable SQLite commit.
- **resolveDependencies** and **Topological sort** run on a fixed 50-milestone, 76-edge DAG (5 layers, fan-in 1 to 3), 500 times each after 50 warmup runs. They are in-memory, pure CPU.
- **Next-milestone query** is the on-disk `getCurrentMilestone` lookup after each completion.
- **Cold crash-recovery resume** starts with a database where 25 of 50 milestones are done and one is blocked, left unclosed to simulate a crash. Each sample opens a new connection, runs the migration check, and calls `resume()`, 100 times after 5 warmup runs.

Results vary between runs on the same machine. Three back-to-back runs here gave full-transition p50 of 7.440, 6.399 and 6.050 ms, and cold-resume p50 of 6.704, 4.061 and 3.874 ms. The table above is the first of those runs, the one stored in `bench/results/loop-bench.json`. Run `bun run bench` on your own hardware for numbers that apply to you.

## Development

```bash
bun run typecheck   # builds loop-core (mcp imports its types), then tsc --noEmit for both
bun test            # every test in the workspace
bun run build       # tsc for loop-core, then mcp
```

CI (`.github/workflows/ci.yml`) runs the same commands on `ubuntu-latest` for every pull request and every push to `main`.

## History

This code was extracted from [`7vignesh/stackforge`](https://github.com/7vignesh/stackforge) (branch `feat/loop-engine` at `51f4bd5`), keeping the original commits. [`ARCHITECTURE.md`](./ARCHITECTURE.md) describes the current design. [`docs/HANDOFF.md`](./docs/HANDOFF.md) holds the original design notes. It predates the rename, so it uses StackForge names.

## License

[MIT](./LICENSE)