Skip to content
AgenticAIWiki
  1. Capstones
  2. Capstone 3

Stateful multi-agent reviewer with an approval gate

A team of four agents (planner, investigator, fixer and critic) fixes seeded bugs in a small shop repo, using tools served over MCP, a SQLite checkpoint after every node and a human approval gate in front of every write. You build the graph engine first, then the tools, the agents, the gate, resume and memory, and finish by measuring resolved issues, unauthorised writes and resume.

A team of agents (planner, investigator, fixer, critic) that works on issues in a code repository or an ops log. Tools come from MCP servers, state is checkpointed so a run can resume, and nothing is written without a human approving it.

Try each milestone yourself first. Hints and the solution for each step are folded away until you open them. Everything runs offline with a built-in fake model, so you need no API key and spend no credits.

Architecture

Multi-agent reviewer with an approval gate

Full screen
issues_getIssue trackerMCP serverPlannerwhich files to read

Swipe to change step

Step 1 of 9. The planner fetches the issue from the tracker, which is an MCP server over stdio. It asks the model which files are worth reading. Issue tracker (MCP server). Planner (which files to read). arrow from Issue tracker to Planner, labelled issues_get. a issue moving along issues_get.

Set up

Clone the capstones repository to run the reference solution, or start an empty folder with the same layout to build it yourself. You need Python 3.11 or later and uv.

git clone https://github.com/gauthamboppana/agentic-ai-wiki-capstones.git
cd agentic-ai-wiki-capstones/multi-agent-reviewer
uv sync
uv run pytest -q
uv run python -m reviewer.cli demo
Lessons to finish first (13)

Milestone 1 of 6

Build the graph engine with a step guard

A tiny state graph runs nodes, follows conditional edges, saves a checkpoint after each node and always ends with a stop reason.

Steps

  1. Write a Graph class that stores nodes (functions that take the state and return updates) and edges, where an edge is either a node name or a router function.
  2. Write run(): call the current node, merge its updates into the state, append the node to a history list and ask the edge for the next node.
  3. Save a checkpoint after every node with the step number, the node that ran, the next node and the whole state.
  4. Before each node, check the step count against max_steps and stop with the reason max_iterations and a detail that names the limit.
  5. Let a node raise an Interrupt to pause the run, and record awaiting_approval as the stop reason.
Hint 1

Keep the state a plain dict of JSON-friendly values, so a checkpoint is just json.dumps(state).

Hint 2

Save the next node in the checkpoint, not only the last one: that is what resume needs.

Hint 3

The guard belongs in the loop, not in any one node, so it covers every path, including a fixer and critic that argue forever.

Hint 4 (strongest)

Return a RunResult with run_id, stop_reason, state, steps and trace. A run that reaches END without a reason gets 'completed'.

Checkpoint

uv run pytest -q tests/test_guard.py

2 passed: a looping fixer is stopped after 12 node runs with max_iterations, and a model with no idea gives up with gave_up.

Show solution src/reviewer/graph.py
    def run(self, state: dict, ctx: Any, *, run_id: str, checkpointer, start: str | None = None,
            step: int = 0, crash_after: str | None = None, hard_crash: bool = False) -> RunResult:
        node = start or self.entry
        trace: list[str] = []
        while node != END:
            if step >= self.max_steps:
                state["stop_reason"] = StopReason.MAX_ITERATIONS
                state["stop_detail"] = f"stopped after {step} node runs without finishing (limit {self.max_steps})"
                checkpointer.save(run_id, step, node, node, state, status="stopped")
                return RunResult(run_id, StopReason.MAX_ITERATIONS, state, step, trace)
            try:
                updates = self.nodes[node](state, ctx) or {}
            except Interrupt as stop:
                state["stop_reason"] = StopReason.AWAITING_APPROVAL
                state["stop_detail"] = stop.reason
                checkpointer.save(run_id, step, node, node, state, status="interrupted")
                return RunResult(run_id, StopReason.AWAITING_APPROVAL, state, step, trace, stop.payload)
            state.update(updates)
            step += 1
            trace.append(node)
            state.setdefault("history", []).append(node)
            nxt = self.next_node(node, state)
            status = "finished" if nxt == END else "running"
            checkpointer.save(run_id, step, node, nxt, state, status=status)
            if crash_after == node:
                if hard_crash:
                    os._exit(137)  # like kill -9: no cleanup, only the checkpoint survives
                raise SimulatedCrash(f"simulated crash after {node}")
            node = nxt
        reason = state.get("stop_reason") or StopReason.COMPLETED
        state["stop_reason"] = reason
        return RunResult(run_id, reason, state, step, trace)

