agentleFS
amyodovamyodov/yet-another-agentic-chat/AGENTS.md

yet-another-agentic-chat

AGENTS.md5 starsChanged 52 days agoMITView on GitHub

See README.md for what YAAC does. This file is about working on it. README.md also tracks features — what is in the current version and what is planned. Update its Status section whenever you ship or defer something; it is the only record, as there is no separate roadmap or issue tracker. ZMQ's own words stay ZMQ's own, prefixed: zmq_routing_id, not a YAAC synonym for it. "frontend" and "backend" are relative to the MCP tool surface, not web layers. "channel"…

  • Installs packages
  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.

    Of the AGENTS.md files we read, the 35,040 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository2 other files it gives its agents.

The file

We split this AGENTS.md into the rules it gives an agent

4 rules. About 0 are common, 1 is distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    No nested ifs where a flat shape exists: prefer match/case or an if/elif/else chain.

    line 62
  2. Very specific:

    Write "ROUTER_MANDATORY raises EHOSTUNREACH for an unknown routing id, so the send fails instead of being dropped", not "a stuck queue must …

    line 463
  3. Distinctive:

    Commit messages: the subject names the change, the body gives the reason and what it displaces.

    line 465
  4. Very specific:

    Probing must not bind: If list_channels bound, a session that only looked would become hat and drop the endpoint when the call returned.

    line 487

≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

AGENTS.md

See README.md for what YAAC does. This file is about working on it.

README.md also tracks features — what is in the current version and what is planned. Update its Status section whenever you ship or defer something; it is the only record, as there is no separate roadmap or issue tracker.

Vocabulary

TermMeaning
frontendThe MCP server: tool definitions, no state.
backendIn-process module: ZMQ sockets, inbox, roster cache.
hatWhichever backend won the bind. Confers the job of passing messages along, and nothing else.
participantAny backend on a channel, wearing the hat or not.
membershipOne (channel, name) a process holds. A process may hold several.
connection idA membership's routing id, returned by join_channel and used to address it.
channelA named conversation. Addressing, not isolation.
nameA user-chosen name within a channel. Raw UTF-8.
routing_idULID set as the ZMQ ROUTING_ID; zmq_routing_id on the wire.
address{name, zmq_routing_id}. How participants are named on the wire — never a bare string.

ZMQ's own words stay ZMQ's own, prefixed: zmq_routing_id, not a YAAC synonym for it.

"frontend" and "backend" are relative to the MCP tool surface, not web layers. "channel" always means a YAAC channel, never the Claude Code feature of the same name.

Layout

src/yaac/
  frontend.py   MCP tool definitions, and the tool a hook calls
  backend.py    sockets, bind election, receive loops, connection state
  hat.py        routing table, whois, roster, bounce, session directory
  protocol.py   envelope + control messages, serialization
  notices.py    each session's own WebSocket: what a watcher streams and a hook asks
  directory.py  the client side of `sessions` — who is running here, asked at the rendezvous point
  hook.py       `yaac-hook`, the program Codex runs because its hooks cannot call a tool
  wake.py       starting a turn in an idle Codex session through its app-server, and keeping its thread loaded
  messaging_socket.py  delivering into the Claude Code session that started us, through the inbox socket it exports
  processes.py  the process tree: ancestry, and command lines, on all three OSes
  chat.py       the terminal client's entry point; imports textual only once it knows it is there
  chat_app.py   the terminal client itself

The last six are all delivery: getting a message in front of a session that did not ask for it. Nothing in them touches the wire — the hat is not involved and there is no second process to find, because the hook runs inside the process that owns the inbox.

Python 3.14+, uv, ruff. Dependencies are pyzmq and mcp — ask before adding another.

To keep a file out of git, put -nogit in its name (notes-nogit.md, probe-nogit.py). .gitignore matches *-nogit*, so don't add per-file entries to it.

Releases go through the releasing skill, and only on the user's explicit request — never on the assistant's initiative. Changes to the tool definitions in frontend.py follow the updating-mcp-tools skill: descriptions first, then it regenerates docs/tools.md — that file is generated and never edited by hand.

Line length 120, code and prose alike. Use current syntax freely: match/case, walrus, PEP 758 except A, B:. Annotations are lazy in 3.14, so no from __future__ import annotations.

No nested ifs where a flat shape exists: prefer match/case or an if/elif/else chain. Use the else clause of try, for, and while when it says what the code means — for/else is exactly "the loop found nothing".

