Lines
99.81 %
Functions
100 %
Branches
use super::*;
use crate::ctx::ScriptLimits;
use nomiscript::{Fraction, Reader};
mod cl_boolean_tests;
mod list_tests;
mod nil_boxing_tests;
async fn handle_form_smoke(frame: &str) -> String {
let ctx = ScriptCtx::new(uuid::Uuid::nil());
let mut session = Session::new(ctx).expect("Session::new");
session.handle_form(frame).await
}
async fn eval_value_of(form: &str) -> String {
handle_form_smoke(&format!("(:id 4 :form {form})")).await
async fn assert_values(cases: &[(&str, &str)]) {
for (form, value) in cases {
assert_eq!(
eval_value_of(form).await,
format!("(:id 4 :value {value})"),
"form {form}"
);
async fn assert_error_code(form: &str, code: &str) {
let response = eval_value_of(form).await;
assert!(
response.contains(&format!(":code {code}")),
"{form} must raise {code}, got: {response}"
fn parse_to_value(input: &str) -> Result<Value, NomiError> {
let program = Reader::parse(input)?;
let mut symbols = SymbolTable::with_builtins();
nomiscript::eval_program(&mut symbols, &program)
#[tokio::test]
async fn evaluates_arithmetic_and_returns_value_envelope() {
let response = handle_form_smoke("(:id 1 :form (+ 1 2))").await;
assert_eq!(response, "(:id 1 :value 3)");
async fn evaluates_nested_arithmetic() {
let response = handle_form_smoke("(:id 5 :form (* (+ 1 2) (- 10 4)))").await;
assert_eq!(response, "(:id 5 :value 18)");
async fn print_in_eval_mode_does_not_panic() {
// Regression: PRINT / DISPLAY / NEWLINE / DEBUG lower to `env.log`,
// which was script-mode-only. In eval mode the missing func index used
// to SIGABRT the compiler (`registry.rs` `HashMap[key]`). The eval-mode
// `log` import + the rpc `env.log` host fn now make it compile + run.
let response = handle_form_smoke("(:id 1 :form (print \"hi\"))").await;
assert!(response.contains(":id 1"), "got: {response}");
assert!(!response.contains(":code"), "must not error: {response}");
async fn dolist_with_print_in_eval_mode_runs() {
// The exact shape from the Metro script that first surfaced the panic.
let response = handle_form_smoke("(:id 2 :form (dolist (x (list 1 2 3)) (print x)))").await;
assert!(response.contains(":id 2"), "got: {response}");
async fn handle_request_captures_output_and_value() {
// `(print "hi")` writes "hi" to the per-request buffer (via env.log) and
// its own return value is nil; the structured outcome must carry the
// captured text in `output` AND the value payload — the SLYNK mREPL
// renders these as `:write-string` + `:write-values` respectively.
let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
let outcome = session.handle_request("(print \"hi\")").await;
outcome.output.contains("hi"),
"captured output should contain the printed text, got: {:?}",
outcome.output
matches!(outcome.payload, ResponsePayload::Value(_)),
"payload should be a Value, got: {:?}",
outcome.payload
async fn handle_request_value_only_has_empty_output() {
let outcome = session.handle_request("(+ 1 2)").await;
assert!(outcome.output.is_empty(), "got: {:?}", outcome.output);
outcome.payload,
ResponsePayload::Value(Value::Number(Fraction::from_integer(3)))
async fn handle_request_rejects_plist_shaped_injection() {
// Adversarial review: the source must be parsed as a standalone AST, not
// interpolated into a `(:id 0 :form …)` envelope string — otherwise
// `1 :form (+ 2 3)` would re-read as a plist and eval to `1`. It must
// instead error (more than one top-level form), never silently return 1.
let outcome = session.handle_request("1 :form (+ 2 3)").await;
matches!(outcome.payload, ResponsePayload::Error { .. }),
"plist-shaped input must error, got: {:?}",
async fn handle_request_interrupt_latch_aborts_before_eval() {
// An interrupt latched before the request (the SLYNK reader arms it on
// `(:emacs-interrupt)`) must abort the eval at the pre-start check, even
// for a form that would otherwise compile fine.
session.interrupt_handle().interrupt();
match outcome.payload {
ResponsePayload::Error { code, .. } => {
assert_eq!(code.as_symbol(), ErrorCode::INTERRUPTED);
other => panic!("expected interrupted error, got: {other:?}"),
async fn handle_file_evaluates_all_forms_and_persists_state() {
// A file with a defun + a call to it: state accumulates across forms,
// and the load returns a summary value (not the last form's value).
let dir = std::env::temp_dir();
let path = dir.join(format!("nms_load_test_{}.nms", std::process::id()));
std::fs::write(&path, "(defun dbl (x) (* x 2))\n(dbl 21)\n").unwrap();
let outcome = session.handle_file(path.to_str().unwrap()).await;
std::fs::remove_file(&path).ok();
ResponsePayload::Value(Value::String(s)) => {
assert!(s.contains("loaded"), "summary: {s}");
assert!(s.contains("2 forms"), "summary: {s}");
other => panic!("expected a load summary string, got: {other:?}"),
async fn handle_file_missing_path_errors() {
let outcome = session.handle_file("/no/such/nms/file.nms").await;
"got: {:?}",
async fn handle_file_aborts_on_a_bad_form() {
let path = dir.join(format!("nms_load_bad_{}.nms", std::process::id()));
std::fs::write(&path, "(+ 1 2)\n(undefined-symbol-here)\n").unwrap();
"a bad form must abort the load, got: {:?}",
async fn handle_file_honours_interrupt_armed_before_load() {
// A `C-g` that lands before/during the synchronous read+parse must abort
// the load (the pre-read latch check), not be ignored until the first
// form reaches the Wasm call.
let path = dir.join(format!("nms_load_intr_{}.nms", std::process::id()));
std::fs::write(&path, "(+ 1 2)\n(+ 3 4)\n").unwrap();
assert_eq!(code.as_symbol(), ErrorCode::INTERRUPTED, "got: {code:?}");
other => panic!("interrupt should abort the load, got: {other:?}"),
async fn handle_request_surfaces_error_payload() {
let outcome = session.handle_request("does-not-exist").await;
"payload should be an Error, got: {:?}",
async fn handle_request_clears_output_between_calls() {
// The buffer must not leak across requests: a print then a pure value.
let _ = session.handle_request("(print \"first\")").await;
let second = session.handle_request("(+ 1 1)").await;
second.output.is_empty(),
"output leaked from prior request: {:?}",
second.output
async fn returns_value_for_literal_form() {
let response = handle_form_smoke("(:id 9 :form 42)").await;
assert_eq!(response, "(:id 9 :value 42)");
async fn returns_value_for_string_literal() {
let response = handle_form_smoke("(:id 9 :form \"hello\")").await;
assert_eq!(response, "(:id 9 :value \"hello\")");
#[test]
fn round_trips_bytes_through_eval() {
let value = parse_to_value("'#u8(1 2 3)").unwrap();
assert_eq!(value, Value::Bytes(vec![1, 2, 3]));
async fn bad_envelope_emits_envelope_error() {
let response = handle_form_smoke("(:form (+ 1 2))").await;
assert!(response.contains(":code args"));
assert!(response.contains(":id 0"));
async fn malformed_envelope_emits_parse_error() {
let response = handle_form_smoke("(((((").await;
assert!(response.contains(":code parse"));
async fn undefined_symbol_emits_compile_error() {
let response = handle_form_smoke("(:id 7 :form does-not-exist)").await;
assert!(response.contains(":id 7"));
assert!(response.contains(":code compile"));
async fn user_function_arity_violation_emits_args_error() {
let _ = session
.handle_form("(:id 1 :form (defun id-fn (x) x))")
.await;
let response = session.handle_form("(:id 2 :form (id-fn))").await;
assert!(response.contains(":id 2"));
fn completions_match_case_insensitively_and_skip_internal() {
let session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
// Lower-case input matches the upper-case folded symbol; the canonical
// upper-case name is returned.
let defuns = session.completions("def");
assert!(defuns.contains(&"DEFUN".to_string()), "got: {defuns:?}");
defuns.iter().all(|n| n.starts_with("DEF")),
"got: {defuns:?}"
// Sorted; no internal `$`/`__` or `(SETF …)` place names.
let all = session.completions("");
assert!(all.windows(2).all(|w| w[0] <= w[1]), "must be sorted");
all.iter()
.all(|n| !n.starts_with('$') && !n.starts_with("__") && !n.starts_with("(SETF")),
"internal/setf symbols must be filtered: {all:?}"
async fn completions_include_a_user_defined_symbol() {
.handle_form("(:id 1 :form (defun my-helper (x) x))")
// The defun's name is folded to upper-case; a lower-case prefix finds it.
let hits = session.completions("my-");
assert!(hits.contains(&"MY-HELPER".to_string()), "got: {hits:?}");
fn completions_unknown_prefix_is_empty() {
assert!(session.completions("zzz-no-such-symbol-").is_empty());
async fn interrupt_before_form_short_circuits_with_interrupted() {
let handle = session.interrupt_handle();
handle.interrupt();
let response = session.handle_form("(:id 11 :form (+ 1 2))").await;
assert!(response.contains(":id 11"));
assert!(response.contains(":code interrupted"));
async fn coalesced_interrupts_abort_one_form_each_in_order() {
// Two `C-g`s observed together before a form cancel THAT form and are
// coalesced (they do not pre-arm cancellation of a later one); a fresh,
// distinct `C-g` later still cancels the next form. This pins the REPL
// contract against both a "lost interrupt" and an "over-eager next-form
// abort" regression.
handle.interrupt(); // two presses before the form
let first = session.handle_form("(:id 60 :form (+ 1 2))").await;
first.contains(":code interrupted"),
"first form must abort: {first}"
// Both presses were coalesced into the one abort — the next form is clean.
let second = session.handle_form("(:id 61 :form (+ 1 2))").await;
second, "(:id 61 :value 3)",
"next form coalesced-poisoned: {second}"
// A fresh, distinct press still aborts the following form.
let third = session.handle_form("(:id 62 :form (+ 1 2))").await;
third.contains(":code interrupted"),
"a distinct later interrupt must still abort: {third}"
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn inflight_interrupt_does_not_poison_next_form() {
// The SLYNK reader arms BOTH the epoch bump and the interrupt signal on
// `(:emacs-interrupt)` (mod.rs). When that lands mid-eval the epoch trap
// cancels the running call; that interrupt generation must then be acked
// so the SAME `C-g` can't also abort the next request.
let bumper = session.epoch_bumper();
let interrupt = session.interrupt_handle();
let cancel_task = tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
bumper.bump();
interrupt.interrupt();
});
let cancelled = session
.handle_form("(:id 30 :form (do ((i 0 (+ i 1))) ((>= i 1000000) i)))")
cancel_task.await.unwrap();
cancelled.contains(":code interrupted") || cancelled.contains(":code runtime"),
"in-flight eval should have been cancelled: {cancelled}"
// The next form must evaluate normally — the acked interrupt must not abort it.
let next = session.handle_form("(:id 31 :form (+ 1 2))").await;
assert_eq!(next, "(:id 31 :value 3)", "next form was poisoned: {next}");
async fn non_interrupt_failure_still_consumes_a_concurrent_interrupt() {
// Race: an interrupt is signalled WHILE a form is in flight, but the
// form loses to its own terminal error (out-of-fuel) before any epoch
// bump could win. The in-flight form is finished, so the interrupt must
// be acked on the error path too — otherwise it poisons the next form.
let latch_task = tokio::spawn(async move {
// Latch only (no epoch bump): the form trips out-of-fuel on its own.
let failed = session
.handle_form("(:id 50 :form (do ((i 0 (+ i 1))) ((>= i 100000000) i)))")
latch_task.await.unwrap();
failed.contains(":code runtime") || failed.contains(":code interrupted"),
"in-flight form should fail terminally: {failed}"
let next = session.handle_form("(:id 51 :form (+ 1 2))").await;
assert_eq!(next, "(:id 51 :value 3)", "next form was poisoned: {next}");
async fn interrupt_after_clean_eval_aborts_next_form() {
// The mirror of the above: after a form completes NORMALLY, an interrupt
// armed before the next form must still abort it. The in-flight cleanup
// only consumes the latch on an actual epoch-interrupt trap, so a `C-g`
// that lands post-completion is NOT swallowed.
let clean = session.handle_form("(:id 40 :form (+ 1 2))").await;
assert_eq!(clean, "(:id 40 :value 3)");
let interrupted = session.handle_form("(:id 41 :form (+ 4 5))").await;
interrupted.contains(":code interrupted"),
"post-completion interrupt must abort the next form: {interrupted}"
async fn epoch_bumper_cancels_inflight_long_eval() {
// The one test that pins the EPOCH-TRAP cancel path specifically.
//
// Two things can end an in-flight eval with `:code interrupted`: the
// pre-start `check_interrupt` latch, and the epoch trap inside Wasm.
// They are easy to confuse, and a test that accepts either silently
// stops covering the trap the moment timing drifts — which is exactly
// what a coverage-instrumented build does to it.
// This isolates the trap structurally rather than by timing:
// - the interrupt handle is never touched, so `check_interrupt` can
// not fire at all and the pre-start path is unreachable;
// - fuel is effectively unbounded and the loop bound is just under
// i32::MAX, so the form can neither finish nor exhaust fuel, ruling
// out `:code runtime`;
// - the bumper runs in a loop rather than after a fixed sleep, so a
// slow host widens the window instead of missing it.
// The assertions then pin the trap by its wire signature: EpochInterrupt
// carries a `:detail`, whereas the pre-start latch reports
// "evaluation interrupted before start" with none.
let ctx = ScriptCtx::new(uuid::Uuid::nil()).with_limits(ScriptLimits {
fuel: u64::MAX,
..ScriptLimits::default()
let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
let bump_until_done = done.clone();
let bump_task = tokio::spawn(async move {
while !bump_until_done.load(std::sync::atomic::Ordering::Relaxed) {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
// Bounded: if epoch interruption regresses, the form runs to a bound just
// under i32::MAX with unbounded fuel and never returns. Without this the
// test would stop being a test and become a job that burns until the k8s
// deadline kills it — silently, since it produces no output meanwhile.
let response = tokio::time::timeout(
std::time::Duration::from_secs(60),
session.handle_form("(:id 22 :form (do ((i 0 (+ i 1))) ((>= i 2000000000) i)))"),
)
.await
.expect("epoch bump did not cancel the eval within 60s — interruption has regressed");
done.store(true, std::sync::atomic::Ordering::Relaxed);
bump_task.await.unwrap();
assert!(response.contains(":id 22"), "{response}");
response.contains(":code interrupted"),
"epoch bump must cancel the in-flight eval: {response}"
!response.contains("evaluation interrupted before start"),
"took the pre-start latch path, so the epoch trap went untested: {response}"
response.contains(":detail"),
"EpochInterrupt must surface its detail; got: {response}"
fn host_prelude_helper_is_loaded_and_compiles() {
// ADR-0029 host-dependent prelude: split:list-for-transaction is loaded
// on the Session path (after register_host_fns) and is callable. We
// compile a form referencing it — proving load + name resolution + the
// qualified native dispatch wire up — WITHOUT running it (it bottoms out
// in the DB-backed list-splits-by-transaction native; execution is
// covered by the db-gated integration test).
session.symbols.contains("SPLIT:LIST-FOR-TRANSACTION"),
"host prelude helper not registered"
// Compile (not run) a real call: lowering emits the qualified-name
// dispatch + the native import, proving resolution wires up. Host fns
// never execute at compile time, so no DB is touched.
let program = Reader::parse("(split:list-for-transaction (car (list-transactions \"\")))")
.expect("parse");
if let Err(e) = session
.compiler
.compile_eval_with_type(&program, &mut session.symbols)
{
panic!("host prelude helper failed to compile: {e:?}");
async fn car_of_quoted_constant_list_compiles_on_eval_path() {
// Regression: CAR/CDR of a quoted CONSTANT list folds on the codegen
// path but used to trap on the eval-with-type (Session) path because
// the stack handler called compile_for_stack on the quoted arg, which
// has no Quote arm. The stack handlers now const-fold first.
let response = handle_form_smoke("(:id 1 :form (car '(1 2 3)))").await;
assert_eq!(response, "(:id 1 :value 1)");
async fn car_of_quoted_heterogeneous_list_compiles_on_eval_path() {
// Mixed number + string quoted list — the element is extracted by fold.
let response = handle_form_smoke("(:id 1 :form (car '(7 \"x\")))").await;
assert_eq!(response, "(:id 1 :value 7)");
async fn car_of_cdr_of_quoted_constant_compiles_on_eval_path() {
// CDR folds to the quoted tail, then CAR extracts its head — exercises
// the cdr fold-first path feeding car.
let response = handle_form_smoke("(:id 1 :form (car (cdr '(1 2 3))))").await;
assert_eq!(response, "(:id 1 :value 2)");
async fn cdr_of_quoted_constant_renders_tail_on_eval_path() {
// The bare-CDR case (no enclosing CAR): folds to a quoted tail and
// renders to its printed form rather than trapping.
handle_form_smoke("(:id 1 :form (cdr '(1 2 3)))").await,
"(:id 1 :value \"(2 3)\")"
handle_form_smoke("(:id 1 :form (cdr '(1)))").await,
"(:id 1 :value nil)"
async fn car_of_quoted_compound_and_symbol_heads_render_as_data() {
// A compound or symbol head is quoted DATA, not code — it renders to
// its printed form (not resolved as a call / variable).
handle_form_smoke("(:id 1 :form (car '((1 2) 3)))").await,
"(:id 1 :value \"(1 2)\")"
handle_form_smoke("(:id 1 :form (car '(x y)))").await,
"(:id 1 :value \"X\")"
async fn reverse_of_constant_list_renders_on_eval_path() {
// Regression (same class as CAR/CDR): REVERSE of a constant or
// runtime-builder list folded but the stack handler rejected the
// non-runtime-pair result on the eval-with-type path. Now it renders
// the reversed datum on both surfaces.
handle_form_smoke("(:id 1 :form (reverse '(1 2 3)))").await,
"(:id 1 :value \"(3 2 1)\")"
handle_form_smoke("(:id 1 :form (reverse (list 1 2 3)))").await,
// Composition still folds through to the element.
handle_form_smoke("(:id 1 :form (car (reverse '(1 2 3))))").await,
"(:id 1 :value 3)"
async fn cons_onto_constant_list_renders_on_eval_path() {
// Regression: CONS with a constant / runtime-builder list cdr trapped
// in push_pair_cdr on the eval-with-type path. A fully-constant cons
// now folds and renders the list datum; a dotted pair renders too.
handle_form_smoke("(:id 1 :form (cons 0 '(1 2 3)))").await,
"(:id 1 :value \"(0 1 2 3)\")"
handle_form_smoke("(:id 1 :form (cons 0 (list 1 2 3)))").await,
handle_form_smoke("(:id 1 :form (cons 1 2))").await,
"(:id 1 :value \"(1 . 2)\")"
async fn append_of_constant_lists_renders_on_eval_path() {
// Regression: all-constant APPEND folds to a quoted list; the stack
// handler used to force it through runtime materialization (which can't
// represent symbols) instead of rendering the folded datum.
handle_form_smoke("(:id 1 :form (append '(1 2) '(3)))").await,
"(:id 1 :value \"(1 2 3)\")"
handle_form_smoke("(:id 1 :form (append '(a b) '(c)))").await,
"(:id 1 :value \"(A B C)\")"
async fn universal_prelude_helper_runs_end_to_end() {
// The universal prelude is loaded on the Session path too; a math:*
// helper executes through wasm and returns its value. No DB.
let response = handle_form_smoke("(:id 9 :form (math:square 9))").await;
assert_eq!(response, "(:id 9 :value 81)");
async fn pp_form_at_value_position_returns_string() {
// Exercises compile_pp_for_stack — the path nms / emacs see
// when `(pp 42)` is the request form.
let resp = handle_form_smoke("(:id 7 :form (pp 42))").await;
assert!(resp.contains(":id 7"), "{resp}");
assert!(resp.contains("\"42\""), "{resp}");
async fn describe_form_at_value_position_returns_doc() {
// compile_describe_for_stack — same shape.
let resp = handle_form_smoke("(:id 8 :form (describe '+))").await;
assert!(resp.contains(":id 8"), "{resp}");
assert!(!resp.contains(":error"), "{resp}");
async fn apropos_form_at_value_position_returns_list() {
let resp = handle_form_smoke("(:id 9 :form (apropos \"entity\"))").await;
assert!(resp.contains(":id 9"), "{resp}");
async fn deftest_form_at_value_position_returns_quoted_name() {
let resp = handle_form_smoke("(:id 10 :form (deftest sanity (assert-equal 1 1)))").await;
assert!(resp.contains(":id 10"), "{resp}");
async fn assert_equal_pass_form_at_value_position() {
let resp = handle_form_smoke("(:id 11 :form (assert-equal 2 2))").await;
assert!(resp.contains(":id 11"), "{resp}");
async fn assert_equal_fail_surfaces_as_error() {
// assert_equal returns Err on mismatch; Session maps to
// :code compile error envelope (it's a NomiError::Compile).
let resp = handle_form_smoke("(:id 12 :form (assert-equal 1 2))").await;
assert!(resp.contains(":id 12"), "{resp}");
assert!(resp.contains(":error"), "{resp}");
async fn coverage_dump_lists_called_natives() {
.handle_form("(:id 1 :form (rpc-protocol-version))")
let dump = session.handle_form("(:id 2 :form (coverage-dump))").await;
assert!(dump.contains("RPC-PROTOCOL-VERSION"), "{dump}");
assert!(dump.contains(":id 2"), "{dump}");
async fn coverage_dump_reports_pre_warmed_natives() {
// Session::new pre-compiles every zero-arg native fn (phase 4
// fast-path stubs), so coverage-dump is non-empty even before
// a user form lands. This is the desired semantic: it
// reflects compile-time reference counts, including pre-warm
// compilations, which is what the parity contract gates on.
let dump = session.handle_form("(:id 1 :form (coverage-dump))").await;
assert!(dump.contains(":id 1"), "{dump}");
async fn interrupt_does_not_persist_across_forms() {
let _ = session.handle_form("(:id 11 :form (+ 1 2))").await;
let response = session.handle_form("(:id 12 :form (+ 1 2))").await;
assert_eq!(response, "(:id 12 :value 3)");
async fn session_state_persists_across_forms() {
let defun = session
.handle_form("(:id 1 :form (defun double (x) (* 2 x)))")
assert!(defun.contains(":id 1"));
let call = session.handle_form("(:id 2 :form (double 21))").await;
assert_eq!(call, "(:id 2 :value 42)");
async fn fraction_results_format_canonically() {
// A fractional (Scalar) literal renders canonically as `n/d`. (Integer
// `(/ 1 4)` is now Index division → 0 per ADR-0028; the canonical
// fraction idiom is the `1/4` Scalar literal.)
let response = handle_form_smoke("(:id 3 :form 1/4)").await;
assert_eq!(response, "(:id 3 :value 1/4)");
fn nomi_runtime_value_carries_through() {
let value = parse_to_value("(+ 0.5 0.25)").unwrap();
assert_eq!(value, Value::Number(Fraction::new(3, 4)));
async fn calls_meta_native_from_nomiscript_source() {
let response = handle_form_smoke("(:id 1 :form (rpc-protocol-version))").await;
let expected_version = crate::natives::meta::PROTOCOL_VERSION;
assert_eq!(response, format!("(:id 1 :value {expected_version})"));
async fn calls_server_get_version_from_nomiscript_source() {
let response = handle_form_smoke("(:id 1 :form (get-version))").await;
// GIT_HASH is baked at server crate build time via env!. We don't
// assert its exact value (changes per build) — just that the
// envelope round-trips a non-empty :value string.
response.starts_with("(:id 1 :value \""),
"expected string response, got: {response}"
assert!(response.ends_with("\")"));
async fn calls_server_get_build_date_from_nomiscript_source() {
let response = handle_form_smoke("(:id 2 :form (get-build-date))").await;
response.starts_with("(:id 2 :value \""),
async fn cons_list_surfaces_as_printable_string() {
// First WasmGC sub-slice: eval-mode `(cons ...)` chains now
// capture through pending_string instead of erroring at compile
// time. The result is a textual `(1 2 3)` value the emacs client
// can (read) back into a real list. Heterogeneous car types ride
// a follow-up slice once Pair/Vector/Closure/Struct share a
// tagged union — today's cons cell stores i32 payloads only.
let response = handle_form_smoke("(:id 12 :form (cons 1 (cons 2 (cons 3 nil))))").await;
response.contains(":value \"(1 2 3)\""),
"expected :value \"(1 2 3)\", got: {response}"
async fn count_native_cannot_mix_with_ratio_arithmetic() {
// account-count returns i32 (a count / Index, not a Scalar). Mixing it
// with a fractional Scalar literal must fail to compile — the design
// forbids accidental arithmetic across the Index/Scalar strata. (An
// integer literal like `10` is itself an Index now (ADR-0028), so
// `(+ 10 (account-count))` is valid Index arithmetic; the genuine
// stratum clash needs a fractional `1/2` Scalar operand.) The explicit
// `index->scalar` bridge is the only legal crossing.
let response = handle_form_smoke("(:id 11 :form (+ 1/2 (account-count)))").await;
assert!(response.contains(":code compile"), "got: {response}");
response.contains("scalar") && response.contains("index"),
"expected Index/Scalar stratum-separation error, got: {response}"
async fn get_commodity_with_non_uuid_arg_falls_back_to_symbol_lookup() {
// get-commodity now accepts a uuid OR a symbol (mirroring get-account's
// name fallback), so a non-uuid arg is NO LONGER an "invalid uuid"
// error — it's treated as a symbol and routed to a DB lookup. On this
// no-DB smoke harness that lookup surfaces a runtime DB-access error
// (not a parse error); a DB-backed test
// (`get_commodity_resolves_by_symbol` in tests-integration) covers the
// successful resolution.
let response = handle_form_smoke("(:id 9 :form (get-commodity \"USD\"))").await;
assert!(response.contains(":id 9"), "got: {response}");
response.contains(":code runtime") && response.contains("get-commodity"),
"expected a get-commodity runtime error (symbol path hits the DB), got: {response}"
!response.contains("invalid uuid"),
"a non-uuid arg must no longer short-circuit as an invalid-uuid error: {response}"
fn meta_native_unknown_in_script_mode_compile() {
// host_fns are only registered in eval-mode contexts; the compiler
// built without with_host_fns shouldn't see them. Sanity that the
// mode flag actually gates the registration.
use nomiscript::CompileMode;
let mut compiler = Compiler::new();
let program = nomiscript::Reader::parse("(rpc-protocol-version)").unwrap();
let result = compiler.compile_with_mode(&program, &mut symbols, CompileMode::Script);
result.is_err(),
"host fn should not be callable when compiler has no specs"
async fn get_config_missing_name_yields_error_envelope() {
let resp = handle_form_smoke("(:id 20 :form (get-config \"\"))").await;
assert!(resp.contains(":id 20"), "{resp}");
assert!(!resp.contains(":value"), "{resp}");
async fn get_config_success_shape_is_config_value() {
// Passes a non-empty name; the DB call fails (no pool) and surfaces
// as an :error envelope — we verify the SUCCESS wire shape is only
// emitted when the command actually succeeds. Here we just confirm
// the argument-validation path (empty string) always errors.
let resp = handle_form_smoke("(:id 21 :form (get-config \"\"))").await;
assert!(resp.contains(":id 21"), "{resp}");