The checkpoint is written after the state is updated and before the next node starts, so a crash at any point loses at most the node that was running. The guard saves a 'stopped' checkpoint too, so the reason survives the process.

Milestone 2 of 6

Serve the tools over MCP

Two stdio MCP servers, one for files and tests and one for the issue tracker, answer initialize, tools/list and tools/call.

Steps

  1. Wrap each tool as a name, a description, a JSON Schema for its inputs and a Python function.
  2. Read one JSON-RPC message per line from stdin and write one reply per line to stdout. Ignore notifications, which have no id.
  3. Answer initialize with the protocol version and server info, tools/list with every tool spec and tools/call by running the tool.
  4. Return tool failures as a result with isError set, so the agent sees them, and keep protocol errors for unknown methods.
  5. Write a client that starts each server as a subprocess, lists its tools and routes a call by tool name.
Hint 1

Flush stdout after every reply, or the client waits forever.

Hint 2

Resolve every path against the repo root and refuse anything outside it, so '../state.db' cannot be read.

Hint 3

Run the repo's tests with python -m unittest -v in a subprocess and parse the 'name (id) ... ok' lines into passed and failed lists.

Hint 4 (strongest)

Put the agent's tools behind one ToolBox.call(name, **args), so the agents never know which server answered.

Checkpoint

uv run pytest -q tests/test_mcp.py

2 passed: both servers list their tools, fs_read returns the file, a path escape comes back as a tool error and an unknown method gets error -32601.

Show solution src/reviewer/mcp_server.py
def handle(message: dict, tools: dict[str, Tool], name: str) -> dict | None:
    method, msg_id = message.get("method"), message.get("id")
    if msg_id is None:  # a notification, such as notifications/initialized: no reply
        return None
    if method == "initialize":
        result: Any = {"protocolVersion": PROTOCOL_VERSION, "capabilities": {"tools": {}},
                       "serverInfo": {"name": name, "version": "0.1.0"}}
    elif method == "tools/list":
        result = {"tools": [t.spec() for t in tools.values()]}
    elif method == "tools/call":
        params = message.get("params", {})
        tool = tools.get(params.get("name"))
        if tool is None:
            return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32602, "message": f"unknown tool {params.get('name')}"}}
        try:
            value = tool.fn(**params.get("arguments", {}))
            result = {"content": [{"type": "text", "text": json.dumps(value)}], "structuredContent": {"result": value},
                      "isError": False}
        except Exception as exc:  # tool errors go back to the model as results, not protocol errors
            result = {"content": [{"type": "text", "text": f"{type(exc).__name__}: {exc}"}], "isError": True}
    elif method == "ping":
        result = {}
    else:
        return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32601, "message": f"method not found: {method}"}}
    return {"jsonrpc": "2.0", "id": msg_id, "result": result}

Tool errors are results, not protocol errors, because the model should read them and try again. A refused write is just another tool error.

Milestone 3 of 6

Add the four agents and their edges

The planner, investigator, fixer and critic work an issue from the tracker to a passing test, retrying when the critic is not satisfied.

