On this page

Diagnostics registry

Every diagnostic the compiler can emit has a stable code listed here. Codes are never reused or renumbered; a retired code stays in the table marked retired. Add a code in the same commit as the compiler change that emits it.

Installer prerequisite/build failures are shell errors prefixed install:, not compiler diagnostics. See installation troubleshooting and requirements.

FFI cache capture/validation failures silently fall back to uncached compilation; they introduce no diagnostic codes and preserve E0974/E0978 classification.

Ranges

Range Phase
E0001–E0099 ordinary lexer (canonical UTF-8 source; unreachable from legacy compact ~1 source)
E0100–E0199 parser and legacy compact reader (E0101–E0117 for canonical UTF-8 source; E0107, E0115, and E0120–E0128 also cover legacy compact ~1 source)
E0200–E0299 names and scopes
E0300–E0399 types
E0400–E0499 records, with, and newtypes (E0420–E0429)
E0500–E0599 unions, match, and ? (E0520–E0529)
E0600–E0649 generics
E0650–E0699 interfaces and coherence
E0700–E0799 blocks, memory and escapes
E0800–E0849 CLI effects and capabilities (E0819, E0821–E0824, E0827–E0839 and E0846–E0849 reserved)
E0850–E0869 paths (M6.4)
E0870–E0899 maps (M6.6)
E0900–E0929 streaming I/O and subprocesses (M6.2/M6.5)
E0930–E0999 packages, platforms and plugins
E1000–E1049 local version control and dependency graphs
E1050–E1059 expression evaluation
E1060–E1099 package registry (M15.5)
E1100–E1149 version-control remotes and Forge hosting
E1150–E1159 static builds and [embed.*] assets (ADR-0282)
E1160–E1169 implicit derive materialization (ADR-0318)
E1170–E1179 script plugins and atomic multi-file tenon batch
E1180–E1189 constrained decoding grammars (E1180–E1184) and interactive sessions (E1185–E1189)
E1200–E1279 modern language ergonomics (let ... else), #! standalone scripts, purity/totality assertions, capability traces, typed holes, and requires/ensures contracts

Warnings use W with the same ranges.

Capabilities

Platform type names, CliError, WsError, Output, path, and map are reserved as types (E0211). path, map and the compiler's synthetic entry name __start are reserved functions (E0203). The type/function namespaces stay separate: a user function named Cli or Stdout is an ordinary function, not a capability constructor. Empty Stdout {} retains the existing E0101 syntax error; record-shaped Stdout { fake: 0 } is E0801.

Capabilities come from the selected platform and may be passed, stored and copied, but cannot be constructed by user code or compared concretely. Derived data cannot contain them (E0813), and capability types cannot be reflected (E0816). Fs.restrict(root: path) -> result<Fs, CliError> canonicalizes an existing root within the parent root; relative paths resolve against it, and escapes through .., absolute paths or symlinks are denied. Fs.read_only() -> Fs denies writes. These checks have a time-of-check/time-of-use window against concurrent attackers; they are capability discipline, not an OS security sandbox.

Fs.no_follow() -> Fs opts into descriptor-relative no-follow access; default Fs still follows internal symlinks. The flag is monotonic through restrict, read_only and repeated no_follow; policy is idempotent, while attenuations still issue distinct opaque handles. Copies preserve authority. Policy identity includes the flag and retained-directory identity. An ordinary successful restrict retains a latent anchor; activation uses it even if its pathname is replaced. Acquisition failure makes activation sticky denied. Unrestricted activation retains /, cwd and its path label; later relative restriction labels from that snapshot, even after chdir. Root acquisition remains a trusted selection boundary: restrict(link)?.no_follow() selects the link's resolved target; no_follow().restrict(link) rejects it. Paths do not atomically transfer Ws authority. Restricted absolute paths require a component-delimited byte-exact root-label prefix and are then resolved through the anchor. Repeated separators and . are allowed in the suffix, not normalized in the prefix. Empty no-follow paths return NotFound (exists is false), even with a root. Ordered ./.. processing cannot cancel a symlink; ascent above the restricted root is denied.

Explicit symlink access in any component returns Denied with prefix no-follow filesystem: (internal status 10013); exists returns false. Open/read/write/append/sync/truncate validate the opened descriptor, reject special files without blocking, and require regular files with one hard link. Opening a directory retains IsDirectory; read-only write denial takes precedence. Listing exposes only sorted regular files/directories, omitting symlinks and disappeared entries; hard-linked files may be listed/exist but cannot be opened. Walks use descriptor-relative traversal without descending links; opted-in Par.walk uses the secure serial implementation. Reads consume the validated descriptor, not a reopened pathname. This does not freeze contents/link counts or sandbox subprocesses. See ADR-0217.

Net.restrict(hosts: vec<str>) -> result<Net, CliError> narrows a grant to DNS names or IP literals with optional ports; malformed literal hosts are E0812 and invalid dynamic hosts return an error. Net.none() -> Net removes the grant. The package ceiling must include "net" to access cli.net.

Mmap

TRT_MMAP_MIN=<bytes> opts large files into mmap; views may change externally (ADR-0055).

Floats

f64 is IEEE 754 binary64 (ADR-0177). Literals need digits on both sides of ., with an optional exponent: 1.5, 2.0e-3. Integer literals never become f64: write 1.0. f64(n) rounds an integer to nearest; i64(x) truncates and traps float conversion out of range on NaN, infinity or overflow; x.saturating_i64() clamps and maps NaN to 0. Other integer conversions need i64(x) first.

+ - * / and unary - never trap: 1.0 / 0.0 is inf, 0.0 / 0.0 is NaN. There is no %. == and ordering are IEEE: NaN is unequal to everything, itself included, every comparison with NaN is false, and -0.0 == 0.0. Records, unions and sequences compare f64 fields the same way. f64 is not a map key (E0870).

Methods: abs floor ceil round trunc sqrt is_nan is_finite min max saturating_i64. round rounds half away from zero; min/max propagate NaN and order -0.0 below 0.0.

Printing and interpolation give the shortest text that parses back to the same value, identical on both backends (ADR-0178): positional for decimal exponents -7 through 20, otherwise d.de<x>, always with a fraction (1.0, 1.0e21, 5.0e-324); -0.0, inf, -inf, nan. s.parse_f64() accepts [+-]? digits ('.' digits)? ([eE] [+-]? digits)?, [+-]?inf and nan, rounds correctly, gives ±inf on overflow and none otherwise.

Text details

Direct for x in s.lines() / s.split(sep) / s.words() heads (str or bytes) are lazy, allocate no vector, and match materialization. chars() returns Unicode scalars. Split preserves empty fields; an empty separator delimits scalars and empty ends. Lines split only on LF, retain CR and omit the final terminator's empty field. Empty text has no lines or chars; empty search finds zero.

Output and arguments

Global print/println are reserved function names (E0203); every call is E0800, even with the wrong arity or a same-named local. Output requires a capability: fn main() is pure. E0800 highlights the callee and replaces it with cli.stdout.print/cli.stdout.println when cli is lexically in scope.

Args/env (M6.3): cli.args traps invalid utf-8 at the field name for invalid argument bytes; raw_args preserves them. Env get/get_bytes require str keys (E0301); empty keys or keys containing NUL/= return none. Missing keys return none, present empty values return some(""); invalid UTF-8 is none only for get. cli.exit requires i64 (E0301), accepts 0..255 and diverges in any expression; invalid codes trap exit code out of range at the method name, flushing stdout. Exit 101 is legal and is not sufficient evidence of a trap. CliError.message() returns its str payload unchanged, independent of variant.

Program exit and error output (M6.3)

Completion Exit Stderr
pure main returns, or Cli main returns ok 0 none added
Cli main returns err(e), including propagated ? 1 error: <e.message()> and LF
cli.exit(n) with 0 ≤ n ≤ 255 n none added
invalid cli.exit(n) 101 trap: exit code out of range at <file>:<line>:<col> and LF
invalid UTF-8 in cli.args 101 trap: invalid utf-8 at <file>:<line>:<col> and LF

