A run, end to end
A run is one top-level evaluation against a persistent Shell, and every
host starts it through a synchronous, runtime-agnostic run door —
Shell::run(RunRequest) -> RunReport (or Shell::run_under when the host
already holds a foreground scope) in
core/src/shell/run.rs. The request’s Run
carries a Program sum naming what runs: source text, or a registered hook
applied to first-order arguments — a block, lambda, or builtin registered by
name in the session-lived hook table (Shell::register_hook), so the host
conveys data, never closures, across the dispatch boundary. No host
reimplements evaluation, and no front-end calls the door itself: each is a
run supplier that dispatches a Run through a transport, whose engine
(Engine::run) enters the door and projects the RunReport onto the wire’s
Report for the front-end to render its own way
(unify-turn-evaluation,
run-turn-host-loop). Completion is the
door returning — never a channel disconnecting — so a spawned
worker (a server, a watch) holding a clone of the surface cannot itself keep
a run from ending; only Run.last explicitly requests the session-worker wait
(run-turn-host-loop). The
reduction primitive behind the door is crate-private, so a host cannot start an
unframed evaluation against a stale frame
(run-turn-is-host-api).
There are two doors, and which one you use is decided by what you hold.
Shell::run is for a host with no run in hand: its frame is minted under
SessionState::anchor. A host that already holds a pre-minted dispatch scope (Scopes::open’s view) uses Shell::run_under(&scope, req); the identity and wire
transports use this form so cancellation can land before a frame exists. Code
already inside a run — a builtin body — opens no second run: it applies a
function under the Mooring it was given, so the outer run’s interrupt and
wall reach whatever it calls
(cancel-is-a-join).
The request carries the run policy. A RunRequest
is exactly the places hosts differ:
- IO — a
RunIoregime sum over byte output.Inheritruns on the session’s ambient streams (cloned, then restored);Capturehas core mint fresh stdout/stderr buffers it returns inRunReport::Ran’scaptured. - Stdin — a
RunStdinchoice, orthogonal to the output regime:Inheritreads the session’s fd 0 (terminal, pipe, or file),Emptyinstalls an immediate-EOF source with no fall-through. - Terminal — a
RequestedTerminalAccess:Leasedmay foreground a terminal-bound child,Deniedmay not.Capturedoes not imply terminal ownership — a pipedral -cisDeniedyetInherits its stdin (terminal-lease). - Limits —
wall(the foreground deadline),worker_cap(the cap on concurrently running workers),cleanup_grace(how long a halting worker or combinator waits for the children it cancels), andworker_title(whether aspawnmust carry a title). - Surface — an optional run-local
SurfaceSink(Arc<dyn EventSink>), installed only for this run;Noneis the identity. - Last run —
Run.last: when the body returns, claim and wait for still-unclaimed session workers in birth order, replay stdout then stderr and discard every ending. This lifetime join never adopts a loose worker’s failure. The wait stays inside the run’s frame, wall and trail; cancellation or a replay failure can still halt it. - Trail —
trail: Option<CapturePolicy>(audit).Somedelimits this dispatch’s own extent as an audit scope and carries it home onRunReport::Ran;Noneneither opens a scope nor collects one.
The spine the run doors orchestrate is one straight line, owning resources
(Sink, Source, the run’s frame, guards, buffers) while the request describes
policy. The run doors dispatch on the Program sum, and the arms differ only
in how the program resolves — the source arm compiles first, the hook arm
looks up the hook table; both then converge on run_built and the run
module’s framed scaffold:
- Mint the run’s foreground scope — a child of the scope the door was entered
under, so a foreground timeout never reaches a loose session worker
(cancellation) — and arm its wall, if any,
before compiling, so
wallbounds the whole run — compile and typecheck included, not only evaluation.compile_run’sprocess::cleartouches only the signal count, never the reaper, so the armed ceiling survives the compile. - The source arm’s
compile_runrunscompile_and_typecheckseeded from the live session’s schemes (the ladder; type-inference). A parse or type failure returnsRunReport::Static { diagnostics }at once — no run state, no root context. The diagnostic carries theSourceits carets point into rather than registering it: a run that failed to compile leaves no live span, so its text has no business in a registry that is append-only precisely because live spans index it (static-diagnostics-render-at-the-seam). The hook arm skips this: its program is an already-compiled value resolved by name in the hook table, and the hook’s registeredDefaultPolicy(capture, terminal authority, andaside— run on ajoin_sessionsibling, so nothing flows back) folds into the run’s conditions — the hook’s to decide, not the dispatching host’s. A fault in it is labelled byHookName::fault_label(plugin 'p' hook 'h',prompt), and a hook run is no ready boundary: only a source run emits the boundary notices. run_builtmaterialises the IO regime —Capturemints the buffers it reads back,Inheritleaves the ambient streams to flow — then assembles the run’s frame in two halves, split by mutability. What the run fixes once (thesurfacesink, the deferred rail with itsworker_cap,cleanup_graceandworker_title, the desk, the foreground scope, and the run’s terminal authority) is aMooring, an owned local onrun_built’s own Rust stack frame; the surface has no liveness role, so a clone of it can never define run completion. What genuinely changes within the run is taken on loan: the byte streams — theIobuild_runseeds from the ambient session — and the two registers the run’s frame owns for its life, the root-source registersession.root_fileand the call-site register inlocal.audit.run_framedborrows the mooring, installs the run’sIothrough anIoLoan, and evaluates. The loan is RAII over that one swap: it moves the new streams ontoshell.ioand restores the previous ones onDrop, so teardown survives a caught worker panic. The mooring needs no guard — it never moved, so an outer run’s is back the instant this stack frame ends. A source run registers its root (register_root) and installs a baseProvnaming its whole-program span; a hook registers no text but installs its resolved name and origin at 1:1. Workers inherit the parent’s register at spawn. The body runs under the session’s stack.audit_deputy_prefixesreports its flagged prefixes to the run’s trail before evaluation —run_phrases(&top.phrases, shell.env.clone(), Mode::Session, mooring, shell)for the source arm, the in-frameshell::evaluator::applyof the resolved hook for the hook arm (the machine; unify-turn-evaluation).run_phraseswrites eachletstraight intoshell.envas itsDefinelands, and acdor hook registration is an unbracketed write straight toshell.context— there is no post-run install step, so a halted run keeps every write that landed before the halt and the run remains a resume point regardless of completion, error, orexit(exchange-ends-ready). After anyRun.lastreturn-wait, the run’s body disarms the wall (waiting on a firing already claimed), andShell::base, the run’s base, makes the closing poll,final_pollon the run’s node, so a stop that landed after the body’s last poll — a key a terminal loan heard back and struck on the node included — is not lost; a stop is an escape notryabsorbs anyway. The same base completes any unlocated error or stop from the run’s own total register, and folds the result intoEnding<Value, Error, Stop>:Ok,Err,Exited,Stopped, orPanicfor a panic it caught.run_framedthen emits ready-boundary notices (none for a panicked run) while the run frame and sinks are still installed.- Back in
run_built, the ending goes into the report. A wall is aTimedOutstop, not a separate flag.RunReport::Ran { ending, base, compact, captured, trail }carries it home;base, the run’s origin at 1:1 thatrun_underresolves once, sites a data-boundary refusal after the register is restored;trailstartsVec::new()here —run_builthas no view of the dispatch’s own scope, only of what a body opened and closed on its own account. - One level up, at
Shell::enter— the durability wrapper all three run doors funnel through — aRun.trail: Someholds aTrailScopeoutside thecatch_unwindthat recovers a mid-run panic, opened beforedispatchruns and closed once it returns, on every exit. That placement is load-bearing: the(env, context)checkpoint the panic arm rolls back does not coverlocal.audit, so only a scope the panic itself cannot skip keeps the trail’s close law true at dispatch granularity. A clean exit’s observations land inRunReport::Ran.trail; a caught panic’s are drained and discarded — the panicked dispatch reportsRanwithEnd::Panic, status 101, no compact root, capture or trail.RunReport::into_reportcallsEnd::renderagainst the shell’s sources, borrowing its actual session exit-hints table; errors, stops and panics share theDiagnosisrenderer. The wire alias isEnding<FOValue, ErrorFact, CancelCause>: a value becomes first-order data, an error itsErrorFact({frame, reason, site}), and aStopits cause. A non-data value becomesErr, code 1, completed with the retained base even after the caller’s frame is restored.Reasonis shared by runtime error and fact; a program reads theErrorRecordprojection, whosemessageandstatusare derived from it (the error record).Report::Ran(Ran { ending, rendered, single_command, captured, trail })keeps run context outside the cases;Report::code()is the host’su8status. AStaticrenders throughStaticDiagnostics::render(2 parse, 1 type);Report::Faultedis only a lost report, not a known panic ending. The seam projects eachObservationthrough `encode` ontoReport::Ran.trail: Vec<FOValue>, unbounded by declaration — the wire’s frame fuse is the shared backstop, as it already is forcaptured.
The hosts differ only in the request they supply.
-
The REPL’s
exec::step(ral/src/repl/exec.rs) suppliesorigin: SourceOrigin::named("<stdin>"),GrantStack::root(), no limits,RunIo::Inherit,RequestedTerminalAccess::Leased,RunStdin::Inherit; it builds aProgram::SourceRunand drains it throughcarrier::dispatch_to_report(..., None)on itsIdentityTransportwith the REPL’s ownHost(ReplHost), rendering the terminalReportwithprint_result— anErr(Severed)prints the cause and ends the session. Thepre-exec,chpwdandpost-execplugin hooks are dispatches of their own around it, as are the prompt body and every other hook (ral/src/repl/plugin.rs,prompt.rs):Program::Hookruns of hooks registered by name, through the same door (loop). -
exarch’s
run_shell(exarch/src/shell_eval.rs) supplies a virtualoriginnaming the call’s turn (turn N), its session grant profile, a per-toolwall, aworker_capon concurrently running workers, a 2 scleanup_grace, a requiredworker_title,RunIo::Capture,RequestedTerminalAccess::Denied,RunStdin::Empty,trail: None; it builds aProgram::SourceRunand drains it throughcarrier::dispatch_to_report(..., Some(exchange))against its call’sRunHost— oneHostpairing the enquiry desk with the applier that renders each live surface value onto the presentation bus — and hands back theResult<Report, Severed>itself;Agent::ralrenders the cappedToolResult, or the one sentenceagent::EngineLostrenders for a severance (agent). The session’s host-installed layers are the sandbox — ral’s grant, not a source-levelgrant { … }the model could escape — which is why exarch needs no evaluator of its own (exarch-architecture). Its owner passes the explicit exchange scope: identity dispatches mint beneath it, while the wire drain polls it everyPOLL_SLICEand strikes only this dispatch id. The dispatcher also checks before sending; cancellation already in force opens the run born cancelled. The engine root still dominates termination:Scopes::endstrikes both root and current dispatch, even when its parent is an exarch exchange. Cancelling threads never write to an engine. A foreground shell call borrows the agent body throughLoanable::lend; it returns on unwind too. Deferred worker batches carry engine generation, surviving Stop/reply and rejected after clear replaces the engine. Loose workers belong to the engine. Jobs are recorded busy periods for every agent; Synod gates its root across baseline and closing walks. Stop recalls human text and cancels only exchange, leaving helpers working (an-agent-is-a-thread). -
ral’s batch path (
ral/src/batch.rs) boots anIdentityTransportfrom thebatchinstaller, dispatches the_ral-boothook, then the script as oneProgram::Sourcerun withlast: true,RunIo::InheritandRequestedTerminalAccesskeyed to whether it owns the terminal — the same door, the same ending law, and the same typecheck as the REPL (startup). Return waits for loose workers and replays their bytes without adopting their endings; halt skips the wait and session teardown takes them down. Batch silently consumes theirdoneevents. REPL lines and exarch calls leavelastfalse; their session ends are halts (endings).
The human and the model are interchangeable suppliers of top-level runs over
one persistent Shell.
See also compilation-ladder, evaluator-machine, cancellation; run-turn-host-loop, run-turn-is-host-api, unify-turn-evaluation; maps repl, exarch.