Steps

  1. Planner: fetch the issue, search memory for similar past fixes and ask the model which files to read.
  2. Investigator: record the passing tests once as a baseline, read the planned files, run the issue's tests and ask the model for the cause.
  3. Fixer: ask the model for find and replace edits, apply them in memory only, and build a unified diff of the change.
  4. Critic: run the issue's tests and the whole suite, compare with the baseline and pass only if both are clean.
  5. Join them with conditional edges: retry goes back to the investigator, and no edits ends the run with gave_up.
Hint 1

Give each node only what it needs in a payload, and keep live objects such as connections in a separate context that is never checkpointed.

Hint 2

Use a deterministic scripted model keyed on the issue id, so every test run takes the same path.

Hint 3

Let the code overrule the critic: if the tests fail, a 'pass' verdict from the model is ignored.

Hint 4 (strongest)

Seed at least one issue whose first fix is partial, so the retry edge is exercised.

Checkpoint

uv run pytest -q tests/test_resolved_issues.py

4 passed: all five issues resolved in order with one fewer failing test after each, two multi-file fixes, a recalled memory and a critic retry on ISSUE-3.

Show solution src/reviewer/agents.py
def critic(state: dict, ctx: Ctx) -> dict:
    target = ctx.tools.call("tests_run", tests=state["issue"]["tests"])
    suite = ctx.tools.call("tests_run")
    regressions = sorted(set(state["baseline_passed"]) - set(suite["passed"]))
    verdict = ctx.model.decide("critic", {"issue": state["issue"], "failed": target["failed"],
                                          "regressions": regressions, "diff": state["proposal"]["diff"]})
    passed = verdict["verdict"] == "pass" and target["ok"] and not regressions  # code has the final word
    if passed:
        return {"verdict": "pass", "lesson": verdict.get("lesson", ""), "suite_passed": len(suite["passed"])}
    return {"verdict": "retry", "attempt": state["attempt"] + 1, "feedback": verdict.get("feedback", "tests still fail")}


def finish(state: dict, ctx: Ctx) -> dict:
    issue = state["issue"]
    ctx.memory.add(issue["id"], issue["title"] + " " + issue["body"], state["written"], state["lesson"])
    ctx.tools.call("issues_close", id=issue["id"], resolution=state["lesson"])
    return {"stop_reason": StopReason.RESOLVED}


def build_graph(max_steps: int = 20) -> Graph:
    g = Graph(entry="planner", max_steps=max_steps)
    for name, fn in [("planner", planner), ("investigator", investigator), ("fixer", fixer), ("gate", gate),
                     ("writer", writer), ("critic", critic), ("finish", finish)]:
        g.add_node(name, fn)
    g.add_edge("planner", "investigator")
    g.add_conditional_edges("investigator", lambda s: END if s.get("stop_reason") else "fixer")
    g.add_conditional_edges("fixer", lambda s: "gate" if s["proposal"] else (END if s.get("stop_reason") else "investigator"))
    g.add_conditional_edges("gate", lambda s: END if s["decision"] == "reject" else "writer")
    g.add_edge("writer", "critic")
    g.add_conditional_edges("critic", lambda s: "finish" if s["verdict"] == "pass" else "investigator")
    g.add_edge("finish", END)
    return g

Regressions are measured against a baseline taken before any change, so a fix that breaks another test is never passed.

Milestone 4 of 6

Put an approval gate before every write

Nothing reaches the repository unless a reviewer approved, edited or rejected the exact diff, and every write is checked against that record.

Steps

  1. Add a gate node between the fixer and a separate writer node, and route a rejection straight to END.
  2. Ask an approval policy for a decision: approve, edit or reject. A policy that returns nothing raises an Interrupt and the run pauses.
  3. Record an approval row per file with the decision, who made it and the SHA-256 of the approved content.
  4. Make fs_write demand an approval id, and refuse it in the server if the record is missing, a rejection, for another path, for other content or already used.
  5. Write an audit that matches every write to an approval and every changed file to its last approved write.
Hint 1

