Engineering architecture

How PaperCusp works

PaperCusp is a desktop app that runs fleets of AI agents against real projects — and ships their work through the kind of release discipline a great engineering org would insist on.

Agents are treated as what they are: capable but unreliable processes. So the architecture spends its effort where it pays — coordination, so many agents can work one codebase without chaos, and verification, so nothing unproven ships. This is the engineering tour: it starts high level and drills down, one subsystem at a time.

Ctrl + scroll (or pinch) to zoom · Ctrl +/− keys work too · drag to pan · click a block to dive into it · Esc resets · deeper zoom reveals internals · ▶ tour plays the storypinch to zoom · drag to pan · tap a block to dive in · deeper zoom reveals internals · ▶ tour plays the story
HOW PAPERCUSP WORKS fleets of AI agents on real projects — coordination + verification, everything on your machine YOUR MACHINE you — the human at the keyboard YOU — the human at the keyboard every turn is provenance-stamped: owner-typed ≠ machine-injected — an agent cannot mistake its own notes for your orders auto mode hands over the keys · every action stays disclosed LLM APIs LLM APIs — the only third party an inference gateway steers a pool of accounts cache-aware · headroom-checked · automatic failover per-agent model + reasoning effort, owner-chosen model calls — the only third party involved 01 · The desktop app Desktop app ⊕ more inside native shell · web UI · operator Cupboard: pots · packs · templates schedulers · DBOS durable workflows embedded Postgres every state a queryable row DESKTOP APP — the operator inside two audited doors screen sync · model calls — nothing else leaves the machine sync URL view state · SSE push — agents drive the same UI you see embedded Postgres plans · locks · events · memory — every state a queryable row process ledger every spawn enrolled, cgroup-scoped killed by task id, never by name durable core DBOS workflows · two-tier schedulers · watchdogs the Cupboard pots · knowledge packs · templates DESKTOP — the operator's real surface ui:get_state · ui:dispatch read the screen you see, drive its controls state:read { cell } live values at act time — never stale copies state:subscribe woken on the edge crossing — no poll loops processes:list WHO launched it, WHICH item, WHAT cost processes:freeze relieve pressure without losing work — kills go by task id through the cgroup dev:pipeline_position { path } "is my change live + the ONE blocker" schedule inventory every recurring timer visible — a bare setInterval fails the lint dev:pg_query ad-hoc reads — hot reads get a typed tool backup:snapshot before anything destructive — restore by id templates:new-app apps start from a maintained scaffold 01 05 · The coordination plane — fleets, locks, claims Agent fleets ⊕ more inside L a leader + members, on a plan agent modes: auto · ideate · drain AGENT FLEETS — the coordination contract pull, don’t push a leader claims the fleet — members PULL work, nothing hand-assigned claim-specs feed by QUERY an idle agent beside a nonempty queue is a spec bug, not fate work claim → wip → checkpoint → complete closure demands EVIDENCE, or reopens gates declared up front they LATCH — a late joiner is told the fire already happened blocked lanes park benched on their gate, not spinning SQL invariants police drift liveness is a verdict live · parked · suspect · ended — heartbeats alone prove nothing FLEETS — the real verbs fleet:launch-on-plan a leader + N members, visible or headless scheduler:get_next atomic pull — claim + intent in one write coord:orient one wake call: assignments · inbox · recall coord:dispatch assign + brief + wake in one atom — woken:0 is a LOUD miss events:await { event } end the turn — the fire carries the payload; sleeping costs nothing work_items:checkpoint re-injects on the item’s next invocation fleet:bench a blocked lane parks on its gate coord:couple opt into a peer’s working state consult:get_feedback "who knows this?" → best peer or archive mode:set auto · ideate · drain — peers SEE the grant 05 09 · The tool fabric Tool fabric ⊕ more inside MCP server · ~550 typed verbs recipes · guards · rules engine TOOL FABRIC — ~550 typed verbs tools:find ask by intent, get the verb projection, every call pick fields · pipe lines — reduce at the source results are capped distilled evidence, never raw dumps recipes auto-captured from real runs — replayable guards at the door risky calls refused, with the reason self-healing failing tools self-report → probation → fix consult: "who knows this?" routed to the peer whose real history answers best FABRIC — a call's whole journey tools:find "what I need" → the verb, by meaning + by name tools:invoke { name, args } any of ~550, dispatched server-side projection: { pick } fields chosen BEFORE they travel pipe: grep → tail logs distilled at the source, never in agent context results cap ~1,500 tok overflow spills to a file, not into the mind recipes:search real runs auto-crystallize, replayable by anyone invocation ledger watchdogs mine it and file the bugs guidance rides each tool when to use, when NOT, what to chain wire schemas columns declared once — only values travel meta:define-tool the fabric grows itself a new verb at runtime 09 02–08, 12, 13 · Goals, plans, work items, coordination, events, blueprints, context & memory, safety, the carry inventory Coordination substrate ⊕ more inside goals + plans work-item ledger file locks events + gates presence memory one shared bus — every agent reads and writes the same rows · zoom in: every subsystem is inside 02–13 02 · The execution flow 02 · execution flow 03 · Plans: success bars before implementation — zoom further for the full verification flow 03 · plans & goals 04 · Work items & scheduling 04 · work items 06 · The event system 06 · events 07 · The blueprint system 07 · blueprints 08 · Context & memory 08 · context & memory 12 · Safety & verification 12 · safety 13 · The carry inventory 13 · carry inventory 02 · The execution flow — internals 02 · EXECUTION — the turn loop the turn loop goal → plan → work items → fleet; each wake: orient → claim → act → checkpoint → end turn wake sources engine loops · gate events · coord wakes · the owner no silent halts a turn ends ONLY with a re-wake guaranteed blocked? park on the event sleep free — the fire re-wakes you 03 · From ambition to verified release — detailed BAR and METHOD flow 04 · Work items — internals 04 · WORK ITEMS — the ledger kinds change · bug · task · feature; create + claim: one atomic write checkpoints death survivable — a successor resumes mid-thought completion demands EVIDENCE tests run · verified how · files; a bare “done” is reopened by audit 06 · Events — internals 06 · EVENTS — gates that latch declare-first whoever OWNS the completion announces the gate key waiters park on the KEY typed keys drift, copied keys rendezvous gates LATCH arriving after the fire still resolves instantly a timeout is a signal go check the emitter — it may be stalled 07 · Blueprints — internals 07 · BLUEPRINTS — personas as data personas as data every persona a validated blueprint — never a hand-rolled prompt file extend + override extend a parent · override per pot layered base + overlay + instance — projected to every client from one canonical source 08 · Context & memory — internals 08 · CONTEXT & MEMORY — layered the layers mem0 semantic store · facts ledger · checkpoints · transcripts · docs facts fold VERBATIM into every orient until retracted compaction loses context, not DATA the verbatim record survives — search it, never re-derive it 12 · Safety — internals 12 · SAFETY — rails at the door rails at the write door locks · secrets guard · content lint · worktree guard — pre-write banned + gated destructive tree-wide git: banned; kills by task id via the cgroup ledger — never by name guards must be FALSIFIABLE mutation probes prove they can fail 13 · The carry inventory — internals 13 · CARRY — death is planned death is planned a session's end is an event with an inventory, not an accident carry doc identity · modes · held items · verbatim tail · checks checkpoints re-inject on the next invocation — yours or an heir's claims auto-release on death — never stuck held 03 · Eight steps across three parties — who is allowed to prove what 03 · WHO PROVES IT 11 · The release pipeline starts at the shared tree Shared working tree ⊕ more inside agents file locks arbitrate edits ONE checkout — staging agents never commit git-sync robot commits + pushes SHARED TREE — one checkout, no branches, no stashes file locks arbitrate every edit a blocked write names the holder + their live intent guards at the write door secrets · content lint · generated files · wrong-worktree — enforced before it lands the anti-footgun rail tree-wide destructive git is banned · a peer's uncommitted work is untouchable blame ≠ authorship sweeps commit as one identity; the work-item ledger holds who did what SHARED TREE — the real verbs locks:queue { paths } who holds a file + their live intent, read before you edit — never guess at a peer git-sync:run force the commit robot's tick when the sweep lags and you need your work committed NOW release:deploy op:'status' — the ONE blocker + a recommendation · 'trigger' ships the already-green pin · 'force' names the reds it accepts — owner-gated, audited release:checkpoint-run re-run the verdict NOW: fixing code never re-greens a red gate by itself dev:pipeline_position { path } committed → gated → main → deployed, and WHICH hop is stalled mutation-probe prove a guard CAN fail without mutating the shared tree: copy-out subjects, fake-destructive shims, historical pre-fix mode 11 10 · The self-improvement loop Self-improvement ⊕ more inside the Blender: observe→ideate→grade→build rubrics · scorecards · graded evidence SELF-IMPROVEMENT — the Blender friction is filed the MOMENT an agent routes around it the Blender loop observations → digest → ideas under rotating lenses every idea graded a low grade WAKES its author to revise rubrics + scorecards turn opinion into evidence the system that builds your app also rebuilds itself SELF-IMPROVEMENT — the real verbs improvements:capture the workaround IS the trigger — filed mid-task, the moment an agent routes around friction, not “later” blender:grade-idea a low grade WAKES the author to revise · self-grades are refused curation:state-of-pot every agent's filings, digested — read it BEFORE you ideate rubrics + scorecards opinion → graded evidence 10 09 · Code intelligence — agents read code as a graph Code intelligence ⊕ more inside the codebase as a graph — not grep gitnexus · lsp · semantic search CODE INTELLIGENCE — read before you write gitnexus the codebase as a GRAPH — call chains · impact · topology lsp compiler-truth defs, refs, types — never guesses search:semantic + fulltext code · docs · plans · sessions — meaning-matched recall code:pack whole-subsystem bundles in one read exec sandbox ten tool calls, one round-trip — only the result returns impact first, edit second the fleet's reflex 09 02 · Triggers & workflows — recurrence as data Triggers & workflows ⊕ more inside events · schedules · conditions durable workflows survive restarts TRIGGERS & WORKFLOWS — recurrence as data triggers are data fire on events · schedules · conditions — never a bare timer orchestrate:run multi-step workflows, typed I/O, inspectable mid-run DBOS durable workflows each step checkpointed in PG — a restart resumes, not redoes watch:create wake me — or quietly note it in my next orient plans:set-schedule recurrence armed on whole plans hooks at every door guards run before writes land 02 01 · Integrations — agents act in the real world Integrations ⊕ more inside gmail · slack · calendar · social agents act in the real world INTEGRATIONS — the same audited doors, outward the same audited doors gmail · slack · calendar · social — outward now mail read, triage, draft — sends sit behind approval gates slack channels as working surfaces — reports where your team reads calendar meetings become triggers — prep + follow-ups unasked invocation ledger every outward call audited, attributable, quota-tracked 01 01 · Plugins & marketplace — extend the fabric without forking it Plugins & marketplace ⊕ more inside WASM plugin SDK · typed WIT seams extend the fabric, never fork it PLUGINS & MARKETPLACE — extend, don't fork plugin SDK WASM against typed WIT seams — any language, sandboxed capability doors never the machine — scoped, auditable, revocable runtime install the fabric grows a verb without a redeploy the marketplace browse · install · publish — ship yours to the world the Cupboard pots · packs · recipes · rubrics · blueprints · app templates 01 10 · Eval & health — measured, gated, accountable Eval · health ⊕ more inside gym · ablation · calibration flags · watchdogs · quota · purge EVAL · HEALTH — measured, gated, accountable the gym scenario batteries replay real work — graded before it ships ablation + calibration what a rule actually buys — evidence, not vibes the learning loop outcomes fold back into specs, prompts, claim routing flags from day one finished work never ships dark watchdogs · telemetry health acks · quota — cost visible · purge on command 10 11 · The release pipeline — sweep, gate, fast-forward, deploy git-sync auto-commit + push green gate full verification suite main fast-forward only production deploy · probe · rollback 11 git-sync sweeps the WHOLE tree on a cadence — one identity agents never run add / commit / push at all merge conflicts route to a resolver agent blame ≠ authorship — the ledger holds the truth green gate the full suite on a cut candidate: affected tests · lint · types · perf · desktop e2e a red gate is EVERY agent's job to green auto-refire rescue · accountable quarantine main fast-forwards ONLY — to a green candidate no human pushes: a hook blocks the branch always releasable, by construction production deploy cuts a release checkout + restarts health probe → automatic rollback on failure force-deploy exists: owner-gated, loud, audited git-sync — the commit robot ticks + on demand sweeps the whole tree on a cadence — or fire it NOW per-slug lock held across commit → push conflict? abort clean a resolver agent merges — no side overwritten mid-refactor sweeps deliberate: the tree is truth, the ledger says who did what green gate — the full verdict cut from LOCAL staging it never fetches — push is not a gate precondition affected radius selected from the actual changed paths re-triage rescue stale reds voided before they block anyone a passing suite ≠ green lint · perf · desktop · delta must also clear main — always releasable fast-forwards only to the pinned green candidate — nothing else no human pushes a pre-push hook blocks every direct write distance-behind is a live cell agents subscribe to the edge crossing — never poll production — deploy + rollback separate release checkout the shared tree is never touched survives its restart the cut outlives the restart it triggers probe → rollback a failed health probe rolls back — no human in the loop force path names the reds it accepts — owner-gated, loud, audited the autonomous release pipeline your other machines pots federate peer-to-peer encrypted mesh no central server — ever YOUR OTHER MACHINES pots federate between your own boxes — bare stores per (hive, repo) p2p encrypted mesh commits flow peer-to-peer · membership is explicit bridged mode syncs via GitHub when you choose — same gates, same locks, same ledger no central server — ever every claim an agent makes ships with graded evidence — ✓ verified · ⚠ contested · ? predicted — checkpoints carry the probe that re-tests them every turn is provenance-stamped (owner-typed vs machine-injected) — an agent cannot mistake its own notes for your orders spawns calls hosts claim · coordinate edits — lock-arbitrated observations sweep · commit · push
The whole machine — every diagram lives inside this map. Everything runs and stays on your machine; the only third party is your model provider. Ctrl+scroll or click a block to dive in — each block contains its subsystem's full diagram. Click again when zoomed to read that subsystem's story below.
SECTION 01
01

