Six stages, two use cases, one package.
The framework on one page: one system, three planes (studio, runtime, training), six stages, deployable on my VMs on hypothesys.ai or the customer's premises
The framework
THE FRAMEWORK · ONE SYSTEM, THREE PLANES, SIX STAGES
Where it came from, what each of the six stages is, where each one runs (the studio, the runtime and the training system), and the customer both use cases serve.
Every company does two kinds of reading, all the time, and every company is regulated by someone: a government, a customer contract, an auditor, its own policies.
The first is documents. Vendors send contracts, security reports and invoices. Someone has to read each one, pull out the facts that matter (a liability cap, an audit period, a total), check them against the company's rules, and send the risky ones to the right person. It is high volume, repetitive, and a single wrong value can auto-renew a contract or approve a payment nobody should have made.
The second is rule change. Regulators, customers and standards bodies publish new versions of the rules a company lives by. Someone has to find what changed, decide whether it touches anything the company owns, work out what to do, and tell the right people, with reasons they can check. It is lower volume, much harder, and the important change is usually one small edit in a long document.
I built a system that does both, and packaged it so a company can run it on its own servers. I show it for a fictitious utility, Acme Power & Light, because a utility lives under more rules than most companies: if the framework works there, it works for a bank reading loan covenants, a hospital tracking payer policies, a manufacturer following supplier contracts and safety standards, or a software company answering security questionnaires.
This post is about the framework behind it: six stages, each one a capability in One Roof, my development environment for agent work. The picture above is the whole framework on one page. The first part of the post explains it: where it came from, what each stage is, and where each stage runs. The next two parts follow each use case, documents first, through all six stages, with every detail of how Lab 5, Acme Lab, is built.
How the framework was conceived
I did not start with a framework. I started with a question, built a lab to answer it, and let each lab's failure set the next question. Five labs later, the same six things had happened every single time:
- Something arrived, and I had to decide what it was and whether I was allowed to act on it.
- I had to decide who or what does each piece of the work: plain code, a small model, or a language model.
- I needed to know how each piece actually performed on real work, not on a leaderboard.
- I needed tests with known answers, kept honest with intervals and with synthetic and real results apart.
- When a model was the weak part, I had to make it better, and prove the improvement before trusting it.
- I had to deliver the proven version somewhere else, and be able to take it back.
Those six became the stages. They are general: none of them is about energy or invoices. That is why the same framework delivers both use cases.
I built this in labs, each one answering a question the previous one raised. All five share one engine, labs-core: intake checks, citations that verify themselves, job states, a case record, a policy layer, an LLM layer, an API and a deploy chart. A lab is a plug-in on top.
- Lab 1 · Energy Lab 1 · obligations, impact and action Diff two docket versions, recognise the kind of change, find the obligations it touches, cite the evidence, route a warrant to a reviewer. The question it raised: the differ can't tell a restyle from a rule change.
- Lab 2 · Energy Lab 2 · change to action, in four parts A trained matcher, a deterministic guard and a fallback that tell material changes from cosmetic ones; a map of how rules from different regulators interact. False alarms on cosmetic edits: from 100% to 4.9%.
- Lab 3 · Document Lab · reading, extraction and citations Contracts, SOC 2 reports and invoices into fields, every field proven by a citation, every risky field sent to the right reviewer. Invented values: 0.56% delivered.
- Lab 4 · One Roof Lab · sessions, status and orchestration The development environment itself: many agents, many accounts, one place to direct, watch and measure them.
- Lab 5 · Acme Lab · a packaged agent framework All of it, for one fictitious regulated customer: intake, crews, agents and their performance record, exams, training, a customer control plane, APIs, and a package Acme installs on its own VM.
Each lab answered a question the previous one raised · Interactive version in the original post
| Lab | What it proved | The number that says so |
|---|---|---|
| Energy Lab 1 | A docket change can become a routed, cited action for a specific company | Citation tampering: 3 of 3 caught, 0 of 12 false alarms |
| Energy Lab 2 | A small trained model plus a deterministic guard tells material changes from cosmetic ones | F1 0.47 → 0.885; false alarms 100% → 4.9% |
| Document Lab | Every extracted value can be proven by a citation, and the unprovable ones stopped | 0.56% invented values delivered; 3 of 3 injection attacks held |
| One Roof Lab | Many agents can be directed, watched and measured from one place | The environment this whole system was built in |
| Acme Lab | The whole system packages as one product for one customer | Installed and running on the customer's own machine |
The six stages
| # | Stage | The question | Where it lives in One Roof |
|---|---|---|---|
| 1 | Intake | What is this system for, what is this request asking, and is it allowed? | Intake, the first place in the Build group |
| 2 | Factory | Which crew does each job, and how? | Factory |
| 3 | Agents | What does the work (model, serving, harness, tools and context, instructions, permissions), and how well did it do? | Agents |
| 4 | Evals | How does each part score on a fixed test? | Evals |
| 5 | Train | How does the weak part get better? | Train, the last place in the Build group |
| 6 | Ship | How does the proven version reach the customer? | Ship, which closes the Run group (Packages, then Deploys) |
One Roof's sidebar is organised the same way. Work is the desk (Home, Inbox, Sessions, Projects). Build is stages 1 to 5, in order: Intake, Factory, Agents, Evals, Train. Run is where a built system operates and leaves: Loops, Trace, Resources and, last, Ship. Read top to bottom, the sidebar is the life of an agent system.
Two loops run through it. Evals → Train → Evals is the improvement loop: nothing a training round produces is trusted until it passes the exam again. Ship → Agents is the feedback loop: what the system does at the customer flows back into the record, and from there into the next exams and the next round of training.
Each stage is a capability in One Roof that any agent system can use. Here is what each one is, before the use cases show it at work.
Stage 1 · Intake: the contract with the customer. Before any agent works, the system decides what a request is and whether it may act on it. Intake has six layers: the use-case menu (what the system does and refuses), intent classification (what this request is actually asking, often more than one thing), channels and APIs (how requests arrive and in what shape), restrictions (rules no request can override, in code), customer controls (the customer's own switches, limits and audit trail) and input safety (checks on every file before any model reads it). Opened in full under documents (the gate, the contract) and rule change (intent, restrictions, controls).
Stage 2 · Factory: the crew that does the work. A recipe names the roles a job needs, who or what plays each (code, a small trained model, or a language model), the pattern they work in (pipeline, maker → checker, two answers → judge, loop until green, fan-out → merge), the finish line and the budget. The rule: every step is done by the cheapest thing that does it well, and exact things are done by code. Opened in full as the extraction crew (documents) and as the compare → interpret → decide crew (rule change).
Stage 3 · Agents: what does the work. An agent is a model, how it is served, the harness around it, its tools and context, its instructions and skills, and an identity with permissions: a Claude Sonnet model in a document-reading worker with a PDF reader and a citation checker; a 23 MB cross-encoder served on a CPU; Claude Haiku 4.5 writing a warrant through a model gateway; Claude Code or Codex building the system itself. This stage chooses and serves the models (closed, open-weight or local), defines each agent's harness, tools, context and permissions, and keeps the performance record: every step of every case writes a work record (who did it, on what kind of task, with what result, how much a person had to step in, what it cost and how long it took), with reviewers' verdicts as labels. Opened as the document readers and their per-field record, and as the comparison crew's agents and their per-step record.
Stage 4 · Evals: the exams. Golden sets with known answers (documents with keys measured from the files, docket pairs built by construction, intents with the right decision, citations tampered with on purpose), scored with 95% intervals, with synthetic and real results always kept apart. Below the bar, nothing moves forward. Opened as the document exams and the docket exams.
Stage 5 · Train: the improvement loop, and the system that runs it. Training covers everything that changes a model's weights: classic machine-learning models (classifiers, cross-encoders, rerankers, embedding models), continued pre-training on a domain corpus, supervised fine-tuning (full or with LoRA adapters), preference learning, reinforcement learning (from human feedback and from rewards code can verify), distillation from a strong model into a small one, and quantisation for serving. It is the most expensive stage, so it runs on a separate training system with its own data pipeline, GPU and CPU compute, experiment tracking, model registry and compute budget. When the record and the exams point at a model, it is improved in rounds, and every round goes back to the exam before it can ship. Opened as the training system and the extraction and intent models (documents), and as the cross-encoder matcher, round by round (rule change).
Stage 6 · Ship: package and deploy. The proven system is frozen as a version (the engines, the customer's configuration, the models, the exams it must pass) and deployed through staging, hosted on my VMs on hypothesys.ai or on the customer's own premises, with a one-step rollback. Opened as what ships for documents and how a retrained matcher reaches the customer as a safe upgrade.
Where each stage runs: the studio, the runtime and the training system
The six stages describe the work. Underneath, the system runs on three separate planes, and keeping them apart is what makes it safe to package and ship.
| Plane | What it is | What runs there | Where it lives for Lab 5 |
|---|---|---|---|
| The studio | One Roof, the development environment | Designing intake (use cases, intents, restrictions, controls), writing recipes, reading the record, starting exams and training runs, building packages | My Mac. It is never in the path of a live request |
| The runtime | The engine that serves live requests | Intake and Factory run here, on every request: the input gate, the intent classifier, restrictions and controls, then the crew. Agents run here and write the performance record, one row per step, as the work happens. Also the job queue, the case store and the audit trail | labs-core: Acme Lab plus the Energy Lab 1, Energy Lab 2 and Document Lab engines, on the hypothesys cluster and, for a customer, in containers on its own VM. Models served here: the 23 MB cross-encoder on a CPU, small open models, and language-model calls to an API or to an open model on the customer's hardware |
| The training system | Separate, offline compute for making models | Train runs here: fine-tuning, domain pre-training, learning from reviewers. It reads data exported from the runtime's record and from the corpora, never live traffic, and writes versioned models into a model registry | CPU or GPU jobs (the first cross-encoder round took 24 minutes on a CPU; domain pre-training needs GPUs), started and watched from One Roof's Train place, on Modal, Hugging Face or owned GPUs |
The stages map onto the planes like this:
| Stage | Designed in | Runs in |
|---|---|---|
| 1 · Intake | the studio | the runtime, on every request |
| 2 · Factory | the studio | the runtime, on every request |
| 3 · Agents | defined in the studio (model, harness, tools, permissions); the record is read there | the runtime: agents run and serve their models there, and write the record as work happens |
| 4 · Evals | started from the studio | an exam harness: offline, against golden sets, before anything ships (in CI or as a job); the runtime's record adds an online check after shipping |
| 5 · Train | started from the studio | the training system, offline; results go to the model registry |
| 6 · Ship | built from the studio | the release pipeline (Woodpecker → Kargo → Argo CD on my cluster; the package and its install script at a customer), which takes a model from the registry plus recipes and configuration and deploys them into a runtime |
The planes form one loop. The runtime does the work and writes the record. The record and the corpora are exported to the training system. Training produces a candidate model in the registry. The exam harness tests it. If it passes, Ship packages it and deploys it into the runtime, and the runtime's record watches it on real work, which starts the loop again.
Two consequences shape Lab 5. First, the customer receives the runtime and its control plane, not the studio: One Roof stays with whoever builds the system. Second, training can live wherever the data may go: on my training system for the public corpora, or inside the customer's boundary when its documents and reviewers' verdicts cannot leave.
Framework capabilities
The six stages say what happens. The capabilities say how: the technical parts each stage is built from. They are the specification Acme Lab is built against, and the roadmap for what One Roof provides in each of its places.
The capability map: six stages × six layers, every capability marked with where it runs
How to read it: each column is a stage and the One Roof place of the same name. Each row is a layer: the interfaces people and systems use, the logic that decides, the models that read and reason, the data it keeps, the infrastructure it runs on, and the governance that keeps it safe. Each tile is one capability, and its dot says which part of the system it runs in. The tables below define every capability and say how Acme Lab implements it.
Stage 1 · Intake: the contract
| Layer | Capability | Runs in | What it does | In Acme Lab |
|---|---|---|---|---|
| Interfaces | REST API | runtime | Typed endpoints that accept requests with their attachments and return a case id and the intake decision. | POST /intake, /intake/use-cases, /intake/intents |
| Interfaces | Upload · mailbox · webhook | runtime | The other doors a request can come through, each normalised into the same request shape. | upload and mailbox channels in the package manifest |
| Logic | Intent classifier | runtime | Maps a request to intents from a fixed list, several per message, with calibrated scores and a real 'none of these'. | rules plus a small model; route above 0.85, restricted intents counted from 0.6 |
| Logic | Use-case registry | runtime | The menu: each use case with its intents, channels, recipe and whether it is switched on. | data/acme/use_cases.json, toggled from the control plane |
| Logic | Routing | runtime | Turns intent + restrictions + controls into route, person or refuse, with the reason. | decision rules in the intake engine |
| Models | Small intent model | runtime | A small model that refines intent when the rules are unsure; can run next to the data. | Qwen3-1.7B class, optional in real mode |
| Models | OCR and layout | runtime | Reads scans and page layout before anything else does, and scores the scan's quality. | labs-core PDF reader and OCR quality score |
| Models | PII detector | runtime | Finds personal data to mask and record before any model sees it. | labs-core intake PII check |
| Data | Request schemas | runtime | The shape every channel's request must take, validated at the edge. | intake request schema |
| Data | Audit log | runtime | Every request, its intents, the decision and the reason, append-only. | GET /audit |
| Infrastructure | Tenancy and auth | runtime | Which customer a request belongs to and who may send it. | per-tenant registers and access codes |
| Infrastructure | File store | runtime | Where arriving files live, with their hash, so duplicates are caught per customer. | the lab's outputs volume |
| Governance | Input safety gate | runtime | Cheapest checks first: file type, size, integrity, encryption, active content, duplicates, scan quality, type, injection, hidden text, PII, page limit. | labs-core intake gate (12 checks, cheapest first) |
| Governance | Restrictions as code | runtime | Rules no request can override, outside every prompt. | never move money, never change payment details |
| Governance | Customer controls | runtime | The customer's switches and limits: use cases, approval limits, allowed models, budgets, stop switch. | GET/PUT /control |
Stage 2 · Factory: the crew
| Layer | Capability | Runs in | What it does | In Acme Lab |
|---|---|---|---|---|
| Interfaces | Recipe definitions | studio | A versioned file per recipe: use case, roles, who plays each, pattern, finish line, budget. | docket-change-to-action, document-to-record |
| Interfaces | Review queues | runtime | Where people approve, correct, reject or escalate, per field or per change. | POST /cases/{id}/decision |
| Interfaces | Connectors | runtime | Writes into the customer's systems of record: ERP, CRM, document stores. | mock CRM/ERP behind an outbox |
| Logic | Orchestration engine | runtime | Runs a recipe as a state machine: steps, dependencies, retries, timeouts, job states. | labs-core job states (queued … dead_letter) |
| Logic | Pattern library | studio | Pipeline, maker → checker, two answers → judge, loop until green, fan-out → merge. | five built-in patterns |
| Logic | Validators and guards | runtime | Deterministic checks that can only escalate: numbers, durations, duties, negations, business rules. | the value/duty guard; validation rules |
| Logic | Citation verifier | runtime | Re-fetches every cited span, normalises it and compares fingerprints; drift blocks. | labs-core provenance; the citation ladder |
| Models | Models per role | runtime | Each role names its agent: code, a small trained model, or a language model. | matcher = cross-encoder, writer = Haiku |
| Models | Retrieval | runtime | Keyword (BM25), vector or hybrid search to shortlist candidates and evidence. | BM25 shortlist, top 4 per provision |
| Data | Case store | runtime | Every case, step, output and citation, queryable. | SQLite in the lab; Postgres at scale |
| Data | Outbox and idempotency | runtime | Every write to a customer system goes through an outbox with an idempotency key, so a retry never writes twice. | idem_key = job:target |
| Infrastructure | Workers and queues | runtime | Sync lane for small jobs, async lane with chunks for long ones. | 8-page chunks, 1 page overlap |
| Infrastructure | Circuit breakers | runtime | Stop calling a failing provider, cool down, probe, redrive; errors are never swallowed. | opens after 3 rate limits in 60 s |
| Governance | Budgets per run | runtime | Minutes, dollars, rounds and parallel parts, set per recipe. | daily dollar cap; per-recipe budget |
| Governance | Rollback | runtime | Restores the pre-state of anything a case wrote, with an audit entry. | rollback(job_id) |
Stage 3 · Agents: what does the work
| Layer | Capability | Runs in | What it does | In Acme Lab |
|---|---|---|---|---|
| Interfaces | Agent definitions | studio | Each agent written down: model, serving, harness, tools, context, instructions, permissions. | readers, matcher, writer, judge, builders |
| Interfaces | Model catalogue | studio | Every model the system may use, with its kind, cost tier and where it may run. | closed, open-weight, local, classic |
| Logic | Harnesses | runtime | The loop around a model: plan, call tools, recover, stop. | document worker, labs-core reasoner, coding agents |
| Logic | Tools and context | runtime | What an agent can call and see: readers, retrieval, registers, memory. | PDF reader, citation checker, Acme register |
| Logic | Routing by evidence | runtime | Picks the agent for a role from the record, within the budget. | best value for this kind of task |
| Models | Closed models | runtime | Hosted frontier and fast models for reading, writing and judging. | Claude Opus 5.5, Sonnet 5.5, Haiku 4.5; GPT via Codex |
| Models | Open-weight models | runtime | Models that run on the customer's own hardware. | Qwen3-VL, Qwen3-Coder, gpt-oss-120b |
| Models | Classic models | runtime | Small trained models that do one job cheaply and exactly. | the 23 MB cross-encoder |
| Data | Work records | runtime | One row per step: agent, model version, kind, result, human effort, cost, time. | GET /record, /record/work |
| Data | Reviewer verdicts | runtime | Accept, correct, reject: the labels public benchmarks lack. | decisions written to the record |
| Infrastructure | Model gateway | runtime | One door to every hosted model: routing, fallback, keys, spend ceilings. | LiteLLM-style gateway, bring-your-own-key |
| Infrastructure | Inference serving | runtime | Open models on GPUs (vLLM, llama.cpp) and classic models on CPUs (ONNX). | ONNX Runtime for the matcher |
| Governance | Identity and permissions | runtime | What each agent may touch, enforced on the agent. | readers write only to the case |
| Governance | Cost and limits | runtime | Tokens, dollars and subscription limits per agent and per run. | dated price table; daily caps |
Stage 4 · Evals: the exam
| Layer | Capability | Runs in | What it does | In Acme Lab |
|---|---|---|---|---|
| Interfaces | Exam runner | exam harness | Runs any golden set on demand or in CI, against any version. | POST /evals/{set}/run |
| Interfaces | Results with intervals | exam harness | Every rate with a 95% interval and a sample size. | Wilson intervals on every metric |
| Logic | Metrics library | exam harness | F1, precision, recall, calibration (ECE), silent errors, out-of-scope recall. | document, docket and intent metrics |
| Logic | Model as judge | exam harness | A strong model grades what code can't, with its agreement with people measured. | Claude Opus 5.5 judge on canary cases |
| Logic | Regression gates | exam harness | A version below the bar cannot be packaged or promoted. | must-pass bars in the manifest |
| Models | Public benchmarks | exam harness | Leaderboard tests, as a first filter for new models. | used to decide what to try, not what to trust |
| Data | Golden sets | exam harness | Versioned items with known answers, split so nothing leaks into training. | Acme: 152 intents, 18 docket pairs, 51 documents |
| Data | Built by construction | exam harness | Labels that follow from how an item was made: operators on provisions, keys measured from PDF bytes. | 33,307 pairs; seeded document generator |
| Data | Adversarial items | exam harness | Attacks on purpose: encrypted, injected, duplicated, tampered, low-resolution. | 18% of the document set |
| Infrastructure | Shadow and A/B | runtime | A candidate runs beside the incumbent on real work, judged but never shipped. | two answers → judge |
| Infrastructure | Drift monitoring | runtime | Watches document, template and model drift in the live record. | fallback share, correction rate by source |
| Governance | Synthetic ≠ real | exam harness | Synthetic and real results are always reported separately. | F1 0.885 synthetic vs 0.85 real |
| Governance | Calibration | exam harness | Stated confidence must match how often the system is right. | ECE 0.05 on real documents |
Stage 5 · Train: the improvement
| Layer | Capability | Runs in | What it does | In Acme Lab |
|---|---|---|---|---|
| Interfaces | Training jobs | studio | Start, watch and compare runs from One Roof's Train place. | jobs on hosted or owned compute |
| Interfaces | Experiment comparison | studio | Two runs side by side: data, settings, metrics, cost. | experiment tracking |
| Logic | Active learning | training system | Chooses what to label next: disagreements, corrections, failing sources. | guard-vs-model disagreements first |
| Logic | Hard negatives, held-out types | training system | Training data that teaches the difficult cases and tests generalisation honestly. | same-docket negatives; 4 held-out operators |
| Models | Classic ML | training system | Classifiers, cross-encoders, rerankers, embedding models. | the 3-way cross-encoder, 24 min on a CPU |
| Models | Pre-training and fine-tuning | training system | Continued domain pre-training; supervised fine-tuning, full or LoRA. | regulatory-corpus pre-training, then fine-tuning |
| Models | Preference and RL | training system | Preference learning from reviewers; RL from human feedback and verifiable rewards. | rewards: citation verifies, field matches |
| Models | Distil and quantise | training system | A strong model's judgement into a small one; int8 / 4-bit export. | int8 ONNX, 23 MB |
| Data | Record export | training system | Work records, verdicts and corrections out of the runtime, de-duplicated and scrubbed. | export from the record |
| Data | Dataset versions | training system | Every training and exam set versioned, so every model has a lineage. | MANIFEST with seeds and splits |
| Infrastructure | GPU and CPU compute | training system | Jobs where the data may go: hosted GPUs, owned GPUs, or inside the customer. | Modal, Hugging Face, owned |
| Infrastructure | Model registry | training system | Versioned models with lineage and exam results; Ship takes only from here. | matcher v1, v2… |
| Governance | Compute budgets | training system | A ceiling in GPU hours and dollars per run; cheapest fix first. | data before fine-tuning before RL |
| Governance | Data boundary | training system | Training happens inside the boundary the data belongs to. | customer data never leaves |
Stage 6 · Ship: package + deploy
| Layer | Capability | Runs in | What it does | In Acme Lab |
|---|---|---|---|---|
| Interfaces | Package manifest | release path | One file: engines, configuration, models, exams that must pass. | acme-framework manifest |
| Interfaces | Install script | release path | Pre-flight, pull, start, smoke test, on any VM. | install.sh in the bundle |
| Interfaces | Control-plane console | runtime | The customer's own console, shipped with the runtime. | the control plane |
| Logic | Promotion rules | release path | A version moves staging → production only after staging verifies it. | Kargo promotion |
| Logic | Canary and shadow | release path | A new version takes a slice of traffic or runs beside the old one first. | shadow before cut-over |
| Logic | Migrations | release path | Store and schema changes that move forward and back safely. | versioned schema |
| Models | Pinned models | release path | Every model in a package is a pinned registry version. | matcher and reader versions pinned |
| Data | Configuration and secrets | release path | The customer's settings and keys, never baked into images. | env files and cluster secrets |
| Infrastructure | Images and charts | release path | Signed images, Helm charts or a compose bundle. | labs-core base image and chart |
| Infrastructure | Hosted on hypothesys.ai | release path | My VMs: one isolated tenant per customer; build, sign, stage, promote, operate. | Woodpecker → Kargo → Argo CD |
| Infrastructure | On the customer's premises | release path | The same package on the customer's VM or cluster, online or fully offline. | one install script |
| Governance | Signing and SBOM | release path | Every image signed, its contents listed. | cosign-signed images |
| Governance | One-step rollback | release path | The previous version is always one deploy away. | previous freight / previous bundle |
| Governance | Compliance and agreements | release path | SOC 2 Type I, then Type II and ISO 27001 for the hosted service (H13); a data processing agreement naming every subprocessor. | hosted service attestations |
Across every stage
| Capability | What it means here |
|---|---|
| Security | Least privilege for every agent and service, secrets outside images, signed artefacts, attacks tested on purpose |
| Tenancy | Every request, record, model and setting belongs to one customer; nothing crosses |
| Audit trail | Every intake decision, step, citation, decision and control change, append-only |
| Observability and traces | Every case traceable step by step, with timings, costs and the agent and model version that ran |
| Cost accounting | Tokens, GPU hours and dollars per step, per case, per customer, from dated price tables |
| Versioning | Recipes, prompts, models, datasets and packages all versioned, so any result can be reproduced |
| Encryption and keys | Encrypted in transit and at rest, with per-tenant keys; a customer can bring its own key |
| Incident response | On-call, a status page, notification within contract and legal limits, written post-incident reviews |
| Backups and recovery | Per-tenant backups with point-in-time restore, tested by restoring; agreed recovery targets |
| Compliance | SOC 2 Type I, then Type II and ISO 27001 for the hosted service, sector rules where the data requires them, a data processing agreement |
| Data residency | Data stays inside the boundary it belongs to: my cluster, in the region the customer chooses, or the customer's premises |
Two use cases, one framework
Here is the whole post on one page: what each stage does for each use case. Every row is a part of the post.
| Stage | Documents (contracts, SOC 2 reports, invoices) | Rule change (versions of a regulatory docket) |
|---|---|---|
| 1 · Intake | "Review this SOC 2": intent, the input gate, hidden instructions held, the customer's rules | "What changes for us in GO 166?": intent, a second request in the same message that is not allowed, restrictions in code |
| 2 · Factory | Extract with a cheap model, prove every field with a citation, apply the rules, escalate per field, send to the right reviewer | Fingerprint, shortlist, cross-encoder, guard, name the change, map it to obligations, verify citations, write the warrant |
| 3 · Agents | The readers (a fast model, a strong model, an on-site document model) in a document worker, and a record per field | The crew's agents (a served cross-encoder, a warrant writer, an independent judge) and a record per step; reviewers' verdicts as labels |
| 4 · Evals | Invented values with intervals, calibration, intake accuracy, adversarial documents | The four-arm test, held-out change types, synthetic vs real, tampered citations |
| 5 · Train | Extraction and intent models: cheap model, then per-field escalation, then a document model fine-tuned on the customer's own fields | The matcher, round by round: base model, fine-tuning, guard, real data, domain pre-training, learning from reviewers |
| 6 · Ship | Package, the customer's control plane, APIs, install on the customer's VM | The same, plus how a retrained matcher reaches the customer as a new version |
Meet Acme Power & Light
Acme Power & Light is fictitious: a mid-size investor-owned electric utility with a growing fleet of solar and battery storage. It answers to the California Public Utilities Commission, the Federal Energy Regulatory Commission, the state grid operator CAISO, the reliability body NERC and the Air Resources Board. Its register lists obligations (each tied to the section of the rule it comes from, a category and an owner), projects, internal documents and the reviewers who sign off: General Counsel for regulatory matters, the VP of Rates, the VP of Asset Management, the Director of Compliance, the CISO's office, procurement and accounts payable.
Acme is built from the patterns of the two companies my energy labs modelled: an independent power producer and developer with a battery fleet, and a large investor-owned utility. Its dockets and documents are real ones from my labs' corpora: regulations from the Federal Register, eCFR, NERC, California bills, CPUC general orders, CAISO, CARB and utility tariffs, and the contracts, SOC 2 reports and invoices Document Lab reads.
Acme has two kinds of work it wants agents to help with:
- Documents. Vendor contracts, SOC 2 reports and invoices arrive. What do they say, is every value provably right, and who must look at what?
- Regulatory change. A new version of a rule arrives. What changed, what does it mean for Acme, who must act, and why?
Documents are the easier of the two and the more familiar, so they come first.
Use case: Documents
USE CASE 1 OF 2 · DOCUMENTS
Contracts, SOC 2 reports and invoices: read every one, prove every value, apply the customer's rules, and send only what needs a person to the right person. The easier of the two use cases, and the more familiar, so it comes first.
One document, end to end
Acme's procurement team uploads a vendor's security report before renewing its contract, with one line: "Can we keep using Willowmere? Their SOC 2 is attached."
ONE SOC 2 REPORT, FROM UPLOAD TO A DECISION
- 14:00 · It arrives, and the intent is clear. The classifier reads the request: review a SOC 2 report (0.94). The use case is on Acme's menu and switched on. Nothing restricted.
- 14:00 · Checked before anyone reads it. A real PDF, not locked, not broken, no scripts, not a duplicate, a text layer, no hidden instructions, twelve pages. Personal data noted and masked. Answer: accept.
- 14:00 · A cheap model reads it into fields. Vendor, auditor, report type, audit period, opinion, exceptions, bridge letter. Every field comes back with the page, the box on the page and the exact words.
- 14:01 · Every citation is checked by code. Each quote is found in the PDF, exactly or normalised. A field without a provable citation is not delivered; it goes to a stronger model or to a person.
- 14:01 · Acme's rules run. Type II: yes. Opinion: unqualified. One exception noted: for 2 of 25 terminated users, access was not revoked within a business day. And the audit period ended more than 12 months ago.
- 14:01 · To the security team, with the reason. The report is stale. The case goes to the CISO's office with one line: ask Willowmere for a bridge letter or a new report, and look at exception CC6.2.
- 16:20 · A person decides. The CISO's office requests a bridge letter and holds the renewal until it arrives. The system never approves a vendor on its own.
- 16:20 · Everything is kept. Every field, citation, rule, decision and its reason go into the case record and the performance record.
Each step belongs to a stage: the first two are Intake, the next four are Factory, and the record at the end is written by the agents (stage 3). The sections below take the stages one at a time.
Stage 1 · Intake: is it safe, and what is it asking?
What this stage does here
For documents, files are the attack surface: nothing reaches a model that shouldn't.
The intake contract
Intake is not an inbox. An inbox is where messages wait for a person. Intake is the contract between a customer and its agents, and it has six layers (table below); a request meets them in five steps:
A request's path through intake
- How requests arrive. A structured API call from the customer's document system needs little interpretation. A free-text email needs a lot. Each channel has a shape, and each is something the customer switches on. Structured channels first: an API call carries its own fields. Free text is the hardest case, and the one intent classification is for.
- Is it safe to read? Before any model reads a file: is it what it claims, readable, unlocked, not a duplicate, free of scripts and of hidden instructions? Accept, send to review, or reject. A reject always carries a reason the customer can act on.
- What does it intend? A small, cheap classifier maps the request to intents from a fixed list, with a confidence, and spots when one message holds two requests. Several intents per message, each with its own score. 'None of these' is a real answer, routed to a person.
- Is it allowed? Restrictions are rules no request can override. Customer controls are the switches the customer sets. Both live in code, not in a prompt. Restrictions: never move money, never change payment details. Controls only tighten: a customer can raise a floor, never lower one.
- Where does it go? This intent, allowed for this customer, through this channel, goes to this recipe, or to a person, or gets a specific, polite no. Every decision is written to the audit trail. Route, person or refuse, always with the reason.
| Layer | The question | At Acme |
|---|---|---|
| Use cases | What jobs does the system do, and which does it refuse? | Assess a regulatory change; answer an obligation question; track a filing deadline; review a contract; review a SOC 2 report; process an invoice. Never: approve a payment; change vendor bank details |
| Intent | What is this request actually asking for? | "What changes for us in the new GO 166?" vs "When is our next filing due?" vs "Pay this today" |
| Channels and APIs | How can requests arrive, and in what shape? | A REST API, an upload page, an intake mailbox, a webhook from the document system |
| Restrictions | What must it never do, whatever the request says? | Never approve or send money; never change payment details; nothing sensitive to a hosted model; every case ends with a person |
| Customer controls | What can the customer switch, limit and see? | Use cases on and off, approval limits, allowed models per kind of data, budgets, the audit trail, one stop switch |
| Input safety | Is the thing that arrived safe and readable? | File type, size, integrity, encryption, active content, page limits, duplicates, text or scan, document type, injection, hidden text, personal data |
Two layers sit after intent, and both are code, never a prompt.
Restrictions are the rules no request can override. At Acme: never approve or send money; never change a vendor's payment details; never send sensitive data to a hosted model; every case ends with a person. A message that combines an allowed request with a restricted one is split: the allowed part continues, the restricted part goes to a person, with the reason.
Customer controls are the customer's own control plane: a console on the customer's side where it switches use cases on and off, sets approval limits and approvers, chooses which models may see which kind of data, sets budgets, reads every request with its intent, decision and reason, and stops everything with one switch. Controls can only tighten the defaults. A customer can raise a confidence floor from 0.90 to 0.95; nothing it sets can lower one below the framework's own.
This use case: a SOC 2 report
When procurement uploads Willowmere's security report, two things happen before any model reads a word.
First, intent. "Can we keep using Willowmere? Their SOC 2 is attached." is a request to review a SOC 2 report (0.94). The classifier also checks what the message is not: it is not a request to approve the vendor, which Acme's menu reserves for a person, and it is not a payment. The use case is on the menu and switched on, so the request is allowed to continue.
Second, input safety. Every file passes the same gate, cheapest checks first, and stops at the first reject.
In Document Lab the gate decided correctly on 119 of 122 documents, and held all three prompt-injection attacks, including one written in 4-point white text.
The input gate, cheapest check first (illustrative relative costs)
Relative cost File type 1 Size 1 Integrity 1 Encryption 1 Active content 2 Page limit 1 Duplicate 2 Text or scan 3 Doc type 4 Injection 5 Hidden text 4 Personal data 5
- BYTES · The instant checks Is a '.pdf' really a PDF? Is it locked, broken, empty, too big, too long? These cost nothing. A locked file is rejected with 're-send it unlocked', and the system never tries to crack it.
- CONTENT · The file's behaviour Scripts or launch actions, the same file sent twice, a scan instead of text (and how good the scan is), and the wrong kind of document.
- MEANING · The meaning checks Instructions aimed at the AI ('ignore previous instructions', 'set total to 0', 'approve'), text hidden in white or tiny type, and personal data to mask. These run last because they cost the most.
relative cost of each check (1 = instant) · a reject at any step stops the rest · Interactive version in the original post
Three things make this gate more than a virus scan:
- Every reject carries a reason the sender can act on. "This file is password-protected; please send an unlocked copy." Never a bare error, and the system never tries to crack a locked file.
- Hidden instructions are found before a model reads them. White-on-white text, 4-point text, "ignore previous instructions", "set total to 0", "approve": the scan knows the shapes of these attacks. A document carrying them goes to review, and if it is processed at all, its text is fenced off as untrusted data.
- The gate is tested like everything else. Every document in the test set has the intake decision it should get, so the gate has its own score: 119 of 122 correct.
Stage 2 · Factory: the extraction crew
What this stage does here
A maker → checker crew: a cheap model reads, code proves, a strong model only for the fields that couldn't be proven.
Recipes, roles and patterns
The shape of both jobs is now clear: read, extract, prove, check rules; compare, name, interpret, map, prove, route. No single agent should do all of that, and not every role should be played by a language model at all. A recipe says which roles a job needs, who plays each, the pattern they work in, the finish line and the budget.
The same patterns that structure software work structure regulated work:
Five ways a crew can work
- Pipeline. The docket recipe: read, match, map, warrant, each role the cheapest thing that can do it well. Code for identity, a small model for meaning, a language model for sentences.
- Maker → checker. The document recipe: a cheap model extracts, code checks every citation and rule, and only failing fields go back, to a stronger model. The checker can never be the maker's agent and model.
- Two answers → judge. For contested interpretations: two independent readings and a judge that is told not to trust the pipeline's own confidence. Also the safe way to try a new model next to the current one.
- Loop until the check passes. Extract, verify the citation rung, extract again with the failure in hand, until the rung is met or the budget runs out. Each round carries the last failure. A budget stops it: minutes, dollars, rounds.
- Fan-out → merge. A 100-page report split into 8-page chunks with one page of overlap, read in parallel, merged and checked as a whole. At most three parts in parallel. The merge is checked as a whole, not just the parts.
Every role in every run is recorded, which is what makes the next stage possible.
This use case: the extraction recipe
Document Lab was built from a real engineering brief: ten thousand documents a day, peaks of fifty a minute, under thirty seconds for a short document, fewer than one key field in a hundred invented, and a person reviewing anything below 85% confidence.
A field you can prove
Document Lab's founding rule is that every extracted value must be proven by a citation: the page, the box on the page, and the exact words it came from. That turns "hallucination" into something you can count: a value with no citation behind it.
Citations are checked on a ladder, strongest first: an exact quote, a normalised match, the value found in the span, or the span entails the value. Identifiers, like a purchase-order number, must be exact. A field's confidence blends the model's confidence, the citation's rung and the validation rules, and it is capped hard when the citation is weak or a rule fails.
Here is a real case from the corpus. A SOC 2 report for a software vendor, Willowmere Software Corp., audited by Marrowgate Assurance LLP:
| Field | Value | Proven by |
|---|---|---|
| Report type | Type II | page 1 |
| Audit period end | 21 June 2025 | page 1, quote "June 21, 2025" |
| Opinion | Unqualified | page 4, "In our opinion, in all material respects" |
| Exceptions | 1 | page 11, "Total exceptions noted: 1" |
| The exception | CC6.2: for 2 of 25 terminated users sampled, access was not revoked within one business day | page 11 |
| Decision | Review, security queue: the report is more than 12 months old; ask for a bridge letter or a new report | the rule period_end_within_12_months
|
Every row can be checked by opening the PDF at the cited page. That is what lets a security reviewer trust the 90% of the work they didn't have to do.
Cheap first, strong only where needed
Extraction runs on a fast, cheap model first, at temperature zero. Only fields whose citation fails, or which the cheap model declined to answer, go to a stronger model. Fields that fail a business rule don't: a stronger model can't fix a stale report. Escalation is per field, not per document, and a daily dollar cap stops paid calls entirely when it is reached.
Look at the first tile in the Document Lab results: the interval is reported, not just the rate. With 70 documents, 0.56% could really be as high as 2%. To prove a rate under 1% you need about 300 key fields with no errors. The lab says so on its own page.
The same document, two customers
Customer rules can only tighten the defaults, never loosen them, and the same document lands differently for different customers:
- A Type I SOC 2 report with a clean opinion passes one customer's rules and fails another's, which requires Type II for vendor approval.
- A contract whose renewal notice deadline is 60 days away creates a procurement task for one customer and nothing for the other.
- A re-posted invoice number is rejected outright by a customer with a duplicate-payment rule.
- A notice period extracted at 0.93 confidence is committed for one customer (floor 0.90) and sent for review by another (floor 0.95, because "a wrong notice period auto-renews contracts").
Acme's rules sit in its control plane, and they are part of the package.
What production taught me
Document Lab includes two cases built to show what goes wrong when an agent system meets production.
A naive worker versus a hardened one. I took the kind of 20-line extraction worker that shows up in real pull requests (a general model, temperature 0.7, raw JSON parsing) and ran it against a hardened worker on 17 scenarios. The naive one failed on 18 findings, 6 of them critical. In one, an invoice with a hidden instruction caused the naive worker to save the total as 0.00withstatus"approved".Thehardenedworkersentittoreviewwiththetruetotal,0.00 with status "approved". The hardened worker sent it to review with the true total, 0.00withstatus"approved".Thehardenedworkersentittoreviewwiththetruetotal,7,420.00, cited. At temperature 0.7 the naive worker gave three different totals in five runs of the same invoice.
A rate-limit storm. A hundred contracts over an hour; for ten minutes, the model provider returns "too many requests". The naive worker swallowed the errors and its dashboard stayed green.
A rate-limit storm: naive vs hardened
- 15 Silent failures (naive)
- 0 Silent failures (hardened)
- 2 Minutes to detect (hardened)
- 4 Hours of manual re-keying (naive)
Two lessons from those cases are now principles of the framework: errors are never swallowed (every exit is a visible job state, and the customer sees the same truth the engineers see), and the write is the point of no return (every write to a customer system goes through an outbox, with an idempotency key so a retry never writes twice, and a rollback that restores the previous state with an audit entry).
Stage 3 · Agents: the readers, and a record per field
What this stage does here
Choose and serve the models that read documents, give each a harness, tools, context and permissions, and record every field each one decides.
What an agent is
The work in every recipe is done by agents, and an agent is more than a model. It has six parts, and the framework defines each one explicitly:
| Part | What it is | Why it is defined, not assumed |
|---|---|---|
| Model | The weights that do the reading or reasoning: a closed model (Claude, GPT), an open-weight model (Qwen, gpt-oss), a small local model, or a trained classic model such as a cross-encoder | Cost, accuracy, latency and where the data may go all depend on it |
| Serving | How the model is reached: a hosted API, a model gateway with routing and fallback, an inference server (vLLM, llama.cpp) on a GPU, or ONNX on a CPU | The same model costs and behaves differently served differently, and a customer may require it on its own hardware |
| Harness | The loop around the model: how it plans, calls tools, handles errors and stops. A coding agent (Claude Code, Codex, OpenCode), a document-reading worker, or the labs-core reasoner | Most failures in production are harness failures: swallowed errors, retries that write twice, runaway loops |
| Tools and context | What it can call and what it can see: a PDF reader, the citation checker, retrieval over a corpus, the customer's register, memory of earlier steps | An agent is only as good as the context it is given, and only as safe as the tools it may call |
| Instructions and skills | Its prompts, recipes and skills, versioned | A changed prompt is a new agent; the record must know which one ran |
| Identity and permissions | Who it acts as, which folders, systems and data it may touch, with what limits | Restrictions are enforced on the agent, not requested of it |
The performance record is how each agent, defined this way, is measured on real work.
The performance record
A public benchmark tells you how a model does on a test. It doesn't tell you how an agent does on your work: your dockets, your documents, your rules. The Agents stage keeps a performance record of how each agent does: every piece of real work, by every agent, model and code path, on every kind of task.
One work record and its six questions
- Did it finish? Or did it stall, fail, hit its budget, or get stopped by the rate limiter? Stalled, failed and out-of-budget are all recorded. Unfinished work is counted, never hidden.
- Did the reviewer agree? Accepted as-is, corrected, or rejected. The reviewer's verdict is the ground truth that public benchmarks never have.
- Did it hold? Still right 14 days on: not corrected later, not reversed, no follow-up case on the same obligation. The strongest signal there is.
- Effort, cost and speed. How often a person had to step in, what it cost in dollars and compute, and how long until a decision. Shown beside results, never ranked alone. Activity such as lines or tool calls is not a result.
For work that has to be right, the record has a property public benchmarks can't have: reviewer verdicts are labels. Every time General Counsel accepts, corrects or rejects a warrant, the record learns which roles, models and kinds of change are trustworthy. Energy Lab 1 feeds those verdicts into calibration buckets, so stated confidence can be checked against how often reviewers actually agree. Its calibration machinery measured an error of 0.026 on synthetic verdicts; the real number arrives with real reviewers, and the record is where it lives.
The record compares like with like (within one kind of task and size), shows the sample size on every number and says "not enough yet" below five, starts a new record for every new model version, and shows the bad days alongside the average. It's how Acme knows whether the interpreter should stay on a cheap model, or whether the cross-encoder needs retraining on its own tariffs.
This use case: the document readers
Document work uses three readers, each a different agent:
| Agent | Model and serving | Harness, tools and context | Permissions |
|---|---|---|---|
| The fast reader | Claude Haiku 4.5 through the model gateway, temperature 0 | The document worker: page windows of up to 60,000 tokens, the document fenced as untrusted data, structured output (value, quote, page, confidence) | Read the document; write only to the case |
| The strong reader | A stronger Claude Sonnet model, called per field, only for fields the fast reader couldn't prove | The same worker, with the failed field, its page and the reason it failed | Same as the fast reader; a daily dollar cap stops paid calls |
| The on-site reader | An open vision-language model (the Qwen3-VL family) on the customer's own GPU, through an inference server | The same worker and tools | Never leaves the customer's network |
Around them sit code paths that are not agents (the citation ladder, the rules, the review queues), but they write to the same record, so a field's whole history is in one place.
This use case: a record per field
Every extracted field writes its own work record: which model read it, which rung of the citation ladder its quote reached, its confidence, whether it was escalated to the strong model, whether a rule failed, which reviewer looked at it, and what the reviewer did.
That makes questions answerable that a document-level score hides:
- Which fields need a person most often? Liability caps are "most often superseded by amendments", which is why one customer raised that field's floor to 0.92. The record shows whether the raised floor sends too much or too little to review.
- Where does the strong model earn its cost? If a field is escalated often and the strong model rarely changes the answer, the escalation is waste. If it changes the answer often, the cheap model is the wrong first reader for that field.
- Which vendors' templates drift? When a vendor changes its invoice layout, the fields from that vendor start failing their citations. The record shows it as a cluster before anyone notices by hand.
- How often is a person needed at all? The review rate (62.9% on the real-document run) is the honest cost of the system, and the number every improvement should move.
Stage 4 · Evals: the document exams
What this stage does here
Fields with answer keys measured from the files themselves, and almost a fifth of the test set (18%) built to attack the system.
The exams
Evals are the tests: golden sets where every item has a known right answer. They are controlled, so they compare cleanly, and they are honest only if you keep synthetic and real results apart.
The exams behind Acme Lab
- Docket pairs. 33,307 pairs built by construction (from 1,000 synthetic dockets and 157 real contracts), with four kinds of change held out of training entirely, plus real regulations from eCFR, the Federal Register, NERC, CPUC, CAISO, CARB and utility tariffs. Splits by docket, so nothing leaks between training and test.
- Documents with answer keys. Generated documents whose answer keys are measured from the saved PDF bytes, never estimated, plus 18% adversarial documents: encrypted, corrupted, duplicated, injected, scanned at low resolution, rotated, 100 pages long.
- Intents. Requests with the right intents and decision: single, multiple, restricted, ambiguous and out of scope. Out-of-scope recall must be near perfect.
- Citations under attack. A fifth of cited passages tampered with on purpose. All three tampered citations were caught, with no false alarms on the twelve clean ones, once a Windows line-ending bug that caused 30% false alarms was fixed.
- Scores become a gate. Every rate comes with a 95% interval. Below the bar, a model or a package doesn't ship. Above it, the score joins the record, next to the job history. Synthetic and real results are reported separately.
Three habits keep the exams honest:
- Intervals, not points. "0.56%" alone is a claim; "0.56%, could be up to 2%" is a measurement.
- Synthetic is not real. The trained matcher looked excellent on synthetic data and fell to F1 0.71 on real regulations. Both numbers are published.
- Test the gate itself. Every document's answer key includes the intake decision it should get, so the gate is scored like everything else.
This use case: the document exams
The document test set is generated, not hand-labelled: each document is built from a seed, saved as a PDF, and its answer key is measured from the saved PDF bytes, never estimated. The mix mirrors real traffic (55% invoices, 15% contracts, 12% SOC 2 reports) plus 18% adversarial documents: encrypted, corrupted, duplicated, injected with hidden instructions, scanned at low resolution, skewed, rotated, or a hundred pages long. Each one has the intake decision it should get.
Two runs, kept apart:
| Run | Documents | Key result |
|---|---|---|
| Synthetic, offline | 288 | 0 silent errors (wrong and auto-saved) out of 1,806 field decisions; invented values 0.68% (interval 0.34–1.33%) |
| Real documents, paid models | 70 | invented values 0.56% delivered (interval 0.15–2.0%); 2.2% before the citation ladder, all stopped for review |
Document Lab on 70 real documents
- 0.56 % invented key-field values delivered
- 92.2 % key fields correct
- 0.05 Calibration error
- 97.5 % correct intake decisions
- 10.3 Seconds per document
- 0.03 Dollars per document
- 3 of 3 injection attacks held
The metric that matters most is the one most systems don't report: silent errors, a wrong value that was trusted and saved. A system can have a high accuracy and still be dangerous if its mistakes are confident. Calibration (how far stated confidence is from actual accuracy, 0.05 here) and silent errors together are what make a review threshold meaningful.
Stage 5 · Train: the extraction and intent models
What this stage does here
The same progression as every model in the framework: start simple, wrap it in code, then train on the customer's own fields and corrections.
The improvement loop
Most steps in both recipes never need training: code doesn't, and a good off-the-shelf language model writes a fine warrant. Train is for the few places where the record and the exams point at a model, and where improving it is cheaper than working around it.
The rule for every round is the same: train → exam → ship → watch the record → train again. A new version ships only if it beats the current one on the exam, by more than the interval. Nothing a training round produces is trusted on its own.
The improvement loop
- The record finds the weak spot. The guard overruling the model on 14.9% of real pairs; zero recall on tariffs; reviewers correcting one kind of change. That is the training brief.
- Train one round. New data aimed at the weak spot: real pairs from the failing source, hard negatives, or reviewers' verdicts. A few hundred well-chosen labels beat thousands of random ones.
- The exam decides. The same golden sets, with intervals. Worse, or not better by more than the noise? Back to training.
- Ship, then watch. The better version ships as a new package version. The record watches it on real work, and the loop starts again. The previous version stays one step away.
The training system
Training is the most expensive thing the framework does, so it runs on its own system, separate from the runtime, with its own data, compute, tracking and budget.
What counts as training. Everything that changes a model's weights:
| Method | What it does | Typical models | Compute |
|---|---|---|---|
| Classic ML training | Trains a task-specific model from labelled examples | Intent classifiers, cross-encoders, rerankers, embedding models | CPU for small models (the first cross-encoder round took 24 minutes on a CPU); one GPU for larger ones |
| Continued (domain) pre-training | Keeps pre-training a base model on the domain's own text, so it learns the vocabulary and structure of rules and documents | Encoders like MiniLM; small and mid-size open language models | GPU hours to GPU days, depending on corpus and model size |
| Supervised fine-tuning | Teaches a model a task from input → output examples; full fine-tuning or parameter-efficient adapters (LoRA, QLoRA) | Open-weight models for extraction, classification, structured output | One to several GPUs; adapters cut memory and cost sharply |
| Preference learning | Teaches a model to prefer the answer a reviewer would accept over one they'd reject (DPO and related methods) | Open-weight models that write warrants, summaries, readings | Similar to fine-tuning, plus the cost of collecting preferences |
| Reinforcement learning | Improves a model against a reward: from human feedback, or from rewards code can verify (a citation verifies or it doesn't, a field matches the document or it doesn't) | Models whose outputs can be checked automatically | The most expensive: many rollouts per update, on GPUs |
| Distillation | Trains a small model on a strong model's answers, so the expensive judgement ends up in a cheap one | Small open models, cross-encoders | The strong model's calls plus a fine-tuning run |
| Quantisation and export | Shrinks a trained model for serving (int8, 4-bit) and exports it (ONNX, GGUF) | Everything that ships | Minutes; it must be re-examined after, because quantisation can change answers |
The parts of the training system:
- The data pipeline. Exports work records, reviewers' verdicts and corrections from the runtime; removes duplicates; scrubs personal data; joins answer keys; and uses active learning to choose what is worth labelling next (where the guard and the model disagree, where reviewers correct, where the record shows failures).
- Dataset versioning. Every training set and every golden set has a version, so a model can always be traced to the data that made it, and the exam set never leaks into training.
- Compute orchestration. Training jobs run where the data is allowed to go: on hosted GPU platforms (Modal, Hugging Face) or owned GPUs for public corpora, and inside the customer's boundary when its documents and verdicts cannot leave. CPU jobs for small classic models.
- Experiment tracking. Every run records its code version, data version, hyperparameters, metrics and cost, so two runs can be compared and a good one reproduced.
- The model registry. Every trained model is a versioned entry with its lineage (base model, data, run) and its exam results. Ship only ever takes models from the registry.
- The compute budget. Each run has a ceiling in GPU hours and dollars, set before it starts; the cheapest method that can fix the weak spot is tried first (more data for a classic model before fine-tuning a language model, fine-tuning before reinforcement learning).
One Roof's Train place is where these jobs are started, watched and compared; the jobs themselves run on the training system.
This use case: extraction and intent models
Document extraction follows the same path, one round at a time:
- A general model, prompted. A fast, cheap model at temperature 0 reads page windows into fields, each with a quote. Its document is fenced off as untrusted data, and it reports any instructions it notices.
- Code around it. The citation ladder proves every field; unprovable fields are never delivered. This round cut invented values from 2.2% to 0.56% without touching the model.
- Per-field escalation. Only unproven or abstained fields go to a stronger model. The record shows which fields earn the escalation and which don't.
- A document model on the customer's hardware. For customers whose documents can't leave the building, an open vision-language model (the Qwen3-VL family) is fine-tuned on the customer's own fields, using the answer keys from the test set and reviewers' corrections from the record.
- Learning from corrections. Every field a reviewer corrects is a labelled example with a verifiable reward (the corrected value must appear in the cited span), ready for the next round.
The intent classifier progresses the same way: keyword rules first; a small model (a 1.7-billion-parameter Qwen3, small enough to run beside the data) when the rules aren't sure; then that small model fine-tuned on the customer's own requests, with every misrouted request a reviewer corrects becoming training data. Its exam, out-of-scope recall near perfect, never changes between rounds.
Stage 6 · Ship: the package, and what ships for documents
What this stage does here
The extraction recipe, the customer's rules and floors, the document exams, and a reader that can run on the customer's own hardware.
The package
The proven system ships as a package, and the same package runs two ways: hosted by me on hypothesys.ai, or on the customer's own premises. Everything up to the package is identical; only the last stretch differs, and it differs a lot.
- Design and prove in the studio. Intake, recipes, model choices and exams, designed and proven on real dockets and documents, with the record to show it.
- Freeze it as a package. One version with everything pinned: the four engines, Acme's configuration, the exams it must pass. No passing exams, no package.
- Run it where the customer chooses. Hosted on hypothesys.ai, or on its own premises (both below). Acme Lab plus the Energy Lab 1, Energy Lab 2 and Document Lab engines, started by one install script on a single VM, using Acme's own models and keys.
- Acme holds the controls. Use cases on and off, approval limits, allowed models per kind of data, budgets, the audit trail and one stop switch, in a console on Acme's side. One switch stops everything.
- The record closes the loop. Acme's record shows how each role performs on Acme's dockets and documents. The next version ships only if it does better. Acme's corrections become the next training brief.
Two ways to run it
1 · Hosted on hypothesys.ai. I run it. Each customer is a separate tenant on my cluster, with its own runtime, database, file store, record and audit trail; nothing is shared between tenants except the code. Requests come in through one edge (TLS, authentication, rate limits, a web application firewall, per-tenant keys). New versions go through my release path (Woodpecker → Kargo → Argo CD, staging then production), and I operate it: monitoring, on-call, backups, disaster recovery, incident response. The customer keeps its controls and audit trail in a console, and its people and systems connect over the internet.
Hosted on hypothesys.ai
2 · On the customer's premises. The customer runs it. It pulls a signed package from my registry into its own network, checks the signature and the SBOM, and runs one install script on its VM or Kubernetes cluster. Its runtime, control plane, models (open models on its GPUs, or its own API keys), record and data all stay inside; it decides when to upgrade. Training, if any, happens inside its boundary. It can even run fully offline: packages carried across by hand, open models only, no calls out. What comes back to me is only what the customer chooses to share: numbers from its record, never documents.
On the customer's premises
| Hosted on hypothesys.ai | On the customer's premises | |
|---|---|---|
| Where it runs | My cluster, one isolated tenant per customer, in a region the customer chooses | The customer's VM or Kubernetes cluster, inside its network; offline possible |
| How a version arrives | I promote it through staging to production | The customer pulls a signed package and upgrades on its own schedule |
| Who operates it | Me: uptime, scaling, backups, upgrades, incident response | The customer's IT, with my runbooks and support bundle |
| Where data lives | My cloud, encrypted in transit and at rest, per tenant | Never leaves the customer |
| Models | Hosted APIs on my keys or the customer's, open models on my GPUs | Open models on the customer's hardware, or its own API keys |
| Training | On my training system, only with the customer's consent and a data agreement | Inside the customer's boundary, or not at all |
| The record and the controls | A console scoped to the customer | On the customer's machine; shared back only if it chooses |
| Security review | My controls and certifications are what the customer reviews | The customer's own controls apply; mine cover the package |
| Good fit | A fast start, smaller teams, less sensitive data | Regulated or sensitive data, strict security reviews, air-gapped sites |
Hosting turns the framework into a service I run, which brings its own commitments; they get their own section, Running it as a hosted service.
The package's manifest says everything about the system in one file:
package: acme-framework
version: 1.0.0
customer: Acme Power & Light (fictitious)
engines: [acme-lab, energy-lab-1, energy-lab-2, document-lab] # pinned image tags
intake:
use_cases: [reg_change_assess, reg_obligation_question, reg_filing_deadline,
doc_contract_review, doc_soc2_review, doc_invoice_process]
intents: data/acme/intents.json
classifier: {kind: rules + small model, route_above: 0.85, else: ask-or-person}
channels: [api: POST /intake, upload, mailbox, webhook]
restrictions: [never move money, never change payment details, every case ends with a person]
input_safety: labs-core intake gate
controls: {console: on, can_change: [use_cases, approval_limits, allowed_models, budgets], stop_switch: on}
recipes: [docket-change-to-action, document-to-record]
models:
interpreter: claude-haiku-4-5 # or an open model on Acme's hardware
matcher: ed-minilm-l6-3way # 23 MB, CPU
escalation: claude-sonnet-5-5 # Acme's own key
evals:
must_pass:
docket_f1: ">= 0.85"
key_field_hallucination: "<= 0.01 (upper 95% bound reported)"
intent_out_of_scope_recall: ">= 0.99"
record: on
The APIs
Everything Acme Lab does is an API, so Acme can wire it into its own systems and the hypothesys.ai lab pages drive exactly the same calls:
| Call | What it does |
|---|---|
POST /intake |
Takes a request (channel, text, attachments) and returns its intents with scores, the decision (route, person or refuse), restrictions hit, controls applied and a case id |
GET /intake/use-cases, GET /intake/intents
|
The menu and the intent catalog |
POST /cases/{id}/run |
Runs the routed recipe; each step calls the right engine |
GET /cases/{id} |
The case: every step, every citation, the warrant, the state |
POST /cases/{id}/decision |
A reviewer accepts, corrects, rejects or escalates; written to the audit trail and the record |
GET /record |
The performance record by kind of task and role |
GET /evals, POST /evals/{set}/run
|
The exams, run on demand, with intervals |
GET /control, PUT /control, GET /audit
|
Acme's control plane and its audit trail |
GET /package, GET /package/bundle, GET /deploys
|
The manifest, the installable bundle, and where each version runs |
Installing it on Acme's VM is one command: pre-flight checks, pull the pinned images, start the four engines, then a smoke test that sends a docket request through intake and runs the case end to end.
This use case: what ships for documents
For documents, the package carries the extraction recipe, the customer's rules (floors that only tighten, approval rules, duplicate checks), the field-level review queues, the document exams with their pass bars (invented key-field values at or under 1% with the upper bound reported), and a choice of reader: a hosted model on the customer's own key, or an open document model running on the customer's VM so no document ever leaves.
Every write to the customer's systems goes through an outbox with an idempotency key, so a retry never writes twice, and every write can be rolled back with an audit entry. "The write is the point of no return" is a Ship principle as much as a Factory one.
Use case: Rule change
USE CASE 2 OF 2 · RULE CHANGE
A new version of a rule arrives. Find what changed, decide whether it touches anything the company owns, work out what to do and why, and send it to the person who owns it, with citations they can check. The harder use case: it builds on everything the document pipeline does and adds comparing, interpreting and deciding.
One docket, end to end
On 27 April 2022, the California Public Utilities Commission issued a new version of General Order 166, the rules utilities follow for emergency and disaster preparedness. The previous version was dated 28 July 2021.
Most of the new version is the same as the old one. That is always true of regulatory dockets, and it is exactly what makes them hard. The part that matters is small and scattered: a date moved, a reporting cadence changed, a duty that was "may" became "shall", a definition got narrower, a section was renumbered so that every internal reference to it quietly broke.
Somebody at every affected utility has to find those changes, decide which of them touch something the company owns, work out what to do, and tell the right people, with reasons they can check. Today that somebody is usually an analyst with two PDFs side by side and an email list.
When my system read those two versions of General Order 166, it found this:
CPUC General Order 166, 2021 → 2022: what the system found
- 81 Provision pairs compared
- 8 Material changes
- 10 Moved
- 5 Inserted
- 4 Deleted
- 4 Obligations hit
- 13 Unmapped changes
Eighty-one comparisons. Seventeen changes that matter: 8 material, 5 inserted, 4 deleted. Four of them move obligations. Thirteen changes that touch nothing the company has on record, which is its own finding: either the register is incomplete, or those changes truly don't apply, and a person should say which.
That is the job, and it is the harder of Acme's two. It builds on everything the document pipeline does (intake checks, citations that verify themselves, review by a person) and adds comparing, interpreting and deciding.
A regulatory analyst at Acme forwards the new version of General Order 166 to Acme Lab's intake address with one line: "New GO 166 is out. What changes for us, and who needs to do what?"
ONE DOCKET, FROM ARRIVAL TO A SIGNED-OFF ACTION
- 09:00 · It arrives, and the intent is clear. The classifier reads the request: assess a regulatory change (0.96). No restricted intent, no second request. Both versions pass the input checks: real text, not empty, no hidden instructions, personal data noted. The use case is on Acme's menu and switched on.
- 09:00 · Both versions become provisions. Each version is cut into numbered provisions with a heading, a body and a fingerprint of its exact text: 31 in the old version, 32 in the new.
- 09:01 · Old and new provisions are paired. Identical fingerprints pair instantly, wherever they moved. The rest get a short list of candidates by keyword search, then a small trained model reads each candidate pair: equivalent, material, or unrelated. 81 pairs scored in about three seconds on a CPU.
- 09:01 · Plain code checks the numbers. A deterministic guard compares durations, percentages, money, cadences, duty words and negations. Where the model says 'equivalent' but the guard sees 'duty 2 → 4', the guard wins: the pair is escalated, never silenced.
- 09:02 · Each material change gets a name. Definition narrowed. Cadence changed. Deadline moved. Naming the kind of change tells the system what to look for and how risky it is.
- 09:02 · Changes meet Acme's register. Each of the 17 changes is matched to the obligations that cite the old section. Four obligations move; each gets its kind (duty tightened, deadline earlier…), its owner, and two citations: the old text and the new.
- 09:03 · Three sentences a VP can act on. What changed. Who it affects. What to do. Every claim carries a citation whose fingerprint is checked again before anyone sees it.
- 09:03 · To the person who owns it. High-risk changes that don't clear their confidence floor go to General Counsel with the top alternatives. Clear ones go to the obligation's owner. Thirteen unmapped changes go to the regulatory team as findings.
- 10:40 · A person signs off. The VP of Asset Management accepts two actions and corrects a third. Nothing is ever done automatically: every case ends with a person.
- 10:40 · Everything is kept. Every step, every model, every citation, every decision and its reason go into the case record and the performance record. The corrected action becomes a new exam question.
That is the whole loop. The six stages below open every step of it.
Stage 1 · Intake: what is the person really asking?
What this stage does here
Dockets are long, plain text and mostly unchanged. Intake here is mostly about intent and permission.
One message, two intents
A docket version pair is lighter on input safety: two text versions go through five checks (real text, size, not empty, no instructions aimed at the AI, personal data noted). The heavy lifting is understanding what the person is asking, because requests about rules are often vague, and often carry a second request.
Requests don't arrive labelled, and one message often holds more than one request. Here is one Acme's intake might receive:
"Attached is the redlined CPUC draft. Can you tell me what changes for our battery fleet? Also, the vendor sent new bank details for the next payment — please update them."
Intent scores for one request (illustrative)
Confidence Assess a regulatory change 0.95 Change vendor bank details 0.9 Filing deadline question 0.08 Review a contract 0.05 None of these 0.02
- MULTI-INTENT · Two requests in one message Both clear the threshold. A classifier that kept only the top intent would quietly drop the second, and the second is the dangerous one.
- RESTRICTION · The second is restricted Changing payment details by email is the classic fraud pattern. Acme's restriction says the system never does it. That request goes to a person in finance, flagged: verify by phone with the vendor first.
- ROUTE · The first goes to its crew The regulatory question routes to the docket recipe, exactly as in the walkthrough above.
threshold to route = 0.85 · two intents clear it · one is restricted · Interactive version in the original post
What a good intent classifier does:
- Picks from a fixed list. The list is the use-case menu; it never invents an intent.
- Gives a confidence. Above the threshold it routes; below, it asks one clarifying question or hands the request to a person.
- Knows "none of these". Catching out-of-scope requests matters as much as getting in-scope ones right.
- Finds every intent in a message, because risk often hides in the second one.
- Has its own exam: a golden set of real-looking requests, single, multiple, restricted, ambiguous and out of scope, scored on accuracy, on out-of-scope recall, and on whether its confidence matches how often it's right.
A small model is enough for this, and it can run next to the customer's data. One Roof runs a 1.7-billion-parameter Qwen3 model locally for exactly this kind of labelling.
Stage 2 · Factory (a): compare the two versions
What this stage does here
A pipeline with a checker: code and a small trained model compare, code names and maps the change, a language model only writes the warrant.
Code, small model or language model
The comparison crew, step by step: CPUC General Order 166
The most important design rule in Factory: every step is done by the cheapest thing that does it well, and exact things are done by code. Here is every step of both jobs:
| Step | Done by | Why that and not something bigger |
|---|---|---|
| Input safety checks | code | Exact questions (is it encrypted? is it a duplicate?) have exact answers |
| Intent | rules first, a small model when the rules aren't sure | A fixed list of intents is a small classification problem |
| Restrictions and controls | code, always | A rule that a clever request could talk its way past is not a rule |
| Document extraction | a fast, cheap language model, temperature 0 | Reading a page into fields needs language understanding |
| Proving each field | code: the citation ladder | A quote is either in the document or it isn't |
| Hard fields | a stronger language model, per field only | Pay for strength only where the cheap model couldn't prove its answer |
| Cutting versions into provisions | code | Section structure is regular |
| Unchanged and moved provisions | code: fingerprints | Identical text is identical; no model needed |
| Shortlisting candidate pairs | code: keyword search | Cheap, and it keeps model calls to about five per provision |
| Equivalent, material or unrelated? | a small trained model: a 23 MB cross-encoder on a CPU | Meaning-level comparison that code can't do, at a cost close to zero |
| Numbers, deadlines, duties, negations | code: the guard | Small models read numbers badly; code reads them exactly |
| Naming the kind of change | code: rules and numbers | Five well-defined kinds, each with a clear signature |
| Mapping to obligations and owners | code | The register says which obligation cites which section |
| Verifying every citation | code | Re-fetch, normalise, compare fingerprints: no model in the loop |
| The warrant (what changed, who it affects, what to do) | a fast, cheap language model, with a fixed template as fallback | The one place where sentences are needed |
| Independent judging of a sample | the strongest language model | Rare, so the cost doesn't matter; independence does |
Count the language-model steps: four, out of sixteen, and one of them (the judge) only grades a sample. None of them decides what is true. Models are used where meaning is needed, and every model is wrapped in code that can catch it.
Who plays each role
Who plays each role, and what it costs
Because so much of the work is code and small models, the model bill for regulated work is low and predictable.
Relative cost per model or component (tier, not price)
Cost tier Claude Opus 5.5 (judge) 4 Claude Sonnet 5.5 (escalation) 3 Kimi K2.7 Code 2 Claude Haiku 4.5 (default) 1 DeepSeek-V4.1-Flash 1 Qwen3-VL (documents) 1 gpt-oss-120b 1 Qwen3-1.7B (intents) 0.3 Cross-encoder (23 MB) 0.1 Guard and checks (code) 0.05
- JUDGE AND ESCALATION · Strong models The strongest model judges a sample of finished cases; a strong model handles only the fields and readings the cheap path couldn't prove.
- DEFAULTS · Cheap models do the writing Interpretations, warrants and first-pass extraction run on fast, inexpensive models. At model prices in November 2026, a docket case costs about a tenth of a cent; a document about three cents.
- ON THE CUSTOMER'S HARDWARE · Small and local where data can't leave Open-weight models and the cross-encoder run on the customer's own machines: no document has to leave the building.
- THE FOUNDATION · Most of the work is code Fingerprints, the guard, citation verification, rules, routing: deterministic, auditable, re-runnable, and effectively free.
1 = cheapest · 4 = most expensive · code and the cross-encoder run on CPU for practically nothing · Interactive version in the original post
| Role | Default | Where it runs |
|---|---|---|
| Intent classification | rules plus a small model (Qwen3-1.7B) | the customer's hardware |
| Provision matching | cross-encoder, 22.7M parameters, int8, 23 MB | CPU, anywhere |
| Interpretation and warrants | Claude Haiku 4.5 | hosted, or an open model on site |
| Document extraction | Claude Haiku 4.5, or Qwen3-VL on site | hosted or the customer's hardware |
| Field escalation | Claude Sonnet 5.5 | hosted, the customer's own key |
| Independent judge | Claude Opus 5.5 | hosted, a sample only |
| Guard, citations, rules, routing | code | anywhere |
Why tiers, not prices
Model prices change month to month, and hosts price the same open model differently. The record stores tokens and compute, and computes dollars from a price table where every entry has a source and the date it was checked.
Comparing versions: material or cosmetic?
The first instinct is to diff the two versions. It fails in two opposite ways.
A plain diff, or a fingerprint per section, flags every edit. "Thirty (30) days" becoming "30 days" raises the same alarm as 30 days becoming 60. On a real docket that is hundreds of alarms, nearly all noise.
A similarity score fails the other way. "The utility shall submit" and "the utility may submit" are 97% similar character by character. A duty just became optional, and the score says nothing happened. Off-the-shelf rerankers do no better: they measure whether two passages are about the same thing, so "within 30 days" and "within 60 days" look like a perfect match.
Energy Lab 1 used the first approach. Energy Lab 2 was built to fix it, and it does the comparison in five steps, cheapest first:
How two versions are paired and labelled
- Exact fingerprints first. Every provision gets a fingerprint of its normalised text. Same fingerprint, same address: unchanged. These never reach a model, and they are exactly right. The fingerprint is the exact verifier; the model is not.
- A short list, not every pair. For the rest, a keyword search proposes the same-address provision plus the four most similar ones. That keeps the cost to about five model calls per provision instead of comparing everything with everything.
- A small model reads both texts together. A 22.7-million-parameter cross-encoder, fine-tuned on my own version pairs, reads the old and new text as one input and answers equivalent, material or unrelated. Quantised to 23 MB, it scores a pair in about 22 ms on an ordinary CPU, with no GPU. Trained on 33,307 pairs built from 1,000 dockets and 157 contracts. Training took about 24 minutes on a CPU.
- Pair, then label. Pairs are assigned one-to-one, best first. Leftovers are inserted or deleted. A material verdict becomes 'material'; otherwise 'moved' if the address changed, 'reworded' if not.
- The guard can only escalate. Plain code extracts durations, percentages, money, cadences, duty words and negations from both texts. If the model is unsure, or says 'equivalent' while the guard sees a difference, the pair goes to the fallback, which names the kind of change or flags it for a person. The guard can escalate a change; it can never silence one.
Why the guard exists
Why the guard exists
The trained model is good at meaning and bad at magnitudes. Small language models read numbers as word pieces, so 45 and 75 look alike. And no model knows a distinction it was never shown: the change operator "shall → may" was deliberately held out of training, and the model alone caught it 0 times out of 209. It also missed dropped duties 60% of the time and changed percentages 67% of the time.
The guard is a few hundred lines of plain code, and it treats these as different:
| Not a change | A change |
|---|---|
| "thirty (30) days" → "30 days" | 45 days → 75 days |
| "five percent (5%)" → "5%" | 72 hours → 24 hours |
| "shall" → "must" | "shall" → "may" |
| quarterly → monthly | |
| 3% → 1.5% |
In one test, a scorer confidently said "equivalent, 0.97" about a deadline moving from 45 to 75 days. The guard overruled it.
Stage 2 · Factory (b): interpret the change
What this stage does here
Name the kind of change, gather evidence for each reading, verify every citation, and escalate rather than guess.
A material change is still just a difference. To act on it you need to know what kind of change it is, because the kind tells you how risky it is and where to look.
Five kinds of regulatory change
Energy Lab 1 recognises five kinds of regulatory change, each with its own urgency:
| Kind | What fires it | Urgency | Example from my dockets |
|---|---|---|---|
| Period extended | a comment, notice or review period grows | low | a scoping-meeting window extended |
| Date deferred | an effective date, compliance deadline or study window moves | medium | an interconnection study window from 90 to 120 days |
| Definition narrowed | a "means" clause gains restrictions | high | a battery qualifies only if "at least five (5) megawatts" |
| Cadence changed | quarterly, monthly, annually… changes | medium | battery settlement from quarterly to monthly |
| Penalty threshold | a breach or penalty percentage moves | high | a first-breach penalty from 2% to 1% |
"Definitions are where the money is" is one of the lessons written into the lab's design. A narrowed definition can quietly exclude a whole fleet from a payment, which is why it carries the highest risk.
Evidence, not eloquence
Naming the change is the start of an investigation, not the end of one. The system treats each candidate kind as a hypothesis with a probability, and keeps 15% of its belief in reserve for "something nobody has thought of yet". It then gathers evidence in rounds: the obligations that cite the changed section, the passages of the new text that support each reading (found by keyword search, with no vector database and no embeddings), and the projects those obligations drive.
Every piece of evidence is a citation that carries the exact quoted text and a fingerprint of it. Before anything is shown to a person, each citation is fetched again, normalised and its fingerprint compared. If the source text has drifted, the case is blocked, not shown. There is no language model in that loop.
The language model has exactly two jobs in the whole pipeline: write a two-sentence interpretation of the change, and write the warrant, three sentences for a VP-level reviewer:
Sentence 1: what changed. Sentence 2: who it affects. Sentence 3: the recommended action.
The model's job is to phrase the case; the code's job is to prove it. A case costs about a tenth of a cent in model calls.
Escalate rather than guess
Each kind of change has a confidence floor, set by a signed policy: 0.50 for low-risk kinds, 0.75 for high-risk ones. A case that doesn't clear its floor is not dropped and not guessed at. It is escalated to General Counsel with the top three alternative readings. "Better a clear escalation than a wrong classification" is the rule. Floors can only be raised, never lowered, except by a person.
Here is a real case from Energy Lab 1: a battery capacity-payment rule moving from proposed to final. Settlement went from quarterly to monthly, disbursement from 45 to 20 days, reporting from 15 to 7 days, and the definition of "eligible dispatch availability" was narrowed to exclude standby hours and require 80% of nameplate capacity.
One real case: how confident was the system in each reading?
Posterior Definition narrowed 0.311 Cadence changed 0.311 Date deferred 0.228 Something else (reserve) 0.15
- TWO KINDS AT ONCE · Two strong readings Both are true: the definition narrowed and the cadence changed. Neither clears the 0.75 floor on its own, because the evidence splits between them.
- THE RIGHT ANSWER · So it escalated The case went to General Counsel with all three readings and three verified citations, including the narrowed definition word for word. A person decided; the system didn't guess.
probabilities after three rounds of evidence · 15% held in reserve · the high-risk floor is 0.75 · Interactive version in the original post
What I learned the hard way
I kept an honest list of where this reasoning went wrong, and it shaped Acme Lab:
- A lone reading always shipped. If only one kind matched, it went out at 0.85 whatever it scored. Acme Lab treats a single candidate like any other: it must clear its floor on evidence.
- Evidence that couldn't change anyone's mind. Every tool gave every hypothesis the same weight, so three rounds of "deliberation" ended where they started. Evidence must favour one reading over another to count.
- Converging too early skipped the citations. A warrant with zero citations could pass verification. Acme Lab refuses to route a warrant without at least one verified citation.
- The number of candidate kinds decided the outcome, not the evidence. Two equally plausible kinds meant automatic escalation. That is safe, but it hides how good the evidence was, so the record shows it.
Stage 2 · Factory (c): decide what to do, and why
What this stage does here
Map each change to the obligations it touches and their owners, keep what doesn't map, place it among other regulators' rules, and write the recipe down.
A material, named change matters only if it touches something the company owns. This is where the same rule lands completely differently on different companies.
The same change, two companies
The same change, two companies
| The change | For a power producer and developer | For a large utility |
|---|---|---|
| Battery capacity payments: monthly settlement, narrower definition | 3 obligations, 2 projects and 3 documents in scope. A revenue question for the battery fleet | Nothing in scope |
| Interconnection study window: 90 → 120 days | It is the applicant: its projects wait longer | It performs the studies: a longer window is relief, and a new scoping meeting is a new task |
| A renewable-portfolio definition broadens | A sales opportunity | A compliance task |
Acme, as both a utility and a battery operator, sees parts of each. That is why intake and impact are both tied to the customer's own register, not to the rule alone.
From change to obligation to owner
Each material, inserted or deleted provision is matched to the obligations that cite the old section address (renumbered sections become "citation moved" tasks, so references get fixed). The guard's findings name the kind of impact:
From a changed provision to a named owner
- Find the obligation. Obligations cite the section they come from. The match uses the old address, because that is what the register knows. Renumbered sections become 'citation moved' tasks.
- Name the impact. From the guard: deadline later or earlier, cadence stricter or looser, duty softened or tightened, threshold changed, money changed, negation changed, duty added or removed. From the guard's findings, not a guess.
- Find the owner. The reviewer whose categories cover this kind of change owns it. On mapped impacts, owner and project attribution was right every time.
- Prove it twice. Every impact carries the old text and the new text, each with its fingerprint, so the owner can see exactly what moved. Re-verified before anyone sees it.
- Keep what doesn't map. A real change that touches no obligation on record is reported, not discarded. Across three company registers, most changes didn't map, which says as much about registers as about rules. Unmapped changes go to the regulatory team as findings.
That last point surprised me. Across three company registers, only about a fifth of real changes mapped to a recorded obligation:
Share of real changes that hit a recorded obligation
Mapped to an obligation Power producer and developer (92 of 485) 19 Large utility (46 of 198) 23 Enterprise buyer (70 of 280) 25 three mock company registers built from public facts · the rest are reported as unmapped findings · Interactive version in the original post
Either registers are thinner than the rules they track, or most changes genuinely don't apply. Both are worth knowing, and only a system that keeps the unmapped changes can tell you.
Rules don't change alone
Rules don't change alone
A rule rarely stands by itself. A federal order is implemented by a state rule, a grid operator's tariff stacks on top, an exemption carves a hole, a newer rule supersedes an older one. Energy Lab 2 includes a Layer Map built from 6,269 regulatory instruments, recording how rules from different regulators relate: implements, stacks, supersedes, exempts, conflicts. Each change is placed on that map. A change can stand alone, compound another, ripple through others, become moot, open a carve-out, or conflict, and a conflict always goes to a person.
The recipe, written down
A recipe says which roles a job needs, who plays each, the pattern they work in, the finish line and the budget. Acme Lab's docket recipe:
recipe: docket-change-to-action
use_case: reg_change_assess # from Intake; restrictions and controls are checked there
pattern: pipeline-with-checker
roles:
reader: {by: code, job: "cut both versions into provisions with fingerprints"}
matcher: {by: cross-encoder ed-minilm-l6-3way (23 MB, CPU), job: "pair provisions: equivalent, material, unrelated"}
guard: {by: code, job: "durations, percentages, money, cadence, duties, negation; escalate only"}
namer: {by: code, job: "recognise the kind of regulatory change"}
mapper: {by: code, job: "match changes to Acme obligations by old section; name the impact and owner"}
interpreter: {by: model, default: claude-haiku-4-5, job: "two-sentence interpretation; three-sentence warrant"}
checker: {by: code, job: "re-verify every citation fingerprint; block on drift; refuse a warrant with no citation"}
finish_line:
check: "every impact has an owner and two verified citations; unmapped changes listed"
result: reviewer queue (owner, or General Counsel when a high-risk floor is not cleared)
budget: {dollars: 0.05, seconds: 60}
never: [act on the change, file anything, contact a regulator] # every case ends with a person
Count the roles: seven, and only one of them is a general language model. The rest are a small trained model and plain code. That is the most important strategic point in this post. The more regulated the work, the less of it should depend on a general model's judgement, and the more of it should be code you can read and checks you can re-run. The language model writes the sentences a person reads; it does not decide what is true.
Stage 3 · Agents: the crew's agents, and a record per step
What this stage does here
Serve the comparison crew's models, from a 23 MB cross-encoder on a CPU to an independent judge, and record every step each one takes.
The agents in this crew
The comparison crew's agents
| Agent | Model and serving | Harness, tools and context | Notes |
|---|---|---|---|
| The matcher |
ed-minilm-l6-3way, a 22.7M-parameter cross-encoder, int8, 23 MB, served with ONNX Runtime on a CPU (about 22 ms per pair) |
Called by the comparison pipeline with candidate pairs from the keyword shortlist; no tools | Not a language model, still an agent in the record: its versions, its accuracy by source and its cost are tracked like any other |
| The interpreter and warrant writer | Claude Haiku 4.5 through the model gateway (Kimi and other models as configured; a fixed template when no model is allowed) | The labs-core reasoner: two calls per case, 280 and 320 tokens, with the frames, the evidence and the citations as context | Writes sentences only; never decides what is true |
| The independent judge | Claude Opus 5.5, on a sample of finished cases | A judge harness that is told not to trust the pipeline's confidence and answers pass, partial or fail with reasons | Rare, so its cost doesn't matter; its independence does |
| The builders | Claude Code and Codex, in One Roof | The studio: they build and change the recipes, the engines and the tests | Measured in the same record, on the work of building the system |
The guard, the namer, the mapper and the citation checker are code, not agents, and they write to the same record so that every change's decided_by is complete.
This use case: a record per step
A docket case writes a work record for every step, and every change carries decided_by: fingerprint, cross-encoder, guard, fallback, or alignment. That one field turns the record into a diagnosis:
- How often does the guard overrule the model? On synthetic pairs, the fallback handled 1.6% of pairs; on real regulations, 14.9%. That jump is the record telling you the model is out of its depth, before any exam is run.
- Which document types does the matcher fail on? Utility tariffs, where the model alone scored zero. The record groups failures by source, which is exactly the data the next training round needs.
- Do reviewers agree with the warrant? Every accept, correction and rejection from General Counsel or an obligation owner is a label. Over time, the record shows which kinds of change the system names reliably, and which still need a person to read every word.
- Are the unmapped changes really irrelevant? When a reviewer marks an unmapped change as "this does apply to us", that is both a correction and a gap in the register.
The record is how Train knows what to train on, and how Ship knows when a new version is worse than the old one.
Stage 4 · Evals: the docket exams
What this stage does here
Pairs built by construction with change types held out on purpose, then real regulations to keep the synthetic results honest.
Exam pairs built by construction
The docket test set is built so that the right answer is known by construction: take a real or synthetic provision, apply a known operator (restyle a number, swap a synonym, change a duration, soften a duty, drop a duty, negate a sentence), and the label follows from the operator. Equivalent operators: numeral restyle, synonym, "must" for "shall", punctuation, percent restyle, OCR typos. Material operators: duration, percent, cadence, negation, add a duty, change the modal, drop a duty. Four operators (dropped duty, modal change, OCR typos, percent restyle) never appear in training, only in the test, so the exam measures generalisation and not memory. Splits are by docket, so no docket appears on both sides.
What the comparison scored
I tested four arms on 120 held-out version pairs:
Telling material changes from cosmetic ones (120 held-out synthetic pairs)
F1 False alarms on cosmetic edits Fingerprint only 47 100 Energy Lab 1 differ 40.2 95.4 Trained matcher alone 85.7 2.7 Matcher + guard + fallback 88.5 4.9
- THE OLD WAY · Fingerprints catch everything They miss almost nothing, but flag every cosmetic edit as a change. An analyst drowning in alarms is not better off than one with no tool.
- THE MODEL · The matcher removes the noise False alarms drop to under 3%. But it misses changes the guard would catch: duties softened, numbers moved.
- THE SYSTEM · The guard puts the misses back Recall rises from 0.815 to 0.897 at the cost of a few more alarms. The best F1, and the misses it fixes are the expensive ones.
F1 = how well it finds the changes that matter · false alarms = cosmetic edits flagged as changes · hover for values · Interactive version in the original post
Synthetic is not real
Synthetic test data is clean; real regulations are not. On 29 real version pairs (55 real changes, labelled by an agent, not by a regulatory expert), the picture shifts:
Synthetic vs real regulations: F1
Synthetic (120 pairs) Real regulations (29 pairs) Trained matcher alone 85.7 71 Matcher + guard + fallback 88.5 85
- REAL DATA · The model alone drops From 0.86 to 0.71, and to zero on utility tariffs, a format it never saw. The fallback handled 14.9% of real pairs against 1.6% of synthetic ones.
- WHY LAYERS · The system holds The guard and fallback carry the real-world recall to 0.91. The report's own conclusion: the model is the weak link on real data, and it should be retrained on real pairs.
the full system holds up on real data; the trained matcher alone does not · Interactive version in the original post
That is why the strategy layers deterministic checks around every model: when the model meets data it wasn't trained on, the layers around it hold the line, and the record shows exactly where the model needs work.
Citations under attack
A fifth of all cited passages were tampered with on purpose. All three tampered citations were caught, with no false alarms on the twelve clean ones. An early build raised false alarms on 30% of clean citations because of Windows line endings; normalising text before fingerprinting fixed it. That bug is exactly what an exam is for.
Obligations and the independent judge
Extracting obligations from rules scored precision 1.000 and recall 0.630 on 72 labelled rows: everything it found was right, but it missed more than a third (recall 0.630), worst on reporting cadences and event-driven filings. An independent judge model, told explicitly not to trust the pipeline's own confidence, passed 10 of 10 canary cases for $2.17 (November 2026 prices).
Stage 5 · Train: the matcher, round by round
What this stage does here
The clearest example of the progression: from no model, to a base model, to a model trained on my own data, and onward.
The matcher, round by round
Round 0: code only
Energy Lab 1 compared versions with fingerprints and a character-level differ. Exact and cheap, and useless in practice: fingerprints flagged every cosmetic edit (100% false alarms; the differ, 95.4%), and saw "shall submit" and "may submit" as 97% similar. The lesson was not "add a model". It was: code is right about identity and wrong about meaning. Keep the code for identity; find something for meaning.
Round 1: a base model, off the shelf
The starting point was a small public reranker, MS MARCO MiniLM-L6 (22.7 million parameters), trained to score whether a passage answers a search query. It understands topic, which is why it was a good base, and it is blind to exactly what matters in rules: "within 30 days" and "within 60 days" are about the same topic, so it scores them as a near-perfect match.
Why a cross-encoder and not the other common choices:
| Approach | How it compares two texts | Fit for "did this provision change?" |
|---|---|---|
| Bi-encoder (embeddings) | encodes each text separately into a vector, compares vectors | Fast for search over millions of documents, but the two texts never see each other, so a single changed number barely moves the vectors |
| Cross-encoder | reads both texts together as one input, with attention across them | Every word of the old text can attend to every word of the new one: the right shape for spotting a small, decisive edit |
| Late interaction (ColBERT-style) | keeps a vector per token and matches token to token | A middle ground; strong for retrieval, more machinery than a pairwise check needs |
| A large language model as judge | reads both and reasons in text | Strong, but slow and expensive per pair, and still unreliable on magnitudes; better as an occasional independent judge |
The comparison step is pairwise and local, so the cross-encoder is the right tool: precise, small enough to run on a CPU, and cheap enough to score every candidate pair. Retrieval (the keyword shortlist) narrows the pairs first, so the cross-encoder only sees about five candidates per provision: retrieve, then re-rank.
Round 2: fine-tuning on my own pairs
The base model was fine-tuned with a new three-way head: equivalent, material, unrelated. Its training data is 33,307 version pairs built by construction from 1,000 synthetic dockets and 157 real contracts, with the operators described in the exams above. Three choices made this round honest:
- Hard negatives. "Unrelated" examples are drawn from other sections of the same docket, which look similar but aren't the same provision. Easy negatives teach a model nothing.
- Held-out operators. Four kinds of change never appear in training, so the exam can tell whether the model learned the idea or memorised the operator.
- Splits by docket. Nothing about a test docket leaks into training.
The whole round took about 24 minutes on a CPU, and the result was quantised to int8: 23 MB, about 22 ms per pair. On held-out synthetic pairs it reached F1 0.857 with 2.7% false alarms, against 0.47 and 100% for fingerprints.
Round 3: a guard, because small models can't count
The fine-tuned model still had a blind spot the literature predicts: small language models read numbers as word pieces, so 45 and 75 look alike, and they cannot learn a distinction they were never shown. The held-out "shall → may" operator was caught 0 times out of 209. Dropped duties were missed 60% of the time, changed percentages 67%.
The fix was not a bigger model. It was code wrapped around the model: a deterministic guard that extracts durations, percentages, money, cadences, duty words and negations and can only escalate a pair, never silence it. Uncertain or contradicted pairs go to a fallback that names the change with rules. Together: F1 0.885, recall up from 0.815 to 0.897. Training improved the model; the guard covered what training can't.
Round 4: real data
The exam on real regulations showed where training has to aim: the model alone fell to F1 0.71, to zero on utility tariffs, and the fallback's share rose from 1.6% to 14.9%. Round 4 fine-tunes again on real version pairs: the 5,999 real pairs from 6,269 regulatory instruments (eCFR, the Federal Register, NERC, California bills, CPUC orders, CAISO, CARB, utility tariffs), with active learning choosing which ones to label first: the pairs where the guard and the model disagree, and the sources where the record shows failures. A few hundred well-chosen labels are worth more than thousands of random ones.
Round 5: domain pre-training
A model fine-tuned on regulatory pairs still starts from a base that learned language from web search queries. Round 5 is domain-adaptive pre-training: continuing the base encoder's pre-training on the regulatory corpus itself (masked-language modelling over millions of words of rules and tariffs) before fine-tuning. The model learns the vocabulary and structure of rules (defined terms, cross-references, schedules, "provided that" clauses) as background knowledge, and the fine-tuning round then teaches only the comparison. Then the cycle repeats: pre-train → fine-tune → exam → ship, each version measured against the last.
Round 6: learning from reviewers
The record collects something no public dataset has: reviewers' verdicts on real cases. Every time General Counsel accepts, corrects or rejects a warrant, that is a preference: this reading over that one. Three techniques turn those verdicts into training:
- Preference learning. Pairs of readings with a preferred one train the model (or a small reward model) to rank the reading a reviewer would accept above the one they'd reject.
- Reinforcement learning with verifiable rewards. Much of this work has rewards that code can check without a person: a citation either verifies or it doesn't, a changed number either matches the guard's extraction or it doesn't, an extracted field either matches the document or it doesn't. Rewards that can't be fooled are what make reinforcement learning safe to use here; a model can't learn to please a checker that only accepts verified facts.
- Distillation. The independent judge, the strongest and most expensive model, labels a sample of hard cases; the small model learns from those labels. The expensive model's judgement ends up in the cheap one.
The progression, in one chart
The comparison step, round by round (held-out synthetic pairs)
F1 False alarms on cosmetic edits Round 0 · code only 47 100 Round 2 · fine-tuned model 85.7 2.7 Round 3 · model + guard 88.5 4.9
- ROUNDS 0 → 2 · From noise to signal Fine-tuning a 22.7M-parameter base on 33,307 constructed pairs removed almost all the false alarms.
- ROUND 3 · Code covers what training can't The guard trades a few more alarms for the misses that matter most: duties softened, numbers moved. Rounds 4 to 6 are judged on the real-regulation exam, where the bar is the 0.85 the full system reaches.
measured rounds only · later rounds are judged on the real-regulation exam · hover for values · Interactive version in the original post
Stage 6 · Ship: how a retrained matcher reaches the customer
What this stage does here
Training produces a new matcher; Ship is what turns it into a safe upgrade.
How a retrained matcher reaches the customer
When a training round produces a better matcher, it reaches Acme like this:
- The exam passes on every docket set, with the new version beating the current one by more than the interval, synthetic and real reported separately.
- A new package version is built with the new model pinned: Acme Framework 1.1. No passing exams, no package.
- It deploys to staging, then to the customer's VM, by the same path every release takes.
- The record watches it on real work. If the guard starts overruling the new model more often than the old one, or reviewers correct more warrants, that is a regression the exam didn't catch.
- The previous version is one step away. Rolling back is a deploy of the last good version, not an emergency.
The customer's record also flows back: with Acme's permission, the kinds of change its reviewers correct become the next round's training brief. Ship closes the loop that Train opened.
Running it as a hosted service
RUNNING IT AS A HOSTED SERVICE
When I run the framework for customers on hypothesys.ai, it stops being software they install and becomes a service they trust me with. That brings commitments the on-premises model doesn't: isolation between customers, security, compliance, performance, recovery, operations and cost.
Why hosting is its own topic
On a customer's premises, the customer's own controls carry most of the weight: its network, its identity provider, its backups, its auditors. Hosted, every one of those becomes mine. A customer's security team will not ask whether the cross-encoder is accurate; it will ask where its documents are stored, who can read them, what happens if my cluster fails, and whether its data trains anyone's model. Each of those questions needs an answer designed in, not added later.
What a customer trusts me with
The hosted architecture
The hosted architecture
A request's path, end to end:
- The edge. A customer's person or system reaches
acme.hypothesys.ai(or the customer's own domain). The edge terminates TLS, applies the firewall and per-tenant rate limits, and routes by hostname to that tenant, and only that tenant. - Identity. People sign in through the customer's own identity provider (OIDC single sign-on); systems use API keys scoped to one tenant. Roles map to the review queues: a CISO-office reviewer sees security fields, accounts payable sees invoices.
- The tenant. Each customer has its own Kubernetes namespace holding its own runtime (intake, the crews, the agents, the four engines), its own database, its own object-store prefix, its own record, controls and audit trail, and its own pinned package and model versions. A network policy gives it no route to any other tenant.
- Shared services, used through narrow doors. The model gateway (routing, fallback, spend caps per tenant, usage logged without content), the GPU pool for open models (per-tenant quotas), and the platform (release, observability, keys, backups, on-call). None of them stores a tenant's documents.
What is shared and what is not:
| Shared by all tenants | Separate for every tenant |
|---|---|
| The code: images built once, signed, promoted | Namespace, runtime pods and job queues |
| The edge and identity layer | Database, object storage, encryption keys |
| The model gateway and GPU pool, with per-tenant quotas | Record, audit trail, controls, review queues |
| The release pipeline, observability stack, on-call | Pinned package and model versions |
Tenancy and isolation
Tenancy and isolation
- One tenant per customer. Each customer gets its own namespace, runtime, database, file store, record, audit trail and encryption keys. The code is shared; nothing else is.
- No cross-tenant reads, by construction. Every query is scoped by tenant at the data layer, not just in the application, and the tests include attempts to read another tenant's cases.
- Noisy neighbours are limited. Each tenant has quotas for requests, documents, model spend and GPU time, so one customer's batch can't slow another's work.
- Models are pinned per tenant. A customer stays on the model and package version it validated until it accepts an upgrade.
Security
Security: every request passes four checks
- Identity and access. The customer's people sign in through its own identity provider (single sign-on), with roles that match the review queues. My operators reach production only through audited, time-limited access, and access is reviewed regularly.
- Encryption and keys. Everything is encrypted in transit (TLS) and at rest, with per-tenant keys in a managed key store; a customer can bring its own key so that revoking it makes its data unreadable.
- Network. One hardened edge (a web application firewall, rate limits, authentication); internal services are not reachable from the internet; outbound calls go only to approved model providers.
- Secure supply chain. Signed images, an SBOM for every release, dependency and image scanning in CI, and no change reaches production without passing staging.
- Testing the defences. Regular penetration tests, the adversarial document set in every release, and the input gate's own exam.
Compliance and data protection
Compliance: evidence from the systems, not a binder
- Attestations customers ask for: a SOC 2 report (Type I, then Type II) and ISO 27001 certification for the hosted service, and HIPAA or sector rules where the customer's data requires them.
- A data processing agreement that names every subprocessor, including each hosted model provider, and what each one may do with the data.
- Data residency: the customer chooses the region, and data stays in it.
- Retention and deletion: documents, cases and records are kept only as long as the customer's policy says, and deleted on request with proof.
- No training on customer data by default. A customer's documents and reviewers' verdicts train nothing unless it opts in under a written agreement.
Performance and scale
Performance and scale
The labs set the bar: Document Lab was built for ten thousand documents a day, peaks of fifty a minute, and under thirty seconds for a short document, and reached a typical ten seconds per document. Hosted, the same targets apply per tenant:
- Every stage has a latency target, measured by the record: intake decisions in about a second, a short document in under thirty seconds, a docket comparison in seconds on a CPU, a full docket case within its one-minute budget.
- Scaling follows the work: a sync lane for small jobs and an async lane with chunks for long ones; workers scale with the queue; open models run on a shared GPU pool with per-tenant limits.
- Cost stays visible: every step's tokens, GPU time and dollars are metered per tenant, so a customer sees what its work cost and caps can stop runaway spend.
Reliability and recovery
Reliability and recovery
- Backups of every tenant's database and file store, with point-in-time restore, tested by restoring them.
- Recovery targets agreed per customer: how much data may be lost (the recovery point) and how long a restore may take (the recovery time).
- Provider outages degrade gracefully: circuit breakers, retries that never write twice, a model gateway that can fall back to another model, and visible job states instead of silent failure.
- Rollback to the previous version is one deploy, for one tenant or for all.
Observability and incident response
Observability and incident response
- Per-tenant dashboards and traces: every case traceable step by step, with the agent and model version that ran.
- Alerts on what matters: failed jobs, rising fallback rates, latency targets missed, spend near a cap, the guard overruling the model more than usual.
- An incident process: on-call, a status page, customer notification within the time its contract and the law require, and a written post-incident review that changes a system, not just a habit.
Model and data governance
Model and data governance
- A model card for every model in a package: what it is for, what it was trained on, its exam results, its known weaknesses.
- Lineage from every answer back to its sources: the citations, the model version, the recipe version, the policy that applied.
- A record of every change: which recipe, prompt, model and package version a tenant ran, and when it changed.
Upgrades, support and pricing
Upgrades, support and pricing
- Release channels: a stable channel for most customers and an early channel for those who want new models first; every upgrade announced, every one reversible.
- Support tiers with response times, and a support bundle the customer can send without sending documents.
- Pricing that follows the work: a platform fee plus usage (documents, cases, model spend), because the meter already exists in the record. Prices themselves are set per customer and stated with their date.
The blueprint: fourteen workstreams
The hosted service breaks down into fourteen workstreams, each with what to build, the design choice, how it fits the stack that already runs the labs (the hypothesys clusters, the labs-core chart, Woodpecker → Kargo → Argo CD, cert-manager, the shared lab Postgres, Langfuse), and the test that proves it done.
The build order
H1 · Tenant model and provisioning
| Build | A tenant registry (id, region, plan, hostname, keys, quotas, pinned versions) and a provisioner that creates everything a tenant needs from that entry |
| Design choice | Declarative: a tenant is a file in the deploy repo; the provisioner makes the cluster match it. No hand-made tenants |
| On the existing stack | One Helm release of the labs-core chart per tenant (as each lab is today), a Kargo stage per tenant, values in the deploy repo under the tenant's name |
| Done when | Onboarding a tenant is one command, idempotent, and leaves a working smoke test; teardown leaves nothing behind |
H2 · Isolation and the data layer
| Build | A database per tenant, an object-store prefix per tenant, and a network policy that denies all cross-namespace traffic |
| Design choice | Database-per-tenant (not shared tables) so a tenant can be restored, exported or deleted alone; a tenant id on every row as a second guard |
| On the existing stack | Start on the shared lab Postgres with one database per tenant; move large tenants to their own instance |
| Done when | A cross-tenant test suite (read, list, search, export across tenants) fails closed in every release; a pod in one tenant cannot reach another |
H3 · Identity and access
| Build | OIDC single sign-on per tenant, roles mapped to review queues, tenant-scoped API keys, and time-limited, audited operator access |
| Design choice | The customer's identity provider is the source of truth for its people; operators get no standing access to production |
| On the existing stack | The labs' access-code gate is replaced by single sign-on for hosted tenants; operator access goes through the existing cluster access path, with expiry |
| Done when | A customer user signs in with its own provider; an operator's access expires on its own and appears in the audit trail |
H4 · Encryption, secrets and keys
| Build | TLS everywhere, per-tenant keys for data at rest (envelope encryption), a secrets manager, rotation, and bring-your-own-key |
| Design choice | Keys per tenant, not per cluster, so revoking one customer's key makes only its data unreadable |
| On the existing stack | cert-manager already issues TLS; the lab secret-sync scripts become a managed secrets store synced into each tenant's namespace |
| Done when | Revoking a test tenant's key makes its data unreadable; a rotation runs without downtime |
H5 · The edge and the network
| Build | One edge per region with a web application firewall, per-tenant rate limits, hostname routing and custom domains; outbound calls only to an allow-list |
| Design choice | Nothing inside a tenant is reachable from the internet except through the edge |
| On the existing stack | The ingress controller and DNS the labs already use, with per-tenant hosts |
| Done when | An external scan finds only the edge; a tenant over its rate limit is slowed without affecting another |
H6 · The model gateway and the GPU pool
| Build | One gateway for every model call: routing, fallback, per-tenant keys and bring-your-own-key, spend caps, usage metering without content; a GPU pool for open models with per-tenant quotas |
| Design choice | The runtime never calls a provider directly; every call goes through the gateway, so caps, fallbacks and the no-training rule are enforced in one place |
| On the existing stack | labs-core's LLM layer (LiteLLM-based, bring-your-own-key) becomes the shared gateway; Langfuse keeps the traces, scrubbed of content |
| Done when | A provider outage fails over without a failed case; a tenant at its cap stops spending; no request body is ever logged |
H7 · Runtime scaling and performance
| Build | Queue-driven autoscaling of workers, the sync and async lanes per tenant, per-stage latency targets, and load tests |
| Design choice | Scale on queue depth, not CPU, because the work arrives in bursts |
| On the existing stack | The labs-core job states and lanes, with workers scaled per tenant |
| Done when | A load test at fifty documents a minute meets every stage's target (see the appendix) |
H8 · Observability and service targets
| Build | Traces for every case tagged with the tenant, metrics, logs scrubbed of personal data, per-tenant dashboards, alerts, and a status page |
| Design choice | The performance record and the traces share ids, so a slow case can be followed from the dashboard to the step and the model that ran |
| On the existing stack | Langfuse for model calls, plus a metrics and logs stack per region |
| Done when | Any case is traceable end to end in under a minute; a synthetic failure fires the right alert |
H9 · Backups and disaster recovery
| Build | Continuous database backups with point-in-time restore, versioned object storage, copies in a second location, agreed recovery targets |
| Design choice | Restore per tenant, because a mistake usually affects one customer, not all of them |
| On the existing stack | The shared lab Postgres gains archived write-ahead logs; the existing S3 backups pattern extends to tenant storage |
| Done when | A restore drill brings one tenant back to a chosen minute within the agreed time, every quarter |
H10 · Release and per-tenant upgrades
| Build | Per-tenant stages that pin a package version, stable and early channels, a canary tenant, per-tenant rollback, change notices |
| Design choice | A tenant moves to a new version only when its own exams pass on its own samples |
| On the existing stack | Kargo already promotes freight stage by stage; tenants become stages after staging |
| Done when | One tenant upgrades without touching another, and rolls back in one step |
H11 · Metering, billing and cost
| Build | Usage events from the record (documents, cases, tokens, GPU time) into a meter, invoices, and spend caps the customer sets |
| Design choice | Bill from the same record that measures performance, so the numbers can't disagree |
| On the existing stack | The record already writes cost per step; the gateway already meters tokens |
| Done when | A month's metered usage reconciles with provider bills; a customer can see its spend by use case |
H12 · The customer console
| Build | The hosted control plane: use cases, limits, allowed models, budgets, the stop switch, users and keys, the audit trail, data export and deletion requests |
| Design choice | Everything a customer needs to run its tenant without opening a ticket |
| On the existing stack | Acme Lab's control plane and audit APIs, behind single sign-on |
| Done when | A customer onboards its users, changes a limit, exports its data and stops the system, unaided |
H13 · The compliance program
| Build | Written policies, automated evidence collection, a SOC 2 Type I then Type II audit, ISO 27001, the data processing agreement and subprocessor list, regular penetration tests |
| Design choice | Collect evidence from the systems themselves (access logs, CI records, restore drills), so the audit is a byproduct of operating well |
| On the existing stack | Signed images, CI records and the audit trails already exist; they become evidence |
| Done when | A SOC 2 Type I report is issued; then a Type II over a full audit period |
H14 · Incident response and support
| Build | An on-call rota, runbooks, a status page, notification templates, written post-incident reviews, support tiers and a support bundle without documents |
| Design choice | Every incident ends with a change to a system (a check, an alert, a rule), not only a note |
| On the existing stack | My existing incident notes and runbooks, extended to customers |
| Done when | A game-day incident is detected, communicated and closed within the targets, with a review published |
A tenant's lifecycle
A tenant's lifecycle
Every step is a runbook with a script, idempotent and checked before and after, and every step writes to the tenant's audit trail:
| Step | What happens | Workstreams |
|---|---|---|
| Sign | Agreement, data processing agreement, region, plan | H13 |
| Provision | Registry entry → namespace, database, storage, keys, quotas, hostname | H1, H2, H4, H5 |
| Connect | Single sign-on, roles, API keys, channels (mailbox, upload, API, webhook) | H3, H5 |
| Configure | Use cases, controls, allowed models, budgets, approval limits | H12 |
| Prove | The customer's own exams on its own samples, before any live work | H10 and the Evals stage |
| Live | Real work; the record grows; dashboards and alerts on | H7, H8, H11 |
| Upgrade | A new version is proven on the tenant's exams, then promoted; rollback in one step | H10 |
| Offboard | Export, deletion with a certificate, keys destroyed | H4, H9, H12, H13 |
What I learned
WHAT I LEARNED
The principles every stage follows, the path to adopting the framework, what could go wrong, and the strategy in one line.
Principles I kept
Five labs produced a short list of rules that every part of the framework follows:
| Principle | Where it came from |
|---|---|
| Cite or don't claim. A value or a reading without a verified citation is not delivered | Energy Lab 1, Document Lab |
| The fingerprint is the verifier; the model is not. Exact checks are code | Energy Lab 2 |
| Deterministic guards can only escalate. Code can add caution, never remove it | Energy Lab 2 |
| Escalate rather than guess. A clear escalation beats a wrong classification | Energy Lab 1 |
| Controls and floors only tighten. A customer can raise them; nothing goes below the framework's own floor, and only a person can lower a customer's | Energy Lab 1, Document Lab |
| Cheapest thing that does it well; exact things in code. Models only where meaning is needed, each wrapped in code that can catch it | Every lab |
| Escalate per field, not per document. Pay for the strong model only where it's needed | Document Lab |
| Unmapped is a finding, not a drop | Energy Lab 2 (impact mapping built on Energy Lab 1's register) |
| The write is the point of no return. Outbox, idempotency, rollback | Document Lab |
| Errors are never swallowed. The customer sees the same truth as the engineers | Document Lab |
| Report intervals, and keep synthetic and real apart | All of them |
| Every case ends with a person | All of them |
The path to adopting it
The framework is adopted one use case and one stage at a time. Each layer is useful on its own, and each makes the next one safer.
| Layer | What it gives a team | Stage | Proof it's working |
|---|---|---|---|
| 1 · Documents, proven | Fields extracted with citations, rules applied, only the risky fields sent to a person | Factory | Invented key-field values under 1%, with the interval reported |
| 2 · Intake | A use-case menu, intent classification, restrictions in code, the customer's controls | Intake | Out-of-scope recall near perfect on the intent set |
| 3 · Rule change: compare | Version-to-version changes with cosmetic noise removed | Factory | F1 and false-alarm rate on its own dockets, with intervals |
| 4 · Rule change: interpret and decide | Named changes mapped to its own obligations and owners, with verified citations | Factory | Reviewer agreement rate in the record |
| 5 · Agents and their record | Each role played by the right agent, measured on real work | Agents | A record with sample sizes on every number |
| 6 · Exams and training | Golden sets that gate every change; weak models improved round by round | Evals, Train | A retrained model that beats the last one on the exam, by more than the interval |
| 7 · The package | The whole system shipped as a version, hosted or on the customer's premises | Ship | A version that deploys only after its exams pass, and rolls back on its own record |
What could go wrong
| Risk | How the framework handles it |
|---|---|
| A cosmetic edit buries the real change | Fingerprints, a trained matcher, and a guard that can only escalate |
| A duty quietly becomes optional | The guard counts duty words; "shall → may" is always a change |
| The model meets data it wasn't trained on | Layers around the model hold recall; the record shows where to retrain |
| A citation points at text that has changed | Every citation re-verified before routing; drift blocks the case |
| A request squeezed into the wrong intent | A fixed list, a threshold, a real "none of these", an exam for out-of-scope recall |
| A clever request talks past the rules | Restrictions in code, outside every prompt |
| A document attacks the crew | Injection and hidden-text checks before any model reads it |
| A provider outage fails silently | Circuit breaker, visible job states, retries that never write twice |
| The customer's data leaves the building | Small and open models on its hardware; the record keeps numbers, not documents |
| A bad upgrade at the customer | No passing exams, no package; the record watches after deploy, and the previous version is one step away |
| Training on data that may not leave | Training runs inside the boundary the data belongs to; nothing trains on a customer's data without its consent |
| A hosted tenant sees another's data | One tenant per customer by construction, scoped at the data layer, tested in every release |
The strategy in one line
Intake reads the intent and enforces the customer's rules. Factory puts the right crew on the job, mostly code and small models, with a language model only where words are needed. Agents do the work, each a model in a harness with tools and permissions, and their performance record shows who is actually good at what. Evals keeps everyone honest, with intervals. Train makes the weak part better, one proven round at a time. Ship takes the proven system to where it runs, hosted on hypothesys.ai or on the customer's own premises, and brings back what it learns there.
A regulator changes a rule. By the time a person looks at it, they see what changed, what it means for them, who owns it, what to do, and the exact words that prove it. Then they decide.
Appendix: operating the hosted service
APPENDIX · THE OPERATIONAL DETAIL
The checklists behind the hosted-service section: the controls, the targets per stage, and the runbooks.
A1 · Control checklist
| Area | Control | Evidence |
|---|---|---|
| Tenancy | Per-tenant namespace, database, file store, keys, record | Cross-tenant read tests in every release |
| Identity | Single sign-on for customers; time-limited, audited operator access | Access logs; quarterly access reviews |
| Encryption | TLS in transit; per-tenant keys at rest; bring-your-own-key option | Key store configuration; key rotation log |
| Network | One edge with a firewall and rate limits; no public internal services; allow-listed outbound | Network policy; external scan results |
| Supply chain | Signed images, SBOM, dependency and image scanning, staging before production | CI records; signature verification at deploy |
| Input safety | The intake gate on every file; adversarial set in every release | Gate exam results |
| Data protection | Data processing agreement, subprocessor list, residency, retention and deletion | Signed agreements; deletion records |
| Training consent | No training on customer data without written opt-in | Consent register; training data lineage |
| Backups | Per-tenant backups with point-in-time restore | Restore tests |
| Monitoring | Per-tenant dashboards, alerts, traces | Alert history |
| Incidents | On-call, status page, notification, post-incident reviews | Incident log |
| Penetration testing | Regular external tests | Reports and fixes |
A2 · Targets per stage
| Stage | What is measured | Target |
|---|---|---|
| Intake | Time to an intake decision | About a second |
| Intake | Out-of-scope recall on the intent set | Near perfect |
| Factory · documents | Time per short document (under ten pages) | Under 30 seconds |
| Factory · documents | Invented key-field values | Under 1%, upper bound of the interval reported |
| Factory · rule change | Docket comparison | Seconds on a CPU |
| Factory · rule change | A full docket case | Within its one-minute budget |
| Agents | Every step has a work record | 100% |
| Evals | Every release passes its exams | No passing exams, no release |
| Train | Every retrained model beats the current one | By more than the interval |
| Ship | Rollback | One deploy |
A3 · Runbooks
- Onboard a tenant: namespace, keys, single sign-on, quotas, first package, smoke test.
- Offboard a tenant: export, deletion, deletion certificate.
- Upgrade a tenant, and roll one back.
- Restore a tenant from backup.
- Rotate a tenant's keys; respond to a key revocation.
- Respond to a provider outage, a security incident, a data request.
Originally published at https://agentair.ai/blog/exams-records-and-crews.
Top comments (0)