TLTan LeAI, cloud & automation for legacy systems · CalgaryLet’s talk
← All posts

The AI agent team on a real codebase: what I had to move from prompts into code

A Leader and five subagents taking Notion tickets to pushed branches in a .NET support-agent repo. What carried over from the toy demo, what broke on the first real ticket, and the three rules I moved out of prompts into a hook, a workflow script and an area map.

1 + 5Leader and subagents
2Full SDD tickets shipped
77 → 82tests after the second ticket

Last time I split a Leader, a Worker and a Reviewer across a word-counter script and worked out the rules that keep them from stepping on each other. I ended with a promise: I would write up the next version once I had run it on a real codebase rather than a toy.

This is that write-up. The codebase is TicketShine.SupportAgent, the .NET 10 sample where an AI drafts customer-support replies and a person approves them. It has an MCP server, a SQLite database, a review gate and an outbox. A careless change there sends the wrong email to a customer. The team now takes a Notion ticket to a pushed branch with PR text, and I only step in at a few gates.

The short version: the rules from the toy demo held up. But on a real ticket the rules that mattered most did not stay in prompts. One became a hook, one became a script, and one became a lookup table.

At a glance
Repotanldt/TicketShine.SupportAgent, plugin in plugins/tssupport-developer/
Runs inClaude Code, as a plugin: one skill for the Leader, five subagent definitions, a hook, a workflow script
TicketsNotion Tasks database, through the Notion MCP server
Tickets so farOne Lightweight docs fix, two Full SDD changes to the database layer
Tests./scripts/test.ps1 (xUnit), 77 after the first Full SDD ticket, 82 after the second

From the toy to the real thing

Every rule from the demo is still here. Most of them got stricter.

In the toy demoIn the real repo
I wrote SPEC.md by handA Spec agent drafts spec.md from the Notion ticket; I approve a numbered revision
Three rolesA Leader plus five subagents: Spec, Planner, Worker, Reviewer, QA
Agents wrote into their own sections of STATUS.mdOnly the Leader writes STATUS.md. Subagents return a Report block and the Leader copies it in
The Reviewer had Edit to write its verdictThe Reviewer has Read, Grep, Glob, Bash. It returns review.md as text, and the Leader saves it
“Tests pass” was the evidenceThe Reviewer re-runs the tests; a QA agent also runs the real app and checks each acceptance criterion
“You do not write code” was a line in the Leader’s promptA PreToolUse hook blocks the Leader from changing src/ or tests/
“At most 2 QA rounds” was a line in the Leader’s promptThe loop is a workflow script that the Leader calls

The second-to-last row fixes the weak spot I admitted in the last post: the Reviewer could still edit code because it needed Edit for its verdict. Now no read-only role has a write tool at all. They return text, and only the Leader writes files.

The team

flowchart TD
  H([Me: approve at the gates]) <--> L[Leader<br/>start-ticket skill]
  N[(Notion ticket)] --> L
  L --> S[Spec agent<br/>read-only]
  L --> P[Planner<br/>read-only]
  L --> W[[implement-review workflow]]
  W --> WK[Worker<br/>edits src/ and tests/]
  W --> R[Reviewer<br/>read-only, re-runs tests]
  W --> Q[QA<br/>runs the app on port 5091]
  G{{leader-guard hook}} -. blocks Leader edits .-> L
RoleWritesReturns
LeaderSTATUS.md, approved spec and plan, saved review and QA reports, git, NotionMessages at the gates
Specnothingspec.md draft with FR, QR and AC IDs, plus open questions
Plannernothingplan.md with an area and a validation for every step
Workersrc/, tests/, validation.mdWhat it changed and the test result. It never commits
Reviewernothingreview.md, starting with Decision: PASS or FAIL
QAevidence files under .codex/logs/ onlyqa.md, starting with Decision: PASS or FAIL

Each agent is a short Markdown file in the plugin’s agents/ folder. The tools: line still does most of the work:

---
name: tssupport-code-reviewer
description: Reviews a TicketShine.SupportAgent diff against its approved spec
  and the review policy, re-runs tests, and returns review.md content with
  Decision PASS or FAIL. Never edits code.
tools: Read, Grep, Glob, Bash
skills: tssupport-code-reviewer
---

Re-run ./scripts/test.ps1 yourself; the coding agent's output is a claim,
not evidence. Check every domain blocker explicitly.

I talk only to the Leader. It stops at five places and nowhere else:

StopWhenMy reply
G0The ticket is Blocked by something not finishedproceed, wait or switch
G1The spec is readyApprove spec revision N
G2The plan is readyApprove plan
G3Review and QA passedShip (then it commits, pushes and moves the Notion ticket to In review)
ESCStill failing after two fix rounds, or the spec turned out wrongMy decision

