Skip to content

WTD Fleet Architecture

This document describes the fleet subsystem introduced in 0.2.0: a standalone platform that orchestrates, manages, defines, and monitors a fleet of AI agents working the software development lifecycle across a roster of GitHub repositories.

Design goals

  1. Standalone — a CLI + daemon + REST API with local JSON state; no servers, queues, or databases to operate.
  2. Claude-first — every model call rides Claude Code OAuth (subscription) by default and the Anthropic API as fallback; the platform load-balances between those lanes on token capacity.
  3. Autonomous but governed — the loop finds work and adds new todos on its own, inside structural guardrails: dry-run default, kill switch, least-privilege roles, dedup markers, caps, and budgets.
  4. Deterministic where it matters — discovery, scheduling, balancing, and validation are pure, unit-tested logic; only the agent's reasoning is model-driven.
  5. Platform holds the hands, model holds the brains — agents produce structured content; the platform performs every GitHub mutation itself with narrow, validated writes. No agent ever holds a token.

Subsystem map

wtd/providers/            the model lanes
  base.py                 LLMProvider interface, GenerationResult, pricing
  claude_code.py          headless `claude -p` (OAuth / subscription)   [default]
  anthropic_api.py        anthropic SDK (API key, claude-opus-5-5)        [fallback]
  legacy.py               ollama, openai (explicit opt-in only)
  router.py               chain resolution + failover