Check approvals in the tool server, not in the agent: then even a buggy or misled agent cannot write.

Hint 2

A one-use approval stops a replayed write.

Hint 3

Comparing files on disk with the seed catches writes that went round the server altogether.

Hint 4 (strongest)

On resume, skip a write whose content is already on disk, so a crash between writes never needs a second approval.

Checkpoint

uv run pytest -q tests/test_approvals.py

6 passed: zero unauthorised writes, a rejected fix leaves the file and the write log untouched, an edited fix writes the reviewer's text, and forged or reused approvals are refused.

Show solution src/reviewer/agents.py
def gate(state: dict, ctx: Ctx) -> dict:
    """The interrupt before any write. Nothing reaches the filesystem without a decision recorded here."""
    proposal = state["proposal"]
    pending = state.get("pending_decision")
    decision = Decision.from_dict(pending) if pending else ctx.policy.decide(proposal)
    if decision is None:
        raise Interrupt("waiting for a reviewer to approve, edit or reject", {"diff": proposal["diff"]})
    write_set, approvals = {}, []
    for path, after in proposal["after"].items():
        content = decision.edited.get(path, after) if decision.action == "edit" else after
        approval_id = ctx.ledger.record(ctx.run_id, state["issue_id"], path, decision, proposal["before"][path], content)
        approvals.append({"id": approval_id, "path": path})
        write_set[path] = content
    updates = {"decision": decision.action, "pending_decision": None, "approvals": approvals}
    if decision.action == "reject":
        ctx.tools.call("issues_comment", id=state["issue_id"], text=f"fix rejected: {decision.reason}")
        return {**updates, "write_set": {}, "stop_reason": StopReason.REJECTED}
    return {**updates, "write_set": write_set}


def writer(state: dict, ctx: Ctx) -> dict:
    for a in state["approvals"]:
        content = state["write_set"][a["path"]]
        if ctx.tools.call("fs_read", path=a["path"]) != content:  # skip writes already done before a crash
            ctx.tools.call("fs_write", path=a["path"], content=content, approval_id=a["id"])
    return {"written": sorted(set(state.get("written", [])) | set(state["write_set"]))}

The decision is stored in the state before the gate runs again, so a paused run can be answered from another process. The writer only sends approved content with its approval id.

Milestone 5 of 6

Checkpoint, resume and remember

A run killed mid-way continues from its last checkpoint, and resolved issues become memories the planner can recall.

Steps

  1. Store checkpoints in SQLite, one row per node run, keyed by run id and step.
  2. Write resume(run_id): load the latest checkpoint, return at once if it finished, and otherwise continue from its next node with its state and step count.
  3. Accept an optional decision on resume, for a run paused at the gate.
  4. In the finish node, add the issue, the files changed and the critic's lesson to an episodic memory table.
  5. In the planner, retrieve the closest past fixes by word overlap and pass them to the model.
Hint 1

Test with a real kill: a subprocess that calls os._exit right after a checkpoint, with no clean-up.

Hint 2

Clear the old stop reason before resuming, or the run looks finished.

Hint 3

Keep memory retrieval simple and explainable: shared words, a minimum overlap and the top two.

Hint 4 (strongest)

Swap word overlap for embeddings later without changing the planner.

Checkpoint

uv run pytest -q tests/test_resume.py

5 passed: a process killed after the writer resumes at the critic and finishes with no repeated writes, and crashes after planner, fixer and gate all resume.