Verified facts

Measured here, not assumed. Re-measure before contradicting.

ROUTER_NOTIFY is unusable and fails in a way that looks fine. It is a libzmq draft option. The constant imports, so a check for hasattr(zmq, "ROUTER_NOTIFY") passes, but setsockopt rejects it with EINVAL — released wheels bundle libzmq built without drafts (zmq.has('draft') is False). True anywhere pip install pyzmq is used.

Replacements, both non-draft:

  • Arrival: the participant's DEALER monitor fires EVENT_CONNECTED, and the participant re-sends hello. Covers the first connect too, so whoever picks up the hat next is told who is present without asking.
  • Departure: ROUTER_MANDATORY raises EHOSTUNREACH when sending to a routing id that left. Eviction is lazy, detected on the first failed send — which is when we want to bounce anyway.

A tool list that changes with state is not one clients will follow, so every tool is listed from the start. YAAC listed two tools while dormant and published five more on the first join with notifications/tools/list_changed. That broke from both ends, and both are properties of the world. MCP 2026-07-28 says list endpoints "no longer vary per-connection", and delivers change notifications only to a client that opened subscriptions/listen. And Claude Code, which did honour the notification when it was measured here in August 2026, stopped reaching newly published tools once MCP tools moved behind ToolSearch: anthropics/claude-code#66084 (open; /mcp reconnect or a restart), and #88483 for Claude Desktop, which never rebuilds the deferred pool at all. Reported from the field in October 2026: a session joined, was told the tools were being published, and never saw send. A reconnect cannot fix that, because it starts a fresh dormant server that publishes them the same way.

