Map: core / engine protocol

core/src/engine.rs is the one engine; core/src/protocol.rs is the frame algebra and nothing that carries it — protocol/probe.rs its probe vocabulary, protocol/channel.rs the duplex byte channel and the one liveness law; core/src/carrier.rs and carrier/ are the two carriers that interpret the algebra — the identity transport in process, the wire transport’s front-end half — with carrier/wire/serve.rs the wire’s engine half; core/src/shell/run/report.rs projects a run onto the algebra; a wire-seat child is made by the host’s factory and born from an Attach carrying its marshalled parent, so core holds no spawn machinery for it. The why is engine-protocol; this page only points at symbols.

core/src/engine.rs

  • EngineInstaller { tag, runtime, root, narrow } — one compiled-in installer, in two halves. runtime: fn(&EngineSpec) -> Result<Runtime, Error> is the process half (Σ, builtins, docs; a root and a child engine each derive their own, an in-process child shares its parent’s); root: fn(&Root, &mut Shell) -> Result<(), Error> is the root-only recipe (libraries, hints, boot bindings, ledgers), which refuses in its own words; narrow: GrantNarrower is the policy every child is held to. Only tag crosses Attach, never the function.
  • Runtime: what the binary supplies, and the only place builtins are installed (install_builtins, install_captured_builtins); a Shell is built over one and cannot hand it back.
  • Engine — one session’s engine: the Shell, its Arc<Runtime>, its Scopes, the installer it was born from. Engine::boot(installers, &attach) is the one boot both carriers call: resolve_installer (version check, then tag lookup), the installer’s runtime, then by attach.origin: Origin::Root(root) is Shell::root, the root recipe, cwd and env, then rehold and permanent installation of Root::grants; Origin::Child(parent) is Shell::child_of(Arc::clone(&runtime), parent, installer.narrow), and no recipe runs. There is no Keep: the attach is the birth, and the scratch is the host’s, named in a root’s env. Engine::run runs one dispatch under the view Scopes::open hands it; Scopes keeps the node, its one writer; Engine::probe (engine/probe.rs) answers one Probe.
  • --guest-engine <cgroup-root>: the Linux x86-64/aarch64 process role names guest_abi::layout::ENGINE_FLAG and installs the jail before carrier::run_engine; Engine::boot performs no process-global jail setup. PROTOCOL_VERSION versions the whole engine contract, frames and command confinement, and every attach refuses a mismatch. Version 31 requires the guest deny-set, including on development media (boot-contract-is-versioned).
  • Rails — one dispatch’s host-facing rails as its carrier lays them: the Outlet its events leave by, the deferred sink and the desk. The carriers differ in these and nowhere else.
  • Scopes — what stops an engine’s runs, shared with whichever thread carries Control: the dispatch scope root, the durable root, and a slot holding the current dispatch and a foretold strike with its cause. open mints a dispatch’s scope ahead of its frame (struck already if a strike foretold it). open(id, within) parents beneath the host scope when supplied, otherwise beneath the dispatch root. apply gives Strike(id, cause) its one meaning: strike only that dispatch with the exact cause, or foretell it. End(cause) cancels the durable root and current dispatch with its RootCause, including one beneath a foreign host scope.

core/src/protocol.rs