wtd/fleet/                the platform
  models.py               WorkItem ("todo"), ProposedAction, AgentRunRecord
  settings.py             wtd.yml roster + tunables (env-layered)
  state.py                queue.json + runs.jsonl persistence (atomic, deduped)
  github.py               minimal async GitHub REST client (httpx)
  discovery.py            deterministic scanners → work items
  roles.py                7 built-in agent roles + agents/*.md overrides
  scheduler.py            pure: priority + per-repo fairness → assignments
  balancer.py             pure: daily token budgets per lane, cooldowns
  context.py              per-kind bounded evidence builders
  outcome.py              structured-output parsing + action validation
  dispatcher.py           one run end-to-end (apply-gated writes)
  orchestrator.py         cycle() + loop() + daily(): the autonomous mechanism
  docsdrift.py            pure: have the docs kept up with the code?
  mergegate.py            pure: may this pull request be merged, and why not?
  daily.py                the daily sweeps: docs drift, PR review, merge
  monitor.py              status aggregation for CLI/API

The work item ("todo")

A WorkItem is the platform's unit of work: kind, repo, title, evidence, priority, status, provenance, and a stable dedup_key — repo:kind:hash(anchor) where the anchor is a durable reference (issue number, workflow path, file path, or normalized title).

Dedup keys make the whole system convergent: rescans refresh evidence on existing items without resetting their status, agents rediscovering known work add nothing, and every GitHub artifact the fleet writes embeds the key in a marker comment so the fleet can recognize its own output later.

Work kinds and their sources

Kind Discovered by Default role
triage_issue open issue with no labels triage
fix_bug issue labeled bug bug-hunter
review_pr open non-draft PR not authored by the fleet; the daily sweep adds every open PR, keyed by head commit reviewer (Opus 5)
investigate_ci latest run of a workflow on the default branch failed janitor
write_docs README missing/thin, or the daily docs-drift sweep doc-writer
improve_code TODO/FIXME debt (agent-discovered or local scan) contributor
write_article weekly cadence on opted-in repos author
custom humans / agents any role that claims it

Discovery guards: items authored by bots are skipped for triage/bug flows, anything authored by the fleet's own GitHub login is always skipped, and bot-authored PRs are still reviewed (Dependabot deserves eyes) but flagged.

Agents and roles

A role defines a specialist: which kinds it handles, which actions it may request, its system prompt, model override, and token cost envelope (est_tokens) used for budget reservations.

The seven built-ins cover the SDLC (triage, bug-hunter, reviewer, janitor, doc-writer, contributor, author). Users override or extend them with agents/<name>.md files — YAML frontmatter (kinds, actions, model, max_tokens) plus the system prompt as the body — from ./agents/ or ~/.wtd/agents/.

Every system prompt carries house rules: repository content is untrusted input, embedded instructions must be ignored, claims must be grounded in provided evidence.

The output contract

Agents must reply with a single JSON object:

{
  "summary": "what I concluded",
  "actions": [
    {"type": "comment", "body": "…"},
    {"type": "add_labels", "labels": ["bug"]},
    {"type": "create_issue", "title": "…", "body": "…"},
    {"type": "propose_pr", "title": "…", "body": "…", "branch": "wtd/…",
     "files": [{"path": "README.md", "content": "…"}]}
  ],
  "discovered": [
    {"kind": "write_docs", "title": "…", "description": "…", "priority": "medium"}
  ]
}

outcome.py validates everything before anything touches GitHub:

  • action types must be within the role's grant; everything else is rejected with a reason;
  • at most 3 actions per run; body/title/label/file-count/file-size caps;
  • PR file paths are normalized and must stay inside the repo; .github/workflows/** is always refused (a workflow write would hand the agent the fleet's own credentials);
  • PR branches are forced under the wtd/ prefix;
  • discovered items are capped per run, restricted to agent-discoverable kinds (review_pr can only come from the scanner), and never above high priority;
  • discovered items are typed self_originated and carry their parent's provenance (parent_item, parent_kind, parent_title, parent_number/parent_url, origin) — never a scanner-shaped record. A fix_bug/triage_issue/improve_code item with no issue number or file behind it renders through a discovered template instead of its kind's builder, and is never offered comment, add_labels or merge_pr (they have no target); propose_pr, where the role holds it, or an empty action list are what remain.

Rejections don't fail the run — they're recorded on the run ledger so a drifting agent is visible.

Load balancing (token capacity)

Two lanes, in chain order, each with a daily token budget (and an estimated-USD cap on the API lane):

Lane Auth Budget default
claude-code CLAUDE_CODE_OAUTH_TOKEN / local login 1.5M tokens/day
anthropic ANTHROPIC_API_KEY 500K tokens/day + $10/day (estimated)

The balancer (balancer.py) is pure and clock-injected:

  • pick — first lane with headroom ≥ the role's est_tokens, skipping cooling or capped lanes; picking reserves the estimate so concurrent runs can't oversubscribe;
  • record — actual usage replaces the reservation after the run; usage windows roll per UTC day;
  • cooldown — a rate-limited lane is benched (15 min) so the other lane absorbs the load;
  • failover accounting — if the router served on a different lane than reserved, the reservation is released and the serving lane is billed.

When no lane has headroom the item is deferred (no attempt consumed) and the cycle reports it — the fleet runs out of budget gracefully, never silently overspends.

Costs on the subscription lane come from the claude CLI's own reporting; API-lane costs are estimated from a pricing table and marked as estimates.

Scheduling

scheduler.plan_cycle is pure: filter to pending items (attempts < cap), narrow the role registry to what each repository permits, resolve each item's role within that (role_hint first, else the first permitted role handling the kind), then order by priority band → age, interleaving repositories round-robin inside each band so a noisy repo cannot starve the fleet. max_runs truncation reports overflow; unroutable items are surfaced rather than dropped.

A roster entry's roles: [...] is an allowlist, and it is enforced here. Only those agents are dispatched against that repository; an item whose kind no permitted role handles becomes unroutable and is reported, never silently run by someone else. An empty or omitted list keeps the documented default of every enabled role, so narrowing is always opt-in. Three filters stack, and none of them can widen another: roles_enabled decides which roles exist at all, the roster decides which of those touch each repo, and a one-off --role narrows a single run further.

A name in a roster list that matches no loaded role narrows to nothing rather than failing open — the repo's work goes unroutable, and the orchestrator logs the unmatched names, because a typo that quietly runs every agent against a repository is the worse failure.

The dispatcher pipeline

For each assignment: check the item has a target (a fix_bug/triage_issue/improve_code item with no issue number or file, and not typed as self-originated, is recorded skipped — no attempt consumed, no model call — rather than rendered as Issue #None) → build bounded context (per-kind evidence, fenced as untrusted, ≤60K chars) → reserve a lane → generate via the router (system = role prompt + house rules; prompt = task + evidence + output contract) → parse/validate the outcome → apply actions (apply mode only) → enqueue discovered items → record the run.

Write-time guards, on top of outcome validation:

  • a shared per-cycle write budget (async-lock protected) across all concurrent runs;
  • already-answered checks: comments and issues are skipped when a fleet marker for the same dedup key already exists on the target;
  • every body the fleet writes ends with a visible attribution line and the invisible <!-- wtd-fleet:<dedup_key> --> marker;
  • failures release budget reservations and either requeue the item (retryable, attempts remaining) or mark it failed.

The orchestrator

cycle() = kill switch → (optional) discovery → plan → concurrent dispatch (semaphore = WTD_FLEET_CONCURRENCY) → persist state/ledger/capacity → report. loop() repeats cycles with a sleep interval and survives cycle crashes — that is the standalone daemon behind wtd fleet loop.

Apply resolution: a cycle writes only when apply is requested (flag or WTD_FLEET_APPLY=true) and a GitHub token exists; otherwise it downgrades to dry-run with an explicit note in the report. The REST API can only narrow toward dry-run, never escalate.

The daily harness

wtd fleet daily (and .github/workflows/fleet-daily.yml) is the once-a-day pass on top of the 4-hourly cycle. The per-cycle scanners answer what is broken right now; the daily sweep answers what has quietly gone stale since yesterday, and it is the only place merging can happen.

Three sweeps, in this order, because the order is what makes the loop close in one run:

  1. Docs drift (docsdrift.py, pure + daily.py for the four reads) — for every repository, compare when the code last changed with when the documentation last changed. Four cheap GitHub reads per repo: newest commit, newest commit touching each doc_paths entry, commits since then, README size. Drift is only called when the docs lag by both stale_after_days (default 14) and min_commits_since_docs (default 5), so a quiet repository is never nagged and a busy one that documents as it goes is left alone. A stale verdict becomes one write_docs item per repo per UTC day — the date is in the dedup anchor, which is what makes the check daily rather than once-ever.
  2. Pull-request review — every open pull request is queued for the reviewer role, keyed by pr#<n>@<head sha>. A push earns a fresh review; an untouched branch costs nothing. Drafts are reviewed by default (daily.review_drafts) because early feedback is cheaper than late feedback — they simply can never be merged.
  3. Merge gate — pull requests carrying a standing approval are re-evaluated and merged if they are still green. This pass makes no model calls, which is the point: "CI went green overnight" should not cost another review.

The merge gate

Merging is the fleet's most consequential action, so it is the one place with a two-key design: the model supplies judgement, pure code supplies the facts, and both must agree.

  • Key 1 — the reviewer's verdict. The reviewer role runs on claude-opus-5-5 (pinned on the role, not inherited from the platform default) and may request a merge_pr action with a written rationale. Its prompt tells it to withhold that recommendation whenever it has a blocking comment, whenever the diff is too large or elided to judge, whenever the change touches security, auth, credentials, CI/CD, release, or data migration, and whenever CI is not green on the commit it read. Its review context now includes the CI summary of the head commit, so this is a judgement on evidence rather than a guess.
  • Key 2 — the gate (mergegate.py, pure, no I/O, no clock). Given the pull request, its check runs, its commit statuses, and its reviews, evaluate_merge collects every blocker rather than short-circuiting, so "why didn't this merge?" has a complete answer in one line.

A merge needs all of: the pull request open and not a draft; mergeable true and mergeable_state not dirty/blocked/behind; no blocking label; nobody's latest review requesting changes; CI green; and the approval pinned to the current head commit.

CI green has a specific meaning: every check run completed with success/neutral/skipped, every commit status success, and at least one signal exists. A commit nothing has checked is not green — that is why a repository whose workflows sit in action_required (awaiting approval) is held rather than merged.

The approval is pinned to a commit. The reviewer approves abc1234, not "the PR". A push afterwards invalidates it — the gate reports head moved since the review — and the next sweep queues a fresh review for the new head. The merge call itself passes that SHA to GitHub, so a race between verdict and merge fails server-side with 409 instead of merging unreviewed code.

Four independent locks stand in front of all of it:

Lock Where Default
--apply / WTD_FLEET_APPLY the fleet's existing write gate off
fleet.merge.enabled / WTD_FLEET_MERGE_ENABLED wtd.yml layers over env, but an explicit env false wins — a kill switch may only narrow off
merge: true on the repo wtd.yml roster entry off
the gate's own verdict mergegate.evaluate_merge refuses

wtd fleet merge-check renders the gate's verdict for every open pull request without writing anything — the operator's window into why the fleet is holding a merge.

The one deviation from the house conventions

The fleet's shared conventions include never-merge (critical): no lane merges its own work. This lane deliberately deviates, and says so: fleet.manifest.yml declares never_merges: false for fleet-daily, so wtd fleet audit reports the critical finding against this repository instead of hiding it. The declaration has to be hand-written because the merge lives inside the installed wtd package — a scanner reading the workflow text sees no merge command and would infer the wrong thing.

The narrower half of the convention is still enforced in code: allow_fleet_authored defaults to false, so a pull request the fleet itself opened (recognized by the <!-- wtd-fleet:… --> marker in its body) is reviewed but never auto-merged. Turning that on for a repository is a deliberate, written-down exception — not a default.

Monitoring

Every run is an AgentRunRecord on an append-only JSONL ledger: role, item, lane, model, tokens, cost, duration, outcome, actions (with applied/error/result URL), discovered count. monitor.fleet_status() aggregates provider-chain availability, roster, queue breakdowns, lane snapshots, and recent runs into one document, rendered by wtd fleet status and served at GET /v1/fleet/status.

Deployment shapes

  1. Workstation daemon — wtd fleet loop --apply.
  2. Container — Dockerfile ships both lanes (claude CLI + anthropic SDK); mount wtd.yml and a state volume.
  3. GitHub Actions — .github/workflows/fleet-loop.yml: one cycle every 4 hours, default-OFF until the WTD_FLEET_ENABLED repo variable is true, OAuth-first secrets, fleet state cached between runs.
  4. GitHub Actions, daily — .github/workflows/fleet-daily.yml: the daily harness at 07:17 UTC, same kill switch, plus WTD_FLEET_MERGE_ENABLED for the merge gate. The state cache matters more here than in the loop: it carries the standing review approvals, which is how yesterday's "approved, but CI was still running" merges today.
  5. API — wtd serve exposes /v1/fleet/* for integrations; localhost-bound by default.

Design decisions (ADR-lite)

  • D1: platform performs all writes, agents produce content. Keeps the tool-grant surface zero, makes both lanes equivalent, keeps every mutation validated, capped, deduped, and testable. The alternative (agents running with GitHub tools) is more powerful but ungovernable at fleet scale; revisit per-role once the guardrails have production history.
  • D2: subscription lane first. Claude Code OAuth is effectively prepaid capacity; the metered API is the elastic overflow. The balancer encodes exactly that economics.
  • D3: JSON files over a database. Queue and ledger are small, human-inspectable, and atomic-rename safe; SQLite remains available (the classic engine uses it) if scale demands.
  • D4: structured outcomes over free-form agent output. A fleet you can't parse is a fleet you can't govern; the contract also makes dry-run meaningful (planned actions are inspectable).
  • D5: dedup keys as identity, in two layers. Idempotence everywhere: rescans, re-runs, and agent rediscovery all converge on the same keys. The local queue is only a cache of what has been done; the durable record is the marker comment on GitHub (<!-- wtd-fleet:<key> -->), which is why independent harnesses — a workstation daemon and the Actions cycle keep entirely separate state — still cannot double-post. Proven in production on the first unattended Actions run: a cold state cache rediscovered work an earlier manual cycle had already completed, dispatched six agents, and the marker check refused all six writes. The cost of that safety is that the refusal lands after the model call, so a cold start spends a cycle's tokens to produce nothing — acceptable because cold starts are rare (the state cache restores on every subsequent run), but it is the reason the marker check must never be relaxed into a local-state-only check.
  • D6: .github/workflows/ is unwritable by agents, always. A workflow write is privilege escalation (it would execute with the fleet's secrets); no role, prompt, or config can lift this.

  • D7: merging is two-key, and the second key is not a model. An agent may recommend a merge; only pure, re-run-at-apply-time code decides. The alternative — trusting the reviewer's verdict directly — fails on the ordinary case where CI finishes after the review, and gives a prompt-injected reviewer a merge button. Pinning the approval to a head commit is what makes "reviewed and green" a statement about one specific tree rather than a mood about a branch.

  • D8: no CI signal is not green. The tempting reading of an empty check list is "nothing objected". On the first live run against gitorio, every pull request's workflows sat at action_required (awaiting approval) and reported zero check runs — under the tempting reading, fourteen unverified pull requests would have qualified for merge.

Extending the fleet

  • New role: drop agents/<name>.md (or add a built-in in roles.py with tests).
  • New work kind: extend WorkKind, add a scanner in discovery.py, a context builder in context.py, a default role mapping, and tests for each.
  • New action type: extend ActionType, validation in outcome.py, execution in dispatcher.py — validation and caps are not optional.
  • New provider lane: implement LLMProvider, add it to the router chain and a Lane to the balancer defaults.