An auto flag lets the Leader approve the spec and plan itself, but only for low-risk tickets. More on what “low-risk” means below.

Not every ticket gets the whole team

Before anything else, the Leader sorts the ticket into one of three levels. I took this from the plugin I built for a legacy WebForms app, and it matters more here because the team is bigger.

LevelWhenWhat runs
Quick answerA read-only questionThe Leader answers. No branch
LightweightLocal, reversible, no behavior changeWorker, then Reviewer against the ticket text. No spec, no plan, no QA
Full SDDEverything else, and always for MCP tools, the review gate, the outbox, email auth and secretsAll of it

The first ticket, SUP-3, was a one-paragraph docs fix. It went Lightweight: a branch, a review that passed against the ticket text, PR text, done. Running six agents on it would have been silly.

The first real ticket: SUP-4

SUP-4 asked for a schema version and ordered migrations in the SQLite database. That is persistence code next to the approve-and-send path, so it went Full SDD, in gated mode.

This is Claude Code’s agent map for that run. The Leader sits on the left. Each box on the right is a subagent with its own context, and each one did exactly one job:

Claude Code agent map for the SUP-4 run: the Leader (SUP-4 ticket-to-PR workflow, Opus 5.5, 196.1k tokens in context) with five subagents. Draft SUP-4 spec 3m 51s, 77.7k tokens. Plan SUP-4 3m 41s, 82.6k tokens. Implement SUP-4 11m 40s, 179.1k tokens. Review SUP-4 round 0 4m 30s, 90.0k tokens. QA SUP-4 in running app 5m 42s, 114.6k tokens.

AgentTimeTokens
Spec3m 51s77.7k
Plan3m 41s82.6k
Implement11m 40s179.1k
Review, round 04m 30s90.0k
QA in the running app5m 42s114.6k
Subagents in total29m 24s544.0k

Implementation took the longest, which is expected. More interesting is that checking the work (review plus QA, about 10 minutes and 205k tokens) took almost as long as writing it, and used more tokens. That is the price of not letting the Worker grade its own homework, and I think it is the right price.

What went to plan:

  • The Spec agent read the repository code and came back with 9 functional requirements, 8 quality requirements and 10 acceptance criteria. It also listed 6 open questions, each with a proposed default.
  • I gave a conditional plan approval: approve it if it only touches files the spec names, plus tests and docs. The Planner’s 17-step plan added two source files the spec did not name: a new SchemaMigrations.cs and an InternalsVisibleTo line in a .csproj. The Leader checked, saw the condition failed, and stopped at G2 instead of going ahead. I approved it after reading why.
  • The Worker added the migration code and a new test class, updated six docs, and wrote validation.md. It claimed 77 of 77 tests passing.
  • The Reviewer did not take that on trust. It re-ran the suite (77/77), ran the new migration tests six times to check they were stable, and compared a frozen copy of the old schema with the new one. PASS in round 0, with notes only.
  • QA started the app on port 5091 with its own databases and checked six of the ten acceptance criteria in the running app, plus eight regression scenarios (approving a stale draft version, a prompt injection in a case note, a spoofed sender, and so on). PASS.

I said Ship. The Leader committed 15 files, pushed the branch, set the Notion ticket to In review and added one comment with the branch and the spec folder.

What went wrong

Three things, none in the product code. All three were in the process around it.

I changed the team in the middle of the ticket. While SUP-4 was in review, I merged the pull request that added the QA role to the plugin. The Leader noticed that the working tree had been switched to master and fast-forwarded under it. It moved the feature branch onto the new commit and carried on, which was the right call. But the QA subagent type did not exist in the running session, because plugins load at session start. The Leader worked around it by giving a general-purpose agent the QA instructions with read-only rules. It worked. I would not rely on it.

QA touched my database. QA is supposed to run on port 5091 with its own database, so my demo on port 5080 stays clean. On its first start the app came up on the right port, but the database path override did not take, so for a few seconds the new build ran against my default support.db. QA reported it as an incident, and the Leader checked the file read-only afterwards: the only change was the additive version stamp. Harmless this time. The QA instructions already gave the exact launch command, and it still went wrong once. “Run in isolation” is a config detail, and an agent can get a config detail wrong. The check I want next is for QA to confirm which database file is open before it drives the app.

My own approval was looser than my own rule. The contract says approval is an explicit Approve spec revision 1, and that “ok” or “looks good” does not count. When the Leader showed me the six open questions, I replied “go with them”. It recorded that as approval of the spec with the defaults. That was what I meant. But the rule exists so that nobody approves a spec by accident, and I broke it in the first real ticket.

Three rules I moved out of prompts

