Map: core / shell / runtime — runtime values & shell state
A runtime value is a value closure ⟨V,ρ⟩; a Shell is its state partitioned
by lifetime, and what a run fixes rides beside it as an immutable Mooring.
core/src/shell/runtime.rs re-exports the types; the evaluator
steps over them. The value types themselves live in core/src/ir/.
Values
ValClos (ir/value.rs) is ⟨V,ρ⟩ with a non-variable root and every direct
name of V bound in ρ (cbpv,
runtime-values-are-value-closures).
- Representation. One form:
ValClos(Val, Env). A list or map built at run time is syntax over%itemKvariables bound in ρ;partshands the marshaller the syntax and environment, nothing more.VClosRef(&Val, &Env)is the borrowed form, and every observation is defined on it. - Formation.
ValClos::close(shell/runtime/close.rs) restricts ρ to the value’s occurrences and pulls each missing direct name from Σ with its scheme.ValClos::thunkforms⟨thunk M, ρ↾occ(M)⟩.VClosRef::subreads a component: a variable is its binding in one lookup, anything else shares ρ without restricting again (a-closure-keeps-only-what-it-mentions).ValClos::closurerebuilds a marshalled closure and refuses an unbound direct name. - Reading.
VClosRef::viewreads the head constructor only; aView::Variant’s payload is aVClosRef, and a bare tag’s is(). - Classification.
VClosRef::shapeis the one classification. A builtin is classified as its η-expansion: arity 0 is aBlock, otherwise aFunction.type_name,foundandheadsall derive from it. - Builtins.
ValClos::builtinis⟨Val::Builtin(entry), ∅⟩. Forcing or applying it entersBuiltinEntry::eta, a λ-chain ending in δ. A partial application is that chain’s residual thunk;residualrecovers the entry and the arguments still awaited.blockis a thunk the checker may read, never a residual. Display is<native NAME>or<native NAME, k of n arguments>. - Tags.
ValClos::variantbinds a builtin, handle or residual payload to a fresh name, so a tag spine holds only syntax. - Exec arguments.
headsgives the heads a value is admitted at; the shapesexecve(2)cannot take areRefusedArg(ty/exec_arg.rs), each with oneremedy.render_argvis total (exec-argv-is-words). - Size.
shallow_sizesums string and byte lengths, recurses lists, maps and tag labels, and charges 32 for a thunk, builtin or handle, never descending a capture. - Drop is trampolined: a dying value queues each environment and list, record or map node it alone owns, bounding the host stack.
- Compile-time bounds:
ValClos ≤ 48,Env ≤ 16and machineFrame ≤ 128bytes.
Beside it:
ir/value/list.rs/map.rs— list and map nodes areimbl::Vector/imbl::OrdMapof syntax.ListRef/MapRefread them over ρ;ListRefalso holds the one definition of cons, snoc, concat and tail, andValClos::mapbuilds a map (runtime-values-are-value-closures).ir/env.rs—Envis ρ alone, andEnv::placethe one placement rule. A scope entry isBinding { value, scheme: Option<Closed> }. Entries areEmpty, a sortedThinArcarray of at most 8, or a persistent hash map, so a shared write copies only the touched node. Session bindings always carry a scheme; block-local ones may not (type-inference).Env::from_bindingsrefuses duplicate names.signature.rs— Σ, the natives and the frozen prelude, stored as typedBindings, oneSignatureper shell,Arc-shared into every child. A native builtin carries its declared scheme (none for a boundary row).lookupis the one resolution rule: ρ, then Σ’s prelude, then Σ’s natives.flow.rs—Settled<T> = Result<T, Break>;BreakisError(catchable) orEscape(Exit,Stopped). A processCancellationbecomes a non-catchableStopped(ral-does-not-suspend).error.rs— rendering of runtimeErrorandoutcome_value, whoseerrarm is the plain recordValClos::from_datum(fact.record()); the type iscore/src/error.rs(diagnostics).audit.rs— theAuditcollector overfact/observation.rs.compare.rs—equalsandcompareonVClosRef, exact acrossIntandFloat.ir/value/first_order.rsconverts to and fromFOValue.coerce.rs— argument decoders onVClosRef(as_str,as_list,as_map,expect_handle);expect_thunkonValClos; shape refusals go throughexpected.expect_thunkaccepts a builtin through its η.expect_handlerefuses a withheld handle aswithheld-handle.walk.rs—Shell::admitted_walkresolves a walk’s root, asks the grant of it, and handspath::tree::Walkthe live grant and cancel scope, raising a root it cannot see or enter and skipping unadmitted entries beneath;Shell::walk_beneathmakes an absent rootNotFound.
core/src/builtin.rs:
BuiltinEntryis a checker-readDeclplus a body;BuiltinTableprojects installed sets into the checker’sManifest.- A row that settles at
Unithas its answer coerced toUnit; debug builds assert the body agrees (Decl::settles_at_unit).
core/src/handle.rs:
HandleisLive(HandleInner)orWithheld(title). A marshalled parent’s handles arrive withheld;Handle::liverefuses observing one.HandleInnercarriesWorkerId, title, birthStamp(monotonic and wall),homenode and one lock over its state, sampled asSample::{Running, Stopping, Ready, Consumed}. The soleCompletionPermitpublishes the end.pins_live_workwalks lists, maps, tag spines and a partial builtin’s supplied arguments, never a block’s capture (binding-leases).handle/brood.rs—Cradle,Brood,BroodGuard;handle/surface.rs—DeferredSurface.
Handlers
Handlers are deep and self-masking, with no resume
(effects-handlers,
handlers-deep-self-masking).
handler.rs holds HandlerStack, HandlerFrame and FrameHandle.
HandlerEntrycarriesHandlerArity, fixed by the surface form:Unaryfor a named arm,CatchAllforwithin [handler: …]. The calling convention is never inferred from the value (handlers-are-lambdas).- A named arm has
U([String] → Command); a catch-allU(String → [String] → Command). Base-frame builtins (Convention::Argv) have that type by construction. - Persistent installation (
Shell::install_handler=vet_handler+commit_handler) vets each arm once:arm_closurerefuses anything but a block the checker can read; a bare builtin is named, with the block that wraps it (Expected::BlockNotBuiltin);arm_stands_inchecks the block against its slot, inferred over its own capture byShell::schemes_over, refusing as oneIllTypedfact.
- Scoped arms are checked statically and never re-vetted. No statement or builtin changes persistent frames; only the host installs them between units (within-dir-is-local-state).
Shell
Shell (state/mod.rs) partitions interpreter state by lifetime; the field
name is the invariant
(turn-local-state). Every field is
pub(crate): hosts use the verbs in host.rs, scope.rs, context.rs.
env— ρ of the session, extended by every sessionDefine.sig—Arc<Signature>, never written after boot, so never checkpointed.context—Context: env overrides, cwd,GrantStack, handler stack, args. Clones wholesale into every child.io— the three byte streams, swapped within a run by redirect frames.scope— the cancel scope the focus polls (Shell::poll). A thread base sets it to its mooring’s node;Shell::shieldswaps it for aguard’s acquisition or release. It is read, never written: strikes aim atMooring::home(delimiters-are-handlers-for-poll).session: SessionState— survives every run: durable cancelrootandanchor, the append-onlysourcesandroot_file,exit_hints,scratch,fixings(ty),runtime(Arc<Runtime>: Σ, builtin table, base handler layer, library docs, terminal state),terminal_lease,stack_limit,child_limits,interactive,stage, andhooks(Someonly on the booted session).local: LocalState— host-local, each member with its own rule:audit, theworkersroster, thecradle, thebindingsledger,machine_depth.
A run checkpoints (env, context) and restores it on panic
(Shell::run_under). The hooks table and local.audit are outside the
checkpoint. Within the run, IoLoan (shell/run.rs) swaps in io, scope,
root_file and the audit call site, restoring them on Drop, so an unwinding
run leaves nothing stale.
The mooring
What a run fixes is a Mooring (mooring.rs), an owned local on the run’s
stack frame passed as &Mooring beside &mut Shell. Being immutable it needs
no restoring; the two borrows are disjoint.
- Fields:
surface,deferred,desk,home,cleanup_grace,worker_cap,worker_title(TitlePolicy),terminal_access. worker_caprefuses a spawn while live plus reserved seats reach it.Mooring::for_threadrebuilds one for a worker or stage: same deferred sink, grace, cap and title policy; its ownhomeandsurface; no desk;TerminalAccess::Denied.Mooring::adriftruns a builtin body outside any run: nothing installed,homeunder a root nothing holds.has_deskgates enquiries;no_deskis the shared refusal.
Surface. Mooring::surface encodes a ValClos to FOValue once and
forwards to the SurfaceSink; surface_data takes FOValue directly. Both are
inert without a sink. A session worker gets a DeferredSurface, delivered once
through its CompletionPermit to the DeferredSink; a gather child or stage
gets the parent’s live sink
(surface-delivers-itself).
Terminal. Authority is a permit, never a resource getter (io-process).
SessionState::terminal_leaseis minted once at startup when ral owns the foreground; hosts requestRequestedTerminalAccessand cannot mint one.TerminalAccessisDenied,LeasedorExplicitLoan.reachyields aTerminalPermitonly with the lease, and forLeasedonly when stdout is the terminal.Mooring::lend_terminalderives a new mooring raisingLeasedtoExplicitLoan, and isNoneotherwise: authority is raised, never minted, and never lent twice.Shell::group_ownerdecides once: a stage answers itsMembership; a session gathers its permit and interactivity.
Workers and the cradle
Roster(state/workers.rs) is a per-sessionWorkerRegistryofWorkerEntry(handle,Owner,settled_epoch). Threads share it (Roster::Shared); a session owns it (Roster::Owned), and dropping an owned roster cancels every worker (cancel_all), waiting up toDEFAULT_CLEANUP_GRACE + TEARDOWN_GRACE.- Retention.
Shell::arm_worker_retentionarms it; each source dispatch ticks the epoch;sweep_retentionstamps aReadyentry and expires it after the retention, leaving entries of a live parent worker or a gather alone. Expiry queues aReapNotice. Unarmed (the REPL),Readyentries stay. Cradlesays where a loose birth hangs: under the durable root for a run or aside (Cradle::loose), or inside a gather with itsBrood(Cradle::owning). A stage keeps its parent’s (a-worker-ends-with-its-children).
Binding lease
BindingLedger (state/bindings.rs) has one writer, the thread owning
&mut Shell, so it takes no lock
(binding-leases).
- Inert until
Shell::arm_binding_leaseseals every visible name as baseline. Shell::note_defineis the one write path for session names, called only fromRan::defineunderMode::Session. It renews the lease and queues a large-binding notice whenshallow_sizemeetslarge_binding_bytes.Shell::set_varbinds a host value with an explicitClosedscheme and bypasses the ledger.
Ready boundary. emit_ready_boundary_notices (shell/run.rs) runs after
each settled source run:
sweep_retention, always;- large-binding notices to stderr, always;
- only with a surface sink: reap notices and
BindingLedger::prune, each as a`noticesurface event. Without a sink both ledgers wait.
Method modules (state/)
construct.rs—Runtime,Image(env, handler frames, sources,Terms, fixings),Terms(stack and child limits, exit hints, scratch, lease, retention; one type in memory and on the wire).Shell::constructis the one session literal;Shell::rootandShell::child_ofare its two uses.Shell::marshal(&grant)writes the image andSpawnGrant.inherit.rs—Shell::child, the one literal for thread children.host.rs— host accessors, probe counts (binding_count,leased_binding_count),group_owner.scope.rs— handler install/vet/remove,set_var,note_define,schemes_over.checks.rs— the authority adapter: judged path lookups,with_layer(pushes, then removes its own layers by position withGrantStack::remove),push_session_capabilities, sandbox projection.cwd.rs— the cwd cell:enter_cwd/restore_cwdforwithin [dir:],seed_cwdfor an in-process front end.hooks.rs— the hook table: named run roots (block, lambda or builtin),vet_hook/register_hook, plugin ledger, dispatched byProgram::Hookunder each hook’sDefaultPolicy.context.rs,json.rs,notice.rs,workers.rs,bindings.rs.
Startup seeding is shell::boot::seed_host_env: env overrides
(env-is-dynamic-only) and
OS_NAME / OS_ARCH / OS_FAMILY.
Children
Thread children share the session’s memory and are built by Shell::child;
a new session crosses marshal / child_of. Exhaustive literals keep a new
field from reaching either by default.
- Same-thread β-step. Forcing a block or applying a lambda runs the body in
the caller’s
Shellunder the caller’s&Mooring; nothing is copied, so an unbracketedcdpersists.within [dir:]restores the cwd (evaluator). - Thread children inherit env, context, Σ, runtime, sources, root file,
call site, exit hints, scratch and fixings, and hold no hooks, no terminal
lease and an unarmed ledger. They differ in their
Holding:spawn_worker— empty stdin, not interactive, no group; shared root and roster; the body replaces the inherited cradle with its own;spawn_stage— the pipeline’sIoand group; shared root, roster and cradle. Both go throughspawn_thread, withhomeminted by the caller viaMooring::for_thread;join_session— an aside: shares root and anchor, writes where the parent does, reads nothing, and holds a fresh roster with the parent’s retention.
- New session.
Shell::child_of(runtime, &parent, narrow)reads the marshalled image, constructs throughShell::constructwith no root recipe, then pushes the grant layer against the child’s cwd.- It inherits bindings with schemes, handlers, context, sources, terms and a fixings snapshot; it owns a fresh durable root and roster, no hooks, no terminal lease, and seals every inherited name as lease baseline.
- Handles cross as titles and arrive withheld; held syntax, sharing, residual arguments survive. A non-Unicode cwd refuses writing; a builtin the receiver lacks refuses reading (transport, agent).