Map: core / shell / exec
core/src/shell/exec/ is the OS plumbing the CBPV machine
dispatches into — command execution, pipeline orchestration, and the
per-child confinement choice. It re-enters evaluation only through the
pipeline::StageEval the machine passes to PipeNode::run (a stage’s
(comp, env), run from pipeline/thread.rs) — stages carry computation
closures, so the mutual recursion is irreducible, though shell::exec names no
shell::evaluator item; the evaluator reaches it at
PipeNode::run and, dispatching an Exec node, at
resolve::Resolution::of → Command::run, and the redirect scope
(redirect::RedirectState), which the machine’s Frame::Redirect holds
(evaluator-runtime-split).
resolve.rs—Resolution::of, the single site that resolves a head (env → handlers → external). The machine’sExecrule runs every arm but the external, whichCommand::run(command.rs) runs under its redirects. There is no builtin arm: a native table entry is anEnvhit on a native value, and a base-frame row is aHandler(HandlerLookup::Base)hit on the handler stack’s base layer, run by theExecrule with the argv slice (builtins, exec).^nameand a path-bearing head are the external directly, consulting neither the env nor the handler stack. Grant admission is an external-command property: only theExternalarm looks the head up and admits it (Command::lookup,Command::admit) before its redirects open, refusing it outright, and carries the admittedCommandto preparation; the env, base, and handler arms pass through. Every base frame has[String] → Command; stored named handlers haveU([String] → Command), and catch-allsU(String → [String] → Command), independent of names and Σ. Arms are written as{ |args| … }or{ |name args| … }, or computed. The install position fixes the convention, checked by type rather than inferred from a value’s runtime shape (handlers-are-lambdas).redirect.rs—RedirectState, the one interpreter of a redirect list: open every target (open_targets), install them over the shell’s streams withIo::swap, and on leaving restore the streams and settle eachPendingWrite(commit,abort,abandon);with_redirectsbrackets a synchronous call. Write targets open overpath’sLocated::stage/open_streaming(StagedWrite,Streamed): staging a write is the path’s, judging and committing it the shell’s.Shell::atomic_writeis the same>recipe, unobserved, for host writes below the redirect frame.capture.rs—with_captureand the audit tee, both over onewith_io_patchedbracket that swaps the streams back on return or panic. Audit retains 1 MiB per stream as a prefix and a byte total, independently of ordinary capture.command.rs::Shell::run_externalis^program args…for a host holding no syntax: theExecrule’s external with no handlers, no redirects and no span, never evaluating shell source. The caller supplies its mooring; current grants, scope, audit and streams remain in force. The REPL external-editor hook uses this entry.command.rs::would_run(name, mooring, shell)checks a bare external name throughCommand::from_name→lookup→admit, then returns the retained lookup error, if any. It launches nothing and records refusals through the ordinary admission door.temp-dir/temp-fileuse it forrmbefore creating a path (a-guard-acquires).record.rs—CommandRecord, an external’s oneObserved::Command, begun from an admittedCommandand ended once; silent, holding nothing, when nobody listens at launch.Command::with_recordis the shape that ends it before its frame closes: enter the frame, begin the record, tee the streams, locate a failure with the visible head and span, end the record.Command::runanddetachshare it. A failure is aReason::processnamed for the head as dispatched, minted where the child’s end is known (command::ending,Program::exec_error); its text isReason::describe. A direct external stage outlives its frame, so it carries aStageFrame(itsProvand its record) from launch through collection, completing errors and stops before its settlement ends the record.command.rs— one external command, in pipeline order:Command::from_namerecords what to look up (Request);lookupfinds the program and checks the grants (Command<Lookup>), reporting nothing, which is allhelpneeds;admitreports a refusal and keeps a missing program (Missing, converted once byinto_error) as anErrorforprepare, so the 127/126 verdict is reported inside the command’s record and redirects and beats a bad argument.prepare(args, ownership, shell)vets argv and builds aPrepared: theProgramLaunch, itsConfinement, and theProgramit starts, which outlives the consumed launch to explain a failed start.Prepared::startinstalls an ownedio::child::Connection, starts the drains from their owned readers, then spawns, so a thread creation failure leaves no child to tear down. A spawn failure returnsStartFailure, owning itsProgram::unstartedreason and drains. A standaloneruntitles the terminal first and settles a failed start before propagating its reason;PipeNode::finishrolls back and joins before settling those drains, even when no stage registered.startspawns throughProgramLaunch::spawnand takesConfinement::denial_pidsof the result: a confined direct child’s pid, orpayload_pidsof a Linux envelope’sGroup::Enveloped.Startedowns the resultingSpawned<Group>, itsdenial_pidsand the runningDrainsuntilcollectorregister(pipeline/collect.rs) consumes it; registration cannot fail. Building describes and starting acts (exec).uutils.rsholds bundled coreutils. The process-layerPlacement::command(shell.group_owner(mooring))selects the request once;Source::offered(placement.input())wires terminal stdin before start.- The program and the 126/127 verdict come from the judged candidate
fold’s walk.
Command::from_namesnapshots aRequestwithout I/O: a bundled tool, a launch path, or a bare name with its effectivePATHandContext::cwd. For a bare name,Command::lookupfolds thePATHcandidates in order throughpath::search, which walks each once and hands the judgment aCandidate. Each candidate’s object, absent leaf orfailure_traceis judged before its kind or error is disclosed. The first admitted program runs; otherwise the first refusal or 126 says why, and only absence yields 127.Command::admitrecords a selected refusal throughShell::exec_refused;preparereads the checked result without probing again. A path head’s native target — as written, or expanded byTildePath::expand— is anchored at the launch cwd with only.folded; the launcher runs the judged program by its real path, the shown spelling asargv[0](exec-judgment). - The argv-shape step is one refused set read at two moments.
check_argvmaps each argument’s head (Value::heads) throughRefusedArg::of_head(core/src/ty/exec_arg.rs) and carries the shape’s ownremedy; the checker maps the argument’s type throughRefusedArg::of_tybefore the run, so this is the backstop for what a type variable hid from it (exec-argv-is-words, exec-boundary-gated-statically). command/detach.rsreceives a description, a program name and an argv slice from the first-class nativedetach, whose type isString → String → [String] → F [pid: Int, desc: String]. It checksShellVerb::Detachpermission and then uses the same command lookup, admission and preparation (Ownership::Surrendered) up to the one act that differs,Prepared::detach, private to that file: the child is born by the matching direct or envelopedspawn_detached(io-process), so its pgid is never observed here and nothing can signal, await, or reap it. What replaces the handle is a first-order{pid, desc}receipt. The birthing frame’s projection is rendered into the launch exactly as for a child we keep, only withauthority::sandbox::Ownership::Surrendereddropping the parent-death tie, so the survivor’s authority is frozen as that frame left it and no later frame can widen it — it cannot name the process at all (capabilities). All three of its standard descriptors are/dev/null. The program is resolved as^programresolves one, bypassing bindings and the whole handler stack, including base frames; an installed handler never causes a refusal. Handlers cannot interceptdetachitself either: stub it by binding its name.- A bundled coreutils/diffutils/ripgrep head is a
Program::Tool, always run as aral --ral-bundled-tool <tool>child — its inherited stdio, env, cwd, process group, and sandbox are the execution context, so it threads the same spawn/collector/audit machinery as a host external, and behaves identically on Windows where no.exeexists to spawn (bundled-tools-as-exec-images, bundled-tools-always-reexec). - Terminal authority is reached once.
Shell::group_ownerreturns a stage membership without a permit, or session facts gated byTerminalAccess::reach: access, a session lease, and terminal-bound stdout (unlessExplicitLoan).Placement::commandmaps a stage toJoin, a permitted session toTenant, and an unpermitted session toInheritwhen interactive orNewSessionotherwise. Capture precedes spawn.Placement::inputpermitsInherit,JoinandTenant, withholdingNewSession. Enveloping changes only the actual landing:EnvelopedLaunch::spawnenforcesStep::NewLeader; an eligible envelope retains readable stdin and a restoration-only hold, even in a script. The direct tenant handoff belongs toPlacement::land, not collection;lend(&Leader)requires the fresh-group birth certificate. Refusal kills the group while its leader pins the ID, kills/reaps the child, restores state, and releases the jail; the caller then settles theStartFailuredrains with no later numeric-ID kill before returning the refusal. There is no parking: the reaper answers any stop withSIGCONT(pipeline-execution, ral-does-not-suspend). - Redirects install on the handler arm. One interpreter,
shell::exec::redirect::RedirectState, installs them for an external and a block alike (redirects-are-bindings).io::child::Connectionbinds child streams for standalone commands, direct pipeline stages, and externals inside stage threads (io-process). Pipeline topology stays inByteInandByteOut: a direct stage consumes its downstream writer throughConnection::to_pipe, while a thread stage makes its ownSink::Pipe. Parent destinations are borrowed after admission; owned pipe writers move. Connection takes the selectedSourceas it stands, so terminal stdin permission remainsTerminalInput’s alone. - The read redirect (
< file), the write redirect (> / >> / >|, settledcommitted/aborted/failedat frame teardown), and the exec (Host andBundledToolcompletion) each build anObservation(core/src/shell/runtime/audit/observation.rs) and pass it toShell::observe(core/src/shell/runtime/audit/fan_out.rs), the one fan-out: it reports to the run’sMooringand to the open audit trail alike, judging neither’s interest — the host filters the rail. It judges only whether anything happened: a write onto the discard device is dropped there (audit). Core emits plainValue::Maps throughValue::from_datum; a host (exarch) decodes their first-order wire form back withObservation::decode. The observation shapes and their card rendering live in io-surface (surface-reads-writes-execs).
- The program and the 126/127 verdict come from the judged candidate
fold’s walk.
pipeline/— pipeline planning and execution; the mechanism, its teardown order and its forgiveness rules are described in pipeline-execution. A multi-stageCompKind::Pipelinesteps through aPipeNode { collect, group }:PipeNode::runresolves the plan, prepares or joins the group, launches every stage onto the collector, rolls a part-way failed launch back, andjoins (drive,end_anchor, thenfold). No frame is pushed, so an unwinding panic tears the group down through the collector’sDrop(evaluator).PipeNode’s field order is its teardown order: the collector drops before the group, so its kill still reaches a pgid the anchor pins (a-teardown-kills-before-it-joins). A standalone external takes the same collector:Started::collectbuildsCollectState::lone, registers through the sameStarted::registeras a pipeline stage, and settles it withsettle_lone; both live besideCollectStateincollect.rs.resolve.rsfreezes each stage’s launch decision once asStageLaunch(Direct { command, args }|Thread) from the head’s resolution, its redirects, and whether a!{…}audit captures bytes, so launch reads a decision rather than re-deriving a dispatch gate. A stage with redirects is aThreadstage run throughRedirectState; aDirectstage has none, andPrepared::startwires its stage pipes without interpreting a redirect list. Nothing about a stage’s value enters that decision: a stage’s dispatch may not depend on what its neighbours return, or the choice would stop being observationally transparent. ADirectstage is a process in the group; aThreadstage is an OS thread whoseShellstarts from the parent’s session, and only an external it spawns, at any nesting depth, is a process. A bundled (uutils) head routesDirectlike any external, itsral --ral-bundled-toolchild the image chosen byCommand::prepare. Ordinary application and bind do not enter this runtime.route.rs’sopen_stage_routesallocates every interior edge as an operating-system byte pipe from stage position alone — the zip ofParent : insagainstouts ++ [Parent]— and no stage is told which one it is: every stage reports what it settled, and the fold, running in launch order, keeps the lastOk, which is the final stage’s whenever that stage isOk(pipes-are-positional-byte-wires). A non-final stage’s returned value is discarded, never serialised onto an edge; aThreadstage’s final value rides home on its ownStageObservation, no wire in between.pipeline.rsis the spine:PipeNode::runis resolve, group, collector,launch, onespawn_stageper stage pushed onto the collector, then, after aroll_backif that failed,join. Only an owning pipeline (no enclosing stage) captures a permitted preparation before anchor spawn.PipelineGroup::preparereturns the group, opaqueTerminalHoldandTerminalInputchosen after readiness and handoff; a nested pipeline joins with readable input and an empty hold.launch.rswires one stage’s byte endpoints (stage_stdinfor a thread,Prepared::startfor a process) and dispatches it on its frozenStageLaunch(spawn_stage, which resolves the stage’s stdout once for either kind, andlaunch_external_stage_direct);LaunchCxcarries what both read,input: TerminalInputamong it; stages never inspect the hold.stage.rsholdsStageHandle, which dispatchescancel/cut/watch/listenover its two kinds,External(LiveExternal)/Thread(ThreadStage).cancelrecords the cause on its ownsent, joined bymax, and tells a thread’s scope (a process hears a cancellation only as the signal the collector sends next);cutis that cancel withReaderGoneplus the external’s kill,Effect::KillStage’s action once the sentinel (sentinel.rs) has heard a dead write;listensets the sentinel on the outbound edge once, andheldis declared beforekind, so a forced end drops the hold before it joins. AnExternalis acrate::process::Watchalone, the reaper’s own subscription: no dedicated waiter thread, the reaper’s posting closure putting the exit straight onto the collector’s channel asEvent::Ended(ix, _).file_external_endreaps the watch, after the stage has leftstages, so no laterKillStagecan name a reaped pid, and releases the held-open edge, leaving anExternalEnd { drain: Drain, settlement: Settlement }to the fold:Drainis the jail and the pumps, which wait on the group kill;Settlementis what the ending reads.file_thread_endjoins before releasing the held edge;collect/tests.rschecks that repeated pipelines return with no live stage tickets. These tickets outlive the stage’s child shell, so they measure stage teardown without counting unrelated process-wide threads.group.rs—PipelineGroupisOwns { anchor, .. }orJoins(Membership).preparespawns the pgid anchor (--ral-pipeline-anchor, ignoringSIGTSTP/SIGTTIN/SIGTTOUand immune to termination signals) on every platform before any stage exists. On Unix it waits for a zero readiness byte after the handlers are installed, and starts its witness in the same act. Only then doespreparelend to the anchor: success selects readable input, no preparation or refusal selects withheld input. Refusal restores immediately because only the anchor exists, reading its release pipe and reporting signals without changing modes; no stage needs teardown yet. The witness is a report reader blocking to EOF on the anchor’s stdout, postingEvent::Heard(signal)raw per swallowed signal, and the anchor’s ownWatchpostingEvent::AnchorDied.group()answersGroup::Ownsfor an owner andGroup::Joins(membership)for a joiner, which lends no terminal on its own account;joiningis the no-anchor shape a nested pipeline in a stage thread gets, andmembershipis what a thread stage’sSeatcarries: an owner’s leader paired with the stage’s scope, or a joiner’s own.AnchorProcess::endcloses the release pipe and joins the report reader; dropping the anchor reaps it. The group’s verbs are lifecycle only —prepare/joining,group,membership,end_anchor,Drop: signalling and killing belong to the collector, which holds the live stages (a-process-group-is-its-owners-to-signal). On Windows an owned group also holds aJob.thread.rs—launch_thread_stageparents a stage node under the current scope, including an acquisition or release shield; worker nodes instead follow their cradle’s owner (shell state). It wires aThreadstage’sIofrom its stdin route and resolved stdout; its closure, given itsSlot { ix, tx }and wrapped in aSettleOnDrop, builds its ownStageObservationand sendsEvent::Returned(ix, obs)as its last act, the guard armed until then so an unwind reports in its place. A non-final stage’sstdoutis its own edge; a final stage’s is the parent’s, so a discarded statement in the final stage writes where an enclosing capture’s buffer (shell.io.stdout) is (capture). A captured final stage is aCapturenode, so it runs as a thread stage.ThreadStageis the collector’s handle onto the running thread:cancelwrites the cause on its node (on Windows also oneCancelSynchronousIo, re-issued while the stage’s chain carries a cause),join_after_settledreclaims a thread whoseReturnedhas arrived, andDropcancels and joins one never observed, a slice at a time.collect.rs—CollectStateowns the stage handles from the first one launched and anmpscchannel every producer feeds: the reaper, a stage thread’s own report, the sentinel, the anchor’s witness and its watch.recvfirst sweeps the edges (sweep_edges), then reads the current scope between slices and mintsEvent::Cancelleditself. The events areEnded,Returned,Wrote,Cancelled,AnchorDiedandHeard; there is noStoppedvariant, the reaper having answered a stop already. The pure foldstepreturns at most oneEffect(KillStage,CancelAll { cause }) for the thin interpreterCollectState::runto perform;driveiswhile live() { recv; step; run }, with no interval and no backoff. Completion is not an effect: the pipeline is finished exactly when no stage handle is left. AHeardkey strikes the run’s node and recordspressed, but only through the collector’s opaqueterminal: TerminalHold, never by matching its representation. Only a lent hold attributes a key.cancel_all(cause)is the teardown, in the order its home page fixes;CollectState::dropwritesTerminatedon every live thread stage and kills whenever it is dropped with a stage still unobserved.foldopens withvacate, which hears out every queued report and returns the loan before any pump is joined, then settles each external throughStageEnd::settleandSettlement::observe: the one place&mut Shellreaches an external’s settlement (audit synthesis, exit-hint lookup, sandbox-denial augmentation). The verdicts join bystrongeroverBreak::rank, an escape outranking an error and ties going to the earlier stage;drive,cancel_allandsteptake no&Shellat all. Which stops the collector forgives is fixed in pipeline-execution. TheSlota stage hands its own producers is minted bylaunchfrom the sending halfPipeNode::runholds and drops once the stages are launched; the collector keeps none.anchor.rsis the hidden--ral-pipeline-anchorchild’s entrypoint (Role::PipelineAnchor; a bundled tool’sRole::BundledToolis launched beside it byauthority::sandbox::reexec::launch). On Windows every external a stage thread spawns still resolvesPlacement::Joinagainst the anchor’s registered Job Object, assigned at creation under the suspended create → assign → resume path (windows-spawn-boundary).
- A
grantis a dynamic effect scope, not a process boundary, so the grant body always evaluates locally — the machine steps its body in process, with no router in between: nested grants compose by intersection over authority, an algebra of the evaluator’s dynamic context. Confinement happens elsewhere — the RAL-owned effects are decided in process byauthority::guard::check_*(capabilities), and child-owned effects are kernel-backed at external dispatch: when a projection is active,Command::prepareobtains a confinedprocess::Launchviasandboxed_command— per-command Seatbelt / bwrap confinement on Unix; on Windows the LowBox token of the projection’s own AppContainer profile, carrying the per-path fs capability SIDs its projection names (path-derived-capability-sids) — and net/fs fail-closed fires when a child is actually spawned, not at grant-body entry (sandbox-external-children). Inside a guest, preparation takes neither projection branch:jail::guest()marks every spawn as already confined by the spawn jail: the one unprivilegedGUEST_ID, a per-exec cgroup, the envelope’s seccomp deny-set, and close-on-exec marking of every descriptor above stderr. An offline command also gets a fresh network namespace with loopback up; IP and outside abstract Unix sockets are out of reach, while pathname Unix sockets remain reachable through the filesystem.process/jail.rs(io-process) carries the plan, andjail/linux.rsenforces it before the pgid and detach hooks, since bwrap needs the user namespaces the guest boot disables; the in-process guards apply unchanged, and the collector’s external stage tracks the per-execJailCgroup, so cancel and settle kill the whole tree throughcgroup.kill(asetsid’d grandchild cannot leave its cgroup) while the grace phase stays pgid-addressed (docs/SPEC.md§12.11).core/src/marshal.rsandmarshal/(crate root, notshell/exec/) encode and read a parent’sImageand spawn grant asMarshalled. Every helper session, in process or in a VM, starts throughShell::child_ofover those bytes. A pipeline stage instead shares memory on its own thread (stages-are-threads).
The Shell state these thread is shell-state; the serde
mirror and wire envelope they ride is transport.