Explicit exit, normal completion and traps flush stdout. Stderr calls do not; stdout and stderr are distinct streams, so a stderr line may precede buffered stdout when externally merged. cli.stderr.println is suitable for usage errors; follow it with cli.exit(1) (or the tool's chosen code). No error variant is special: NotFound, Denied, IsDirectory, Io, Failed all print their payload. cli.exit is accepted in used branches, match arms and arguments, and non-unit functions ending in it need no return. Arguments evaluated before it keep their effects; subsequent arguments and enclosing calls do not execute. Copy/promotion reports omit synthetic startup: its error dispatch has no source copy site and does not change user-code destination-construction guarantees.

E0312–E0319: integer types (M5.7). E0316–E0319 remain spare for this lane.

Subprocesses (M6.5)

cli.process.run(cmd: str, args: vec<str>) -> result<Output, CliError> captures raw bytes into Output { status: i64, stdout: bytes, stderr: bytes }, with stdin from /dev/null. Both pipes are drained concurrently, without a cross-pipe order guarantee. cli.process.stream(cmd, args) -> result<i64, CliError> flushes stdout first and inherits all three process streams. Only the Process capability exposes these methods; it can be passed to helpers. The root cli.process is unsandboxed; use sandbox for restricted children. Neither method runs a shell. PATH lookup is supported; shell syntax requires an explicit executable such as run("/bin/sh", ["-c", "printf hello"]). Empty arguments, spaces, metacharacters and Unicode are passed literally. Captured bytes may contain NUL or invalid UTF-8; use to_str() to validate. Child exit status, including nonzero, is success; signals map to 128 + signal. Discarding a direct run or stream call is E0902: both return a result for OS failures, even when the child status or captured output is unneeded. Use ? to propagate those failures, or match the result. Children start with default SIGPIPE even if the parent inherited it ignored. Capture OOM traps kill and reap the owned child before exiting. Spawn ENOENT returns NotFound("no such program: <cmd>"); EACCES returns Denied("permission denied: <cmd>"); other OS failures return Io("spawn <cmd>: os error <number>"). Embedded NUL in command/arguments is EINVAL (22). Errors use the shared lowering, never libc's localized strerror. E0911 diagnoses literal program names containing a space. Its repair separates simple literal words into argv and preserves existing literal-vector arguments; quoted/escaped command strings need a manual repair. Dynamic names are passed unchanged and may name actual executables containing spaces. E0910 repairs a str argument to [x]; other wrong types use [] as a placeholder. See ADR-0056.

Sandboxed processes

process.limit(max_output: i64, timeout_ms: i64) -> Process returns a handle whose later run and run_input are bounded by those positive limits. Limits stack per field with min and are kept by sandbox. A limited stream fails with EINVAL before flushing or spawning. On a cap or deadline the process group is killed and the direct child is reaped; the language errors are Io("output limit exceeded: <cmd>") and Io("timed out: <cmd>"). A non-positive literal is E0818; a dynamic non-positive value denies the handle with EINVAL. call_plugin uses the minimum of the handle and the plugin manifest.

process.cwd(p: path) -> Process sets the child working directory for subsequent run, run_input and stream calls. Unsandboxed non-directory, empty, or NUL paths fail at spawn with Failed("invalid working directory"). When sandboxed, cwd must canonicalize to an existing directory inside the primary sandbox filesystem root or spawn fails closed with Denied. process.clear_env() -> Process clears inherited environment variables (and any earlier env entries on that handle); sandboxed children still retain minimal PATH=/usr/bin:/bin (and macOS writable workspace TMPDIR) unless overridden by subsequent env calls. process.env(key: str, val: str) -> Process sets or overrides one child environment variable; empty keys, keys containing = or NUL, and values containing NUL fail at spawn with Failed("invalid process environment").

process.sandbox_roots(primary: Fs, extra_ro: vec<Fs>, net: Net) -> Process grants primary (respecting its read/write mode) plus zero or more additional canonical read-only Fs roots (attenuated to read-only even if the caller passed a writable Fs). Unrestricted / handles in extra_ro fail closed with Denied. On macOS Seatbelt and Linux Landlock, each extra root grants read-only file/directory reads inside that canonical subtree only; policy setup failures fail closed. Re-sandboxing remains monotonic: every new primary or extra root must lie within an already-granted root.

process.sandbox(fs: Fs, net: Net) -> Process restricts subsequent run, agent run_input and stream children; wrong argument kinds produce E0817. Re-sandboxing can narrow, not widen, the existing policy. The child has read and execute access to fixed system roots /usr, /lib, /lib64, /bin, /sbin, /etc, access to /dev/null, and access to the selected filesystem root in its read-only or read-write mode. Symlinks do not grant access outside allowed roots; hardlinks across directory hierarchies are restricted by Landlock's REFER right when available. System roots remain readable even with a restricted filesystem root; unusual loader locations outside these roots may prevent execution.

Agent tool adapters use workspace_tool_process with the owner's Ws and a trusted WorkspaceFs host hook implementing Fs.restrict. Released workspaces are rejected. See ADR-0117 for ownership and trust boundaries.

The child environment is cleared except for PATH=/usr/bin:/bin and internal app scope. On macOS, workspace-rooted children start at the canonical root; writable ones also get TMPDIR=<root>/. Root / and Linux retain cwd and no TMPDIR. macOS [policy] sandbox_toolchains accepts unique xcode-select (default) and homebrew names, or [] to disable; Linux ignores it. Tool roots are read-only; Homebrew excludes var. Ancestors grant metadata, not listings or secret reads. Root Net allows networking; net.none() denies socket creation (but not socketpair). A non-empty host list cannot be enforced and returns Denied rather than silently permitting or denying all networking. Sandbox setup fails closed: unavailable Landlock or seccomp, Landlock below ABI 3, or a missing C compiler for the interpreter's launcher returns Denied. Ordinary spawn failures retain the NotFound, Denied, or Io kinds described above.

Linux enforcement uses Landlock, seccomp and no_new_privs; a gate reporting UNVERIFIED verifies fail-closed behavior, not containment. General macOS rooted-process enforcement is established only by its escape gate (sandbox: enforced seatbelt); that evidence does not cover pinned plugin launches (ADR-0215, ADR-0229). Seatbelt denials are EPERM (or EACCES). Missing sandbox-exec fails closed; portable tests alone prove no containment.

On Darwin, locked Process.call_plugin launches a verified private snapshot under the same deny-default Seatbelt policy (ADR-0229). Its canonical source package root is a containment witness only; fs = "none" does not grant that root. The staged executable receives an exact-file read and executable-map grant, with no optional toolchain subpaths. Snapshot preparation and child execution consume one deadline, and the parent removes the staged image after completion or failure. This plugin path is separate from the general rooted Process.sandbox escape gate: that gate alone does not establish plugin containment. Snapshot relocation changes argv[0] to the staged path and may break package-relative Mach-O dylib lookup; see ADR-0099 for support limits.

Conventions

#line maps C errors/debuggers to source.

Integer matches (M8.2) use in-range literal/half-open-range patterns and |, with exactly one final _ default; overlapping intervals select the first arm. E0517 rejects invalid bounds/patterns/default placement; E0518 requests a default. String literal alternatives require one final _; E0517/E0518 also cover invalid string patterns/defaults and missing defaults, retaining integer wording. Union wildcards cover remaining variants; malformed or redundant wildcards are E0503. Proven byte-domain constant-result matches may emit 256-entry C tables; other matches retain comparisons. Such tables preserve semantics and introduce no traps or unchecked conversions. Pure scalar conditional assignments may emit C selects; conditional increments add 0/1 while preserving checked overflow and its source position unless proven safe.

Diagnostics go to stderr and set exit code 1. Spans are half-open byte offsets; line and col are 1-based, with columns counting Unicode scalar values. fix is replacement text for the span.

tenon parse --dump <file.tn> renders lexer and parser diagnostics with empty stdout; it checks syntax only. Usage errors (including missing --dump or a file argument) and file-read errors exit 2.

fmt uses the same syntax diagnostics and leaves invalid files untouched. It stages the new bytes and preserves the source mode before publication. fmt --check <path> exits 1 for non-canonical files, listing their paths on stderr without diagnostic codes; it never writes. Canonical .tn files use readable UTF-8 ordinary Tenon; tenon fmt formats UTF-8 and legacy compact (~1) files deterministically while preserving each file's surface (pass --migrate-utf8 to convert legacy ~1 files to canonical UTF-8). Formatting twice equals once. Usage and I/O errors exit 2.

For heads use for x in v { or for i in a..b {. for is a hard keyword, including in impl Area for T; in stays contextual. For heads evaluate once, advance before the body, and charge fuel at for, including the final test. Direct str lines/split heads use lazy cursors; materialized methods are unchanged.

Interface restrictions

Interfaces contain newline-separated signatures; impls contain newline-separated function bodies. Both format without semicolons. Static dispatch adds no runtime trap kinds: the receiver precedes other arguments, and method entries consume ordinary interpreter call fuel at the impl method name. Unreached impl methods emit no C/IR functions; their bodies are still checked. E0302 counts explicit method arguments; qualified calls count the receiver too. Qualified method existence is checked before zero-argument arity (E0653). Interface checking collects declarations/signatures, then all impl keys for coherence. E0650 stops before impl signature/body checking, retaining every earlier diagnostic sorted by source span. Next, impl completeness and signature checks run; E0652/E0653/E0654/E0655/E0660/E0661 stop before checking any bodies. Otherwise free-function signatures, free-function/impl bodies, then monomorphization are checked. Bounds accept recovery types containing an error at any depth, avoiding dependent E0651 diagnostics after failed inference. Impl targets include builtins and instantiated generics (not fn or dyn, E0665). Bounds must be unique (E0611). No generic interfaces, methods or impls, inherent impls, defaults or associated types; dyn-compatible interfaces support dyn I (ADR-0275); see ADR-0027.

Diagnostic explanations and commands

tenon explain <code> prints the code, meaning and fixed example/help from the embedded Codes table below, followed by wrong and corrected compact programs (exit 0, stdout). The checked pairs are in teach-core.tsv, teach-advanced.tsv, teach-cli.tsv, teach-map.tsv, teach-process.tsv, teach-compat.tsv, teach-generators.tsv, teach-plugins.tsv and teach-inline.tsv: code, wrong compact source, corrected compact source separated by tabs; \n encodes a newline and \\ a backslash, and sibling files use // file: NAME markers. E0606's wrong cell is @instances, which expands the existing generic-instance-limit fixture, also printed by human explain. Codes whose wrong program has no compact spelling (the lexical and parse diagnostics E0001-E0117, and structural rejections such as E0406, E0414, E0415, E0420, E0421, E0509, E0513, E0514, E0603, E0656-E0658, E0700, E0701, E0710, E0715 and E0717; compact decoding reports E0125 or E0128 instead) have no card and print help only. Tests require exactly the intended diagnostic and successful checking of each correction. Retired codes remain explainable and marked retired, without a failing example. Codes are case-sensitive (E or W plus four ASCII digits); unknown or malformed codes and missing/extra arguments are usage errors (exit 2, message on stderr).

explain --json returns only {"code":"E0301","corrected":"..."} — the complete checked correction from the embedded teaching corpus (compact ~1 for legacy TSV cards, or help text for codes without a TSV card), not a span replacement. Canonical Tenon authoring is UTF-8; meaning and wrong source stay in the human view so JSON explanations remain compact. Tests enforce 540 bytes (150 estimated tokens at bytes / 3.6) for every JSON explanation and every emitted diagnostic line across the diagnostic fixtures. Ordinary JSON diagnostic shape and existing goldens are unchanged; use its code with explain to retrieve the teaching program (ADR-0048).

In multi-file teaching examples, // file: path.tn starts a sibling module; the preceding text is the root file.

check, run, build, emit-c, emit-ir and interp use the same front-end diagnostics (exit 1): syntax, names, arity and types. Types are checked after successful name resolution. check, emit-ir and interp need no C compiler. Tool errors, including no C compiler, exit 2 with a plain message. A C compiler rejection exits 3 and reports an internal compiler error plus the C compiler's stderr; successful compiler warnings pass through to stderr. Internal lowering/verifier failures also exit 3 and report a compiler bug. --diagnostics=human|json and the --json alias are accepted anywhere; the last selector wins. Human form is the default. Errors have help except E0406 on a non-name base, where no safe local rewrite is available; type errors include expected/found types and a repair (a replacement fix when mechanical).

Shapes

Generic restrictions

Generic parameters cannot repeat or hide types (E0609/E0608); main cannot be generic (E0610). Calls infer type arguments: expression </> are comparisons, including across call arguments. Explicit id<i64>(42) receives E0603; a literal Box<i64> { … } receives E0106 and should be Box { … }.

Monomorphization runs in the shared front end: E0605 limits discovery to 64 levels and type trees to 256 nodes (also guarded during inference and field/payload expansion); E0606 limits distinct generic functions and concrete generic layouts to 10,000 each. These are exit-1 diagnostics even under check. Unreached definitions are still checked, but emit no instances.

Rendered diagnostics

Human form:

error[E0301]: expected i64, found bool
  --> examples/sum.tn:4:13
   |
 4 |     let n = true + 1
   |             ^^^^ this is bool
   = help: use an integer here, or compare instead: `if flag { 1 } else { 0 }`

JSON form (--diagnostics=json), one object per line, kept under about 150 tokens:

{"code":"E0301","severity":"error","message":"expected i64, found bool","file":"examples/sum.tn","line":4,"col":13,"span":[52,56],"help":"use an integer here","fix":"if flag { 1 } else { 0 }"}

Keys have the fixed order code, severity, message, file, line, col, span, help, fix, edits, with no spaces between fields. help, fix and edits are omitted when absent; help is present for every emitted M1 error. edits is present only when nonempty and contains objects of the form {"file":"name","span":[start,end],"replacement":"..."}. These spans are zero-based, half-open UTF-8 byte offsets in the named file (unlike the diagnostic span, which uses concatenated SourceFile offsets). Apply edits to the original file text in sorted, non-overlapping order; an empty span inserts and an empty replacement deletes. The existing fix field remains advisory text. Name diagnostics are sorted by span start. For assignment to a let local, E0204 edits the declaration's mutability flag in compact source.

Checked Auto-Fix (tenon fix, tenon check --fix)

tenon fix [--apply] [--gen] [--surface auto|compact|ordinary] [--json] <file.tn> applies machine-applicable diagnostic edits (Diagnostic::edits) and AST-safe canonical rewrites iteratively (up to 4 passes). tenon check --fix is an alias for tenon fix --apply. Without --apply, tenon fix runs in dry-run mode and prints proposed diffs or a structured JSON report (applied, skipped, remaining, changed_files, diffs, passes, applied_to_disk, stale_generated, generated) without writing to disk. With --apply, verified changes are published atomically.

Every candidate fix batch is re-checked in memory and accepted only if total diagnostic count strictly decreases and zero new diagnostic codes appear; non-improving or conflicting batches are rolled back cleanly. Machine-applicable repair rules cover E0111 (++ on UTF-8 input), E0115 (import ordering), E0125/E0126 (legacy compact framing/ordinals), E0204 (let to var), E0223/E0225 (missing pub on local private items), E0224 (duplicate identical imports), E0304 (integer condition != 0), E0306 (missing return on matching tail expression), E0405 (zero-arg builtin method accessed as field), E0406 (record field assignment to with update), E0516 (parentheses on nullary enum constructors/patterns), E0711 (discarded immutable method result on local receivers, promoting let to var when needed), E0850/E0852 (path(...) / .display()), E0902 (propagatable fallible call ?), plus unused/unsorted import cleanup once diagnostics reach zero. Generated companion files (with a generated header / ~1g) are always refused (fix_generated); when E0968/E0969/E0971 indicate stale or missing companions, passing --apply --gen invokes tenon gen and re-checks.

Dual-Surface Authoring (--surface)

Canonical Tenon source is readable UTF-8 (.tn), while legacy compact (~1) files remain dual-read. Read and edit commands accept --surface so tools can inspect and edit canonical UTF-8 files (the default for UTF-8 targets) or legacy compact files, check the whole module, and publish atomically while preserving the target file's surface:

Runtime traps are not diagnostics: they print trap: <kind> at <file>:<line>:<col> on stderr and exit with code 101, after flushing stdout. Kinds are integer overflow, division by zero and shift out of range; the location points at the operator, conversion type name or shift/rotate method name. fuel exhausted is enabled by platform policy on both backends, or by tenon interp --fuel N: it points at the function name (an entry) or the while/for keyword (a loop head), and is not a diagnostic code (ADR-0017). deadline exceeded is enabled by platform deadline_ms policy (zero disables it), with a monotonic clock checked every 4,096 charges at those same sites, even when fuel is unlimited. It is cooperative: blocking native calls are not interrupted. Wall-clock trap positions need not match between backends (ADR-0098). Signed minimum / -1 overflows; signed minimum % -1 returns 0 without trapping. See ADR-0012 and ADR-0044.

Interpolation and output

Interpolation produces str anywhere and evaluates parts left to right before construction. Parts and print/println arguments accept integers of any width, bool and str (otherwise E0309); integers use decimal and bool uses true/false. Full expressions and nested interpolation work; quotes inside braces are written \", and literal braces as {{/}}. Unclosed/empty braces are E0113/E0114. Concatenation operands must have the same type; interpolate mixed printable types.

Heap allocation in compiled programs can trap out of memory, at the interpolation's opening quote, concatenation's +, or promoted retaining flow. The interpreter has no corresponding arena-exhaustion trap. Function/iteration scratch resets automatically; surviving values are placed in older regions or promoted. The C backend can reclaim replaced carry storage in the first qualifying top-level loop of a function. The loop must replace a single heap-bearing record local declared outside it. Scalar counters and read-only borrows are allowed. Other loops retain replaced carry storage until its region ends. See ADR-0219. Value interpolation accepts the same parts as printing (E0309); E0311 is retired. Direct print interpolation retains its allocation-free segment path. Placement and promotion introduce no diagnostic codes and consume no interpreter fuel.

Arena budget

Native arenas default to an 8 GiB writable-page budget across all colours, including persistent storage. TRT_MEMORY_LIMIT in the executable's environment (also inherited by tenon run) overrides it: unsigned decimal bytes, optionally followed by K/M/G (case-insensitive, powers of 1024). Zero forbids page commitment; empty, malformed or size_t-overflowing settings use the default. The runtime reads it once, before the first arena commitment; unused arenas remain lazy. Compiling C with -DTRT_MEMORY_LIMIT=<bytes> changes the default, not the environment's precedence. Discarded pages return budget. Exhaustion traps out of memory with exit 101 and flushed stdout at the allocating expression, including the receiver of push/set (not the earlier buffer allocation). OOM depends on resources and is excluded from C/interpreter differential parity; interp has no corresponding arena trap. The budget bounds retained copies, not external OS pressure or non-arena memory. set is an O(n) copy unless the compiler proves a fresh local never aliases its container; then direct v = v.set(i, x) reuses storage in O(1). Snapshots/views/fields/calls conservatively disable that proof (ADR-0040). A terminal return v permits reuse while building a fresh unaliased local in a helper; prior snapshots still disable reuse throughout that helper. Return placement and promotion are unchanged.

Allocation reports

--report=promotions and --report=copies (either or both; promotions print first) are accepted anywhere with check, run, build, interp, emit-c and emit-ir. Shared IR produces identical plain-text stderr reports, before execution, without changing stdout or exit status. check lowers IR only when reporting is requested. Unknown/empty report values and unsupported commands exit 2 with usage text. Reports count static sites in reachable functions (omitting synthetic startup and uncalled shared originals whose callers all target $own). The C backend may reclaim a reported carry at runtime. retained entries do not increment the promotion count. Positions identify the retaining RHS (or return operand); a loop location identifies the source iteration scope. Promotion reports end with promotions: N; copy reports end with copies: N followed by clones: M (the number of emitted $own specialized clones, at most one per function with consumable parameters; see ADR-0278).

Copies include set, map-set and map-remove for each vector/map update whose backing storage is copied; the regions pass's uniqueness, field-take and consumed-parameter proof (VecSetUnique/MapSetUnique/MapRemoveUnique, $own clones) excludes in-place updates. Positions identify the receiver and include a parenthesized reason when storage reuse could not be proved: alias <var> live at L:C, param not consumed (caller <f> L:C), captured, indirect call, recursive call, or passed to call at L:C, as in copy: 2:12 overwrite: set vec<i64> (alias saved live at 2:28). Copying a 24-byte sequence handle is uncounted; promoting its backing storage is counted as promote.

Other copy kinds are tip-miss (non-in-place concat), aggregate (>16-byte record/union from a local, field or payload), and return (>16-byte non-slot record/union). Literal, call, with, match, if and sole-local returns use caller slots; parameters and multiple locals may copy. Arguments and embedded fields are uncounted. Fresh returned vec buffers use caller storage; scratch escapes may promote. See ADR-0043.

retained excludes tip accumulation through helper calls as well as direct appends. A helper that may also return an unrelated fresh allocation remains a retained site, even when another return extends its carry argument. Example:

promotion: 7:14 main: str into `best` (loop at 5:5)
retained: 9:9 main: str into `key` (loop at 5:5)
promotions: 1

Check reports

--report=checks is accepted wherever the allocation reports are, and prints after them. It counts static sites per reachable function, source line and kind, in function order, then line, then kind; generic and $own instances report under their own names (see Allocation reports for --report=copies reasons and clones: N). Each row is check: <line> <function>: <kind> remaining=N eliminated=M, and the report ends with checks: remaining=N eliminated=M:

check: 3 total: overflow remaining=0 eliminated=1
check: 4 total: bounds remaining=0 eliminated=1
check: 4 total: overflow remaining=1 eliminated=0
checks: remaining=1 eliminated=2

Kinds are bounds (v[i], b[i], s.byte(i), v.set(i, x)), slice, overflow (+ - *, unary -, checked conversions), divide (/ and %, covering zero and overflow together) and shift. A for head's increment counts at the for. Allocation, I/O, UTF-8 and platform failures are not value checks and are not listed. Eliminated checks are dropped from emitted C only when a range fact proves they cannot fail; the interpreter still runs them, so traps and output are unaffected. slice sites always remain. See ADR-0066.

checkfree is contextual, directly before a top-level fn; methods cannot take it. Every command, including check, reports E0720 for each listed check left in the body, sorted by position. It runs after all other front-end diagnostics, on reached instances of generics (a site left in several is listed once). The proof is per function: callees' checks and allocation, I/O and platform failures do not count, and facts about a parameter's values are not assumed.

Shift-count help: use a constant or guarded count in 0..width. Contradictory sequence lengths retain bounds checks, including in dead branches. Proven conditional increments emit plain branchless addition, matching the report.

Interpreter call depth is limited to 200,000 and active nested blocks across calls to 1,000,000; exceeding either flushes stdout and exits 2. A closed stdout pipe exits 141 silently. Decimal u64 fuel may precede/follow the path; each function entry (including main) and loop head charges one, trapping at the next charge. --fuel 0 traps at main; compiled commands have neither fuel nor interpreter depth limits.

The internal generator API interp::run_pure runs a zero-argument synthetic entry on a scoped worker and returns owned Rust strings from result<str, str>. Generator policy fixes 50,000,000 fuel charges (the ADR-0017 unit), 256 MiB of cumulative fresh-buffer allocation/growth, and 16 MiB for either returned string. Heap growth is checked before allocation; views are uncharged and there are no refunds. The heap budget bounds charged allocations, not exact RSS. Sandboxed platform, print and exit IR are compiler-bug tool errors (exit 3). These are internal tool policies, not source diagnostics; see ADR-0079.

The stdout flush includes the runtime's redirected-output buffer, including partial lines and embedded NULs. When stdout and stderr share a file or pipe (2>&1), all preceding stdout bytes appear before the trap line. Normal exit also flushes pending stdout.

Interpreter trap events

For a genuine runtime trap, tenon interp --json writes the ordinary trap line to stderr and appends one compact JSON object followed by LF. Application stdout and stderr keep their original bytes. The final diagnostics selector controls the mode. Human mode and the C backend keep the ordinary trap line. Trap status is 101 when output handling permits it. Output failures retain their usual precedence. Explicit exit 101, compiler errors and depth-limit failures follow their existing paths.

The object has event: "trap", backend: "interp", kind, at, frames, omitted_frames and truncated. The at object contains the trap site as file, line and column. Each frame has its source function name and an at object for its definition position. Frames run from innermost to outermost. Synthetic and native host frames are elided.

The first frame includes arguments and omitted_arguments. Each argument has a zero-based ordinal, source type and a status of complete, truncated, redacted or unavailable. Only complete previews carry a value. Checked integers use lossless decimal strings. Booleans use JSON booleans and unit uses null. Text, bytes and aggregate contents are withheld. Capabilities and secret references are redacted. Acquiring a secret suppresses integer and boolean previews, including arguments captured before acquisition.

The event uses at most 4,096 UTF-8 bytes including JSON escapes and LF, with at most eight frames and four arguments. The interpreter clips long labels at character boundaries. The encoder drops outer frames if needed to fit the event. Omission counts and truncated record these limits. The original trap line retains the full trap location. Application stderr can contain lookalike JSON, so this stream cannot authenticate an event.

Authority reports

--report=authority is accepted anywhere with check, run, build, interp, emit-c and emit-ir. It reports modeled operations reachable from each materialized function instance in the verified lowered root. It prints last, after promotions, copies and checks, regardless of flag order; repeated flags print once. Existing report bytes and program stdout/status are unchanged. Authority is always text, even with --json; that flag still selects JSON compiler diagnostics. Unknown/empty report values or unsupported commands exit 2.

The format begins with exactly:

authority 1 scope=lowered-root coverage=materialized-instances

Rows sort by stable function key, then category. A represented instance with no findings has effect=none-observed; this is scoped observation, not a proof of purity, determinism, termination, absence of traps, or coverage of uninstantiated functions/other roots. Each other row has one complete shortest deterministic witness to a real operation or opaque boundary. Direct sites win; equal-length paths choose stable callee key then source position. Unknowns remain findings even without a known effect.

authority: function="main.tn#fn main instance main" kind=function effect=none-observed
authority: function="main.tn#fn relay instance relay" kind=function effect=env.read witness="main.tn#fn relay instance relay" --("main.tn":2:1:statement)--> "main.tn#fn read instance read" terminal="main.tn":1:28:operation reason="reads the host environment"

The witness starts with its function key and repeats the arrow for each call; a direct effect has no arrow. terminal identifies the final operation's file, 1-based line/column, and precision; reason is a static classification. Columns count Unicode scalar values. Precision is operation, statement, definition or synthetic-anchor: statement/synthetic anchors do not claim exact callee tokens. Quoted keys/files/reasons use JSON string escaping, preserving UTF-8 and escaping controls. Rows end in LF and never embed a literal argument, secret value, raw FuncId or global parallel slot as an identity.

Kinds are function, entry-wrapper, parallel-body or synthetic. Concrete generic/impl instances remain separate. Lifted bodies stay in the graph and have their own rows. The compiler's entry wrapper is separately labelled; its error-branch printing/exit are not attributed to its callee. Paths reuse source-item identities relative to the logical root, retaining dependency names.

Categories include stdout/stderr writes, program exit, arguments/environment, filesystem open/inspection/read/write/sync/close, delegated input reads, process launch, clock, workspace, secret access and authority acquisition/narrowing. A passed capability alone is not an operation. Restricting a grant does not perform its eventual action. Reader origin can be unspecified; terminal reads may flush stdout, and output redaction may inspect acquired secret snapshots. Workspace helper/backend behavior is conservatively included. Trusted externs remain unknown.extern even with scalar signatures; child execution retains process.spawn and unknown.child. Residual unmodeled native expansion remains unknown.native. Possible effects in untaken branches still count.

The report is computed only when requested, from existing checked source and lowered IR. It adds no execution, fetch, persistence, instrumentation or runtime enforcement. Frontend failure emits its ordinary diagnostics with no authority report. Successful lowering prints the static report before emission/execution; later native-build or program stderr can follow it. Use check when comparing before/after authority without running the program.

For review, materialize the baseline and checked candidate in separate disposable projects with the same relative source paths. Run check --report=authority on each root and first compare represented instance keys. Missing/new instances are coverage changes; compare effect-category sets only within the shared scope. Review added (instance, category) pairs with their full witnesses. Moving a terminal line alone is not a new effect. An unused capability can become a write when a callee starts using it, even though the function's signature stays fixed. Keep this inspection separate from sandbox policy and edit authorization. A future signature-edit preview can supply the checked disposable candidate; the report does not expand that operation's required trailing-i64 contract.

Output failures

Stdout uses terminal line buffering, otherwise lazy 64 KiB buffering. Non-pipe stdout write failures print error: cannot write stdout and exit 1; broken stdout pipes exit 141. Normal completion and traps flush pending stdout. Stderr writes retry interruptions. Broken stderr pipes exit 141 without flushing pending stdout, including when the native process inherits ignored SIGPIPE. Other stderr write failures (including synthetic main-error output) flush stdout and exit 1; a broken stdout pipe during that flush takes precedence (141). Tool-error reporting is best-effort: a lost stderr message keeps the error's exit code.

Generated C maps function bodies back to .tn source lines with #line directives. C compiler messages and debugger locations use those lines; generated includes, prototypes and the entry wrapper retain their C file locations. This mapping adds no Tenon diagnostic codes.

Agent edit tools

These commands print plain tenon: <message> errors to stderr and exit 2 (including candidate syntax/type errors, which keep their E… code and line:col in the message); they allocate no diagnostic codes. Successful edits exit 0 with empty stdout/stderr. Ordinary check remains the way to request coded diagnostics. --json changes only outline output here.

edit replace-fn rejects symlinks and nonregular files. An explicit formatter path may resolve a symlink, but the opened target must be a regular file. Source publication stages and syncs sibling files with original permissions. Cooperating writers lock the containing directories. Each file is exchanged with its candidate so that a racing version can be identified and recovered. Conflict and rollback errors name any retained version in a sibling .tenon-edit-* directory. Atomic exchange requires filesystem support on macOS or Linux. There is no cross-file crash transaction or atomic compare-and-replace, and the guard cannot protect subsequent writes through a detached file descriptor. Other hard links to a formatted file keep their original inode. ADR-0184 describes recovery.

Generated files are identified only by this exact first line:

~1g

Directory fmt --check walks skip them. Direct fmt (including --check) and edit replace-fn refuse them with exit 2. Generated declarations are ordinary host-module items for hashes and check-compat; derive directives do not enter canonical forms or hashes. These refusals are plain CLI errors.

Bounded caller context

tenon context <root.tn> '<path>#fn <name>' --budget <bytes> [--json] checks one program or library root and reports the selected top-level free function, its original source, direct callers and one-hop dependency signatures. The selector is an exact dependency-graph identity: relative to the worktree or package root, or the input directory for a standalone file. For example:

tenon context examples/tools/head.tn 'examples/tools/head_config.tn#fn chunk_size' --budget 1024 --json

Aliases keep their original call spelling and provider identity. Repeated and recursive calls remain separate. Methods and extern targets are unsupported. Only the chosen root's checked closure is analyzed; a caller in test code is an ordinary static caller, not evidence of test execution or coverage.

One required budget is ASCII decimal in 19..=1048576, with no sign or suffix. It bounds successful stdout bytes, including UTF-8, escaping and the final LF. Success exits 0 with empty stderr. --json or --diagnostics=json selects compact JSON output; the default is labelled text. Global diagnostic flags follow their ordinary last-flag-wins rule. Program arguments after -- and execution reports are rejected. Arguments are validated before loading source.

Normal JSON field order is target,signature,complete,source,callers,dependencies, other_refs,unknown_refs,omitted,truncated. source is the complete original function text or null. Each caller contains caller,callee,file,callee_span, call_span,spelling,generated; both spans are {start,end}, zero-based half-open byte ranges in the original file. The call range excludes surrounding grouping. Dependencies contain id,signature; references contain file,span,kind or file,span,reason (unmapped unknowns have null locations). Known generated callers carry generated:true; generated status alone does not imply unknown analysis. omitted counts source (0/1) and the four lists.

complete describes analysis, while truncated describes presentation. Exact mapping across an escaped nested-string boundary is unsupported: relevant uses appear in unknown_refs and set complete:false, rather than guessed spans. Unknowns can remain even in an untruncated response. No response grants edit authority or describes other entry roots.

The mandatory target/signature/status/counter envelope is reserved first. Optional records are tried as first caller, source, remaining callers, dependencies, other references, unknown references. Sites sort by stable file identity, start/end and identity ties; dependencies sort by ID. Oversized records are skipped whole, then later records are tried. Text uses the same ordered facts with labelled compact JSON record rows and independently counted bytes. If even the all-omitted envelope cannot fit, stdout is exactly {"truncated":true}\n in JSON (19 bytes) or truncated\n in text; these sentinels give no completeness or caller-count information.

Source diagnostics exit 1, preserve existing codes and use the requested stderr format. Usage, unreadable input and missing/unsupported/ambiguous selectors exit 2 with plain tenon: <message> stderr. All such failures leave stdout empty, including with a tiny valid budget; no new diagnostic code is allocated. Output I/O uses the source tools' existing handling (broken pipe exits 141).

Context reads existing dependencies and verified generated companions. It never executes the program, builds, fetches, regenerates companions, snapshots the VC store or writes a project/cache file. A stale companion is a source diagnostic. The existing deps command retains its separate graph-cache behavior.

API cards and symbol index

tenon doc --card <pkg-or-file> [--budget N] [--module M] [--symbol NAME] [--query SUBSTR] [--format card|json] [--json] extracts a deterministic, token-budgeted public API card from a single .tn file, a package directory, or an edition-2026 member name. It allocates no diagnostic codes: usage and I/O errors print tenon: <message> to stderr and exit 2; success exits 0.

Application tests

For fixture setup and worked examples, see the application testing guide.

tenon test <project-dir> [--timeout-ms N] [--json] checks trusted application fixtures on native C and the interpreter. Run from any directory. The project contains tests/<case>/expected.out; cases are sorted by UTF-8 name. Sources remain in their original project/module/package context. Existing prepared locks, dependency trees and generated companions are used offline: the command never fetches, generates or invokes fixture hooks. It needs a C compiler even for interpreter checks. Existing compiler diagnostics retain their stable codes.

The default source is project main.tn; optional case source selects one project-relative .tn entry. Optional expected.err defaults empty and expected.exit defaults 0 (ASCII 0..255). stdin and expectations are raw bytes. args holds one literal argument per line; env holds distinct KEY=VALUE lines. files/ is copied separately for each backend and a fresh tmp/ is made. {case} and {tmp} expand to . and tmp. expected.file checks tmp/out. Input symlinks/special files and source escapes are refused. Compiler, loader, PATH and Tenon control environment settings are reserved; ordinary app keys remain allowed. Execution uses a clean app environment, not the caller's loader or tool settings. Private workspaces isolate fixture data; they are not OS containment for untrusted code.

Fixture discovery and validation precede case budgets. Each case has one monotonic wall-clock budget covering copies of validated inputs, native build, native execution, interpreter preparation/execution and pipe completion. Default 30,000 ms; --timeout-ms N takes one unsigned ASCII decimal integer 1..600,000. It cannot reset or disable the budget. Duplicate/missing/invalid values, extra arguments and -- forwarding are usage errors (exit 2); use fixture args. Suite compiler/bootstrap probing is separately bounded. Combined stdout/stderr capture is limited to 1 MiB per stage; requested output-file reads have the same bound. Exceeding a limit is a failure, not a truncated passing comparison.

Exit 0 means all reported cases passed both backends. Exit 1 means case mismatch, source/build/execution failure, timeout or no cases; exit 2 means invalid fixture or unavailable compiler prerequisite; exit 3 means internal/ownership failure. Mixed results keep the highest severity. Numeric app exits 1/2/101 can pass only with matching expected bytes; tool errors cannot satisfy expected.exit. Signals are execution failures. Timeout reports one failed case with backend, prepare or execute phase and configured limit; partial output/exit/file/trap data is omitted. Cleanup finishes before a healthy next case. Ownership uncertainty stops the suite; unexecuted cases are not invented as passed results.

Human reports identify case, backend, field and final counts. JSON writes one summary on stdout, with ordered keys status, total, passed, failed, cases, then optional error. Status is passed or failed; counts describe reported cases. Case keys are name, status, failures; failures retain C, interpreter, pair order, then stdout/stderr/exit/file order. Failure keys include backend, field, optional phase/limit_ms or compile code, and detail. Byte mismatches give the first zero-based offset, lengths and bounded hex excerpts. Details are capped at 4096 UTF-8 bytes, with controls escaped for presentation. Child streams never become report syntax or pass/fail authority. A failed case with a completed interpreter trap also has one trap_report after failures. It uses the interpreter event fields and the same byte and disclosure limits. The private worker completion supplies the report from the execution used for comparison. An expectation-matching trap passes without an attachment. Explicit exits, a native-only trap, timeouts and missing completions supply no interpreter report. A missing completion remains an infrastructure failure.

A missing/empty tests directory gives error.kind="no_cases" and zero counts. Malformed fixtures give invalid_fixture before execution. missing_compiler covers unavailable or timed-out compiler/bootstrap prerequisites; internal covers infrastructure/ownership uncertainty. These suite errors include bounded detail; failed cases use the typed field names above. Standard output-write failure handling still applies (broken pipe 141, other write error 2).

Plugins

tenon plugin check [dir] checks manifest metadata (E0980), docs and index limits (E0981-E0984), name squatting (E0985), fmt --check, gen --check, tenon.requires freshness, kind conformance (E0986), plugin-local goldens (E0987), and prints a capability summary, in that order. Missing requirements are skipped. Checks continue after failures and exit 1 if any fail; usage errors exit 2. A missing C compiler exits 2. No source files are written. Names lowercase, remove underscores and map 0 to o and 1 to l before comparison; names of at least four normalized characters also reject edit distance one. Byte-identical embedded edition members are exempt. Generator kind conformance (E0986) tests each public generator on a small embedded struct, enum and newtype. A clean err is allowed; traps, limits, invalid output, stale companions, unequal repeated output or generator code in runtime declarations fail. Successful output must pass gen --check. Libraries report ok (library: no generator interface). Platform kind conformance validates platform.toml with the normal platform declaration checker. Unreadable or malformed declarations report E0988. Plugin-local goldens (E0987) live in tests/<case>/, with tenon.toml depending on { path = "../.." } (or on the plugin's own { edition = "2026" } member), main.tn and expected.out. Each runs on C and the interpreter, requiring successful exits and byte-identical stdout matching expected.out. Optional stdin, newline-separated args, env (KEY=VALUE) and expected.file follow program-golden conventions, including {case} and {tmp} substitutions. A case without main.tn is an in-language unit-test package (such as tests/unit/) and passes when tenon test does on both backends. Backend workspaces are separate. A missing C compiler exits 2 with installation guidance. Scratch projects, fetched locks and generated files are confined to the plugin's .tenon/ and cleaned up on success or failure; checked-in goldens are not rewritten. Goldens use offline path or edition dependencies. The tests/ root must be absent or a real directory. Discovery and copying do not follow case symlinks. Scratch checks for generator conformance and goldens never acquire Git dependencies, even through an indirect path dependency. The final summary lists the declared capability ceiling and capability types in public function signatures; generators also report generator stage: no capabilities. Generation checks, public capability summaries and edition-member module checks exclude tests/, .tenon/ and nested packages with their own tenon.toml.

A plugin is a package with optional [plugin] metadata: kind = "generator", "library", "platform", "process" or "script", and an index string starting with <name>:. The index is one line of at most 40 estimated tokens (about 30 is the target). Invalid plugin fields/kinds are E0980; malformed or over-budget index lines are E0983. Script plugins also name api = "<host>.plugin/<major>" and cannot declare the ffi capability, [ffi] or a platform (E0955); see script plugins.

tenon plugin new <kind> <name> [dir] scaffolds a generator, library or platform in dir (default ./<name>), with a manifest and DOCS.md. Generators and libraries include starter source; tenon plugin new platform <name> [dir] creates a stdout-only platform.toml using trusted natives. Generators include a tiny derive example under tests/example/. Package names use the manifest rule; invalid names report E0932 and exit 1. The plugin name check reports E0985 for reserved names before any scaffold files are written. Only the target directory is written, and an existing empty directory is accepted. Non-empty targets, non-directory targets (including symlinks) and I/O failures are plain CLI errors and exit 1; created paths are rolled back on failure. Missing parent directories are not created. Bad arguments exit 2. The unavailable kinds intrinsic, backend and tool exit 2 and point to the interface register in docs/extension-points.md.

tenon plugins index [dir] prints installed plugins, sorted by package name, then numeric version, one line each: <name>@<version>: <rest of index>. The directory defaults to .; a directory without a manifest prints nothing. Installed plugins are those in the root dependency graph plus members of the root package's edition (see the edition table), with declared packages taking precedence by name. Plain packages are omitted. The index does not read docs or load source modules. The edition index stays within 150 estimated tokens.

tenon plugins docs <file.tn> prints DOCS.md only for plugin packages imported by the root package's loaded modules. Generator-only imports count; transitive plugin imports do not. Each plugin appears once, sorted by name, as === plugin <name> <version> === followed by a newline and the docs verbatim, adding a final newline if absent. Both commands write nothing, fetch nothing, and use the existing dependency graph and lock validation. Run tenon fetch first when dependencies need a lock. Successful output goes to stdout; no matching plugins means empty output. Usage/source-read errors exit 2, diagnostics exit 1 and leave stdout empty; --json selects JSON diagnostics on stderr.

DOCS.md lives beside the plugin's tenon.toml, declares <!-- token-budget: 1500 -->, and contains at most 1,500 estimated tokens, including that comment. The estimator takes the greater of words × 1.35 and Unicode characters ÷ 3.6, rounding ties to even. E0981 means missing, unreadable or non-UTF-8 DOCS.md; E0982 means no 1,500-token budget comment or docs over that limit. Only selected docs are read and checked.

Platforms

The root package may select [package] platform = "cli" (the default, also for single files) or name a direct dependency whose [plugin] kind = "platform". Dependencies must not declare platform, even if it matches the root. The name uses the package-name syntax. See registry entries E0988–E0992 below.

A platform plugin's platform.toml is data, not executable native code. For example:

[platform]
root = "Out"
headers = ["trt_cli.h"]
seeded = ["CliError"]

[capability.Out]
kind = "Cli"
ceiling = ""
[capability.Stdout]
kind = "Stdout"
ceiling = "stdout"
[field."Out.stdout"]
type = "Stdout"
[method."Stdout.println"]
params = ["Printable"]
ret = "Unit"
native = "Stdout.println"

[platform] requires the root string and string arrays headers and seeded. Headers are selected without duplicates from trt_cli.h, trt_io.h, trt_proc.h, trt_net.h (and trt_agent.h, trt_ws.h for the agent platform); seeded types from CliError, Output. The root ABI requires trt_cli.h and CliError. Reads require trt_io.h, process operations require trt_proc.h, and result types may require Output or a File-kind capability.

Each [capability.Name] gives a unique trusted kind and its matching ceiling; names start with an ASCII uppercase letter and contain only ASCII letters, digits and underscores. CliError and Output are reserved. The root names the Cli-kind capability. [field."Receiver.member"] gives type as a declared capability name, args or raw_args. [method."Receiver.member"] gives string-array params, string ret and native: receiver kind and signature must exactly match the trusted toolchain registry in crates/tenon-compiler/src/natives.rs. Receivers must be declared, member identifiers start with an ASCII letter, and fields and methods cannot share a name on a receiver. Each kind of keyed table must be sorted by its key and unique. Optional [policy] accepts nonnegative integer fuel, heap, output and deadline_ms values; zero disables a limit. Unknown fields and tables are rejected. Natives are toolchain-owned and shared by both backends; a platform cannot provide arbitrary native implementations.

Type-checking notes

? diagnostics point at the postfix operator: E0520 rejects non-fallible values, E0521 rejects a non-fallible enclosing return (including main), E0522 rejects different result error types, and E0523 rejects mixing option and result. Propagation converts an error only by wrapping it in the unique variant of the return's (non-generic) error enum whose sole payload is that type (ADR-0275); zero or several such variants are E0522, whose help names the fix. Otherwise use r.map_err { e -> … } (a block method returning result<T, F>) or match. Malformed option/result annotations retain ordinary generic arity diagnostics (E0600/E0601), including when they are operands or enclosing returns of ?. Invalid generic annotations (E0600/E0601) and hidden parameters (E0608) recover with an error type, suppressing dependent mismatches. Invalid arithmetic operands likewise suppress a second return-type error for the same expression. Newtype E0301 help wraps the actual representation expression: let id: UserId = UserId(3) or id == UserId(1); extraction help refers to the operand at the diagnostic span.

Vector methods

Vectors have len() and is_empty(); get(i), first() and last() return option<T> (none for missing/out-of-bounds elements). contains(x) uses structural equality. set(i, x) checks an i64 index, trapping out of bounds; it copies O(n) unless a fresh unaliased local permits O(1) reuse, including before terminal return (see the arena/set notes above). concat(v) copies both inputs; push(x) appends; vec<str>.join(sep) returns str. Updates preserve snapshots; discarding their immutable results is E0711. The push guarantee in ADR-0041 applies through locals, fields and helpers. vec<u8>.to_bytes() copies the vector elements into bytes unchanged, including values from 0x80 through 0xFF; an empty vector produces empty bytes. Other vector element types have no to_bytes() method (E0662). The result is an independent byte value, so later vector updates preserve the converted snapshot.

Codes

Sequence traps also exit 101 after flushing stdout: index out of bounds, slice out of bounds, invalid char boundary. They point at the base expression. Slice bounds are checked before UTF-8 boundaries. Bytes slicing does not require UTF-8; to_str() returns none on invalid bytes. Search uses byte offsets; parsing never traps on malformed/overflowing text.

Code Meaning Fixed example
E0001 Unterminated string literal cli.stdout.println("hello"): close the quote before the end of the line.
E0002 Unknown character or malformed number; source is ASCII outside strings and comments let name = 1: remove the unsupported character. Also 0x without digits, uppercase 0X10 and literal suffixes (0xFFu8): write u8(0xFF) or let x: u8 = 255.
E0003 Integer literal does not fit in u64 18446744073709551615 is the largest u64.
E0004 Unknown escape in string cli.stdout.println("a\nb"); valid escapes are \n \t \r \\ \" \0.
E0005 Lone & or | is not an operator a && b or a || b.
E0006 Malformed float literal: 1., .5, 1e5 or a suffix 1.0, 0.5, 1.0e5; floats have no suffixes (ADR-0177).
E0007 Float literal rounds to infinity Keep the magnitude below 1.7976931348623157e308.
E0100 Expected an expression let x = 1; use a number, string, name, call or (…).
E0101 Missing statement separator let x = 1; cli.stdout.println(x); separate statements with a newline or ;. Braces retain statement newlines even inside parentheses.
E0102 Expected a top-level declaration: fn, struct, enum or type; message also lists planned interface/impl (M4.7) fn main() { let x = 1 }; statements belong inside functions.
E0103 Unclosed { or (; span points at the opening delimiter fn main() {}; add the matching } or ).
E0104 Expected a token or name (context in help) cli.stdout.println(1); add ) to close the call. Newtype declarations need newline, ; or EOF after the representation; type is a keyword, not a name (let kind = 1).
E0105 Cannot assign to this expression x = 2; only a variable name can be left of =.
E0106 Comparison operators cannot be chained at the same precedence a < b && b < c. For invalid Box<i64> { v: 1 }, dedicated help says generic struct literals infer their arguments: write Box { … }; fix removes the type arguments.
E0107 break or continue outside a loop Use it inside while or for: for i in 0..1 { break }.
E0108 Parameter needs a type fn f(n: i64) {}.
E0109 let or var needs a value let x = 0.
E0110 = assigns; use == to compare if x == 1 {}.
E0111 ++ is not supported Write x = x + 1 or x += 1 (+=, -=, *=, /=, %= are supported on var bindings).
E0112 Expression nested too deeply (limit 256) let part = a + b; cli.stdout.println(part + c); split nesting with let bindings.
E0113 Unclosed { in a string interpolation cli.stdout.println("value: {x}"); close the expression, or write {{ for a literal brace.
E0114 Empty string interpolation cli.stdout.println("value: {x}"); put an expression inside the braces.
E0115 Malformed import declaration/alias or import after an item import util { parse }; imports need a module path and selected names, aliases need both names, and imports must come first.
E0116 pub cannot be applied to an impl impl Area for Point { … }; impls are global and do not take a visibility modifier.
E0117 Malformed derive declaration Write derive Generator for Target without pub or type arguments.
E0120 Malformed or unsupported compact source header (legacy compact-only error) Ordinary UTF-8 .tn files dual-read directly; for compact files, start with ~1 followed by LF or convert with tenon fmt --migrate-utf8.
E0121 Missing or malformed compact source header Start the file with ~1 followed by LF.
E0122 Unsupported compact source version Use a compiler that supports the file's format.
E0123 Unregistered compact dictionary Use the pinned dictionary build.
E0124 Unknown compact opcode Use the opcode for the current declaration or operand.
E0125 Invalid compact frame, field, record or text block Correct the reported compact operand or boundary. For text blocks, delete surplus | lines; reduce N when lines exist or insert bare | lines when none; replace N=0 with an empty " frame; delete the offending control byte.
E0126 Invalid compact binding reference or override Use the in-scope ordinal or correct its spelling entry.
E0127 Compact source exceeds a structural or byte budget Split the source or reduce nesting and operand counts.
E0128 Source cannot be represented by the conversion utility Check the original construct at the reported range.
E0201 Unknown variable name let x = 1; cli.stdout.println(x); declare it before use. Bare some/ok/err need a local; constructor help suggests some(…)/ok(…)/err(…).
E0202 Unknown function fn helper() {}; define it before calling (definition order is unrestricted).
E0203 Duplicate function name, reserved print/println, integer conversion redefinition, reserved seeded type/function name, or integer type name used as a function (fn u8) fn helper() {} or struct Item { value: i64 }; do not redefine integer conversion functions or top-level types/functions named option, result, some, none, ok or err. Locals remain legal.
E0204 Assignment to an immutable let local or for binder var x = 1; x = 2; fix replaces let with var. For binders suggest a separate body-local var, without a token replacement.
E0205 Missing main; span is [0,0] fn main() {}.
E0206 Duplicate parameter name fn pair(x: i64, y: i64) {}.
E0207 main takes no parameters or cli: Cli Write fn main() or fn main(cli: Cli) -> result<unit, CliError>.
E0208 Local name already declared in the same block var x = 1; x = 2; assign to an existing var, or choose a new name.
E0209 Local shadows an outer local or parameter let x = 1; if true { let inner = x + 1 }; choose a distinct name.
E0210 Type is defined twice struct Point { x: i64 }; rename one of the duplicate types.
E0211 Type name is a builtin struct Count { value: i64 }; do not redefine builtin types including i64, i32, u8, u32, u64, bool, str, bytes, vec or unit. Seeded union/constructor names use E0203.
E0212 Test name is defined twice in one file Rename one of the test blocks.
E0220 Imported module file not found; names the path tried Place the module at the root-relative path, or remove the import.
E0221 Import cycle; names the module chain Remove an import to break the cycle.
E0222 Module has no such provider item, imported or qualified m.item; names the module and nearest provider spelling (not its import alias) Import the original item declared by that module, or correct its spelling.
E0223 Imported or qualified item is private; names its module Add pub to the provider's declaration.
E0224 Imported local or module name conflicts with a local item, another import or module name, or a whole module is imported twice Change the alias or remove/rename the conflicting declaration or import.
E0225 Public signature exposes a private type of its module Make the type public or remove it from the public signature; newtype representations are exempt.
E0226 Newtype constructor is private to its declaring file Use a public factory function from the named module; root-file declarations cannot be imported.
E0227 Newtype .value is private to its declaring file Use a public accessor function from the named module; root-file declarations cannot be imported.
E0228 Method's interface is not in scope in the calling file Import the named interface; a bound enables only its own receiver parameter. Qualified names grant no access; root-file declarations cannot be imported. Error-typed receivers suppress this cascade.
E0229 One file imports a module both selectively and whole Use one form: import a.b for qualified b.f, or import a.b { f }.
E0301 Expected T, found U: operands, arguments, annotations, assignment or if branches let n: i64 = 1; use matching types, or explicitly convert integers with i64(x). Use matching types in both branches of if flag { 1 } else { 0 }. none in a non-option context reports one mismatch with option<T>, not E0602. For "a" + 1, use interpolation: "a{n}".
E0302 Wrong argument count, including output methods cli.stdout.println(1); supply the declared number of arguments.
E0303 Retired in M2.2: string literals are now typed str values let text: str = "hello"; cli.stdout.println(text) is legal.
E0304 Condition expected bool, found another type if x != 0 {} or while x != 0 {} for any integer type.
E0305 Return expected the function's declared type, found another type (bare return is unit) fn n() -> i64 { return 0 }.
E0306 Function may reach its end: expected declared non-unit type, found unit fn n(flag: bool) -> i64 { if flag { return 1 }; return 0 }; fix appends a return before the closing brace. Loops conservatively may finish.
E0307 Expected a type, found an unknown type name; suppresses follow-on type mismatches let n: i64 = 1; use a builtin or declared type, not int.
E0308 If used as a value expected an else branch producing T, found unit let n = if flag { 1 } else { 0 }; add else.
E0309 Print argument or interpolation part expected an integer, bool or str, found another type Print a field or newtype .value; for vectors print v.len() or loop with for x in v { cli.stdout.println(x) }. Call unit functions separately; unit alone has fix 0.
E0310 main must be fn main() or return result<unit, CliError> Write fn main() or fn main(cli: Cli) -> result<unit, CliError>. Return annotation edits are offered only when their range contains no comments.
E0311 Retired in M5.3a: interpolation now produces str anywhere let text: str = "value: {x}" is legal; parts must be integers, bool or str (E0309).
E0312 Integer literal does not fit its inferred or expected integer type let x: u8 = 255; use a literal within the type's range. Write the i64 minimum as -9223372036854775807 - 1, the i32 minimum as -2147483647 - 1.
E0313 Cannot negate an unsigned integer x.wrapping_neg() or -i64(x); checked conversion can overflow.
E0314 Cannot convert a non-integer to an integer u8(42); conversions take integers, and only i64(x) takes f64: u8(i64(x)).
E0315 Integer conversion takes exactly one argument u8(x); provide one integer argument.
E0316 f64(x) takes an integer or f64 s.parse_f64() for text; f64(n) for integers.
E0317 f64 has no % operator Compute x - (x / y).trunc() * y.
E0400 Unknown record type struct Point { x: i64 }; declare the record before constructing it (source order is unrestricted).
E0401 Record literal is missing fields; all names listed in declaration order Point { x: 1, y: 2 }; add every field; all are required.
E0402 Field is set twice Point { x: 1 }; remove the duplicate initializer.
E0403 Record literal has an unknown field Point { x: 1 }; use one of its listed fields.
E0404 Record field access names an unknown field p.x; use one of its listed fields.
E0405 Field access needs a record or newtype value p.x or id.value; use a declared field. Builtin method help suggests s.len(); parameterless method fixes append parentheses.
E0406 Cannot assign to a field of a non-local target Bind a mutable var local first (var t = f(); t.y = 1); field assignment on immutable let bindings emits E0204.
E0407 Record is not a function Point { x: 1 }; use a record literal rather than Point(1).
E0408 Field is declared twice struct Point { x: i64, y: i64 }; rename one of them.
E0409 Record has no fields struct Point { x: i64 }; add a field.
E0410 Type contains itself by value; first cycle shown in source order Direct struct Node { next: Node } is rejected. Break the cycle with vec/map (or option of those), or store an index/i64 id. Inductive recursion through containers is allowed (ADR-0270).
E0411 `with` expected a record, found {} p with { x: 1 }; use a record value.
E0412 record `{}` has no field `{}` (in with) p with { x: 1 }; its fields are {}.
E0413 field `{}` is replaced twice p with { x: 1 }; remove one.
E0414 `with` needs at least one field p; fix removes with { }.
E0415 Duplicate or overlapping field paths in with Keep each updated path distinct (do not update both a and a.b, or a.b twice, in one with).
E0420 Type aliases are not supported type UserId = new i64; use new to declare a nominal wrapper.
E0421 Newtypes cannot be generic type UserId = new i64; use a generic struct when a generic type is needed.
E0500 match expected a union, found {} if flag { 1 } else { 2 }; match a union, integer or str scrutinee, and use if for bool or f64.
E0501 union `{}` has no variant `{}` Shape.Empty; its variants are listed in help.
E0502 match is not exhaustive: missing {}; every name in declaration order Rect(_, _) => 0; add an arm for every listed variant.
E0503 invalid wildcard arm on union `{}` ; redundant wildcard arm on union `{}` use one unqualified `_` as the final arm, without binders or alternatives; remove `_`: every variant is already covered.
E0504 variant `{}` is matched twice A => 1; remove the later arm.
E0505 variant `{}` has {} fields but the pattern binds {} Rect(w, h) => w * h; write the right positional shape.
E0506 alternatives bind different names: {} and {} A(x) | B(x) => x; bind the same names in every alternative.
E0507 binder `{}`: expected {}, found {} A(x) => 1 and B(y) => 2; split into separate arms.
E0508 binder `{}` is used twice in this pattern Rect(x, _) => x; rename one, or use _.
E0509 enum variants use positional payloads: `{}` Rect(i64, i64), not Rect(w: i64, h: i64) or Rect { w: i64, h: i64 }; use positional types, or a record payload.
E0510 enum `{}` has no variants enum E { A }; add a variant.
E0511 variant `{}` is declared twice enum E { A, B }; rename one of them.
E0512 variant `{}` needs a value Shape.Circle(3); supply the payload.
E0513 patterns take names only: nested and literal patterns are not supported; string patterns cannot interpolate values; f64 values cannot be match patterns In union patterns use Circle(r) => r; bind a name, then match or if inside the arm. For strings, use a literal string pattern, or compare inside an arm. For f64, write if x == 1.5 { … }.
E0514 expected a newline or `,` after the match arm, found {}; or unexpected , between arms match e { A => 1, B => 2 }; put each arm on its own line or use a single comma, also inside call arguments; remove stray commas.
E0515 pattern qualifier `{}` is not the scrutinee's union `{}` For a value of E, write E.A => 1 or A => 1, not F.A => 1; fix replaces the qualifier. Recognized variants still count toward coverage.
E0516 variant `{}` has no payload; omit parentheses Write E.C instead of E.C(), or pattern C => 1 instead of C() => 1; fix removes the parentheses and any arguments.
E0517 Invalid integer or str pattern or default placement (integer wording unchanged) Use in-range integer literals/nonempty half-open ranges or str literals, and one final _ arm.
E0518 Integer or str match requires a final default arm (integer wording unchanged) Add _ => … after the patterns.
E0520 `?` expected option or result, found {} For fn main() { let x = 1? }, remove ?: fn main() { let x = 1 }. Use ? only on a fallible value.
E0521 `?` needs a function returning option or result, found {} In main use fn main(cli: Cli) -> result<unit, CliError>; in helpers change the return type, or match here.
E0522 `?`: expected error type {}, found {} Add a variant carrying the found type to the error enum (Io(IoError) in AppError) so ? wraps it, or map explicitly: read().map_err { e -> 0 }?. Several wrapping variants are ambiguous; use map_err.
E0523 `?`: expected {}, found {} (option vs result) fn f(x: option<i64>) -> result<i64, str> { return match x { some(n) => ok(n), none => err("missing") } }; match and return the right kind.
E0600 Type takes a different number of type arguments Pair<i64, str>; supply the declaration's argument count.
E0601 Generic type needs type arguments Box<i64>; annotations require explicit type arguments.
E0602 Cannot infer type parameter or empty vector element Annotate: let v: vec<i64> = [] or let x: Choice<i64> = Choice.Empty; help retains solved arguments.
E0603 Type arguments are inferred at calls; refines invalid comparison syntax only id(42); remove <i64> from id<i64>(42) (mechanical fix). Valid comparisons such as f(a < b, c > (d)) remain expressions.
E0604 Type parameter has no method in its bounds fn f<T: Area>(x: T) { x.area() }; add a bound declaring the method.
E0605 Generic instantiation is too deep or too large id(42); simplify types/call chains to at most 64 discovery levels and 256 type nodes; chains longer than six entries show the first three and last three separated by ….
E0606 Too many generic instantiations (limit 10000) id(42); id(43) shares one instance; use fewer distinct type arguments.
E0607 Bounds belong on functions, not types struct Box<T> { value: T }; move bounds to functions (M4.7).
E0608 Type parameter hides a type fn id<T>(x: T) -> T { return x }; choose a name other than a builtin or declared type.
E0609 Type parameter is declared twice fn pair<A, B>(a: A, b: B) {}; rename one of them.
E0610 Main cannot be generic fn main() {}; remove its type parameters.
E0611 Interface bound is declared twice on a type parameter fn g<T: A>(x: T) {}; remove the duplicate bound from T: A + A.
E0650 Interface is implemented twice for the same exact type; cross-package conflicts name both packages and versions, with root first then package-name ordering independent of working directory; same-package wording is unchanged impl Area for Point { … }; keep one implementation, in one package.
E0651 Type does not implement a required interface impl Area for Point { … }; add an impl, or forward the bound on a type parameter.
E0652 Impl is missing required methods; lists every missing name impl Area for Point { fn area(self) -> i64 { return self.x } }; add each method.
E0653 Interface has no such method Area.area(p); use one of its listed methods.
E0654 Impl method signature differs; shows expected and found after substituting Self fn add(self, other: Self) -> Self; match the interface's signature.
E0655 Interface/impl method needs self first fn area(self) -> i64; write self as the first parameter.
E0656 Method cannot be generic fn area(self) -> i64; move generics to a free function.
E0657 Generic impls and interfaces are not supported impl Area for Point { … }; implement each concrete type.
E0658 Methods need an interface; inherent impls are unsupported interface Area { fn area(self) -> i64 }; use an interface, or a free fn f(x: Point).
E0659 Method is ambiguous between interfaces Qualify with the intended interface, e.g. Area.area(p). The fix uses the first candidate with an unshadowed name in the calling file.
E0660 Unknown interface in a bound or impl interface Area { fn area(self) -> i64 }; declare the interface.
E0661 Method is declared twice in an interface or impl interface Area { fn area(self) -> i64 }; rename one of them.
E0662 Concrete type has no applicable builtin/interface method impl Area for Point { … }; implement an interface declaring it. Builtin sequences, integers, options and results list their supported methods; bool has a no-such-method note.
E0663 Interface used as a value type fn f<T: Area>(x: T) {} or dyn Area; use a bound or dyn interface value.
E0664 Function or dyn value compared with ==/!= or contains fn and dyn values have no equality; compare a key or call them instead.
E0665 Function or dyn type in impl, FFI, or derive fn and dyn cannot be impl targets, FFI parameters/returns, or derived/reflected.
E0666 Function-typed record field called with method syntax (r.f)(x); parenthesize the field read to call a stored function.
E0667 Interface is not dyn-compatible Remove Self outside the first self parameter, or use a <T: I> bound.
E0700 A block is not a value Pass a block to a vector method, or write a { x -> … } closure with an expected fn type.
E0701 Function or method does not take a block Functions cannot take blocks; use for, a .map { … } method, or a closure argument.
E0702 Block or closure has the wrong number of parameters Match the method block or expected fn(…) parameter count.
E0703 Control cannot leave a block or closure Use a for loop for return/break/continue; ? is allowed inside closures targeting their own option/result.
E0704 Vector method needs a block Write v.map { x -> x * 2 }, v.filter { x -> x > 0 }, v.fold(init) { acc, x -> acc + x } or v.sort_by { a, b -> a < b }.
E0705 Block result has the wrong type Make the last expression bool for filter/sort_by, the accumulator type for fold, or the expected element type for map. A statement tail is unit.
E0706 Closure needs an expected fn type let f: fn(i64) -> i64 = { x -> x + 1 }; annotate the binding or pass to a typed parameter.
E0707 Cannot assign to a captured outer var in a closure Closures capture snapshots by value; return the new value instead of mutating an outer var.
E0708 Function-typed local shares a visible function name Rename the local so name(…) is unambiguous.
E0709 Cannot call a non-function value Call a named function or a fn(…) value.
E0710 Cannot assign to an element or slice: values are immutable Rebuild strings using concatenation; for vectors write v = v.set(i, x).
E0711 Result of an immutable update is unused Assign text = text.trim(), v = v.set(i, x), v = v.concat(w) or v = v.push(x) (receiver must be var); named receivers get an assignment fix.
E0712 Cannot index str by position Use s.byte(i) for u8, s[a..b] for a substring, or s.chars() for Unicode scalars.
E0713 Brackets need a sequence, found another type Read a field first, or index bytes or a vec.
E0714 Expected i64 index, found another type Use an i64 offset, for example 0.
E0715 Range .. is only valid in for and slices Write s[a..b] or for i in a..b { … }.
E0716 Expected vec, bytes or range in for, found another type For str use s.chars() or s.bytes().
E0717 Unknown for form: expected for name in … Write for x in v { … }, or for k, v in m { … } for maps.
E0718 Expected a slice bound of i64, found another type Use an i64 offset, for example s[0..1].
E0719 Expected str or bytes for +, found an unsupported operand Use a.concat(b) for vectors (M5.4) or "{a}{b}" for mixed printable values. Integer arithmetic keeps E0301.
E0720 A runtime check remains in a checkfree fn; one error per remaining site Guard the value (if i >= 0 && i < v.len() { … }), use a wrapping method, or remove checkfree.
E0721 Parallel block assigns to a captured variable Use a worker-local variable or return a result instead.
E0722 Parallel block captures or returns a non-Fs capability, or uses Fs.open or File Capture Fs and use fs.read or fs.read_text; bind par outside the worker (nested Par is forbidden).
E0800 Global {} was removed: output goes through cli Write cli.stdout.{}(…); main takes cli: Cli. Fix replaces the callee when cli is in scope.
E0801 Cannot construct a capability Take cli.stdout (or another field) from main's cli: Cli parameter.
E0802 Cli has no such field Fields: stdin, stdout, stderr, args, raw_args, env, fs, net, process.
E0803 Capability has no such method Stdout/Stderr: print, println, write, flush; cli.exit; env.get, env.get_bytes. Stdin, File: lines, byte_lines, chunks, read_all, read_text; File: close. Fs: exists, list, open, read, read_text, write, restrict, read_only, no_follow; Net: restrict, none. Agent-only Host.grant, Host.secret, Grant.name, Grant.narrow and SecretRef.reveal require the agent platform.
E0804 Cli field is not a method Write let out = cli.stdout, without parentheses.
E0805 No cli in scope Only when the receiver is neither a local nor a type/interface qualifier. Add a cli: Cli parameter; main needs fn main(cli: Cli) -> result<unit, CliError>.
E0806 Write expects bytes For str use println, or write x.bytes().
E0807 Capability cannot be compared Capabilities have no value to compare; pass the capability to a helper instead.
E0808 ok() needs result<unit, E>, found result<T, E> Write ok(value) for a non-unit success payload.
E0810 Fs restriction root is not a path Wrap a string with path(".").
E0811 Capability cannot be attenuated with this method Use restrict, read_only or no_follow on Fs, or restrict or none on Net.
E0812 Malformed literal network host Use a DNS name or IP literal, optionally with a port from 1 to 65535.
E0813 Cannot derive or serialize a type containing a capability Keep capability handles outside derived data, including nested and generic fields.
E0814 Capability not exported by the selected platform Use capability types declared by the application's platform.
E0815 platform.toml requires a platform plugin package Declare [plugin] kind = "platform" or remove platform.toml.
E0816 Capability types cannot be reflected Reflect ordinary data types; receive capabilities from the platform.
E0817 Sandbox argument is not an Fs or Net Pass an Fs first and a Net second to Process.sandbox.
E0818 Process limit must be positive Use a limit of at least 1, e.g. limit(1048576, 10000).
E0820 Thread limit must be positive Use a thread limit of at least 1, e.g. cli.par.limit(2).
E0825 Unsupported ToolSchema field type: capability (including Grant or SecretRef), recursive type, or non-str map key Use acyclic ordinary data with string map keys.
E0826 Invalid tool name or duplicate tool name in one union Use unique names matching ^[a-z][a-z0-9_]{0,63}$ within the union.
E0840 Agent state is not sendable across workers: it recursively contains a capability handle, including a stream Keep capability handles outside agent state; Grant, SecretRef and ports are allowed.
E0841 Unknown workspace_backend platform policy value Use "auto" (reflink → git-worktree → Unsupported), "reflink", "git-worktree", opt-in "copy", or "vc" with trusted TENON_VC_BIN; overlay is detect-only.
E0842 Invalid concurrency limit: zero, negative, non-integer, duplicate or unknown provider/tool key shape Use [policy.limits.provider] or [policy.limits.tool] with name = 1; omit names for unlimited. [policy.limits] also accepts provider = { default = 1 }, tool = { echo = 1 } or quoted "tool.echo" = 1. Names contain ASCII letters, digits, _ or -; dynamic tool names are not a static registry.
E0843 Invalid tool-server declaration: missing/relative command, unknown kind/scope, or malformed fields Use [tool_server.<id>] with kind = "mcp" or "lsp", absolute string command, optional string-array args (default []), and scope = "repo" or "runtime". Command and arguments cannot contain NUL bytes.
E0844 Duplicate tool-server id, or multiple repo-scoped declarations of the same kind Use unique ids and at most one repo-scoped server per kind in a platform declaration. Runtime-scoped declarations do not claim a repo slot.
E0845 Invalid sandbox toolchain policy: expected unique known names in a string array Use sandbox_toolchains = ["xcode-select"] or ["xcode-select", "homebrew"]; [] disables.
E0850 Expected path, found another type Wrap str or bytes with path(x).
E0851 Cannot convert this type to path path takes str or bytes, e.g. path("file").
E0852 Path is not printable, including in interpolation: it may not be UTF-8 Write p.display() for lossy UTF-8, or match p.to_str() for strict validation.
E0853 Paths do not support + Write a.join(b) with a path argument.
E0870 Map key must be an integer, bool, str, bytes, path or their newtype Use an id, or build a str key.
E0871 A map has two binders Write for k, v in m.
E0872 Two binders need a map For sequences/ranges write for x in v.
E0873 Maps have no index operator Write m.get(k) for option, or m.get_or(k, default).
E0874 Cannot assign to a map entry: values are immutable Write m = m.set(k, v); declare m with var.
E0875 map() takes no arguments Write let m: map<str, i64> = map().
E0900 Cannot iterate a reader directly Write for line in x.lines(). Parenthesize an if or match receiver. byte_lines() and chunks(n) also work.
E0901 Chunk size must be positive Use a size such as 1048576; a size computed at run time traps invalid chunk size.
E0902 Direct call to a result-returning platform method is discarded Match the result, or add ? outside block arguments when the enclosing result has the same error type.
E0910 Expected vec arguments Write [x] for a str argument, or [] for none: cli.process.run("printf", ["hello"])?.
E0911 Program name contains a space: no shell runs Write cli.process.run("ls", ["-l"])?; pass arguments separately.
E0930 Unsupported, malformed, duplicate-key or unreadable manifest TOML, or manifest edit failed Use version = "0.1.0", not version = 0.1; define each key once and check manifest permissions.
E0931 Unknown or missing manifest field Declare [package] with name = "app", version = "0.1.0", edition = "2026"; remove unknown fields.
E0932 Invalid package/dependency name, version, edition or capability; dependency key std is reserved Use name = "app", version = "0.1.0", edition = "2026", capabilities = ["stdout"]; dependency keys cannot be keywords or std.
E0933 Invalid dependency source specification Use { edition = "2026" } for bundled plugins, relative util = { path = "../util" }, or git with exactly one of rev, tag, or version.
E0934 Dependency/local module clash, import crossing a nested package, or local std/reflect.tn Move or rename local util.tn/util/ before declaring dependency util; remove local std/reflect.tn (even if empty); import nested packages through declared dependencies.
E0935 Dependency lock is missing or stale Run tenon fetch after changing a dependency graph.
E0936 Pinned git or edition dependency has not been fetched Run tenon fetch from the root package directory before building.
E0937 Fetched dependency hash differs from tenon.lock, or its cache/tree cannot be read Restore the readable pinned tree, or remove its checkout and run tenon fetch; do not bless local edits by changing the hash.
E0938 Dependency name differs from its manifest name Use the package's manifest name as the dependency key.
E0939 Same package name resolves to conflicting sources Make every requirer use one shared source for that package name.
E0940 Package dependency cycle Remove an edge from the dependency cycle.
E0941 Unsafe git tree/cache layout, or a path dependency escapes its checkout Use regular files in git trees, directories for cache components and a regular .tenon/.gitignore; keep path dependencies inside the checkout.
E0942 Git is unavailable or failed, or git cache storage/cleanup failed Install git, check URL/access and cache permissions, then retry tenon fetch; only https, ssh and file transports are allowed.
E0943 Pinned Git object is missing or is not a commit Pin the full 40-lowercase-hex ID of a commit, then run tenon fetch.
E0944 Malformed or unreadable dependency lock Restore a valid UTF-8 version-1 or version-2 lock, or remove it and run tenon fetch.
E0945 Dependency capability ceiling is not a subset of the declared root ceiling Remove capabilities from the dependency or declare them at the root; the span is its capabilities key, or package key if omitted.
E0946 Capability use is outside this source file's package ceiling Declare the required capability in the package manifest, or pass a derived handle.
E0947 Git dependency tag is missing or does not name a commit Depend on an existing v<x.y.z> tag of a commit, then run tenon fetch.
E0948 Git tag differs from the tagged package's [package].version Tag the commit whose version matches (v1.2.3 for 1.2.3), or depend on that tag.
E0949 Locked git tag now names a different commit A moved tag is never followed silently; to accept it, remove the package's entry from tenon.lock and run tenon fetch.
E0950 Item hashes need a sibling manifest and an importable file stem Add tenon.toml beside the source and use a module filename such as lib.tn.
E0951 Host does not provide a required item or foreign impl Add it to the host, or update the plugin; a moved impl provider can also cause this conservative error. Plugin-owned impls are not host requirements.
E0952 Host item's signature differs from the requirement Align the signature, or review the change and regenerate requirements.
E0953 Malformed or unreadable tenon.requires Regenerate it with tenon hashes <file.tn> --requires.
E0954 Unsupported requirements or hash version Regenerate requirements with this toolchain.
E0955 Invalid script plugin: missing or malformed api, api on another kind, or FFI/platform use Add api = "<host>.plugin/<major>" (for example harness.plugin/1), and move FFI or platform code into a compiled or process plugin (script plugins).
E0955–E0959 Reserved for item compatibility
E0960 Generator name is not bound to a function Bind the generator name to a function, or remove the derive declaration.
E0961 Function does not have the generator signature Use fn X(t: std.reflect.Type) -> result<str, str>.
E0962 Derive target is not a non-generic struct, enum or newtype declared in this file Declare the target in the deriving file and use a non-generic type.
E0963 Generator's module closure depends on the deriving module Remove the dependency on the deriving module.
E0964 Generator trapped; reports the trap kind and source location Fix the generator operation reported at the trap location.
E0965 Generator exceeded its fuel, heap, depth or output limit Reduce generator work, allocation, nesting or returned output.
E0966 Generator returned err; payload is shown at the derive declaration Correct its input type. For Args, each flag field must normalize to a nonempty name.
E0967 Generator output failed parsing or validation (including main/derive) Return valid source for the deriving package without main or derive.
E0968 Generated companion file is missing From the deriving module's package root, run tenon gen <deriving-module.tn>; main gen cannot bootstrap a missing generator-closure companion.
E0969 Generated companion is stale for its generator inputs From the deriving module's package root, run tenon gen <deriving-module.tn>; dependencies are verified, not regenerated.
E0970 Generated companion is unreadable/non-UTF-8, has a malformed header or edited output Restore the generated file, then run tenon gen <deriving-module.tn> from its package root.
E0971 Generated companion is an orphan with no matching derive Run tenon gen in the deriving package to remove intact orphans automatically; remove edited orphans manually.
E0972 The same generator and target are derived more than once in a module Remove the duplicate derive declaration.
E0973 Extern declaration outside an FFI package or missing package ffi authority Declare [ffi] and include ffi in that package's capabilities.
E0974 Extern type cannot map to the C ABI or declared C prototype does not match Use FFI-mappable scalar types, borrowed str/bytes arguments and supported returns; make the declaration match the C prototype.
E0975 Invalid extern declaration: public, body, placement or C symbol Use a private top-level extern "c_symbol" fn name(params) -> ret without a body and with an ASCII C identifier.
E0976 Invalid FFI manifest metadata, unknown ffi key, or the same package-relative header path declared by multiple FFI packages Use distinct package-relative header paths without .., safe system header and library names, and an optional pkg-config name. Use vendored = ["sqlite"] in place of libs or pkg_config. No free-form flags.
E0977 Root capability ceiling does not admit an FFI dependency Explicitly include ffi in the root package capabilities.
E0978 FFI system header or library could not be found Install the dependency or set TENON_FFI_PREFIX to a prefix containing its headers and libraries.
E0979 Interpreter FFI host is unavailable or failed to build Install a C compiler and resolve the helper build error; extern calls under interp require C.
E0980 Invalid plugin table: unknown field, missing field or invalid kind/index type Use [plugin] with kind = "generator" or "library" and index = "app: helpers".
E0981 Plugin DOCS.md is missing, unreadable or non-UTF-8 Provide readable UTF-8 DOCS.md beside the plugin's tenon.toml.
E0982 Plugin docs exceed 1,500 estimated tokens or lack the budget comment Declare <!-- token-budget: 1500 --> in DOCS.md and keep the whole file within 1,500 estimated tokens.
E0983 Plugin index is multiline, lacks the package-name prefix or exceeds 40 estimated tokens For package app, use one line such as index = "app: helpers" within 40 estimated tokens.
E0984 Unknown dependency edition or package is not a member of that edition Use { edition = "2026" } for bundled plugins (tenon plugins index --all); package-level edition metadata does not add dependencies.
E0985 Plugin name collides with or closely imitates a reserved name Choose a distinct name, not a keyword, builtin, platform type or edition member.
E0986 Plugin conformance failed Fix generator safety and freshness.
E0987 Plugin golden failed or backends differ Match expected.out.
E0988 Malformed platform.toml or unknown declaration field/table Use [platform] with string root, string-array headers and seeded.
E0989 Platform method names an unknown trusted native operation Use a toolchain native such as Stdout.println.
E0990 Duplicate/unsorted platform entry, invalid capability, native shape or agent policy binding Sort keyed tables, declare receivers and match native signatures. The agent policy_limits() -> str binding returns one string literal.
E0991 Unknown platform or selected dependency is not a platform plugin Select platform = "cli" or a direct dependency with [plugin] kind = "platform".
E0992 Dependency selects a platform Remove its [package] platform; only the application root selects a platform.
E0993 Invalid process plugin policy Require [process] exactly for process plugins; set a nonempty command, positive max_output/timeout_ms, fs to none or package, and net = false.
E0994 Process command is not a package file Ship a regular binary inside the package; PATH lookup requires explicit --dev.
W0995 Development process plugin uses an unhashed PATH command run, build and interp accept --dev; executable identity is not pinned. Without --dev, builds refuse PATH commands with E0994. A dev-built executable warns once at startup.
E0995 Process executable hash differs from tenon.lock Restore the pinned binary; explicitly remove the lock and fetch to trust a replacement.
E0996 Process executable pin is missing or lock is stale Run tenon fetch from the root package directory to record exec_hash for every process plugin, including path dependencies.
E0997 Invalid process-plugin call name Use a string literal naming a direct, locked process-plugin dependency. Dynamic names, unknown names and non-process dependencies are rejected.
E0998 Process-plugin caller lacks process authority The calling package's capability ceiling must include process; receiving a Process handle does not enlarge that ceiling.

Process plugins {#process-plugins}

E0993 rejects invalid process policy; E0994 rejects commands that are not package-local regular binaries unless development PATH lookup is enabled. W0995 warns that a --dev PATH command is unhashed; it is distinct from E0995, which reports a mismatch with the executable's exec_hash in tenon.lock. E0996 reports a missing pin or stale lock, E0997 rejects invalid Process.call_plugin names, and E0998 reports a caller without process authority. Fetch to record pins. Each call sends request bytes on stdin through EOF and reads response bytes from stdout through EOF; status must be zero. Request/response bytes use the codec Binary schema, and malformed response bytes are returned as an error, not a trap. Output and runtime are bounded by the plugin's max_output and timeout_ms policy. See ADR-0099.

tenon hashes <file.tn> [--all] [--requires] [--json] checks the loaded graph and prints per-item hashes or requirements. It needs a sibling manifest and an importable root file stem (E0950). tenon check-compat <tenon.requires> [host-dir] reports all missing items and signature mismatches sorted by item name (E0951/E0952); malformed requirements are E0953 and unsupported versions E0954. See item hashes for details.

Generators

The parser accepts top-level derive Generator for Target, ending at newline, ; or EOF. derive is contextual before Ident for and remains a legal name in declarations and expressions. Malformed declarations, pub derive and explicit target type arguments report E0117; E0102's existing wording is unchanged. Resolve the generator through normal file bindings; its signature is textually fn X(t: std.reflect.Type) -> result<str, str>. The target must be a non-generic struct, enum or newtype in the deriving file. Repeating the same generator/target pair is E0972.

tenon gen <file.tn> [--write | --check | --eject | --print] runs generators explicitly (--write writes committed gen/ companions, --check verifies freshness without writing, --print prints derived code). Since ADR-0318, check, build, run, interp, and test also materialize missing derives implicitly in $TENON_CACHE_DIR without writing gen/ into the workspace; when committed gen/ companions are present, they verify freshness and report E0969/E0970/E0971 on drift or corruption. Generation is offline and never changes the lockfile. It validates and formats source, then checks the complete program in memory before publishing files and removing intact orphans; failure leaves the tree untouched. Fresh companions are reused without running the generator. The pure interpreter sandbox has no capabilities, I/O or clock, with fixed limits of 50,000,000 fuel, 256 MiB charged fresh heap growth and 16 MiB returned output. E0964 reports a trap kind and generator source location; E0965 covers fuel, heap, depth and returned-output limits; E0966 shows a returned error payload at the derive declaration. E0967 covers output that does not parse or violates the generated source rules: output cannot declare main or another derive. Generated imports may use the deriving package, std.reflect, or the resolved generator's own package or packages of loaded types derived by that same generator, through existing dependencies; other external packages are E0967 (ADR-0084). E0968 means a companion is absent; E0969 means an intact header's generator, target, key or toolchain/ABI no longer matches current inputs; E0970 means the file is unreadable or non-UTF-8, the header is invalid or its post-header output hash differs; E0971 means a provenance header identifies an orphan without a matching derive, including a companion whose module was deleted. For marked generated files, header and output integrity are checked before generated source is parsed. Unmarked handwritten companions with lexical/parse failures report E0970; syntactically valid companions can first produce ordinary binding or semantic errors, but cannot pass check without valid provenance. Fresh-only reuse requires both a matching key and intact output; --check writes nothing. To repair E0968/E0969, run tenon gen <deriving-module.tn> at that module's package root first. Main-module gen cannot bootstrap a missing or stale companion in the generator's own stage closure; dependencies are verified, never regenerated. Generation locates the nearest ancestor tenon.toml, so with a package-root manifest tenon gen a/b.tn keeps identity a.b and package-relative gen/a/b/ output. Without a manifest, generation falls back to the entry's directory: recovering a nested stage companion whose imports are package-root-relative requires adding tenon.toml at the package root before running the advised command. check a/b.tn always resolves from the entry's directory (including a/gen/b/ companions), unlike manifest-rooted generation; use check main.tn with an import of a.b to verify that module in its package-root graph. Orphan inspection skips non-files, including directories named *.tn. fmt <dir> and fmt --check <dir> both skip generated companions. Checked edit candidates tolerate E0969 only and validate generator-closure code too; run tenon gen after the edit to refresh outputs. The key hashes canonical post-rewrite signature/body forms for the complete generator module closure (private/transitive helpers included), sorted by item key, plus ABI, toolchain version, generator identity, target signature hash and the reflection literal. Derive-free graphs do no generator hashing; derive-bearing graphs share one canonical-forms result across jobs and hash each provider's module closure once. Unrelated runtime bodies do not enter generator keys.

JSON wire rules

The path-dependent codec package implements these rules in Tenon (ADR-0083). codec.json.Json generates <snake>_to_json(v: T) -> str, public only for public targets, inserting _ before each interior capital. It encodes declaration-order struct fields, enums as "Empty" or {"Circle":[3]}, nested derived named types, vectors, required option keys (none is null), str-key maps in insertion order, newtypes, escaped strings, lowercase hex bytes, booleans and all integer widths as decimal numbers (including integers beyond JavaScript's exact range, without quoting). Newtypes use their representation without an extra wrapper. Encoders emit no whitespace; decoders accept space, tab, LF and CR between tokens. Unsupported types or named children without derive Json return field-path errors through E0966, as do non-str map keys. Nested options retain the existing encoder's null representation: null decodes to outer none, so some(none) does not round-trip; use an explicit enum to preserve that distinction (ADR-0085). All supported targets also get <snake>_from_json(input: bytes) -> result<T, JsonError>, with the target's visibility. Fields may arrive in any order with JSON whitespace; option keys remain required and null means none. Fused readers return codec.rt.JsonError values with byte offset/message for duplicate (including escaped-equivalent), unknown or missing keys, invalid UTF-8, trailing garbage, malformed strings, fractions/exponents, leading zeros, -0 and out-of-width integers. Enum readers reject unknown tags, incorrect payload counts, unit variants in object form and payload variants in string form. Vector/map readers validate elements directly, reject trailing commas and compare map keys after unescaping to reject duplicates. Bytes require even-length lowercase hex. Named children use their own companions, including across modules via generated imports; normal import cycles report E0221. Public targets expose an internal __codec_<snake>_from_json_at cursor reader for nested generated calls. A negative enum cursor returns a JsonError at that offset.

Binary wire rules

codec.binary.Binary generates <snake>_to_binary(v: T) -> bytes and <snake>_from_binary(input: bytes) -> result<T, BinaryError>, with the target's visibility. The eight-byte header fingerprints the reachable wire schema, including direct and nested newtype representations. It appears once per outer value. Regenerate companions. Decode legacy payloads with the original codec and re-encode them with the regenerated codec. See ADR-0188. Named children require derive Binary and use their own payload helpers without nested headers. Fields and zero-based enum tags follow declaration order. Unsigned integers use canonical LEB128, signed integers declared-width zigzag LEB128, and u8 is raw. Bool and option tags are 0/1 bytes: false/none is 0, true/some is 1, with a payload only for some. Strings/bytes have u64 LEB128 byte lengths; vectors/maps have u64 LEB128 element counts. Vector elements follow in order; map entries are key then value, in insertion order. Strings contain UTF-8; bytes are uninterpreted. Enum payloads follow the tag in positional order; newtypes use their representation directly. All lengths/counts are bounded by remaining input before narrowing, slicing or allocating. Decoders return offset/message errors for fingerprint mismatches, truncated/overlong/out-of-width values, excessive lengths, bad tags, invalid UTF-8, duplicate map keys and trailing bytes. Nested options preserve each distinct none/some layer. Binary map keys are integers, bool, str, bytes or newtypes over these (including nested newtypes); other keys return a field-path E0966 before emitting code. Path codecs are unsupported.

Codec errors

codec.rt.JsonError and codec.rt.BinaryError are structs with offset: i64 and message: str, not enums or compiler diagnostic codes. Malformed wire input returns err; callers match the result rather than expecting a decoder trap. Unsupported schemas and missing nested derives instead fail generation with E0966. The following classes group the implemented message strings; a malformed value can violate several rules, and the first detected failure wins.

JSON class Implemented messages
Object fields/map keys duplicate key, unknown field, missing field
Structure/token type expected punctuation, expected boolean, expected string, expected quote
Integer syntax/sign expected integer, expected digit, unsigned integer cannot be negative, invalid integer, invalid integer suffix, leading zero
Integer range integer out of width
String syntax raw control character, truncated escape, invalid escape, unterminated string
Unicode escapes truncated Unicode escape, invalid Unicode escape, missing low surrogate, invalid low surrogate, lone low surrogate
Hex bytes odd hex length, expected lowercase hex
Enum shape/tag unknown or non-unit variant, unknown or unit variant; wrong payload arity reports the expected token/type
Encoding/end of input invalid UTF-8, trailing garbage
Binary class Implemented messages
Header/schema truncated fingerprint, fingerprint mismatch
Truncation expected byte, expected varint, truncated varint
Varint range/canonical form varint out of width, overlong varint, varint too long
Length/count length exceeds remaining input
Tags invalid boolean tag, invalid option tag, invalid enum tag
Map keys duplicate map key
Encoding/end of input invalid UTF-8, trailing bytes

Offsets are zero-based byte cursors in the original input, sometimes at EOF or at the start of the offending value rather than the exact bad byte. In particular, the JSON entry point reports invalid input UTF-8 at 0, and hex-byte failures at the opening quote (escapes may change decoded offsets). Binary header errors are at 0; duplicate map keys report the cursor after the key. Direct runtime helpers such as hex_decode instead report offsets in their own input text.

Companions and reflection

The companion path is <package>/gen/<module-or-root-stem-path>/<T>.<X>.tn (E0968 if missing). It shares the host module identity but has its own file identity: it sees host bindings and its own imports and declarations; the host sees its declarations without importing them. Identical provider/name imports are deduplicated. Only newtype access uses the companion's host file as owner; unrelated files cannot access the representation. The deriving package retains ownership and its capability ceiling. Imports used exclusively as generators stay loaded for hashing but exclusively stage-reachable modules are excluded from the runtime program. A generator closure depending on its deriving module is E0963. See ADR-0080.

std.reflect is an embedded module selected only by that exact import path. Its source is compiled in with include_str! and named std@<version>/reflect.tn so trap locations do not depend on the checkout. Dependency key std is rejected with E0932; a local std/reflect.tn is rejected with E0934, including an empty file. A module that spells std.reflect.Type must itself import std.reflect; another module's import does not qualify it, so the unimported spelling is E0307.

Reflection is a flat schema of i64-indexed tables, not recursive nested values. Type.target and Ref.Named index Type.named. Fields, enum payload positions, newtype representations and container arguments store reference indices. References describe primitives, Vec, Option, Map, Named, or Unsupported with the type spelling. Named entries carry the local name, rewritten module identity, visibility, signature hash, shape, and derived (whether this same generator is derived for that qualified type anywhere in the loaded graph).

The builder reads the post-Rewrite AST, after rewriting the target module and before host type checking; it requires no checked type table. Named types in the target closure are emitted in deterministic declaration-order postorder, with the target last. Generic user fields and capability types become Unsupported entries containing their type spelling. The caller supplies the set of qualified names derived by this generator. Per-type signature hashes use canonical signatures. The generator key includes the rendered reflection expression literal, including newtype representations and derived flags, so changes to any observed reflection data invalidate generated output. The literal is placed in the synthetic Tenon entry source and evaluated normally by the interpreter.

Packages and manifests

The loader reads only tenon.toml beside the root source file, without searching parent directories. A missing manifest (including a nonexistent or non-directory parent) preserves single-file/module behavior. A package manifest is not added to emitted source files. Dependencies are loaded from the root manifest; each dependency's manifest is read at its declared path, and its own tenon.lock is ignored.

[package] requires string name ([a-z][a-z0-9_]*), version (three decimal components x.y.z, without leading zeros), and edition ("2026"). Optional capabilities is a string array drawn from stdin stdout stderr env fs process; duplicate capability names are E0932. Omission is distinct from []. [dependencies] maps valid non-keyword package names to { path = "../util" }, { git = "URL", rev = "40-hex" }, { git = "URL", tag = "v1.2.3" }, or { git = "URL", version = "^1.2.3" }. Git revisions are validated as 40 lowercase hexadecimal digits; branches and uppercase hashes are rejected. A tag is v plus an x.y.z version (no prerelease) and excludes rev; other forms are E0933. Git version accepts exact 1.2.3/=1.2.3 or caret ^1.2.3, with exactly git and version keys (no rev, tag, path, or edition); it selects v<x.y.z> tags by minimal version selection, locks as an exact tag without pkg, and offline accepts a locked tag admitted by the requirement. Published registry releases cannot include git version dependencies. Paths and URLs must be nonempty, with no NUL; paths must be relative and URLs cannot start with -. URL authority userinfo (https://user@host/... or user:password@host) is E0933, so credentials cannot enter locks; scp-style SSH git@host:path remains allowed. Unknown fields/tables fail. Declared path sources must be representable by this TOML subset; absolute paths and unsupported control characters are E0933. Import-free files ignore visibility.

[embed.<m>] (ADR-0282) takes a package-relative dir and optional include globs (default ["**"]; * and ? stay within one segment and skip dotfiles). Importing m loads a module generated from those files on every build: paths() -> vec<str> (sorted), get(path) -> option<bytes>, text(path) -> option<str> (none for non-UTF-8 files) and etag(path) -> option<str> (the first 16 hex digits of SHA-256). Names use the http.files.safe_path charset. tenon gen --embed <dir> m prints the module. Errors: E1154 (bad table, or a real m.tn exists), E1155 (unsafe path or symlink out of the package), E1156 (8 MiB per file, 16 MiB generated source).

The shared TOML subset accepts comments, [a.b] headers, bare keys, basic strings with \" \\ \n \t escapes, signed decimal integers (digit-separated underscores allowed), string arrays and one-line nonnested inline tables. Floats, dates, booleans, literal/multiline strings, dotted keys, nested or non-string arrays of tables, duplicate keys and other syntax produce E0930. Root [[name]] arrays of flat string tables parse (for sources.toml); manifests and locks reject them as unknown fields.

tenon fetch [dir] writes tenon.lock; builds never write it or access the network. Any package dependency requires a current lock. The lock starts with lock_version = 1, then has sorted [package.<name>] tables for every reachable package including the root. Each contains version, declared source, and sorted direct deps; the root uses source = "path:.". Recording the root's direct edges detects their removal even when the same packages remain reachable transitively. Path sources are normalized lexically relative to the root package directory (for example path:deps/util), including a dependency's own path dependencies, without resolving symlinks, and have no hash. Canonical targets identify/load sources separately from diagnostic display paths. Git package hashes use SHA-256 over regular files in bytewise relative path order, framing each file as relpath NUL decimal-length NUL bytes. Git entries record source = "git+<url>#<rev>" and hash = "sha256:<64-hex>"; executable bits and empty directories do not affect the hash. Directory dependency graphs are recomputed and compared with the lock on every build with dependencies, so dependency manifest and graph changes make it stale (E0935). The root version is informational and never invalidates a lock by itself. Dependency-free packages never require or check a lock, even an existing one.

tenon pack [dir] [-o file] writes a deterministic package pack and prints its output path and SHA-256. The pack begins with tenon-pack 1\n; its body is the bytewise-path-ordered relpath NUL decimal-length NUL bytes stream. The SHA-256 covers the framed body, not the header. There is no manifest include field. A valid manifest is required; path dependencies and package names std and tenon are refused (E1062). The default output is ./<tree-hash-hex>.tvp, regardless of the input directory; an existing output is kept and only accepted if it is byte-identical. The file set is tenon.toml, every *.tn recursively, everything under gen/ and native/, and top-level *.md, LICENSE*, COPYING*. .git/, .tenon/, .tvc/ and tenon.lock are excluded at every depth (ASCII-case-insensitive); nothing else is included. Keep the input tree unchanged during packing.

Pack paths are relative UTF-8 with / separators; absolute paths, backslashes, duplicate components and ASCII-case-insensitive path or prefix collisions are refused. Symlinks and other non-regular files in the set are refused (E1063). The framed body is limited to 64 MiB, 10,000 files and 1,024 bytes per relative path; I/O failures and cap violations are E1064. tenon pack --verify file.tvp prints sha256:<hex> of a valid pack. Readers apply the same path and cap rules and also refuse ./../empty components, NUL, a bad header, non-canonical decimal lengths, unsorted or duplicate entries, truncation and trailing bytes (E1065). Extraction stages beside the destination, requires both the body digest and the extracted tree hash to equal the pinned hash (E1066), then renames into place. tenon pack --release-check <tag> <dir> [--json] validates a materialized release directory without writing a .tvp file or reading a VC store, and prints its canonical registry index line JSON (deps, edition, hash, v, yanked). It enforces core-semver tags (v<major>.<minor>.<patch>, E1085), root UTF-8 tenon.toml parsing and tag/version agreement (E1071), reserved names and path-dependency refusal (E1062), directory/regular-file/portable-path and collision checks (E1063), I/O and pack caps (E1064), and canonical index line encoding (E1068). Graphs with a git tag dependency or index dependency write lock_version = 2: the same schema plus tag = "v1.2.3" right after source on those git entries, or pkg right after source on index+ entries. Other graphs keep version 1 byte for byte; tag or pkg in a version-1 lock, tag on a non-git entry, pkg on a non-index entry or not matching its source path, or a version-2 lock with neither a tag nor an index+ entry is E0944. Malformed lock syntax, schema, version or hashes give E0944.

tenon add github.com/acme/[email protected] edits only the current directory's tenon.toml, offline; run tenon fetch afterward. Shorthand supports github.com, gitlab.com and codeberg.org, with 1–3 nonempty path segments using ASCII letters, digits, ., _, - (no ..). @1.2.0 normalizes to @v1.2.0. Other hosts require tenon add --git URL --tag v1.2.0; --rev <40-lowercase-hex> is also supported, instead of --tag. Both forms accept --name util. Otherwise the last URL path segment, minus a trailing .git, is the name; invalid names require --name. The key must equal the dependency's [package].name, checked at fetch (E0938). Add preserves comments and surrounding formatting, appends missing dependencies, and leaves identical dependencies byte-identical. Re-adding the same URL under the same key explicitly upgrades its tag/rev in place; another source at that key or the same URL under another key is E1061. Non-inline dependency tables are unsupported. Add reparses before atomic replacement, never writes the lock and never runs git or accesses the network.

Only fetch runs git. It clones without checkout or templates into staging under the root manifest's .tenon/, checks out the pinned commit detached with core.autocrlf=false, disables hooks and submodule recursion, removes .git, hashes the tree and atomically renames it into .tenon/deps/<name>/<rev>/. An interrupted acquisition never publishes a partial tree under deps/. fetch atomically replaces .tenon/.gitignore with a regular file containing *. Concurrent fetches for the same project serialize acquisition and lockfile publication. A fetch cleans up its own staging. Interrupted invocations may leave private staging directories, which can be removed when no fetch or Git child is using them. Git runs through argv without a shell, with GIT_ALLOW_PROTOCOL=https:ssh:file and GIT_TERMINAL_PROMPT=0; repository/index/object/namespace and injected-config environment variables are removed, as is GIT_CEILING_DIRECTORIES. On acquisition, Git checks the exact pinned object's type before detached checkout with <rev>^{commit}. Git replacement objects are disabled. Missing objects, annotated tag objects, trees and blobs give E0943. Acquisition first tries git init --template= plus git fetch --depth 1 -- <url> <rev> and falls back to the full clone on any failure (servers may refuse unadvertised wants); the tree and hash are identical either way. fetch resolves an unlocked tag with git ls-remote -- <url> refs/tags/<tag> refs/tags/<tag>^{}, preferring the peeled commit of an annotated tag; a missing tag or a non-commit target is E0947. The checked-out [package].version must equal the tag's x.y.z (E0948, also checked on every read). Reads take a tag's commit only from the lock entry with the same URL and tag; a changed tag is E0936. A locked tag whose tree is present and verifies needs no git; otherwise fetch resolves it again and a different commit is E0949. Git failure stderr is a single-line excerpt of at most 163 UTF-8 bytes. ext:: and other unlisted transports are refused. SHA-256 git object-format repositories are outside v1; commits use the 40-digit SHA-1 object identity.

A present tree matching the lock hash needs no git, even during fetch. check, build, run, interp and emission verify git trees on every use, never run git or access the network, and create nothing for a missing checkout (E0936). A present checkout with a missing or source-stale lock gives E0935. Content changes or unreadable trees give E0937. Symlinks and special files in git trees give E0941; relative path dependencies of a git package must stay inside that checkout, including through further path dependencies.

For import util { item } or import util.str { item }, the first segment checks the importing package's direct dependencies before local module paths. For a dependency, the first form loads lib.tn; the second loads str.tn. Local paths resolve from that package's root. Transitive-only package imports diagnose E0220 with help to declare the dependency; they do not capture local modules with the same name. Missing-name help never suggests undeclared packages. A dependency whose name clashes with local <name>.tn or <name>/ is rejected eagerly (E0934), even when not imported. Dependency source names are logical <package>@<version>/<module>.tn paths, independent of checkout location. The same package name must resolve to one source/version (E0939), and package cycles diagnose E0940. Root module imports cannot cross a nested tenon.toml: declare that package as a dependency (E0934). Directory fmt --check walkers skip nested package roots and .tenon; invoke them at the dependency's own root to edit it.

Capability ceilings (M9.2 Step 6)

The capability names are stdin, stdout, stderr, env, fs, process, net and workspace. workspace is agent-platform only; Workspace methods are not yet provided. A root manifest with no capabilities key has no ceiling; when it declares a list, every dependency's list must be a subset (E0945). A dependency omitting the key has the empty ceiling []. E0945 names both packages and points to the dependency's capabilities key.

E0946 applies per source file: calls on capability receivers and Cli capability-field access require the owning package to declare that capability. The owner is determined by the source file, not the caller or qualified name (ADR-0069). Generic definitions keep definition-file scope: a bound call whose receiver specializes to a capability is checked at the generic definition's call span, including interface dispatch. Derived File and reader handles are exempt. Cli.args, Cli.raw_args and Cli.exit are not assigned one of these capabilities. These checks express declared intent, not security; sandboxing belongs to M10.

Examples: process exceeding a root ceiling produces E0945. A dependency calling an fs receiver method or accessing cli.stdout without that declared capability produces E0946.

E0903–E0909 and E0920–E0929 are reserved, not emitted diagnostics; E0910–E0919 belong to subprocesses (M6.5). Only E0900–E0902 are needed for M6.2.

Reader receivers are evaluated before chunk-size expressions, even if those expressions reassign a File variable. Opening a File performs no read or file mapping: optional mmap starts at its first lazy stream step, and whole reads never initiate a mapping. Streaming stdin and opened File readers flush stdout at every terminal OS refill, including multiple refills for one line or chunk; steps consuming only buffered input do not flush. On the native backend a process with closed stdin receives EBADF from stdin reads even if it opens a File. E0901 rejects provably non-positive signed literals, including nested negation and zero. Positive double negation is accepted; complex expressions retain checked arithmetic and the runtime invalid chunk size check.

E0902 covers discarded direct calls to Stdin.read_all/read_text, File.read_all/read_text, Fs.open/read/read_text/write/list, and Process.run/run_input/stream, including through capability aliases or parameters. These are all platform methods returning result<_, CliError>; none is exempt. Binding, returning, passing or matching the result counts as use; E0902 does not track whether a bound result is later handled or apply to user-function results. Calls with other errors do not also emit E0902. Reader lines/byte_lines/chunks are intentionally excluded: they return vectors (or step lazily as direct for heads), with I/O failures trapping io error and invalid UTF-8 in lines trapping invalid utf-8 (ADR-0054). File.close returns unit and is idempotent, not a fallible result. Output print/println/write/flush also return unit; failures exit as specified under Output failures. Fs.exists returns bool; environment lookups return options. Internal status/read operations are lowering machinery, not additional result-returning source methods.

Maps are insertion-ordered immutable values (ADR-0053). E0602 asks for a map annotation when key/value types cannot be inferred. E0711 rejects discarded set results. E0309 teaches looping with for k, v in m for output. --report=copies lists unproven map-set table copies. Unique direct local self-updates are amortized O(1); fields, helpers and snapshots copy O(n). Updating an inner map stored in an outer map can copy the inner table each time. Map iteration order is independent of the hash seed. Overwrites preserve a key's insertion position. Loop heads are evaluated and frozen once. Sequence keys copy into the map's region on insertion only; values retain normally. Promotion deep-copies keys and values. Hashing, probing and capacity/OOM rules are specified in ADR-0053; map allocation traps point at the receiver. get_or evaluates the receiver, key and default eagerly, left to right (even on a hit). get returns none on a miss. keys() and values() materialize insertion-ordered vectors. A read-only map loop needs no extra container alias; if its body may assign, its explicit snapshot rejects unique-set reuse.

TCP

On POSIX, Net.listen(addr) and Net.connect(addr) accept IP-literal socket addresses, including bracketed IPv6. DNS lookup is not performed. Listen port 0 asks the OS for an ephemeral port, available through Listener.port(). Grants use the existing exact-host and optional-port rules; an unspecified grant port covers ephemeral binds. Wildcard addresses require that exact wildcard grant. Denied authority returns CliError.Denied; no socket is created before admission.

Listener.timeout(ms) sets the total deadline for subsequently accepted connections, not an inactivity timeout; the default is 30000 ms. After expiry, writes may attempt one immediate nonblocking send, never wait or retry, allowing a best-effort HTTP 408 before close (ADR-0180). Conn.read(n) reads at most n bytes; empty bytes mean EOF. A nonpositive literal read size is E0901; dynamic nonpositive sizes trap invalid chunk size. Discarded socket results are E0902; ceiling violations reuse E0946. No new diagnostic codes. Socket failures use CliError.Io with fixed payloads timeout, reset, closed, address in use, refused, or limit, rather than OS-dependent messages. Accept retries aborted peers rather than ending the listener. Closed listeners can be rebound immediately on the same fixed port in both backends.

Listener and Conn are unforgeable derived handles with no capability ceiling. Copies alias the same socket. Close is idempotent; later operations through any closed alias trap listener closed or connection closed, even after a new socket is opened. Socket descriptors do not survive child exec. Socket writes cannot terminate the program with SIGPIPE. Each connection serves one HTTP request at a time in the HTTP plugin; TCP itself imposes no HTTP framing.

File and stream details

chunks(n) yields exactly n bytes until the end. words splits on ASCII whitespace; bytes methods take bytes needles. fs.write creates or truncates. A directory fails at open (IsDirectory), never at a first read. fs.read never maps a file. Messages are built by lowering, not from strerror: no such file: x, permission denied: x (EACCES, EPERM), is a directory: x, open x: os error N (also read, write, list), invalid utf-8: x (Failed). A path with a NUL byte fails with error 22; exists is false for it. list excludes . and .. and joins each name to the argument, so an entry can be opened directly. A view read before close stays valid in its iteration, including across another open; retaining it beyond that iteration copies it. Read-path buffers are freed after close/replacement and their last live iteration lease (ADR-0061). Closed File aliases stay closed even after their internal slots are reused. TRT_MMAP_MIN=<bytes> opts open streams of regular files at or above that size into live mapped views, not snapshots. External overwrites may change exposed views (even validated str); post-exposure truncation may zero them. These mutations are exceptions to value immutability and output parity with read and the interpreter (ADR-0055). Unmodified files retain parity; fs.read and copied retained values keep their read/copied bytes.

read_some(max_bytes: i64) -> result<bytes, CliError> performs a single bounded read (returning buffered or immediately available bytes up to min(max_bytes, 65536), or empty bytes at EOF; max_bytes < 1 traps invalid chunk size, literal E0901). byte_lines_max(max_bytes: i64) -> result<vec<bytes>, CliError> (also usable lazily as for line in r.byte_lines_max(n)?) caps each line excluding LF at max_bytes bytes without unbounded buffering; oversize lines return Failed("line exceeds limit") and max_bytes < 1 traps invalid chunk size. fs.stat(p) and fs.lstat(p) return result<FileStat, CliError> where FileStat { kind: str, size: i64, mtime_ms: i64 } reports "file", "dir", "symlink" or "other" (FIFOs, sockets, devices) without ever opening the entry (safe on FIFOs). Both honor Fs.restrict and Fs.no_follow (stat on a symlink under no_follow returns Denied; lstat inspects the link without following). fs.mkdir(p) creates one directory with mode 0700 inside writable Fs roots, refusing read_only() handles and escaping paths. fs.walk_pruned(p, skip_names) behaves like fs.walk(p) while skipping matching directory basenames before descending (without opening them or counting them as unreadable).

POSIX path details

path methods are checked before erasure to bytes: bytes methods do not leak onto paths. join evaluates the base before its argument; an absolute argument replaces the base byte-for-byte, and an empty base yields the argument. Otherwise it removes trailing slashes from the base and inserts one slash, including when the argument is empty. No interior separators, dots, dot-dots, NULs or non-UTF-8 bytes are normalized or rejected. Filesystem APIs own their I/O validation. parent, file_name, extension and components return byte views, preserving the source lifetime. Parent strips trailing slashes and the final component, then strips separator runs down to one slash at the root. File name is none for empty/root and final ./... Extension is none when the last dot is the first byte or absent; a. has an empty extension. Components keep a single leading root component, omit empty pieces and preserve ./.. verbatim. Display replaces maximal invalid UTF-8 subparts exactly as Rust's String::from_utf8_lossy; to_str instead returns none for invalid bytes.

Expression evaluation

tenon eval <file.tn> '<expression>' [--json] checks one ordinary UTF-8 expression (or a legacy compact expression when <file.tn> uses ~1 compact source) in the selected module. It can call the module’s private helpers. Imports and visibility follow the ordinary compiler rules. Give the expression as one shell argument. The command takes no forwarded program arguments.

tenon eval bench/fib/main.tn 'fib(10)'
# 55
tenon eval bench/fib/main.tn 'fib(10)' --json
# {"type":"i64","value":"55"}

The result must infer to i64, i32, u64, u32, u8, bool or str. Success exits 0 with a complete stdout record followed by LF. Human output uses bare decimal integers and booleans, or a quoted JSON-escaped string. JSON output is one object with type and value. Integer values are lossless decimal strings. Booleans and strings use their JSON types. Diagnostic selectors follow the usual last-selector-wins rule.

Project loading reads source, dependencies and generated companions offline. Use tenon fetch explicitly to prepare missing dependencies. Eval leaves project files, locks and generated outputs untouched. The interpreter runs the checked expression without entering the original main or building native code. Every reachable branch must be eligible. Externs, capability-bearing signatures, platform operations, I/O, exits, parallel execution and host secret-state operations are refused before execution.

The worker allows 50,000,000 fuel charges, 256 MiB of cumulative charged heap allocation, a call depth of 200,000 and a block depth of 1,000,000. The complete encoded success record, including any JSON envelope, escapes and LF, is limited to 16 MiB. These are fixed interpreter policies. Project loading and process RSS have separate costs.

Evaluation failures leave stdout empty. Source and eligibility diagnostics use the normal human or JSON diagnostic format and exit 1. Expression locations use <expression>. Interpreter traps, including fuel exhaustion and charged heap exhaustion, exit 101. In human mode they use trap: <kind> at <file>:<line>:<column>. JSON mode writes a single {"event":"trap","backend":"interp","kind":"...","at":{"file":"...","line":1,"column":1}} record on stderr.

Operational failures use human stderr or a JSON stderr record with event set to eval_error and fields code and message. The IDs eval_usage, eval_input, eval_worker, eval_depth_limit and eval_output_limit exit 2. The IDs eval_result_refused and eval_internal exit 3. Shared CLI argument decoding and stdout write failures retain their normal handling.

Code Meaning Guidance
E1050 Evaluation needs an inferred scalar value Use an expression producing i64, i32, u64, u32, u8, bool or str.
E1051 Eval reaches a forbidden operation Call a pure helper whose reachable branches use no host effects.
E1052 A return cannot leave the expression wrapper Use a value-producing branch or call a helper.

Package registry

Code Meaning Guidance
E1060 Invalid tenon add arguments or name Use <bundled-plugin>..., --path <dir> [--name N], host/[email protected], or --git URL --tag v1.2.3 / --rev <40-lowercase-hex>.
E1061 tenon add source/name collision Remove the conflicting dependency explicitly; keep one source per name and one name per git URL.
E1062 Package pack policy rejection Use a non-reserved package name and replace path dependencies with publishable sources.
E1063 Unsafe pack path, ASCII-case collision or unsupported file type Rename unsafe or colliding paths and replace symlinks or special files with regular files.
E1064 Package pack I/O failure or cap exceeded Check file permissions and output space, or reduce the pack below its size, count and path limits.
E1065 Malformed package pack framing Recreate the pack with tenon pack; do not edit .tvp files by hand.
E1066 Package pack hash does not match the pinned hash Re-download the release, or pin the hash printed by tenon pack --verify.
E1068 Malformed registry index line Restore the line registry build wrote: one LF-terminated JSON object with only deps, edition, hash, v and yanked.
E1069 Invalid registry root, config, package path or publish target Run tenon registry build <root> once (format = 1); publish to <root>/<seg>/<name> with 1-3 [a-z0-9][a-z0-9_-]* segments via file:// or a local path.
E1070 Registry version already published with different bytes Versions are create-once: bump the version, or remove the conflicting incoming pack.
E1071 Registry index line disagrees with its release Restore the release pack named by the line's hash; never edit index/ or releases/ by hand.
E1072 Yanked version is not in the registry index Yank a version listed in index/<seg>/<name>; there is no unpublish.
E1073 Registry I/O failure Check registry directory permissions and that .registry.lock, index/, releases/ and incoming/ are a regular file and directories.
E1074 Invalid registry pkg dependency or version requirement Use { pkg = "host/seg/name", version = "1.2.3" } with an exact "1.2.3" or caret "^1.2.3" version.
E1075 Invalid [[registry]] source rule Use a valid [[registry]] host/root (https://, http://, file:/// or an absolute path) in source config.
E1076 Registry version not published or yanked, or no published unyanked version satisfies the requirements Depend on a published, unyanked version listed in the registry index.
E1077 Locked registry release hash changed in the index Investigate the registry; to accept it, remove the entry from tenon.lock and fetch.
E1078 Registry release disagrees with its index line Ask the publisher to republish; the pack's tenon.toml must match the line's version and deps.
E1079 Registry download failed Check the registry root, network access and curl, then retry tenon fetch.
E1080 Selected version violates a caret bound or exact pin Align the requirers' requirements so one release satisfies all; the error names both requirer chains.
E1081 Selected registry release needs an edition this toolchain lacks Upgrade the toolchain or require an older release.
E1082 tenon fetch --update target is not an updatable root dependency Choose a root pkg or git version dependency with a caret requirement; exact pins must be changed in tenon.toml.
E1083 Invalid [sources], [[mirror]], [private] or [[auth]] source config Use allowed source config keys; auth belongs only in user sources.toml.
E1084 Registry token unavailable: bearer_env unset, empty or not a bearer token Set the configured environment variable to a valid bearer token; its value is never shown.
E1085 Release tag is not a core-semver v<major>.<minor>.<patch> tag Use tenon vc tag --release v1.2.0 [rev]; ordinary local tags are unchanged.
E1086 Release commit is not reachable from the protected tip Tag a commit on the protected history's parent chain, or land it first.
E1087 Registry token is not sent over plain http:// to a non-loopback authority Use an https:// or loopback root.

tenon registry build <dir> maintains a static file registry: tenon-registry.toml (format = 1, name; created when missing), index/<seg>/<name> (one line per version, semver ascending), releases/<hash>.tvp and the drop folder incoming/<seg>/<name>/*.tvp. Index versions compare numerically by component, using digit count then bytes, so components can be arbitrarily large without overflow. Under an OS lock on <dir>/.registry.lock it moves each incoming pack into releases/ (an already-stored duplicate goes to incoming/.done/, never deleted), appends the line read from the pack's tenon.toml, rewrites the index atomically with existing lines byte-identical, then verifies every line against its release. Lines are {"deps":{...},"edition":"2026","hash":"sha256:<hex>","v":"1.4.2","yanked":false}; deps values are {"edition":E}, {"git":U,"rev":R} or {"git":U,"tag":T}. An identical re-publish prints unchanged; reserved names std/tenon and path dependencies are E1062. tenon publish <pkgdir> --to file:///<root>/<seg>/<name> (or a local path) packs into the nearest registry root above the target and builds; a refused publish removes only its own dropped pack. Other schemes are refused: self-host by syncing the folder (rsync, aws s3 sync). tenon registry yank <dir> <seg>/<name> <version> [--undo] flips only that line's yanked under the same lock; nothing is ever deleted.

tenon registry render --vc <store> --path <ns/repo> [--yank-journal <file>] <dir> renders a local tvc store into an existing registry destination directory. Pass the explicit store path (e.g. .tenon/vc); --path has exactly two lowercase segments, each matching [a-z0-9][a-z0-9_-]*. It renders every core-semver v<x.y.z> tag and ignores other tags. Outputs reuse the append-only registry layout: existing lines stay byte-identical; a version with different bytes is E1070, and a tag/manifest version mismatch is E1071. An optional yank journal has LF-terminated <version> yank|unyank <actor> <time> records; the last record for a version wins. An unknown version is E1072, malformed input is E1069, and without a journal existing yank flags are preserved. This local file-only mechanism is not release admission, protected-history enforcement, authentication or hosting.

tenon vc tag --release v1.2.0 [rev] opts into local release preflight; without --release, local tags retain their ordinary behavior. The default revision is the worktree head. The preflight requires a v<major>.<minor>.<patch> tag and a commit reachable from the configured protected tip by following parent links (not branch or merge-base ancestry). It checks the release manifest against the tag and package name, edition and path-dependency policy, then enforces the package pack limits before creating the tag. The protected branch comes from store configuration. This is local admission only: it does not publish remotely or provide quotas or authentication.

Registry dependencies are json2 = { pkg = "pkgs.example.com/acme/json2", version = "2.1.0" }: a lowercase DNS host (optional :port) plus 1-3 [a-z0-9][a-z0-9_-]* segments and an exact 1.2.3/=1.2.3 or caret ^1.2.3 requirement (>=1.2.3,<2.0.0; ^0.2.3 is <0.3.0; ^0.0.3 is exact), with no other keys; other forms are E1074. Index lines record them as {"pkg":P,"version":V} with = stripped. tenon fetch maps the host through the user's $XDG_CONFIG_HOME/tenon/sources.toml (else $HOME/.config/tenon/sources.toml; absent means no rules), which allows [[registry]] tables with exactly host and root; root is credential-free https://, http://, file:/// or an absolute path. Plain HTTP is allowed for loopback (localhost or 127.0.0.1, any port); a non-loopback HTTP root must be in user config, and explicitly allows that exact authority (host and optional port). The root manifest (only; dependency manifests' [sources] is ignored, and offline builds read neither) may add [[sources.registry]] rules, which win over a user rule for the same host. Without a rule, github.com, gitlab.com and codeberg.org resolve pkg through git at https://<pkg>. Other hosts are discovered by probing https://<host>/tenon-registry.toml (at most once per host per fetch, capped at 64 KiB, without mirrors); a valid format = 1 selects index+https://<host>/, and HTTP 404/410 selects git at https://<pkg>. Private packages skip the probe and use git. Other probe failures are E1079, not git fallback; malformed files are E1069. Fetch reuses the locked source kind for a matching pkg unless a rule applies (rules win). Builds use the lock and never rediscover. An unknown user key/table, duplicate host or other scheme is E1075; any other root [sources] content, including auth, is E1083. [[mirror]] (root: [[sources.mirror]]) has exactly from, a credential-free https:// prefix ending /, and to, a root as above; a user HTTP to also allows its exact authority. Project HTTP roots and mirror destinations must be loopback (E1083). The longest matching from wins (root on a tie) and to replaces it in the fetch URL of index files, release packs and https:// git URLs (HTTP canonical, ssh and file URLs never mirror). Locks, messages and hash checks keep the canonical URL, so swapping mirrors leaves lock bytes unchanged and a tampering mirror fails E1066, E1077, E0937 or E0949. A mirror is authoritative: failures never fall back to the origin. [private] patterns = ["host/seg/*"] (root: [sources.private]; 1-4 segments, * is one segment) disables mirrors for pkg paths and git host/path (minus .git) that start with a pattern's segments. Bad mirror or private config, or a duplicate from in one file, is E1083. Fetch reads this config when a pkg or https:// git dependency needs the network; git then runs without any configured bearer_env variable in its environment. User [[auth]] entries specify host and bearer_env; tokens are read only when needed and attached only to HTTPS or loopback HTTP requests whose authority exactly matches the configured host. A token configured for non-loopback HTTP is refused with E1087 before reading the environment variable. Tokens are not sent to mirrors unless the mirror authority has its own auth entry. Unset, empty or invalid bearer tokens are E1084; validation is lazy and never exposes the value. The token is passed to curl in stdin config (-K -), not argv, environment or files, and any request using a token refuses redirects. Fetch reads each <root>/index/<seg>/<name> once and selects by minimal version selection (ADR-0239, ADR-0251): per name the highest minimum any reached release requires, or the oldest unyanked release above it within that requirement's bound (unpublished, or yanked and not locked, with none above: E1076); index line order is irrelevant and new releases never change it. Every selected requirer's pin and caret bound must admit the selection (E1080, naming both chains); an unknown index edition is E1081. pkg requirements of path and git packages take part. Fetch then downloads releases/<hash>.tvp into .tenon/ staging (index 4 MiB, pack 64 MiB plus header), checks the pack hash (E1066) and that its tenon.toml version and dependency table equal the line (E1078), then extracts to .tenon/deps/<name>/<hex> and recurses. HTTPS uses a fixed-argv curl -q --proto =https with a scrubbed environment (PATH, CURL_CA_BUNDLE, SSL_CERT_FILE, SSL_CERT_DIR, HTTPS_PROXY, https_proxy, ALL_PROXY, all_proxy, NO_PROXY, no_proxy only); proxy userinfo and passwords are redacted from curl and git errors before truncation. HTTP fetches use no proxies or redirects and warn once per non-loopback authority that the connection has no TLS. Download failures are E1079. Git-backed pkg resolution applies the same minimum version selection to semver v<x.y.z> tags. Its version 2 lock records canonical source = "git+https://<pkg>#<commit>", pkg, tag, version, deps and tree hash; offline builds use the locked entry. A tagged manifest version mismatch is E0948; a locked tag moved to another commit is E0949. tenon fetch --update [name] operates on . only and raises root pkg and git version caret requirements, keeping ^ and comments. For index sources it selects the newest compatible unyanked release with a known edition; for git sources, including git-backed pkg, it selects the newest compatible tag. Without a name, it updates in key order and skips exact pins. Naming an exact pin, unknown root dependency, or dependency without a pkg or git version requirement is E1082. Other requirers' bounds are checked by the following fetch; if it fails, the original manifest bytes are restored. A second update without new releases is a byte-for-byte no-op. The lock entry is lock_version = 2 with source = "index+<root><seg>/<name>", pkg = "<host>/<seg>/<name>" immediately after source, and a mandatory hash. The v2 reader also accepts git-backed pkg entries with canonical source = "git+https://<pkg>#<commit>" and a required tag = "v<x.y.z>" (ADR-0253). An entry whose pkg differs from the manifest or is missing is stale: offline and read-only operations report E0935; online tenon fetch re-resolves and rewrites it. Offline builds accept a locked version that every requirement admits (else E0935) until the next fetch re-resolves. Legacy entries without pkg parse but are stale; their first re-fetch skips the E1077 changed-hash guard once. A verified cached tree needs no index read; otherwise a locked hash that the index no longer names is E1077 and the lock stays unchanged; a locked yanked version keeps fetching and building. Builds never read sources.toml or the network.

Static builds

tenon build --static [--target T] [-o out] writes one executable (ADR-0282). Targets: x86_64-linux-musl, aarch64-linux-musl, x86_64-macos, aarch64-macos; the default is the host. Linux output is a fully static musl ELF; macOS keeps only libSystem. The compiler is $CC if set, musl-gcc for a native Linux target, else zig cc -target T from $TENON_ZIG, Tenon's managed Zig installed by install.sh, or PATH (zig 0.13 or newer). Ordinary builds are unchanged. FFI packages link static archives (pkg-config --static, -L paths or the toolchain's own) and vendored sources such as SQLite, built with the same toolchain.

Code Meaning Guidance
E1150 Unknown or unsupported static target Use one of the four targets; Windows is out of scope.
E1151 No usable C toolchain for the static target, or it failed Install musl-tools or zig 0.13+, set TENON_ZIG, or set CC to a static-capable compiler.
E1152 An FFI library has no static archive for the static toolchain Install the static library (lib<name>.a) for the target or set TENON_FFI_PREFIX; the message lists each package and archive.
E1153 --static refuses libcurl Use the CurlProcess transport (ADR-0247) or build without --static.
E1154 Invalid [embed.<module>] table, or it shadows a real module file Use a lowercase module name, a package-relative dir without .., and a nonempty include array of relative globs; rename the table or the .tn file.
E1155 An embedded path is unsafe, unreadable, or escapes the package Keep embedded files inside the package, avoid symlinks out of it, and use http.files.safe_path names (letters, digits, ., _, -, /, no dotfiles).
E1156 Embedded assets exceed the size limits Keep each file under 8 MiB and the generated module under 16 MiB; serve larger assets from disk.
E1160 Implicit derive materialization failed Fix the generator or source syntax error, or run tenon gen directly to inspect details.
E1170 Script plugin conformance or FFI restriction failed Keep script plugins pure .tn without native FFI headers and implement the required entrypoints.
E1171 Script plugin interface or API extraction failed Check the exported script plugin interface signatures and types.
E1172 Script plugin production exec_hash mismatch Re-pin the plugin hash in the lockfile or run with --dev-plugins during development.
E1174 tenon script-serve fatal runtime or framing error Verify the script plugin path, JSON frame syntax, and frame size limits.
E1175 Invalid tenon batch transaction payload Provide a valid tenon-batch-1 JSON object with an ops array.
E1176 tenon batch precondition (expect_hash) mismatch Re-read the target file hash via tenon view --with-hashes and retry.
E1177 tenon batch edit operation failed Fix the invalid operation target or body; no files were written to disk.
E1178 tenon batch typecheck failed on staged overlay Fix the reported diagnostics; no files were written to disk.
E1179 tenon batch impacted unit tests failed Fix the failing tests or pass --commit-on-test-fail to keep typechecked edits.
E1180 Invalid tenon grammar CLI invocation Pass --surface ordinary or `--actions <file
E1181 Failed to read --actions input for tenon grammar Check that the file exists and is readable UTF-8 (or pass - to read stdin).
E1182 Invalid --actions JSON schema for tenon grammar Provide a valid JSON array of ActionSpecs or an app_actions snapshot object.
E1183 Reserved grammar emission diagnostic (tenon-frontend::grammar, E1180–E1184) Reserved for future constrained-decoding grammar emission errors.
E1184 Reserved grammar emission diagnostic (tenon-frontend::grammar, E1180–E1184) Reserved for future constrained-decoding grammar emission errors.
E1185 Invalid tenon session CLI invocation or JSONL command Pass a valid package/file path and well-formed JSONL session commands (start, step, render, rewind, fork, reload, quit).
E1186 tenon session failed to load or compile target package Fix syntax or type diagnostics in the target package before starting or reloading the session.
E1187 tenon session revision or fork not found Specify a revision within 0..=max_rev or an existing fork name.
E1188 tenon session runtime trap during step or render Inspect the returned trap location and fix the trapping handler; prior checkpoints remain intact.
E1189 tenon session hot-reload replay failed Resolve the incompatible state transition after the struct layout change and retry reload.
E1200 let ... else block does not diverge End the else block with return, break, continue, or cli.exit(...) so control cannot fall through.
E1201 Invalid non-variant pattern in let ... else Use a variant pattern such as some(x), ok(v), err(e), or Enum.Variant(...).
E1230 Malformed //! script header directive Use //! edition = "2026", //! capabilities = [...], or //! deps = [...] with valid values and no duplicate keys.
E1231 //! script header directive appears after imports or declarations Move all //! directives to the top of the script before imports and items.
E1232 Unknown capability in //! capabilities Use valid capability names: stdin, stdout, stderr, env, fs, process, net, clock, traps, ffi.
E1233 Unsupported edition in //! edition Set //! edition = "2026" (the edition shipped by this toolchain).
E1234 Unknown plugin in //! deps Depend only on plugins bundled in the selected edition (tenon plugins index --all).
E1235 Script dependency requires an undeclared capability Add the required capability to //! capabilities = [...] or remove the dependency.
E1236 Standalone script cache or materialization I/O failure Ensure $TENON_CACHE_DIR (or ~/.cache/tenon) is writable and retry.
E1250 --assert-pure failed: function reaches modeled capability or extern effects Remove the capability/FFI dependency shown in the call-chain witness or drop --assert-pure for this function (ADR-0320).
E1251 --assert-total failed: function or transitive callee retains runtime checks Guard indexing/slicing/arithmetic or mark callees checkfree until zero runtime checks remain (ADR-0320).
E1255 Invalid or missing capability trace for --record-caps / --replay-caps Pass a single --record-caps or --replay-caps flag with a valid tenon-cap-trace-1 trace file (ADR-0321).
E1256 Capability trace replay diverged from recorded sequence Re-record the trace with tenon interp --record-caps after program or input changes (ADR-0321).
E1265 Release build rejected because unfinished todo(...) typed holes remain Replace every remaining todo(...) hole (list them with tenon holes --json) before tenon build --release (ADR-0323).
E1270 requires contract predicate is not bool Write a boolean expression referencing the function parameters in requires <expr> (ADR-0324).
E1271 ensures contract predicate is not bool Write a boolean expression referencing the bound return value in ensures <ident> => <expr> (ADR-0324).

Runtime traps

Uncaught traps flush stdout, print trap: <kind> at <file>:<line>:<col> on stderr, and exit 101. Sequence kinds: index out of bounds, slice out of bounds, invalid char boundary (position: base expression). Numeric kinds: integer overflow, division by zero, shift out of range, float conversion out of range (position: operator, conversion type or method name). Budget kinds: fuel exhausted, deadline exceeded.

Trap domains (ADR-0277)

Traps (cli.traps, host.traps; capability ceiling traps) contains traps inside a structured call boundary without adding exceptions to the language:

Version control

Local VC and dependency codes E1000–E1049 and remote codes E1100–E1149 are cataloged in full with recovery commands in vc-diagnostics.md. The durable format, wire protocol and CLI contract are in vc.md. tenon explain reads both registries. The table below indexes the VC, dependency-graph, and registry-render codes emitted directly by the Rust toolchain (crates/tenon, crates/tenon-compiler):

Code Meaning Fixed example / help
E1000 Store I/O, discovery, format, or VC client launch failed (vc_launch, registry_render) Run tenon vc init in an accessible directory with a tvc 1 store.
E1001 Object hash mismatch (registry_render / tvc) Preserve the store and run tenon vc fsck.
E1002 Invalid object encoding or provenance (registry_render / tvc) Use canonical object data and valid TENON_VC_BY fields.
E1004 Missing or invalid store configuration (vc_launch, registry_render) Correct duplicate, unknown, or missing config fields in .tenon/vc/config.
E1005 Invalid ref namespace, name, file kind, or target (registry_render / tvc) Use a real refs directory, a regular branch/tag file, and an existing commit.
E1009 Store lock acquisition failed (registry_render / tvc) Check store access and retry after concurrent VC operations finish.
E1015 Invalid tenon deps input or CLI arguments (crates/tenon/src/deps.rs) Run tenon deps <file.tn> [--json] with a valid entry file.
E1016 tenon deps source load or typecheck failed (crates/tenon/src/deps.rs) Fix the reported source diagnostics before requesting the dependency graph.
E1017 Checked-source re-parse inconsistency in tenon deps (crates/tenon/src/deps.rs) Report the input and tenon version --verbose output as a toolchain bug.
E1029 Unsafe or failed export/clone materialization (vc_launch, registry_render: existing destination, unavailable parent, non-UTF-8 path, or non-regular file) Choose an empty destination with an existing parent directory, UTF-8 paths, and regular files only.
E1101 Invalid VC remote CLI usage, credentials in remote URL, non-UTF-8 path, or invalid clone destination (vc_launch) Use tenon vc clone <url> [dest] [--credential FILE] [--json]; pass credentials via --credential FILE, never in the URL.