The day after SUP-4 I made three changes to the plugin. They have the same idea behind them. A rule that lives only in a prompt holds until the moment it is inconvenient, so the rules that guard real damage should live somewhere the agent cannot argue with.

1. A hook for “the Leader does not write code”

In the toy demo this was one line in the Leader’s prompt. Now it is a PreToolUse hook:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write|MultiEdit|NotebookEdit|Bash",
        "hooks": [
          {
            "type": "command",
            "shell": "bash",
            "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/leader-guard.sh\"",
            "timeout": 10
          }
        ]
      }
    ]
  }
}

The script is active only while a ticket is running, which it reads from STATUS.md: a Current phase: line that is not Done. While it is active, it blocks the main session from editing anything under src/ or tests/. That covers the edit tools and Bash commands that write there: redirects, sed -i, rm, git checkout, PowerShell Set-Content, dotnet format and more. Calls from subagents carry an agent_id in the hook input, and those pass, so the Worker can still edit code. When the hook blocks the Leader, the reason goes back to the model, and the Leader delegates the change instead.

It is a guardrail, not a security boundary. A write hidden inside python -c "..." gets through. That is fine for its job: stopping a coordinator from “just quickly fixing” something nobody will review.

2. A workflow script for the implement-review loop

In the toy demo, “run the Reviewer after the Worker, never at the same time, at most two fix rounds” was also prompt text. On a real ticket, the Leader has a lot to keep in its head. So phases 5 and 6 are now a JavaScript workflow that the Leader starts with Claude Code’s Workflow tool. The order of steps is plain code:

for (let round = 0; ; round++) {
  const review = effective(await agent(reviewPrompt(round, worker), {
    agentType: AGENTS.reviewer, schema: DECISION_SCHEMA }), 'Reviewer')

  let qa = null
  if (review.decision === 'PASS' && a.qaApplies) {
    qa = effective(await agent(qaPrompt(round, review), {
      agentType: AGENTS.qa, schema: DECISION_SCHEMA }), 'QA')
  }

  if (review.decision === 'PASS' && (!a.qaApplies || qa.decision === 'PASS'))
    return done('READY_FOR_SHIP', `passed after ${round} fix round(s)`)
  if (round === MAX_FIX_ROUNDS)
    return done('ESCALATE', `still FAIL after ${MAX_FIX_ROUNDS} fix rounds`)

  worker = await agent(workerFixPrompt(round + 1, review, qa), {
    agentType: AGENTS.worker, schema: WORKER_SCHEMA })
  if (worker.status !== 'IMPLEMENTED') return done(worker.status, worker.conflict)
}

The Reviewer and QA return structured results against a schema: a decision, findings with severity and file:line, and a status for every acceptance criterion. That allows one more rule in code. A PASS that contradicts its own findings is downgraded:

function effective(result, who) {
  const mustFix = result.findings.filter((f) => f.severity === 'must-fix').length
  const failing = result.acceptance.filter((x) => x.status === 'Not met' || x.status === 'Fail').length
  if (result.decision === 'PASS' && (mustFix || failing)) {
    log(`${who} said PASS but reported ${mustFix} must-fix and ${failing} failing AC(s): treated as FAIL`)
    return { ...result, decision: 'FAIL', decisionOverridden: true }
  }
  return result
}

The workflow ends in one of five states, and the Leader has one instruction for each: READY_FOR_SHIP goes to the ship gate, ESCALATE and BLOCKED go to me, SPEC_CONFLICT starts a new spec revision, and INVALID_ARGS is the Leader’s own mistake to fix. The script has no file access, so the Leader still saves review.md and qa.md and updates STATUS.md from the result. That keeps a single writer for every file.

3. An area map, instead of more Workers

At the end of the last post I sketched a parallel version: several Workers, each owning an area of the code, each in its own git worktree. I did not build it. The tickets in this repo are small and touch one or two layers at a time, so parallel Workers would mostly add merge work.

I kept the “area” idea and used it for something else: rules. There is still one Worker, but every plan step is tagged with an area, and each area has a file of rules:

AreaCoversBlockers the Reviewer walksQA scenarios
Lookup-AIMCP server, lookup contract, Live AI drafting, seed dataD1–D12Order not found, MCP fault, prompt injection
EmailIngest, sender authentication, Gmail adapterD16, D20–D23Spoofed sender
WorkflowState machine, validation, SQLite, approve and outboxD13–D19Edit and approve, stale approve, overdue order
UIBlazor pages and stylesD13Approve flow, plus a visual check
PlatformHosting, config, scripts, CID12, D24, D26Loopback-only binding
DocsREADME and docsD25, D26none