Show solution src/reviewer/app.py
    def _go(self, run_id: str, state: dict, **kw) -> RunResult:
        with ToolBox.start(self.repo, self.db) as tools:
            ctx = Ctx(tools, self.model, self.policy, self.memory, self.ledger, run_id)
            return self.graph.run(state, ctx, run_id=run_id, checkpointer=self.checkpoints, **kw)

    def run(self, issue_id: str, crash_after: str | None = None, hard_crash: bool = False) -> RunResult:
        run_id = f"{issue_id}-{uuid.uuid4().hex[:6]}"
        return self._go(run_id, {"issue_id": issue_id}, crash_after=crash_after, hard_crash=hard_crash)

    def resume(self, run_id: str, decision: Decision | None = None, crash_after: str | None = None) -> RunResult:
        """Continue a run from its last checkpoint. A decision answers a run paused at the approval gate."""
        cp = self.checkpoints.latest(run_id)
        if cp is None:
            raise KeyError(f"no checkpoints for run {run_id}")
        state = cp.state
        if cp.status in ("finished", "stopped"):
            return RunResult(run_id, state.get("stop_reason", "completed"), state, cp.step)
        if decision is not None:
            state["pending_decision"] = decision.to_dict()
        state.pop("stop_reason", None)
        state.pop("stop_detail", None)
        return self._go(run_id, state, start=cp.next_node, step=cp.step, crash_after=crash_after)

Resume only needs the run id: the checkpoint holds the state and the next node, and the tool servers are started fresh, because live connections are never part of the state.

Milestone 6 of 6

Measure the acceptance targets

One command runs every target on a fresh copy of the repo and prints resolved issues, unauthorised writes, resume and the guard.

Steps

  1. Run all five seeded issues in order and count those resolved, printing the suite after each.
  2. Audit the ledger and the repo, including a run where every change is rejected.
  3. Kill a real run after the writer node, resume it in this process and print where it carried on.
  4. Run a looping fixer with a low step limit and print the stop reason.
  5. Print one line per target and ALL TARGETS MET only when every one holds.
Hint 1

Use a temporary directory for every run, so the demo never touches the seeded repo.

Hint 2

Start the killed run with stdin closed and auto approval, so it cannot hang on a prompt.

Hint 3 (strongest)

Keep the tests and the demo on the same numbers, so the README report stays true.

Checkpoint

uv run pytest -q

19 passed, and the demo prints 5/5 resolved, 0 unauthorised writes, a resume after exit code 137 and max_iterations, then ALL TARGETS MET.

Show solution src/reviewer/approval.py
def audit(ledger: Ledger, repo: Path, seed: Path) -> dict:
    """Check every write against an approval, and every changed file against the last approved write.

    The second check catches writes that bypassed the tool server altogether.
    """
    approvals = {a["id"]: a for a in ledger.approvals()}
    problems = []
    last_written: dict[str, str] = {}
    for w in ledger.writes():
        a = approvals.get(w["approval_id"])
        if a is None or a["action"] not in ("approve", "edit") or a["path"] != w["path"] or a["sha_after"] != w["sha256"]:
            problems.append(f"write to {w['path']} has no matching approval")
        last_written[w["path"]] = w["sha256"]
    for f in sorted(p for p in repo.rglob("*") if p.is_file() and "__pycache__" not in p.parts):
        rel = f.relative_to(repo).as_posix()
        now = sha256(f.read_text(encoding="utf-8"))
        original = seed / rel
        if original.exists() and sha256(original.read_text(encoding="utf-8")) == now:
            continue
        if last_written.get(rel) != now:
            problems.append(f"{rel} changed without an approved write")
    rejected = [a for a in approvals.values() if a["action"] == "reject"]
    return {"writes": len(ledger.writes()), "approvals": len(approvals), "rejected": len(rejected),
            "unauthorised": len(problems), "problems": problems}

The audit has two halves: every logged write must match an approval, and every changed file must match its last logged write. The second half catches changes made without the tool server.

Acceptance targets

Resolved issues
multi-file issues fixed end to end on a test repoRun on at least five seeded issues; tests pass after each fix.
Unauthorised writes
zeroAudit every write against an approval record.
Resume
a killed run resumes from its last checkpointStop the process mid-run, restart, and show it continues.

Stretch: Stream the graph's events to a small UI so a reviewer can watch and step in.

Back to all capstones