# ADR 0083: A persistent interpreter REPL is a transactional source session **Status:** Proposed (2026-11-11); needs engineering review (#44) for issue #341. ## Context A useful interpreter front end must retain definitions between inputs, but an interpreter `Val` contains `Rc`/`RefCell` and belongs to one run's interpreter thread. Retaining those values would retain actors, regions, capabilities and runtime state as well. It would also make result lifetimes depend on generated Core and raw `FnId` identities surviving later edits. The compiler already has the required parser, analysis database, type printer, ordinary entry validation and diagnostics. The REPL should reuse those paths, not grow a second language implementation. Issue #339's B1 slice owns the ordinary-entry result-preserving API that lets a host receive an owned `String` without sending `Val` across a thread. This ADR deliberately separates that API from #339's later comptime runner and immutable statics. Interactive input also has problems a whole-file parser does not answer: whether text is a declaration or an expression, whether an error means "wait for another line" or "reject this input", when a command is recognized, and how much an unbounded input, evaluation or captured stream may allocate. ## Decision ### A session persists source, never runtime values `louise repl` owns one `Db`, one synthetic `+repl` module and its stable `FileId`, the committed declaration/import text, a monotonic private-wrapper counter, and diagnostic bookkeeping. `Db::without_tests()` applies. Initial append-only persistence includes declarations and imports only. There is no persistent `Val`, top-level `let`, actor, continuation, mutable interpreter `State`, native code pointer per entry, process image or on-disk session. Redefinition and duplicate imports use the ordinary coherence/duplicate diagnostics; `:reset` is the remedy, not implicit shadowing. Every submission is a transaction. The implementation remembers the committed text, installs candidate text with `Db::set_text`, and runs the real parser, name resolution and type checker. Clean declarations/imports commit verbatim. Parse/name/type/coherence/FIP failures restore the old text. Diagnostics render through `louise_diag::render` to the injected error stream. Warnings from an accepted submission print once; later candidates do not replay diagnostics whose primary range lies in already committed text. The synthetic session uses the program analysis mode, so its import policy does not emit W0102 merely because an import is intended for the next prompt; this is not a global lint change. Expressions and type queries append a generated private function. Entry names have the reserved-looking form `__louise_repl_N`; evaluated candidates also use `std/prelude as __louise_repl_prelude_N`. The monotonic counter skips both names when either occurs in the synthetic module's resolved visible value, type or module namespaces (including constructors, named imports and aliases), with prelude exports included. A transient wrapper/import is discarded on success and every failure. Core is rebuilt for the candidate, the current wrapper is resolved to its current `FnId`, and no `FnId`, raw code pointer, `Program` reference or runtime value is retained for a later prompt. Reanalysis is bounded by the committed-source limit rather than presented as incremental per-item checking. ### Expressions run once as ordinary entries and print with Louise `Debug` An evaluated candidate has the conceptual form: ```louise import std/prelude as __louise_repl_prelude_7 fn __louise_repl_7 :: { __louise_repl_prelude_7.debug ((fn { list.range 1 5 }) ()) } ``` The fresh module alias makes the callee the actual prelude `Debug` method even when the session defines or imports another `debug`. There is no unqualified name-resolution shortcut. The original expression runs once inside a generated, immediately invoked zero-argument lambda; its wrapper result is the language `String` returned by `Debug`, including for `()` and strings. HIR gives the lambda its existing `Boundary::Refuse("a lambda")`, so a `return` at the REPL expression boundary, including one in an ordinary block, receives E0119 rather than returning raw text before `Debug`. Session definitions and explicit user lambdas keep the ordinary language return rules. This boundary is semantic validation, not reliance on the mapped value happening to be `Val::Str`. The expression's ordinary inferred effects go through `louise_core::runnable`; no REPL effect/capability exception is added. Fresh `RunOptions`, fresh runtime state and ordinary root handling apply on every expression. Spawning an actor does not make it survive entry completion, and unwinding finishes before the result is mapped. C passes the prepared ordinary entry once to B1's `run_value_map`. B1 maps its `Val::Str` to an owned Rust `String` on the interpreter thread; the host then prints it once with a trailing newline between two complete prompts, after any program output. A non-`Str` result from this wrapper is a clean runtime invariant error. Rust's `Val` `Debug` implementation is never user-facing, and a missing Louise `Debug` instance is a normal source diagnostic. The rejected alternative of invoking `io.println` on the debug string would add an effect and change host/runtime output ordering; there is only the result-mapping design, not a fallback implementation of both. Program `RunOptions.out` and `.err` remain distinct from REPL diagnostics and the final returned-value line. Their effectful ordering is program output first, returned value second. Runtime errors print a diagnostic and leave the source session usable; effects already performed are not undone. C uses the published B1 ordinary mapper directly. It does not return a raw `Val`, route through `run_direct`, invoke CTFE's extern allowlist, disable actor cleanup, or carry a runtime value into another candidate. `os.exit` uses test-runner-style `RunOptions::exit_ends_run = true`: it ends only the current evaluation, produces its ordinary runtime diagnostic, and the host reaches another prompt. It never pretends earlier external effects were rolled back. This is intentional host-survival behavior, not literal `run` process-exit parity. A subprocess test must prove recovery after exit once B1 is connected. ### `:type` analyzes a raw wrapper and never executes it `:type EXPR` uses a separate private wrapper around the same generated lambda as evaluation, but with no prelude import or `debug` call. The lambda remains unexecuted and supplies the same E0119 function-level-return rejection. The wrapper's inferred `Scheme` loses only its generated unit parameter. The type/result, effect row, variables, constraints, markers, equalities and capture information of the original expression are otherwise retained and rendered with `louise_types::Printer` (and the stored `BodyResults` rigid-name convention where applicable). `:type` distinguishes a bare value item from a computed expression. An unqualified item, transparent parenthesized item or `module.item` resolves through the synthetic module's real HIR scopes and prints that definition's stored `Scheme` with `Printer::scheme`, as LSP item hover does. This deliberately avoids `instantiate_def`'s call-site rule which opens a closed effect row for subsumption, and avoids attributing a generated wrapper/lambda capture row to the definition. Imported aliases and session definitions follow their actual resolved declaration; hidden capabilities or REPL roots are not inserted. Every other expression keeps the generated query's inferred type and rows. Thus `:type io.println` renders the declaration's `fn(String) -> () / `; `:type io.println "hello"` is the raw call expression's `() / `. Likewise, `:type identity` prints a committed function's canonical `fn(a) -> a`, while `:type identity 1` is `Int`. Type/resource limits use the same bounded scheme renderer in either case. For the required acceptance example, the output is exactly: ```text :type list.range fn(Int, Int) -> List ``` An effectful value expression prints its result type followed by its effect row; there is no call to `runnable` and no execution, even when the row contains a user effect or the value has no `Debug` instance. Type-query wrappers never commit and never advance a runtime session. ### Commands and multiline input The commands are exactly: - `:type EXPR` — type an expression, continuing parser-incomplete input; - `:load FILE.lse` — transactionally append declarations/imports from one file; - `:reset` — empty the synthetic source, reset wrapper numbering and diagnostic bookkeeping, and drop candidate analysis/runtime artifacts; - `:help` — print these commands and the source-only persistence limitation. Ordinary EOF succeeds at a fresh boundary. EOF with an incomplete pending fragment prints a targeted incomplete-input diagnostic and a failing status. Unknown commands, malformed command arguments and unknown future `:quit` do not change the session. Commands are recognized only at a fresh input boundary, never inside a pending declaration, expression, interpolation, template or language text. A syntax-level fragment entry parses declarations with the item grammar and expressions with the Pratt/expression grammar, preserving every byte in its CST. `fn NAME ::` starts a declaration while `fn` without that head starts a lambda expression. Parser/lexer state, not raw brace counts, distinguishes complete, incomplete and invalid input. Grammar expectation paths explicitly label EOF errors `Incomplete`; permanent errors such as excessive nesting stay `Invalid`, regardless of accompanying zero-width EOF expectations. Optional followers such as an import's trailing `.` before `.{items}` and an attribute's `(` before an identifier use this same EOF-aware path. Unterminated lexical modes are incomplete from their lexer origin. An ordinary top-level bodyless function remains pending so its `{` may be on the next line, except declared `@extern`/`@intrinsic` forms. `:load` still applies whole-module semantic checks to bodyless functions. The public fragment API exposes `syntax()`, `errors()` and `diagnostics()` directly. Its expression root is `EXPRESSION_ROOT`; it does not expose the whole-file `Parse::tree()` accessor, which cannot cast that root to a source file. Existing whole-file `parse()` behavior and its typed tree are unchanged. Input is submitted as soon as the accumulated text is syntactically complete. There is no speculative look-ahead for what a later indented line might add: `1 + 2` submits on its first complete line, while delimiters, infix tails, lambda/match/handler bodies and indentation the real continuation parser needs remain pending according to their actual parse. Interactive stdout receives and flushes `louise> ` / `...> ` before a blocking read. If either stdin or stdout is not a terminal, prompts and colors are off. Initial noninteractive output is therefore byte-deterministic and requires no PTY. The first version has no line editing, history, completion or terminal dependency. An OS interrupt terminates the front end under normal process signal rules; deterministic evaluation limits, not a claim that every blocking OS extern is cancellable, are the in-process runaway defense. ### Bounded loading and diagnostics `:load` resolves non-absolute paths against the directory in which `louise repl` started. The path is the trimmed remainder of the command (so it may contain spaces); shell quoting is not reinterpreted. It must name one `.lse` file. Trusted host command I/O is not hidden Louise `fs` authority. Each load snapshot uses a checked `take(limit + 1)` byte read through EOF, never an unbounded whole-file read or metadata-only size check. The host opens and reads the path twice with that same bound and compares the complete byte snapshots. Different contents—including same-size changes and paths whose `modified()` metadata is unavailable or low-resolution—are rejected; open/read errors propagate instead of converting absent metadata and errors into matching `None` values. This does not claim a persistent file lock or protection from every adversarial filesystem race, only that two observed bounded snapshots must agree. Non-UTF-8, read failure, excess bytes or differing contents produce a concise error and leave committed text untouched. The loaded text is one whole-file declaration candidate: it may contain several declarations/imports, but no package resolution occurs and no `main`, declaration initializer or earlier expression runs. Read, syntax, analysis, duplicate-definition and coherence failures are all atomic. A deterministic same-size two-snapshot fixture replaces concurrent-writer/mtime timing tests, limiting host I/O to small owned files plus this pure fixture. ### Resource limits The defaults below are deterministic product limits, not environment-variable knobs. Small test-only values prove each boundary without an OOM/full-tmpfs test. More input after a source-limit error is usable; in particular `:reset` releases an overgrown session. A pending overlong line is drained through its newline without growing a buffer and the pending fragment is discarded. | Resource | Default and behavior | |---|---| | One input line, excluding its newline | 16 KiB; drain and reject the rest of that line. | | One pending fragment | 64 KiB; reject and discard the pending fragment. | | `:load` file | 256 KiB; reject on byte 262,145. | | Committed declaration/import source | 1 MiB; reject the candidate and advise `:reset`. | | Diagnostics per submission | 64 KiB retained/written with one explicit truncation diagnostic; UTF-8 scalars split across writes are carried (at most one scalar prefix) and truncation lands only on a valid scalar boundary; underlying stream errors still propagate. | | Printed type result | 64 KiB and 4,096 conservatively visited structural nodes; a preflight bounds the intended `Printer` String construction, an exact-size check remains defensive, and rejection emits no partial type. | | Program stdout and stderr capture | Active C `Limits::program_output_bytes = 64 * 1024` per stream per evaluation; fresh bounded `OutputCapture`s are an independent host-emission backstop, not another charge added to B1's count. They preserve only deterministic bytes accepted before failure. | | Printed `Debug` result | Active C `Limits::debug_bytes = 64 * 1024`; the mapper tests `Val::Str` length before owning/copying or writing the result. An excess becomes `RtError::Evaluation(EvaluationError::Limit(LimitError { kind: LimitKind::OutputBytes, limit, requested }))`; no partial result is printed. | | Machine frames | Active B1 `RunOptions::max_frames = Some(Limits::max_frames)` and scoped `EvaluationLimits::max_frames = Limits::max_frames = 4096`. B1 applies their effective minimum and returns structured `LimitKind::Frames` exhaustion per ordinary evaluation. | | Machine steps | Active B1 `EvaluationLimits::max_steps = Limits::max_steps = 1_000_000`, cumulative across all actor work and repeated preemption in one ordinary entry. A fresh entry starts with fresh usage. | | Interpreter allocation/output growth | Active B1 `EvaluationLimits::max_allocation_bytes = Limits::max_allocation_bytes = 16 * 1024 * 1024` for deterministic logical charges; `EvaluationLimits::max_output_bytes = Limits::program_output_bytes as u64 = 64 * 1024` for logical output/generated-content charges. Unused ordinary `max_reified_nodes` and `max_static_bytes` are `0`, which B1 ignores rather than using to reject data. | | Subprocess tests | Small fixed transcripts; stdin explicitly closed; stdout/stderr readers have fixed caps; a short deadline and owned process-group kill/wait clean up the whole child. No PTY. | Each expression installs `RunOptions::evaluation = Some(...)` explicitly, which creates fresh ordinary B1 accounting shared by that entry's actors and cleanup. `RunOptions::new` defaults this to `None`; C's activation does not make B1's `direct` flag true or call CTFE's extern/no-root protocol. B1 owns fuel, frame, output/allocation and repeated-preemption semantics; C does not add a scheduler. None changes ordinary root grants. Logical allocation and output charges are deterministic upper bounds, not claims about actual Rust heap RSS; orchestrator resource scopes provide real host-memory confinement. String-length checks at the mapper are necessary but are not represented as a substitute for bounding custom `Debug` while it runs. Type analysis is bounded separately by source/parser limits; the type-result check claims output allocation and emission bounds, not a budget for all inference work. A resource error returns to the prompt whenever the process is still alive; the external process-group deadline is test-harness protection, not a claimed Louise timeout facility. Every test capture, log and temporary source file has a small explicit bound and owner under the orchestrator's resource scope. Transcript input is size-capped and fed by a supervised writer after the deadline starts. Normal leader exit, error and timeout all clean up the owned process group before completion-bounded writer/reader joins; a harmless TERM-resistant descendant fixture with its own finite backstop proves inherited pipes cannot extend the test past normal leader exit. ## Consequences - Declaration/import sessions are inspectable, restartable and safe across analysis rebuilds. Reanalysis cost grows only to the fixed session cap. - Values cannot accidentally escape interpreter threads or keep actors and mutable runtime state alive between prompts. - Evaluated expressions share ordinary `run` entry/default-root semantics. `:type` remains more permissive precisely because it has no execution and no `Debug` requirement. - C consumes B1's ordinary mapper and scoped ordinary limits. Comptime reification is not a C dependency. Program/result output and usage state use fresh bounded per-entry captures/state rather than a session image. - Source exhaustion is recoverable; external side effects, process interruption and trusted host `:load` access are not described as transactional rollback or a security sandbox. - Native/JIT evaluation, redefinition, top-level `let`, images, package loading, editing/history/completion, debugging/tracing and new ambient powers remain explicitly outside this ADR. ## B1 contract required by this decision The exact intended ordinary entry shape is (with the existing concrete Rust argument lifetimes/elision preserved by B1's implementation): ```text run_value_map( program: impl Into>, entry: FnId, options: RunOptions, map: FnOnce(Val) -> Result + Send, ) -> Result ``` The consumed B1 mapper preserves the entry value through ordinary actor cleanup, invokes `map` on the interpreter thread before teardown, and keeps the existing `run`/`run_with` unit wrappers behavior-compatible. C contributes only the bounded `Val::Str -> Result` mapper. No raw-`Val` return or separate C runner exists. C uses B1's actual `RunOptions.evaluation: Option` with `Some` on every expression. B1's ordinary state creates fresh run-local accounting, keeps `direct = false`, preserves ordinary root/default-handler behavior (clock, random, io, ffi and ordinary default fs access included), applies the effective minimum legacy/scoped frame limit, and drops machine/value/accounting state on the interpreter thread after actor cleanup. Its ordinary tests cover mapping, bounded cleanup, cumulative preemption/fuel, output generated by normal indirections, and `io.eprintln`/actor-crash error output. Reification/static fields are ignored ordinarily, so C's `0` values do not impose backend support assumptions on data. C supplies the exact table values above; this is not CTFE evaluation and takes no purity/allowlist shortcut. Logical accounting remains distinct from externally enforced process memory.