The desktop app

The short versionPaperCusp is a native desktop app. The agents, their coordination, their memory, and your code all run — and stay — on your machine.

The shell is a native window hosting a fast web UI; behind it runs the operator, the system's backbone process:

  • serves the UI — every screen is a live view over the same state the agents write
  • hosts the agents' entire tool surface — every verb an agent can call terminates here
  • runs the schedulers and background routines — the recurring machinery has one home
  • owns a Postgres instance embedded in the app — the choice that shapes everything
Every plan, work item, memory, lock, event, message, and test result is a queryable row in one database — not a pile of JSON files — so agents and humans interrogate the same live state with the same queries, and nothing about the system's behavior is invisible.

Agents themselves are ordinary CLI coding-agent sessions launched as OS processes — visible terminals arranged on your desktop when you want to watch, headless background sessions when you don't.

  • MCP is the umbilical — each session connects back to the operator's tool surface over MCP, so any capable agent CLI can join a fleet without bespoke integration
  • projects arrive as pots — packaged repos with their agents, docs, conventions, and work queues
  • installed from the Cupboard — an in-app distribution shelf
  • pots federate peer-to-peer — between your own machines over an encrypted mesh; there is still no central server in the loop

Everything the operator sends out passes through one of two audited doors:

  • the sync path — state to your screen; because this door is addressable, an agent can read what you're looking at and drive the same interface you do
  • the inference gateway — model calls to providers: the only traffic that leaves the machine at all

