Several AI coding sessions run side by side on one Mac in my setup. Each one is a lane with its own job: one does heavy builds, one handles a single repository, one makes decisions. They talk to each other by mail through the myAI gateway, and one of them holds a lease that makes it the swarm master. The machinery behind that (the lease, the mailbox, worktrees, the ship lock) is a topic for another post.
This post covers one week of changes to it. None of them added a feature. Each one came from looking at where the money went or why something paged me when nothing was wrong.
1. The master was the most expensive session to wake up
The master session reads every report, blocker and merge request the other lanes send. In the old layout, the master was an API-billed session, and every mail woke it up. Each wake-up re-read a long-lived context before it could even look at the new message. Most messages were small. The cost wasn't the message, it was the context it had to carry to read it.
The fix came in three steps over the week, and the order matters.
Step 1: take routing away from the model. A new myai-mail container now does the routing. It is a small compose service with a 64 MB memory limit and restart: unless-stopped. It routes mail by a plain config file, sends anything it can't route once to the heavy-work lane, and flags lanes that have gone quiet. It never merges anything, never answers a result, and never calls a model. The only secret it gets is the local gateway token. Routing costs nothing in tokens now, because nothing in the routing path thinks.
Step 2: write the rule down and enforce it. For a couple of days the router also held the master lease, which mixed two jobs: delivering mail and deciding. So I wrote it down as a rule: the router is comms only and never holds the badge. It got its own lease, separate from the master's. The check script now returns RED in two cases: if the router holds the master badge, or if some other session holds it while the designated master is alive on that host. The fleet health check fails on the same two cases. A rule nobody checks is just a suggestion, so the rule went into the health check, not only into the docs.
Step 3: move the master to the session where waking is cheap. The last change made a flat-rate session both master and decider. The router wakes it in batches, and the API-billed session now gets zero routine wake-ups. Lanes may now merge their own pull requests into test. Merging into main is still for the operator only. Merges into test happen dozens of times a day and are safe to delegate. Production is the one gate that has to stay with a person.
flowchart LR
IN["Mail from lanes<br/>reports, blockers, merge requests"] --> R["Router container<br/>64 MB · zero model calls"]
CFG[("Routing rules<br/>plain config file")] -.->|read| R
R -->|"work"| W["Worker lanes"]
R -->|"decisions, batched<br/>one line each"| M["Master session<br/>flat-rate, decides"]
R -->|"unmatched: escalate once"| H["Heavy-work lane"]
R -.->|"quiet lane flagged"| M
The lesson I keep relearning: in an agent system, decide where the expensive context lives first, then send as little traffic to it as you can.
2. The gateway that never came back after the lid closed
The gateway keeps its state in MongoDB. After the Mac slept and woke, the Mongo connection sometimes dropped and never reconnected. The container stayed up, the health check said unhealthy, and nothing happened, because Docker never restarts a container just for being unhealthy. A restart policy only acts when a process exits. A process that is alive but broken looks fine to it.
The fix is a small connection watchdog:
- After 60 seconds without a connection, it closes and reopens using the same URI that last worked, primary or failover, and retries every 15 seconds.
- If it is still down after 10 minutes, the gateway sends itself a single SIGTERM. Graceful shutdown exits, and the restart policy brings the container back clean. In other words, the watchdog turns "unhealthy" into "exited" so the existing restart policy can do its job.
- It only does this for a connection that worked at least once. A database that is down at boot stays with the normal boot retry, so there's no restart loop.
sequenceDiagram
participant H as Laptop
participant GW as Gateway
participant DB as Database
participant RP as Restart policy
participant S as Agent sessions
H->>H: Lid closes, host sleeps
Note over GW,DB: Connection drops during sleep
H->>H: Wake
GW-xDB: Health probe fails (container still up)
loop every 15 s, after 60 s down
GW->>DB: Reopen with the last good URI
end
alt reconnects
DB-->>GW: Connected
else still down after 10 min
GW->>GW: SIGTERM itself, graceful exit
RP->>GW: Restart the container clean
GW->>DB: Fresh connection
end
GW-->>S: Health OK
S->>GW: Sessions reconnect
The morning boot got the same treatment. It now waits up to 420 seconds for the gateway instead of 180, long enough for a slow cloud connection plus a local failover start. If the gateway still isn't healthy, the boot starts the dashboard anyway, checks that it answers, and still fails loudly naming the gateway. A red boot with a working dashboard is much more useful than a red boot with nothing on screen.
The watchdog has six unit tests on a fake clock, so ten minutes of downtime runs in milliseconds.
3. The router kept saying a lane had died. It hadn't.
Once the router was flagging quiet lanes, it paged me that the heavy-work lane had exited, twelve times in one day. Each time the lane came back on its own, between one and seventy minutes later. A page that is wrong twelve times a day teaches you to ignore it, which is worse than no page.
The router logs showed two kinds of event:
| What the log showed | Count | Cause | |---|---|---| | Lane state empty | 9 | The lease query answered with plain text instead of JSON (a database blip after sleep). The parser produced nothing, and the router read "nothing" as "not alive". | | Lane state dead | 3 | The presence lease really was stale. Ticks come from hooks and the mail watcher, so one long tool call or a sleep can hold the lease past its 10-minute expiry. |
Two fixes, one per cause:
- A reply the router can't read is not evidence. If the lease reply has no
leasesarray, the router skips that check, logs that it skipped it, and keeps the last known state. Before, "I couldn't parse the answer" counted as "the lane is dead", and that is never the same thing. - Grace before paging. A lane has to stay not-alive for 15 minutes before it is paged, and coming back alive restarts the clock. A lane that really exits still gets paged once, about 15 minutes later, and the page now says how long the heartbeat has been missing.
stateDiagram-v2
[*] --> Alive
Alive --> Unreadable: lease reply is not JSON
Unreadable --> Alive: skip check, keep last state
note right of Unreadable: The old router read this as dead
Alive --> Stale: heartbeat missing
Stale --> Alive: tick arrives, clock resets
Stale --> Paged: stale for 15 min
Paged --> Alive: lane comes back
The new test section covers a 9-minute stale (no page), a recovery that restarts the clock, a 15-minute stale (one page, not repeated), and three unreadable replies: plain text, an error object, and truncated JSON. Seven of the new checks fail on the old router, which is how I know they test the bug and not just the new code.
4. What the week adds up to
Looking back, all three changes follow the same idea: the cheap, dumb parts should do the routine work, and the expensive, smart parts should only see what needs judgment.
- Routing is a config file in a 64 MB container, not a model reading its inbox.
- Recovering from a dropped connection is a timer and a signal, not a person noticing a dashboard.
- Spotting a dead lane needs an answer it can parse and a grace period, not a hair trigger.
When a swarm runs on one machine, sleep and wake become a fault you have to design for. The lid closes, connections drop, leases expire mid-thought, and every component has to tell "I can't see it" apart from "it's gone". Most of this week's work was teaching each piece that difference.
If you run something similar, and especially if you've solved the "master is expensive to wake" problem a different way, I'd like to compare notes. Get in touch.