Codex never re-read the list either (openai/codex#10105), and was special-cased by clientInfo.name until then -- detection that 2026-07-28 removes with initialize itself. The answer the spec gives, "explicit, server-minted handles passed as ordinary tool arguments", is what connection_id and peer_secret already were. So an on-air tool called before a join answers NOT_JOINED from a Backend that was never constructed, and the one tool still withheld from the listing -- the hook's -- is withheld from every client alike.

Cross-client delivery is measured, not argued: a Claude Code session and a Codex session exchanged messages both ways on one channel, each running its own server process.

MCP cannot push into an idle session — read off the specification rather than measured here, and true of revision 2026-07-28, re-checked on 2026-08-30 against the changelog with nothing changed. Every other entry in this section is a property of the world and stays true; this one describes a document under active revision and will expire, so read the changelog rather than this line. What it says today is that the direction of travel is away from push: a server may not initiate a request at all, and the schema has no ServerRequest type to do it with; sampling/createMessage, roots and logging are deprecated with a twelve-month window; and the one long-lived server→client stream, subscriptions/listen, carries a closed set of four change notifications, three with empty parameters and one carrying a URI and no body. Delivery is therefore pull-only — from MCP. What reaches an idle session comes through a door the host leaves open, and two do: Codex an app-server, Claude Code an inbox socket. The tool descriptions carry the reminder to call check_inbox for every client that leaves neither, and join_channel's result says which kind of session this is.

The revision that introduced this went further in the same direction than the wording above suggests: it removed initialize and protocol-level sessions entirely, and Multi Round-Trip Requests replaced server-initiated requests outright — where a server once sent sampling/createMessage, roots/list or elicitation/create, it now returns resultType: "input_required" and waits for the client to retry. Every exchange is therefore begun by the client, by construction rather than by omission.

The roadmap's Triggers & Events working group is about telling a client that work it started has finished, not about unsolicited content; the one proposal for re-entering a model's turn (SEP-2495) is open, unsponsored, and answered by a maintainer with "the host owns the loop". That sentence is the whole reason delivery is a hook — a hook is a host mechanism, and the host is what owns the loop.

A Claude Code hook can call a tool on the MCP server it is bundled with, in the same process. type: "mcp_tool" names a server and a tool; for a plugin-bundled server the name is the scoped plugin:<plugin>:<server>, not the bare key under mcpServers. The tool's text content is then read exactly as a command hook's stdout: valid JSON is taken as a decision object, anything else as plain output. So hook_report returns a JSON string rather than a result dict — a tool result shaped like a tool result parses fine, matches no decision field, and is silently discarded.

Measured live on 2026-08-28, with the hooks wired into .claude/settings.local.json against a server running from the working tree: a message sent by a second process arrived beside the next tool result on PreToolUse, check_inbox then found the inbox empty, and Stop reopened a turn that had already ended. So the one undocumented assumption holds -- a tool absent from every tools/list can still be called by name from a hook. For a server that is not plugin-bundled the server field is the bare key, yaac, and Claude Code's file watcher picks up a new hooks block with no restart.

Codex reads the same contract, with one different door. codex-cli 0.147.0 supports command and mcp_tool handlers -- prompt and agent are parsed and skipped -- and joins an MCP tool's text blocks before running them through the same output parser a command hook's stdout goes through, so returning a JSON string works there for the same reason. Its binary carries hookSpecificOutput, additionalContext and hookEventName, so most events are answered identically. Stop is the exception: its output schema admits no hookSpecificOutput, and text reaches the model as decision: "block" with a reason, which Codex turns into a continuation prompt acting as a new user prompt. Stop is spelled the same in both clients, so hook_report takes the contract as an argument the hooks file sets rather than inferring it. Consumption still makes a loop impossible: the continuation re-fires Stop, which finds nothing, so stop_hook_active needs no consulting.

Claude Code captures an MCP server's stderr only while it connects. It keeps a log per server under ~/Library/Caches/claude-cli-nodejs/<project>/mcp-logs-<server>/, and the startup line is there as "stderr: [yaac] dormant ..." -- but on air as ... from a real join appears in no file this project has ever written. So the log is not a place a running server can leave a trace for anything else to watch, and waking an idle session needs a channel or a socket of our own rather than a tail. This is a client's internal cache layout, undocumented and free to move.

That is why nothing about delivery touches the wire. The hook runs inside the process that owns the inbox, so there is no second process to find, no socket to open, no session identifier to pass around, and the hat is not involved at all. An earlier attempt had every backend push an unread tally to the hat so an out-of-process hook could ask it — the hat kept a ledger of everyone's mailbox, which is not its job and cannot be kept true.

Where a hook's additionalContext lands depends on the event: next to the tool result for PreToolUse and PostToolUse, alongside the prompt for UserPromptSubmit, and at the end of the turn for Stop — where, the documentation says, "the conversation continues so Claude can act on the feedback". Stop is therefore the one that can reopen a finished turn. Text placed there is in the model's context, which makes it a delivery and not a notification: hook_report takes the messages, exactly as check_inbox does, and a second Stop then finds an empty inbox, which is what makes a loop impossible without any stop_hook_active bookkeeping.

SessionStart is the fourth, and the only one that answers the opposite problem: not that something arrived, but that what the model held is gone. Read off the documentation on 2026-08-30 — it fires with source in startup, resume, clear, compact, fork, and for that event "Claude Code adds plain-text stdout as context that Claude can see and act on". So the plugin matches compact alone, since no other source means anything was lost, and hook_report hands back the memberships instead of the inbox. The mail is deliberately left unread there: a session that cannot present its peer_secret cannot act on a message yet. PreCompact and PostCompact also exist, but the documentation does not say either injects context, and SessionStart says it does.

A peer older than a control message answers nothing, and only ordering reveals it. A 0.3.0 hat logs ignoring control message 'unread?' and never replies, so a lone query waits out its whole timeout. This is the trap sessions walked straight into in 0.5.1, where it cost a hook the full timeout on every event for as long as an older peer kept the hat. The technique: pair a new query with one every version has answered — channels — and rely on a ROUTER handling one peer's messages in order, so a channels reply arriving with no answer before it proves the peer read the new query and had nothing to say. Measured against a real 0.3.0 hat, that turned a 1.0 s timeout into 0.13 s. directory.py now does this, and test_directory.py holds a hat that answers channels and not sessions so the next wire addition inherits the test rather than the bug.

A stderr nobody reads wedges the process, and diagnostics are where that gets forgotten. A client that pipes a server's stderr and stops reading it leaves a 64 KB kernel buffer and no more -- and Claude Code is exactly such a client, since it captures a server's stderr only while it connects. The write that fills the buffer blocks, and if it blocks inside the event loop the session stops answering entirely: measured on 2026-09-01, 3000 warnings wedged a real server for good, and every tool call afterwards reported Transport closed, including the one somebody would call to diagnose it. logging.shutdown flushes handlers at interpreter exit, so a wedged stream also stops the process from ever exiting -- the same fact met on the way out.

The flood is not hypothetical: a hat logs when an operator message is one it does not know, and a Codex hook asks on every tool call, so a mixed-version net produces it unaided. Two answers, both needed. configure_logging puts a bounded queue and a writer thread between the logger and the stream, so a line is dropped rather than waited on -- a radio that stops relaying because nobody read its log has failed at the only job it has. And the hat says an unknown op once rather than once per message, since a newer peer questioning an older hat is ordinary rather than alarming.

A connect to a closed local port does not fail fast on Windows. Measured in the field by Vadim: walking eight candidate ports cost 8.2 s on every hook event, where the same walk on macOS and Linux is immediate -- ECONNREFUSED comes back on the loopback at once there. This is why nothing in YAAC probes a range of addresses: the notice socket takes whatever port the kernel offers and publishes it, and the hat's sessions directory is where a hook reads it.

Two other reasons the derivation it replaced was wrong, both properties of the world rather than of our code. Codex keeps one mcp_servers block for a whole machine, so any per-session value put in its env is the same value for every session -- a key derived from it made all of them answer for one inbox. And Node's crypto declines to truncate blake2s, so a digest Python produced could not be reproduced there without hand-writing the hash in another language.

A session's app-server is its own forebear, so the wake address is discovered rather than configured. Measured on 2026-08-29: an MCP server started for a thread appears in the process tree as codex app-server --listen ws://… -> uv run … yaac -> python … yaac, and a tool the model runs is a direct child of the same app-server. So wake.serving() walks this process's ancestry and reads the address off the command line of the nearest forebear carrying --listen. Verified end to end with a real app-server starting a real MCP server: no variable in the environment, and ws://127.0.0.1:4607 found.

This answers which app-server, not merely which ones are listening -- so two at once are no more ambiguous than one, and the permanent codex app-server daemon pid-update-loop, which every Codex install runs and which carries no --listen, is never a candidate. What must not be matched is the program name: that daemon would answer to it always.

Since codex-cli 0.163, plain codex sessions are not under such an app-server. Measured on 2026-10-19: every Codex session's YAAC server was a child of one shared, Codex-managed app-server, codex app-server --remote-control --listen unix:// --managed-daemon, and the terminal UIs were thin clients of it. It answers the same WebSocket handshake and initialize over its Unix socket, but that socket sits at an internal path (/tmp/codex-daemon-<uid>/<hash> on macOS) and nothing hands it to a server, so YAAC does not reach for it. A user-started codex app-server --listen ws://… with sessions attached by codex --remote ws://… still starts MCP servers as its own children on 0.163, measured the same day, so serving() finds it as before. A session under a Codex app-server with no WebSocket is therefore told so when it joins (Backend.stranded()), with that recipe.

The reverse relation does not hold, and was checked first: an app-server with no thread running has no descendants at all, and a hook is not obviously among them either -- project-local hooks are skipped entirely until the project is trusted in ~/.codex/config.toml, which is silent except for one line in the app-server's stderr.

Codex gives each MCP tool call the thread id its hook receives. Measured on 2026-10-19 with codex-cli 0.163.0, under both plain codex and a user-started codex app-server --listen ws://127.0.0.1:53588 with codex --remote ws://127.0.0.1:53588: two open user threads started two separate YAAC server processes beneath one app-server. Calling each thread's tool reached its own process. The shared managed daemon shares neither the YAAC process nor its inbox between those threads.

Neither initialize nor the server's environment carried a thread id. initialize.clientInfo identified codex-mcp-client, version 0.163.0; the environment had no CODEX_THREAD_ID. Each tools/call instead carried params._meta.threadId, including direct app-server tool calls and ordinary model-generated calls. The latter also carried equal sessionId, x-codex-turn-metadata.thread_id, and x-codex-turn-metadata.session_id values. The installed MCP SDK exposes the metadata as the mapping Context.request_context.meta.

Scratch hooks under both setups received the same value as session_id. Restarting the app-server and running codex resume <id> or codex --remote ws://… resume <id> preserved it, confirmed by SessionStart with source: "resume", UserPromptSubmit, and Stop. Those resume probes establish identity stability, not MCP reconnection: their tools were unavailable after restart. join_channel reads threadId before its first hello, publishes it as the directory's client, and sets the wake thread, so the hook matches exactly even when several Codex threads or a Claude Code session share the working directory. No per-session config or process-tree guess is needed for identity on the measured version; older versions were not measured.

Codex reports whether a thread is idle, with a short lag at turn start. Measured on 2026-10-20 with codex-cli 0.163.0 against an isolated WebSocket app-server: thread/read with {threadId, includeTurns: false} returned result.thread.status: {"type": "idle"} before a turn, then {"type": "active", "activeFlags": []} while its model worked, then {"type": "idle"} after completion. The same initialized connection received thread/status/changed notifications with params: {threadId, status: {...}} for the active and idle transitions. An unknown thread id returned error.code: -32600 and message: "thread not loaded: <id>".

The status check is not an atomic guard on queueing: immediately after turn/start returned a turn with status: "inProgress", one thread/read still reported idle; the next sample, 0.5 seconds later, reported active. Queueing one prompt per arrival on a busy thread leaves prompts waiting after the hooks or check_inbox have already read their mail. Wake scheduling therefore needs process-level coalescing and an unread check after waiting for idle. The start-of-turn lag and the race between checking status and queueing can still permit an occasional empty wake; this API does not offer atomic enqueue-only-if-idle semantics.

Codex unloads a thread nobody is subscribed to, and a subscription is a connection held open. Reported from the field on Windows in November 2026 -- joined Codex threads dropping off their channels after a while idle -- and measured here on 2026-11-05 with codex-cli 0.166.0, against isolated app-servers started with -c thread_unload_delay_secs=60, which takes effect. A thread with no subscribed connection unloaded 60-70 s after its last activity. thread/status/changed to notLoaded and thread/closed were sent to every connection, subscribed or not, and the thread's MCP server processes exited, YAAC's included. The default delay is 1800 s.

thread/resume {threadId, excludeTurns: true} subscribes the connection that sends it, including on a thread that is already loaded. There it returned 2.4 KB and left the thread's MCP server processes running, with the same PIDs. thread/unsubscribe answers {"status": "unsubscribed"}, and so does closing the connection. A connection held this way for 420 s kept the thread loaded, and the thread unloaded about 70 s after the connection let go. Over that time the app-server sent no WebSocket pings and split no message across frames. The held connection receives the thread's whole event stream: one short turn was 265 frames and 73 KB, nearly all item/agentMessage/delta. A thread with no turns has nothing on disk to resume, and once unloaded its thread/resume is refused.

End to end, with YAAC from the working tree as the thread's MCP server: the model joined a channel, every other client disconnected, and the thread stayed loaded past three delays. After leave_channel it unloaded 70 s later. Backend therefore holds the thread from the first join to the last leave (wake.hold). The client still answers pings and reassembles fragments, since a held connection lives for days and nothing promises it never sees either.

A queued prompt can be taken back, and a thread reports its own hooks. Measured on 2026-11-05 with codex-cli 0.166.0. thread/queue/add answers {queuedSubmission: {id, input, clientUserMessageId}}; thread/queue/delete {threadId, queuedSubmissionId} answers {"deleted": true} while the prompt still waits behind a busy turn, and {"deleted": false} once it has drained -- an idle thread drains it within 0.3 s -- or when asked twice. Both are experimental, listed only by generate-json-schema --experimental, like thread/queue/add. thread/resume's answer carries thread.status, so a line knows the status from the moment it connects.

hooks/list {threadId} answers {data: [{cwd, hooks, warnings, errors}]}, one entry per hook with eventName (preToolUse, stop), command or server/tool, enabled and trustStatus. Measured in an isolated CODEX_HOME: an unapproved user hooks file reports untrusted; a recorded hooks.state.<key>.trusted_hash that does not match reports modified; enabled = false there reports enabled: false with trusted. A project's .codex/hooks.json in an untrusted project is not listed at all, with no warning in the answer. A thread's source cannot tell the desktop app from the terminal: threads started from the terminal report "vscode".

End to end, with YAAC from the working tree: an idle thread that had joined a channel was woken by a peer's message through the line's status notifications, its turn read the mail with check_inbox, and the withdraw that followed answered deleted: false, since the prompt had already run.

Also from the field, not measured here: the Codex desktop app runs its threads on an existing app-server when CODEX_APP_SERVER_WS_URL names it, a variable read in the app's own code and documented nowhere. On Windows that is the only route, because the app turns its local-daemon mode off there.

Codex's app-server has two doors into a session, and the queue is the better one. Measured against codex-cli 0.151.0 on 2026-08-29, over codex app-server --listen ws://127.0.0.1:4599. thread/queue/add takes {threadId, input, clientUserMessageId}; on an idle thread it drains at once and a whole turn runs, and on a thread already working it waits its place. turn/start on a busy thread does not refuse -- it answers with a second turn id, status: inProgress, alongside the first. So the queue is what YAAC knocks with, and turn/start is only the fallback.

Two things it costs. capabilities: {"experimentalApi": true} in initialize, without which the queue answers -32600; and clientUserMessageId, echoed back and read by nobody here, without which the call is refused for a missing field. An app-server too old for the queue answers -32600 naming the method -- unknown variant `thread/queue/add` -- which is the only thing separating it from -32600 for a thread that does not exist. Both facts are visible in the binary's strings as well as on the wire.

Found by Vadim, who had the queue working before YAAC did; the busy-thread comparison and the fallback's discrimination were measured here.

Claude Code exports its inbox socket to the MCP server it starts, and a line written there is a user turn. Measured on 2026-09-08 against 2.1.261, from a server started by the session itself: CLAUDE_CODE_MESSAGING_SOCKET and CLAUDE_CODE_MESSAGING_TOKEN are in the server's environment (servers Claude Desktop starts carry neither), and two NDJSON lines -- {"type":"auth","token":…} then {"type":"user","message":{"role":"user","content":…}}, the Agent SDK's stream-json user message -- landed in the session's context at its next tool round, framed as "another Claude session sent a message". The docs say the same line starts a new turn when the session is idle, which is the case neither a hook nor MCP reaches. The socket answers nothing and drops an unknown type without a word, which is how three guesses at the shape vanished before the real one was read out of the binary's own usage snippet; a top-level from is ignored, so the sender goes in the content. The token is optional on macOS and Linux and required on native Windows, where the door is a named pipe -- measured on macOS only.

A post there is printed in the user's transcript as well as handed to the model, so since 0.6.1 it is a doorbell: one line naming sender and subject, with the bodies left in the inbox for the hook's additionalContext, which the model sees and the transcript does not. Reported from the field in October 2026, when 0.6.0's posts carried every body in full and filled the transcript with them.

Two consequences. The suite, run from inside a Claude Code session, inherits those variables, and a Backend under test delivered a test message into the developer's own conversation; conftest.py scrubs both. And the registry the client keeps at ~/.claude/sessions/<pid>.json -- sessionId, name, cwd, status, messagingSocketPath -- is plain JSON that names every session's socket, which is what makes reaching a session that never joined YAAC possible; nothing reads it today, and doing so is a design question rather than a step.

Binding a busy port fails in ~0.4 ms with EADDRINUSE. That is why every backend can just try.

Windows needs the selector event loop (found in pyzmq zmq/asyncio.py; measured since — the CI Windows job runs the full suite). zmq.asyncio waits on sockets with loop.add_reader, which the default ProactorEventLoop lacks; pyzmq then raises RuntimeError at first socket use unless tornado ≥ 6.1 is importable. main therefore passes loop_factory=asyncio.SelectorEventLoop on win32 — loop_factory, not set_event_loop_policy, because 3.14 deprecates the policy API. The reverse constraint holds in tests: asyncio.create_subprocess_exec is proactor-only on Windows, so conftest.py picks the loop per test module via the pytest_asyncio_loop_factories hook.

The bind election stays single-winner on Windows (found in libzmq tcp_listener.cpp; exercised by the CI Windows job). Plain SO_REUSEADDR there would let a second bind of an actively-bound port succeed; libzmq uses SO_EXCLUSIVEADDRUSE on Windows instead, so exactly one ROUTER holds the endpoint on every OS.

CLAUDE_CODE_SESSION_ID is visible to both the MCP server and hooks, and equals the session_id a hook gets on stdin. Better key than the cwd if v1 ever needs an out-of-process reader to find the right session, since it separates two sessions in one directory. Absent on Claude Desktop. Nothing uses it today.

Several memberships per process. Backend holds a dict of Membership, each with its own routing id, DEALER, roster and inbox, so the hat sees them as unrelated participants and the protocol needed no change. This matters for clients running one server per application rather than per conversation, such as Claude Desktop — where it also means one conversation can address another's connection, so check_inbox requires the id rather than guessing.

Message format

The wire format itself is specified in docs/message-format.md; this section is the rules for code that touches it. docs/zmq.md keeps the reasoning behind the envelope system rather than a plan for it — it shipped in 0.5.0, and version 2 does not bridge to version 1. Both sides name the version they saw when they disagree, because a mismatch otherwise reads as an empty net rather than as a disagreement.

protocol.dumps is the only serializer, and it stamps yaac: PROTOCOL_VERSION first on every top-level dict. That ordering is the point: every message opens with {"yaac":2, a magic number a reader can key on without parsing. No trailing comma is promised — a message with no other field ends there. dumps asserts its own output against MAGIC, which is written out by hand so the two can be caught drifting apart.

Field order is otherwise whatever the to_wire constructors build, so keep body last in them: it is the only unbounded field, and head -c on a log should show routing regardless of body size. Equal content gives equal bytes, so a message has one identity to hash or sign later. Nothing computes a signature today.

PROTOCOL_VERSION marks the encoding generation, not the field list. Renaming or adding fields does not bump it; replacing JSON with a binary framing would.

Received frames go through protocol.parse, never loads — it rejects a yaac field that is not exactly this build's version, checking the parsed value rather than the leading bytes, since that is what the format guarantees. type(version) is not int because 1.0 and True both equal 1. Do not call json.dumps on anything that goes on the wire. frontend.hook_report is the one other caller, and it is answering Claude Code's hook contract rather than writing a YAAC message -- protocol.dumps would stamp yaac: 1 into somebody else's format.

from and to are Scope objects whose fields compose — {channel}, {peer}, {channel, peer}, and {} for the hat, which is the only mail it reads. A peer is an Address: {name, zmq_routing_id}, either locator optional and the one you do not have simply left out. A name is unique on a channel only while its holder is connected; a routing id identifies one connection and is never reused. Further locators can be added as fields without breaking parsers, which is why these are structures.

One concept, one encoding: null and {"channel": null} are refused rather than read as the hat, and an address naming nobody is refused rather than read as an address to nowhere. Unknown fields are ignored, because refusing those would make every locator added later a breaking change.

Address, Scope and Envelope are frozen dataclasses with to_wire/from_wire. Parse with from_wire rather than reading dict keys — it rejects a malformed address instead of coercing it.

Hard rules

Each has a test.

  1. The MCP server writes nothing to stdout. It carries the stdio transport; one print() breaks the session with a parse error. Diagnostics go to stderr through logging, which the entry points point there. The terminal client is the exception and owns its own stdout, which is why it is a separate entry point rather than a flag.
  2. Nothing is ever written to disk, and a dormant server opens no socket. Unread messages, rosters and membership all live in memory and die with the process, so there is nothing to clean up after a crash. Backend is not constructed at all until join_channel.
  3. send never blocks. A full queue or absent peer must raise. Blocking inside an MCP call freezes the session.
  4. Participant and channel names are never parsed, split, validated, or case-folded by the hat or on the wire. That is why routing uses a separate opaque routing id: ROUTING_ID has length and byte constraints that user-chosen names must not inherit. The MCP boundary makes exactly one check, because it is the only layer that knows a human was meant to supply the value: it refuses a completely empty name, which is what an unexpanded template looks like rather than a choice. " " is a name, and trimming it would be parsing.
  5. The hat never reads a body. A body that looks like a control message gets delivered, not obeyed.
  6. from and the sender's channel come from the hat's table, never from the sender. This is what makes cross-channel injection impossible rather than merely forbidden.

Tests

Parametrize hard. Minimum number of test functions, maximum behaviour each. If a new test would differ from an existing one only in its inputs, add a parametrize case instead.

Compare values. Asserting that something was called, or is truthy, or is non-empty, tests nothing — a stub returning plausible shapes would pass.

No second argument to assert. It suppresses pytest's rewritten diff. Explain in a comment on the line above.

In src/ the rule is the opposite: no rewriting, and -O strips asserts, so use them only for invariants that cannot fail unless this code is wrong — dumps checking its own output against MAGIC is the case. Anything a peer or a malformed frame can trigger must raise.

ASCII names in tests — ann, bob, forum. Non-ASCII appears only as parametrized data where encoding is what is being tested. Docs and examples may use any UTF-8; the README's Cyrillic name shows that names are unrestricted. Tool descriptions are mostly English but need not be only English.

Prose

These rules cover everything written in words: comments, docstrings, commit messages, docs — and this file.

  • Say what the mechanism, constraint, or failure mode is, with real names and numbers. Give the why; the what is in the code, and the next reader is as capable as you.
  • Numbers that measure the world earn their place; numbers that count our own files do not. "Binding a busy port fails in ~0.4 ms" stays true forever, while "the version lives in four files" is wrong the moment a fifth appears — and it is a second copy of a fact, kept somewhere the thing it counts cannot reach. Enumerate, or state the invariant, and let a test name the exact set.
  • Cover intent, not implementation. Text that restates the line below it says nothing and goes stale the first time that line changes. If it is clear from the code, do not repeat it.
  • Technical vocabulary is free: "asynchronous queue with exclusive locking" is exactly right. Fancy general words are not — "think", not "ponder". No metaphors or slogans; the radio analogy lives in the README, not the source.
  • Write "ROUTER_MANDATORY raises EHOSTUNREACH for an unknown routing id, so the send fails instead of being dropped", not "a stuck queue must fail, not grow silently".
  • Commit messages: the subject names the change, the body gives the reason and what it displaces. Not a list of files touched — the diff already shows that.
  • Tool descriptions, server instructions and the plugin's skill are read by a model on every session, not by a person once. Write them as instructions: imperative, terse, no history and no reasoning the model will not act on. The why belongs here and in the code.
  • The skill only adds to the tool surface, and has to stay that way. The plugin is the minority install, so anything a session needs to use YAAC correctly goes in a tool description, the server instructions or a result, which every client sees. A rule whose only copy is in the skill is a gap in the tools.

Design notes

  • The hat is put on by getting there first. Soft state only, no policy, and it comes off when the process exits. Since 0.5.2 a session may say whether it is racing — --bind insists on winning and refuses to join if it loses, --connect never tries — but neither decides who wins, and the default still races and settles for either answer. Configuring the outcome would be a different thing, and is not built: a hat is still whichever process reached the endpoint first.
  • One address, three spellings, and no --port. --rendezvous, --bind and --connect name the same endpoint and differ only in policy, defined once in backend.py because both entry points offer them and a drift between the two would be a net that behaves differently depending on which program reached it. A bare port is what makes a wildcard bind easy to type by accident, so there is nothing to type it into.
  • The hat connects its own DEALER to its own ROUTER. Costs one socket, and keeps a single send path — no "am I the hat" branch anywhere.
  • Probing must not bind. If list_channels bound, a session that only looked would become hat and drop the endpoint when the call returned. Its 10 s timeout is the only exit when nothing is listening, because ZMQ queues instead of failing. "Nobody on the air" is a normal answer.
  • Hold, don't bounce, during a changeover. A message from an unknown routing id is parked and a whois sent, so the send succeeds late instead of failing. pending is bounded on count and age so a silent peer cannot leak memory.
  • No heartbeat, no TTL. An idle net generates zero traffic.
  • TCP, not ipc. An ipc:// socket file survives kill -9 and then blocks bind forever, needing a lock file and manual cleanup. The kernel frees a TCP port itself, and libzmq sets SO_REUSEADDR.
  • Port 19116 is 0x4AAC, below the ephemeral range so the kernel won't hand it out as a source port.
  • created is derived from the roster, not sent by the hat: channels are deleted when empty, so being alone on one means you just made it.

Decided, not built

Settled in discussion with Alex; build only when told, ask before deviating.

  • Privacy is convention, not protection. Everything runs on one machine under one user account, where any session can already read another's transcript from disk, so YAAC cannot add a boundary the OS does not have. Identity mechanisms exist to prevent accidents and default misuse by well-behaved participants — never to stop a determined session, and they must not claim otherwise.
  • Docs examples use the classical cast — Alice, Bob, Carol; the hat-sees-everything caveat is "the hat is Eve by construction". One side note keeps a non-ASCII name to show names are unrestricted.

Out of scope

Deferred on purpose — ask before adding.

  • Outbox, SQLite, retries, acks, dedup, store-and-forward
  • Delivery guarantees. v0 may lose messages, as long as it loses them loudly.
  • Multi-host, CURVE auth, namespaced names
  • Direct participant-to-participant connections after discovery
  • Channel UUIDs as anything more than a reported field
  • Presence beyond "who is on this channel now"
  • Threads, reactions, history, shared task lists

Reference

ZeroMQ's Zyre (RFC 36 / ZRE) solves nearly this problem: ENTER/EXIT, JOIN/LEAVE, WHISPER, SHOUT, over DEALER-ROUTER. Worth reading before changing the protocol. Don't take the dependency — we need a subset, and pyre is LGPLv3 and tracks Zyre 1.0.

Its better idea: separate discovery from data, so peers meet at a rendezvous point and then connect directly. That removes the relay bottleneck and the confidentiality caveat in the README. Candidate for later.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.