The Worker reads the area file before each step. The Reviewer maps every changed file to an area and walks that area’s blockers, even if the plan did not declare it. QA picks its regression scenarios from the same table. A short list of files is marked always Full SDD: everything in Lookup-AI, sender authentication, the repository class that holds the approve transaction, the draft validator, the loopback guard. If a plan touches any of them, auto mode is off.

That last rule is my “conditional approval” from SUP-4, written down. What I typed by hand in the first ticket (“approve if it only touches spec files, tests and docs”) is now the definition of when the Leader may approve on its own.

Here is the flow with all three in place:

sequenceDiagram
  actor Me
  participant L as Leader
  participant S as Spec / Planner
  participant WF as Workflow
  participant W as Worker
  participant R as Reviewer
  participant Q as QA
  Me->>L: start-ticket SUP-n
  L->>S: draft spec, then plan
  S-->>L: spec (FR/QR/AC), plan (areas)
  L-->>Me: G1, G2 (unless auto applies)
  Me->>L: Approve
  L->>WF: run implement-review
  WF->>W: implement, read area rules
  W-->>WF: IMPLEMENTED
  loop at most 2 fix rounds
    WF->>R: review diff, re-run tests
    R-->>WF: PASS / FAIL + findings
    WF->>Q: only after a PASS
    Q-->>WF: PASS / FAIL + evidence
  end
  WF-->>L: READY_FOR_SHIP
  L-->>Me: G3
  Me->>L: Ship
  L->>L: commit, push, Notion

The second ticket: SUP-6, on the new version

SUP-6 was the follow-ups the Reviewer had left as notes on SUP-4: wrap a few startup failures in the migration exception, add tests for cancellation and lock timeouts, and fix an outdated example. I started it with auto.

  • G0 fired. SUP-6 was blocked by SUP-4, and SUP-4 was still “In review” in Notion even though its pull request had already merged on GitHub. The Leader saw the Notion status, stopped, and told me both facts. I said proceed. The rule did its job: it only trusts the ticket system, and the ticket system was behind.
  • Auto mode switched itself off, twice. The spec touched SqliteCaseRepository.cs, which is on the always-Full-SDD list, so the Leader refused to approve the spec on its own and stopped at G1. It did the same for the plan at G2. That is exactly what I wanted, even though I had asked for auto.
  • The workflow ran the loop. The Worker changed 9 files and took the suite from 77 to 82 tests. It also ran the new lock-contention tests five times to show they were stable; two of them wait about 30 seconds on a held lock. The Reviewer passed it in round 0. QA passed it, ran four of the acceptance criteria against the real app, and marked two as not reachable from the app (the startup code passes no cancellation token), so it re-ran those unit tests instead of pretending.
  • The Reviewer found a gap in my rules. One of its notes: plugins/** is not in the area map. The team found a hole in its own rulebook, and wrote it down instead of guessing.

Both Full SDD tickets passed on the first review round. So the fix loop has never run on a real ticket.

What I still don’t trust

The fix loop is tested only with stubs. implement-review.test.mjs runs the workflow with fake agents that return FAIL on purpose, so I know the control flow is right. I do not yet know how a real Worker behaves when a real Reviewer sends back three must-fix findings in a migration class.

Auto mode almost never applies here. In this repo the interesting code is almost all on the always-Full-SDD list. That is correct, but it means auto is mostly a docs-and-UI feature. If I ever find myself trimming the list just to make auto work more often, that is the moment to stop.

Changing the team mid-ticket is unsafe. Plugins load at session start. Editing agents, hooks or the workflow while a ticket runs leaves the Leader with a mix of old and new rules. Finish or stop the ticket first, then change the team.

The hook depends on the client. It needs bash (Git Bash on Windows) and a Claude Code version that sends agent_id for subagent calls. Without that, it blocks the Worker too, and the only way out is an environment variable that turns it off.

Each subagent is its own session. On SUP-4 the five subagents used about 544k tokens between them, on top of the Leader’s own context (196k by the end). For a schema migration that is worth it. For a typo it is not, which is why the Lightweight level exists.

Takeaways

  • The rules from a toy carry over. Where they live does not. On a real codebase, I moved every rule that prevents real damage out of a prompt: tool lists for who can write, a hook for what the Leader cannot touch, a script for the order and the round limit.
  • Read-only roles should return text, not write files. One writer per file is easier to keep when the reviewers have no write tools at all.
  • Areas worked better as rule sets than as a reason for more agents. One Worker that reads the right rules before each step was enough for this repo.
  • Write down what you check by hand. My one-off conditional approval became the definition of auto mode.
  • The process fails before the code does. Both incidents in SUP-4 were about the process, not the product: a plugin changed mid-run and a QA config detail. Plan for those failures as well as for bugs.

Next: a ticket that actually fails review, so the fix loop runs for real. And the plugins/** row the Reviewer asked for.