Both doors exist so that flow is deliberate and observable rather than ad-hoc.

TO YOUR SCREEN — THE SYNC PATH TO THE MODEL — THE GATEWAY the view state lives in the URL operator queries resolve here SSE push results stream down a write, anywhere agent or human precise invalidation exactly the touched queries re-resolve — no polling, no refresh loops asks agents read the URL and drive the same surface the UI uses — the screen is addressable agent 1 agent 2 … agent N each with its own model + effort choice gateway cache-aware: same account, warm prompt cache headroom checked account A account B account C rate-limited → steered around, not died on the one thing that leaves the machine everything else — state, tools, coordination — stays local twenty agents don't die on one exhausted key — failover is automatic
Two doors out of the operator. The sync path carries state to your screen — resolved in the operator, pushed over SSE, invalidated precisely. The gateway carries model calls to providers — cache-aware, headroom-checked, failing over instead of failing. Nothing else leaves the machine.
// the sync path, from either side of the glass:
// a UI pane reads — one declared query, resolved in the operator, pushed over SSE
useSyncQuery({ queryName: 'workItems.list', args: { state: 'wip' } })

// any write — agent or human — invalidates precisely; exactly the touched queries re-resolve
notifySyncInvalidate('workItems.list')

// and because view state lives in the URL, an agent reads + drives the same screen you see
ui:get_state {}            → { url: '/plans/db-rework?tab=items' }
ui:dispatch { url: '/plans/db-rework?tab=decisions' }
SECTION 02
02

