Map: exarch / frontend
A frontend addresses agents by id through Port and observes the host’s
feed. The port reads the cell’s folds, never owner resources, and holds
only the fleet’s Registry and usage meter, not its launch. The owner is
Agent; Host owns launch and joined end
(agent,
a-frontend-holds-a-port).
Inbound: one mailbox
bus/mailbox.rs linearises the three control folds and their payloads.
AgentMailboxis the owner end;AgentAddressshares cell and home.Mail,SchedulesandModellive under one mutex.transactlends a closure-scopedTxn; poison ends life instead of recovering memory that may disagree with the log. The port reads fold-backed status, not a copy.Txn::postrecords every accepted human text, message, child report, wakeup, generation-stamped surface batch or command asPosted.nextanddraincommitTakenbefore handing over payloads. Queued posts equalmail.pending()at every live unlock;Goneis unrecorded join plumbing.Agent::admitchecks stale generations and claimed workers beforebeginrecords the mail’sJobOpened; a declined input opens no job. Human fragments coalesce over maximal post runs, ignoringGone, but not other posts; a run carries its head’s harness preface, so only a run’s head is prefaced. Drain stops at the first rewrite.Freeadmits any input at rest;Gatedconsumes one release per job, set only at rest, andHost::revokewithdraws an unused one;Parentadmits the human and parent, refusing resting peers. Commands, child reports and departures are quiet and never held by admission.- Pending helpers are those whose mail
owes. A report holds the helper cell across status commit and parent notice; paid debt cannot overtake delivery. A report after life ends withdraws every pending post, so a dead reported helper owes nothing.Gonejoins quietly. - Timers only ring weak cell addresses, recording nothing.
Next::Rungand the boundary before each drain let the ownerfire: readSchedules, ignore obsolete timer ids, re-check wall time, commit a coalesced wakeup plus booking update/retirement, then retime/drop the unlocked timer. Returning agents wait on bookings; conversing schedules can open later jobs. - Report and clear retire bookings and withdraw queued wakeups before timer drop. Late rings cannot post; there is no epoch admission. Clear also withdraws reports and surfaces, retaining human text, messages and commands. Generation checks reject outgoing-engine batches.
- Lock order: descendant cell → ancestor cell → journal → bus channel.
Only reporting nests cells. The timer registry has no lock; transactions
never span provider requests, dispatch, joins or the owner’s
Context.
tui/commands.rs::route_submit classifies input once:
- Immediate UI commands (
/help,/copy, overlays, …) act on the UI thread./quitand/exitreturnBreak;App::keyhands the loopHandoff::Quit, which?carries out of it asExit::Quit, without ending agents. - Reads (
/new,/branch,/context,/resources) enter throughPort::command(agent, Command::Read)and run at the next tool or exchange boundary. - Rewrites (
/clear,/close,/evict,/rewind) enter throughPort::command(agent, Command::Rewrite)and hold subsequent input until the exchange boundary. /modelpostsCommand::Model(Pick)to the tab that opened the picker. The owner builds, commitsModelChangedthroughTxn::change_model, then swaps its immutable client; the next request reads it afresh.model_picker::persist_landed, called byApp::commit, saves project selection from liveModelChangedrecords alone, includingvia, afterApp::syncedcovers that exact record. The owner syncs before swapping its client. Asking and catch-up save nothing; login/provider notes are view chrome.- Other text, including unknown slash-shaped lines, enters through
Port::submit(agent, text, None); the third argument is a harness preface only the model reads, which Synod supplies and the TUI never does. Queue observation and recall usePort::{queued, recall}.PromptState::edit_queued_promptchecks draft/history state before invoking recall, so Up withdraws only text it can display.AgentAddress::recallwithdraws every queued human post under the mailbox lock, across intervening reads, rewrites and other inputs, which stay queued in order; an ended agent recalls nothing. It is not a barrier-aware trailing-run recall.
Outbound: records and live edges
Recording precedes publication, and completion is not channel state.
record/seam.rs::Emitter::commitappends one commit torecord.jsonland publishes it whole under the writer’s mutex;emitcommits one record.Transcript,Control,DisplayandForensicare durable classes.beginseeds the head;commit_toappends and steps shared control folds together; ordinarycommitrejects control records;Transienthas no sequence or durable form. The writer owns aFiledirectly. The first uncommitted append (write, encoding or append-lock poison), or durable record refused by the fold, latchesUnavailableacross clones and ends the home supplied byEmitter::bind.emitreturns that failure;check_availableobserves it;emit_or_endleaves it to the owner. Producers never report it. The owner’s terminus announces it once asTransient::Faulton the independent fleet sink and makes it the outcome.bus/signal.rs::SignalisCommit,Synced,Born, orTransient, addressed byAgentId.Emitter::childpublishes birth before that emitter can send any work.bus/sink.rs::Sinkconsumesfactper record within oneaccept,syncedfor an inclusive stable-storage watermark, andtransient. Attach andReader::sincesupply the current watermark too; a reopened writer starts at zero. Screens draw provisionally, outside actions wait.bus/emitter.rs::FleetBusowns the session-lived channel and usage meter.host.rs::Hostlaunches the human’s joined children; frontends receive their signals without driving agent work. Completion comes from records or terminal death, never channel emptiness.bus/channel.rscoalesces adjacent same-agentToken/Thinkingtext and replaces adjacentState; facts and other edges remain ordered.MERGE_TEXT_CAPbounds a merged text run;Transient::Elidedreports presentation loss without turning it into a session fault.BusReceiver::{depth, bytes}supply resource probes.AgentStateis live presentation state (Ready,AwaitingModel,Evaluating,Evicting,WaitingOnAgents), never model context. The record layer knows no bus: it publishes throughPublish; bus knows no agent (exarch-is-a-dag).
shell_eval/surface.rs decodes the shell’s surface vocabulary once;
pin writes come from the desk, not that decoder. Both record through the
same seam; card interpretation is cards’s.
The transcript calls workers errands: birth and completion carry the same
worker id/title. surface_notice (bus/post.rs) words the model notice with
elapsed time, actual ending and how to use await / workers.
Agent::admit suppresses redundant wakeups for already-claimed workers.
Host and observed jobs
Host owns the human’s children and their bus; hosts gate, never drive.
Host::{found, resume}constructs and launches the human’s children.childrenexposes every adopted child’s id in birth order, joined or not;port,feedandrun_direxpose reach, signals and logs.try_holdreturns aHold(bus/barrier.rs) only while no agent is taking up an item, never waiting; while it lives no agent takes up an item, so no exchange or command runs and no engine is dialled, though an open job may still settle.rebind_engine(root, hold, grants, cwd, system, mode)takes theHoldas proof the fleet is held, refuses a helper, and waits for the root’s oneRebindOutcome::{Rebound { teardown_failures }, Busy { workers }, Failed, LogRefused}: a pending rebind wakes the held root, which serves it before taking up any item (agent).revoke(root)answersGate::RevokedorShut;Busyonly while an input that may open a job is in hand or a job is open; orEnded. After each exchange the owner emitsTransient::ExchangeEnded.Port::usagereads run accounting.endandDropend the fleet and join the human’s children, whose teardown joins helpers. The feed stays with the host;Porthas no subscription operation.- Every agent records a busy period:
JobOpened’s commit number isJobId;JobSettled { job, stopped }closes it. Opening/registration, settlement and addressed Stop share the mailbox lock. Port::stop(agent, JobId)marks the matching open job and cancels its latest exchange withInterrupted, recalling human text oldest first. Stale job ids and rest are no-ops.WithdrawalFaileddistinguishes an ended agent from recording/sync failure; cancellation or withdrawal may already have happened. Recall likewise returns text only after sync, never empty success on failure. Helpers keep working; reports and subsequent input can continue the same job, whose stopped mark persists.- Settlement requires an empty queue and no pending helper; a helper whose life ended before settlement is joined first. A helper ending after it can fail Synod’s walk and report. A returning agent also waits for armed schedules.
- Synod uses
Admission::Gated: release after the baselines and after each round of closing walks admits the next job; a folder change revokes an unused release, retrying until it isRevokedor a job opens, and runs under a hold. Worker batches, wakeups and messages can open it as human text does. The host observes records and takes the walk; it never lends a child to a job driver (synod). EngineSeveredrecords engine loss;TeardownFailedrecords uncertified engine end. Failures propagate through joins toHost::end. Synod treats teardown failure as terminal, not permission for a folder account.
The session record and its mirrors
A transcript is a projection of one record, never a second log.
record/session.rs::AgentLogowns the modelContextand record seam.render_messagesbuilds the provider view on call; it is memoised nowhere. Falliblequiescecommits owed protocol repairs before advancing the fold. Success leaves a fresh prompt admissible; failure makes the owner explicitly unavailable and reaches the host as a failed session (session-record, exchange-ends-ready).Born.readergivesScrollbackarecord::Reader, never an append handle. Its crate-privatesincedelegates torecord/log.rs::Log::since, fixing extent and read handle under the writer mutex, then streaming commits beyond aCursoroutside it. Commits arriving after that extent take the channel.record/replay.rsowns replay/refusal;EmitterandAgentLogare crate-private.record/view.rs::Blocksfolds each witnessed fact;DeltareportsOpened,Grew,Patched,Rewound,Cleared, orQuiet.tui/mirror.rs::Mirrormaintains one rendered block per retained incident;Scrollback::commitcatches up from the log at birth or a commit gap. Duplicate commits fold once. Headless/Synod sinks narrate rather than catch up.- Resume catches up each child only to its recorded pre-run extent, draws the resumed note there, then catches up the new run. The bus’s usage meter plus resumed usage supplies totals, independent of views.
- A held session directory contains
record.jsonlalone.tui/export.rs::export_torenders a validated fixedSnapshotthroughMirror, creating a new destination rather than overwriting. Live/exportusesReader::snapshot, requiring a watermark-covered extent. Standaloneinactive_snapshotaccepts only associated inactive managed sessions, session-directory and canonical record-file forms; it holds the actual existing run lock before source open and through rendering. Held directory identity checks reject replacements. NoncreatingOwnDir::open_updateopens a regular source read+write; that same file and required directories sync before any destination/stdout. Active/unmanaged sources refuse usefully. Transcript::ClearedandRewoundwithdraw context in the same file. Resource readings are live diagnostic cards, not pressure histories.
Reopen folds Context and control in one read-only pass before quarantine,
then records pending withdrawals, open-job settlement and schedule retirements
with SessionResumed and a note naming unread input. Its new cell is empty;
taken-but-unanswered debt and a same-model narrowed window survive. The view
reads all four classes; Synod narrates no Control, and each new multi-record
commit yields at most one event it narrates.
TUI: a view per address
The TUI owns presentation, never agent liveness.
tui/tui_loop.rsdrains the feed and UI jobs, polls overlays and routes input throughApp::key/paste. After a drain to empty,Tabs::settledrequires every known human child’sDied; queued births are dispatched before this check. Initial births precederun, later births precede their creator’s death, and helper deaths precede their parent’s. Natural completion gets an uncapped final drain/frame;App::leavingreturns immediately without that frame.terminal.rsowns raw mode, alternate screen, bracketed paste, mouse capture and panic restoration.tui::runrestores the terminal and returnsLeaving(log directories and recalled usage).lib::runends and joins the host, then reports with finalPort::usage, including exchanges cut short by quitting.tui/tabs.rs::Statusholds the live pin slots, notScrollback.tui/app.rsappliesTransient::Pin/Unpinthere in first-seen order./clearempties the slots; resume starts empty.Forensic::Pin/Unpinpersist only keys and remainDelta::Quietin view replay (pins).tui/tabs.rs::Tabsis an id-ordered forest of birth facts andStatus/Life; there is no special root tab. It holds aPort;row/focused_rowread publishedAgentRows androwstakes one roster per call. Model/effort/account chrome readsAgentRow.selectedfrom the cell. A known account is labelled against current availability; an unavailable account uses its recorded label snapshot.Transient::Diedis the final owner presentation cue, after availability classification, failure reporting and retirement. Terminal delivery uses the owner’s fleet sink even when append state is poisoned; the poisoned log is never recovered. Buffered records preceding death must still draw. Descendants retired by/clearlinger through the same path. AfterLINGER, scrollback, render memos and pins drop; held log directories remain for export.- Focus and matrix navigation are presentation identities.
matrix.rsderives rows/connectors from the forest before clipping; idle demotion is computed from the inbox exchange clock, never stored as lifecycle state. scrollback.rsowns viewport and live tails;block.rs,group.rsanddial.rsown graded disclosure. TheBlockswindow bounds retained incidents; mirror trimming follows the fold rather than a second policy.row.rs::Row { gutter, content }keeps marginal ink out of copying.render.rslays out at the known width, records gesture geometry, and brackets terminal writes in synchronized updates.gesture.rsreturns effects over immutable views; its caller applies them.rail.rs,line.rsandgroup.rsbind shape to kind, hue to producing agent, luminance to magnitude/figure-ground. Machine output is recessed; human prompts have their own neutral fence. Cards use one mark interpreter.record/stream.rs::Streamcuts prose/thinking at newlines; the view draws the uncommitted tail in the block that will absorb it.Boundaryretires abandoned tails.md.rsshares ral highlighting with tool panels, renders math throughtui-math, and falls back to literal source on refusal.prompt.rsandprompt/editor/own drafts, history, undo and the fuzzy slash-command popup. Completion is one undoable edit; recalling another draft starts a fresh undo baseline. Vi/Emacs yank and put use a private register; only Ctrl-C and/copyreach the OS clipboard, through theclipboardcrate (native locally, OSC 52 over ssh).PromptStateholds the draft, guarded recall, searches and the live popup (refresh_menu,menu_key), over an injectedHistory;prompt/search.rstraverses matches;prompt/editor.rsowns the editor wrapper, witheditor/{editing,navigation,geometry}.rsfor native transactions, visual movement and height, andeditor/completion.rsfor popup geometry.- Composer input has one owner at a time. The UI loop admits only key
presses — Windows also reports releases; under the
DISAMBIGUATE_ESCAPE_CODESflags alone no terminal reports repeats — so nothing downstream inspects a key’s kind.App::keyroutes each press once, in order: the open overlay; prompt-selection copy, on a steerable tab outside the matrix; matrix navigation; a live search (PromptState::search_key: editor-native Vi search, else Ctrl-R history search, which Ctrl-R opens); the popup, or Tab into the matrix; chords; then interrupt, submit or edit. Only unmodified Enter submits. Watch-only tabs cannot edit, paste, accept completion or launch the editor.Ctrl-GandCtrl-X Ctrl-Eask the UI loop to compose externally. The armedCtrl-XisApp’sPrefix, taken by the next key; focus, modal, paste, mouse, resize and suspension boundaries drop it.MouseOwneralone records a left gesture from press through release; crossing the prompt edge never transfers a drag. A prompt press yields aGrip, the editor’s selection anchor, held only inMouseOwner::Prompt; a key or paste ends that ownership, since it may rewrite the draft the anchor indexes. Terminal ownership is taken only on a shifted left press; any shifted event leaves selection to the terminal. Ctrl-C copies an editor selection before considering exchange cancellation, and copy errors are reported. Record-backed/copyand gesture copying require a watermark-covered scrollback without streamed tails; unrelated draft copying is unrestricted. Selection clears only after a confirmed clipboard write; failure retains it for retry, while success uses the transient copy toast. prompt/history.rs::Historyowns the entries, their store and the arrow browse position; replacing the entries ends the browse.tui_loop::runopens it and injects it intoPromptState. The store is shared$XDG_STATE_HOME/exarch/prompt-history.json, private and under a nonblocking file lock, read throughral_core::io::read_bounded. It retains at most 500 entries and 1 MiB of prompt bytes, merges other sessions’ entries on save, and reports failures without losing submission. An unreadable startup history leaves an unstoredHistoryand a notice rather than being overwritten.history_prev/history_nexteither move or report refusal; arrow recall requires Insert mode, an empty draft or unchanged history entry, and the absolute buffer start/end. Queued recall additionally requires an empty draft and no active history browse/search.prompt/search.rsandPromptState::search_keyown Ctrl-R search: the query and footer preview leave the draft, cursor and undo untouched until acceptance; a click in the box is claimed but inert. An empty query previews the newest entry; Ctrl-R/Up and Ctrl-S/Down traverse matches. Enter adopts without submitting; Esc/Ctrl-C cancel without cancelling the exchange. Paste goes to the owning search query, not the draft. Paste normalizes CRLF/CR to LF; the large-paste footer is only a byte/line summary, never a placeholder that is expanded at submit.terminal.rs::TerminalGuard::edit_text_in_editorlends terminal modes to the external editor. Only the child receives the saved pre-TUI stderr; parent diagnostics remain instderr.log. The guard’sStderrRedirectholds one owned saved destination that serves both the editor, duplicated per edit, and restoration on drop; Windows captures it as a noninheritable native handle before the log opens. Absent or closed native stderr becomes explicit child discard. Stdio is prepared before creating the secret draft or suspending modes. The editor follows the shared contract inral_core::external_editor:EditorCommand::selecttakes nonblank VISUAL, then EDITOR, then the platform default, splitting quoted argv without a shell (shlexon Unix,winspliton Windows) and refusing NUL;admit_draftandread_draftcap input and readback atMAX_DRAFT_BYTES(16 MiB) and keep trailing newlines. The secret draft is a consumingDraftFilein exarch’s cacheeditor-draftsdirectory, outside its writable scratch subtree;DraftFile::editruns the editor undercatch_unwindsoremove(self)happens exactly once, even on unwind, andafter_cleanupnever drops a removal failure. Failure keeps the draft and reports a diagnostic; terminal restoration failure exits the UI loop.tui_loop::compose_in_editoradopts successful text into a fresh draft and repaints, never submits it.- Patched native edtui is the sole undo owner.
editor/editing.rsuses its transactions and explicit range/movement primitives for Insert-mode grapheme edits, kill/yank and repeat recording. Native history is bounded by steps and snapshot bytes; no facade history or second Vi parser exists. Pending native commands retain their character arguments, includingu.vendor/edtui/PATCHES.mdrecords the local 0.11.7 patch rationale: expose grouping without rebuilding editor state, and share extended-grapheme geometry across drawing, height, cursor placement and mouse hit-testing. Native action execution also snaps cursor boundaries during replay, not just after live dispatch.editor/geometry.rsconsumes this geometry;editor/navigation.rsmoves Insert-mode Up/Down and Ctrl-P/N through visual rows, retaining the preferred display column across height-only layout changes. Characterwise selection extraction removes exactly its projected byte range, leaving unselected newlines intact. This is not full native Vi grapheme-count semantics: storage and Vi counts remain scalar-indexed. Codex-derived host algorithms and their Apache-only boundary are inNOTICE; the separately patched vendor crate remains MIT-licensed. paste_burst.rs::PasteBurstbuffers rapid unbracketed character runs and guards a following Enter, emitting lossless paste chunks instead of submit gestures. This is a timing heuristic, not proof of paste: sufficiently slow unbracketed input is indistinguishable from typing. Bracketed paste remains explicit; no placeholder text is expanded into instructions at submission. Bursts form only whileApp::takes_text.tui_loop::guard_ownerwraps every act that may move input (a fact, a death, a job, a tick, a delivered key) and finishes the burst when theInputOwnerchanges, so held text never crosses owners. A deterministic integration test routes burst output throughApp, checking that the guarded Enter inserts a newline rather than submitting.overlay.rsowns the shared bezel. Model, login, provider and rewind overlays run in the one UI loop; background results apply only to their originating overlay generation./rewindpreviews and posts to the tab it opened on, not whichever tab later acquires focus.- The status rule times state transitions rather than arriving events.
StateSpanis active activity orEnded; retirement cannot be overwritten by a later Ready or streaming update. A recording failure is transient error chrome followed by ordinary owner retirement, not a fake ready tab. Usage and context figures use the same provider data as other frontends.tui/resources.rsadds frontend-owned probes to the owner’s resource card.
Keys and signals
Stop cancels the exchange; end cancels life.
- A TUI tab tracks
JobOpened/JobSettled. Esc / Ctrl-C on an active tab callsPort::stop(agent, job); with no matching job no Stop occurs. An unclaimed Esc reaches the editable prompt, including Vi’s mode change; Ctrl-C never edits. Helpers and loose shell workers survive. The TUI has no/stopcommand. PromptState::restore_stopped_promptsprepends every recalled prompt to the live draft, preserving text even during history browsing or outside insert mode. Stop never uses Up’s guardededit_queued_promptpath.- Overlays, matrix navigation, searches and selected-text copying consume their gestures first. A successful Ctrl-C copy retains the draft; only an unclaimed key reaches Stop. Raw-mode keys are local, not process signals.
signals::faceforwards SIGINT to each human child’sstop_current, shutdown toRegistry::end. Windows handles Ctrl-C/Ctrl-Break before ral’s escalating handler; repeated interactive gestures never tick the force-exit ladder.- Provider waits poll the exchange; ral dispatchers strike their own id. Cancelling threads never write to a transport.
Port::end(agent),/close, helper idle timeout and owner drop end life;/quitreturns tolib::run, whoseHost::endends and joins the fleet. Clear prepares first, joins helpers, commits and replaces the engine, preserving human/message input. Failed preparation changes nothing; failed commit ends life and retires the unused prepared engine.
See cancellation for scope propagation.
One-shot headless
Headless::run(port, feed, …) observes its one returning root on the
host’s feed, an identity root’s or a guest’s (exarch --vm) alike. It checks that the first signal is the root’s Born,
retaining its log directory for “Agent log:”. It submits the seed and reads usage through a
port, folds only that agent’s records into one Blocks memo, and
finishes on a watermark-covered Control::Status or terminal Died.
Death/disconnection never promotes an unsynced buffered success. Helper facts do not print;
helper faults remain visible and usage includes the fleet. Replied(v)
writes its first-order FOValue as ral text or JSON to stdout; Failed,
Stopped or death without a reply fail honestly. lib::run ends the host afterwards and includes
teardown failures in the result.