Map: repl / startup
The ral binary startup has four parts: startup.rs decides what
kind of process this is and holds the binary’s engine installers, cli.rs
distils argv into a Mode, main.rs dispatches the answer, and batch.rs
runs non-interactive programs through an engine it boots, speaking only the
protocol. Interactive sessions then hand to the REPL, above a
pre-clap dispatch that lets the binary re-enter itself in confined or helper
roles.
main itself holds no substance — it refuses to run setuid, lets the
POSIX bridge claim an ral-sh invocation, adopts the process dispositions,
asks startup::identify() what this process is, and runs the session named. identify answers with a two-armed Invocation:
Shell(Mode), or Exit(ExitCode) for a re-exec child that has already done
its work — or for an argv that is not text: ral’s arguments become strings,
so one that is not UTF-8 is refused with status 2, never mangled.
Process-role dispatch
One pure classifier names the hidden role a process was started for, and
one dispatch serves it. ral_core::classify(argv)
(core/src/role.rs) keeps the launch vocabulary and classification independent
of execution; core/src/invocation.rs owns dispatch. The classifier reads the
first argument alone over Role::ALL and
returns an Invocation: Engine, Linux x86-64/aarch64 GuestEngine,
PipelineAnchor, Warrant,
BundledTool, Unix EnvReport, or Shell. Each flag is spelled once,
by Role::flag, and disjointness lives there and nowhere else — a flag a
script was given, or a tool’s own --engine, names no role. ral_core::invocation::serve(&role, installers)
is the one place a role is served, each role’s body staying with the code it
serves. ral’s identify hands it the role it classified; exarch’s main
calls ral_core::invocation::serve_process(installers), which reads argv
itself, and every test #[ctor] its twin serve_process_before_main, which
reads it where a constructor can (on musl std has no argv before main, so
/proc/self/cmdline, though the role it serves still runs without one: see
exarch). They differ only in what they do with its Option<u8>; what
it decides is when each role is pinned. Before argv
is parsed, main refuses to run setuid — the shell inherits the caller’s
environment and must not run elevated, and neither must any re-exec child, so
the refusal precedes the whole chain — and restores the Unix signal
dispositions. Then, per role:
- Confined child (
Warrant) — served byserve_warrantalone, before any pin, so the child pins and opens nothing before it is confined.ral --warrant <fd>is the whole argv of a confined re-exec: the child takes its warrant off that descriptor, enters the OS sandbox, and only thenexecves the host program or runs the bundled tool in-process. Windows refuses it. - Environment reporter (
--ral-env-report, Unix) — writes the host environment on fd 3 and exits, without pinning or booting anything./bin/sh -lexecs it bylogin_env::collect’s canonical self path. - Pipeline anchor —
shell::exec::pipeline::anchor::serve(--ral-pipeline-anchor, the one multicall re-exec a pipeline uses: a stage itself runs on a thread of the parent process, but a multi-stage pipeline needs one process to hold its pgid open for its whole life). It spawns nothing, so it is not pinned. - Every other role runs
authority::sandbox::bootfirst, which pins the binary (and, on Linux, bwrap) and, on Windows, sweeps what a crashed prior session left registered; the bundled tool onlyauthority::sandbox::pins, as a re-exec child that reaches no ledger.- Guest engine (
--guest-engine <cgroup-root>, Linux x86-64/aarch64): validates one absolute root and euid 0, installs the spawn jail, then servescarrier::run_engine. A refusal is rendered byterminal::cmd_errorand exits 126. - Engine (Unix) — then hands the process to
ral_core::engine::run_engine(installers), pinned exactly as the shell is: its grant-confined launches need the envelope as much as the shell’s.ralpassesstartup::engine::INSTALLERS, so a wire-engine child boots through the very recipes the in-process front-ends boot through. The table holds twoEngineInstallers:repl(repl_runtimeandrepl_rootover the REPL surface, configured by nothing) andbatch(batch_runtimeandbatch_rootover the batch surface, decodingBatchConfig {args}), each registering the boot builtin; the REPL’s also registers theexternal-editorhook. Both share a refusingGrantNarrower, because the shell spawns no child engines and has no base-tag lexicon to resolve a grant against. - Bundled tool (
serve_bundled_tool,--ral-bundled-tool <tool> …) — then runs the bundled coreutils/ripgrep image in this child process (uutils::serve), under whatever sandbox the process inherited. Every bundled head launches as such a child (bundled-tools-as-exec-images, bundled-tools-always-reexec), and each external child launches under the effective policy (sandbox-external-children). - Shell —
None, andidentifyanswersShell(Mode).
- Guest engine (
The roles that are not the shell exit here, never reaching clap.
Modes
ral/src/cli.rs owns the clap surface, and Mode::from_argv is the one entry
through it: clap, then Cli::into_mode. The mode tests
enter by the same entry, so the parse they exercise cannot drift from the one
startup::identify performs. Cli::into_mode distils the parsed flags into a
Mode: Interactive(InteractiveOpts), Script, or Command — login is not a
mode of its own but a flag on InteractiveOpts (login, set by -l or a
--prefixed argv[0]), so a login shell with -c or a script positional
still resolves to Command/Script and runs it, as cron, su -, and
$SHELL -l -c … require; the flag matters only once resolution has landed on
Interactive, where adopts_login_env requires login, no --norc, and
an interactive stdin mode. On Unix, run calls login::adopt_posix_profile
before the UTF-8 environment warnings and before session boot: /bin/sh -l
reads /etc/profile and ~/.profile, and host::login_env collects its
NUL-delimited report from an unnamed file on fd 3. Changed/new variables are
set, removed variables unset, with SHLVL, PWD, OLDPWD, _ ignored.
Failure warns and leaves the starting environment intact. This occurs before
any thread exists; signal setup and the engine follow. Windows adopts nothing
(login environment). RunOpts (--recursion-limit, --capabilities)
rides every mode; BatchOpts adds --audit / --pretty / check: bool
(--check); InteractiveOpts adds -l, --norc, -i, -s, and
--surface.
- Argv boundaries. Clap’s
trailing_var_argpreserves everything after a script positional, including the literal filename-. The value-taking-cusesnum_args = 1..andallow_hyphen_valuesto consume source and program arguments, including flag-shaped tokens and literal--. Short clusters putclast (-ec,-lc); attached text is source (-cemeans sourcee). Long options retain clap’s ordinary value parsing. Theral-shbridge routes POSIX-cinvocations before this parser. - Frontend selection.
--surface <minimal|readline>(a clapValueEnum, defaultreadline) picks the interactive frontend, overriding the rcsurface:key;Nonedefers to rc, then the default. The capability axis stays theRAL_INTERACTIVE_MODEenv var — the escape hatch for setups that do not own argv — and still wins over the surface choice. Surface internals live in frontend. - Interactive/script fork.
InteractiveOpts::reads_stdin_as_scriptencodes the precedence:-sforces stdin-as-script and beats-i,-iforces the REPL, otherwise stdin being a tty decides; a script positional, if present, is run instead of either. The REPL path hands off to `repl::run_interactive`.
Batch execution
ral/src/batch.rs owns the whole non-interactive pipeline, from the source
text inwards: run_file reads a script path, run_stdin reads a piped script,
and both meet -c at run_source, which is therefore where line endings are
normalised — one place, one rule. Batch holds no Shell: it boots an
IdentityTransport from the batch installer and speaks only the protocol,
through dispatch_to_report with its output host, so it shares the REPL’s
one ending law and one typecheck
(engine-protocol).
- Boot, stage one.
IdentityTransport::bootwith thebatchinstaller (the table is notcfg(unix)-gated, onlyrun_engineis), whose recipe decodesRoot.config—{args}— strictly, boots the batch surface, sets exit hints and args, and registers the boot builtin.platform::local_attachbuilds the attach at this process’s cwd and home, the probed terminal inEngineSpec.terminal, and batch adds its config. A refusal exits 2 with its sentence on stderr. - Boot, stage two. The first dispatch is
Program::HookonSession "boot", the_ral-bootbuiltin itself (ral/src/boot_builtin.rs), applied to the REPL’s own record,{no-rc: true, recursion-limit, capabilities}. The builtin is one-shot — it unregisters its own hook — sources no startup file here, sets the recursion limit, and applies--capabilitiesunder its own mooring. Each profile path reaches it absolute, anchored at the invocation cwd byBoot::profiles, so no profile’scdcan redirect a later one.boot_builtin::settlereads itsEnding: a load failure isErrstatus 2, anexit NisExited(N), and either stops batch there, exactly as it stops the REPL. - Check or run. After the same full boot,
--checkdispatchesProgram::Checkinstead ofProgram::Source. Both compile in the engine under the booted session’s environment and grant;Checkstops before evaluation. Profiles and--recursion-limitapply equally. Module reads therefore have one resolution and authority rule. The CLI has no static dump flags or-nalias. - The run. The script is a
Program::Sourcedispatch underGrantStack::root()withRun.last: true, inheriting IO and stdin; the engine typechecks it once against the live session. The terminal isLeasedonly when the probed terminal carriesstartup_foreground(terminal-lease). A watched worker’s lines reach batch’s deferred sink, which prints them to stdout. A returning script claims and waits for still-unclaimed loose workers in birth order, replaying stdout then stderr and discarding all five endings. A halt skips that wait and session teardown takes them down. Theirdoneevents are silently consumed; no completion notice changes output or status. - The verdict. batch prints the
Report’srenderedas the REPL does and exits onReport::code() -> u8throughstd::process::ExitCode::from(u8). - Audit.
--auditasks the script’s dispatch for its trail (Run.trail) and maps the whole ending throughDatum:`ok value,`err record,`exited n,`stopped causeor`panic text. Unit’s payload is absent, so a unit result reads{"tag":"ok"}; no record re-decoding or fallback is needed (endings). Static refusals also carry a trail envelope, including check-time module-read denials stamped atuse; their diagnostics retain their static status and rendering.
Embedding and the baked prelude
A run-evaluating host needs three things before rc files or capability
frames: the prelude as a baked `Comp`, its top-level scheme
list, and its own builtin surface as a ral_core::HostSurface. Every mode
reaches for them through ral_core::shell::boot — the Shell-embedding seam — via the
crate-root PRELUDE: ral_core::shell::boot::BakedPrelude static built by the
ral_core::baked_prelude!() macro, and
ral_core::shell::boot::boot_shell(terminal, &PRELUDE, surface), which constructs
the shell, installs the surface next to CORE_BUILTINS, seeds default env
vars, and registers builtins against the prelude comp. BakedPrelude lazily
postcard-decodes the IR blob on first access. Probing the
underlying machine is a separate concern, owned by ral_core::host.
build.rs is the git-hash block — stamping RAL_VERSION_SUFFIX (+<hash>
in a git checkout, empty in a release tarball) into the version string — plus
one call to ral_core::shell::boot::bake_prelude, which
parses, elaborates, and bake_preludes core/src/shell/prelude.ral (annotating each top-level
bind with its inferred scheme in one checked pass) and returns the
annotated Comp serialised, which the script writes into OUT_DIR. This is the consumer half of core’s schema-less prelude discipline
(core): a crate’s build script cannot depend on the crate it builds,
so core cannot bake its own prelude, and each embedding host bakes it from core’s
source. Evaluating the annotated prelude installs each binding’s scheme into
scope[0], so the per-run seed and the prelude’s own schemes agree by construction
(type-inference).
Platform glue
ral/src/platform.rs centralises the host queries and shared exits the
binary needs: probe_terminal (under RAL_INTERACTIVE_MODE),
local_attach (an in-process engine’s Attach, at this process’s own cwd and
home), load_exit_hints (user override in the data dir, else the embedded
data/exit-hints.txt). Every shell ending already has a byte status;
exit and fail refuse out-of-range inputs and only external failures are
clamped at entry. The utility subprocess’s own i32 clamp in uutils.rs
is separate from this family.
Default-env seeding is core’s: boot_shell seeds the host’s env and cwd
(shell::boot::seed_env, private) between building the shell and seating the
prelude.
Builtins are shell-scoped: each mode declares its surface as one
HostSurface value and hands it to boot_shell, so the checker surface and
the runtime surface cannot drift. Batch’s surface is core plus
WATCH_BUILTIN, SURFACE_BUILTIN and the boot builtin; --check uses that
booted engine, not a shell-less manifest. The REPL surface adds the `_ed-*` editor builtins and
_external-editor, all static. Both ral front-ends print a watched worker’s lines, so watch is the
ral hosts’ to install
(watch-repl-builtin).