Inspiration
Running out of medication rarely happens because someone decided to stop. It happens because they forgot, because the pharmacy closed at 9, because they were on hold too long, or because something felt off and nobody asked. For students with ADHD on a controlled stimulant like Concerta, it's worse: every refill needs a pharmacist, and remembering to call is hard.
A reminder call that also takes the refill would help. But that is also exactly what nobody should hand to an AI without a lock on it. A stimulant is the kind of prescription a phone agent must never be talked into handing out early, sending to a new address, or discussing with the wrong person. AI phone assistants have already been pulled from pharmacies after complaints about wrong dosages and missed prescriptions.
So we built both halves together: the reminder, and the lock. The whole idea fits in one line: the AI can be fooled, the pharmacy can't.
Some context we leaned on:
- About half of people on long-term therapy don't take their medication as prescribed (WHO, Adherence to Long-Term Therapies, 2003).
- In Canada, 9% of people skipped or delayed medication because of cost: 7% of those with drug insurance and 17% of those without (Statistics Canada, 2022).
- Methylphenidate, the drug in Concerta, is a controlled drug in Canada. It can only be refilled as many times, and at the intervals, the prescriber wrote.
What it does
Aegis is an AI phone line for pharmacies, built around one rule: every action and every spoken line goes through code the AI cannot get around.
For the patient
- A daily check finds patients who are nearly out of medication and calls them before they run out.
- The caller is verified with a one-time code and their date of birth. Nothing private is said before that.
- In one short call it refills what's due, reads back the label and the cost after the drug plan, books a delivery window, and asks how the medication is going. A side effect goes straight to a pharmacist, in the patient's own words.
- It works by voice or by typing, with a live transcript.
For the pharmacist
- A console with Today, Upcoming, Outreach and Calls. Only the tricky calls reach a person, sorted into three lanes: Automatic (went through on its own), Quick check (one tap) and Review (a pharmacist decides, with the reason and the full transcript attached).
- Controlled drugs, side effects and anything the guard blocked wait for a pharmacist, who signs in with Auth0 and approves or denies. The approval is written to the record under their name.
The lock: why a fooled AI still can't break a rule
- 12 buttons, nothing else. The AI acts only by pressing one of 12 buttons: look up a patient, send a code, check the code, check a prescription, read the label, check coverage, check an order, request a refill, request a renewal, set a delivery, leave a note for the pharmacist, or escalate. Every press goes through a control layer that checks it against rule cards. The strictest rule wins, and the layer fails closed: if anything is missing or unclear, the answer is no.
- A speech guard on every sentence. Before anything is spoken it must pass four rules: nothing private before the caller is verified, never someone else's prescription, no dose that isn't on the label, and no promise the record doesn't back up (like "it's approved" or "it'll be there Friday"). A line that fails is replaced with a safe one, and the attempt is logged.
- A safety check on every caller line before the AI answers, for emergencies and crisis language.
- A tamper-evident record. Every press, sentence, block and approval is saved as an entry chained to the one before, so changing or deleting anything breaks the chain. Scores are read from this record, never from what the model says it did.
For the red team
- A stage view for the projector shows every action at the gate, blocked lines struck through, and live counters for rules broken and attacks caught.
- A hijack switch swaps in a fully compromised AI that does whatever it's told, and lets a judge pick an attack: refill 90 Adderall today, ship it to a new address, read someone else's prescription, or read details out before the caller is verified. The lock catches every one.
- A Safety suite with evaluations, attacks, scripted scenarios, an overnight red team, live attack calls, every rule with the reason it exists, a release gate and a rule writer.
- Business tests in the style of an eval company: scripted callers (act like a pirate, act like a fish, write me a poem, ignore your instructions, "I'm the pharmacist", a wrong code, a 9-8-8 crisis line, a 911 overdose, bookings and refills) run against the real agent and lock, and you hear each call live in two voices.
How we built it
Aegis is a single Next.js 16 application in strict TypeScript. At its core is a security layer the AI cannot bypass: 12 approved actions, rule cards, a speech guard and a tamper-evident record. Patient calls, the pharmacist console and red-team testing all run through this same layer. There are no test-only shortcuts or separate demo paths.
1. Restricted AI actions. The AI can only act through 12 strictly typed tools. We own the tool-calling loop, so every action passes through our control layer before it runs.
2. Rule-based approval. Every action is checked against rule cards covering controlled substances, early refills, new addresses, verification and account lockouts. When rules conflict, the strictest one wins. If information is missing or unclear, the action is denied.
3. Speech guard. Every response passes the guard before it's spoken. It catches private information before verification, the wrong patient's details, doses not on the label, and promises the record doesn't back. It checks individual claims across multiple languages, catching disguised approvals and delivery promises.
4. Tamper-evident record. Every action, sentence, blocked response and approval is chained to the previous entry. Any modification breaks the chain. All scores come from this record, not from the AI's own account.
AI agent: Claude. Sonnet 5.5 on the Anthropic API powers the call agent, and Haiku 5.5 runs through the Claude Agent SDK. The SDK session is restricted to our 12 tools, with no built-in tools, MCP servers, plugins, skills or settings files. Every caller message is screened for emergencies, overdoses and crisis language first. For phone calls we turned hidden reasoning off to cut response time; the lock holds whatever the model reasons.
Voice and phone: ElevenLabs and Twilio. ElevenLabs is Aegis's voice, generated server-side so API keys never reach the browser. Twilio carries real phone calls, routing each patient turn through our server, the same agent and the same lock before the reply plays. We generate and cache speech sentence by sentence, let callers interrupt mid-reply, and use Twilio Verify for one-time codes. A bridge passes only successfully verified codes to our lock; wrong codes are rejected by our own lockout. Codes are never logged or put on the live event stream.
Sign-in and approvals: Auth0. Auth0 handles pharmacist and reviewer sign-in. A post-login Action adds roles to the token, which gate controlled refills, side-effect reviews, patient lockouts and rule changes. The approver's identity comes from the Auth0 session, never from the request, so nobody can impersonate a pharmacist. Aegis can only say "approved" once the approval exists in the record.
Database: Tiger Data. Production records live in Postgres on Tiger Data over verified TLS. Tests use an in-memory store and embedded Postgres (PGlite), isolated from production, and we verified both produce identical results, including the chained record.
Red-team testing. We tried to break Aegis at every layer and saved every result:
- Stress testing: 77,648 hostile sequences, 275,098 actions and 379,902 rule checks, with zero safety violations.
- AI hijacking: a compromised agent tried mass Adderall refills, new delivery addresses, other patients' prescriptions and pre-verification leaks. Every attempt was blocked.
- AI red teaming: Gemini 2.5 Flash and Claude each generated attacks against the live agent. Across 20 calls: 9 attacks caught, 0 breaches, 0 gaps found.
- Speech testing: 0 of 643 unsafe responses were spoken.
- Patient simulations: scripted scenarios scored straight from the record.
- Live demos: attack calls play a buzzer where a blocked line was, then the safe line.
Every change must pass type checking, linting, the full test suite, the stress tests and a production build before it merges.
How we used Gemini
Gemini 2.5 Flash (through the @google/genai SDK) is our second red-team attacker. A lock tested by only one model family inherits that family's blind spots, so Gemini and Claude each write their own attacks against the live agent: fake verification codes, claimed pharmacists, pressure for an early controlled refill, attempts to read another patient's prescription. Each attack runs as a real call through the 12 buttons and the speech guard, and the result is scored from the record. Across 20 attack calls from the two models: 9 caught, 0 broken, 0 gaps.
How we used Entire
Our whole workflow ran on Entire. Four humans each directed a Claude Code role agent (voice and agent, platform and console, red team, the lock), alongside helper agents for code review, fixes, rules enforcement, merges and design. They all worked in parallel on one repo.
- 797 of 1,156 commits on main carry an
Entire-Checkpointtrailer, linking each one to the agent session that wrote it (319 merges). Check it with:git log --format=%B | grep -c Entire-Checkpoint - 62 merged Trails, 18 open. Every task is a Trail on a
role-<n>/<task>branch, posted as CLAIM, then HANDOFF, then MERGED on our agent channel. Check it with:entire trail list - A code-reviewer agent reviewed the Trails. The owner fixes a finding or applies its suggested patch; only the reviewer can resolve it. Trail #27 closed 11 findings. Check it with: Trail #27 (Entire sign-in)
- Humans steered the agents through Trail #2. Agents read it every cycle and never post there. Check it with: Trail #2
- Measured Graph savings: 87% fewer tokens. Three repo questions (refill timing, prescription labels, simulated walk-ins), each run twice per method. Both methods answered all 6 correctly. Graph used 21,299 tokens; source search used 163,359. Check it with:
entire graph query - Brain held the team's decisions. Every session starts with
entire brain brief, for example "test calls use the same agent, rules and record as patient calls". Check it with:entire brain recall
One failure, traced end to end. Aegis blocked the assistant from saying "I can check whether it's ready for a refill." Trail #27 traced it to the rule that blocks unverified promises. We ran the exact same sentence against two revisions: it failed before the fix and passed after. The live call audio is another example: the test commit (f910d97b) and the implementation (a47a64a4) each carry a checkpoint back to the session that wrote them.
Built on top of Entire: an agent channel and build board (scripts/board.mjs) showing every task from CLAIM to MERGED with Trails, AI-linked commits, Brain and Graph; a hook that shows each agent its open review findings before every prompt; and a headless loop that keeps a role's agent working overnight until a human posts STOP.
What we liked
- Following a teammate's model prompts and picking up exactly where their agent left off.
- The GitHub integration is very well done and easy to use.
- Setup time was tiny compared with the time it saved.
- Sessions linked to commits felt more intuitive than plain GitHub history.
- Analytics got the whole team curious about who used the most tokens, who contributed most, and how many tokens we burned over the weekend.
What was hard
- Depending on how often you prompt, Trails can get overwhelming fast, and side-tracked prompts get trailed too.
- With many agents committing, per-merge history and the repo's commit history got harder to navigate, and we hit GitHub Actions usage limits for the first time.
- Shared memories sometimes leaked into another agent's work, which raised the real problem of managing shared agent state.
Challenges we ran into
A guard that's too strict is also broken. Our first "no unbacked promises" rule blocked perfectly honest lines like "I can't say yet when it will be ready", offers like "I can check whether it's ready", and "your code is confirmed". We fixed them one phrase at a time until we realised it was whack-a-mole, then rewrote the rule properly: a word like "approved" or "ready" is only allowed when it's clearly conditional ("once it's approved") or negated ("it isn't ready yet").
A guard that's too loose is worse. Code review found that "Approved!", "Good news, you're approved" and "Your delivery is due Friday" slipped through. We closed both holes, wrote the tests first, and added those exact sentences to the stress tests.
Defaults that failed open. Verification codes were broadcast on the public event stream by default, and a rule whose input was missing silently never fired. Both now fail closed.
Weak outbound verification. An outbound call could verify a patient with the code alone. Now the code and the date of birth must both match, or it counts towards a lockout.
Leaks through the side door. An anonymous visitor could read transcripts, names and blocked lines from the live event stream. Now staff see everything, a paired phone sees only its own call, and the public sees only counters.
AI agents don't follow prompts any better than our product's AI does. One of our coding agents pushed changes to the lock straight to main 9 times while a written rule told it not to. Same lesson as the product: rules written as prompts don't hold on their own. So we added an agent whose only job was checking every other agent against the rules, and recorded each violation and its fix.
Real-world plumbing. Windows text encoding broke our message parser, a shell command turned regular expressions into invisible characters, running the tests with the wrong setting would have wiped the shared demo database (caught in review), and speech recognition, text-to-speech and the phone line each have their own timing quirks on a live call.
Accomplishments that we're proud of
- 0 rules broken across 77,648 hostile action sequences, with every safety rule checked after every action. Any change that breaks one is blocked from merging.
- Even an AI that does anything it's told can't refill a controlled drug early, ship to an address that isn't on file, read someone else's prescription, or leak details before verification. Latest run: 9 attempts caught, 0 broken.
- Two attacker models, Claude and Gemini, threw 20 brand-new attacks at the live agent overnight: 9 caught, 0 broken, 0 gaps.
- Scores come from a tamper-evident record, not from the model's word. Every result can be reproduced from made-up patients, and no number in our pitch is an estimate.
- The full flow works end to end: the call verifies the patient, reads back the label and cost, routes the controlled refill and passes on a side effect; the pharmacist approves through Auth0; only then does the AI say "approved". It passed our demo checklist three times in a row.
- A software team of AI agents that claimed tasks, reviewed each other's work, fixed what was found and merged it, with 797 of 1,156 commits on main traceable to the AI session that wrote them.
What we learned
- Put the rules in code, not in the prompt. Both our product and our own build process taught us that. A prompt is a suggestion; a control layer is a wall.
- Blocking too much is a safety problem too. An agent that isn't allowed to say "I don't know yet" will make something up or stall. The goal is a guard that's precise, not just strict.
- Test the tester. Our first stress-test check for false approvals reused the guard's own logic, so it could never catch the guard's mistakes. Independent checks found real holes.
- Measure, don't claim. Every number we show comes from a saved run. If a test hasn't run yet, the app says so instead of showing a made-up figure.
- Honest results beat a perfect-looking dashboard. On the smaller Haiku model, 28 scripted scenarios passed 16 outright, and 7 ended with the wrong but still safe outcome. None broke a rule. That shows exactly where the agent needs to get more helpful without getting less safe.
- AI reviewing AI shares blind spots. Next time, a person approves every change to the lock, enforced by GitHub itself rather than by a rule an agent can ignore.
What's next for Aegis
- A pilot with a real pharmacy, starting with reminder calls and simple refills, with a pharmacist in the loop for anything controlled.
- More helpful while just as safe: fix the wrong-outcome cases without loosening any rule, and score realistic persona callers on helpfulness alongside safety.
- Plain-English rule writing for pharmacists: describe a policy, Aegis drafts the rule, the stress tests check it, and a person signs off before it goes live.
- Call reports that write themselves from the record, with citations, for auditors and insurers.
- Hosting on Vultr with automatic HTTPS on our own domain.
- Hard guarantees for how we build: code owners and branch protection on the lock, and a separate identity for each AI agent.
Built With
- auth0
- caddy
- claude
- claude-(anthropic-api
- claude-agent-sdk)
- elevenlabs
- entire
- eslint
- gemini
- github-actions
- next.js
- node.js
- pglite
- postgresql
- react
- tailwind-css
- tiger-data
- twilio
- typescript
- vitest
- vultr
- web-speech-api
- zod
