Edit Coordinator & Message Bus
When multiple coding agents, interactive kompile chat sessions, MCP tool hosts, and background subagents work in the same repository — or share the same machine's RAM and GPU — they need coordination without requiring a central broker daemon.
Kompile implements this as a file-based coordination state manager and durable message bus (CoordinationStateManager) exposed through the edit_coordinator tool and bridged automatically into every kompile chat REPL.
Architecture & on-disk layout
Project-scoped coordination state lives under <projectRoot>/.kompile/coordination/ with owner-only POSIX permissions (0700 directories, 0600 files). Machine-wide memory and GPU admission state lives under the user's global ~/.kompile/ directory (SystemActivityCoordinator).
<projectRoot>/.kompile/coordination/
├── .lock # Short-lived OS FileLock sentinel (held for ms only)
├── agents/<session>.json # Active agent presence, PID, task, wake-bridge flag
├── edits/<lockId>.json # Single & batch file edit locks
├── locks/<name>.json # Named FIFO project resource locks (build lanes, devices)
├── processes/<id>.json # Shared published background processes
├── cancel-requests/<owner>/ # Cross-session stop requests for published processes
├── messages/<mailbox>/ # Durable pending CoordinationMessage files (per session/subagent)
├── outbox/<messageId>.json # Sender-side delivery & reply-deadline tracking
├── owed-replies/<id>.json # Recipient-side unfulfilled expectReply obligations
├── message-acks/YYYY-MM.jsonl # Append-only monthly acknowledgment audit journal
├── message-sequences/ # Per-session sent/received sequence counters (gap detection)
├── subscriptions.json # Topic subscriptions for scoped broadcasts (max 16/mailbox)
└── wakes/<chat>/<host>.json # Tool-host wake outbox & open wait records (adopted on crash)Cross-process safety & heartbeats
- Atomic mutations: State transitions acquire a short-lived OS
FileLockon the sentinel file (bounded waits:500 msfor edit locks,2,000 mswhen releasing an ended agent's locks) and write JSON atomically. - 30-second daemon heartbeat: Every active
CoordinationStateManagerrefreshes its own agent presence (120 sTTL), its hosted in-process subagents, its owned edit lock leases (60 sdefault, configurable viaeditLockLeaseSeconds), and its user-wide high-memory activity reservations. - Stale cleanup without false eviction: Stale entries past TTL are lazily evicted on queries. A stalled JVM whose PID is still alive is treated as ended after
10 minuteswithout a heartbeat (STALLED_AGENT_LIMIT), preventing reused PIDs from holding locks forever while giving paused turns room to breathe.
The four coordination primitives
All four primitives are exposed under one edit_coordinator tool:
1. File edit locks
| Actions | Purpose |
|---|---|
register_edit, release_edit | Acquire or release a lock on one file path. |
register_edits, release_edits | Atomically acquire or release a batch of file paths (pairs with read_batch / edit_batch / edit_patch). |
query_edits | Inspect all live edit locks in the project. |
monitor_edit, unmonitor_edit, query_edit_monitors | Subscribe to a wake notification (wake.*) when another agent releases a locked file. |
- Session vs. agent enforcement: Edit locks are advisory for callers without an agent identity (they warn on conflict without blocking writes), and enforced for agent-scoped edits (
guardAgentEditrefuses writes to any file held by another live owner). - Lease renewal: Active agent edit locks automatically renew while the agent is alive, with a minimum lease of two heartbeat intervals (
60 s).
2. Durable session mailboxes & message bus
| Actions | Purpose |
|---|---|
register_agent, query_agents | Publish agent presence/task on the bus and discover peers (including hosted subagents). |
send_message | Send a targeted durable message to a session or agent (kind, message, optional reply_to, optional expect_reply). |
broadcast_message | Fan out a message to all active peers — or only mailboxes subscribed to a topic. Set requires_ack=false for informational broadcasts (broadcast.info). |
subscribe_topics | Register up to 16 broadcast topics for this mailbox (subscriptions.json). |
read_messages, ack_message, ack_all, message_status | Drain pending messages, acknowledge them (recording to message-acks/YYYY-MM.jsonl), and inspect delivery/reply status. |
Every CoordinationMessage (up to 64 KiB, 24 h default TTL) carries:
sequence: Per-sender, per-target monotonic counter starting at1, so recipients immediately detect if an earlier message was missed.replyTo&expectReply: Links threaded answers and optionally enforces that the recipient must reply after acknowledging.- Traffic separation by
kind:- Informational kinds (
activity.intent,activity.complete,activity.blocked,broadcast.info,expiry.notice) — surfaced as notices to peers, never interrupt work or start a model turn in idle chats. - Host-raised wakes (
wake.*) — system events such as watched process completions, freed resource lanes, released edit locks, or interactive tool-host questions (wake.question). - Actionable peer mail (default
send_message,message-broadcastfrom/message-broadcastand/loop-broadcast) — queued for handling and enforced before further work.
- Informational kinds (
3. Named project locks (CoordinationLockManager)
| Actions | Purpose |
|---|---|
acquire_lock, release_lock, query_locks | Acquire, release, or inspect named FIFO locks for long-lived shared resources (a build lane, test device, or deployment). |
- Arrival-order handoff (no thundering herd): If a named lock is held, callers queue in FIFO order. Releasing the lock hands ownership directly to the first waiter and delivers a durable wake message so even a restarted session discovers the grant.
- Liveness over wall-clock timeouts: A named lock is never stolen from a live holder just because time passed (preventing two concurrent builds from colliding). Ownership transfers only when the holder releases, is forced, or its OS process (
ProcessHandle) is gone past the missing-grace window (and any child processes launched under the lock have ended). - Holder reminders: While another session is waiting, the holder is notified on arrival and reminded periodically until it releases.
4. User-wide RAM/GPU admission lanes & shared processes
| Actions | Purpose |
|---|---|
preflight_activity, release_activity, query_activities | Reserve or inspect machine-wide high-memory/GPU lanes (SystemActivityCoordinator, fail-closed OS file lock under ~/.kompile/). Supports shared reader lanes (:read) vs. exclusive writer lanes. |
watch_activity, wait_for_activity, query_activity_waits, cancel_activity_wait | Join the FIFO queue for a busy lane and receive a wake when it is your turn (later arrivals cannot jump ahead of earlier waiters). |
publish_process, unpublish_process, query_processes | Publish long-running builds/servers onto the coordination bus so sibling sessions see live status and can issue cross-session stop requests (cancel-requests/). |
awareness, status | Compact snapshot of active peers, locks, processes, and activity lanes. |
Delivery guarantees & pre-tool enforcement
Durable files alone do not force a busy LLM agent to stop and read its mail. Kompile closes that gap on both sides of the wire:
Sender-side tracking (MessageDeliveryTracker)
Every tracked send_message writes an entry under outbox/<messageId>.json and sweeps every 10 seconds:
- Unacknowledged retries: Retries up to 3 times with exponential backoff (
30 s→120 s), re-resolving the recipient's active mailbox on each attempt (so mail follows a restarted tool host or newly bridged chat). - Undelivered wake: If all retries go unacknowledged (or the message expires unread), the sender is woken (
mail.undelivered/expiry.notice). - Reply deadline: If
expectReply=trueand the recipient acknowledges without answering within 10 minutes (REPLY_DEADLINE), the sender is woken withmail.no-reply.
Recipient-side enforcement (CoordinationMessageMandate)
Before every tool execution — in Kompile's own AgenticChatLoop, in DirectSubagentRunner / ServerSubagentRunner, and in external provider pre-tool hooks (ShellMandateHook) — Kompile runs a deterministic, zero-LLM pre-tool check:
- While the session's (or hosted subagent's) mailbox holds unacknowledged actionable messages, OR while
owed-replies/holds acknowledgedexpectReply=truemessages not yet answered, every tool call is blocked (BLOCK) except the mailbox-draining actions (read_messages,ack_message,ack_all,send_message,broadcast_message,message_status). - Informational kinds (
activity.*,broadcast.info,expiry.notice) never trigger a block. - Storage read errors fail open (so a transient filesystem hiccup cannot brick a session); valid pending obligations fail closed.
Bridging the bus into kompile chat
Two components connect the file-based bus seamlessly to an interactive chat session:
HostWakeOutbox(wakes/<chat>/<host>.json): When an MCP tool host needs to wake the chat it serves (a monitored process exited, a named lock was granted, a resource lane freed), it delivers awake.*message. If the chat cannot accept it immediately, the host persists the wake on disk and retries every2 seconds. Each host also records its open resource waits and edit-lock monitors beside the outbox; if that host JVM dies, the next host for the same chat adopts both owed wakes and lost-wait notices so the model is never stranded waiting for a wake that will never come.AgentBroadcastManager(chat queue bridge): Every interactivekompile chatstarts a background bridge polling its session mailbox every2 seconds(plus an immediatedrainNowpass on startup/resume) and advertises its wake bridge on the bus:wake.questionpayloads are intercepted and shown directly to the user above the input prompt (routing the user's next line back as the answer).- Other
wake.*messages are offered directly toChatMessageHandler.handleExternalMessage(entering the active turn or waking an idle chat). - Informational messages are printed as a single dim notice line and acknowledged without queueing a model turn.
- Actionable peer mail and broadcasts are enqueued into the chat's disk-backed
MessageQueueexactly like queued user messages. The bridge callscoordinator.acknowledgeMessage(id)only afterqueue.ensureSaved()confirms the queue is persisted to disk — guaranteeing zero message loss if the chat process exits mid-handoff — and then nudges the idle turn dispatcher so an idle session starts automatically.
Related docs
- How the Chat REPL Works — how
ChatRepl,ChatMessageHandler,MessageQueue, and.pending-events.jsonconsume wakes and queued messages - The Enforcer — deterministic pre-tool rules (including
CoordinationMessageMandateand shell/build mandates) - Subagents — hosted subagent mailboxes, containment, and admission budgets
- CLI Harness (TUI & Config) — top-bar cross-agent build/lane indicators and
/message-broadcast//loop-broadcast