Skip to content
Back to search

mcp_agent_mail_rust

Rust MCP server for multi-agent coordination: 34 tools, Git-backed archive, SQLite indexing, advisory file locks, and an interactive TUI console

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Dicklesworthstone/mcp_agent_mail_rust with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Dicklesworthstone/mcp_agent_mail_rust'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/dicklesworthstone--mcp-agent-mail-rust/badge.svg)](/listings/dicklesworthstone--mcp-agent-mail-rust)

HTML

<a href="/listings/dicklesworthstone--mcp-agent-mail-rust"><img src="/api/listings/dicklesworthstone--mcp-agent-mail-rust/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

One-Liner (recommended)

curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/mcp_agent_mail_rust/main/install.sh?$(date +%s)" | bash

Downloads the right binary for your platform, installs to `~/.local/bin`, optionally updates your `PATH`, and auto-configures detected Codex CLI configs for HTTP MCP URL mode. Downloaded release archives are verified **before extraction by default**. The requested version is normalized to the release tag `vX.Y.Z` (or `vX.Y.Z-prerelease`), and the trust model depends on the release generation:

- **Releases v0.3.31 and later** (the current model): releases are built and published by the maintainer's own release infrastructure rather than GitHub Actions, and every release ships a `SHA256SUMS` manifest plus a detached **minisign** signature (`SHA256SUMS.minisig`) made with the maintainer-held release key (id `1BBD79B28BF718D0`; the public key is pinned inside the installer). The installer verifies the signature over the exact manifest bytes with `minisign`, then verifies the archive's SHA-256 against the authenticated manifest. A missing `minisign` executable, manifest, signature, or checksum entry aborts the install; `cosign` is not required or consulted for these releases. This replaced the earlier keyless GitHub-Actions Sigstore requirement, which had become unsatisfiable once releases stopped being built by Actions — the trust anchor is now a key the maintainer controls (the same model as the maintainer's other released tools), and verification remains fail-closed. `am self-update` applies the same model with a built-in minisign verifier (the release public key is embedded in the binary; no `minisign` executable is needed) and refuses unsigned or tampered manifests. See [SECURITY.md](SECURITY.md#release-trust-model). - **Releases before v0.3.31** (legacy): the installer requires a SHA-256 witness plus a non-empty modern Sigstore bundle that `cosign` validates against the literal workflow identity `https://github.com/Dicklesworthstone/mcp_agent_mail_rust/.github/workflows/dist.yml@refs/tags/<requested-tag>` and OIDC issuer `https://token.actions.githubusercontent.com`, so a valid archive and bundle from any other tag are rejected. A stable `cosign` **v3.1.3 or newer in the v3 line** must be on `PATH`; older versions are rejected because of [GHSA-fx35-mq7g-6g98](https://github.com/sigstore/cosign/security/advisories/GHSA-fx35-mq7g-6g98), and v4 is not accepted until its verifier contract is reviewed. Verification forces the modern bundle parser and ignores caller-supplied `SIGSTORE_ROOT_FILE`, `SIGSTORE_REKOR_PUBLIC_KEY`, and `SIGSTORE_CT_LOG_PUBLIC_KEY_FILE` overrides.

In both models, a missing checksum, SHA-256 implementation, signature witness, or required verifier executable—and any malformed or mismatched signature evidence—aborts the install.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 2,451 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # MCP Agent Mail (Rust)
  2. <div align="center">
  3. <img src="docs/assets/am_illustration.webp" alt="MCP Agent Mail - A mail-like coordination layer for AI coding agents">
  4. </div>
  5. <div align="center">
  6. [![License: MIT+Rider](https://img.shields.io/badge/License-MIT%2BOpenAI%2FAnthropic%20Rider-yellow.svg)](./LICENSE)
  7. </div>
  8. > "It's like Gmail for your coding agents!"
  9. A mail-like coordination layer for AI coding agents, exposed as an MCP server with 45 tools and 25 resources, Git-backed archive, SQLite indexing, an interactive 16-screen TUI, a server-rendered web UI, and an agent-first robot CLI. The Rust rewrite of the [original Python project](https://github.com/Dicklesworthstone/mcp_agent_mail) (1,700+ stars).
  10. **Supported agents:** [Claude Code](https://claude.ai/code), [Codex CLI](https://github.com/openai/codex), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [Oh My Pi (OMP)](https://omp.sh), [GitHub Copilot CLI](https://docs.github.com/en/copilot), and any MCP-compatible client.
  11. Watch the [23-minute walkthrough](https://youtu.be/68VVcqMEDrs) to see seven AI coding agents send over 1,000 messages to each other while implementing a development plan over two days.
  12. <div align="center">
  13. <h3>Quick Install</h3>
  14. ```bash
  15. curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/mcp_agent_mail_rust/main/install.sh?$(date +%s)" | bash
  16. ```
  17. <p><em>Works on Linux and macOS (x86_64 and aarch64). Auto-detects your platform, downloads the right binary, and configures detected coding agents for HTTP MCP.</em></p>
  18. <p><em>Needs <code>minisign</code> on <code>PATH</code> to verify the release (and <code>xz</code> on minimal Linux images); see <a href="#one-liner-recommended">One-Liner</a>.</em></p>
  19. </div>
  20. ---
  21. ## Table of Contents
  22. - [TL;DR](#tldr)
  23. - [Why This Exists](#why-this-exists)
  24. - [What People Are Saying](#what-people-are-saying)
  25. - [Design Philosophy](#design-philosophy)
  26. - [Rust vs. Python: Stress Test Results](#rust-vs-python-stress-test-results)
  27. - [Installation](#installation)
  28. - [Quick Start](#quick-start)
  29. - [Agent Configuration](#agent-configuration)
  30. - [Server Modes](#server-modes)
  31. - [Operator CLI Surface](#operator-cli-surface)
  32. - [The 45 MCP Tools](#the-45-mcp-tools)
  33. - [TUI Operations Console](#tui-operations-console)
  34. - [Robot Mode (`am robot`)](#robot-mode-am-robot)
  35. - [File Reservations](#file-reservations-for-multi-agent-editing)
  36. - [Multi-Agent Coordination Workflows](#multi-agent-coordination-workflows)
  37. - [Web UI](#web-ui)
  38. - [Deployment Validation](#deployment-validation)
  39. - [Configuration](#configuration)
  40. - [Architecture](#architecture)
  41. - [ATC Learning Implementation Map](#atc-learning-implementation-map)
  42. - [Core Data Model](#core-data-model)
  43. - [How the System Works](#how-the-system-works)
  44. - [Search Architecture](#search-architecture)
  45. - [Coordination Algorithms and Safety Invariants](#coordination-algorithms-and-safety-invariants)
  46. - [Consistency and Recovery Model](#consistency-and-recovery-model)
  47. - [Comparison vs. Alternatives](#comparison-vs-alternatives)
  48. - [Development](#development)
  49. - [Performance and Benchmarking](#performance-and-benchmarking)
  50. - [Mailbox Diagnostics (`am doctor`)](#mailbox-diagnostics-am-doctor)
  51. - [Troubleshooting](#troubleshooting)
  52. - [Limitations](#limitations)
  53. - [FAQ](#faq)
  54. - [Appendix: Protocol Transcript](#appendix-protocol-transcript)
  55. - [Appendix: TUI vs. Web vs. Robot](#appendix-tui-vs-web-vs-robot)
  56. - [Documentation](#documentation)
  57. - [About Contributions](#about-contributions)
  58. - [License](#license)
  59. ---
  60. ## TL;DR
  61. **The Problem**: Modern projects often run multiple coding agents at once (backend, frontend, scripts, infra). Without a shared coordination fabric, agents overwrite each other's edits, miss critical context from parallel workstreams, and require humans to relay messages across tools and teams.
  62. **The Solution**: Agent Mail gives every coding agent a persistent identity (e.g., `GreenCastle`), an inbox/outbox, searchable threaded conversations, and advisory file reservations (leases) to signal editing intent. Everything is backed by Git for human-auditable artifacts and SQLite for fast indexing and search.
  63. ### Why Use Agent Mail?
  64. | Feature | What It Does |
  65. |---------|--------------|
  66. | **Advisory File Reservations** | Agents declare exclusive or shared leases on file globs before editing, preventing conflicts with a pre-commit guard |
  67. | **Asynchronous Messaging** | Threaded inbox/outbox with subjects, CC/BCC, acknowledgments, and importance levels |
  68. | **Token-Efficient** | Messages stored in a per-project archive, not in agent context windows |
  69. | **25 MCP Resources** | Read-only inbox, thread, reservation, tooling, identity, and attention views for cheap lookups |
  70. | **45 MCP Tools** | Infrastructure, identity, messaging, contacts, reservations, search, macros, product bus, and build slots |
  71. | **16-Screen TUI** | Live operator cockpit for messages, threads, agents, search, reservations, metrics, health, analytics, attachments, archive browsing, and ATC |
  72. | **Web UI** | Server-rendered `/mail/` routes for human oversight, unified inbox review, search, attachments, and overseer messaging |
  73. | **Robot Mode** | 19 agent-optimized CLI subcommands with `toon`/`json` output (`md` for thread and message views) for non-interactive workflows |
  74. | **Git-Backed Archive** | Every message, reservation, and agent profile stored as files in per-project Git repos |
  75. | **Hybrid Search** | Portable lexical Search V3 uses the local Tantivy bridge. Optional FrankenSearch integration supplies semantic and hybrid routing in builds with the `hybrid` feature and the runtime opt-in `AM_SEARCH_SEMANTIC_ENABLED=true`. Without both, every query runs lexical. |
  76. | **Pre-Commit Guard** | Git hook that blocks commits touching files reserved by other agents |
  77. | **Dual-Mode Interface** | MCP server (`mcp-agent-mail`) and operator CLI (`am`) share tools but enforce strict surface separation |
  78. ### Quick Example
  79. ```bash
  80. # Start the server (the installer already configured your detected coding agents;
  81. # `am setup run` re-runs that setup at any time)
  82. am
  83. # That's it. Server starts on 127.0.0.1:8765 with the interactive TUI.
  84. # Agents coordinate through MCP tools:
  85. # ensure_project(human_key="/abs/path")
  86. # register_agent(project_key="/abs/path", program="claude-code", model="opus-4.6")
  87. # file_reservation_paths(project_key="/abs/path", agent_name="BlueLake", paths=["src/**"], ttl_seconds=3600, exclusive=true)
  88. # send_message(project_key="/abs/path", sender_name="BlueLake", to=["GreenCastle"], subject="Starting refactor", body_md="Taking src/**", thread_id="FEAT-123")
  89. # fetch_inbox(project_key="/abs/path", agent_name="BlueLake")
  90. # Or use the robot CLI for non-interactive agent workflows:
  91. am robot status --project /abs/path --agent BlueLake
  92. am robot inbox --project /abs/path --agent BlueLake --urgent --format json
  93. am robot reservations --project /abs/path --agent BlueLake --conflicts
  94. ```
  95. ### What Agent Conversations Look Like
  96. Example exchange between two agents coordinating a refactor:
  97. ```
  98. ┌──────────────────────────────────────────────────────────────────────────────┐
  99. │ Thread: FEAT-123 - Auth module refactor │
  100. ├──────────────────────────────────────────────────────────────────────────────┤
  101. │ │
  102. │ ┌──────────────────────────────────────────────────────────────────────────┐ │
  103. │ │ GreenCastle -> BlueLake 2026-02-16 10:03 │ │
  104. │ │ Subject: Starting auth refactor │ │
  105. │ ├──────────────────────────────────────────────────────────────────────────┤ │
  106. │ │ I'm reserving src/auth/** for the next hour. Can you focus on the API │ │
  107. │ │ tests in tests/api/** instead? │ │
  108. │ │ [ack_required: true] │ │
  109. │ └──────────────────────────────────────────────────────────────────────────┘ │
  110. │ │
  111. │ ┌──────────────────────────────────────────────────────────────────────────┐ │
  112. │ │ BlueLake -> GreenCastle 2026-02-16 10:04 │ │
  113. │ │ Subject: Re: Starting auth refactor │ │
  114. │ ├──────────────────────────────────────────────────────────────────────────┤ │
  115. │ │ Confirmed. Releasing my reservation on src/auth/** and taking │ │
  116. │ │ tests/api/** exclusively. Will sync when I hit the auth middleware │ │
  117. │ │ boundary. │ │
  118. │ │ [ack: OK] │ │
  119. │ └──────────────────────────────────────────────────────────────────────────┘ │
  120. │ │
  121. │ ┌──────────────────────────────────────────────────────────────────────────┐ │
  122. │ │ BlueLake -> GreenCastle 2026-02-16 10:31 │ │
  123. │ │ Subject: Re: Starting auth refactor │ │
  124. │ ├──────────────────────────────────────────────────────────────────────────┤ │
  125. │ │ Found a broken assertion in tests/api/auth_test.rs:142 -- the expected │ │
  126. │ │ token format changed. Heads up if you're touching the JWT issuer. │ │
  127. │ └──────────────────────────────────────────────────────────────────────────┘ │
  128. │ │
  129. │ ┌──────────────────────────────────────────────────────────────────────────┐ │
  130. │ │ GreenCastle -> BlueLake 2026-02-16 10:33 │ │
  131. │ │ Subject: Re: Starting auth refactor │ │
  132. │ ├──────────────────────────────────────────────────────────────────────────┤ │
  133. │ │ Good catch. I just changed the claims struct. Updated the test fixture │ │
  134. │ │ in my commit. Releasing src/auth/** now -- all yours if you need it. │ │
  135. │ └──────────────────────────────────────────────────────────────────────────┘ │
  136. │ │
  137. └──────────────────────────────────────────────────────────────────────────────┘
  138. ```
  139. No human relay needed. Agents negotiate file ownership, flag breaking changes in real time, and hand off work through structured, threaded messages stored in Git.
  140. ---
  141. ## Why This Exists
  142. Modern projects often run multiple coding agents at once (backend, frontend, scripts, infra). Without a shared coordination fabric, agents overwrite each other's edits, miss critical context from parallel workstreams, and require humans to relay messages across tools and teams.
  143. Agent Mail has been available since October 2025 and was designed around real multi-agent coding workloads across providers such as Claude Code, Codex CLI, and Gemini CLI. The adjacent [Beads](https://github.com/Dicklesworthstone/beads_rust) and [bv](https://github.com/Dicklesworthstone/beads_viewer) tools make it more useful as a full coordination stack: Beads tracks work, bv helps pick the right next work, and Agent Mail carries the coordination traffic.
  144. ### The Footguns Agent Mail Avoids
  145. **No "broadcast to all" mode.** Given the option, many agents will overuse broadcast-style messaging. That is the equivalent of default reply-all in email: lots of irrelevant noise and wasted context.
  146. **Carefully refined API ergonomics.** Bad MCP documentation and poor agent ergonomics quietly wreck reliability. Agent Mail's 45 tool definitions have gone through repeated real-world iteration so they work predictably without wasting tokens.
  147. **No git worktrees.** Worktrees can slow development velocity and create reconciliation debt when agents diverge. Agent Mail takes the opposite approach: keep agents in one shared space, surface conflicts quickly, and give them tools to coordinate through them.
  148. **Advisory file reservations instead of hard locks.** For this problem, advisory reservations fit better than hard locks. Agents can temporarily claim files while they work, reservations expire automatically, and stale claims can be reclaimed. That makes the system robust to crashed or reset agents; hard locks would not.
  149. **Semi-persistent identity.** An identity that can last for the duration of a discrete task (for the purpose of coordination), but one that can also vanish without a trace and not break things. You don't want ringleader agents whose death takes down the whole system. Agent Mail identities are memorable (e.g., `GreenCastle`), but ephemeral by design.
  150. **Graph-aware task selection.** If you have 200-500 tasks, you don't want agents randomly choosing them or wasting context communicating about what to do. There's usually a "right answer" for what each agent should work on, and that right answer comes from the dependency structure of the tasks. That's what [bv](https://github.com/Dicklesworthstone/beads_viewer) computes using graph theory, like a compass that tells each agent which direction will unlock the most work overall.
  151. ### What Agent Mail Gives You
  152. - **Prevents conflicts:** Explicit file reservations (leases) for files/globs prevent agents from overwriting each other
  153. - **Reduces human relay work:** Agents send messages directly to each other with threaded conversations, acknowledgments, and priority levels
  154. - **Keeps communication off the token budget:** Messages stored in per-project Git archive, not consuming agent context windows
  155. - **Offers quick reads:** `resource://inbox/{Agent}?project=<abs-path>`, `resource://thread/{id}?project=<abs-path>`, and 23 other MCP resources
  156. - **Provides full audit trails:** Every instruction, lease, message, and attachment is in Git for human review
  157. - **Scales across repos:** Frontend and backend agents in different repos coordinate through the product bus and contact system
  158. ### Typical Use Cases
  159. - Multiple agents splitting a large refactor across services while staying in sync
  160. - Frontend and backend agent teams coordinating thread-by-thread across repositories
  161. - Protecting critical migrations with exclusive file reservations and pre-commit guards
  162. - Searching and summarizing long technical discussions as threads evolve
  163. - Running agent swarms with [Beads](https://github.com/Dicklesworthstone/beads_rust) task tracking for dependency-aware work selection
  164. ### Productivity Math
  165. Parallel agent work changes the economics of supervision. One human operator can spend an hour steering several agents while those agents produce many hours of implementation work in parallel. The exact multiplier depends on the task and on how disciplined the workflow is, but the point is straightforward: coordination overhead matters, and Agent Mail is built to keep that overhead low.
  166. ---
  167. ## What People Are Saying
  168. > "Agent Mail and Beads feel like the first 'agent-native' tooling."
  169. > — [@jefftangx](https://x.com/jefftangx/status/1998100767698506047)
  170. > "Agent mail is a truly brain-melting experience the first time. Thanks for building it."
  171. > — [@quastora](https://x.com/quastora/status/2001130619481502160)
  172. > "Between Claude Code, Codex CLI, and Gemini; Beads; and Agent Mail — basically already 80% the way to the autonomous corporation. It blows my mind this all works now!"
  173. > — [@curious_vii](https://x.com/curious_vii/status/2000315148410695927)
  174. > "Use it with agent mail == holy grail."
  175. > — [@metapog](https://x.com/metapog/status/1995323125790089251)
  176. > "The only correct answer to this is mcp agent mail."
  177. > — [@skillcreatorai](https://x.com/skillcreatorai/status/2006099437144199479)
  178. > "GPT 5.2 suggesting beads + agent mail for agent co-ordination (of course, I am already using them)."
  179. > — [@jjpcodes](https://x.com/jjpcodes/status/1999778297488826542)
  180. ---
  181. ## Design Philosophy
  182. **Mail metaphor, not chat.** Agents send discrete messages with subjects, recipients, and thread IDs. Work coordination is structured communication with clear intent, not a firehose. Imagine if your email system at work defaulted to reply-all every time; that's what chat-based coordination does, and it burns context fast.
  183. **SQLite for live state, Git for the durable ledger.** The accepted write path mutates SQLite first so inboxes, resources, TUI, web, and robot views see one fresh operational state. The same write then emits human-readable message, profile, and reservation artifacts into the per-project Git archive for audit and recovery.
  184. **Advisory, not mandatory.** File reservations are advisory leases, not hard locks. The pre-commit guard enforces them at commit time, but agents can override if needed. Acquiring a reservation reports conflicts instead of waiting for another agent to release its lease. Reservations expire on a TTL; they do not prevent deadlocks in the storage or runtime layers.
  185. **Resilient to agent death.** Agents die all the time: context windows overflow, sessions crash, memory gets wiped. Any agent can vanish without breaking the system. No ringleader agents, no single points of failure. Semi-persistent identities exist for coordination but don't create hard dependencies.
  186. **Dual persistence.** Human-readable Markdown in Git for auditability; SQLite for live indexing plus Search V3 for fast lexical/semantic retrieval. Both stay in sync through the write pipeline.
  187. **Structured concurrency, no Tokio.** The entire async stack uses [asupersync](https://github.com/Dicklesworthstone/asupersync) with `Cx`-threaded structured concurrency. No orphan tasks, cancel-correct channels, and deterministic testing with virtual time.
  188. ---
  189. ## Rust vs. Python: Stress Test Results
  190. The Python implementation had three recurring failure modes under real multi-agent workloads: Git lock file contention from concurrent writes, SQLite pool exhaustion under sustained load, and cascading failures when many agents hit the server simultaneously. The Rust rewrite addresses these through batching, bounded pools, and backpressure. The measurements below are retained results from the original stress campaign, not a passing verdict for the current release candidate or a guarantee for every workload (the heavy multi-agent stress tests in `crates/mcp-agent-mail-storage/tests/stress_pipeline.rs` are marked `#[ignore]` for explicit `-- --ignored` stress runs and currently enforce a 120s release-host ceiling, measured at 38–47s after durable archive-fsync hardening).
  191. ### The 10-Test Gauntlet
  192. | Test | Result | Key Metrics |
  193. |------|--------|-------------|
  194. | 30-agent message pipeline | PASS | 150/150 success, p99=6.8s, 0 errors |
  195. | 10-project concurrent ops | PASS | 150/150 success, 0 errors |
  196. | Commit coalescer batching | PASS | 9.1x batching ratio (100 writes &rarr; 11 commits) |
  197. | Stale git lock recovery | PASS | Lock detected, cleaned, writes resumed |
  198. | Mixed reservations + messages | PASS | 80+80 ops, 0 errors |
  199. | WBQ saturation | PASS | 2000/2000 enqueued, 0 errors, 0 fallbacks |
  200. | Pool exhaustion (60 threads, pool=15) | PASS | 600/600 success, 0 timeouts, 24 ops/sec |
  201. | Sustained 30s mixed workload | PASS | 1494 ops, ~49 RPS, p99=2.6s, 0 errors |
  202. | Thundering herd (50 threads, 1 agent) | PASS | All 50 got same ID, 0 errors |
  203. | Inbox reads during message storm | PASS | 150 sends + 300 reads, 0 errors |
  204. ### Python Problem &rarr; Rust Fix
  205. | Python Failure Mode | What the Rust Tests Exercise | Result |
  206. |---------------------|------------------------------|--------|
  207. | **Git lock file contention** | Commit coalescer batching (100 concurrent writes &rarr; 11 commits, 9.1x reduction), stale lock recovery, multi-project isolation | 0 lock errors |
  208. | **SQLite pool exhaustion** | 60 threads on pool of 15, sustained 50 RPS for 30s, thundering herd (50 threads &rarr; 1 agent) | 0 timeouts, 0 DB errors |
  209. | **Overloading with many agents** | 30 agents &times; 5 messages, 10 projects &times; 5 agents, 2000 WBQ operations, mixed reservation+message workload | 0 errors across all |
  210. ### What Makes the Difference
  211. - **Fewer Git lock acquisitions.** The commit coalescer batches rapid-fire writes into fewer git commits (9.1x reduction in the recorded run). Git plumbing commits avoid `index.lock` in the normal archive path; other Git operations can still contend.
  212. - **Pool exhaustion handled gracefully.** Even with 4x more threads than pool connections (60 vs 15), all 600 operations succeeded with 0 timeouts. WAL mode + a bounded 20s `busy_timeout` lets writers queue rather than fail (and give up before the 30s client deadline).
  213. - **Stale lock recovery works.** Crashed-process lock files are detected via PID checking and cleaned up automatically, so a dead agent never holds the archive hostage.
  214. - **Write-behind queue backpressure is clean.** 2000 rapid-fire enqueues from 20 threads &mdash; all accepted with 0 fallbacks or errors.
  215. - **Read/write concurrency is solid.** Concurrent inbox reads and message writes produce 0 errors. WAL mode allows unlimited readers alongside writers.
  216. The stress tests live in `crates/mcp-agent-mail-storage/tests/stress_pipeline.rs` (Rust unit tests targeting the DB+Git pipeline) and `tests/e2e/test_stress_load.sh` (HTTP E2E tests hammering a live server through the full network&rarr;server&rarr;DB&rarr;git pipeline).
  217. ---
  218. ## Installation
  219. ### One-Liner (recommended)
  220. ```bash
  221. curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/mcp_agent_mail_rust/main/install.sh?$(date +%s)" | bash
  222. ```
  223. **Prerequisites:** the installer verifies the release with `minisign` and refuses to install without it, and minimal Linux images also lack `xz`. macOS: `brew install minisign`. Debian 12+ and Ubuntu 24.04+: `apt install minisign xz-utils`. Ubuntu 22.04 and Debian 10 have no `minisign` package: use the static binary from the [minisign releases](https://github.com/jedisct1/minisign/releases).
  224. Downloads the right binary for your platform, installs to `~/.local/bin`, optionally updates your `PATH`, and auto-configures detected Codex CLI configs for HTTP MCP URL mode. Downloaded release archives are verified **before extraction by default**. The requested version is normalized to the release tag `vX.Y.Z` (or `vX.Y.Z-prerelease`), and the trust model depends on the release generation:
  225. - **Releases v0.3.31 and later** (the current model): releases are built and published by the maintainer's own release infrastructure rather than GitHub Actions, and every release ships a `SHA256SUMS` manifest plus a detached **minisign** signature (`SHA256SUMS.minisig`) made with the maintainer-held release key (id `1BBD79B28BF718D0`; the public key is pinned inside the installer). The installer verifies the signature over the exact manifest bytes with `minisign`, then verifies the archive's SHA-256 against the authenticated manifest. A missing `minisign` executable, manifest, signature, or checksum entry aborts the install; `cosign` is not required or consulted for these releases. This replaced the earlier keyless GitHub-Actions Sigstore requirement, which had become unsatisfiable once releases stopped being built by Actions — the trust anchor is now a key the maintainer controls (the same model as the maintainer's other released tools), and verification remains fail-closed. `am self-update` applies the same model with a built-in minisign verifier (the release public key is embedded in the binary; no `minisign` executable is needed) and refuses unsigned or tampered manifests. See [SECURITY.md](SECURITY.md#release-trust-model).
  226. - **Releases before v0.3.31** (legacy): the installer requires a SHA-256 witness plus a non-empty modern Sigstore bundle that `cosign` validates against the literal workflow identity `https://github.com/Dicklesworthstone/mcp_agent_mail_rust/.github/workflows/dist.yml@refs/tags/<requested-tag>` and OIDC issuer `https://token.actions.githubusercontent.com`, so a valid archive and bundle from any other tag are rejected. A stable `cosign` **v3.1.3 or newer in the v3 line** must be on `PATH`; older versions are rejected because of [GHSA-fx35-mq7g-6g98](https://github.com/sigstore/cosign/security/advisories/GHSA-fx35-mq7g-6g98), and v4 is not accepted until its verifier contract is reviewed. Verification forces the modern bundle parser and ignores caller-supplied `SIGSTORE_ROOT_FILE`, `SIGSTORE_REKOR_PUBLIC_KEY`, and `SIGSTORE_CT_LOG_PUBLIC_KEY_FILE` overrides.
  227. In both models, a missing checksum, SHA-256 implementation, signature witness, or required verifier executable—and any malformed or mismatched signature evidence—aborts the install.
  228. Options: `--version vX.Y.Z`, `--dest DIR`, `--system` (installs to `/usr/local/bin`), `--from-source`, `--verify` (run an additional post-install self-test), `--no-verify` (**unsafe** explicit escape that skips the checksum and signature checks), `--easy-mode` (auto-update PATH), `--force`, `--no-service` (never install/modify/restart the background service; also implied automatically by a non-default `--dest`), `--uninstall`, `--yes`, `--purge`. **`--no-verify` allows unauthenticated downloaded binaries to execute during mandatory version probes before installation; malicious archive bytes can therefore run arbitrary code as the installer user.** Archive verification applies to downloaded release archives, not source builds. Every downloaded archive must contain the two expected flat, non-empty regular-file binaries and may also contain flat regular-file `README.md` and `LICENSE` entries; duplicate or other members are rejected. Both staged binaries and both installed binaries must report the exact requested version. Those member/version checks are mandatory even with `--no-verify`; the flag also does not disable the optional broader `--verify` post-install self-test. A failed archive download never silently changes into a source build. Explicit `--from-source` checks out the exact requested tag, uses its Cargo.lock for `cargo build --locked`, and subjects the staged and installed pair to the same exact-version and byte-preserving transactional replacement gates.
  229. A successful source install prints the path of a mode-private `source-receipt` retained inside its committed transaction-history directory. The hash-witnessed receipt binds the normalized release tag, exact Agent Mail commit, Cargo.lock SHA-256, and both installed binary SHA-256 digests. Cargo resolves external dependencies from the tagged lockfile; the installer verifies that its digest stays unchanged through the locked build. Source installation does not fetch unused sibling repositories. Tags with external path dependencies are refused before compilation. Interrupted or rolled-back transactions retain their evidence under an explicitly non-committed history name and are never reported as installed source provenance.
  230. Source builds also require working Python 3 or Perl with `JSON::PP` to verify dependency metadata. Every local path dependency must resolve inside the tagged checkout; an external path or symlink escape is refused before compilation. Registry and Git dependencies remain governed by Cargo.lock.
  231. ### Windows One-Liner (PowerShell)
  232. ```powershell
  233. iwr -useb "https://raw.githubusercontent.com/Dicklesworthstone/mcp_agent_mail_rust/main/install.ps1?$(Get-Random)" | iex
  234. ```
  235. PowerShell enforces the same per-release trust contract before `Expand-Archive`: for releases v0.3.31 and later it verifies the minisign-signed `SHA256SUMS` manifest with the same pinned maintainer key (a `minisign` executable on `PATH` is required; `cosign` is not consulted), and for older releases it requires the same stable `cosign` v3.1.3-or-newer-in-v3 verifier, forces modern-bundle parsing, and isolates verification from the three custom Sigstore trust environment variables named above. The ZIP must contain `am.exe` and `mcp-agent-mail.exe`, with optional `README.md` and `LICENSE` entries. Every member must be a flat, non-empty regular file; duplicate or other members are rejected. The binaries' staged and post-install version lines must exactly match the requested release. Both executables are replaced under one per-destination installer mutex and rollback domain; backups remain until byte-for-byte installed-digest and version checks pass. Options: `-Version vX.Y.Z`, `-Dest PATH`, `-Force`, `-Verify` (explicitly request the already-default cryptographic checks), and `-NoVerify` (the **unsafe** escape that skips only those checksum and signature checks). Archive-member and exact-version checks still run with `-NoVerify`, which means unauthenticated downloaded executables run during version probes and may execute arbitrary code as the installer user.
  236. ### Container (Docker or Podman)
  237. Each release also publishes a `linux/amd64` + `linux/arm64` image to GHCR, tagged `vX.Y.Z`, `X.Y.Z`, `0.3` and `latest`:
  238. ```bash
  239. docker run -d --name agent-mail -p 127.0.0.1:8765:8765 \
  240. -e HTTP_BEARER_TOKEN="$(openssl rand -hex 32)" \
  241. -v agent-mail-data:/data/mailbox \
  242. ghcr.io/dicklesworthstone/mcp_agent_mail_rust:latest
  243. ```
  244. The image runs `mcp-agent-mail serve --no-tui` as the non-root `appuser`, serving MCP on port 8765 at `/mcp/`, with the whole mailbox (Git archive and SQLite) under `/data/mailbox`. Mount a volume there so mail survives replacing the container. Every request needs the token (`Authorization: Bearer <token>`); clients connect to `http://127.0.0.1:8765/mcp/` with it. Keep the published port on loopback unless remote agents should reach it. Docker's healthcheck polls `/health/liveness`. The image packages the release's Linux glibc binaries unchanged ([`Dockerfile.release`](Dockerfile.release)).
  245. For a local source image, resolve the revision before building and tag the
  246. result by both the source commit and its image ID. A rebuild that produces
  247. different bytes receives a different tag. Run these commands from the checkout
  248. with Docker Buildx installed. The selected commit must be fetchable from the
  249. project's GitHub repository.
  250. ```bash
  251. revision=$(git rev-parse --verify 'HEAD^{commit}')
  252. build_dir=$(mktemp -d)
  253. BUILDX_METADATA_PROVENANCE=max docker buildx build \
  254. --file Dockerfile --build-arg "AM_REF=$revision" \
  255. --load --iidfile "$build_dir/image-id" \
  256. --metadata-file "$build_dir/build-metadata.json" "$build_dir" &&
  257. image_id=$(cat "$build_dir/image-id") &&
  258. docker image tag "$image_id" "mcp-agent-mail-rust:source-$revision-${image_id#sha256:}"
  259. ```
  260. The resulting image exposes its commit in `org.opencontainers.image.revision`.
  261. It also records the Cargo lockfile and Rust toolchain file digests in
  262. `/usr/share/mcp-agent-mail/source-provenance`.
  263. `build-metadata.json` records the Dockerfile bytes and image config digest.
  264. [BuildKit metadata reference](https://docs.docker.com/reference/cli/docker/buildx/build/#metadata-file)
  265. ### From Source
  266. ```bash
  267. git clone https://github.com/Dicklesworthstone/mcp_agent_mail_rust
  268. cd mcp_agent_mail_rust
  269. ./install-local.sh # builds release, installs to ~/.local/bin
  270. # DEST=/usr/local/bin ./install-local.sh # custom destination
  271. ```
  272. The script resolves the correct Cargo target directory via `cargo metadata`, so the
  273. installed binary always matches the freshly-built artifact regardless of
  274. `CARGO_TARGET_DIR` overrides or workspace settings. Do **not** manually copy from
  275. `target/release/am` -- if `CARGO_TARGET_DIR` is set, that path may be stale.
  276. Requires Rust nightly (see `rust-toolchain.toml`). Current `main` records [FrankenSearch](https://github.com/Dicklesworthstone/frankensearch) 0.6.1 at revision `616c9a7a6bdada97d81f760808996911ba3be294` in `Cargo.toml` and `Cargo.lock`, aligned with `FRANKENSEARCH_COMMIT` in `.github/workflows/dist.yml`. This optional `hybrid` integration shares FastMCP's rustix 1.1.5 requirement and enables local Model2Vec and native reranking without FastEmbed or Tokio. Portable builds use the local Tantivy bridge for lexical Search V3 without enabling FrankenSearch integration.
  277. A manual build, source installation, and the release build recipes need no FrankenSearch, fast_cmaes, or Beads sibling checkout. Use `cargo build --locked` to retain the checked-in dependency graph. Source-install receipts record that lockfile's digest alongside the exact source commit and binary pair.
  278. The mailbox uses FrankenSQLite `=0.4.13` through SQLModel 0.5.1 on Asupersync 0.5.0. Only `fsqlite-core` is patched to [revision `e7ffeff4`](https://github.com/Dicklesworthstone/frankensqlite/commit/e7ffeff4eb1eda0a4d62d00bbe778d6103058e7f) to keep archive headers and rows on one transaction and recover bounded zero-filled WAL certificate tails, including false EOF boundaries; its package version is 0.4.14, while the other 19 engine packages remain registry 0.4.13.
  279. SQLModel's pool, core and FrankenSQLite driver are pinned to [revision `ca959f89`](https://github.com/Dicklesworthstone/sqlmodel_rust/commit/ca959f899b98fbea7af19e942e687dae9b71f258) for cancellation-safe waiter cleanup, cooperative acquisition deadlines and synchronous SQLite connection retirement; published 0.5.1 lacks these fixes. Synchronous driver work must still yield for a deadline to interrupt it.
  280. Asupersync is pinned to [revision `2946438a`](https://github.com/Dicklesworthstone/asupersync/commit/2946438a5d2bd164c9aee73a5ea079afe0c13907) so malformed HTTP request heads receive an error response before the connection closes; registry 0.5.0 silently drops those connections. This revision also includes the upstream resume-factory Send fix and keeps all consumers on one 0.5 runtime type graph. No sibling checkout is needed for these patches.
  281. `Cargo.lock` selects the FastMCP 0.13.0 family from crates.io, with `fastmcp-rust` imported as `fastmcp`. Beads discovery and queries use the installed `br` CLI; discovery runs its database-free config-path command, and Agent Mail no longer embeds a second storage engine. See [`UPGRADE_LOG.md`](UPGRADE_LOG.md) for engine qualification results. If persisted tool metrics have already bloated your mailbox, stop the server and follow the [offline recovery procedure](docs/RECOVERY_RUNBOOK.md) before running `am doctor vacuum --yes`; upgrading does not compact existing pages.
  282. ### Platforms
  283. | Platform | Architecture | Binary |
  284. |----------|-------------|--------|
  285. | Linux | x86_64 (static; the installer's default) | `mcp-agent-mail-x86_64-unknown-linux-musl` |
  286. | Linux | x86_64 (glibc 2.28+) | `mcp-agent-mail-x86_64-unknown-linux-gnu` |
  287. | Linux | aarch64 | `mcp-agent-mail-aarch64-unknown-linux-gnu` |
  288. | macOS | x86_64 | `mcp-agent-mail-x86_64-apple-darwin` |
  289. | macOS | Apple Silicon | `mcp-agent-mail-aarch64-apple-darwin` |
  290. | Windows | x86_64 | `mcp-agent-mail-x86_64-pc-windows-msvc.zip` |
  291. ---
  292. ## Quick Start
  293. ### 1. Start the server
  294. ```bash
  295. am
  296. ```
  297. Starts the HTTP server on `127.0.0.1:8765` with the interactive TUI. It leaves existing MCP client configuration untouched: the curl installer configures detected coding agents (Claude Code, Codex CLI, Gemini CLI, OMP, etc.), and `am setup run` (or `am serve-http --setup`) configures them explicitly afterwards.
  298. ### 2. Agents register and coordinate
  299. Once the server is running, agents use MCP tools to coordinate:
  300. Terminology note: `ensure_project` takes a `human_key`, which must be the absolute repo path. Most follow-on tools take `project_key`, which can be that same absolute path or the project's computed slug.
  301. ```
  302. # Register identity
  303. ensure_project(human_key="/abs/path/to/repo")
  304. register_agent(project_key="/abs/path/to/repo", program="claude-code", model="opus-4.6")
  305. # Reserve files before editing
  306. file_reservation_paths(project_key="/abs/path/to/repo", agent_name="GreenCastle", paths=["src/**"], ttl_seconds=3600, exclusive=true)
  307. # Send a message
  308. send_message(project_key="/abs/path/to/repo", sender_name="GreenCastle", to=["BlueLake"],
  309. subject="Starting auth refactor", body_md="Taking src/auth/**",
  310. thread_id="FEAT-123", ack_required=true)
  311. # Check inbox
  312. fetch_inbox(project_key="/abs/path/to/repo", agent_name="BlueLake")
  313. acknowledge_message(project_key="/abs/path/to/repo", agent_name="BlueLake", message_id=123)
  314. ```
  315. ### 3. Use macros for common flows
  316. ```
  317. # Boot a full session (ensure project + register agent + reserve files + fetch inbox)
  318. macro_start_session(human_key="/abs/path/to/repo", program="claude-code", model="opus-4.6")
  319. # Prepare for a thread (fetch context + recent messages)
  320. macro_prepare_thread(project_key="/abs/path/to/repo", thread_id="FEAT-123",
  321. program="claude-code", model="opus-4.6")
  322. # Reserve, work, release cycle
  323. macro_file_reservation_cycle(project_key="/abs/path/to/repo", agent_name="GreenCastle",
  324. paths=["src/auth/**"], ttl_seconds=3600, auto_release=true)
  325. # Contact handshake between agents in different projects: approves the link and
  326. # delivers the welcome into the target's project (without auto_accept the link
  327. # stays pending, no welcome is sent, and the response says why; auto_accept never
  328. # overrides a link the target has blocked)
  329. macro_contact_handshake(project_key="/abs/path/to/repo", requester="GreenCastle",
  330. target="BlueLake", to_project="/abs/path/to/other/repo",
  331. auto_accept=true, welcome_subject="Coordination channel",
  332. welcome_body="Use thread FEAT-123 for the cutover")
  333. ```
  334. ---
  335. ## Agent Configuration
  336. The installer and `am` command auto-detect installed agents and write their configs in HTTP URL mode. The examples below are the manual fallback.
  337. ### Claude Code
  338. Add to your project's `.mcp.json` or `~/.claude/settings.json`:
  339. ```json
  340. {
  341. "mcpServers": {
  342. "agent-mail": {
  343. "command": "mcp-agent-mail",
  344. "args": []
  345. }
  346. }
  347. }
  348. ```
  349. Or for HTTP transport (when the server is already running):
  350. ```json
  351. {
  352. "mcpServers": {
  353. "agent-mail": {
  354. "type": "url",
  355. "url": "http://127.0.0.1:8765/mcp/"
  356. }
  357. }
  358. }
  359. ```
  360. ### Codex CLI
  361. The curl installer writes this automatically for detected Codex CLI installs. For source installs, manual setup, or custom endpoint overrides, add this to `~/.codex/config.toml`:
  362. ```toml
  363. [mcp_servers.mcp_agent_mail]
  364. url = "http://127.0.0.1:8765/mcp/"
  365. # Add this when HTTP bearer auth is enabled:
  366. http_headers = { Authorization = "Bearer <HTTP_BEARER_TOKEN>" }
  367. ```
  368. ### Gemini CLI
  369. Add to `~/.gemini/settings.json`:
  370. ```json
  371. {
  372. "mcpServers": {
  373. "agent-mail": {
  374. "command": "mcp-agent-mail",
  375. "args": []
  376. }
  377. }
  378. }
  379. ```
  380. For a project-local Gemini setup plus Agent Mail identity registration:
  381. ```bash
  382. scripts/register_gemini.sh /abs/path/to/repo
  383. AGENT_NAME=BlueLake AGENT_MODEL=gemini-2.5-pro scripts/register_gemini.sh /abs/path/to/repo
  384. ```
  385. ### Oh My Pi (OMP)
  386. `am setup run --agent omp` writes OMP's native project config at `.omp/mcp.json`
  387. and the active profile's user config. The default profile uses
  388. `~/.omp/agent/mcp.json`; named profiles selected through `OMP_PROFILE` (or the
  389. legacy `PI_PROFILE`) use `~/.omp/profiles/<name>/agent/mcp.json`. Profile names
  390. must use OMP's lowercase `[a-z0-9][a-z0-9._-]{0,63}` syntax; an invalid
  391. explicit profile fails closed instead of redirecting setup to the default.
  392. Setup also honors OMP's `PI_CONFIG_DIR` and default-profile `PI_CODING_AGENT_DIR`
  393. overrides, with a stricter path-safety contract: neither may contain `..`
  394. components. `PI_CONFIG_DIR` is rooted beneath the user's home directory;
  395. a relative `PI_CODING_AGENT_DIR` is resolved against the working directory,
  396. and an absolute path is accepted. For example, use `agent` instead of
  397. `foo/../agent`. Invalid overrides cause setup to fail before writing config
  398. files; setup also refuses symlink traversal when accessing those files.
  399. The project config is profile-independent and applies under every named OMP
  400. profile.
  401. `am setup run --agent omp --no-user-config` leaves active-user bytes untouched,
  402. but setup and status still read the authorities that decide whether the
  403. project entry can run. They check the active canonical `mcp.json`
  404. `disabledServers` list against all three accepted Agent Mail aliases
  405. (`mcp-agent-mail`, `mcp_agent_mail`, and `agent-mail`). OMP also discovers the
  406. read-only `.mcp.json` sibling after `mcp.json` in both project and active-user
  407. scopes. An exact repeated server name is shadowed by the earlier source, while a
  408. different Agent Mail alias remains a separate MCP key; setup status reports and
  409. fingerprints that conflict without mirror-writing the secondary file. Status
  410. also evaluates
  411. `mcp.enableProjectConfig` with OMP's persistent settings precedence: the active
  412. profile's `config.yml` (falling back to `config.yaml` only when it is absent).
  413. When both main YAML names are absent, an existing legacy `settings.json` or
  414. `agent.db` remains a migration authority and setup fails closed until OMP has
  415. migrated it or an operator has inspected it. Project settings providers then
  416. merge in runtime order: `.omp/settings.json`,
  417. `.omp/config.yml`, `.claude/settings.json`, `.codex/config.toml`,
  418. `.gemini/settings.json`, project-root `opencode.json` and `opencode.jsonc`,
  419. `.opencode/opencode.json` and `.opencode/opencode.jsonc`, and
  420. `.cursor/settings.json`. Ordered ambient `PI_CONFIG_FILES` overlays apply last.
  421. Foreign-provider parse failures are skipped as OMP skips them. Unsafe or
  422. unreadable paths still fail closed: OMP may follow a symlink or otherwise read
  423. bytes that Agent Mail deliberately refuses to trust, so treating that authority
  424. as absent could produce a false-green verdict. The active-profile YAML, native
  425. `.omp/config.yml`, and explicit overlays are also strict authorities. An
  426. effective `false`, an unsupported authority, or a missing explicit overlay is
  427. reported as runtime-relevant drift instead of success. OpenCode `{env:...}` and
  428. `{file:...}` substitutions are also reported
  429. unsupported because their external dependencies cannot be proven by a cache of
  430. the config bytes alone. Remediation deliberately omits `--no-user-config`,
  431. because a project-only write cannot overcome an authority that excludes every
  432. project MCP source.
  433. This check is bound to the persistent files and the `PI_CONFIG_FILES` value in
  434. the `am` process environment. A one-shot OMP `--config` argument or a
  435. programmatic runtime settings override is launch-specific and is outside this
  436. static setup/status boundary; run `am setup status` under the same ambient
  437. overlay environment used to launch OMP.
  438. To configure it manually:
  439. ```json
  440. {
  441. "mcpServers": {
  442. "mcp-agent-mail": {
  443. "type": "http",
  444. "url": "http://127.0.0.1:8765/mcp/"
  445. }
  446. }
  447. }
  448. ```
  449. When HTTP bearer authentication is enabled, add an `Authorization` entry under
  450. `headers`; `am setup run` does this automatically and adds `.omp/mcp.json` to
  451. the project `.gitignore` so the credential is not committed.
  452. ### Any MCP-Compatible Client
  453. Agent Mail supports both stdio and HTTP transports:
  454. - **stdio**: Run `mcp-agent-mail` as a subprocess (the default for most MCP clients)
  455. - **HTTP**: Connect to `http://127.0.0.1:8765/mcp/` when the server is running via `am` or `mcp-agent-mail serve`
  456. One server process owns a mailbox at a time. While `am` (or `mcp-agent-mail serve`) is serving a storage root, a stdio `mcp-agent-mail` started for the same root refuses to start ("another Agent Mail server is already serving this storage root") instead of contending for it, so configure clients with the HTTP URL whenever `am` runs; the installer and `am setup run` write HTTP URL entries.
  457. - **Examples**: Token-free client templates live under `docs/examples/mcp/`
  458. ---
  459. ## Server Modes
  460. ### MCP Server (default)
  461. ```bash
  462. mcp-agent-mail # stdio transport (for MCP client integration)
  463. mcp-agent-mail serve # HTTP server with TUI (default 127.0.0.1:8765)
  464. mcp-agent-mail serve --no-tui # Headless server (CI/daemon mode)
  465. mcp-agent-mail serve --reuse-running # Reuse existing server on same port
  466. ```
  467. ### CLI Operator Tool
  468. ```bash
  469. am # Start server + TUI (non-interactive: robot status)
  470. am serve-http --port 9000 # Different port
  471. am serve-http --setup # Explicitly update detected MCP clients before serving
  472. am serve-http --host 0.0.0.0 # Bind to all interfaces
  473. am serve-http --no-auth # Skip authentication (local dev)
  474. am serve-http --path api # Use /api/ transport instead of /mcp/
  475. am --help # Full operator CLI
  476. ```
  477. Server startup preserves existing MCP client configuration by default, including
  478. project and user-level URLs. Use `am setup run` to configure clients separately,
  479. or `am serve-http --setup` to update detected clients to that launch's endpoint.
  480. The setup flag can rewrite existing entries; omit it for temporary test servers.
  481. For CLI deployments that require an explicitly supplied sending credential, set
  482. `AGENT_MAIL_REQUIRE_EXPLICIT_SENDER_TOKEN=1`. `am mail send` then requires
  483. `--sender-token`, `--sender-token-file`, or `AGENT_MAIL_SENDER_TOKEN`; it refuses
  484. to borrow a token from persisted agent identity state. The same resolver applies
  485. to queued-send replay and contact handshakes (use the environment variable where
  486. the command has no token flag). The default retains automatic token reuse.
  487. This controls CLI token selection; it does not establish MCP session ownership
  488. or isolate hostile processes sharing the same OS account. Server-side verified
  489. send enforcement remains `MESSAGING_FAIL_CLOSED_SEND_PROFILE=true`.
  490. #### Session-bound agent identity (opt-in)
  491. Available since v0.3.39 (see [CHANGELOG.md](CHANGELOG.md)).
  492. Set `MESSAGING_SESSION_IDENTITY=true` on the server to let an MCP session act as
  493. the identities it established without a registration token in the model-visible
  494. transcript:
  495. - **The session.** Over stdio, the session is the client's server process. Over
  496. Streamable HTTP, a successful `initialize` returns an `Mcp-Session-Id` header;
  497. requests that send it back (over any connection) share the session, and
  498. `DELETE` on the MCP endpoint with the header ends it. A session is tied to the
  499. `Authorization` it was created under: another credential, an unknown id or an
  500. expired id (24 h idle) gets a stateless request. Sessions live in memory, so a
  501. restart ends them. Bearer/JWT authorization is still checked on every request:
  502. this is identity context inside an authorized connection, not authentication.
  503. - **Binding.** `create_agent_identity` (use `return_registration_token: false`
  504. to keep the token out of the transcript) binds the new agent, and so does a
  505. `register_agent` that creates its agent. Naming an existing agent never binds
  506. it.
  507. - **Acting as a bound agent.** `send_message` / `reply_message` from the session
  508. as a bound agent are verified without `sender_token` (`"verified_sender": true,
  509. "sender_verification": "session"`), including under
  510. `MESSAGING_FAIL_CLOSED_SEND_PROFILE`.
  511. - **No borrowed names.** A session that holds an identity in a project cannot,
  512. in that project, send/reply, read an inbox (`fetch_inbox`,
  513. `fetch_inbox_events`, or that project's view in `fetch_inbox_product`), mark
  514. read or acknowledge, reserve/renew/release files, manage build slots, request
  515. a forced reservation release, or re-register (rewriting the profile and
  516. rotating the token) as any other
  517. agent: those calls fail with `SESSION_IDENTITY_MISMATCH` (a send or reply that
  518. carries the other agent's own `sender_token` is still accepted). A session
  519. holding no identity in the project keeps the trusted-local behavior.
  520. - **Database outages.** ACKs and reservation releases can be queued durably
  521. after the acting identity is authorized. If an outage prevents that check
  522. and the session holds a potentially relevant binding, the call returns the
  523. database error without queuing an intent, even for its own supplied name.
  524. Retry after database access recovers. Already authorized intents remain
  525. replayable when another session triggers recovery.
  526. - **Lifecycle.** `retire_agent` / `deregister_agent` drop the identity from the
  527. calling session; lifecycle authorization itself is unchanged (registration
  528. token, or a bound tmux pane over stdio).
  529. This does not authenticate the model, provider or OS process, and it cannot
  530. isolate hostile clients that share one bearer credential and can read each
  531. other's session ids.
  532. When an interactive `am` finds a healthy Agent Mail service already serving the
  533. configured endpoint, it defaults to an attach/takeover/quit prompt
  534. (`AM_ATTACH_MODE=ask`). Enter chooses a read-only view of the service's
  535. `/mail/ws-state` snapshot; that attachment does not stop or restart the service,
  536. acquire a mutation lock, or run service-control commands. Set
  537. `AM_ATTACH_MODE=attach` to select it without prompting. Choose takeover, pass
  538. `--takeover`, or set `AM_ATTACH_MODE=takeover` for an explicit local replacement
  539. through the supervised service-control path; a managed service is restored when
  540. the local session ends. If this decision runs without interactive stdin, the
  541. default is read-only attachment.
  542. ### Dual-Mode Interface
  543. This project keeps MCP server and CLI command surfaces separate:
  544. | Use case | Entry point | Notes |
  545. |---------|-------------|-------|
  546. | MCP server (default) | `mcp-agent-mail` | Default: MCP stdio transport. HTTP: `serve`. |
  547. | CLI (operator + agent-first) | `am` | Recommended CLI entry point. |
  548. | CLI via single binary | `AM_INTERFACE_MODE=cli mcp-agent-mail` | Same CLI surface, one binary. |
  549. Running CLI-only commands via the MCP binary produces a deterministic denial on stderr with exit code `2`, and vice versa, preventing accidental mode confusion in automated workflows.
  550. ---
  551. ## Operator CLI Surface
  552. `am` is more than a launcher. It is the operator surface for runtime control, diagnostics, migration, exports, benchmarking, and agent-facing non-interactive workflows. In non-interactive contexts, bare `am` automatically falls back to robot output instead of trying to launch a blocking TUI.
  553. ### Command Families
  554. | Surface | Subcommands / form | What it is for |
  555. |---------|--------------------|----------------|
  556. | Runtime | `serve-http`, `serve-stdio`, `service install|status|logs|restart`, `check-inbox`, `inbox-events` | Start the server, run stdio MCP, manage a background service, poll inbox state, or resume a durable inbox monitor |
  557. | Quality gates | `ci`, `verify`, `lint`, `typecheck`, `bench` | Run the native quality pipeline, build-slot-protected verification lanes, and CLI/perf baselines |
  558. | E2E and determinism | `e2e list|run|show`, `golden capture|verify|list`, `flake-triage scan|reproduce|detect` | Test transports and workflows, guard CLI output contracts, and triage flaky failures |
  559. | Share and deploy | `share export|update|preview|verify|decrypt|wizard|static-export`, `share deploy validate|tooling|verify|verify-live` | Build portable mailbox bundles, preview them, and validate live static deployments |
  560. | Archive and recovery | `archive save|list|restore`, `doctor ...` (28 verbs: `check`, `health`, `triage`, `locks`, `drain`, `fix`, `undo`, `repair`, `reconstruct`, ...; see Family Detail) | Snapshot mailbox state, scan/archive hygiene, normalize safe archive debt, or repair/rebuild SQLite from the Git archive |
  561. | Coordination data | `agents ...`, `mail ...`, `contacts ...`, `macros ...`, `file_reservations ...`, `acks ...`, `list-acks` | Operate directly on the same concepts the MCP tools expose |
  562. | Project and product routing | `projects ...`, `products ...`, `list-projects`, `beads ...` | Manage project identity, cross-project product groupings, and task-tracker views |
  563. | Platform and setup | `setup run|status`, `config set-port|show-port`, `amctl env`, `tooling ...`, `docs insert-blurbs` | Bootstrap connectors, inspect runtime config, introspect tool schemas/metrics/locks, and stamp docs |
  564. | Migration and lifecycle | `legacy detect|import|status`, `upgrade`, `migrate`, `self-update`, `am-run`, `guard ...` | Migrate Python installs, perform DB-format upgrades, run slot-aware build commands, and manage guard hooks |
  565. | Break-glass admin | `clear-and-reset-everything` | Fully reset local state after optional archival. A running server holding the mailbox is stopped for the wipe: a systemd user service or LaunchAgent through its manager (and started again afterwards), any other Agent Mail process with SIGTERM, then SIGKILL after a grace period. Use sparingly. |
  566. ### Setup Drift Reports
  567. `am setup status` is read-only. It inventories supported MCP clients, reports the
  568. current redacted server entry beside the expected entry, and labels drift such
  569. as `missing_file`, `legacy_stdio`, `stale_http_path`, `wrong_bearer_header`,
  570. `wrong_startup_timeout`, `duplicate_server_entries`, and `unsupported_config`.
  571. Use the reported remediation in two steps:
  572. ```bash
  573. am setup status --format json
  574. am setup run --dry-run --project-dir "$PWD" --format toon
  575. am setup run --yes --project-dir "$PWD" --format toon
  576. ```
  577. For bearer-header checks, pass `--token` to `am setup status` or expose the
  578. expected token through `HTTP_BEARER_TOKEN` / `config.env`; status output redacts
  579. token values.
  580. ### Family Detail
  581. | Family | Current subcommands / modes |
  582. |--------|------------------------------|
  583. | `share` | `export`, `update`, `preview`, `verify`, `decrypt`, `wizard`, `static-export`, `deploy validate`, `deploy tooling`, `deploy verify`, `deploy verify-live` |
  584. | `archive` | `save`, `list`, `restore` |
  585. | `guard` | `install`, `uninstall`, `status`, `check` |
  586. | `file_reservations` | `list`, `active`, `soon`, `reserve`, `renew`, `release`, `conflicts` |
  587. | `acks` | `pending`, `remind`, `overdue` |
  588. | `projects` | `mark-identity`, `discovery-init`, `adopt` |
  589. | `mail` | `status`, `send`, `reply`, `inbox`, `read`, `ack`, `search`, `summarize-thread`, `replay-queued`, `discard-queued` |
  590. | `products` | `ensure`, `link`, `status`, `search`, `inbox`, `summarize-thread` |
  591. | `doctor` (28 verbs) | `check`, `health`, `triage`, `locks`, `drain`, `fix`, `undo`, `ls`, `explain`, `fixers`, `capabilities`, `robot-docs`, `artifacts`, `reclaim`, `selftest`, `mcp-selftest`, `write-selftest`, `support-bundle`, `repair`, `reconstruct`, `backups`, `restore`, `archive-scan`, `archive-verify`, `archive-normalize`, `fix-orphan-refs`, `pack-archive`, `vacuum` |
  592. | `agents` | `register`, `create`, `list`, `show`, `detect`, `reap`, `resolve-pane` |
  593. | `tooling` | `directory`, `schemas`, `metrics`, `metrics-core`, `diagnostics`, `locks`, `decommission-fts` |
  594. | `macros` | `start-session`, `prepare-thread`, `file-reservation-cycle`, `contact-handshake` |
  595. | `contacts` | `request`, `respond`, `list`, `policy` |
  596. | `beads` | `ready`, `list`, `show`, `status` |
  597. | `setup` | `run`, `status` |
  598. | `golden` | `capture`, `verify`, `list` |
  599. | `flake-triage` | `scan`, `reproduce`, `detect` |
  600. | `robot` | `status`, `inbox`, `timeline`, `overview`, `thread`, `search`, `message`, `navigate`, `reservations`, `metrics`, `health`, `analytics`, `agents`, `contacts`, `projects`, `attachments`, `atc`, `handoff`, `tui-dump` |
  601. | `verify` | `cargo-fmt`, `cargo-check`, `cargo-clippy`, `cargo-test`, `e2e-list`, `e2e-stdio`, `bench-quick`, `reliability-coverage` |
  602. | `legacy` | `detect`, `import`, `status` |
  603. | `service` | `install`, `uninstall`, `status`, `logs`, `restart` |
  604. ### Durable Inbox Event Cursors
  605. `am inbox-events` is the CLI for restart-safe inbox monitors. It reads
  606. append-only, body-free delivery events oldest first; its `--after` value is a
  607. delivery cursor, never a message ID. Persist `next_cursor` only after the
  608. corresponding events have been processed.
  609. ```bash
  610. # Establish a durable starting position without consuming events.
  611. am inbox-events --project /abs/path --agent BlueLake --position-now --format json
  612. # Resume from the last processed delivery cursor.
  613. am inbox-events --project /abs/path --agent BlueLake --after 42 --limit 100 --format json
  614. ```
  615. Each page includes `events`, `next_cursor`, `has_more`,
  616. `oldest_available_cursor`, and `tail_cursor`. Retention records durable loss
  617. markers for the affected recipient. Deleting another recipient's mail does
  618. not expire your cursor, and deleting the newest or every retained event does
  619. not move your durable tail backwards.
  620. If retention removed a delivery after your saved position, the read fails
  621. with code `cursor_expired` (the `fetch_inbox_events` tool reports
  622. `CURSOR_EXPIRED`). This also detects holes inside retained history, even when
  623. older events remain. The error's `oldest_available_cursor` identifies the first
  624. position after the lost history; after handling the loss according to your
  625. recovery policy, resume with `--after` set to that value minus one. The page's
  626. `oldest_available_cursor` still describes its oldest retained event. To
  627. intentionally start monitoring only future mail, use `--position-now`.
  628. A cursor beyond the durable tail fails with `cursor_ahead` (`CURSOR_AHEAD`);
  629. check that the cursor belongs to this mailbox and recipient before choosing a
  630. new position. The migration preserves the database's existing issued-cursor
  631. ceiling, including when all events were already deleted. It cannot reconstruct
  632. which recipients lost events before durable retention markers were introduced.
  633. ---
  634. ## The 45 MCP Tools
  635. ### 9 Clusters
  636. | Cluster | Count | Tools |
  637. |---------|-------|-------|
  638. | Infrastructure | 4 | `health_check`, `ensure_project`, `install_precommit_guard`, `uninstall_precommit_guard` |
  639. | Identity | 9 | `register_agent`, `create_agent_identity`, `retire_agent`, `unretire_agent`, `deregister_agent`, `whois`, `resolve_pane_identity`, `cleanup_pane_identities`, `list_agents` |
  640. | Messaging | 9 | `send_message`, `reply_message`, `fetch_inbox`, `fetch_topic`, `fetch_inbox_events`, `get_message_delivery_receipt`, `acknowledge_message`, `mark_message_read`, `mark_all_read` |
  641. | Contacts | 4 | `request_contact`, `respond_contact`, `list_contacts`, `set_contact_policy` |
  642. | File Reservations | 5 | `check_file_reservation_conflicts`, `file_reservation_paths`, `renew_file_reservations`, `release_file_reservations`, `force_release_file_reservation` |
  643. | Search | 2 | `search_messages`, `summarize_thread` |
  644. | Macros | 4 | `macro_start_session`, `macro_prepare_thread`, `macro_contact_handshake`, `macro_file_reservation_cycle` |
  645. | Product Bus | 5 | `ensure_product`, `products_link`, `search_messages_product`, `fetch_inbox_product`, `summarize_thread_product` |
  646. | Build Slots | 3 | `acquire_build_slot`, `renew_build_slot`, `release_build_slot` |
  647. `fetch_inbox_events` is the MCP equivalent of `am inbox-events`: it is a
  648. durable, recipient-scoped delivery feed for monitors, not a replacement for
  649. message-body inbox reads.
  650. `file_reservation_paths` accepts an optional `idempotency_key` for an exact
  651. retry after a timeout. The same key and normalized request replay the original
  652. grant without a second lease or archive write and mark the response
  653. `idempotent_replay: true`. Reusing a key with different arguments returns
  654. `IDEMPOTENCY_KEY_CONFLICT`. Keys are scoped to `(project, tool)`, expire after
  655. the configured retention window, and are optional; this is not a blanket
  656. idempotency claim for every mutating tool.
  657. On replay, `granted` contains the original IDs and expiries, even after release
  658. or expiry; it does not reacquire those paths. `conflicts` is a current snapshot.
  659. A partial or empty original grant stays partial or empty; use a new key for a
  660. new acquisition attempt. Fresh reacquisition of an active lease reuses its ID
  661. and applies the requested exclusive/shared mode and reason after checking peers.
  662. Keys recorded before the normalized path-set fingerprint update can return
  663. `IDEMPOTENCY_KEY_CONFLICT` after an upgrade, even within their retention window.
  664. The original grants remain unchanged; inspect them before making a new attempt.
  665. ### Agent identities
  666. Omit `name` from `register_agent` (or `name_hint` from `create_agent_identity`)
  667. to get an automatically generated adjective+noun name such as `GreenLake`.
  668. For a stable task identity, supply a name such as `app-x-refactor`, `worker_42`,
  669. or `api.review`.
  670. Explicit task identifiers start with an ASCII letter or digit, contain at
  671. least one `.`, `_`, or `-`, and use only ASCII letters, digits, and those
  672. separators, up to 128 characters. They preserve their spelling. Vocabulary
  673. names still normalize to PascalCase. Both forms are unique within a project
  674. without regard to case: registering `APP-X-REFACTOR` after `app-x-refactor`
  675. updates the same identity and returns its original canonical spelling.
  676. `create_agent_identity` instead rejects a name that is already in use.
  677. Path separators, address delimiters, consecutive or trailing dots, template
  678. placeholders, Windows device names, and reserved program/model/operator
  679. identities are rejected. Broadcast tokens remain unsupported. A dot inside
  680. an identity is part of its name; cross-project recipients still use
  681. `Name@project` or `project:project#Name` and require the usual contact approval.
  682. ### 25 MCP Resources
  683. Read-only resources span environment/config inspection, project and agent discovery, inbox and thread views, reservation views, and tooling diagnostics. They are there so agents can fetch state cheaply without mutating anything.
  684. ```
  685. resource://inbox/{Agent}?project=<abs-path>&limit=20
  686. resource://thread/{id}?project=<abs-path>&include_bodies=true
  687. resource://mailbox/{Agent}?project=<abs-path>
  688. resource://views/ack-overdue/{Agent}?project=<abs-path>
  689. resource://agents/<project-slug>
  690. resource://file_reservations/<project-slug>?active_only=true
  691. resource://tooling/metrics
  692. resource://config/environment
  693. ```
  694. `resource://agents/...` and `resource://file_reservations/...` take the project in the path segment. Inbox, mailbox, thread, and message resources put the agent or thread in the path and the project in the query string.
  695. ### Macros vs. Granular Tools
  696. - **Prefer macros when you want speed** or are on a smaller model: `macro_start_session`, `macro_prepare_thread`, `macro_file_reservation_cycle`, `macro_contact_handshake`
  697. - **Use granular tools when you need control:** `register_agent`, `file_reservation_paths`, `send_message`, `fetch_inbox`, `acknowledge_message`
  698. ---
  699. ## TUI Operations Console
  700. The interactive TUI has 16 screens. Jump directly with `1`-`9`, `0` (screen 10), and shifted digits `!`, `@`, `#`, `$`, `%`, `^` (screens 11-16). Use `Tab`/`Shift+Tab` to cycle in order.
  701. | # | Screen | Shows |
  702. |---|--------|-------|
  703. | 1 | Dashboard | Real-time operational overview with event stream and anomaly rail |
  704. | 2 | Messages | Message browser with detail pane, presets, and compose/reply flows |
  705. | 3 | Threads | Thread explorer and conversation drill-down |
  706. | 4 | Agents | Agent roster with activity, state, and quick actions |
  707. | 5 | Search | Unified multi-scope search with facets and preview |
  708. | 6 | Reservations | File reservation status, conflicts, and create/release actions |
  709. | 7 | Tool Metrics | Per-tool call counts, latency distributions, and failures |
  710. | 8 | System Health | Probe/circuit/disk/memory diagnostics plus ATC health widget |
  711. | 9 | Timeline | Events/Commits/Combined/Log timeline views with inspector |
  712. | 10 | Projects | Project inventory and routing helpers |
  713. | 11 | Contacts | Contact links, policy view, and graph/mermaid modes |
  714. | 12 | Explorer | Unified inbox/outbox explorer with direction and ack filters |
  715. | 13 | Analytics | Anomaly insight feed with confidence and deep links |
  716. | 14 | Attachments | Attachment inventory with preview and provenance |
  717. | 15 | Archive Browser | Two-pane Git archive browser with tree + file preview |
  718. | 16 | ATC | Snapshot-driven ATC control surface with decision drill-in and retention report |
  719. **Global keys:** `?` help, `Ctrl+P`/`:` command palette, `/` the screen's own filter (global search focus on screens without one), `.` contextual action menu, `Ctrl+N` compose overlay, `Ctrl+Y` toast-focus mode, `Ctrl+T`/`Shift+T` cycle theme, `m` toggle MCP/API transport, `q` quit.
  720. **ATC keys:** `d` decision detail, `r` retention report, `i` toggle detail pane, `Tab` switch agents/decisions.
  721. **Screen-specific highlights:** Messages uses `g` for Local/Global inbox; Threads uses `e/c` for expand/collapse-all in conversation view; Timeline uses `V` for Events/Commits/Combined/Log and `v` for visual selection; Search uses `f` + facet rail navigation for scope/sort/field controls; Contacts uses `n` to cycle Table/Graph/Matrix (sender × recipient heatmap); batch-capable screens share `Space`/`v`/`A`/`C`; preset-enabled screens use `Ctrl+S`/`Ctrl+L`.
  722. **Compose from any screen:** Press `Ctrl+N`, choose the project with the arrow
  723. keys, then use `Tab` to reach recipients and the remaining fields. Existing
  724. active agents are loaded from that project's live mailbox. A mailbox with more
  725. than one project requires an explicit choice. Select recipients with `Space`
  726. and cycle their To/Cc/Bcc role with `Ctrl+T`; the Acknowledgement field can
  727. request a receipt. `Ctrl+R` refreshes projects and recipients, and
  728. `Ctrl+Enter` sends.
  729. Loading and delivery run in the background. A failed send keeps the draft;
  730. retrying it unchanged reuses its delivery key to avoid duplicate mail. While
  731. sending, the form prevents edits and duplicate submissions. `Esc` dismisses a
  732. pending form while delivery continues. Changing project clears its recipients
  733. and thread, preserving the message text; refreshing the same project keeps
  734. selected unavailable recipients visible until you explicitly remove them.
  735. **Command palette:** Press `Ctrl+P` (or `:` outside text-entry) to open a searchable action launcher that includes screen navigation, transport/layout controls, and dynamic entities (agents/projects/threads/tools/reservations).
  736. **Themes:** 42 named palettes are in the `Ctrl+T`/`Shift+T` cycle (Cyberpunk Aurora, Darcula, Lumen Light, Nordic Frost, High Contrast, Dracula, Monokai, Nord, and more; see `NAMED_THEMES` in `crates/mcp-agent-mail-server/src/tui_theme.rs`). The five config-level themes are selectable through `TUI_THEME`. Accessibility support includes high-contrast mode and reduced motion.
  737. Archive Browser note: use `Enter` to expand/preview, `Tab` to switch tree vs preview pane, `/` to filter filenames, and `Ctrl+D/U` for preview paging.
  738. If an interactive `am` attaches to an already running service, this terminal is
  739. read-only and detaches with `Ctrl-C`; the service keeps serving MCP/API traffic.
  740. Use an explicit `--takeover` only when replacement is intended.
  741. ---
  742. ## Robot Mode (`am robot`)
  743. Non-interactive, agent-first CLI surface for TUI-equivalent situational awareness. Use it when you need structured snapshots quickly, especially in automated loops and when tokens matter.
  744. ### 19 Subcommands
  745. | Command | Purpose | Key flags |
  746. |---------|---------|-----------|
  747. | `am robot status` | Dashboard synthesis | `--format`, `--project`, `--agent` |
  748. | `am robot inbox` | Actionable inbox with urgency/ack synthesis | `--urgent`, `--ack-overdue`, `--unread`, `--all`, `--limit`, `--include-bodies` |
  749. | `am robot timeline` | Project event stream (last 24h unless `--since`) | `--since`, `--kind`, `--source` |
  750. | `am robot overview` | Cross-project summary | `--format`, `--counts` |
  751. | `am robot thread <id>` | Full thread rendering | `--limit`, `--since`, `--format`, `--server` |
  752. | `am robot search <query>` | Full-text search with facets/relevance | `--kind`, `--importance`, `--since`, `--limit`, `--cursor`, `--format` |
  753. | `am robot message <id>` | Single-message deep view | `--format`, `--project`, `--server` |
  754. | `am robot navigate <resource://...>` | Resolve resources into robot-formatted output | `--format`, `--project`, `--agent` |
  755. | `am robot reservations` | Reservation view with conflict/expiry awareness; JSON entries carry absolute `granted_ts`/`expires_ts` (RFC 3339 UTC) and integer `remaining_seconds`/`granted_age_seconds` next to the humanized `remaining` | `--all`, `--conflicts`, `--expiring`, `--agent` |
  756. | `am robot metrics` | Tool call rates, failures, latency percentiles (server-wide) | `--format` |
  757. | `am robot health` | Runtime/system diagnostics (server-wide) | `--format`, `--include-host` |
  758. | `am robot analytics` | Anomaly and remediation summary | `--format`, `--project`, `--agent` |
  759. | `am robot agents` | Agent roster and activity overview | `--active`, `--sort` |
  760. | `am robot contacts` | Contact graph (incoming cross-project requests included) and policy surface | `--format`, `--project`, `--agent` (links on either side) |
  761. | `am robot projects` | Per-project aggregate stats (every project) | `--format` |
  762. | `am robot attachments` | Attachment inventory | `--format`, `--project` |
  763. | `am robot atc` | Live ATC snapshot with local DB fallback when the server is unavailable | `--since`, `--stratum`, `--summary-only`, `--limit` |
  764. | `am robot handoff` | Read-only stale bead ownership and handoff dashboard | `--stale-minutes`, `--active-minutes`, `--fresh-comment-minutes`, `--include-fresh`, `--dry-run` |
  765. | `am robot tui-dump` | TUI freeze escape hatch (alias of `am tui-dump`): the situational snapshot the TUI renders, fetched live or from local SQLite | `--format` |
  766. ### Output Formats
  767. - **`toon`** (default at TTY): Token-efficient, compact, optimized for agent parsing
  768. - **`json`** (default when piped): Machine-readable envelope with `_meta`, `_alerts`, `_actions`
  769. - **`md`** (`thread` and `message` only, and their default even when piped): Human-readable narrative for deep context. Pass `--format json` to pipe them into `jq`.
  770. ### Search Pages
  771. `am robot search` accepts `--limit` from 1 through 1000 (default 20) and
  772. `--cursor` to continue from the response's `next_cursor`:
  773. ```bash
  774. am robot search 'migration' --project /abs/path --limit 50 --format json
  775. am robot search 'migration' --project /abs/path --limit 50 --cursor '<next_cursor>' --format json
  776. ```
  777. Keep the query, project, and filters the same when resuming. Stop when
  778. `next_cursor` is absent. Both the existing live-server route and the local
  779. snapshot route carry the requested page size and cursor. Recipient-kind
  780. filtering (`--kind to`, `cc`, or `bcc`) resumes after the last displayed match,
  781. including when more matches remain inside a fetched backend page. Invalid
  782. limits and malformed cursors fail before opening a mailbox. Search pages
  783. reflect the current index; they do not freeze a changing corpus across calls.
  784. `am robot overview` summarizes the whole mailbox; the global `--project` and
  785. `--agent` flags do not scope this command. Message counts use one grouped query,
  786. and active reservations use one candidate scan with release-ledger filtering.
  787. `--counts` returns totals from the same aggregation. The snapshot cache is
  788. process-local, so separate CLI invocations each read the database.
  789. `am robot atc` reads the live ATC snapshot over `/mail/ws-state` when the local server is running and falls back to a local SQLite rollup/liveness view when that snapshot is unavailable. Use `--since` to trim recent decisions/executions, `--stratum` to focus open-stratum counts, and `--summary-only` for the compact health view.
  790. `am robot handoff` correlates in-progress beads with Agent Mail activity, active file reservations, thread mail, and recent comments. It is always read-only: reopen/takeover rows contain proposed `br update ... --status open --json` commands, but agents must inspect reservations, peer dirty work, and the related thread before running them.
  791. ### Agent Workflow Recipes
  792. ```bash
  793. # Startup triage
  794. am robot status --project /abs/path --agent AgentName
  795. # Immediate urgency pass
  796. am robot inbox --project /abs/path --agent AgentName --urgent --format json
  797. # Incremental monitoring loop
  798. am robot timeline --project /abs/path --agent AgentName --since 2026-02-16T10:00:00Z
  799. # Deep thread drill-down
  800. am robot thread br-123 --project /abs/path --agent AgentName --format md
  801. # Reservation safety check before edits
  802. am robot reservations --project /abs/path --agent AgentName --conflicts --expiring 30
  803. # Heavy verification recommendation with build-slot admission and rch
  804. am robot status --project /abs/path --agent AgentName --format json \
  805. | jq '.recommendations[] | select(.category == "verification_lane")'
  806. ```
  807. ---
  808. ## File Reservations for Multi-Agent Editing
  809. Before editing, agents reserve file paths to avoid conflicts:
  810. ```
  811. file_reservation_paths(project_key, agent_name, paths=["src/**"], ttl_seconds=3600, exclusive=true)
  812. ```
  813. The pre-commit guard (`mcp-agent-mail-guard`) installs as a Git hook and blocks commits that touch files reserved by other agents. Reservations are advisory, TTL-based, and support glob patterns.
  814. New reservation artifacts are named
  815. `id-<reservation-id>-g<db-generation>.json` and carry the same generation in
  816. their JSON. This prevents a re-created SQLite database from overwriting an
  817. older generation's row-id artifact. Readers still recognize legacy
  818. `id-<reservation-id>.json` artifacts; parity reports stamped artifacts from a
  819. different live generation as foreign-generation debris rather than current
  820. reservation drift.
  821. The guard has narrow operational exemptions: `.beads/**` metadata is always
  822. exempt so shared task-state commits cannot be stranded, and an agent's own
  823. reservation does not conflict with its commit. Source files reserved by another
  824. agent remain protected. When no matching mailbox archive can be found (including
  825. a proven slug collision), the hook emits a warning and allows the commit rather
  826. than turning stale/missing mailbox state into a universal commit gate.
  827. The pre-push hook lists the paths a push touches with one streamed
  828. `git rev-list | git diff-tree --stdin` pipeline per pushed ref, so its cost no
  829. longer grows with a git process per commit. The scan is bounded by
  830. `AGENT_MAIL_GUARD_PUSH_MAX_COMMITS` (default 2000 commits per ref, newest
  831. first), `AGENT_MAIL_GUARD_PUSH_MAX_PATHS` (default 100000 path records per
  832. ref) and `AGENT_MAIL_GUARD_PUSH_TIMEOUT_SECS` (default 120 seconds for the
  833. whole push); `0` removes a bound. Reaching a bound truncates the scan: the
  834. paths already read are still checked, and if none of them conflicts while
  835. another agent holds an active lease, the hook fails closed (exit 2) naming what
  836. was skipped and which variable to raise, the same way every other unfinished
  837. inspection does. `AGENT_MAIL_GUARD_MODE=warn` turns that into a warning.
  838. Installing with `am guard install <project> <repo> --prepush` also installs a
  839. composed post-commit hook. It independently checks the exact committed snapshot
  840. against active reservations, including both rename endpoints and every merge
  841. parent. A complete check in block mode records a private, signed admission in
  842. the repository's Git metadata. A later editing lease can then protect the next
  843. editor's work without vetoing publication of that already admitted commit.
  844. The pre-commit guard still checks staged changes; publishing never modifies
  845. the index or working tree.
  846. Pre-push skips only individually admitted commit objects. It still checks
  847. unadmitted ancestors and commits created without a successful admission, using
  848. the same scan bounds. Commit timestamps, branch names, replacement refs and
  849. grafts do not establish admission. Receipts are bound to the canonical
  850. repository, project and archive authority and the generated guard policy;
  851. copying receipts to another repository or changing that authority cannot reuse
  852. them. A failed or incomplete post-commit check leaves the commit unadmitted
  853. and prints a warning, since Git cannot veto a commit from that hook.
  854. Explicit bypass, disabled enforcement and warn mode never record admission.
  855. Ambiguous or malformed reservation evidence cannot record it either. Existing
  856. user hooks remain composed and are restored when the guard is uninstalled.
  857. Reinstall with `--prepush` to enable admission in repositories with older hooks.
  858. Shallow repositories, and platforms without directory-relative no-follow file
  859. operations, retain the ordinary pre-push reservation check without admission.
  860. | Area | Reserve glob |
  861. |------|-------------|
  862. | Core types/config | `crates/mcp-agent-mail-core/src/**` |
  863. | SQLite layer | `crates/mcp-agent-mail-db/src/**` |
  864. | Git archive | `crates/mcp-agent-mail-storage/src/**` |
  865. | Tool implementations | `crates/mcp-agent-mail-tools/src/**` |
  866. | TUI | `crates/mcp-agent-mail-server/src/tui_*.rs` |
  867. | CLI/launcher | `crates/mcp-agent-mail-cli/src/**` |
  868. ### Message and Thread Context Through the Server
  869. Use `--server` when the running daemon can answer but a new local database
  870. connection cannot be admitted:
  871. ```bash
  872. am robot message 1234 --project /abs/path --server --format json
  873. am robot thread 1234 --project /abs/path --server --limit 200 --format md
  874. am thread TKT-123 --project /abs/path --server --since 2026-01-01T00:00:00Z
  875. ```
  876. These commands preserve the normal message/thread output, including sender
  877. program/model, acknowledgement counts, message neighbours, whole-thread
  878. participants, and the newest `--limit` messages in chronological order with
  879. their full-thread positions. `--since` filters the count and displayed window;
  880. the subject and participants still describe the whole conversation. They pin
  881. the configured endpoint and bearer token, verify stored project identity, and
  882. never open a local mailbox or fall back to an archive. Older servers without
  883. complete context support are rejected explicitly. As with other MCP resources,
  884. BCC identities are redacted and excluded from the participant list.
  885. MCP clients can request these envelopes using
  886. `resource://message/<id>?project=<slug>&context=true&format=json` or
  887. `resource://thread/<id>?project=<slug>&context=true&limit=200&include_bodies=true&format=json`.
  888. Thread context accepts `since_ts` as an ISO-8601 timestamp. The versioned
  889. envelope includes stored project identity, a capture time and `complete=true`.
  890. All context fields come from one read snapshot. The server refuses conversations
  891. with more than 10,000 messages or receipt rows, more than 1,000 displayed
  892. messages, or more than 4 MiB of context; it never silently truncates those
  893. bounds. Resources without `context=true` keep their existing response formats.
  894. ### Complete Reservation Reads Through the Server
  895. Ordinary `resource://file_reservations/<slug>` pages include optional activity
  896. hints. Filesystem and Git enrichment share a 100 ms cooperative time budget;
  897. Git history is also capped at 1,000 commits per page and diffs are restricted
  898. to the reserved paths. `last_git_activity_ts` reports a recent touch found
  899. within `FILE_RESERVATION_ACTIVITY_GRACE_SECONDS`, not an exhaustive historical
  900. last-touch lookup. It is null if no recent touch was established. When the
  901. scan is incomplete, `stale_reasons` includes `git_activity_unknown`
  902. and `stale` remains false. Cancelling or abandoning a read stops its worker
  903. at the next checkpoint; a single filesystem or libgit2 call cannot be
  904. interrupted. Bounded reads always use libgit2, independently of the legacy
  905. `AM_GIT_LS_FILES_SHELL` and `AM_GIT_RESERVATION_ACTIVITY_SHELL` escape hatches
  906. for the single-pattern force-release probe. Snapshot modes omit activity
  907. enrichment entirely.
  908. Use `--server` to read reservations through the configured authenticated MCP
  909. endpoint while the server owns the mailbox:
  910. ```bash
  911. am reservations --project /abs/path --all --json --server
  912. am file_reservations active /abs/path --server
  913. am file_reservations list /abs/path --all --server
  914. ```
  915. These reads now use a complete database snapshot and can return more than the
  916. resource's normal 250-row page. Project identity, holder identities, lease rows,
  917. and the active-lease cutoff come from the same read snapshot. Historical leases
  918. retain their holder names even when those agents have retired. Navigation still
  919. applies the requested ordering and page after obtaining the complete set.
  920. MCP clients can request the same envelope with
  921. `resource://file_reservations/<slug>?snapshot=true&active_only=true&format=json`.
  922. It includes `schema_version`, `complete`, `project`, `agents`, `captured_ts`,
  923. `active_only`, `count`, and `reservations`. Set `active_only=false` to include
  924. released and expired leases. Snapshot mode accepts no `limit` or `offset` and
  925. refuses results exceeding 10,000 reservations, 10,000 holder identities, or
  926. 4 MiB of JSON. For history reads (`active_only=false`), a CLI receiving this
  927. specific capacity refusal negotiates `snapshot_pages=true` with the same
  928. authenticated server. The server captures a larger bounded set once, then
  929. returns immutable pages of at most 250 rows and 4 MiB each. This supports
  930. `am file_reservations list <project> --all` beyond the single-response limits
  931. without opening another database connection in the CLI.
  932. Paged snapshots allow at most 100,000 reservations and holder identities and
  933. 64 MiB of serialized pages, including repeated identity metadata. All rows,
  934. holder names, release states, and ordering (`created_ts`, then `id`) come from
  935. one database read snapshot. Changes after capture appear only in a new read.
  936. Each page includes `consistency: "materialized_snapshot"`, `snapshot_token`,
  937. `captured_ts`, `total_count`, `offset`, `count`, and an explicit `next_offset`
  938. (null on the terminal page), alongside `project`, `agents`, `active_only`, and
  939. `reservations`. `captured_ts` marks capture start, not an exact historical query
  940. timestamp. Continue with the same URI plus `snapshot_token=<token>` and
  941. `offset=<next_offset>`; do not supply `snapshot` or `limit` in paged mode.
  942. Tokens expire 300 seconds after publication, do not survive server restart,
  943. and remain bound to the mailbox engine generation, project identity, and
  944. active/history scope. Every continuation requires normal server authentication.
  945. New pages advertise `supports_release: true`. Once a client finishes or abandons
  946. the read, it can free the snapshot using the same URI with its `snapshot_token`
  947. and `snapshot_release=true`, omitting `offset`. Release is authenticated, scoped,
  948. and idempotent; page retries remain valid until release or expiry. The CLI makes
  949. this best-effort cleanup request after success or a pagination failure, with a
  950. two-second request timeout. Cleanup failure does not replace the listing or its
  951. original error; expiry handles crashes, lost connectivity, and older paged servers
  952. that do not advertise release.
  953. The server retains at most four snapshots within a 128 MiB serialized cache
  954. budget; in-progress captures reserve capacity too. A full cache, expired token,
  955. oversized individual row/identity metadata, or exceeded aggregate bound is an
  956. explicit error. The CLI validates every page, permits at most 1,024 requests
  957. within a 300-second history-read budget, and displays nothing until the entire
  958. set and final project identity checks succeed. Retry a failed read from the
  959. beginning; partial results are never reported as complete.
  960. This path requires both the updated CLI and server. Older servers that return
  961. only ordinary arrays cannot provide the paged snapshot guarantee; the CLI
  962. retains the original size refusal and gives an upgrade/restart hint. Existing
  963. small legacy reads still require a short explicit page to prove completeness.
  964. Active-only safety reads retain the original single-snapshot limits. Ordinary
  965. resource reads without either snapshot mode keep independent `limit`/`offset`
  966. pagination and are not a consistent snapshot. Server rejection diagnostics
  967. retain the numeric error code and sanitized reason; only actual HTTP
  968. authentication failures receive authentication guidance.
  969. ---
  970. ## Multi-Agent Coordination Workflows
  971. ### How Agents Interact (Protocol Flow)
  972. ```mermaid
  973. sequenceDiagram
  974. participant A as Agent A (GreenCastle)
  975. participant S as Agent Mail Server
  976. participant B as Agent B (BlueLake)
  977. A->>S: ensure_project(human_key="/abs/path")
  978. A->>S: register_agent(project_key="/abs/path", program="claude-code")
  979. S-->>A: identity: GreenCastle
  980. B->>S: register_agent(project_key="/abs/path", program="codex-cli")
  981. S-->>B: identity: BlueLake
  982. A->>S: file_reservation_paths(project_key="/abs/path", agent_name="GreenCastle", paths=["src/auth/**"], exclusive=true)
  983. S-->>A: reserved ✓
  984. B->>S: file_reservation_paths(project_key="/abs/path", agent_name="BlueLake", paths=["src/auth/**"], exclusive=true)
  985. S-->>B: CONFLICT — reserved by GreenCastle
  986. B->>S: file_reservation_paths(project_key="/abs/path", agent_name="BlueLake", paths=["tests/api/**"], exclusive=true)
  987. S-->>B: reserved ✓
  988. A->>S: send_message(project_key="/abs/path", sender_name="GreenCastle", to=["BlueLake"], thread_id="FEAT-123", ack_required=true)
  989. S-->>B: new message in inbox
  990. B->>S: fetch_inbox(project_key="/abs/path", agent_name="BlueLake")
  991. S-->>B: [message from GreenCastle]
  992. B->>S: acknowledge_message(project_key="/abs/path", agent_name="BlueLake", message_id=1482)
  993. S-->>A: ack received ✓
  994. A->>S: release_file_reservations(project_key="/abs/path", agent_name="GreenCastle", paths=["src/auth/**"])
  995. S-->>A: released ✓
  996. ```
  997. ### Same Repository
  998. 1. **Register identity:** `ensure_project(human_key=<abs-path>)` + `register_agent(project_key=<abs-path>, ...)`
  999. 2. **Reserve files before editing:** `file_reservation_paths(project_key, agent_name, paths=["src/**"], ttl_seconds=3600, exclusive=true)`
  1000. 3. **Communicate with threads:** `send_message(..., thread_id="FEAT-123")`, check with `fetch_inbox`, acknowledge with `acknowledge_message`
  1001. 4. **Quick reads:** `resource://inbox/{Agent}?project=<abs-path>&limit=20`
  1002. 5. **Tell the whole project once:** address the project's shared mailbox as `project:<slug>` (or `project:<human_key>`). Available since v0.3.39 (see [CHANGELOG.md](CHANGELOG.md)):
  1003. ```
  1004. send_message(project_key="/abs/path", sender_name="GreenCastle",
  1005. to=["project:abs-path"], subject="Schema freeze until 18:00",
  1006. body_md="Do not touch migrations/ until the release is cut.", ack_required=true)
  1007. ```
  1008. - The message is stored **once**, with one project delivery: no per-agent copies, rows, signals or archive inbox files. This is not `broadcast` (which stays rejected).
  1009. - Every other non-retired agent of the project that was registered when the message was sent sees it in `fetch_inbox` (and `resource://inbox/...`, `am robot inbox`) with `"via": "project"`. An agent that joins later is not handed the backlog; project history stays readable through threads, `fetch_topic` and search. An agent whose `contact_policy` is `block_all` opts out, and a direct to/cc/bcc delivery to the same agent takes precedence so nothing appears twice.
  1010. - Read and acknowledgement state is per agent and recorded lazily: `fetch_inbox` read receipts, `mark_message_read`, `acknowledge_message` and `mark_all_read` record only the calling agent's state. `get_message_delivery_receipt` reports the delivery under `project_mailbox` with each visible agent's read/ack state.
  1011. - It can be combined with named recipients in `to`/`cc`, cannot be `bcc`, and can only name the sender's own project. Replies may address it too.
  1012. - Retention treats a project message as settled only after every agent that can see it has read it (and acknowledged it when required). Archive reconstruction restores the delivery from the canonical message's `to`/`cc` envelope, and salvage restores the per-agent receipts.
  1013. - Restart-safe monitors see it too: a project delivery appends one event to the durable `fetch_inbox_events` / `am inbox-events` cursor ledger, and each visible agent's page includes it (`"kind": "project"`) under the same single cursor.
  1014. - `am robot overview` and `am robot overview --counts` include each visible agent's unread, urgent-unread, and overdue acknowledgement obligations. One shared message can therefore count for several agents, while a named recipient is counted only once; generating the overview never creates receipts or marks mail read.
  1015. ### Across Different Repos
  1016. - **Option A (single project bus):** Register both repos under the same `project_key`. Keep reservation patterns specific (`frontend/**` vs `backend/**`).
  1017. - **Option B (separate projects):** Each repo has its own `project_key`. Link two agents with a contact handshake, then address the other agent with a project-qualified name:
  1018. ```
  1019. macro_contact_handshake(project_key="/abs/path/frontend", requester="BlueLake",
  1020. target="GreenCastle", to_project="/abs/path/backend",
  1021. auto_accept=true)
  1022. send_message(project_key="/abs/path/frontend", sender_name="BlueLake",
  1023. to=["GreenCastle@/abs/path/backend"], subject="API change",
  1024. body_md="Please bump /v2.", thread_id="br-124", ack_required=true)
  1025. ```
  1026. - `Name@project` takes the project's human key or its slug (as returned by `ensure_project` and listed by `resource://projects`), and so does the older `project:<project>#Name` form. The qualified name is resolved in that project only and is never auto-registered.
  1027. - The message is delivered only while an approved, unexpired contact link exists between the two agents (in either direction). Without one the send fails with `CONTACT_REQUIRED` and a ready `macro_contact_handshake` call; a blocked link or a `block_all` recipient fails with `CONTACT_BLOCKED`. This holds even when the recipient's own contact policy is `open`.
  1028. - The message is stored in the recipient's project, so the recipient reads it with its ordinary `fetch_inbox`, acknowledges it with `acknowledge_message`, and answers with `reply_message` in its own project. A default reply to a message from another project goes back to the original sender in that sender's project over the same link.
  1029. - One message lives in one project: a send may address agents of one other project, or local agents, but not both (`INVALID_ARGUMENT`; send twice instead).
  1030. - A plain name still addresses only the sender's project. Naming a contact from another project, or an agent registered in another project of the same product, is refused with `CROSS_PROJECT_RECIPIENT` (the error carries the qualified address to use); no same-name placeholder is created.
  1031. The product bus (`fetch_inbox_product`, `search_messages_product`, `summarize_thread_product`) aggregates an agent's inboxes and threads across the linked projects.
  1032. ### External Git Coordination (opt-in)
  1033. `mcp-agent-mail` serializes its own in-process git shell-outs via
  1034. per-repo `flock` on `<repo>/.git/am.git-serialize.lock`. External tools
  1035. (wrapper scripts, editor integrations, CI) can honor the same sentinel
  1036. by invoking git through `scripts/git-with-amlock.sh`:
  1037. ```bash
  1038. # one-time: put the wrapper on PATH
  1039. install -m755 scripts/git-with-amlock.sh ~/.local/bin/git-with-amlock
  1040. # per-shell: resolve an "am-aware" git for automation
  1041. export GIT_BIN="$(command -v git-with-amlock || command -v git)"
  1042. alias gitam='"$GIT_BIN"'
  1043. # your automation invokes gitam instead of git:
  1044. gitam status
  1045. gitam commit -m 'synced'
  1046. ```
  1047. **Scope of the mitigation:**
  1048. - mcp-agent-mail's own in-process calls → always coordinated
  1049. (automatic).
  1050. - External tools that opt into the wrapper → coordinated.
  1051. - Your IDE running `git commit` directly, with no wrapper →
  1052. **still races**. The only complete mitigation for that case is to
  1053. set `AM_GIT_BINARY` to a safe git binary, or upgrade/downgrade the
  1054. system git. See the
  1055. [Known-bad git versions](#known-bad-git-versions) section.
  1056. The wrapper honors `AM_GIT_BINARY` for binary selection and
  1057. `AM_GIT_FLOCK_TIMEOUT_SECS` (default 60s) for the bounded wait cap.
  1058. Exit code 75 (`EX_TEMPFAIL`) signals a flock timeout.
  1059. ### With Beads Task Tracking
  1060. Agent Mail pairs with [Beads](https://github.com/Dicklesworthstone/beads_rust) (`br`) for dependency-aware task selection:
  1061. 1. **Pick ready work:** `br ready --json` (choose highest priority, no blockers)
  1062. 2. **Reserve edit surface:** `file_reservation_paths(..., reason="br-123")`
  1063. 3. **Announce start:** `send_message(..., thread_id="br-123", subject="[br-123] Start: <title>", ack_required=true)`
  1064. 4. **Work and update:** Reply in-thread with progress
  1065. 5. **Complete and release:** `br close 123`, `release_file_reservations(...)`, final Mail reply
  1066. Use the Beads issue ID (`br-123`) as the Mail `thread_id` and prefix message subjects with `[br-123]` to keep everything linked.
  1067. ## Web UI
  1068. The server includes a lightweight, server-rendered web UI for humans at `/mail/`. Agents should continue using MCP tools and resources; the web UI is for human review and oversight. Use `/mail/*` for mailbox and task oversight. The authenticated live browser TUI mirror at `/web-dashboard` remains deferred and is not a supported surface.
  1069. The project website separately embeds the real production `DashboardScreen` through
  1070. `crates/mcp-agent-mail-dashboard-wasm/` and FrankenTUI's browser renderer. That surface
  1071. is an interactive, read-only public replay: six SQLite aggregate counts are real, while
  1072. all names, paths, messages, and replay events are synthetic. It does not connect to a
  1073. visitor's mailbox or expose the deferred `/mail/ws-input` path. The deterministic opening
  1074. frame carries 192 synthetic history events, 500 agent rows, 41 project rows, and 200
  1075. contact rows so the production dashboard opens at the same busy visual density as a real
  1076. operator session without publishing mailbox content. See
  1077. [`docs/SPEC-browser-parity-contract-deferred.md`](docs/SPEC-browser-parity-contract-deferred.md)
  1078. for the shipped replay boundary and the still-deferred live parity contract.
  1079. ### Routes
  1080. | Route | What You See |
  1081. |-------|-------------|
  1082. | `/mail/` and `/mail/unified-inbox` | Unified inbox across all projects with importance filtering and related-project context |
  1083. | `/mail/projects` | Project inventory page for browsing into one mailbox at a time |
  1084. | `/mail/{project}` | Project overview with the six most recently active conversations, search, agent roster, and quick links |
  1085. | `/mail/{project}/threads` | All project conversations, with subjects, canonical IDs, message counts, timestamps, and older/newer navigation |
  1086. | `/mail/{project}/inbox/{agent}` | Reverse-chronological inbox for one agent with pagination and mark-read actions |
  1087. | `/mail/{project}/message/{id}` | Full message detail with metadata, recipients, thread preview, and attachments |
  1088. | `/mail/{project}/thread/{thread_id}` | Full thread rendering with chronological conversation context |
  1089. | `/mail/{project}/thread?thread_id=...` | Query-form conversation link, including dot-only identifiers that browsers normalize in URL paths |
  1090. | `/mail/{project}/search?q=...` | Search V3-powered query route with field filters (`subject:foo`, `body:"multi word"`) |
  1091. | `/mail/{project}/file_reservations` | Active and historical file reservations |
  1092. | `/mail/{project}/attachments` | Messages with attachments and provenance |
  1093. | `/mail/{project}/overseer/compose` | Human compose form for pushing high-priority instructions to agents |
  1094. | `/mail/api/unified-inbox` | JSON feed backing the unified inbox |
  1095. | `/mail/api/projects/{project}/agents` | JSON roster for one project |
  1096. | `/mail/archive/*` | Archive browser and time-travel routes |
  1097. Auth: HTTP authentication is off when neither `HTTP_BEARER_TOKEN` nor JWT auth
  1098. is configured; this supports the trusted-local deployment described in
  1099. [`SECURITY.md`](SECURITY.md). Configure a bearer token or JWT before exposing the
  1100. server beyond loopback. With auth configured,
  1101. `HTTP_ALLOW_LOCALHOST_UNAUTHENTICATED=true` explicitly permits the guarded local
  1102. bypass; it is not needed for no-token operation. These transport controls do not
  1103. isolate hostile clients sharing the same OS account or bearer credential.
  1104. ### Browsing conversations
  1105. Open **Threads** or **Browse all threads** from a project to browse its conversations
  1106. without searching first. The browser defaults to 50 conversations per page;
  1107. `?limit=...` accepts up to 200. Conversations are ordered by their latest message's
  1108. timestamp and message ID. Older/newer links retain a message watermark, so new
  1109. messages do not move conversations between pages during a browsing session. Use
  1110. **Latest conversations** to refresh that view.
  1111. Each nonblank explicit thread ID is preserved exactly. A message with no thread
  1112. ID uses its decimal message ID as its conversation key, joining replies with that
  1113. same key. Numeric keys never expand into an unrelated named conversation; `42`
  1114. and `0042` stay distinct. Thread links in search, message details, and inboxes use
  1115. the same identity rules and remain scoped to the message's project.
  1116. The conversation list reads indexed message metadata and hydrates only the selected
  1117. subjects. It does not load message bodies or change read/acknowledgement receipts.
  1118. The dynamic browser is omitted from static-export project pages.
  1119. ### Human Overseer
  1120. Sometimes you need to redirect agents mid-session. The **Overseer** compose form at `/mail/{project}/overseer/compose` lets humans send high-priority messages directly to any combination of agents.
  1121. Overseer messages:
  1122. - Come from a special `HumanOverseer` agent (program: `WebUI`, model: `Human`)
  1123. - Are always marked **high importance** so they stand out in agent inboxes
  1124. - Bypass normal contact policies so you can always reach any agent
  1125. - Include a preamble instructing agents to pause current work, handle the request, then resume
  1126. Agents see overseer messages in their normal inbox via `fetch_inbox` or `resource://inbox/{name}?project=<abs-path>`. They can reply in-thread like any other message. The send writes the message to SQLite; the background DB-to-archive reconciler then writes its Git archive copy, in the same envelope as agent-to-agent mail, so it is auditable once reconciled.
  1127. ---
  1128. ## Deployment Validation
  1129. ```bash
  1130. # Export a bundle
  1131. am share export -o /tmp/agent-mail-bundle --no-zip
  1132. # Verify a live deployment against the bundle
  1133. am share deploy verify-live https://example.github.io/agent-mail \
  1134. --bundle /tmp/agent-mail-bundle \
  1135. --json > /tmp/verify-live.json
  1136. # Inspect verdict
  1137. jq '.verdict, .summary, .config' /tmp/verify-live.json
  1138. ```
  1139. Exit codes: `0` = pass, `1` = fail.
  1140. ---
  1141. ## Configuration
  1142. All configuration via environment variables. The server reads them at startup via `Config::from_env()`.
  1143. | Variable | Default | Description |
  1144. |----------|---------|-------------|
  1145. | `AM_INTERFACE_MODE` | (unset = MCP) | `mcp` or `cli` |
  1146. | `HTTP_HOST` | `127.0.0.1` | Bind address |
  1147. | `HTTP_PORT` | `8765` | Bind port |
  1148. | `HTTP_PATH` | `/mcp/` | MCP base path |
  1149. | `HTTP_BEARER_TOKEN` | (unset unless configured, including via `.env`) | HTTP bearer credential; with JWT auth also disabled, an unset token leaves HTTP authentication off for trusted-local operation |
  1150. | `HTTP_ALLOWED_HOSTS` | (none) | Comma-separated extra `Host:` header values the HTTP listener accepts, in addition to the bind host, its loopback variant, and `localhost`. Set this (or pass repeatable `serve-http --allowed-host <HOST>`) to reach the `/mail` web UI via a hostname or reverse proxy instead of getting an HTTP 421. Empty by default (loopback-only). |
  1151. | `DATABASE_URL` | `<STORAGE_ROOT>/storage.sqlite3` | SQLite connection URL. Unset, the database lives inside `STORAGE_ROOT`; an explicit relative path is resolved against the working directory |
  1152. | `AM_CACHE_PROFILE` | `balanced` | Cache budget preset: `conservative`, `balanced`, or `high-memory` |
  1153. | `DATABASE_CACHE_BUDGET_KB` | profile-derived `524288` | Total SQLite page-cache budget across pooled connections, clamped to 16 MiB..4 GiB |
  1154. | `AM_READ_CACHE_ENTRIES_PER_CATEGORY` | profile-derived `16384` | Per-category read-cache entry cap, clamped to 1,024..1,048,576 |
  1155. | `STORAGE_ROOT` | XDG-aware (see below) | Archive root directory |
  1156. | `ALLOW_EPHEMERAL_PROJECTS_IN_DEFAULT_STORAGE` | `false` | Permit `/tmp`-style project roots in the default global mailbox archive. Prefer a per-run `STORAGE_ROOT` instead. |
  1157. | `LOG_LEVEL` | `info` | Minimum level for Agent Mail's own logs: `trace`, `debug`, `info`, `warn`, `error` or `off` (`WARNING`/`CRITICAL` accepted). Dependencies log at `warn` unless `LOG_LEVEL` is stricter. `RUST_LOG`, when set, replaces it for `mcp-agent-mail` (and for `am` with `AM_ALLOW_DEBUG_STARTUP_LOGS=1`) |
  1158. | `TUI_ENABLED` | `true` | Interactive TUI toggle |
  1159. | `TUI_HIGH_CONTRAST` | `false` | Accessibility mode |
  1160. | `AM_TUI_TOAST_ENABLED` | `true` | Enable toast notifications |
  1161. | `AM_TUI_TOAST_SEVERITY` | `info` | Minimum toast severity (`info`/`warning`/`error`/`off`) |
  1162. | `AM_TUI_TOAST_POSITION` | `top-right` | Toast stack position |
  1163. | `AM_TUI_TOAST_MAX_VISIBLE` | `3` | Max visible toasts at once |
  1164. | `AM_TUI_TOAST_INFO_DISMISS_SECS` | `5` | Info toast auto-dismiss timeout |
  1165. | `AM_TUI_TOAST_WARN_DISMISS_SECS` | `8` | Warning toast auto-dismiss timeout |
  1166. | `AM_TUI_TOAST_ERROR_DISMISS_SECS` | `15` | Error toast auto-dismiss timeout |
  1167. | `AM_TUI_THREAD_PAGE_SIZE` | `20` | Thread conversation page size |
  1168. | `AM_TUI_THREAD_GUIDES` | `rounded` (theme default) | Thread tree guide style (`ascii`/`unicode`/`bold`/`double`/`rounded`) |
  1169. | `AM_TUI_COACH_HINTS_ENABLED` | `true` | Enable contextual coach-hint notifications |
  1170. | `AM_TUI_EFFECTS` | `true` | Enable text/animation effects |
  1171. | `AM_TUI_AMBIENT` | `subtle` | Ambient mode (`off`/`subtle`/`full`) |
  1172. | `AM_TUI_FULL_REDRAW_MAX_SECS` | `30` | Wall-clock bound (seconds) for a guaranteed full TUI redraw that repairs terminal desync (e.g. after a mux pane swap). Each forced redraw resends the whole screen, so lower values cost terminal output; `<= 0` disables the bound |
  1173. | `AM_IDEMPOTENCY_RETENTION_SECS` | `86400` | Retention window in seconds for `file_reservation_paths` idempotency keys; invalid or non-positive values fall back to 24 hours |
  1174. | `WORKTREES_ENABLED` | `false` | Enables build slots and the product bus (`ensure_product`, `products_link`, `search_messages_product`, `fetch_inbox_product`, `summarize_thread_product`); while off, those tools return `FEATURE_DISABLED`. `GIT_IDENTITY_ENABLED=true` also enables them |
  1175. | `INTEGRITY_CHECK_ON_STARTUP` | `true` | Run the boot-time `PRAGMA quick_check`; `false` skips only this probe and leaves the background guard enabled |
  1176. | `INTEGRITY_GUARD_ENABLED` | `true` | Enable periodic integrity checks, automatic backups and database maintenance; `false` stops that worker |
  1177. | `INTEGRITY_QUICK_CHECK_INTERVAL_SECONDS` | `300` | Background quick-check cadence and initial delay when startup checking is skipped (minimum 1 second) |
  1178. | `INTEGRITY_CHECK_INTERVAL_HOURS` | `1` | Periodic full integrity-check cadence (`0` disables scheduled full checks; quick checks remain enabled) |
  1179. | `STARTUP_READINESS_BIND_TIMEOUT_SECS` | `20` | Max seconds to wait for DB readiness before binding the listener anyway (`/healthz` stays up while the DB warms) |
  1180. | `DB_MAINTENANCE_ENABLED` | `true` | Enable checkpoint/ANALYZE/VACUUM/journal-size maintenance within the integrity guard; `false` leaves checks and backups enabled |
  1181. | `DB_CHECKPOINT_INTERVAL_SECS` | `300` | Passive WAL checkpoint cadence (`0` disables that op) |
  1182. | `DB_ANALYZE_INTERVAL_SECS` | `21600` | `ANALYZE` planner-stats refresh cadence (`0` disables) |
  1183. | `DB_VACUUM_INTERVAL_SECS` | `86400` | Isolated ATC telemetry sidecar `VACUUM` cadence (`0` disables). Main-mailbox compaction requires a stopped server and explicit `am doctor vacuum --yes`. |
  1184. | `DB_JOURNAL_SIZE_LIMIT_BYTES` | `16777216` | `journal_size_limit` WAL truncation cap (16 MiB); an automatic checkpoint over the cap truncates the WAL |
  1185. | `AM_GIT_BINARY` | (resolver) | Override the `git` binary for all in-process shell-outs (mitigates the git 2.51.0 index race) |
  1186. | `AM_GIT_FLOCK_TIMEOUT_SECS` | `60` | Bounded wait for the per-repo `am.git-serialize.lock` before a git shell-out fails `EX_TEMPFAIL` (75) |
  1187. | `AGENT_MAIL_GUARD_PUSH_MAX_COMMITS` | `2000` | Most commits the pre-push guard inspects per pushed ref (newest first); past it the scan is truncated and fails closed. `0` removes the bound |
  1188. | `AGENT_MAIL_GUARD_PUSH_MAX_PATHS` | `100000` | Most `--name-status` path records the pre-push guard reads per pushed ref before truncating. `0` removes the bound |
  1189. | `AGENT_MAIL_GUARD_PUSH_TIMEOUT_SECS` | `120` | Wall-clock budget for the whole pre-push path scan; git is killed at the deadline and the scan is truncated. `0` removes the bound |
  1190. For the full list of 100+ env vars, see `crates/mcp-agent-mail-core/src/config.rs`.
  1191. The feature-flag and tuning-knob registry is inspectable at runtime with
  1192. `am flags list` (`--subsystem atc`, `--set` for non-defaults, `--json`) and
  1193. `am flags explain <VAR>`; see [docs/FLAGS_REGISTRY.md](docs/FLAGS_REGISTRY.md).
  1194. ### Air Traffic Control (ATC) configuration
  1195. ATC is the built-in operator that reviews agent liveness, detects reservation
  1196. deadlocks, and can send probe/advisory mail or reclaim reservations. It is **on
  1197. by default**, but since v0.3.31 its executor defaults to `shadow`, so a fresh
  1198. install observes and decides without writing any mail. The whole surface is
  1199. the `AM_ATC_*` family below; `am config atc` (alias of `am flags list
  1200. --subsystem atc`) prints each variable's effective value and whether it came
  1201. from the process environment, the persisted config file, a project `.env`, or
  1202. the compiled default. Restart the server after changing any of them except the
  1203. two canary-report paths.
  1204. | Variable | Default | Meaning |
  1205. |----------|---------|---------|
  1206. | `AM_ATC_ENABLED` | `true` | Master switch. `false` stops the operator loop and makes the engine ignore every hook: no probes, advisories, reservation releases, population hydration, or experience rows. Liveness surfaces then fall back to the database `last_active_ts` written by ordinary tool calls ("passive liveness only"), and reservations held by crashed agents are reclaimed only by TTL expiry. Also forced `false` by `ATC_LEARNING_DISABLED`. |
  1207. | `AM_ATC_EXECUTOR_MODE` | `shadow` | How decisions become side effects: `shadow` (observe/decide, emit nothing durable), `dry_run` (same, suppressed effects shown in the operator snapshot), `canary` (send activity-check / acknowledgment-request mail, never force-release reservations), `live` (everything, including releases). Unknown values fall back to `shadow`. |
  1208. | `AM_ATC_WRITE_MODE` | `off` | Experience-ledger persistence: `off`, `shadow` (trace-log only), `live` (append rows to the ATC sidecar). Durable rows additionally need `canary`/`live` executor mode and a file-backed DB. Forced `off` by `ATC_LEARNING_DISABLED`. |
  1209. | `AM_ATC_PROBE_INTERVAL_SECS` | `120` | Operator tick interval and per-agent liveness-probe cadence (floor 5; ticks never run faster than 250 ms). |
  1210. | `AM_ATC_ADVISORY_COOLDOWN_SECS` | `300` | Minimum seconds between advisories to the same agent (floor 10). |
  1211. | `AM_ATC_SUMMARY_INTERVAL_SECS` | `300` | Seconds between ATC summary lines in the console/log (floor 10). |
  1212. | `AM_ATC_SAFE_MODE_RECOVERY_COUNT` | `20` | Consecutive correct liveness predictions required to leave safe mode (floor 1). |
  1213. | `AM_ATC_EPROCESS_THRESHOLD` | `20` | E-process calibration alert threshold; crossing it enters safe mode (`20` ≈ 5% significance). Finite, `> 0`. |
  1214. | `AM_ATC_CUSUM_THRESHOLD` | `5` | CUSUM change-point threshold on prediction error. Finite, `> 0`. |
  1215. | `AM_ATC_CUSUM_DELTA` | `0.1` | Minimum shift the CUSUM detector is tuned to catch. Finite, `> 0`. |
  1216. | `AM_ATC_LEDGER_CAPACITY` | `1000` | In-memory evidence-ledger ring buffer size (entries) behind transparency cards (floor 10). |
  1217. | `AM_ATC_SUSPICION_K` | `3` | Rhythm-based liveness factor: an agent is suspect once its silence exceeds its expected gap by `k` standard deviations; lower probes sooner. Finite, `> 0`. |
  1218. | `AM_ATC_EXPERIENCE_MAX_ROWS` | `50000` | Ceiling on raw `atc_experiences` rows in the sidecar; the retention sweep rolls up/evicts above it. `0` disables. |
  1219. | `AM_ATC_RETENTION_SWEEP_INTERVAL_SECS` | `900` | Cadence of the sweep enforcing the ceiling above. `0` disables the sweep. |
  1220. | `AM_ATC_POPULATION_RECENCY_SECS` | `604800` | Only agents active within this window (7 days) are hydrated into ATC on cold start / periodic sync. Lower it on mailboxes with many recently-active identities to bound cold-start effect bursts. `0` hydrates nobody. |
  1221. | `AM_ATC_POPULATION_LIMIT` | `4096` | Maximum agents materialized per population sync, most recently active first (clamped to `1..=65536`). |
  1222. | `AM_ATC_POLICY_BUNDLE_PATH` | `(unset)` | Path to a liveness policy bundle JSON to load instead of the compiled-in baseline. |
  1223. | `AM_ATC_CANARY_REPORT_PATH` | `(unset)` | Exact canary perf-gate report JSON for `am robot atc` / the TUI; default `<STORAGE_ROOT>/atc_perf_gate/latest_canary_report.json`. Read per render. |
  1224. | `AM_ATC_CANARY_REPORT_DIR` | `(unset)` | Directory holding `latest_canary_report.json`; `AM_ATC_CANARY_REPORT_PATH` wins if both are set. Read per render. |
  1225. | `ATC_LEARNING_DISABLED` | `false` | Hard kill switch (no `AM_` prefix, kept for compatibility): forces `AM_ATC_ENABLED=false` and `AM_ATC_WRITE_MODE=off` regardless of the values above. Dynamic: `am flags on ATC_LEARNING_DISABLED`. |
  1226. The file `<STORAGE_ROOT>/.atc_kill_switch` additionally stops durable ATC writes
  1227. without a restart (checked every operator tick).
  1228. To keep ATC's observation but stop it from writing mail, leave the default
  1229. `AM_ATC_EXECUTOR_MODE=shadow`; to switch ATC off entirely use
  1230. `AM_ATC_ENABLED=false`.
  1231. For operations guidance and troubleshooting, see
  1232. [docs/OPERATOR_RUNBOOK.md](docs/OPERATOR_RUNBOOK.md). For copy-paste operator
  1233. recipes, see [docs/OPERATOR_COOKBOOK.md](docs/OPERATOR_COOKBOOK.md).
  1234. ### Registration Proof Gate (optional, off by default)
  1235. By default Agent Mail uses a **self-asserted** identity model: any caller may
  1236. `register_agent` under any well-formed name. That is the right trade-off for
  1237. local, trusted, single-operator multi-agent coordination and remains the
  1238. default — nothing changes unless you opt in.
  1239. Deployments where agents come from **different operators or less-trusted
  1240. sources** can require a cryptographic proof before any identity is persisted.
  1241. When enabled, `register_agent` (and every other path that can implicitly
  1242. create an agent row, including `send_message` / `request_contact`
  1243. auto-registration and the CLI) demands a `registration_proof` argument: a JSON
  1244. bundle binding the final agent name, project key, program, model, capability
  1245. scope, an `issued_at`/`expires_at` window, and a single-use nonce, signed
  1246. (Ed25519) by one of your configured trust anchors. Verification is
  1247. **fail-closed**: a missing, malformed, untrusted, expired, replayed, or
  1248. mismatched proof rejects the registration and writes nothing. Consumed nonces
  1249. are persisted in the database, so replay protection survives server restarts.
  1250. | Variable | Default | Description |
  1251. |----------|---------|-------------|
  1252. | `AM_REGISTRATION_PROOF_GATE_ENABLED` | `false` | Master switch. Off = self-asserted identity (unchanged default). |
  1253. | `AM_REGISTRATION_PROOF_TRUSTED_KEYS` | (empty) | Comma-separated base64 Ed25519 public keys (32 raw bytes each). Enabled with no keys = every registration fails closed. |
  1254. | `AM_REGISTRATION_PROOF_MAX_LIFETIME_SECONDS` | `300` | Maximum allowed `expires_at - issued_at` window. |
  1255. | `AM_REGISTRATION_PROOF_CLOCK_SKEW_SECONDS` | `60` | Clock-skew tolerance for the validity window. |
  1256. | `AM_REGISTRATION_PROOF_REQUIRE_NONCE` | `true` | Require and consume a single-use nonce per proof (replay protection). |
  1257. The canonical signing bytes (v2) are explicit, so issuers can be written in any
  1258. language. They are LF-terminated lines:
  1259. 1. `agent-mail-registration-proof:v2`.
  1260. 2. `identity`, `project_key`, `program` and `model`, in that order. Each is
  1261. `label=N:value`, where N is the value's UTF-8 byte length; values are neither
  1262. escaped nor trimmed.
  1263. 3. `capabilities=N` with the count, then one `capability=N:value` line per
  1264. capability (trimmed, non-empty, sorted by bytes, de-duplicated).
  1265. 4. `issued_at=N` and `expires_at=N` as decimal i64.
  1266. 5. `nonce=N:value`.
  1267. v1 proofs (`field=value` lines without length prefixes) are rejected; reissue
  1268. them. Verification is expressed through a
  1269. pluggable `ProofVerifier` trait (`crates/mcp-agent-mail-tools/src/proof_gate.rs`);
  1270. the shipped implementation is the Ed25519 trust-anchor verifier, and external
  1271. verifier backends can be added without touching registration call sites.
  1272. ---
  1273. ## Architecture
  1274. Cargo workspace with strict dependency layering:
  1275. ```text
  1276. MCP Client / Operator / Browser
  1277. │ │ │
  1278. ├─ stdio ───┤ │
  1279. ├─ HTTP ───┼───────────┤
  1280. ▼ ▼ ▼
  1281. mcp-agent-mail-server
  1282. │
  1283. ┌────────────┼────────────┬─────────────┐
  1284. ▼ ▼ ▼ ▼
  1285. 45 MCP Tools 25 Resources TUI Web UI
  1286. │ │ │ │
  1287. └────────────┴──────┬─────┴─────────────┘
  1288. ▼
  1289. mcp-agent-mail-tools
  1290. │
  1291. ┌──────────┼──────────┬──────────────┐
  1292. ▼ ▼ ▼ ▼
  1293. mcp-agent-mail-db storage search-core share/export
  1294. (SQLite index) (Git) (query path) (bundles/static)
  1295. │
  1296. mcp-agent-mail-core
  1297. (config, models, errors, metrics)
  1298. ```
  1299. ### Workspace Structure
  1300. ```
  1301. mcp_agent_mail_rust/
  1302. ├── Cargo.toml # Workspace root (12 member crates; dashboard-wasm is excluded and built standalone)
  1303. ├── crates/
  1304. │ ├── mcp-agent-mail-core/ # Zero-dep: config, models, errors, metrics
  1305. │ ├── mcp-agent-mail-db/ # SQLite schema, queries, pool, cache, Search V3 integration
  1306. │ ├── mcp-agent-mail-storage/ # Git archive, commit coalescer, notification signals
  1307. │ ├── mcp-agent-mail-search-core/ # Pluggable search traits
  1308. │ ├── mcp-agent-mail-guard/ # Pre-commit guard, reservation enforcement
  1309. │ ├── mcp-agent-mail-share/ # Snapshot, scrub, bundle, crypto, export
  1310. │ ├── mcp-agent-mail-tools/ # 45 MCP tool implementations (9 clusters)
  1311. │ ├── mcp-agent-mail-server/ # HTTP/MCP runtime, dispatch, TUI (16 screens)
  1312. │ ├── mcp-agent-mail/ # Server binary (mcp-agent-mail)
  1313. │ ├── mcp-agent-mail-cli/ # CLI binary (am) with robot mode
  1314. │ ├── mcp-agent-mail-test-helpers/ # Shared test scaffolding
  1315. │ ├── mcp-agent-mail-dashboard-wasm/ # Standalone public DashboardScreen WASM replay + safe exporter (excluded from the workspace)
  1316. │ └── mcp-agent-mail-conformance/ # Python parity tests
  1317. ├── experimental/
  1318. │ └── mcp-agent-mail-wasm/ # Parked standalone WASM/browser prototype
  1319. ├── tests/e2e/ # End-to-end test scripts
  1320. ├── scripts/ # CLI integration tests, utilities
  1321. ├── docs/ # ADRs, specs, runbooks, migration guides
  1322. ├── install.sh # Unix installer
  1323. ├── install.ps1 # Windows PowerShell installer
  1324. └── rust-toolchain.toml # Nightly toolchain requirement
  1325. ```
  1326. ### Canonical File Layout
  1327. The runtime uses several paths whose defaults have evolved across versions.
  1328. This table resolves the three-way ambiguity:
  1329. | Path | Purpose | Notes |
  1330. |------|---------|-------|
  1331. | `~/.mcp_agent_mail_git_mailbox_repo/` | Legacy archive root (pre-v1) | No longer created; honored if it already exists on disk |
  1332. | `$XDG_DATA_HOME/mcp-agent-mail/git_mailbox_repo/` | Current archive root (`STORAGE_ROOT` default) | `~/.local/share/mcp-agent-mail/git_mailbox_repo/` on most Linux systems |
  1333. | `$XDG_CONFIG_HOME/mcp-agent-mail/config.env` | Canonical env file (installer writes here) | `~/.config/mcp-agent-mail/config.env` on most Linux systems |
  1334. | `$XDG_CONFIG_HOME/mcp-agent-mail/.env` | Compatibility env file | Checked when `config.env` is absent |
  1335. | `~/.mcp_agent_mail/.env` | Legacy env file | Checked after XDG paths |
  1336. | `<STORAGE_ROOT>/storage.sqlite3` | Runtime database (`DATABASE_URL` default) | Inside the archive root unless `DATABASE_URL` is set |
  1337. The `STORAGE_ROOT` resolution logic: if the legacy path `~/.mcp_agent_mail_git_mailbox_repo/`
  1338. exists on disk, it is used for backward compatibility. Otherwise the XDG data
  1339. directory is preferred. Override with `STORAGE_ROOT=/your/path` in the environment.
  1340. ### Storage Layout (inside STORAGE_ROOT)
  1341. ```
  1342. $STORAGE_ROOT/ # e.g. ~/.local/share/mcp-agent-mail/git_mailbox_repo/
  1343. ├── projects/
  1344. │ └── {project_slug}/
  1345. │ ├── .git/ # Per-project git repository
  1346. │ ├── messages/
  1347. │ │ └── {YYYY}/{MM}/ # Date-partitioned canonical messages
  1348. │ ├── agents/
  1349. │ │ └── {agent_name}/
  1350. │ │ ├── inbox/ # Agent inbox copies
  1351. │ │ └── outbox/ # Agent outbox copies
  1352. │ ├── build_slots/ # Build slot leases (JSON)
  1353. │ └── file_reservations/ # Reservation artifacts
  1354. └── .archive.lock # Global advisory lock
  1355. ```
  1356. ### Key Design Decisions
  1357. - **Git-backed archive** for human auditability; SQLite as fast index
  1358. - **WAL mode** with PRAGMA tuning and connection pooling for concurrent access
  1359. - **Write-behind cache** with dual-indexed ReadCache and deferred touch batching (30s flush)
  1360. - **Async git commit coalescer** (write-behind queue) to avoid commit storms
  1361. - **i64 microseconds** for all timestamps (no `chrono::NaiveDateTime` in storage layer)
  1362. - **Search V3**: portable lexical retrieval uses the local `TantivyBridge`; optional FrankenSearch semantic retrieval and hybrid fusion compile through the `hybrid` feature and run only with `AM_SEARCH_SEMANTIC_ENABLED=true`. Portable builds and the default runtime keep the deterministic lexical path.
  1363. - **Compatibility testing** against intentionally retained Python wire contracts,
  1364. plus Rust-native durability and behavior fixtures. The Rust implementation is
  1365. authoritative; legacy parity never overrides reliability, security, bounded
  1366. work, or structured-concurrency invariants.
  1367. - **Advisory file reservations** with symmetric fnmatch, archive reading, and rename handling
  1368. - **`#![forbid(unsafe_code)]`** across all crates
  1369. - **Query-only read lane** — direct mailbox reads use an existing live SQLite pool and do not wait for archive reconstruction or write-behind coalescing
  1370. - **Evidence-bearing timeouts** — timeout responses and health output expose the measured stage and latency evidence instead of assigning generic database blame
  1371. - **asupersync exclusively** for all async operations (no Tokio, reqwest, hyper, or axum)
  1372. ---
  1373. ## ATC Learning Implementation Map
  1374. > **Validated ATC learning loop — rollout remains gated by write mode.**
  1375. >
  1376. > ATC now has a durable live-learning path: hot-path `atc_note_*` hooks append experience rows, real runtime signals resolve outcomes, rollups/retention/replay are implemented, and robot/TUI surfaces consume the shared live operator snapshot. `AM_ATC_WRITE_MODE` still gates rollout (`off` default, `shadow` for observation, `live` for durable writes), so broader promotion remains operator-controlled rather than always-on. Treat the map below as the current ownership contract and rollout/hardening guide, not as a future-only blueprint.
  1377. The `br-0qt6e` ATC learning work is intentionally cross-cutting, but it should not be cross-owned. The codebase already has the right seams; future implementation should deepen those seams instead of spreading ATC state across tools, UI layers, or ad-hoc SQL in random crates.
  1378. ### Ownership by crate and module
  1379. | Area | Current modules | Owns | Must not own |
  1380. |------|------------------|------|--------------|
  1381. | Core contract | `crates/mcp-agent-mail-core/src/experience.rs`, `evidence_ledger.rs`, `atc_baseline.rs`, `config.rs` | Canonical `ExperienceRow` shape, lifecycle transitions, feature vector/extension schema, decision/evidence identifiers, frozen pre-learning baseline, env/config surface | SQL persistence, archive writes, UI-specific formatting |
  1382. | SQLite persistence | `crates/mcp-agent-mail-db/src/schema.rs` (v16 `atc_experiences`, `atc_experience_rollups`) | Durable raw experience rows, open-resolution lookup indexes, stratum rollups, retention/compaction mechanics, future insert/resolve/query APIs | Decision policy, ATC tick logic, web/TUI rendering |
  1383. | Git/archive boundary | `crates/mcp-agent-mail-storage/src/lib.rs` | Human-auditable artifact writes, WBQ/commit coalescing, selected policy/audit artifacts when explicitly promoted | Raw ATC experience exhaust; the current `WriteOp` surface intentionally handles message, reservation, profile, and notification artifacts, not learning-row mirroring |
  1384. | ATC runtime | `crates/mcp-agent-mail-server/src/atc.rs` | Decision engine, liveness/conflict/routing/calibration math, policy bundle loading, global ATC singletons, tick loop, outcome feedback, summary snapshots | Direct SQLite schema ownership, long-lived CLI state, alternate UI-specific models |
  1385. | Runtime wiring | `crates/mcp-agent-mail-server/src/lib.rs` | Bootstrapping via `init_global_atc()` and `start_atc_operator_runtime()`, tool-dispatch liveness hooks via `atc_register_agent_with_project()` and `atc_observe_activity_with_project()`, shared ATC operator snapshot publication | Per-tool bespoke learning persistence; tool handlers should emit domain facts, not become the learning store |
  1386. | Agent/operator surfaces | `crates/mcp-agent-mail-cli/src/robot.rs`, `crates/mcp-agent-mail-server/src/tui_screens/system_health.rs`, `tui_web_dashboard.rs`, `/mail/ws-state` | Rendering the shared ATC/operator snapshot for robot and live TUI consumers; reserved browser-mirror modules stay read-only/non-owning and fall back to local heuristics only when live server state is unavailable | Independent ATC truth, separate persistence, or duplicate learning logic |
  1387. | Tool/resource layer | `crates/mcp-agent-mail-tools/src/*`, `crates/mcp-agent-mail-tools/src/resources.rs` | Normal tool/resource contracts for mailbox coordination; ATC-adjacent work should surface through existing runtime hooks and shared snapshots | Owning ATC learning state machines or experience-row lifecycle rules |
  1388. ### Append and resolution hooks
  1389. - Session/bootstrap and liveness hooks already land at the server dispatch boundary: successful `register_agent` and `macro_start_session` calls register agents with ATC, and tool execution updates ATC activity timestamps.
  1390. - The durable append path now belongs in that same server/runtime seam, not inside individual UIs. Message and reservation learning hooks flow from the tool-result/event boundary in `mcp-agent-mail-server/src/lib.rs` into the ATC-facing note functions in `mcp-agent-mail-server/src/atc.rs`: `atc_note_message_sent()`, `atc_note_message_received()`, `atc_note_reservation_granted()`, `atc_note_reservation_released()`, and `atc_note_reservation_conflicts()`.
  1391. - Outcome resolution now flows through the server ATC runtime: message outcomes are resolved from the tool-result boundary (`record_atc_message_outcome_from_tool_payload_with_pool` in `mcp-agent-mail-server/src/lib.rs`) plus the overdue/retention sweeps, with the DB crate owning the actual row mutation and rollup updates. (`atc_record_outcome()` in `atc.rs` is the in-memory engine hook and currently has no production caller.)
  1392. - `/mail/ws-state` polling, `am robot atc`, the ATC TUI screen, and the System Health screen stay snapshot-driven consumers of `atc_operator_snapshot()` / `atc_summary()`, not alternate sources of learning state. The deferred `/web-dashboard/*` browser mirror is intentionally outside the supported live ATC surface today.
  1393. ### Hot path vs. cold path boundaries
  1394. - Hot path: `mcp-agent-mail-server/src/atc.rs`, the tool-dispatch hook in `mcp-agent-mail-server/src/lib.rs`, and the DB append/resolve calls behind `AM_ATC_WRITE_MODE`. This path must stay append-friendly, bounded, and free of Git write amplification.
  1395. - Warm path: ATC operator snapshots, `/mail/ws-state` polling, `am robot atc`, and the TUI/System Health surfaces. These consumers should read already-computed ATC state and only fall back to local heuristics when the live server snapshot is unavailable. The deferred `/web-dashboard/*` mirror is intentionally excluded from the live warm path until a future resurrection effort lands.
  1396. - Cold path: promoted policy bundles, transparency cards, replay artifacts, and operator-facing audit bundles. These may be written through `mcp-agent-mail-storage`, but only after they are intentionally compacted and selected.
  1397. - Explicit non-owner boundary: `mcp-agent-mail-search-core`, share/export, and the WASM/browser mirror are consumers or transport layers. They should not become the canonical home of ATC learning policy, persistence, or attribution logic.
  1398. ### Verification ownership
  1399. - `crates/mcp-agent-mail-core/src/experience.rs`: unit/property coverage for lifecycle validity, feature-vector stability, serialization, and idempotent resolution transitions.
  1400. - `crates/mcp-agent-mail-db/src/schema.rs` plus the ATC DB query modules: migration coverage, insert/resolve semantics, rollup correctness, retention/compaction tests, and replay/reconstruct safety.
  1401. - `crates/mcp-agent-mail-server/src/atc.rs`: decision math, policy-bundle loading, safe-mode transitions, tick budgeting, and feedback/calibration tests.
  1402. - `crates/mcp-agent-mail-server/src/lib.rs`, `tui_ws_state.rs`, `tui_screens/system_health.rs`, and `crates/mcp-agent-mail-cli/src/robot.rs`: snapshot publication, route contracts, robot fallback behavior, and operator-surface rendering tests.
  1403. - `tests/e2e/` and performance harnesses: live-server E2E plus soak/perf coverage validate that ATC learning stays low-write-amplification and does not regress request/tick budgets.
  1404. ### Rollout and hardening priorities
  1405. 1. Keep `mcp-agent-mail-core` as the schema-and-policy contract so experience/evidence/config changes stay centralized and reviewable.
  1406. 2. Preserve `mcp-agent-mail-db` as the only durable ATC mutation/query surface for append, resolve, rollup, retention, and replay behavior.
  1407. 3. Continue routing real runtime events through `atc_note_*` and the server-side outcome-resolution path instead of duplicating learning logic in tools, UIs, or ad-hoc SQL paths.
  1408. 4. Keep robot, TUI, and browser/dashboard surfaces snapshot-driven consumers of `atc_operator_snapshot()` rather than alternate sources of ATC truth.
  1409. 5. Land remaining rollout/default-flip, data-minimization, and operator-hardening work on top of the existing live path rather than reopening seam ownership questions.
  1410. ---
  1411. ## Core Data Model
  1412. | Type | Role |
  1413. |------|------|
  1414. | `Project` | Stable identity for one codebase, keyed by absolute path and slug |
  1415. | `Product` | Cross-project grouping for search, inbox aggregation, and routing |
  1416. | `Agent` | Registered worker identity with name, program, model, policy, and task metadata |
  1417. | `Message` | Canonical envelope for subject, body, importance, thread, attachments, and recipients |
  1418. | `Recipient` | Delivery metadata for `to`/`cc`/`bcc`, read state, and acknowledgement state |
  1419. | `Thread` | Logical conversation identifier spanning replies and summaries |
  1420. | `FileReservation` | Advisory lease over file paths/globs with TTL, exclusivity, and reason |
  1421. | `BuildSlot` | Named lease used to serialize build-heavy work on a shared checkout |
  1422. | `ToolMetrics` | Per-tool latency, error, and call-count telemetry used by TUI, CLI, and diagnostics |
  1423. The important boundary is this: Git stores the durable human-auditable artifacts, while SQLite stores the queryable operational state. Every surface in the project is built around that split.
  1424. ---
  1425. ## How the System Works
  1426. ### Write Path
  1427. 1. An MCP tool call, CLI command, web overseer action, or guard hook enters the runtime.
  1428. 2. Inputs are normalized and validated against project identity, agent names, and policy constraints.
  1429. 3. The SQLite layer performs the indexed mutation: insert/update rows, enforce invariants, and emit IDs/timestamps.
  1430. 4. The storage layer writes canonical Markdown/JSON artifacts into the per-project archive.
  1431. 5. The commit coalescer batches archive updates so bursts of activity do not become commit storms.
  1432. 6. Metrics and event streams are updated so TUI, robot, and web surfaces all observe the same fresh state.
  1433. ### Read Path
  1434. 1. A resource read, robot command, TUI view, or web request asks for mailbox or tooling state.
  1435. 2. The server resolves scope: project, agent, product, thread, search query, or tooling view.
  1436. 3. For direct state, an existing live SQLite mailbox answers through a query-only lane; it does not wait for archive reconstruction or the write-behind coalescer, and a read request does not create a missing project. `fetch_inbox` performs its optional read-receipt update separately after the bounded read. For search, Search V3 plans the query and executes the appropriate lexical route, or the semantic/hybrid route when the `feature = "hybrid"` build path is compiled in and `AM_SEARCH_SEMANTIC_ENABLED=true`.
  1437. 4. The result is rendered as MCP JSON, robot `toon`/`json`/`md`, TUI widgets, or HTML under `/mail/`.
  1438. That consistency comes from a shared DB + archive + metrics pipeline. The TUI, web UI, robot CLI, and MCP resources are separate renderers over the same underlying state.
  1439. ---
  1440. ## Search Architecture
  1441. Search V3 is not an afterthought bolted onto mailbox rows. It is a dedicated query path with shared planning and diagnostics:
  1442. - Queries are normalized, classified, and routed through a unified search service.
  1443. - Lexical mode provides the baseline contract and diagnostics surface; semantic and hybrid modes extend that contract in a `hybrid`-feature build with `AM_SEARCH_SEMANTIC_ENABLED=true`. Otherwise a semantic, hybrid, or auto request runs lexical.
  1444. - Candidate budgeting and fusion keep broad natural-language queries from exploding while preserving exact-match strength for identifiers and short phrases.
  1445. - The same search path serves MCP tools, `am mail search`, `am robot search`, TUI search, and web UI search routes.
  1446. - Empty or non-searchable queries route through a deterministic SQL plan before Search V3 candidate retrieval. Legacy SQLite FTS artifacts still exist for migration hygiene and cleanup, but the current search architecture is Search V3 plus that deterministic SQL plan, not a hidden FTS fallback.
  1447. The dedicated `mcp-agent-mail-search-core` crate exists specifically so search planning and backends can evolve without entangling the rest of the mailbox stack.
  1448. ---
  1449. ## Coordination Algorithms and Safety Invariants
  1450. - **Explicit recipients only.** `send_message` keeps a `broadcast` field for schema compatibility, but `broadcast=true` is intentionally rejected so agents cannot spam every other agent by default.
  1451. - **Project isolation first.** Agent names are only meaningful inside a project unless a contact link or product bus path explicitly bridges them.
  1452. - **Symmetric reservation matching.** File reservation conflicts use symmetric glob overlap checks, so `src/**` conflicts with `src/lib.rs` in either direction.
  1453. - **TTL instead of forever-locks.** Reservations and build slots expire, which makes the system robust to crashed or vanished agents.
  1454. - **Wrong-surface denial.** MCP-only and CLI-only commands fail deterministically when invoked through the wrong entrypoint, reducing automation footguns.
  1455. - **Idempotent session bootstrapping.** `ensure_project`, `register_agent`, and the session macros are designed so agents can safely retry startup without creating duplicate identity state.
  1456. - **Durable monitor cursors.** Inbox-event consumers advance a recipient delivery cursor only after handling an oldest-first page; a message ID is never a safe cursor substitute.
  1457. - **Contact approval as policy, not convention.** Cross-project messaging is gated by explicit contact workflows and per-agent contact policies.
  1458. These are the design rules that let many agents share one checkout without immediately degenerating into chaos.
  1459. ---
  1460. ## Consistency and Recovery Model
  1461. - **SQLite is the live operational state.** MCP tools, resources, the TUI, the web UI, and robot/CLI reads use SQLite for current inboxes, message IDs, read/ack state, reservations, agents, products, and search planning.
  1462. - **Git is the durable artifact ledger.** Canonical messages, inbox/outbox copies, reservation files, and agent profiles are written as files under per-project archives so the mailbox remains human-auditable and recoverable.
  1463. - **Concurrent writes are queued, not hand-merged.** Parallel agents can send to the same thread at the same time; the server/DB layer serializes the indexed mutations, and the archive write-behind queue plus commit coalescer batches the corresponding Git artifact writes. There is no workflow where two agents create a Git merge conflict and a human resolver has to pick the winning message.
  1464. - **Reservation artifacts have a database generation.** A new physical SQLite database gets a new generation token, so its reservation row IDs cannot overwrite a prior generation's archive artifacts. Foreign stamped artifacts remain inspectable without being treated as live parity drift.
  1465. - **Repair is not reconstruct.** `am doctor repair` is the in-place hygiene path. `am doctor reconstruct` is the archive-first rebuild path when SQLite is no longer trustworthy.
  1466. - **Backups are first-class.** `archive save`, doctor backups, and restore flows all exist because operational recovery is part of the product, not a manual afterthought.
  1467. - **Stale lock cleanup is expected.** Guard hooks, archive lock management, and doctor checks assume agents crash and processes die unexpectedly.
  1468. If the live layer gets sick, the durable ledger can rebuild it.
  1469. ---
  1470. ## Comparison vs. Alternatives
  1471. | Feature | MCP Agent Mail | Shared Files / Lockfiles | Custom MCP Tools | Chat-Based Coordination |
  1472. |---------|---------------|-------------------------|------------------|------------------------|
  1473. | Agent identity & discovery | Persistent names, profiles, directory queries | None | Manual | Ephemeral |
  1474. | Threaded messaging | Subjects, CC/BCC, ack, importance, search | N/A | Build yourself | Linear chat, no structure |
  1475. | File reservation / advisory locks | Glob patterns, TTL, exclusive/shared, pre-commit guard | Lockfiles (no TTL, no glob) | Build yourself | None |
  1476. | Audit trail | Full Git history of all communication | File timestamps | Depends | Chat logs (if saved) |
  1477. | Cross-repo coordination | Product bus, contact system | Manual | Build yourself | Manual |
  1478. | Search | Search V3 (lexical in release binaries; semantic + hybrid in default-feature source builds) | `grep` | Build yourself | Limited |
  1479. | Operational visibility | 16-screen TUI, robot CLI, metrics | None | None | None |
  1480. | Token efficiency | Messages stored externally, not in context | Files in context | Varies | All in context |
  1481. ---
  1482. ## Development
  1483. ```bash
  1484. # Quality gates
  1485. cargo fmt --check
  1486. cargo clippy --workspace --all-targets -- -D warnings
  1487. cargo check --workspace --all-targets
  1488. cargo test --workspace
  1489. # Compatibility and Rust-native conformance tests
  1490. cargo test -p mcp-agent-mail-conformance
  1491. # Run specific crate tests
  1492. cargo test -p mcp-agent-mail-db
  1493. cargo test -p mcp-agent-mail-tools
  1494. cargo test -p mcp-agent-mail-server
  1495. # E2E tests
  1496. tests/e2e/test_stdio.sh # MCP stdio transport
  1497. tests/e2e/test_http.sh # HTTP transport
  1498. tests/e2e/test_guard.sh # Pre-commit guard
  1499. tests/e2e/test_macros.sh # Macro tools
  1500. tests/e2e/test_share.sh # Share/export
  1501. tests/e2e/test_dual_mode.sh # Mode switching
  1502. scripts/e2e_cli.sh # CLI integration (99 assertions)
  1503. # Native E2E runner (authoritative path)
  1504. am e2e list
  1505. am e2e run --project . # all suites
  1506. am e2e run --project . stdio http # selected suites
  1507. am e2e run --project . --include tui_ # pattern include
  1508. am e2e run --project . tui_full_traversal # traversal + flash + soak regression gate
  1509. am e2e run --project . --tag reliability --release-scorecard # reliability release gate
  1510. # ^ runs every @tags: reliability suite (incl. the incident_corpus harness) and writes
  1511. # tests/artifacts/release_scorecard/<ts>/release_scorecard.json (per-suite rows +
  1512. # per-incident-class rows with anchors + a combined release_ready verdict)
  1513. # Legacy compatibility shim (deprecated primary path)
  1514. ./scripts/e2e_test.sh stdio
  1515. # rollback guard: AM_E2E_FORCE_LEGACY=1 ./scripts/e2e_test.sh stdio
  1516. # Benchmarks
  1517. cargo bench -p mcp-agent-mail
  1518. # Multi-agent builds: offload heavy cargo work through rch
  1519. rch exec -- cargo check --workspace --all-targets
  1520. # Shared-checkout verification lanes: acquire a build slot, run through rch, preserve logs
  1521. am verify cargo-check --path . --agent AgentName --block-on-conflicts
  1522. am verify cargo-clippy --path . --agent AgentName --block-on-conflicts
  1523. am verify cargo-test --path . --agent AgentName --block-on-conflicts
  1524. am verify e2e-stdio --path . --agent AgentName --block-on-conflicts
  1525. am verify bench-quick --path . --agent AgentName --block-on-conflicts
  1526. ```
  1527. `am verify` is a thin `am-run` lane mapper. It always shows the exact command, uses a `verify-*` build slot even when `WORKTREES_ENABLED` is not set in the shell, routes cargo-heavy work through `rch exec -- ...`, and writes `command.json`, `stdout.log`, `stderr.log`, `exit_code.txt`, and `result.json` under `STORAGE_ROOT/artifacts/verify/<timestamp>-<lane>/` unless `--artifact-dir` is supplied.
  1528. `result.json` includes `rch_proof.status`, `child_exit_code`, and the final proof `exit_code`. For `rch exec` lanes, a zero-exit child is only green when the captured output includes a positive remote-execution marker. Local fallback or missing remote proof fails closed, writes `rch_proof_failure.txt`, and best-effort captures `rch_status_workers.json` plus `rch_queue.json` so operators can distinguish a remote test failure from transport/sync/fleet degradation.
  1529. Release evidence for robot/doctor fields must prove the installed `am` binary, not only the source-built test binary. For parity-sensitive fields such as `forensic_timeline`, search-index health, recovery status, artifact links, next actions, and redaction, run the installed-binary parity gate against the release candidate installed on the same host or remote worker:
  1530. ```bash
  1531. AM_INSTALLED_BINARY_PARITY_BIN=/path/to/installed/am \
  1532. rch exec -- cargo test -p mcp-agent-mail-cli --test it \
  1533. integration_runs::installed_binary_parity_probe_compares_source_and_installed_am -- --ignored --nocapture
  1534. ```
  1535. The gate writes `tests/artifacts/installed_binary_parity/<run>/parity_report.json` with one pass/fail row per required JSON path, redacted source/installed values, value-mismatch status, and redacted command metadata. If the candidate lacks fields that source tests rely on, or returns different required values, the report is red and the release is not closed. A local direct `am doctor check --json` or `am robot ... --format json` probe is useful for quick inspection, but it is not sufficient release evidence unless paired with this parity report and an `rch exec -- ...` cargo proof.
  1536. Use `--dry-run` to inspect the lane without running it. Use `--no-block-on-conflicts` only when the slot conflict is understood and you intentionally want advisory behavior.
  1537. ### E2E Entrypoint Policy (T9.9)
  1538. - Native `am e2e` is authoritative for operator and CI invocation.
  1539. - `scripts/e2e_test.sh` remains compatibility-only and emits deprecation guidance.
  1540. - Rollback condition: set `AM_E2E_FORCE_LEGACY=1` only if native runner regression is confirmed.
  1541. Verification checklist:
  1542. - `am e2e list` and `am e2e run --project . <suite>` succeed for targeted suites.
  1543. - Artifact repro commands reference `am e2e run` (not script-first commands).
  1544. - CI/release docs and runbooks do not present `scripts/e2e_test.sh` as the primary command.
  1545. ### Verification Realism Policy
  1546. The canonical realism and closure policy lives in [docs/VERIFICATION_COVERAGE_LEDGER.md](/data/projects/mcp_agent_mail_rust/docs/VERIFICATION_COVERAGE_LEDGER.md).
  1547. - `R0` and `R1` are the lanes that carry closure weight.
  1548. - `R2` and `R3` substitutes are second-best evidence and must name their compensating real-path coverage.
  1549. - Stub-only lanes do not close transport, persistence, install/update, search-quality, LLM-quality, crypto/share, or operator-surface claims by themselves.
  1550. ### Key Dependencies
  1551. | Crate | Purpose |
  1552. |-------|---------|
  1553. | `asupersync` | Structured async runtime (channels, sync, regions, HTTP, testing) |
  1554. | `fastmcp-rust` / `fastmcp` | MCP protocol implementation (JSON-RPC, stdio, HTTP transport) |
  1555. | `sqlmodel_rust` / `sqlmodel` | SQLite ORM (schema, queries, migrations, pool) |
  1556. | `frankentui` | TUI rendering (widgets, themes, accessibility, markdown, syntax highlighting) |
  1557. | `frankensearch` | Hybrid search engine (lexical + semantic, two-tier fusion, reranking) |
  1558. | `br` (external CLI) | Issue tracking integration |
  1559. | `toon` | Token-efficient compact encoding for robot mode output |
  1560. ---
  1561. ## Performance and Benchmarking
  1562. The repository carries both stress tests and reproducible benchmark baselines. The two serve different purposes:
  1563. - **Stress suites** answer “does the system stay correct under ugly concurrency?”
  1564. - **Bench suites** answer “how fast is the operator and mailbox path right now?”
  1565. ### Native `am bench`
  1566. The native CLI benchmark runner is built around four categories in `crates/mcp-agent-mail-cli/src/bench.rs`:
  1567. | Category | Built-in cases | What it measures |
  1568. |----------|----------------|------------------|
  1569. | Startup | `help` | Pure CLI startup and argument parsing |
  1570. | Analysis | `lint`, `typecheck` | Cost of native quality commands |
  1571. | Stub encoder | `stub_encode_1k`, `stub_encode_10k`, `stub_encode_100k` | Compact encoding subprocess path |
  1572. | Operational | `mail_inbox`, `mail_send`, `mail_send_no_atc`, `mail_send_atc_shadow`, `mail_send_atc_live`, `mail_search`, `robot_status`, `doctor_check`, `message_count`, `agents_list` | Real mailbox/operator workflows over a seeded DB (`am bench --list` is authoritative) |
  1573. ### Checked-In Baselines
  1574. These numbers come from [`benches/BUDGETS.md`](benches/BUDGETS.md), which records dated benchmark baselines and budgets.
  1575. #### CLI Operational Baselines (`am bench --quick`, 2026-02-09)
  1576. | Command | Baseline mean | Budget |
  1577. |---------|---------------|--------|
  1578. | `am --help` | 4.2ms | < 10ms |

Lines 2,001–2,451 are not shown. The link to the file on GitHub has every line.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.