The frame algebra. Everything on it is a wire type; nothing here carries.

  • PROTOCOL_VERSION (currently 50): checked at Attach; a mismatch refuses. The contract includes Start’s parent record field and parent-decode facts. An engine’s ceiling rides Root.config as a grant value, decoded where it lands; guest media must be rebuilt with just vm::boot.
  • build-tools’ manifest::check compares the same number at build time, against the proto_version= line media-manifest compiles into the guest media; check-media, tauri’s beforeBuildCommand, refuses to package media that disagrees.
  • Frame — the whole wire enum: Attach, Dispatch, Probe, Event, Session, Control, Answer, Ping, Pong; Frame::kind names a variant for the diagnostic about a frame out of place.
  • Attach { engine: EngineSpec, origin: Origin } — what every engine is born from, under either carrier. EngineSpec names the engine: proto_version, installer, terminal, home. Origin is Root(Root { cwd, env, grants, config }) (env: per-session variables the host seeds; grants: host-resolved layers installed once after the recipe; config: the installer’s own settings, an FOValue its recipe decodes) or Child(Marshalled) (a child’s parent, carrying its own cwd and env). home and cwd are path::EnginePaths (path/namespace.rs): a path on the engine’s machine, named in the namespace the front-end can name it in — Host(PathBuf) for an engine sharing the front-end’s computer (in process, or a child process), Guest(GuestPath) for one inside a Posix guest, a /-separated string that a Windows front-end has no PathBuf for. The engine reads either as its own through EnginePath::native, crate-private, since only the engine’s side has the OS a guest path is native to. Attach::new is a plain root’s, at this build’s version; Attach::root pairs an EngineSpec with a Root, whose with_env, with_grants and with_config edit it. A root’s env is an environ::EnvVars, so an attach binding PWD or OLDPWD does not decode; Attach::child pairs an EngineSpec with parent: Marshalled; with_terminal edits either. protocol/json.rs::RawOrigin::Child carries those opaque bytes as base64.
  • Run / Program — one dispatch’s payload: the policy fields plus Program::Source/Program::Hook. Run’s field types are the run regime, held by session state, and live below the wire: RunIo and RunStdin (io/regime.rs), Captured (io/sink.rs) and RequestedTerminalAccess (process/lease.rs); ral_core re-exports them at the root. Run.last asks a returning run to claim and wait for still-unclaimed session workers, replay their bytes and drop their endings inside its frame. Batch sets it on its script; ordinary REPL and exarch calls leave it false.
  • Event — engine→front-end, inside a dispatch’s window: Surface, Enquiry, Reading, Report. Every surfaced value is a tagged variant; an audit observation rides as `observed <record> (Observation::to_surface). Reading(Result<FOValue, ProbeFailure>) answers a Frame::Probe under its DispatchId: the probe’s own event, not a run that ended.
  • SessionEvent — engine→front-end with no dispatch to ride: Attached / Refused(WireError) (the attach verdict) and DeferredSurface(Vec<FOValue>) (a worker’s batch, and a watched worker’s lines).
  • WireError { reason: Reason, context: Option<String>, hints: Vec<String> } — a refusal envelope for Frame::Answer, SessionEvent::Refused and Severed::Refused. of(&Error) borrows the live error and clones only these portable facts; to_error(&self) -> Error restores them without changing the reason or hint order. message(&self) -> String derives presentation only. Both carriers normalize through this pair. Intrinsic advice and code are derived from the preserved reason; provenance, witnesses, compiler rejections and unwind facts do not cross. The enquiring operation claims its own site. ErrorFact is the separate {frame, reason, site} failure, not this report envelope.
  • Control — Strike(DispatchId, CancelCause) and End(RootCause), the closed Cancelled | Terminated | Aborted; applied by Scopes::apply under both carriers. Even a terminal dispatch-local cause never ends the engine.
  • Report — Static { rendered, status } before evaluation; Ran(Ran { ending, rendered, single_command, captured, trail }) after it; Faulted { rendered, status } only when the report was lost (engine-worker panic or report plumbing/fuse failure), so what ran is unknown.
  • Ending = fact::Ending<FOValue, ErrorFact, CancelCause> has five cases: Ok(value), Err(fact), Exited(u8), Stopped(cause), Panic(text). A non-data result becomes a typed Invalid error, status 1, with its fact and reason-derived advice. The ErrorFact is the failure behind the record try hands its handler (ErrorFact::record); serde goes through its first-order encoding, typed reason included, and exarch reads its reason() for the command-exit tip. Report::Ran(Ran) holds the ending with its rendering, captured streams and trail.
  • The wire failure is exactly {frame, reason, site}, with a total site; the message and status a program reads are derived from the reason, not stored. Report::code() -> u8 reads the NonZeroU8 host status for Static/Faulted and delegates to the ending for Ran, whose errors project through the one Reason code table. Desk refusals retain their typed causes. Hosts exit through std::process::ExitCode::from(u8). The versioned wire carries the new fact unchanged, without backwards compatibility (the error record).
  • Serde externally tags the ending in kebab-case: {"exited":3}, {"stopped":"timed-out"}, {"panic":"…"}. Ok carries an FOValue ({"ok":"unit"} for Unit), and Err carries the record. This is not the Datum encoding used for language values and stored worker endings (endings).

core/src/shell/run/report.rs

RunReport::into_report projects the engine’s End onto the wire alias. It first turns a value into first-order data, or into Err(not_data(..)); then renders that ending once (Ran.rendered, empty for Ok, Exited and a reader-gone stop; single_command records the compact-drawing context); then maps an error to its record and a Stop to its cause. A caught run panic is Ran with Panic, status 101, after checkpoint restore, with no capture or trail. Static diagnostics render against their own source (static-diagnostics-render-at-the-seam). Report::refused renders a typed Reason spanlessly: nothing ran. Report::faulted renders ReportFault directly: the report is unavailable, not a recoverable error or an evaluation that returned a panic ending.

core/src/protocol/probe.rs

The probe vocabulary, typed once for both ends.

  • Probe — the payload of Frame::Probe: BindingCount, LeasedBindingCount, LargestBindingBytes, EnvVar(String), Cwd, Home, BuiltinNames, PathBytes(PathBuf), Workers, SessionEnded, CompletionNames, Bindings, PathEntries(PathBuf), Grants; WorkerCount exists only under test-util. Each variant states what it takes, so a payload its probe does not take is not representable.
  • The rows the answers come in, rendered engine-side, each a record!: WorkerRow, BindingRow/HandleRow, CompletionNames, PathEntry. WorkerState::Ready(Done) holds the shared worker ending; WorkerState::unclaimed is Running | Ready(_). A missing row also means claimed, so an announcing host requires a present unclaimed row. Probe::Grants answers Grants, a record!: each layer of the session’s stack a reader needs (GrantLayer::is_shown: it restricts, or its exec runs something), oldest first, as its LayerValue (the grant, and the fragment that extends it where the layer runs every program), and withholds-gpu, whether the engine’s host holds a withheld GPU. Plain ral data, not the opaque codec Root.grants and a marshalled parent ride (a-grant-has-one-outward-form).

core/src/protocol/channel.rs

  • WireStream — UnixStream on Unix, TcpStream on Windows: std’s owner of a connected stream socket, never a statement about address family (vm-manager hands back an AF_VSOCK socket on macOS, and on Windows an AF_UNIX socket that OpenVMM relays to the guest’s vsock, through the same type).
  • WireChannel — length-prefixed JSON framing (io/frame.rs) over one WireStream; pair() (test-only: a socketpair on Unix, a loopback accept on Windows), from_stream, try_clone.
  • poll_readable (Unix) — wait for a frame or a timeout, by rustix::event::poll against a Timespec deadline, without blocking inside read_frame; how engine_session notices a silent front-end with no dedicated thread. Windows has no engine half, so no twin.
  • set_write_deadline — bounds every put on every clone of the channel (SO_SNDTIMEO lives on the shared file description), turning a stalled write into the same fatal error a severed pipe already gives.
  • write_or_sever / WriteError — the severance law itself, enforced once for both doors (carrier::Line::write, engine_write, which differ only in what they record): the frame is encoded before the lock is taken, and a frame the fuse refuses is Unencodable, the wire untouched, for its writer to answer where it stands; a failed write is Severed, recorded and the channel shut down before the lock is released, so nothing appends a frame after a truncated one and no window leaves the record calling an already-shut socket healthy. Only failed I/O severs.
  • Liveness / ticks — how briskly a front-end pings and how much silence it tolerates; the deadline is judged as a count of unanswered pings (Liveness::probes), never as elapsed clock. HOST_SILENCE_DEADLINE, the engine’s armed read silence, is six default ping intervals, written beside Liveness::default.

core/src/carrier.rs

The two interpretations of the algebra, and what they share.

  • Severed — why no further frame will cross: Refused / Closed / Silent / Faulted, Displayed as the sentence a front-end shows, and code() the stable name it is quoted by; the first cause stands.
  • ProbeError — Rejected (a probe mid-run, a panicked reading, or one the fuse refused before it was sent) or Severed.
  • Host trait — one run’s host-facing surface: surface, enquire; impl Host for () is the mute host.
  • Ends — the front-end state both carriers hold in one value: the ControlSender, the EventReceiver, the severance, a Fatal<Severed>, and the session sink. A carrier supplies Transport::ends and the verbs that differ in carriage (dispatch, probe, answer); control, events, severed, sever, bind, unbind and set_deferred_sink are provided. The wire carrier overrides sever only to shut the socket too, through its Line.
  • Transport trait — the front-end side of the protocol. Construction is attach, so the trait has no attach of its own; sever lets a front-end record a fault it observed. bind(life) ends a life when the transport severs; unbind() releases it unended. It also provides the host’s typed probe doors, one per Probe: cwd, home, env_var, builtin_names, path_bytes, binding_count, leased_binding_count, largest_binding_bytes, workers, session_ended, completion_names, bindings, path_entries, each decoding through Datum and severing the transport Faulted on an answer outside its shape (read). It has no explicit session-ending verb; acknowledged detach belongs to WireTransport::end.
  • forbid_reentry / Dispatching — the carrier-uniform reentrancy law: a thread-local registry of the transports this thread is dispatching on, entered by dispatch_to_report and checked by every typed reading and the identity carrier’s probe, panicking with a didactic sentence.
  • dispatch_to_report — mint a DispatchId, aim the control door at it, call transport.dispatch (which refuses with the standing Severed itself; its Ok promises the run’s Report or the stream’s close), drain events() to that dispatch’s own Report, forwarding Surface/Enquiry to host; Result<Report, Severed>. With within, it polls every POLL_SLICE and sends an addressed strike before dispatch and whenever the observed cause rises.
  • ControlSender — interrupt(), cancel(id), end(RootCause) over one of two routes: ControlRoute::Identity applies the verb straight onto the engine’s Scopes; ControlRoute::Wire holds its transport’s Line weakly and writes a Control frame through it, a no-op once the line is gone. aim(id) records the dispatch in flight with the interrupt_epoch it was sent at, until its Aimed guard drops; interrupt() names that dispatch, and hear(ambient) names it only if the epoch has moved since, sending Control::End(cause) for a root cause; end(cause) sends one itself, and IdentityTransport::end ends with Cancelled; forward_signals() holds a process listener forwarding through that route.
  • EventReceiver — the front-end’s single-drainer event queue; its stash hands back an event a probe’s or a desk’s pre-drain read past, in arrival order, rather than dropping it.
  • Line — the wire front-end’s write end, owned by its WireTransport alone: write is the severance law’s front-end half, and sever latches a cause and shuts the never-locked duplicate.

carrier/identity.rs

  • IdentityTransport / SessionLock — the in-process carrier: an Engine behind a poison-recovering session lock. Scopes and Arc<Runtime> are held outside the lock, so control and child construction need not re-enter a dispatching engine. boot(installers, &attach) gives the wire attach’s verdict; child(&Marshalled) reads a parent through Shell::child_of, shares this runtime and applies this installer’s narrow, returning a new transport. over retains the runtime before locking the engine away. Nothing yields or accepts a Shell. dispatch lays Rails with an in-process outlet and IdentityDesk.
  • IdentityDesk — the identity binding’s EnquiryDesk: drains queued Surface events before calling host.enquire, so a handler can never outrun its own run’s earlier output.

carrier/wire/front.rs

  • WireTransport — the wire carrier’s front-end half. adopt(stream, Liveness) drives an existing duplex stream; attach(Attach) writes the only legal first frame and only then starts the heartbeat; await_attached() blocks on the reader’s Attached/Refused verdict or its own patience, counted in waits observed. A probe writes Frame::Probe and drains the event queue to the Event::Reading under its id, stashing what it reads past. A frame the fuse refuses is answered where its writer stands: a Dispatch by a Report::refused stashed on its own event stream, a Probe by ProbeError::Rejected, an Answer by an Err answer; an Attach, with no session yet to refuse into, severs Refused. It owns its Line alone. end() sends Detach and waits for Ended, proof of engine and session-worker teardown. Drop severs and shuts the socket, ending an unattended connection without certifying remote teardown.
  • spawn_wire_reader / spawn_heartbeat — the reader severs before dropping event_tx, on every exit path, and severs Faulted on a frame only a front-end sends; the heartbeat pings on Liveness::interval, holding the line weakly and upgrading it once per tick, never across its sleep, severs Silent once Liveness::probes pings go unanswered, and never takes the write lock on that path.

carrier/wire/serve.rs

The wire carrier’s engine half: a connection-lived engine process.

  • run_engine(installers) — adopts guest_abi::layout::ENGINE_FD (fd 3) as the wire channel and calls engine_session.
  • engine_session — reads Attach (the only legal first frame), restore_process_dirs (the process-level half of an attach, which only a carrier owning its process performs: a root’s cwd, every engine’s HOME, each read EnginePath::native; a child restores no cwd), Engine::boot, writes Attached/Refused, moves the engine onto a worker thread, then runs the reader loop; returns the process exit code. The loop distinguishes Detached (Detach, requiring an Ended acknowledgment), Closed (EOF, requiring no reply), and Corrupt (a read error, dead worker, silence past the deadline, or frame only an engine sends). A wire fault demotes either clean end to 1.
  • engine_write / engine_send — every engine-side write. A Report or Reading the fuse refuses is replaced by a fault; any other refusal goes back to its writer, engine_send diagnosing and dropping a frame with no writer to refuse into (a session frame, a Pong).
  • The worker’s Rails — an outlet writing Frame::Event through engine_write (an Outlet answers Result<(), WriteError>), a ChannelDeferredSink writing Frame::Session, and a WireDesk.
  • WorkItem / refusal / fault — what the worker is handed, a run or a probe, and the refusal or fault in the shape each waits on: a busy engine’s run ends in a Report::refused, a panicked worker’s or fuse-refused one in a Report::faulted, a probe in an Event::Reading(Err(..)) either way.
  • WireDesk / Parks — the wire engine’s EnquiryDesk: writes Event::Enquiry (a refused or severed write is its own Err), then parks on a oneshot registered under its EnquiryId until Frame::Answer fills it or the run’s own cancel scope fires. A park that gave up has deregistered its sender, so a late answer is dropped.
  • Dispatch — the one-run-or-probe rendezvous; claiming is the only way to mint one, so “engine busy” is never raised without work in flight.
  • Patience — the engine’s own read-silence and write-stall deadlines, armed once the first Ping arrives (both HOST_SILENCE_DEADLINE in production, a test gets a brisker pair).
  • The teardown settle — on any loop exit: Scopes::end, close the work channel, then wait for the engine thread under SETTLE_TIMEOUT (wait_ended). Join includes engine destruction and its roster drain. Only a successful join with WorkerRegistry::is_drained() may send Ended; timeout, panic or a surviving worker exits without acknowledging teardown.

carrier/testkit.rs

Core’s own test engines, booted as every engine is (BARE, boot, eval).

core/src/engine/probe.rs

The engine’s answers: Engine::probe reads one Probe off the shell (answer), rendering rows engine-side — never a live handle. probe/fs.rs — entries and bytes (behind Probe::PathEntries and Probe::PathBytes): read-only metadata walks of the engine’s own filesystem, under its cwd, judged for reading under the live grant; bytes sizes a path::tree::Walk (Granted::bytes, as path::tree::bytes does exarch’s own trees under no grant).

core/src/shell/grant/spawn.rs

  • SpawnGrant — Inherit, Base(name), or Restrict(record) carried unfrozen. layer resolves it against a FreezeCtx; narrow_onto pushes that layer onto a shell as a session frame, using Shell::freeze_ctx for the child’s env, logical cwd and scratch — the one layering step, which Shell::child_of takes for IdentityTransport::child and Engine::boot alike, so neither seat holds a narrowing decision of its own (a-spawn-is-one-layer). A `restrict record crosses undecoded and is decoded there, which keeps GrantLayer’s resolved-by-construction invariant true of every layer pushed.
  • GrantNarrower — fn(&str, &FreezeCtx) -> Result<GrantLayer, Error>, a field of EngineInstaller rather than a registered hook: core has no base-tag lexicon of its own, so a `base arm is always resolved by the host that boots the engine (exarch::policy::base_layer), and the policy is demanded of every host that boots an engine instead of left in a slot one could forget to fill.

A child’s Attach carries Marshalled, one JSON document with no inner frame. marshal::read wraps every read refusal once as a path-bearing ProtocolFailure::Decode { kind: Parent, operation: "child" } — transport’s marshalling section.

See also

engine-protocol (the why — one engine and two carriers, the channel table, the laws of an enquiry, liveness and severance), transport (io/frame.rs’s framing, Datum, marshal/Marshalled), agent (the seat, the wire-seat spawn that dials the factory), loop (the REPL as an identity front-end), synod (WireTransport::adopt over a guest VM’s virtual socket).