The execution flow

The short versionA sentence in chat becomes a plan; the plan becomes work items; the items form a dependency graph; a fleet (§05) drains it — and context is injected at every hop, so no agent has to remember anything.

Everything starts in conversation. A goal — "build X", "migrate Y" — lands with an agent, and then:

  • scope and route are pinned first — what exactly, built how, run by whom (this session, an existing fleet, a new one) — before anything executes
  • the answer becomes a plan — a durable, itemized, dependency-edged execution contract, audited against the full source conversation before it activates (§03)
  • activation promotes plan items — into the work-item ledger, where each unit gets an owner, a lifecycle, and — eventually — completion evidence (§04)

From there, no human walks the graph: a fleet drains it, and completed work rides the pipeline out (§11).

What makes this survivable at scale is the diagram's bottom band — the substrate re-delivers state at exactly the moments it's needed, so an agent's memory is an engineered input, not a hope (§08).
// the same flow as verbs — chat is the only freeform step
plans:new { slug: 'db-rework', title: 'Rework the schema' }
plans:add-item { slug: 'db-rework', text: 'write migration' }     // × N items, with dependency edges
plans:start { slug: 'db-rework' }   // activation: audited first, then items PROMOTE to work items

// a fleet member pulls — the scheduler walks the DAG, nobody dispatches by hand
scheduler:get_next {}
   → { item: 'WI-1204', checkpoint: …, planDecisions: […] }   // context rides the claim in
SECTION 03
03

The plan system

The short versionA plan is a durable, auditable execution contract — not a chat message that scrolls away.

