Cure v0.38.0 :: Trust, But Mechanically Verify
by Aleksei Matiushkin
There is a particular brand of philosophical serenity that comes from maintaining a dependently typed language whose standard library refuses to touch a single disk sector. Nothing can go wrong with a file you cannot open. No environment variable can betray you if you politely pretend POSIX does not exist. With 252 modules of Agda metatheory and a kernel-checked Std.* that proves what it claims, the universe is tidy, total, and entirely insulated from reality.
Unfortunately, users have a stubborn habit of wanting their programs to read files.
Worse still, when a language withholds file I/O on principle, programmers do not become ascetics—they copy-paste @extern(:file, :read_file, 1) and :erlang.element(2, ...) into their own modules, quietly turning a dependently typed language into an artisanal badarg generator. Nothing in the type signature hints that a missing file will crash the process; the failure simply arrives at runtime with the understated grace of an Erlang stack trace.
v0.38.0 retires that polite fiction. Meet Cure.Trusted—a second-level standard library for the unruly, unprovable outside world, governed by a contract that is enforced mechanically, snapshotted in Git, and audited on every CI run.
Std.* Is Proved. Trusted.* Is Trusted. The Name Says Which.
The tempting shortcut would have been to tuck @extern(:file, :read_file, 1) somewhere inside Std.* and call it pragmatism. We did not do that, because one namespace should not mean two contradictory things. The moment Std.File lives beside Std.Proof, a reader can no longer tell at a glance what the kernel checked and what a human merely swore was true after reading the OTP manual.
Instead, v0.38.0 draws a bright, unmistakable line:
Std.* kernel-checked, proof-carrying where claimed (85 modules)
Trusted.* trusted, annotated, audited — never proved ( 6 modules)
lib/trusted/ is now wired end to end: it resolves via use Trusted.* from a checkout, a bundled release, CURE_LIB, or the standalone escript; it compiles in the foundation sweep alongside Std.*; it bundles to priv/trusted/ with its .trust baselines; it has its own :trusted preload group (included in :all, never dragged in silently by selecting a Std group); and it shows up in the ExDoc standard library under an unapologetically labelled Trusted (unproved) sidebar group. All 91 modules (85+6) pass mix cure.check.docs with 458 checked doc snippets and zero allowlist entries.
What Ships in Trusted.*
Trusted.Error: The sharedFileErrorADT plusclassify/1anddescribe/1, keepingIoError(Atom)as an honest open tail—because OTP's POSIX reason atoms vary by platform and release, and pretending otherwise would be a lie the first time an unfamiliarerrnowandered in.Trusted.File: Total file I/O and filesystem inspection:read/1decodes UTF-8 strictly (Error(InvalidUtf8())rather than silently smuggling replacement characters into your data), whileread_binary/1is the explicit escape hatch for bytes that are not text.write/2andwrite_binary/2provide atomic visibility via exclusively opened, uniquely named sibling staging files, bounded collision retries, owned-descriptor writes, close-before-rename, and strictly owned failure cleanup that never clobbers pre-existing staging files, symlinks, or hard links. (Anddocs/TRUSTED.mdis equally blunt about what that is not: there is nofsyncpower-loss durability guarantee and no metadata-preservation promise.)append/2is deliberately non-atomic—a single kernel-serialised:appendwrite—because making append atomic would quietly change its cost class to full-file rewrite.remove/1answersError(NotFound())on missing paths rather than congratulating you for deleting thin air;mkdir_p/1is idempotent only after confirming an existing:eexisttarget is actually a directory; andexists?/1,directory?/1,size/1, andlist/1discriminate:filereplies before projecting nested#file_info{}records in two explicit steps.
Trusted.Env:get/1,get_checked/1,has?/1, andnames/0. Reads each variable once through a narrow typed host boundary so concurrent updates cannot tear a read; keeps unset (None()) strictly distinct from deliberately empty (Some("")); rejects empty names and names containing=or NUL with typed failures; and documents OTP-decoded text honestly rather than claiming to validate raw native bytes OTP has already converted.Trusted.Random: OS entropy viabytes/1(:crypto.strong_rand_bytes/1, returning an empty binary on negative lengths) and uniformint_in/2using rejection sampling instead of modulo bias. (Std.Genremains your seeded, reproducible PRNG for property testing;Trusted.Randomis for secrets.)Trusted.Time:monotonic_us/0,monotonic_ms/0,elapsed_us/1,elapsed_ms/1,sleep_ms/1, andsleep_us/1(rounding sub-millisecond requests up to1msinstead of silently truncating them into a no-op).Std.Timemodels calendar time;Trusted.Timegives you a monotonic clock that will not hand you a negative duration the first time NTP steps backwards.Trusted.Probe: The minimal namespace-wiring probe that keeps the Phase 0 plumbing honest.
mod Day1
use Std.Io
use Std.String
use Std.Result
use Trusted.File
fn solve_file(path: String) -> Int =
match read(path)
Ok(raw) -> Std.String.length(raw)
Error(_) -> 0
Notice what is missing: there is no unwrap. If you want to crash on a missing file, you are welcome to write that decision in your own code, where your future self can see it.
The Module We Tried to Write—and Gladly Lost
We also tried to write Trusted.Process. Cure's own compiler refused it on the spot:
-- UNINDEXED PROCESS TYPE WAS RETIRED [E093]
`Pid` belonged to Cure's unrestricted process algebra. The formal OTP surface
uses indexed process handles and distinct reference types.
The compiler was right, and we were wrong. Std.Otp.Raw is already the sealed, effect-typed, indexed concurrency boundary where sending a message to the wrong process is a type error. A Trusted.Process exposing bare Pid would have been a second, strictly worse trust boundary over the same BIFs. The governing rule is now written into docs/TRUSTED.md: a Trusted module is justified when it fills a genuine gap, never when it duplicates a better API.
The Trust Contract (T1–T4): Because Good Intentions Rot
Documentation that says "please keep your FFI wrappers total and well-documented" has a half-life of roughly two pull requests. In v0.38.0, the four rules of Cure.Trusted are enforced mechanically and fail-closed by Cure.Audit.Trusted and cure audit trust --check (wired directly into CI):
- T1 — Total public surface: No public
Trusted.*function may return a bareTupleorBinary(with one narrow structural exception: a single-call pass-through to aBinary-returning extern likeTrusted.Random.bytes/1, where aBinarygenuinely is the value and cannot fail). The audit inspects normalized Core result types, so hiding a raw carrier behind an inferred type, a chained or parameterized type alias, an imported alias, a macro-generated definition, or a same-arity overload will not sneak past it. - T2 — Declared boundary: Every reachable
@externmust carry a non-empty, lexically attached## Trust:doc block naming the exact MFA and the specific OTP contract relied on. A## Trust:marker sitting inside a string literal, an example fence, or a neighbouring function's comment is rejected—and so is an undocumented transitive non-Stdboundary hidden behind an imported wrapper, reconstructed from checked defining sources in an audit-only view. - T3 — No proof claims:
Trustedmodules may not containproofcontainers,Equivalent(...)returns (direct, aliased, nested, or higher-order), or@reducibleproof terms.Stdproves what it claims;Trusteddoes not pretend. - T4 — Reviewable axiom snapshots: Every trusted module has a deterministic, sorted
lib/trusted/<module>.trustbaseline recording normalized signature digests, attached## Trust:annotations, and host-helper contract/source digests.cure audit trust --checkis strictly read-only and fails on any missing or drifted snapshot, nested layout, or failed elaboration. You cannot grow the trust boundary without leaving a diff a human has to read.
Everything Else Since v0.37.2
A lot of quiet, unglamorous, genuinely useful engineering rode alongside Cure.Trusted—including a small v0.37.3 pit stop that never got its own fanfare:
Compiler, Namespace & Packaging Hardening
- The
Trusted.Timenamespace escape: BothStd.*andTrusted.*originally searchedPaths.all_source_dirs/0, wherelib/stdcame first.Trusted.File,Trusted.Env, andTrusted.Randomworked purely becauseStdhad no modules with those stems—untiluse Trusted.Timesilently handed backlib/std/time.cure. Each namespace now searches only its own tree, whileStd.*keeps the embeddedlib/std_deps/regexdirectory soStd.Regex.Runtimecontinues to resolve. BufferParse& single-file resolution:Cure.Compiler.BufferParse.user_module?/1now excludesTrusted.*alongsideStd.*, unblocking doc-snippet checking and editor single-buffer parsing for trusted imports.- Defining-equation dependency hygiene: Fixed dependency extraction so
vector_width.Empty()and nested defining-equation calls are no longer mistaken for external module imports. - Installed-source cache relocation & sweep isolation: Validated cached interfaces now relocate cleanly to requested installed-source paths without altering semantic hashes or allocating needlessly, and fixture-only
BundleStdlibBeamssweeps are isolated from implicit trusted sources.
Experimental Std.CodeGen (Landed in v0.37.3)
Cure now ships an AST-backed Cure-to-Cure code generation module, Std.CodeGen (lib/std/codegen.cure, :cure_std_codegen, docs/CODEGEN.md), built directly on Std.Syntax and Cure.Compiler.Printer. It brings stacked decorators and doc comments to the printer, fluent pipe-friendly builders, a ToSyntax interface, hygiene helpers, multi-file render_all, and parse-verified round-trip emission.
The CLI Argument Audit (Also v0.37.3 + @spec Cleanup)
We systematically exercised every flag and subcommand of the standalone cure escript (docs/CLI-ARGUMENT-AUDIT.md):
cure verifyandcure export-typesno longer crash in the escript trying to callMix.shell/0(an amusing oversight in a binary that does not bundle:mix);Cure.ExportTypes.parse_enum/2also now handles enum variants whose payloads are type applications.- Invalid
--format,--target,--filter, and--templateflags now fail closed withE099instead of silently falling back or—in the case of--template—cheerfully minting arbitrary atoms from user typos. cure new --appnow scaffoldslib/app.cureandlib/root_sup.curewith propermoddeclarations and validapp/supmacro syntax so a freshly generated OTP application actually compiles on the first try.- Added
@spec usage_error(String.t()) :: no_return()acrossCure.CLIand eightMix.Tasks.Cure.*tasks, retiring another Dialyzer suppression.
Try It Out
Upgrade to v0.38.0, import Trusted.File or Trusted.Time, run cure audit trust --check to watch the trust contract earn its keep, and enjoy reading a file on the BEAM without crossing your fingers around :erlang.element/2.
For the full technical inventory, see CHANGELOG.md and docs/TRUSTED.md.