Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(blog): add internals posts — mailboxes, single-committer, hooks, node-pty (#4,#6,#7,#10)

Chaitanya Giri13531393cbc1
diff --git a/blog/src/posts/atomic-file-mailboxes-for-agents.md b/blog/src/posts/atomic-file-mailboxes-for-agents.md
new file mode 100644
index 00000000..abe44e00
--- /dev/null
+++ b/blog/src/posts/atomic-file-mailboxes-for-agents.md
@@ -0,0 +1,169 @@
+---
+title: "Atomic File Mailboxes: How Agents Message Each Other"
+description: "Can Claude Code agents talk to each other? Yes — here's the outbox-router-inbox design that lets agents message safely using plain files and atomic renames."
+date: 2026-05-31
+category: internals
+categoryLabel: Internals
+type: Technical
+primaryKeyword: "can claude code agents talk to each other"
+secondaryKeywords: ["ai agent messaging", "agent mailbox", "inter-agent communication"]
+tags: ["Internals", "Messaging", "Multi-Agent", "Claude Code"]
+author:
+ name: Chaitanya Giri
+ initials: CG
+faq:
+ - q: "Can Claude Code agents talk to each other?"
+ a: "Yes. Each agent has an outbox it writes to and an inbox it reads from; a router process moves messages between them. The agents never write into each other's folders, so messaging is safe even with many agents running at once."
+ - q: "Why use files for agent messaging instead of a message queue?"
+ a: "Files plus atomic renames give you durability, auditability, and crash-safety for free, with no broker to run. One JSON file per message, delivered by rename, is simpler and more robust than a shared log every agent appends to."
+ - q: "What stops two agents from messaging each other forever?"
+ a: "Only requests, queries, and proposals obligate a reply; informational messages are terminal. Every reply increments a hop count, and past a cap the exchange is escalated to a human instead of looping."
+---
+
+<div class="callout tldr"><span class="ic">TL;DR</span><p>Yes,
+<strong>Claude Code agents can talk to each other</strong> — and the safest way is plain files. Each
+agent writes to its own <code>outbox/</code>; a <strong>router</strong> drains it and delivers each
+message into the recipient's <code>inbox/</code> by <strong>atomic rename</strong>. One JSON file per
+message, never a shared log. The result is durable, auditable, crash-safe messaging with no broker and
+no write conflicts.</p></div>
+
+"Can Claude Code agents talk to each other?" is one of the first questions people ask when they move
+past a single session. The answer is yes — but *how* they talk is where most designs go wrong. Let a
+shared chat file be appended by every agent and you've built a multi-writer conflict. The robust
+approach is a mailbox: outbox, router, inbox, with atomic file operations underneath. Here's the whole
+design.
+
+## The shape: outbox → router → inbox
+
+Every agent gets a private workspace, and two of the folders in it are for messaging:
+
+```
+agents/<agent-id>/
+ inbox/ # messages delivered TO me — one JSON file each
+ inbox/.done/ # messages I've handled (kept for audit, not deleted)
+ outbox/ # messages I want to SEND — the router drains these
+ outbox/.sent/ # archived after delivery, so they're never reprocessed
+```
+
+The flow is one direction at a time:
+
+1. To send, an agent writes a single JSON file into its **own** `outbox/`.
+2. A **router** — one coordinating process — scans every outbox, reads each message, and delivers it
+ into the recipient's `inbox/`.
+3. After delivery, the router moves the original from `outbox/` into `outbox/.sent/` so it's never
+ sent twice.
+4. The recipient reads its `inbox/` at the start of its next turn, acts on each message, and moves the
+ handled ones to `inbox/.done/`.
+
+The critical rule sits underneath all of it: **an agent only ever writes into its own directory.** It
+never reaches into another agent's inbox. Delivery is the router's job. That single-writer discipline
+is what makes the whole thing safe under concurrency — no two processes touch the same file. (It's the
+same principle behind [the single-committer git pattern](/blog/single-committer-git-pattern/).)
+
+## Why atomic renames matter
+
+Here's the subtle part. If the router wrote a message into an inbox with a normal "open, write bytes,
+close," a reader scanning the inbox at the wrong moment could pick up a half-written file and choke on
+invalid JSON.
+
+The fix is an **atomic rename**: write the message to a temporary filename first, then `rename` it
+into its final place. On every mainstream filesystem, rename within a directory is atomic — the file
+either isn't there or is there *complete*. A reader never sees a partial message. There's no lock, no
+coordination, no window of inconsistency.
+
+```
+write inbox/<id>.json.tmp-9f3a ← may be partial mid-write
+rename inbox/<id>.json.tmp-9f3a → inbox/<id>.json ← appears atomically, whole
+```
+
+This one trick is why files beat a naive shared log. A log every agent appends to is a multi-writer
+race; a directory of atomically-renamed files is conflict-free by construction.
+
+## The message itself: speech acts, not free text
+
+A message isn't just a blob of text — it carries intent. The design borrows the one genuinely useful
+idea from decades of agent-communication research, the **speech act**, and drops the rest:
+
+```jsonc
+{
+ "id": "2026-05-30T14-03-11-123Z-a1b2", // unique, time-sortable
+ "conversation": "conv-7f3", // groups a thread
+ "in_reply_to": "<prev message id> | null",
+ "from": "agent.researcher",
+ "to": "agent.coder | god | broadcast",
+ "act": "request | inform | propose | query | agree | refuse | done",
+ "subject": "short human-readable summary",
+ "body": "the details",
+ "hops": 3, // increments per reply; capped to kill loops
+ "requires_reply": true,
+ "needs_human": false,
+ "created_at": "ISO-8601"
+}
+```
+
+An agent writing a message only has to supply the meaningful fields — `to`, `act`, `subject`, `body`,
+and optionally a `conversation` to thread it. The harness fills in the `id`, the authoritative `from`
+(taken from the owning outbox directory, so an agent can't spoof another's identity), the `hops`, and
+the timestamps.
+
+The `act` field is what makes coordination tractable. It tells the recipient — and the router —
+whether a reply is even expected.
+
+## Anti-livelock: how the conversation ends
+
+Two agents told to "coordinate" will, without guardrails, message each other forever. Three rules stop
+that:
+
+- **Only some acts obligate a reply.** `request`, `query`, and `propose` expect an answer. `inform`
+ and `done` are *terminal* — replying to them is exactly how a loop starts, so the protocol forbids
+ it.
+- **Hops are capped.** Every reply increments the `hops` counter. Past a fixed cap, the message is
+ flagged for a human instead of being delivered again — a livelock fuse.
+- **Delivery is idempotent.** Each agent keeps a cursor of the last message id it processed, so
+ re-seeing a message is a no-op. Combined with moving handled messages to `inbox/.done/`, an agent
+ can't accidentally act on the same request twice.
+
+These are small rules with a big payoff: the messaging layer can be busy and still provably converge.
+
+## Broadcast and escalation
+
+Two special addresses round out the system:
+
+- **`broadcast`** delivers a copy to every agent except the sender — useful for "I'm taking ownership
+ of the auth module, don't touch it."
+- **`human`** (or any message flagged `needs_human`) doesn't go to an inbox at all. The router diverts
+ it to an approvals queue for a person to answer. This is how an agent reaches *you* for the genuinely
+ critical calls, and it's the same mechanism the orchestrator uses to escalate — covered in
+ [the best way to coordinate AI coding agents](/blog/coordinating-ai-coding-agents/).
+
+## Why this design holds up
+
+Step back and the properties fall out for free:
+
+- **Durable.** Messages are files. A crash mid-run loses nothing already written; the router picks up
+ where it left off.
+- **Auditable.** Every message and every delivery is a file, and the coordinating process commits the
+ changes to git — so you can read back exactly who said what, in order.
+- **Brokerless.** There's no Redis, no RabbitMQ, no daemon to keep alive. The "infrastructure" is a
+ directory and the `rename` syscall.
+- **Conflict-free.** Single-writer-per-file plus atomic renames means concurrency is safe without
+ locks.
+
+It's almost boring, which is the point. The most reliable inter-agent messaging is the kind with the
+fewest moving parts.
+
+## FAQ
+
+**Does the router poll or watch the filesystem?** A simple poll on a short interval is both cheaper and
+more robust than filesystem-watch APIs, which have well-known quirks across platforms. The router
+scans every outbox on a tick, delivers what it finds, and goes back to sleep.
+
+**Can an agent message itself?** It can, but there's rarely a reason to. The interesting traffic is
+agent-to-agent and agent-to-orchestrator.
+
+---
+
+Munder Difflin runs exactly this mailbox system for a whole hive of Claude Code agents — atomic
+delivery, speech-act messages, hop caps, and a full git audit trail, all local.
+[Download Munder Difflin](https://munderdiffl.in/#install) to watch envelopes fly between agents on
+the office floor; it's free and open source.
diff --git a/blog/src/posts/claude-code-hooks-explained.md b/blog/src/posts/claude-code-hooks-explained.md
new file mode 100644
index 00000000..b2f25a46
--- /dev/null
+++ b/blog/src/posts/claude-code-hooks-explained.md
@@ -0,0 +1,185 @@
+---
+title: "Claude Code Hooks, Explained (PreToolUse, PostToolUse, Stop)"
+description: "A practical tour of Claude Code hooks — the PreToolUse, PostToolUse, and Stop lifecycle — and how a Unix-socket hook shim drives an autonomous multi-agent office floor."
+date: 2026-06-03
+category: internals
+categoryLabel: Internals
+type: Technical
+primaryKeyword: "claude code hooks"
+secondaryKeywords: ["pretooluse posttooluse", "stop hook", "claude code lifecycle"]
+tags: ["Internals", "Hooks", "Claude Code", "Automation"]
+author:
+ name: Chaitanya Giri
+ initials: CG
+faq:
+ - q: "What are Claude Code hooks?"
+ a: "Hooks are commands Claude Code runs at points in its lifecycle — before and after a tool call, when it's about to stop, on a notification, and more. Each hook receives a JSON payload on stdin and can return JSON to influence what Claude does next."
+ - q: "What does the Stop hook do?"
+ a: "The Stop hook fires when Claude is about to finish a turn. If it returns {\"decision\":\"block\",\"reason\":...}, Claude keeps working with that reason as new instructions — which is how you build an autonomous loop. A stop_hook_active flag prevents it from looping forever."
+ - q: "Do hooks modify my repository?"
+ a: "They don't have to. Claude Code accepts a --settings file, so you can attach hooks from a settings file outside your project instead of editing files in the repo itself."
+---
+
+<div class="callout tldr"><span class="ic">TL;DR</span><p><strong>Claude Code hooks</strong> are
+commands that run at lifecycle points — <code>PreToolUse</code>, <code>PostToolUse</code>,
+<code>Stop</code>, <code>Notification</code>, and more. Each gets a JSON payload on stdin and can
+return JSON to steer Claude. Munder Difflin attaches a tiny <strong>hook shim</strong> via
+<code>--settings</code> that forwards every event to the harness over a Unix socket — driving live
+avatars from <code>PreToolUse</code>/<code>PostToolUse</code>, and building an <strong>autonomous
+loop</strong> out of the <code>Stop</code> hook.</p></div>
+
+Hooks are the most underrated part of Claude Code. They're the official extension point for "do
+something when Claude does something" — and once you understand them, a lot of agent tooling that
+looks like magic turns out to be a well-placed hook. This post walks the lifecycle, then shows exactly
+how Munder Difflin uses hooks to animate a multi-agent office floor and keep agents working
+autonomously.
+
+## What a hook is
+
+A hook is a command Claude Code runs at a defined moment in its lifecycle. When the moment arrives,
+Claude executes your command and pipes it a **JSON payload on stdin** describing what's happening. Your
+command can do whatever it likes, and — for some events — return **JSON on stdout** that influences
+Claude's next move.
+
+You configure hooks in settings, mapping each event to one or more commands:
+
+```jsonc
+{
+ "hooks": {
+ "PreToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node my-hook.js" }] }],
+ "PostToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "node my-hook.js" }] }],
+ "Stop": [{ "hooks": [{ "type": "command", "command": "node my-hook.js" }] }]
+ }
+}
+```
+
+The `matcher` (for tool events) lets you scope a hook to specific tools — `*` means "every tool." Tool
+events carry that matcher; lifecycle events like `Stop` don't need one.
+
+## The lifecycle events that matter
+
+There are several hook events; these are the ones you'll reach for most.
+
+### PreToolUse
+
+Fires **before** Claude runs a tool. The payload includes the `tool_name` (e.g. `Edit`, `Bash`) and
+the `tool_input`. This is your "Claude is about to do X" signal. You can use it for observability, or —
+because PreToolUse can return a decision — to gate or block a tool call before it runs.
+
+### PostToolUse
+
+Fires **after** a tool completes. Same shape, now with the result available. PostToolUse is the natural
+place to react to what just happened: log it, update a UI, trigger a follow-up.
+
+Together, PreToolUse and PostToolUse bracket every action Claude takes. If you want a faithful,
+real-time picture of what an agent is doing, these two events are it — you're not scraping terminal
+output or guessing, you're getting structured "about to / just did" events straight from Claude.
+
+### Stop (and SubagentStop)
+
+Fires when Claude is about to **finish a turn** — it's done and ready to hand control back. This is the
+most powerful hook, because of what it can return:
+
+```json
+{ "decision": "block", "reason": "Here's what to do next…" }
+```
+
+Returning `block` tells Claude *not* to stop — to keep going, treating `reason` as fresh instructions.
+That's the entire basis of an **autonomous loop**: every time the agent tries to finish, a Stop hook
+can hand it more work. `SubagentStop` is the same event for a spawned subagent.
+
+The obvious danger is an infinite loop, so the payload carries a `stop_hook_active` flag: it's true
+when a previous Stop hook already blocked this turn. Check it, and you can guarantee you never block
+twice in a row — the loop always has an exit.
+
+### Notification, UserPromptSubmit, SessionStart
+
+- **Notification** fires when Claude surfaces a message — including when it's idle and waiting for
+ input, or asking permission. The payload's text lets you tell "needs you" apart from "just done."
+- **UserPromptSubmit** fires when a prompt is submitted — a clean "the agent started working" signal.
+- **SessionStart** fires when a session begins — handy for setup or registration.
+
+## How Munder Difflin uses hooks
+
+Munder Difflin runs many `claude` agents at once and needs two things from each: a live view of what
+it's doing, and a way to keep it working through a queue. Both come from hooks.
+
+### A hook shim over a Unix socket
+
+The harness can't run heavy logic inside each hook invocation — hooks fire constantly and must be fast.
+So each agent is launched with a **hook shim**: a tiny script wired to every relevant event. The shim
+does almost nothing. It reads the hook payload on stdin, tags it with the agent's id (from an
+environment variable), forwards it to the harness over a **Unix domain socket**, and relays the
+response back to Claude. All the real logic lives in the harness's main process, which listens on that
+socket.
+
+```text
+claude ──hook fires──▶ shim ──UDS──▶ harness (main process)
+ ▲ │
+ └──── response ◀───────┘
+```
+
+The shim is deliberately dumb and crash-proof: if the socket isn't there or anything errors, it exits
+cleanly and never blocks the agent. Newline-delimited JSON over the socket keeps the protocol trivial.
+
+### Attached without touching your repo
+
+A key detail: the hooks are attached with Claude Code's `--settings` flag, pointing at a settings file
+the harness writes **outside** your project. Your repository is never modified to add hooks — no stray
+`.claude/settings.json` diff, nothing to gitignore. The agent is hive-aware purely through launch
+flags and environment variables.
+
+### PreToolUse/PostToolUse → live avatars
+
+Every tool event the harness receives is forwarded to the UI. That's what drives the office floor: when
+an agent calls a file tool, its avatar walks to the right station; when it runs a command, it moves to
+a terminal. Because the events are structured and come straight from Claude, the visualization reflects
+*real* activity rather than a scripted animation or fragile log-scraping.
+
+### Stop → the autonomous loop
+
+This is where hooks earn their keep. When an agent's `Stop` hook fires, the harness checks that agent's
+inbox for unread messages. If there are any, it returns `{"decision":"block","reason": <the
+messages>}` — so instead of stopping, the agent reads its new messages and keeps working. If the inbox
+is empty, it returns nothing and the agent is allowed to finish.
+
+Two guards keep this safe:
+
+- **`stop_hook_active`** — if a previous Stop already blocked this turn, the harness lets it stop, so
+ it can never block twice back-to-back.
+- **A per-agent cursor** — the harness tracks the last message id it surfaced, so each message is fed
+ to the agent exactly once. No message is re-delivered, and the loop can't spin on stale mail.
+
+The result is an agent that drains its work queue on its own and only goes quiet when there's genuinely
+nothing left — the foundation of [letting agents build while you sleep](/blog/claude-code-automation-while-you-sleep/).
+It's also how the [GOD orchestrator](/blog/how-the-god-orchestrator-works/) keeps the whole floor
+moving: route a task into an agent's inbox, and its next Stop hook picks it up automatically.
+
+## Writing your own hooks: practical tips
+
+If you're building with hooks directly, a few lessons that save pain:
+
+- **Keep them fast.** Hooks run synchronously in Claude's path. Do the minimum and offload anything
+ heavy (a socket forward, a queued job) rather than blocking.
+- **Fail open.** A hook that errors shouldn't wedge the agent. Catch everything and exit cleanly.
+- **Respect `stop_hook_active`.** Any Stop hook that can block must check this flag, or you'll build an
+ infinite loop.
+- **Use `--settings` for portability.** Attaching hooks via a settings file outside the repo keeps your
+ project clean and lets you apply the same hooks to many sessions.
+
+## FAQ
+
+**Can a hook block a dangerous tool call?** Yes — PreToolUse can return a decision that prevents a tool
+from running, which is useful for guardrails. Munder Difflin leans on its orchestrator and approval
+queue for that judgment, but the hook-level gate is available.
+
+**Do hooks slow Claude down?** Only as much as your hook command does. A shim that just forwards a
+payload over a local socket adds negligible overhead, which is exactly why the heavy logic lives
+elsewhere.
+
+---
+
+Munder Difflin turns Claude Code's hook lifecycle into a live, autonomous office: real-time avatars
+from tool events and a self-draining work loop from the Stop hook — all without editing your repo.
+[Download Munder Difflin](https://munderdiffl.in/#install) to see hooks driving a hive of agents; it's
+free and open source.
diff --git a/blog/src/posts/node-pty-electron-real-terminals.md b/blog/src/posts/node-pty-electron-real-terminals.md
new file mode 100644
index 00000000..6d3b7e24
--- /dev/null
+++ b/blog/src/posts/node-pty-electron-real-terminals.md
@@ -0,0 +1,212 @@
+---
+title: "Real Terminals in Electron with node-pty"
+description: "How to run byte-for-byte authentic shells inside Electron with node-pty: the native-rebuild gotcha, the macOS PATH trap, and streaming PTY output over IPC."
+date: 2026-06-03
+category: internals
+categoryLabel: Internals
+type: Technical
+primaryKeyword: "node-pty electron"
+secondaryKeywords: ["node-pty", "pseudo terminal", "electron terminal app"]
+tags: ["Internals", "Electron", "node-pty", "Terminals"]
+author:
+ name: Chaitanya Giri
+ initials: CG
+faq:
+ - q: "Why use node-pty instead of child_process for a terminal app?"
+ a: "child_process gives you pipes, not a terminal. Interactive programs detect that they're not attached to a TTY and change behavior — no colors, no prompts, broken full-screen UIs. node-pty allocates a real pseudo-terminal so programs behave exactly as they would in a normal shell."
+ - q: "What's the native-rebuild gotcha with node-pty in Electron?"
+ a: "node-pty is a native addon compiled against a specific Node ABI. Electron ships its own Node, so the npm-installed binary won't load. You have to rebuild node-pty against Electron's ABI — typically with electron-rebuild in a postinstall step."
+ - q: "Why can't my Electron app find `claude` or other commands?"
+ a: "On macOS, a GUI-launched Electron app doesn't inherit your interactive shell's PATH, so commands installed by nvm, asdf, or Homebrew aren't found. Resolve the command against an interactive login shell, or fall back to known install locations."
+---
+
+<div class="callout tldr"><span class="ic">TL;DR</span><p>To run real shells inside Electron, use
+<strong>node-pty</strong> — it allocates a genuine pseudo-terminal so programs behave byte-for-byte
+like they do in a normal terminal. The three things that bite everyone:
+<strong>rebuild the native addon against Electron's ABI</strong> (electron-rebuild),
+<strong>resolve commands against an interactive shell PATH</strong> (GUI apps don't inherit it on
+macOS), and <strong>stream output over IPC safely</strong>, guarding sends during window teardown.</p></div>
+
+If you want to embed a working terminal in a desktop app — a dev tool, an IDE, an agent harness that
+runs `claude` sessions — `node-pty` is the foundation. But "embed a terminal" hides three sharp edges
+that every Electron + node-pty project hits. This post is the field guide: what a PTY is, why you need
+one, and the gotchas that turn a one-line `spawn` into a day of debugging.
+
+## Why a pseudo-terminal, not a pipe
+
+The instinct is to reach for Node's `child_process.spawn` and pipe stdout into a `<div>`. It seems to
+work — until you run anything interactive. Here's why it breaks.
+
+Programs check whether their output is attached to a **TTY** (a terminal). When they detect a plain
+pipe instead, they assume "I'm being scripted" and change behavior:
+
+- colors and styling switch off,
+- interactive prompts vanish or hang,
+- full-screen TUIs (editors, `top`, anything using the alternate screen buffer) don't render at all,
+- line editing, arrow keys, and signals like Ctrl-C don't behave.
+
+A **pseudo-terminal (PTY)** is the fix. It's a kernel feature that presents a real terminal interface
+to the child process while handing the bytes to your code on the other end. The program thinks it's
+talking to an honest terminal — because it is — so it behaves exactly as it would in your shell.
+`node-pty` is the Node binding that allocates one and gives you `write`, `resize`, `onData`, and
+`onExit`.
+
+```ts
+import * as pty from 'node-pty';
+
+const proc = pty.spawn('claude', [], {
+ name: 'xterm-256color',
+ cols: 100,
+ rows: 30,
+ cwd: '/path/to/project',
+ env: { ...process.env, TERM: 'xterm-256color', COLORTERM: 'truecolor' }
+});
+
+proc.onData((data) => sendToRenderer(data)); // bytes from the shell
+proc.onExit(({ exitCode, signal }) => cleanup(exitCode, signal));
+```
+
+Note `name: 'xterm-256color'` and the `TERM`/`COLORTERM` env — they tell the child what terminal it's
+talking to, which is what unlocks 24-bit color. Set them, or you'll spend an hour wondering why output
+is monochrome.
+
+## Gotcha 1 — The native-rebuild trap
+
+This is the one that stops people cold on first install. `node-pty` is a **native addon**: it's
+compiled C++ that links against a specific Node ABI. You `npm install node-pty`, it builds against your
+system Node, and everything looks fine — until you load it inside Electron and get:
+
+```
+Error: The module was compiled against a different Node.js ABI version
+```
+
+Electron bundles **its own** Node, with a different ABI than the one npm built against. The binary that
+works in a plain `node` REPL won't load in Electron. The fix is to rebuild the addon against Electron's
+ABI, which is what `electron-rebuild` does. Wire it into a postinstall script so it happens
+automatically:
+
+```jsonc
+{
+ "scripts": {
+ "postinstall": "electron-rebuild -f -w node-pty"
+ }
+}
+```
+
+The `-w node-pty` scopes the rebuild to just that module (faster than rebuilding everything), and `-f`
+forces it. After this runs, the addon loads cleanly inside Electron. Forget it, and the app crashes on
+launch with an ABI error that looks scarier than it is.
+
+## Gotcha 2 — The macOS PATH trap
+
+You ship the app, double-click it, and your terminal can't find `claude` — or `node`, or `git`, or
+whatever you installed with nvm, asdf, or Homebrew. Run the same command in a real terminal and it
+works fine. What gives?
+
+On macOS, an app launched from the **GUI** (Finder, Dock) doesn't inherit your interactive shell's
+environment. Your `PATH` additions live in `.zshrc`/`.zprofile`, which a login shell reads — but the
+GUI process never started a login shell, so it gets a bare system `PATH` that's missing every
+user-installed tool.
+
+There are two halves to fixing this:
+
+**Resolve the command's full path.** Don't trust a bare command name to be found. Ask an interactive
+login shell where it lives, then fall back to common install locations:
+
+```ts
+function resolveCommand(command: string): string {
+ if (command.includes('/')) return command; // already absolute
+ // Ask the user's login shell — picks up nvm/asdf/brew.
+ const res = spawnSync(process.env.SHELL ?? '/bin/zsh', ['-ilc', `which ${command}`], {
+ encoding: 'utf8', timeout: 3000
+ });
+ const found = res.stdout.trim().split('\n').pop();
+ if (found && existsSync(found)) return found;
+ // Fall back to known locations.
+ for (const c of [
+ `/opt/homebrew/bin/${command}`,
+ `/usr/local/bin/${command}`,
+ `${process.env.HOME}/.local/bin/${command}`
+ ]) if (existsSync(c)) return c;
+ return command; // last resort — let it ENOENT
+}
+```
+
+The `-ilc` flags matter: `-i` interactive, `-l` login, `-c` run a command — that combination loads the
+same startup files your terminal does, so `which` finds what you'd expect.
+
+**Give the child a real PATH too.** Even with the binary resolved, the spawned shell needs a full
+`PATH` so *its* subprocesses resolve (the `claude` session that shells out to `git`, say). Compute the
+login shell's `PATH` once and pass it into the PTY's env:
+
+```ts
+const userPath = spawnSync(process.env.SHELL ?? '/bin/zsh', ['-ilc', 'echo -n "$PATH"'],
+ { encoding: 'utf8', timeout: 3000 }).stdout.trim() || process.env.PATH;
+```
+
+Skip this and your terminal will run, but anything it tries to launch will mysteriously not be found.
+
+## Gotcha 3 — Streaming over IPC without crashing on quit
+
+In Electron, the PTY lives in the **main** process and the UI lives in the **renderer**. So PTY output
+has to cross the process boundary over IPC. The pattern is straightforward — forward each `onData`
+chunk on a per-session channel:
+
+```ts
+proc.onData((data) => webContents.send(`pty:data:${id}`, data));
+proc.onExit(({ exitCode, signal }) => webContents.send(`pty:exit:${id}`, { exitCode, signal }));
+```
+
+But there's a teardown hazard that produces an ugly crash dialog. During app quit, killing a PTY fires
+`onExit` **asynchronously**. By the time that callback runs, the window may already be destroyed — and
+calling `.send()` on a destroyed `webContents` throws `"Object has been destroyed"`, which surfaces as
+a main-process crash. The guard is simple but essential: check the target is alive before every send.
+
+```ts
+function safeSend(channel: string, payload: unknown) {
+ const wc = this.webContents;
+ if (!wc || wc.isDestroyed()) return; // window torn down — drop it
+ try { wc.send(channel, payload); } catch { /* raced during teardown */ }
+}
+```
+
+Route every PTY-to-renderer message through that, and quitting the app is clean instead of a crash
+report.
+
+## Managing many sessions
+
+A real app runs more than one terminal, so wrap all of this in a manager keyed by session id —
+`spawn`, `write`, `resize`, `kill`, `list`, `killAll`. Two details pay off at scale:
+
+- **Resize is a real operation.** When the UI panel changes size, recompute cols/rows and call
+ `proc.resize(cols, rows)`, or full-screen TUIs will wrap wrong. The renderer side of this — measuring
+ the grid and writing keystrokes back — is its own craft, covered in
+ [building a terminal UI with xterm.js and node-pty](/blog/building-a-terminal-ui-xterm-node-pty/).
+- **Clean up on exit.** Remove a session from your map in `onExit`, and on app quit kill everything so
+ you don't leak child processes.
+
+## Why this matters for an agent harness
+
+Everything above is in service of a simple idea: if your "agents" are real `claude` CLI sessions, they
+deserve real terminals. A PTY makes each agent byte-for-byte authentic — same colors, same prompts,
+same behavior as if you'd typed `claude` yourself. That authenticity is the whole premise of a
+[multi-agent harness](https://munderdiffl.in/#what): you're not reimplementing the agent, you're
+running the genuine article and coordinating many of them. And because every session is a real process,
+the same single-writer discipline that keeps their shared state safe — see
+[the single-committer git pattern](/blog/single-committer-git-pattern/) — applies cleanly on top.
+
+## FAQ
+
+**Does node-pty work on Windows?** Yes — it uses the ConPTY API on modern Windows (and winpty as a
+fallback on older versions). The PATH gotcha is macOS-specific; the native-rebuild gotcha applies
+everywhere.
+
+**Can I avoid the native addon entirely?** Not if you want a true TTY. Pure-JS "terminals" that pipe
+`child_process` hit exactly the non-TTY problems described up top. node-pty exists because a real
+pseudo-terminal needs a kernel-level allocation.
+
+---
+
+Munder Difflin runs every Claude Code agent in a real node-pty terminal — authentic shells, streamed
+to a live UI, coordinated as a hive. [Download Munder Difflin](https://munderdiffl.in/#install) to see
+real terminals driving real agents; it's free and open source.
diff --git a/blog/src/posts/single-committer-git-pattern.md b/blog/src/posts/single-committer-git-pattern.md
new file mode 100644
index 00000000..dc2acd8b
--- /dev/null
+++ b/blog/src/posts/single-committer-git-pattern.md
@@ -0,0 +1,165 @@
+---
+title: "The Single-Committer Pattern: Multi-Agent Git Without Corruption"
+description: "Parallel agents corrupt a repo with git index.lock races. The single-committer pattern — agents write files, one process commits — fixes concurrent git writes for good."
+date: 2026-06-02
+category: internals
+categoryLabel: Internals
+type: Technical
+primaryKeyword: "single committer git multi agent"
+secondaryKeywords: ["git index.lock", "multi-agent git", "concurrent git writes"]
+tags: ["Internals", "Git", "Multi-Agent", "Concurrency"]
+author:
+ name: Chaitanya Giri
+ initials: CG
+faq:
+ - q: "What causes git index.lock errors with multiple agents?"
+ a: "Git takes an exclusive lock on .git/index while staging or committing. If two processes run git at the same time, the second finds the lock held and fails — or worse, a crashed process leaves a stale lock behind that blocks every future commit."
+ - q: "How do you let many agents share one git repo safely?"
+ a: "Don't let the agents call git at all. Agents write plain files; a single coordinating process owns every commit, serializing them. Concurrency on the repo drops to one writer, so the lock is never contended."
+ - q: "Do agents lose anything by not running git themselves?"
+ a: "No. They still create, edit, and delete files freely. They just don't stage or commit — that's delegated to one committer, which turns git into a clean, serialized audit log of the team's work."
+---
+
+<div class="callout tldr"><span class="ic">TL;DR</span><p>Run several agents against one git repo and
+they'll race on <code>.git/index.lock</code>, producing failed and half-staged commits. The
+<strong>single-committer pattern</strong> fixes it: <strong>agents only write plain files; one process
+owns every commit</strong>, serialized, with retry-and-backoff and stale-lock recovery. Concurrency on
+the repo drops to exactly one writer, so corruption becomes impossible — and git turns into a tidy
+audit log of everything the team did.</p></div>
+
+If you've ever pointed two automated agents at the same repository, you've probably met this error:
+
+```
+fatal: Unable to create '/path/.git/index.lock': File exists.
+```
+
+It looks transient. It isn't a fluke — it's git telling you that two processes tried to write its index
+at once. As you add agents, it goes from occasional to constant, and a crashed agent can leave a stale
+lock that blocks *every* future commit. This post explains why it happens and the pattern that ends it.
+
+## Why concurrent git writes corrupt
+
+Git is not designed for concurrent writers. When you stage or commit, git takes an **exclusive lock**
+by creating `.git/index.lock`; it does its work against that file, then atomically renames it over
+`.git/index` and releases the lock. The lock guarantees that only one operation mutates the index at a
+time.
+
+That's fine for a human typing one command. It falls apart with parallel agents:
+
+- **Contention.** Two agents commit at the same instant. One gets the lock; the other finds
+ `index.lock` already present and fails outright.
+- **Half-applied state.** Interleaved `git add`/`git commit` from different processes can stage a
+ partial set of changes — a commit that doesn't reflect any single agent's intent.
+- **Stale locks.** An agent crashes (or is killed) mid-commit and never removes its `index.lock`. Now
+ the lock file is orphaned, and every subsequent commit — by anyone — fails until someone deletes it
+ by hand.
+
+You can't "be careful" your way out of this. Two well-behaved agents that simply finish at the same
+second will collide. The guarantee has to come from the design, not the agents' manners.
+
+## The pattern: one writer for git
+
+The single-committer pattern is exactly what it sounds like: **only one process is ever allowed to run
+git.** Everything else is downstream of that rule.
+
+- **Agents write plain files.** They create, edit, and delete files in their workspaces freely. They
+ do *not* run `git add`, `git commit`, or anything else that touches the index. As far as the agents
+ are concerned, git doesn't exist.
+- **One coordinating process commits.** A single committer watches the shared state, stages changes,
+ and commits them — one at a time, in order. Because it's the only thing calling git, `index.lock` is
+ never contended. There is no second writer to race with.
+
+This collapses a hard concurrency problem into a trivial one. The repo has many *readers* and exactly
+one *writer*, which is the configuration git is perfectly happy with.
+
+## Making the single committer bulletproof
+
+"One committer" removes contention between agents, but the committer still has to handle the messy
+real world: a previous run that died, an occasional transient failure. A production-grade committer
+does three things.
+
+### 1. Retry with backoff
+
+Even a lone committer can hit a lock left by something else (a stray `git` you ran in another terminal,
+a hook). So each commit attempt is wrapped in a small retry loop: try to commit; if it fails on a lock,
+wait a short, growing interval and try again. A handful of attempts with increasing backoff absorbs any
+brief contention without surfacing an error to the user.
+
+```text
+for attempt in 0..5:
+ clear stale lock if present
+ git add -A
+ git commit -m <message>
+ → success? return
+ → "nothing to commit"? return # not an error
+ → lock error? sleep 50ms * (attempt + 1); retry
+ → other failure? give up quietly; the next change retries
+```
+
+### 2. Stale-lock recovery
+
+A lock file that's been sitting untouched for a while almost certainly belongs to a dead process. The
+committer checks the lock's age before each attempt and, if it's older than a threshold (say, ten
+seconds with no modification), removes it. That single check is what turns "a crashed agent bricked our
+commits" into a non-event — the next commit cleans up and proceeds.
+
+### 3. A deterministic git identity
+
+Because the committer commits on behalf of the whole team, it uses a fixed identity and disables
+signing, so commits never block on a GPG prompt or a missing `user.name`:
+
+```bash
+git -c commit.gpgsign=false -c user.name=Hive -c user.email=hive@local commit -m "…"
+```
+
+Now every coordination step is a clean, attributable commit, and nothing can hang waiting for
+interactive input.
+
+## The bonus: git becomes an audit log
+
+Here's the part that turns a workaround into an asset. Once one process owns every commit, the repo
+stops being a liability and becomes a **serialized history of everything the team did**. Each routed
+message, each task assignment, each memory update lands as its own commit, in order. When a multi-agent
+run goes sideways, you don't guess — you read the log.
+
+That pairs naturally with the messaging layer: agents coordinate through files (see
+[atomic file mailboxes](/blog/atomic-file-mailboxes-for-agents/)), and the single committer commits
+those file changes as they happen. The same single-writer discipline runs through both — it's the
+backbone of [coordinating AI coding agents](/blog/coordinating-ai-coding-agents/) without collisions.
+
+## What about the user's own repo?
+
+A fair question: if agents are editing your *actual* code repository, who commits *that*? The
+single-committer pattern is about the **coordination** repo — the shared state the agents use to talk,
+remember, and track tasks. Your source repo is separate, and you stay in control of its commits the way
+you always have (or you delegate them deliberately to one agent with that role). The point is that the
+machinery the agents rely on to cooperate never corrupts itself, no matter how many of them are running.
+
+## When you need this
+
+You need the single-committer pattern the moment **more than one automated process** shares a git repo:
+
+- multiple coding agents in the same project,
+- an agent plus a background job that both commit,
+- any "swarm" or "hive" where coordination state lives in git.
+
+If it's just you and one agent taking turns, you'll rarely see a lock. Add a second concurrent writer
+and the races begin — which is precisely when this pattern stops being optional.
+
+## FAQ
+
+**Why not use git worktrees to isolate each agent?** Worktrees give each agent its own working
+directory, which helps with *file* isolation — but each worktree still has its own index, and shared
+refs can still contend. Worktrees and single-committer solve different halves of the problem; see
+[git worktrees vs a hive](/blog/claude-code-git-worktrees-vs-hive/) for when each applies.
+
+**Isn't a lock just a retry-until-it-works situation?** Retrying helps with transient contention, but
+it does nothing for a *stale* lock from a dead process — that one never clears on its own. You need the
+age-based cleanup, not just retries.
+
+---
+
+Munder Difflin uses the single-committer pattern for its entire coordination layer: agents write
+files, one process commits with retry and stale-lock recovery, and the repo stays a clean audit log.
+[Download Munder Difflin](https://munderdiffl.in/#install) to run a hive of Claude Code agents that
+never corrupt their own state; it's free and open source.