Plans live in a shared store every agent can read. A plan carries:

  • typed items — discrete units of work with dependency edges
  • a "now" pointer — naming the current focus, so nobody guesses what matters this week
  • decisions — numbered, addressable rulings recorded the moment a trade-off is settled; a decision is citable (plan#D-012), so a peer acting on a ruling re-reads the authority instead of trusting a paraphrase relayed through chat
  • success bars declared before implementation — the acceptance rubric owns what must become true; the verification method is filled in once the implementation is known
The load-bearing step is the activation audit: nothing starts until the full source conversation — not a summary of it — provably maps to the plan. It's the difference between "the agent remembers what you asked" and "the plan can prove it".

Plans are also where cross-lane disputes go to die: a ruling is recorded as a decision the moment it forms, and rules travel with the work.

The mechanism has teeth. In one observed run, an agent re-reading a recorded ruling mid-execution discovered its own earlier report was wrong — it self-corrected, then swept up several more instances of the same error.

A relayed chat message cannot produce that outcome; an addressable decision can.

From ambition to verified release

BAR means what must become true; METHOD means how we will check it. Requirements capture the objective before implementation. They seed versioned success bars in the acceptance rubric, mapped into plan items, spec clauses and work contracts. Once the code exists, the author adds a concrete method and structured check for each bar. Filling in a method cannot quietly lower the bar.

  • Prove the outcome in its required setting. Bind current evidence to the exact spec revision. A code test, a deployed check and an actual live workflow prove different things; a child plan's completed tasks do not prove its parent's promised outcome.
  • Keep the judgments separate. Review the measurement method, independently grade every outcome, then record the acceptance author's response. A disclosure or an unmeasured result cannot satisfy a mandatory outcome.
  • Repair failures explicitly. Failed evidence sends work back for repair. A changed success bar requires a recorded amendment, refreshed mappings and new proof and grading where the change makes them stale. Old plans are backfilled from trustworthy requirements or left explicitly unresolved.

Who does each step matters as much as the order. The audit runs first, while the implementation is still warm and code-truth gaps are cheap to find. The rubric is authored afterwards, against as-built reality — never at plan creation, because a bar written before the work describes the plan rather than the result. Read the figure by its lanes rather than its arrows: the vertical zigzag is the design. Every drop out of the implementer's lane is a point where the system stops trusting the party that did the work.

CODE TRUTH ACCEPTANCE RUBRIC RELEASE IMPLEMENTER authors the rubric CRITIC a live peer, via consult GRADER outside the author's lineage Finish or dropevery item plans:auditcode truth rubrics:proposeas-built bar Attest againstmeta-rubric Record acceptor reject Shipset-plan-status Critiquethe rubric Grade everycriterion 123 456 78 reject ⇒ the work returns to implementation THE PLAN'S OWN LIFECYCLE draft active awaiting-acceptance shipped activation audit the whole request, mapped every item done or explicitly dropped graded, then accepted a verdict, not a release Shipped is not deployed: the release gate — commit → green tests → main → deploy — is a separate pipeline with its own evidence.
Eight steps across three parties. The audit runs first, while the code is warm; the rubric is authored afterwards, against as-built reality. Steps 4 and 6 leave the implementer's lane on purpose — an author can neither vet nor grade their own bar. Below, the plan's own lifecycle: a second, earlier audit gates draft → active, and acceptance is not shipment — a plan whose work is finished sits in awaiting-acceptance until it has been graded and accepted.
Three views, one map. Open the Plans tile for the overview; zoom further for the complete verification flow, and further still for the three parties above. All are native SVG inside the existing zoom, pan and detail controls.
SECTION 04
04

Work items & scheduling

The short versionEvery unit of work is a ledger row with an owner, a state, a checkpoint — and, at the end, evidence. The scheduler walks the DAG so nobody has to.

The work-item ledger is the durable, fleet-visible record of everything in flight, and it exists to enforce one rule: nothing important lives only in a conversation.

  • closing is where the discipline bites — a terminal close needs structured evidence, and a bare "done" gets re-opened
  • the way in is guarded too — a stale claim can be routed through reproduce-before-implement, so a fleet never builds a fix for a bug that already died
// closing is where the discipline bites — evidence is structured, not prose
work_items:complete { id: 'WI-1204', state: 'done',
  completion: {
    summary:      'migration 0812 applied + backfill verified',
    testsRun:     'npm run test:file -- db/migrate-0812.test.ts',
    testResult:   'passed (14/14)',
    verifiedHow:  'integration',
    filesChanged: ['db/sql/0812-rework.sql'] } }

// a bare "done" without evidence? the state write REFUSES — and a leader audit re-opens fakes
SECTION 05
05

The coordination plane

The short versionMany agents, one codebase, no chaos: every claim, lock, message, gate, and decision goes through one shared substrate that all agents — and you — can see.

Work runs as fleets — a leader and N members on a plan (§03) — and the plane rests on a few hard bets:

  • pull over push — members claim work through a spec the leader tunes; an idle agent next to a non-empty queue is a spec bug, not a dispatch chore
  • concurrent editing is safe by design, not by hope — lock arbitration at the write turns collisions into conversations instead of clobbers
  • liveness is one shared verdict — every surface agrees on live · parked · dead, so "is anyone actually working this?" has exactly one answer
  • supervising N agents costs one read, not N check-ins — a leader brief folds every member's liveness, claims, unanswered questions, and context pressure into a single call, so the leader re-orients from live state instead of interviewing the fleet
  • gates latch — nobody sleeps forever on a flip they missed

Peer awareness — a theory of mind

Coordination is also an awareness problem — a working theory of mind about your peers.

Messages are structured envelopes rather than chat, so confidence and its gaps travel with every claim — and awareness arrives while you work, not in a mailbox you remember to poll.

theory of mind A B C coupled sees B's live goal + its freshness uncoupled: pays nothing declared intents every distinct piece of work declares itself read at the lock · on the wall · by the leader stale-flagged when the claim stops progressing "who is on what" = one query, never a meeting the message envelope expects: ack | answer | action | none — named, always premises — what this claim rests on forYouBecause — why THIS recipient youMayNotKnow / couldNotDetermine — gaps travel too audience selectors: @fleet · @plan · @file-holders resolved live at send · queryable later as history delta injection — push, mid-turn [coord+N] → typed lines land INSIDE a running turn: > intent · * completion · + claim · ! finding · ^ escalation awareness arrives while you work — no polling, no meetings
Awareness and messaging. Coupled peers share live goals; envelopes carry expectations and gaps; deltas inject into running turns — the plane that replaces standups.
// a message is an envelope, not a chat line — expectations and gaps travel with it
coord:send { to: ['@fleet-leader:db-rework'], expects: 'answer',
  summary: '0812 backfill: rows with NULL owner — drop or default?',
  body: [{ text: '…',
    forYouBecause:     { relation: 'owns', ref: 'db-rework' },
    couldNotDetermine: [{ what: 'whether NULL owners are load-bearing' }] }] }

// expects ≠ 'none' ⇒ the message stays visibly UNANSWERED on every leader surface
// until a reply threads back to it — asked-and-ignored is a state the system can see

The same don't-let-it-drop principle guards commitments. A pending owner decision or an unmet promise is recorded as a wall — pinned into every subsequent wake, brief, and carry document until it is explicitly cleared — so a blocked question survives any number of context resets instead of quietly falling out of somebody's window.

You don't have to know who to ask. The consult router (consult:get_feedback) turns "who knows this?" into one call: it searches every agent's real transcript history and wakes the best-qualified peer — or answers instantly from the archive when a closed consult already settled the question. Below the relevance floor it is honest: "no one knows more than you do," never a costumed expert.

Two more routes round out the exits. Work that outgrows its holder moves by structured handoff — the item, its checkpoint, and its open questions travel together. And a decision that is genuinely the human's becomes an owner-gated ask, recorded as a wall until answered — routed, never guessed at.

Getting a message to a live session

And delivery is engineered around one hard question: how does a message reach an agent that is a live terminal session? By its liveness — never by hoping it polls a mailbox.

envelope expects · premises · audience selector outbox durable queue — a crash loses nothing presence verdict one shared oracle: live · parked · dead LIVE → inject mid-turn typed delta lines land inside the running turn, between tool calls: > intent · * completion · ! finding PARKED → wake a fresh turn starts with the payload in hand — parked costs nothing until then DEAD → loud miss the sender is told nobody woke — relaunch follows; never a silent drop the inbox is the query side — catch-up and audience history delivery never depends on an agent remembering to poll it; the push above is what makes awareness mid-turn
Delivery by liveness. One presence verdict routes every message: injected into a running turn, woken into a fresh one, or reported as a loud miss. The outbox is durable; the inbox is for history, not for hoping.

Under that diagram sits a deliberately split mailbox design — an outbox that owns delivery, an inbox that owns history:

  • the outbox is the delivery side — every send lands in a durable queue first, so a crash between "sent" and "seen" loses nothing; from there, delivery is driven by the recipient's liveness verdict, never by hoping it checks mail
  • live sessions never poll — the message is injected mid-turn as a typed delta line, landing between tool calls while the agent works; a parked session is woken into a fresh turn with the payload already in hand
  • a miss is loud — a send to a dead session reports recipient_absent back to the sender, who relaunches or reroutes; there is no silent drop to discover a day later
  • the inbox is the query side — catch-up after time away, audience history ("what was my fleet told while I was down"), and threading: a reply wakes the original asker, and a message that expects an answer stays visibly unanswered on every leader surface until a reply threads back to it
The split is the point: delivery never depends on an agent remembering to read its inbox. The outbox pushes by liveness; the inbox exists so catch-up and history are queries, not archaeology.
SECTION 06
06

The event system

The short versionBlocking conditions park on events, not poll loops: declare a gate once, open it with one emit — and it latches, so a late subscriber can never sleep through the flip.

The design goal is sleeping safely: an agent that waits should cost nothing while parked and should be un-strandable. Everything in the diagram serves that:

  • keys are returned by declaration — because a one-character drift in a hand-typed key is a rendezvous that never happens
  • gates latch — arriving late still resolves, instantly
  • a timeout wake is not a shrug — it's a cue to go diagnose the stalled emitter

What it looks like in practice — three calls, one rendezvous:

// the LEADER declares the gate up front — the scoped key is RETURNED, never hand-typed
events:emit { event: 'schema-migrated', announce: true }
   → { key: 'fleet:db-rework:schema-migrated' }   // discoverable in every member's orientation

// a MEMBER parks on the returned key — its turn ENDS; parked costs nothing
events:await { event: 'fleet:db-rework:schema-migrated',
               timeout_sec: 1800, on_timeout: 'wake' }

// later the leader fires it ONCE — every waiter is re-invoked, payload in hand
events:emit { event: 'fleet:db-rework:schema-migrated', summary: 'migration 0812 applied' }
   → { waiters: 4 }   // the announcement LATCHES: a member arriving late resolves instantly

The properties that carry the weight:

  • announce: true — declares the gate without firing it; the platform returns the scoped key (auto-prefixed per fleet, so two fleets' gates can't collide) and registers it where every member's orientation will surface it — a zero-message rendezvous
  • timeout_sec + on_timeout — every wait is bounded; a timeout wake means "go check whether the emitter is still progressing", never "wait harder"
  • payload — the emit's data rides the wake itself, so the woken agent starts with the answer rather than a hint to go fetch it
  • waiters — the emit reports how many parked awaits it actually matched; waiters: 0 is a loud "this reached no one", not a log line
  • scope: 'hive' — the same key can rendezvous across machines: each federated peer re-fires it into its own local await store
SECTION 07
07

The blueprint system

The short versionAn agent's behavior is versioned configuration, not a hand-rolled prompt file: layered blueprints assemble every session's operating contract from one canonical source.

Agent behavior is engineered the way code is: inherited, never copied.

  • a fix to a base persona propagates — every descendant gets it, instead of forking into drift
  • every rendered prompt is a projection — of one canonical source: edit the source and every surface follows; edit a projection and the next render erases you
  • that property is the point — it's what keeps a fleet of role variants coherent
// a new role is a validated CHILD of an existing one — never a copied prompt file
blueprint:catalog { }                    → find the parent to extend
blueprint:extend { parent: 'su-engineer', name: 'migration-runner',
  override: { mission: 'drain the migration queue',
              tools: { deny: ['release:deploy'] } } }

// the child is validated against the parent's contract, versioned in the catalog,
// and every session launched from it renders base + overlay + instance — in order
SECTION 08
08

Context & memory

The short versionAgents forget; the system doesn't. State lives in layered, queryable stores — and agents are engineered to outlive their own context windows.

The window is an assembled artifact, not an accumulation — every slab of it has a store that feeds it and a rule that decides when.

Nothing depends on the agent remembering to ask. State reaches the window through two deliberately different disciplines:

  • what an agent must see is pushed — deterministically, verbatim, with no query an agent could forget to issue — so it cannot be missed
  • what an agent might need is pulled — by relevance, ranked and capped — so the window never fills with maybes

The split is the design:

ONE TURN'S CONTEXT WINDOW operating contract blueprint layers · project guide · tool guidance orientation fold — every wake held claims · inbox summary · announced gates standing facts (VERBATIM) · semantic recall (by intent) registered modes — standing rules, re-injected claimed work the item's checkpoint · its plan's decisions, inline the live turn peer deltas inject mid-turn · tool results, projected to fit blueprint catalog — rendered contract canonical in the database, projected per client the memory stores semantic memory → returns by MEANING standing facts → return VERBATIM (TTL, retractable) transcripts → return by SEARCH, across agents provenance tags: who actually said it work-item ledger — checkpoints · decisions returns ON RESUME — successors pick up mid-task coord bus — messages · events · presence returns LIVE — deltas injected as they happen compaction: window fills → flush state to the stores → cut to a fresh context → re-assemble — same identity, same claims, new headroom
Anatomy of a turn. Each slab of the window has a store that feeds it and a delivery rule that decides when — the window was never the system of record.

Compaction — outliving the context window

The layer that makes long-running autonomy real is compaction. When a session nears its context limit:

  • it flushes state — to the surfaces above, as the work happens, not as a dying gasp
  • then cuts to a fresh context — that re-orients from them: same identity, same claims, same work, new headroom
  • work survives any number of windows — because the context was never the system of record; the database was
  • even attribution is engineered — carried directives are provenance-tagged, so "the owner said X" always traces to a turn a human actually typed; an agent's note-to-self can't launder itself into an order through repeated summarization
// the memory verbs behind the diagram — each store, one call
memory:remember { text: 'wrangler deploys need node ≥ 25 on this box' }  // recalled by MEANING
facts:assert { key: 'gate-authority', body: 'plan v75 D-028 governs', ttlDays: 14 }
   // folded VERBATIM into every relevant orientation until retracted
work_items:checkpoint { id: 'WI-1204', checkpoint: 'backfill 60% — resume at batch 41' }
   // re-injected on the item's NEXT claim — yours or a successor's
sessions:search { session: 'self', query: 'why did we skip table X?' }
   // the transcript survives compaction — retrieve, don't re-derive
semantic memory durable knowledge, recalled by meaning standing facts scoped conclusions · TTL · retractable work-item checkpoints in-flight state, written as it forms session transcripts every turn, indexed across agents → folded into orientation, by relevance → re-injected VERBATIM, every wake → re-delivered on resume or takeover → retrieved by search, not re-derived compaction context fills flush cut fresh re-orient the context was never the system of record
Four layers, four delivery paths. What matters is not where state is kept but how it finds its way back — by relevance, verbatim, on resume, or by search.

Sessions end; the work carries

Sessions themselves are engineered to end, restart, and carry without losing the thread.

Either way, the survival inventory is the same — and none of it lives in the window. What's in it, and where the GUI surfaces each piece: §13.

ONE AGENT, MANY WINDOWS session · window 1 works · checkpoints as it goes window fills flush → cut session · window 2 same identity · same claims parked costs nothing woken: message · gate · schedule · claim warm carry the same live context resumes on every wake fast · remembers the thread — the default cold carry each wake rebuilds fresh from the stores cheaper over long runs · immune to summary rot the survival inventory — none of it lives in the window claims + checkpoints · armed loop + carry-note · registered modes · standing facts · plan decisions coupling edges · full indexed transcripts (searchable across the whole carry chain) · provenance tags
End, restart, carry. Warm resumes the thread; cold rebuilds from the stores; the inventory survives either way — which is why an agent here can work for weeks.
SECTION 09
09

The tool fabric

The short versionAgents don't get a shell and good luck — they get ~550 typed, documented verbs for everything from claiming work to shipping a release, found by intent, guarded at the call.

The principle: documentation lives at the call site.

  • every verb carries its own guidance — and discovery is by intent, so nobody memorizes 550 names
  • the invocation ledger keeps the system honest — audits replay what actually happened, and drift detectors reconcile what the docs claim against what the fleet actually calls
  • the rails teach as they block — a refusal names the safe form, so the lesson lands at exactly the moment it's needed

Here's what a real tool looks like — this is (lightly trimmed) the actual definition of locks:queue, the "who's holding what?" diagnostic:

export default defineTool({
  name: 'locks:queue',               // server:verb — the cross-client identity
  description: 'Read the active locks and pending waiters for a workspace…',
  guidance: {                        // teaching, shipped WITH the verb
    when:    'Diagnostics — "why am I blocked?". Cheap, MVCC read.',
    notWhen: 'Before every acquire — locks:acquire already returns busy context.',
    seeAlso: ['locks:list (named resources, not file contention)'] },
  capability: 'locks:read',          // what this verb may touch — gated per role
  args: z.object({                   // a real schema, validated at the door
    paths: z.array(z.string()).optional(),
    owner: z.string().optional() }),
  async handler(args, ctx) { /* one read, one stable shape out */ } })

The properties that matter:

  • nameserver:verb, the tool's real identity on every client; every doc and prompt cites it in exactly this form
  • description + guidance — the documentation lives ON the tool: when, notWhen, and seeAlso route an agent before it can pick the wrong verb — and a prompt-weight gate keeps this text from bloating every session
  • capability — the permission this verb exercises; roles are granted capabilities, never raw verb lists
  • args — a typed schema validated at the door, so a malformed call is refused with the safe form named — not half-executed
  • handler — runs inside the operator with an identity-resolved context; every invocation lands in the ledger the audits replay
SECTION 10
10

The self-improvement loop

The short versionThe same fleets that build your product also rebuild the platform: friction observed while working becomes filed, graded, and eventually shipped improvement.

It starts at the moment of friction: the rule is to file the observation mid-task, the instant a workaround happens, before the detail evaporates into transcript prose.

  • filing is unconditional — the classic excuses are banned by name: "it was transient," "it recovered," "it didn't block me"
  • an uncaught incident is two bugs — the incident, and the watchdog that should have caught it
  • a mitigation is never a fix — a band-aid must name its durable fix and who owns it
// the flywheel's intake — filed mid-task, the moment the workaround happens
improvements:capture { kind: 'bug',
  title: 'headless-browser console: daemon-origin errors pollute page verification',
  body:  'repro: goto example.com → console shows ERR_FILE_NOT_FOUND ×8 …' }

// dedup is search-first; a second independent reporter promotes the SAME row;
// and kind:'bug' is eligible for the auto-implement lane — the queue feeds itself

The flywheel's proof is its own queue: the PaperCusp pot inside PaperCusp carries thousands of work items of the system improving itself.

SECTION 11
11

The release pipeline

The short versionAgents never push code — an autonomous pipeline commits their work, verifies it, ships it, and rolls it back if it regresses.
  • no agent holds commit rights — a background sweep commits the whole tree; main's history is by construction a chain of verified states, and a bad deploy rolls itself back
  • a red gate is the whole fleet's highest-priority work — it freezes everyone's deploys, so "not my lane" is not a valid answer
  • a quarantined flake files its own follow-up — nothing rots silently

What makes the gate livable at fleet scale

Two subtleties, both learned the hard way:

  • fixing the code does not re-color the gate — the verdict is periodic, so landing a fix and shipping it are three distinct hops — commit, re-judge, deploy — each with its own on-demand lever. Conflating them is how an agent fixes every red test and then stalls, staring at a gate that stays red until the verdict re-runs
  • "the gate is red" ≠ "the gate is red about my change" — whether the judged candidate contains a given change is a content question: a blob-containment check against the candidate's tree, exposed as a one-call read — never a timestamp inference, which on an auto-committing tree misattributes routinely. A stale red can even void itself: the gate re-fires onto a newer tip that may already carry the fix, a rescue an impatient manual re-run would discard

“Is my change live?” is one call

// "is my change live — and if not, what is the ONE thing blocking it?"  one call:
dev:pipeline_position { path: 'db/sql/0812-rework.sql' }
   → { positions: { committed ✓, staging ✓, main ✗, deployed ✗ },
       blockedOn: 'green-checkpoint RED (2 files)',
       nextAction: 'fix the reds, then re-judge',
       changeInCandidate: { judgingContainsPath: true } }  // a content check, not a timestamp guess

// each hop has its own lever:  git-sync:run (commit now) ·
// release:checkpoint-run (re-judge now) · release:deploy (ship the green pin)
SECTION 12
12

Safety & verification

The short versionAutonomy is only useful if you can trust what comes out the other end — so verification and containment are architectural, not aspirational.

Verification is layered from the change outward — and even the guards are tested.

A mutation probe deliberately breaks a guarded property to prove the guard can actually fail — because a guard that has never failed is a guard nobody has tested.

Containment is just as structural:

  • every spawned process tree is enrolled — in a task ledger, confined by the OS, and killed by identity, never by name pattern — so an agent can't take down its neighbors (or your desktop) with an over-broad kill
  • secrets never enter the tree — credentials live in injected configuration outside the repo, with lint and pre-call hooks watching the boundary
  • feature flags default on — finished work never ships dark, with a shrink-only registry (and expiry dates) for the rare flag that must stay off
  • the truly dangerous sits behind owner gates — irreversible migrations, outward-facing sends, force-deploys past a red gate: a human says yes, loudly, and the ledger remembers who

PaperCusp is in private testing — request access · home

SECTION 13
13

The carry inventory

The short versionA session is disposable; its work is not. Everything an agent needs to stay on task is tracked outside the window — and the GUI shows you the very same rows.

Kill any session mid-task — a crash, a context cut, a machine restart — and the question that matters is: what does its successor need to resume on task rather than start over?

PaperCusp's answer is a specific, enumerable carry inventory, written as the work happens — write-through, never a dying gasp.
// a carried CLAIM travels with the probe that falsifies it — so a successor can
// tell an asserted claim from a verified one, and re-check instead of re-trust
work_items:checkpoint { id: 'WI-1204',
  checkpoint: 'backfill 60% — resume at batch 41',
  checks: [{ claim:    'live mp3 is the 140.5s build',
             recheck:  'curl -sI …/arch-tour.mp3 | grep content-length',
             verified: '21:07Z — 1,124,589 bytes, matches' }] }

// rendered on every re-injection: ✓ VERIFIED (with evidence) vs ? PREDICTED (run the probe first)

A successor re-orients and continues. Warm or cold (§08), it rebuilds from the inventory: same identity, same claims, same task, new window.

And the GUI is not a dashboard bolted onto the side — it renders the same store the successor reads (§01). What you watch is the carry.