Skip to content

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).

text
<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 FileLock on the sentinel file (bounded waits: 500 ms for edit locks, 2,000 ms when releasing an ended agent's locks) and write JSON atomically.
  • 30-second daemon heartbeat: Every active CoordinationStateManager refreshes its own agent presence (120 s TTL), its hosted in-process subagents, its owned edit lock leases (60 s default, configurable via editLockLeaseSeconds), 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 minutes without 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 ​

ActionsPurpose
register_edit, release_editAcquire or release a lock on one file path.
register_edits, release_editsAtomically acquire or release a batch of file paths (pairs with read_batch / edit_batch / edit_patch).
query_editsInspect all live edit locks in the project.
monitor_edit, unmonitor_edit, query_edit_monitorsSubscribe 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 (guardAgentEdit refuses 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 ​

ActionsPurpose
register_agent, query_agentsPublish agent presence/task on the bus and discover peers (including hosted subagents).
send_messageSend a targeted durable message to a session or agent (kind, message, optional reply_to, optional expect_reply).
broadcast_messageFan out a message to all active peers — or only mailboxes subscribed to a topic. Set requires_ack=false for informational broadcasts (broadcast.info).
subscribe_topicsRegister up to 16 broadcast topics for this mailbox (subscriptions.json).
read_messages, ack_message, ack_all, message_statusDrain 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 at 1, 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-broadcast from /message-broadcast and /loop-broadcast) — queued for handling and enforced before further work.

3. Named project locks (CoordinationLockManager) ​

ActionsPurpose
acquire_lock, release_lock, query_locksAcquire, 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 ​

ActionsPurpose
preflight_activity, release_activity, query_activitiesReserve 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_waitJoin 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_processesPublish long-running builds/servers onto the coordination bus so sibling sessions see live status and can issue cross-session stop requests (cancel-requests/).
awareness, statusCompact 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:

  1. 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).
  2. Undelivered wake: If all retries go unacknowledged (or the message expires unread), the sender is woken (mail.undelivered / expiry.notice).
  3. Reply deadline: If expectReply=true and the recipient acknowledges without answering within 10 minutes (REPLY_DEADLINE), the sender is woken with mail.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 acknowledged expectReply=true messages 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:

  1. 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 a wake.* message. If the chat cannot accept it immediately, the host persists the wake on disk and retries every 2 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.
  2. AgentBroadcastManager (chat queue bridge): Every interactive kompile chat starts a background bridge polling its session mailbox every 2 seconds (plus an immediate drainNow pass on startup/resume) and advertises its wake bridge on the bus:
    • wake.question payloads 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 to ChatMessageHandler.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 MessageQueue exactly like queued user messages. The bridge calls coordinator.acknowledgeMessage(id) only after queue.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.
  • How the Chat REPL Works — how ChatRepl, ChatMessageHandler, MessageQueue, and .pending-events.json consume wakes and queued messages
  • The Enforcer — deterministic pre-tool rules (including CoordinationMessageMandate and 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

Released under the Apache-2.0 License.