Design decisions (the F-series)

An append-only log of Hale's locked design commitments — one record per major decision. Each F.N is a stable navigation tag, referenced from code comments…

Reference material, synced from the compiler repo’s spec/. The guide is the gentler path in.

An append-only log of Hale’s locked design commitments — one record per major decision. Each F.N is a stable navigation tag, referenced from code comments, spec sections, and CHANGELOG entries. New commitments append at the end with a fresh tag; records are never renumbered.

This is the decision / historical layer, distinct from the current contract in the rest of spec/. A record may describe a shipped feature, note where a design superseded an earlier one, or capture an unshipped (sketch). Ship-dates live in ../CHANGELOG.md; the normative current behavior lives in the spec files; conceptual rationale for the current surface stays in design-rationale.md.


F. Locked design commitments

Section titled “F. Locked design commitments”

The F-series are the language’s locked design commitments — each one is a stable navigation tag referenced from code comments, spec sections, and CHANGELOG entries. Section numbering is stable; new commitments append at the end with fresh F.N tags. Ship-dates for each commitment live in ../CHANGELOG.md.

F.1 Optimize for runtime perf, never sacrifice behavior

Section titled “F.1 Optimize for runtime perf, never sacrifice behavior”

When choosing between two options, the faster runtime wins — provided correctness, framework discipline, and cyclic-closure invariants hold. Compile-time perf is secondary; we accept expensive compile passes (e.g., per-projection-class monomorphization) if they produce faster runtime code.

This is an architectural directive, not a syntactic feature. It informs every implementation decision: codegen strategies prefer runtime speed, allocator design prefers runtime determinism, scheduler design prefers runtime throughput.

F.2 ProjectionClass as the “any-of-three” constraint

Section titled “F.2 ProjectionClass as the “any-of-three” constraint”

ProjectionClass is a built-in type-system primitive analogous to Go’s any. The constraint <T: ProjectionClass> requires T to be Rich, Chunked, or Recognition. No full trait system in v0; the constraint is built into the compiler.

The three classes are a perspective-resolution gradient, not three flavors of allocation strategy. Rich serves fine-grained observation (named-child resolution); chunked serves mid-grained observation (chunk-level resolution); recognition serves aggregate observation (population-level resolution — “curve,” “histogram,” “count”). The allocator choice in each case is downstream of the resolution commitment: rich’s per-child arenas make per-child observation cheap; chunked’s parent-arena sub-regions make chunk observation cheap; recognition’s recpool makes population observation cheap. See section 11 (region-based memory) for the storage consequences.

This resolves the open question of “how does a generic bound work without traits” without adding type-system surface. If later versions need richer constraints (e.g., custom-defined projection classes), the trait system can grow then.

F.3 Per-arena defrag, no whole-program GC

Section titled “F.3 Per-arena defrag, no whole-program GC”

Within a parent’s arena, dissolved-coordinatee bookkeeping slots are reclaimed via a free-list (for chunked-class loci) or periodic defrag (if churn is high). The reclamation is per-arena, bounded, and deterministic — it cannot stop the world.

Coordinatee sub-regions remain pristine arenas freed wholesale on dissolution; only the parent’s bookkeeping about coordinatees (registry slots, dispatch entries) needs free-list reclamation. This keeps the no-GC commitment intact while solving the “long-running parent with churning children leaks bookkeeping” problem from notes/open-questions.md.

F.4 drain() cascades depth-first

Section titled “F.4 drain() cascades depth-first”

Calling drain() on a locus:

  1. Recursively calls drain() on each child first (depth-first traversal).
  2. Waits for all children to finish draining.
  3. Drains itself.

There is no separate drain_cascade() syntax — drain() is always cascading.

SIGINT triggers drain() on the runtime root locus, cascading through the entire process tree. This gives clean shutdown for free: from the user’s perspective, “Ctrl-C and the program exits cleanly” is the default.

F.6 Lifecycle methods are not implicit loci

Section titled “F.6 Lifecycle methods are not implicit loci”

(See §D for full discussion.) Lifecycle methods (birth, accept, run, drain, dissolve, on_failure) run as the locus, not in their own scope. Children instantiated inside a lifecycle method attach to the enclosing locus.

F.7 accept() runs before child birth

Section titled “F.7 accept() runs before child birth”

When a child locus is instantiated inside a parent’s lifecycle method, the parent’s accept() runs before the child’s region is allocated and birth() runs. This lets accept() inspect the child’s declared params + contract surface and reject the child (panic, return error) before any resources are committed.

If accept() rejects the child, the child instantiation expression fails. The child’s region is never allocated; its birth() never runs.

If accept() accepts the child, the child’s region is allocated as a sub-region of the parent’s, and birth() runs. The instantiation expression returns the child handle.

For an unbound child instantiation, the child dissolves at the enclosing statement boundary (per §A) if it has no run, or becomes an anonymous child of the parent if it has run. The parent’s lifetime bounds the child’s.

F.8 Contract compatibility is type-checked

Section titled “F.8 Contract compatibility is type-checked”

When a parent declares consume X: T and a child declares expose X: T, the compiler verifies at compile time that the child’s expose-surface is a superset of the parent’s consume-surface, and that the types match. A mismatch (missing field, wrong type, missing trait bound) is a compile-time error.

This is the framework’s contract-graded visibility commitment expressed as a type rule. The full typing rule lives in types.md.

The check fires once per parent locus that declares any consume entry. The parent’s accept(c: ChildType) declaration tells the compiler which child to verify against. A parent that declares consume but no accept is itself a compile-time error — the consume surface has nothing to bind against.

F.9 Collapse vs. explosion as dissolution modes

Section titled “F.9 Collapse vs. explosion as dissolution modes”

(Added in v0.1.4 from 03-closure-test.)

A locus that dissolves with all closures passing collapses — clean dissolution from the parent’s perspective. A locus that dissolves with at least one closure failing at the dissolve epoch explodes — the discrepancy is surfaced to the parent.

This is the framework’s distinction between structural failure (panic; the locus crashed) and audit failure (the locus completed normally but its books didn’t balance).

Mechanically:

  1. When a closure fires (at its declared epoch boundary) and fails, the runtime flips an “exploded” flag on the locus. The locus continues running otherwise (it might still pass later epochs, but the explosion flag persists for that closure’s failure).
  2. At dissolve, if any closure-failure has been recorded, the parent’s on_failure(self, ClosureViolation { ... }) is invoked. The ClosureViolation carries: the closure name, the epoch at which it fired, the left/right values, the tolerance, and the diff.
  3. If the parent’s handler returns without re-raising (effectively absorbing), the locus is treated as collapsed — the parent has accepted the imbalance into its own books.
  4. If the parent bubbles, the failure propagates up another level.
  5. If no parent handler exists (e.g., the runtime root), the process exits non-zero with a structured violation report.

Why this distinction matters. Books at the parent’s level must balance, even if a child’s didn’t. The parent has to know about the imbalance to absorb it correctly. Exploding the failure upward — with typed information about exactly which closure broke and by how much — gives the parent’s handler the data it needs to take corrective action. Conflating audit failure with structural failure (everything is just “panic”) loses this information.

Recovery primitives interact. A parent’s on_failure for a ClosureViolation can:

The handler receives a structured ClosureViolation value with fields:

Field access uses the standard err.closure, err.locus, etc. — the parser admits these reserved-word names in member position because post-. is unambiguous.

F.10 Mode keywords as member names

Section titled “F.10 Mode keywords as member names”

(Added in v0.1.5 from 04-modes. Generalized by F.43: the mode words, like the rest of the framework vocabulary, are contextual keywords now and name anything but a locus method.)

Superseded by F.61: modes were removed, and bulk, harmonic and resolution are ordinary identifiers, a locus method’s name included.

The keywords bulk, harmonic, resolution are reserved at the lexer level (per tokens.md). They appear at top-level in the grammar as part of mode_decl. They also need to appear post-. and post-:: for member access — self.bulk() is the natural mode-invocation syntax.

The grammar’s postfix_op non-terminal admits a member_name production that accepts either an IDENTIFIER or one of the three mode keywords. This permits self.bulk() while keeping bulk as a reserved word at top-level.

Considered and rejected:

This is the same approach Rust takes with raw identifiers (though Rust uses r# prefix for any keyword; Hale permits just the mode keywords post-dot, less surface area).

F.11 self.children typing and lifecycle

Section titled “F.11 self.children typing and lifecycle”

(Added in v0.1.5 from 04-modes.)

A locus that declares accept(c: ChildType) exposes self.children as a typed iterable — specifically, [ChildType] (slice / list) of the currently-attached coordinatees.

Membership in self.children:

Iteration with for c in self.children is O(N) for chunked- class loci. The cost reflects the projection class:

Summary access. self.children.count (Int) and self.children.is_empty (Bool) are the shipped summary surface — they read the accept’d-child tracker’s live count directly (a load of __child_count) instead of a hand-rolled for c in self.children counter. Valid only inside a method of a locus that accepts a child type (typecheck-enforced); self.children itself remains a for-iterand only (not a value). Richer entity- collection sugar (filter/map/broadcast, first_where) would need a closure-value surface Hale doesn’t yet have — deferred.

v0 limitation: single-accept-type only. A locus with accept(c: ChildType) for a single ChildType has well-typed self.children. A locus that accepts multiple types (accept(c: TypeA) and accept(c: TypeB) overloads — not yet in grammar) would need self.children as a sum type ([TypeA | TypeB]) and is deferred to a future version. (2026-10-12) The one clause may name an interface: it accepts every locus satisfying it, resolved statically per concrete type (semantics.md § Locus instantiation, “An interface accept”). Its children are of several types, so its self.children keeps the summary surface (count, is_empty) and is not an iterand; the sum type is still deferred.

F.12 Bus send is the <- operator

Section titled “F.12 Bus send is the <- operator”

(Added in v0.1.6 from 05-bus; revised in v0.1.8 — operator shape replaces the original publish() builtin.)

A locus emits a message on a declared subject with the <- operator at statement position:

"fitter.action" <- action_value;

The left side names a subject declared in the locus’s bus { publish SUBJECT of type T; ... }; the right side is any expression of the declared payload type. The compiler verifies at each call site that the subject is declared and the type matches.

<- is in scope inside any locus that declares at least one matching publish entry in its bus block. Calling <- outside a locus body, or with an undeclared subject, or with a mismatched payload type, is a compile-time error.

Send is a statement, not an expression. There is no x = ("subject" <- v); the construct produces no value. This matches Erlang’s Pid ! Msg shape — single-direction, no return — and avoids the need for a value-of-send convention.

Subscribe is declarative, not an operator. A subscription is set up by the subscribe SUBJECT as HANDLER of type T clause inside the bus block, and the named handler runs as a regular fn on the locus body whenever a message arrives. There is no runtime <- subject (recv) operator; reception is attached to the locus structurally, not invoked dynamically.

The runtime emits the message on whatever transport is bound to the subject in the deployment configuration (per std::bus::Adapter / runtime bus router). Author writes typed declarations; deployment config selects transports; typechecking happens at compile time; routing happens at runtime.

Considered and rejected:

F.13 Bus subscription handler signature

Section titled “F.13 Bus subscription handler signature”

(Added in v0.1.6 from 05-bus.)

A handler named in subscribe SUBJECT as HANDLER of type T is a function defined elsewhere on the locus body, with signature:

fn HANDLER(payload: T) { ... }

It returns nothing (-> ()); to emit responses, the body calls publish(...) explicitly. This gives the handler full control over how many responses to emit, on which subjects, and under what conditions — more flexible than the return-value-as-publish pattern (which v0 doesn’t have but a future version might add for the simple single-response case).

F.14 Three-way interface: locus + parent + contract

Section titled “F.14 Three-way interface: locus + parent + contract”

(Added in v0.1.7 as a structural design direction; sharpened through conversation but not yet given dedicated syntax.)

The contract between a locus L at depth D and its parent at depth D-1 is three entities, not two:

  1. L owns its arena, its state, and its translation implementations.
  2. The parent at D-1 receives translated values through the contract; cannot see L’s internal state directly.
  3. The contract is itself first-class — declares the typed surface that crosses the D/D-1 boundary; mediates between implementation and observer.

The constraint: any function injected by L into its arena that satisfies a contract entry must return a type permitted by the contract. Translation implementations cannot route around the contract; they bound their return shapes by it.

This is the interface / implementation split, framework-aligned:

What it gives us:

For v0, the commitment is the typing rule only: a function satisfying a contract entry must return the contract’s typed surface. Multiple-implementations-per-field syntax (e.g., @projection rich fn greeting_rich() -> string annotations) is deferred to a future version when an example forces it.

For now: a locus’s params provide a default implementation for each contract field (read the field directly). User-defined fns can add additional implementations as long as they return the contract’s typed surface.

Superseded in part by F.61: modes were removed, and with them the exposed-mode pull rule (expose bulk: T; bound to mode bulk). An exposed name binds a params field or a fn member, a fn bulk included.

F.15 Predefined type names are PascalCase, not keywords

Section titled “F.15 Predefined type names are PascalCase, not keywords”

(Added in v0.1.8 — restructured to remove the lexical collision between primitive type names and stdlib namespace identifiers.)

The built-in primitive types use PascalCase spellings:

Int Uint Float Decimal String Bool Time Duration Bytes

These names are emitted by the lexer as ordinary Ident tokens. They are not reserved words. The parser recognizes them by name in type position only (after :, in -> return type, in generic args, in type declarations). In expression and namespace position, they are unreserved — so the lowercase names time::sleep, string::to_upper, etc. work as regular path expressions.

Why this matters. The original design (v0.1.0) had int, time, decimal, etc. as reserved keywords. This created an unavoidable collision: the stdlib wanted time::sleep, string::format, but time and string were keywords and could not appear in path position. Working around the collision required either a try_keyword_as_name fallback (parser hack with action-at-a-distance behavior) or renaming the stdlib namespaces (stdtime::sleep — ugly).

The PascalCase move resolves it cleanly:

This also matches the case-convention rule from spec/tokens.md (PascalCase for type names) — type names were the only place we had been violating that convention, which was itself a smell.

Considered and rejected:

Shadowing a predefined type name with a user-defined type (type Int = ...) is permitted by the grammar but produces a compiler warning. The compiler does not block shadowing (it’s sometimes useful — e.g., a project-specific Int wrapper) but flags it for readers.

F.5 Mode-projections share the locus’s arena

Section titled “F.5 Mode-projections share the locus’s arena”

Withdrawn by F.61 (2026-11-21). Locus modes were removed. The compile-time check this entry promised between the modes’ writes was never built, and it had nothing to find: a mode call is synchronous on one locus, so two modes never interleave. The entry is kept as history.

A locus may declare any subset of mode bulk, mode harmonic, mode resolution. All declared modes operate on the same underlying locus state and share the same arena. The arena cascade (parent arena ⊃ child arena) gives mode-projection sharing for free — there is no duplicate allocation, no copy, no separate per-mode region.

This was implicit in §11 (region-based memory) but worth making explicit: when you write three mode blocks, the runtime generates three implementations that all read/write the same arena. The compiler is responsible for verifying that the modes don’t conflict (e.g., resolution-mode mutating state that bulk-mode also writes is a compile-time error if the writes race).

F.16 self.k_max is a built-in computed field

Section titled “F.16 self.k_max is a built-in computed field”

Any locus that declares the framework parameters as numeric params (B, c, sigma, phi) exposes self.k_max as a built-in field of type Float. The runtime computes:

self.k_max = B / [(1 − phi) · c + phi · sigma]

from current state values — the params are mutable, so the bound floats with them. A locus that adjusts phi to formalize its interface at runtime sees k_max move correspondingly.

The typechecker recognizes k_max on every locus type as Ty::Float; the runtime errors cleanly on missing params or zero denominator rather than producing NaN or infinity.

Read shape is uniform across receivers: self.k_max inside a locus method and g.k_max on a borrowed LocusRef g lower to the same arithmetic — codegen extracts the field-load helper so non-self receivers reach the same path. Same rule applies to the F.27 synthetic draining flag.

This makes the framework’s signature equation an executable language primitive. A closure can audit against it directly:

closure within_capacity {
self.children.length ~~ 0 within self.k_max;
}

Numerically: B=100, c=10, sigma=1, phi=0.5 yields k_max ≈ 18.18, the small-k regime the ancient texts predict for mixed formality.

F.17 Strict field-access checking + method types on locus values

Section titled “F.17 Strict field-access checking + method types on locus values”

Every Locus, Type, and Perspective value has a known surface of fields and methods. The typechecker enforces it strictly: when the receiver type is statically resolvable and the named field doesn’t exist on it, that’s a compile error. Permissive only on Ty::Unknown receivers (stdlib paths, externally typed values, anything the bundle can’t see).

Methods on a locus or perspective — free fn members, mode declarations (bulk / harmonic / resolution), the implicit is_stable() -> Bool on every perspective — appear in the same field-lookup namespace as params. They resolve to Ty::Function so handle.method(args) typechecks through the standard call machinery.

This catches typo bugs that would otherwise be silent runtime no-ops (self.greting returning Ty::Unknown and sneaking through every check downstream).

Superseded in part by F.55: perspectives were removed; the rule holds for locus and type values.

F.18 Match exhaustiveness checked at typecheck

Section titled “F.18 Match exhaustiveness checked at typecheck”

A match whose arms don’t cover all scrutinee values is a compile error. v0 rules:

Permissive on Ty::Unknown scrutinees. The runtime previously fell through silently when no arm matched, so a typoed match became a hidden no-op. The check makes match safe by default.

Enum-variant patterns have since landed (m47 / m47-payloads): for a user-enum scrutinee, a match is covered iff every variant is present (unguarded) or a catch-all _ arm exists — a missing variant errors match is not exhaustive. Payload-bearing variants (Trade(Decimal, Int)) bind their fields in the arm. See crates/hale-codegen/tests/fixtures/examples/45-enum-payloads.

F.20 Structural interfaces (Go-shaped)

Section titled “F.20 Structural interfaces (Go-shaped)”
interface Sink {
fn write(s: String);
fn line(s: String);
fn newline();
}
locus StdoutSink {
params { }
fn write(s: String) { print(s); }
fn line(s: String) { println(s); }
fn newline() { println(""); }
}
fn render(sink: Sink) {
sink.line("hello");
}
fn main() {
let s = StdoutSink { };
render(s); // implicit: StdoutSink satisfies Sink
}

Commits to. A new top-level declaration form, interface Name { fn ...; fn ...; }, declaring a named set of method signatures. A locus structurally satisfies an interface iff for every method in the interface, the locus has a method with the same name, same arity, compatible param types, and a compatible return type. No impl I for L declaration — satisfaction is implicit (Go’s shape, not Rust’s). Interfaces admit no default methods at v0; the body is signature-only.

Why. Multiple friction-log entries pointed at the same gap: std::text::Sink had been a tagged-locus antipattern (one locus with dest: String branching on every method) because there was no interface mechanism; std::log::StdoutSink had to couple through the bus for the same reason. Structural interfaces let StdoutSink / StringSink / FileSink coexist as separate loci with one shared surface, eliminating the inner dispatch entirely. The Go-shape (structural, no impl declaration) is the simplest mechanism that solves the friction without adding a trait/impl-coherence design surface that v0 isn’t ready for.

The structural rule keeps the type-system surface small: no new “this locus implements that interface” relationship to track in metadata; the resolver knows about loci and interfaces independently, and the typechecker walks the satisfaction-check on demand at each call site where an interface-typed param meets a concrete arg.

Considered and rejected.

How it lowers. interface Name { fn ...; ... } parses to an InterfaceDecl and registers as TopSymbol::Interface in the bundle scope. The typechecker enforces the structural-impl rule at every call site where a fn declares an interface-typed param; mismatches produce typed diagnostics (missing method, arity, param type, return type).

CodegenTy::Interface(name) represents an interface value at the codegen layer; LLVM-level layout is a single ptr to an arena-allocated {i8* data, i8* vtable} fat-pointer struct (uniform single-pointer ABI matching LocusRef). Per (locus, interface) pair, ensure_vtable synthesizes a static [N x ptr] global __vt.<locus>.<iface> holding the locus’s methods in interface-declaration order. At call sites where a fn declares an interface-typed param, coerce_to_interface arena-allocs the fat-pointer struct and stores data = locus_ptr, vtable = __vt.<locus>.<iface>. Method calls on an interface receiver lower in lower_iface_method_call: load data + vtable, GEP to the method’s slot (decl-order index), build_indirect_call through the m80 machinery with data as the implicit self arg.

Interface values are storable in locus param fields, @form(vec) cell elements, and free-fn return positions — field-store / cell-set / return-coercion sites all insert the locus → interface coercion automatically. For free-fn returns, the m90 locus-instantiation routing extends to fire when the fn declares -> Interface(I) and the instantiated locus satisfies I, so the underlying locus lives in the program-lifetime payload arena rather than the fn subregion; emit_return_value_deep_copy deep-copies the 16-byte fat-pointer struct into the caller’s arena.

G20 follow-up: interface elements inside fixed arrays, array-repeat literals, and tuples now coerce at the construction site. The codegen routes the RHS through lower_expr_into(expr, hint) when a let-binding carries a composite ascription, propagating the element type down so per-position coerce_to_interface fires before the “mixes element types” check would reject heterogeneous LocusRefs. Ty::assignable_from extends recursively through Array, Tuple, Fallible, and Projection composites so typecheck sees the ascription as compatible with the inferred-from-leaves type.

Still deferred: locus-routing across nested return positions. A fn declared -> [Greeter; N] instantiating loci inside its return expression still aliases the fn’s stack frame — emit_return_value_deep_copy’s composite extension plus the m90 routing extension to nested-position locus instantiations need to fire together. Same gap governs tuple-of-LocusRef escape today, where the pointers in the returned tuple alias loci in the fn’s stack frame and only happen to read correctly because the freed memory hasn’t been clobbered yet.

m90 routing of nested-field children. A returning locus whose params declares fields of locus type (e.g., locus Mapper { params { a: AssetMap; b: VenueMap; c: ContractTypeMap; d: ContractMap; } }, each an @form(hashmap)) used to land its outer struct in the payload arena via m90 while leaving each child’s struct in the returning fn’s stack frame (via alloca_in_entry_with_nulled_arena). After the fn returned, the outer struct held dangling pointers to children; some happened to read back stale-but-valid stack bytes, others corrupted to garbage len() values. The pattern manifested in a downstream persist-loader’s fn load_snapshot(path: String) -> Mapper fallible(PersistError) shape — first two of four @form(hashmap) children survived; third and fourth corrupted.

A new transient instantiating_into_payload_arena: bool flag on the codegen Cx struct propagates the routing. The params-init loop of an m90-routed locus sets it before each field-value lowering; the nested lower_locus_instantiation consumes it (via mem::take) and routes its own self_ptr to the payload arena. The flag clears unconditionally after each lower_expr so a primitive-valued field (Decimal default, etc.) doesn’t leak the routing to the next iter or to the next top-level instantiation.

Coverage: crates/hale-codegen/tests/locus_fallible_return_multichild.rs covers fallible + non-fallible shapes with 3 and 4 distinct @form(hashmap) children.

Coverage: crates/hale-codegen/tests/interface_dispatch.rs, interface_return.rs, interface_in_form_vec.rs, interface_in_composites.rs, sink_polymorphism.rs.

F.21 Cascading-dimension interface (sketch)

Section titled “F.21 Cascading-dimension interface (sketch)”

A second interface form, cascading-dimension, paired with F.20 for the substrate-aware case: arena management + arbitrary n-dim cascading flow (the std::lotus::Grow family — a future arc, Lotus harness for n-dim growth). Where F.20 is “any locus matching these methods satisfies,” F.21 is “this locus participates in the cascade along these axes, with these arena-bound translation impls per axis.” Specific shape lives in F.14 (three-way interface + translation impls) once a workload forces the design.

v0 status: sketched only; not implemented. F.20 ships first because it solves the immediate friction (Sink). F.21 ships when the n-dim growth arc has its first concrete demo (a high-rate ingest or triangulator).

F.19 Per-directory seed model

Section titled “F.19 Per-directory seed model”

A directory of .hl files compiles as one seed: every top-level decl (locus, type, free fn, perspective, const) in any file in the directory is visible to every other file in the same directory, in one shared scope. hale build <dir>, hale run <dir>, and hale check <dir> accept directory targets and bundle every .hl file under them; hale build <file.hl> keeps working for one-file apps.

File order in the merged bundle is alphabetical by filename (deterministic). Resolution is order-free — the typechecker flattens all top-level decls into one bundle scope before name lookup, so a fn declared in z.hl is callable from a.hl without ceremony.

Superseded in part by F.55: perspectives were removed, so a perspective is no longer one of the seed’s top-level decls.

There is no per-file visibility (no pub, no Go-style uppercase-exported convention). Anything declared at the top level is visible to every file in the seed. Cross-seed imports — one apps/myapp reaching into another apps/lib — remain deferred (the module keyword is reserved with no semantics; see notes/open-questions.md Q18).

Why. Single-file apps grew unwieldy quickly (one app hit ~2,300 lines before this milestone landed). The single-file-app-monolith pattern was the canonical friction case. The implementation cost was small — the typechecker’s Bundle already accepted multiple programs, and hale run / hale check already handled directory targets; only hale build had a hard “single .hl file” check. Lifting it cost a CLI refactor plus a merge step. The user-visible shape mirrors Go’s per-package model.

Considered and rejected.

F.22 Capacity-tuple as N-D allocator surface

Section titled “F.22 Capacity-tuple as N-D allocator surface”

Every locus declares its storage discipline as an N-tuple of capacity slots. Slot 0 is the locus’s own Arena (the v0 1D baseline — wholesale-free at dissolve). Loci that need richer discipline declare additional slots in a capacity block:

locus Foo {
capacity {
pool entries of Int; // slot 1: cell-recycling of Int-sized
heap registry of Command; // slot 2: growable, individual free
}
params { ... }
}

Domain framing — three capacity modes, not three allocator strategies. Each slot kind is a commitment the locus makes about its own state, not a hidden implementation detail:

Slot 0 (Arena) is implicit because the simplest commitment — “everything dies with me” — is the case where the locus makes no extra promise about its state, and shouldn’t have to write it down.

Slot ABI. Each declared slot adds a field to the locus struct (__slot_<name>: ptr) initialized at instantiation and torn down at dissolve. Access is method-shaped via the locus-scoped slot handle:

let cell = self.entries.acquire(); // pool: borrow a cell
self.entries.release(cell); // pool: return cell
let p = self.registry.alloc(); // heap: alloc a Command
self.registry.free(p); // heap: free a Command

Slot names are identifiers resolved at typecheck against the current locus’s declared slots — not stringly-typed path-calls. Mirrors F.16’s “synthetic self-field” precedent: self.entries reads as a member of self, with member-typed methods rather than a free-fn taking a name parameter.

Slot lifetime (F.4 ordering). Slots are created at instantiation in declaration order, after slot 0 initializes, before the locus’s own field initializers run. Slots are destroyed in reverse declaration order at dissolve, before the slot-0 Arena itself dissolves. Matches F.4’s reverse-instantiation cascade rule for let-bound loci.

Slot 0 parent-override is the existing chunked/recognition machinery. The v0 codegen already lets a chunked-class parent allocate a child’s slot 0 (Arena) as a sub-region of its own — lower_locus_instantiation checks parent_accepts_us && parent.projection_class in {Chunked, Recognition} and routes through lotus_arena_create_subregion. F.22 formalizes that machinery as “projection class governs parent-override of slot 0.” No new behavior at v0 — F.22 names the existing capability so future slot-1..N overrides sit on a consistent vocabulary.

Slot 1..N parent-override. A parent declares capacity { pool entries of Int as_parent_for Child; } and any Child accepted by this parent gets its matching slot pointer replaced with the parent’s at accept time. Generalizes the chunked-class sub-region hand-off to all slot kinds. Runtime mechanic: every locus struct carries a synthetic __slot_borrowed_mask: i64 with one bit per slot; the bit is set when the slot was borrowed, and the dissolve pass skips destroy on borrowed slots so the parent retains ownership of the underlying allocator. Codegen-side defensive kind+elem_ty validation rejects mismatched borrows at the swap site; @form(vec) slots cannot be borrowed (rejected with a focused diag).

Restrictions (v0).

  1. Slot element type must be a value-shape, not a LocusRef. Loci have lifecycle; cell recycling (Pool.release) would orphan the locus, and individual heap free would race with the locus’s own dissolve. Loci go under self.children via accept(c: Child) per the existing membership model; slots are for types. The typechecker rejects pool X of Some and heap Y of Some with a diagnostic pointing at this rule.

  2. Slot pointers don’t cross the bus. A slot lives in the locus’s own address space; the wire format has no shape for “give me a cell of your pool back.” synthesize_serializer rejects any payload type whose field would resolve to a slot.

  3. Pool of T and Heap of T use the same T-as-cell convention. Element size and alignment come from T’s LLVM struct layout. The slot itself stores lotus_pool_t * / lotus_heap_t *; the user-visible acquire / alloc return *T-shaped pointers.

Naming note. F.22’s pool slot is distinct from the recognition projection class’s recpool (see spec/memory.md § “Recognition sub-modes (v1.x-3)” — lotus_recpool_fixed_* for fixed_cell sub-mode, lotus_recpool_slab_* for shared_slab). Both are “pools of cells” in the substrate sense, but the Recognition recpool is part of projection-class semantics (slot 0 storage strategy for recognition-classed loci), whereas F.22’s pool slot is a user-declared slot at 1..N with chunked-+-free-list backing and no projection-class entanglement. The two systems may unify in v1.x once F.22 slots 1..N stabilize.

Why. The 1D collapse forced every long-lived data structure into wholesale-free semantics. Growable types — Map, Vec, ropes — leaked per-mutation until the enclosing locus dissolved. Workarounds (fixed-cap parallel arrays as locus params) burned per-instance footprint and obscured the intent — notes/hale-friction.md dense-locus-storage-bloat is the canonical writeup. F.22 names the substrate distinction so the same locus can hold “what dies with me” (Arena) and “what I recycle / grow during my life” (Pool, Heap), in language the locus writes down rather than smuggles in via runtime convention. Operationalizes The Design’s multi-dimensional capacity principle at Hale’s substrate.

Considered and rejected.

Implementation pointers.

Pickup pointers for implementation. This session locked the spec; implementation tasks are tracked at the friction plan level (crates/hale-codegen/runtime/lotus_arena.c gets Pool + Heap primitives first; codegen surface follows).

F.23 Int → Float widening at let/arg sites

Section titled “F.23 Int → Float widening at let/arg sites”

Codegen inserts an implicit sitofp widening at the following surfaces:

Strictly one-way. Float → Int narrowing remains explicit; Decimal never participates in implicit cross-type conversion; other numeric pairs (Int↔Decimal, Float↔Decimal) still reject.

Why. The friction-log entry float-surface-gaps in notes/hale-friction.md documented the cost of forcing every Float-heavy library to carry parallel Int+Float counters and explicit conversion plumbing. std::math::{sqrt, exp, log, floor, ceil, pow} shipped alongside the widening so the libm primitives are ergonomic without per-callsite to_float() ceremony.

Considered and rejected.

F.24 Block-tail expression / if as expression

Section titled “F.24 Block-tail expression / if as expression”

A block’s last item may be an expression without a trailing ;. In expression position (let-RHS, fn-call argument, if-arm body) that trailing expression is the block’s value; in statement position (function body, loop body, statement-form if / match blocks) the tail is evaluated for side effects and discarded — pre-Phase-2b code keeps its semantics unchanged.

if cond { ... } else { ... } becomes dual-position:

else if chains carry through the value path — ElseBranch::ElseIf recurses and the innermost arm’s tail feeds the phi at the outermost merge.

Why. The friction-log entry if-needs-block-value in notes/hale-friction.md documented the canonical case: index selection, default fallbacks, and ternary-ish expressions all need a small conditional value, and the statement-only-if workaround (let mut x = i; if cond { x = j; }) is verbose and obscures intent.

The shape is form-completeness within the expression-evaluation substrate: match-arm direct expressions (MatchArmBody::Expr(Expr)) and function-body returns already produced values; if-blocks were the lone holdout. Closes the form-asymmetry — same shape as Rust, which is what the friction-log entry asked for.

Considered and rejected.

F.25 Cross-seed imports — vendored source, alias-required

Section titled “F.25 Cross-seed imports — vendored source, alias-required”

An importer references a vendored library by literal path with a required alias:

import "lib/moa" as moa;
import "../shared" as shared;

Cross-seed references read as alias::Name. The library is a directory of .hl files (per-dir seed per F.19) copied into the importer’s source tree; v1 has no package manager, no registry, no fetch, no versioning, no lockfile. The source IS the dependency.

Resolution order is three-step (first hit wins):

  1. <importer-dir>/<path>.hl — single-file lib.
  2. <importer-dir>/<path>/ — directory bundle.
  3. <workspace-root>/<path>/ — workspace fallback (workspace root = upward hale.toml / Cargo.toml search).

Library decls are auto-mangled at parse-time with prefix __lib_<lib_id>_<file_stem>_<name> (where <lib_id> is a stable, path-derived identifier for the lib — workspace-root- relative when known, file-name fallback otherwise) and registered into a per-build path-rename table parallel to the static STDLIB_PATH_RENAMES table. The user never writes the mangled form; alias::Name resolves through the table at codegen. Two apps importing the same lib produce the same <lib_id> regardless of which aliases they chose, so DTO seeds on a bus have symbol-identical types across consumers.

Qualified TypeExpr rewriting. The codegen-side path-rename table resolves alias::Name references at call-position lowering — but expression-position resolution runs AFTER typecheck. Type-position uses of alias::Name (struct fields, fn signatures, locus params, @form(hashmap) cell types) need the rewrite to happen BEFORE the typechecker sees them, or the “unknown type” check fires against the un-rewritten qualified path. A pre-typecheck pass in hale_codegen::mangle::apply_qualified_path_renames walks every TypeExpr in the entry program and collapses multi-segment paths whose first segment matches an import alias to a single-segment path carrying the mangled name. Lets the typechecker resolve qualified-type cell types the same way it resolves bare ones.

Codegen-side, the single-segment branch of type_expr_to_codegen_ty consults pending_type_names as well as user_types so an apply_qualified_path_renames- collapsed name forward-refs cleanly when the imported lib’s TypeDecl lands later in the merged items stream than the entry-program decl that references it. Mirrors the multi-segment branch’s pre-existing forward-ref fallback.

Why. F.19 (per-directory seed model) fixed the single-file-app-monolith friction at the intra-seed layer. Cross-seed sharing remained the next gap: cross-app helper patterns (tagged-accumulator, directory walks, JSON glue) had no library home, so the std seed absorbed friction that should have lived in user libraries.

F.25 opens user libraries as a first-class shape: user helpers can graduate from copy-paste / std-seed-bloat to a vendored shared lib.

Vendor-the-source as the v1 commitment. A real package manager (registry + fetch + semver + lockfile) is several months of work. The friction this milestone unblocks is “can libraries exist at all” — not “can we deduplicate dependencies across projects.” Vendoring is how C, early Go, and many other languages bootstrapped library ecosystems before package managers existed. Hale’s file-based dir-seed model is well-suited to it. When a real workload surfaces friction that vendoring causes (version skew, duplicate sources on disk, manual update toil), that’s the signal to design the package manager — not before.

Forcing-function alias. Bare import "<path>"; is a parse error. The user names the namespace at the import site so a downstream reader doesn’t reconstruct it from the path. Mirrors v1.x-3’s no-default-sub-mode rule and v1.x-FORM-2’s two-channel rule — same discipline applied at a different layer.

Considered and rejected.

Implementation entry points. See spec/projects.md § “Implementation entry points” for the file paths and primary functions.

F.27 Inline closure violation

Section titled “F.27 Inline closure violation”

A locus method body can escalate a value error into a structural failure by declaring an assertion-less epoch inline closure and firing it with the new violate statement:

locus DbConnection {
params {
host: String = "127.0.0.1";
port: Int = 5432;
conn_fd: Int = -1;
last_error: String = "";
}
bus { subscribe ExecuteQuery as on_query; publish QueryResult; }
closure fatal_io { captures: last_error; epoch inline; }
birth() {
self.conn_fd = std::io::tcp::connect(self.host, self.port)
or self.handle_io(DbError { kind: "connect_failed", detail: err.kind });
}
dissolve() { if self.conn_fd >= 0 { std::io::tcp::close_fd(self.conn_fd); } }
fn handle_io(e: DbError) -> Row {
self.last_error = e.detail;
if e.kind == "send_failed" || e.kind == "recv_empty" {
violate fatal_io;
}
return Row { data: "" };
}
fn on_query(q: Query) {
let r = send_query(self.conn_fd, q) or self.handle_io(err);
if !self.draining { QueryResult <- r; }
}
}

The pattern let r = expr or self.handle_io(err); — paired with handle_io returning the success type on recoverable cases and calling violate on fatal ones — is the error-check function: one named method on the locus owns both the audit-log update (self.last_error = ...) and the recovery / escalation choice. Channels stay separated (per the two-channel rule, F.22-era); the conversion from value error to structural failure happens at exactly one named site.

The parent’s on_failure(c: DbConnection, err: ClosureViolation) body reads the audit-log state through the child handle — c.last_error, c.conn_fd, etc. — not through the ClosureViolation payload. Because violate is divergent, the child’s locus state is frozen at the violate moment (the remainder of the method body doesn’t execute), so the child handle’s field reads return exactly the state at the escalation point. The captures: clause is a declarative audit hint pointing the reader at the structurally relevant state; the portable access path is via the child handle.

Commits to.

  1. A new closure shape. closure declarations may omit the assertion when an epoch inline clause is present. The body then consists only of optional clauses (captures:, persists_through(...), resets_on(...), epoch inline). Assertion-bearing closures cannot pair with epoch inline.

  2. captures: clause. A captures: f1, f2, ... ; clause names locus state fields that are structurally relevant at the violate point — a declarative audit-log hint. Field names must reference declared locus params. The parent’s on_failure(c, err) body reads each captured field through the child handle (c.f1, c.f2) — because violate is divergent, the child’s state is frozen at the violate moment, so the handle reads return the snapshot the captures clause names. The ClosureViolation value itself carries err.locus + err.closure; the captured fields are read through the frozen child handle. The child-handle path is the access pattern for captured state.

  3. epoch inline. A new variant alongside tick, duration(d), dissolve, birth, and explicit. Inline closures do not fire automatically at any epoch boundary; they fire only via violate <name>;.

  4. violate statement. Statement-level, recovery-primitive- shaped. Form: violate IDENT; or violate IDENT with EXPR;. Divergent (typechecker treats as Never, same as fail in fallible fns and bubble in on_failure). Resolves the identifier to a closure declared on the enclosing locus; the target closure must be epoch inline.

  5. Inline fires initiate drain. Auto-epoch closures keep F.9’s behavior: flip the exploded flag, locus keeps running, parent’s on_failure fires at natural dissolve. Inline closures do that and request drain — at the next cooperative yield point the runtime transitions the locus to the draining state, cascading through children depth-first as usual. The exploded flag is set identically; the only difference from auto-epoch is that the locus stops accepting new work instead of completing its current epoch.

  6. self.draining reads as a synthetic Bool. Locus method bodies may read self.draining to check whether the locus has entered the winding-down state. This lets the canonical pattern above suppress a downstream send after escalation:

    if !self.draining { QueryResult <- r; }

Rejection contexts. violate is rejected:

Allowed everywhere else that has self: named locus method bodies, bus-handler methods (subscribe X as foo → fn foo), run(), lifecycle methods (birth(), dissolve(), drain()), mode-method bodies. The same body shape gets the same primitive.

Why. The two-channel rule (locus methods cannot declare fallible(E)) keeps recovery paths legible: parents handle structural failures (on_failure), free fns and @form-synthesized methods handle value errors (fallible). But the bridge between them — converting a caught value error into a structural failure inside a locus method — had no clean primitive. The workaround was a should_exit: Bool flag plus a while !should_exit { yield; } loop in run() plus a separate last_error field for diagnostics: three pieces of state doing what should be one named call.

violate collapses the three-piece workaround to one line by naming the closure being violated. The closure name is the audit-log handle (ClosureViolation.closure) the parent receives, and captures: makes the diagnostic payload declarative instead of folded into a free-form Error payload.

Considered and rejected.

Implementation entry points.

F.28 BytesBuilder is a locus, not a primitive type

Section titled “F.28 BytesBuilder is a locus, not a primitive type”

Commitment. The bytes-accumulator surface (std::bytes::builder_*) is no longer a family of free functions over an opaque Bytes handle. It’s now a stdlib locus, std::bytes::BytesBuilder, with method dispatch (b.append, b.len, b.snapshot, b.shift_front, b.clear, b.finish) and lifecycle (birth allocates the underlying malloc-backed buffer; dissolve frees it at scope exit). The prior free-fn surface is removed; the C primitives stay as the locus’s method-body externs.

The bug being closed. The builder header (lotus_str_builder_t { cap, len, buf* } — a separately- malloc’d buffer behind an internal pointer) and a Bytes blob ([i64 len][u8 data] — single contiguous allocation) are genuinely incompatible ABIs that cannot be unified without giving up stable handles (the body has to be relocatable; the Bytes blob layout forbids that). The original surface returned a builder as Bytes — the only Hale type wide enough to carry a pointer — under the convention “you should treat it as opaque.” When that convention slipped (a builder passed to std::bytes::at(b, i) reading the cap field as the length), the runtime silently misread and ran off the heap. A downstream workload hit this with RSS exploding 2.6 GB in 5 seconds. The mechanical fix is to make builder and Bytes statically distinct.

Why a locus, not a parallel primitive type. Hale’s foundational axiom says types are pure data (no flow); loci are flow with invariants. The bytes builder is textbook flow — allocate → append (auto-grow) → snapshot → free — with invariants (cap >= len, buf is a valid malloc region, len is the count of valid bytes). It belongs on a locus. Introducing it as a primitive type would have closed the typecheck footgun, but would also have added a magic non-locus thing with lifecycle to the language — a special case that contradicts I4 (every named structural thing is in exactly one locus tower). The locus shape is the principled answer; the type-discrimination win is a free byproduct.

What the user sees.

fn pump_frames(sock: Int) {
let buf = std::bytes::BytesBuilder { initial_cap: 4096 };
loop {
let n = std::io::tcp::recv_into(sock, buf, 4096);
if n <= 0 { break; }
// ... peel via buf.len() / buf.shift_front(consumed)
}
// buf dissolves here → malloc freed, no explicit cleanup
}

The typechecker rejects std::bytes::at(buf, 0) inside that loop — at takes Bytes, buf is a __StdBytesBytesBuilder locus reference. Same for len(buf), slice(buf, ...), anywhere a Bytes is expected. The discipline is mechanical.

Discarded alternatives.

Failure routing (F.27). append() routes realloc-NULL failure through violate alloc_failed. The locus declares closure alloc_failed { captures: initial_cap; epoch inline; }; append checks the C primitive’s int64_t status return (1=ok, 0=fail), and routes through violate on 0. Owners of the BytesBuilder bind an on_failure policy to handle the violation (restart / drain / bubble); an unhandled violation bubbles past main and exits the process non-zero with the captured payload on stderr.

F.27 v2: birth_check synthesis hook. A declarative invariant check that runs AFTER the locus’s birth() body completes (and after birth-epoch closures fire), at the well-defined point where every field has its declared post-birth value:

locus L {
params { x: Int = 0; }
closure invariant_broken { captures: x; epoch inline; }
birth() { /* set up state */ }
birth_check { self.x < 0 } -> violate invariant_broken;
}

If the boolean cond evaluates to true, the named closure violates with the locus’s fully-constructed state. Multiple birth_check clauses on a locus evaluate in declaration order; the first to fire short-circuits the rest (subsequent checks sit in unreachable basic blocks after the violate’s terminator).

Why a synthesis hook and not just violate inside birth(): the v1 form lifted the codegen restriction on violate in lifecycle bodies, but violate alloc_failed fired mid-birth leaves the locus PARTIALLY CONSTRUCTED — some fields set, others at defaults — when the on_failure handler reads the closure’s captures. For BytesBuilder that worked by luck (only initial_cap is captured, and it’s set before birth runs), but for any locus with multi-step birth and field inter-dependencies the partial-construction case produces undefined intermediate state in the violation payload. The birth_check form sidesteps this: the body runs to completion, the check fires at a well-defined point, the violation’s captures read coherent state.

Codegen. emit_birth_check (see crates/hale-codegen/src/codegen.rs) emits the cond + violate routing INLINE at the instantiation site — NOT through the standard Stmt::Violate codegen. Standard violate’s divergent return targets the CALLER’s LLVM function (e.g. Parent.run), which is wrong for birth_check: an absorbed violation should let the caller keep running after the failing instantiation expression, not return from the caller’s whole fn body. The inline emission writes __drain_requested = 1, allocates the ClosureViolation, branches on parent_on_failure (indirect-call vs dprintf+exit), then unconditionally branches to a continuation block so the caller proceeds normally.

BytesBuilder migrated. std::bytes::BytesBuilder now uses the birth_check form for the null-handle case (birth_check { self.handle == 0 } -> violate alloc_failed), replacing the earlier inline if self.handle == 0 { violate alloc_failed; } in birth body.

F.27 extension (superseded by F.27 v2): violate in lifecycle bodies. The codegen restriction on violate was lifted for lifecycle blocks (birth / drain / dissolve / accept / run); they now participate in the same divergent-return + parent-on_failure routing as regular method bodies. The original spec rationale (“only fn-bodies can violate”) was an implementation simplification, not a structural requirement — lifecycle bodies are void-returning fn contexts at the codegen level, and the violate machinery’s build_return(None) path handles them identically once current_user_fn_ret is set to Some(None) at lifecycle entry. Both forms remain supported in v1.x; new locus designs should prefer the birth_check synthesis hook for construction-time invariants (the partial- construction hazard described above). The accepted-child dissolve trade-off (parent_accepts_us skips dissolve bodies entirely) is unchanged; dissolve violate is observable only along the F.29 locus-field cascade path where emit_locus_field_dissolves does fire the inner’s dissolve.

Caveats at v1.

Implementation entry points.

Phase-2 (1): zero-copy view(). Added b.view() -> Bytes returning a non-owning Bytes pointer that aliases the builder’s buffer. Pond/websocket’s recv loop had a residual leak after Phase 1 — rx_buf.snapshot() per peel attempt to materialize a Bytes value for parse_frame to read via std::bytes::at / len. view() is the same value without the allocation.

Memory layout (changed). Prior layout was {cap, len, buf*} with the data area separately malloc’d. Reshaped to {cap, buf} where buf points at the data area of a single [i64 len][u8 data[cap]] malloc’d region — the 8-byte length prefix lives inline immediately before the data. view() returns buf - 8, which IS a valid Bytes pointer: lotus_bytes_len / lotus_bytes_at / lotus_bytes_data all just work. Every mutation (append, shift_front, clear, finish) updates the inline prefix to match. The cost is one extra pointer dereference per len access (negligible at our scale); the win is true zero-copy view + zero-allocation peel.

Lifetime contract. A view() Bytes is valid until the next mutation on the source builder. The aliasing property means a captured view sees stale len if the builder grew / shrank after capture, and a view captured after a mutation sees the new state. At v1 (no borrow checker) this is documented-and-trusted — same shape as the rest of Hale’s lifetime story. The canonical pattern is “view immediately, read immediately, don’t store across mutations.” The snapshot() path remains for cases that need a stable Bytes (consumer holds across producer mutations).

This obviates Phase-2 ask (3a) — proposed b.at(i) / b.slice(lo, hi) methods on BytesBuilder. With view(), the existing std::bytes::at(b.view(), i) / std::bytes::slice(b.view(), lo, hi) work directly, no new method dispatch needed. The BytesBuilder surface stays minimal.

Tests: crates/hale-codegen/tests/bytes_builder_view.rs — 5 cases covering current-contents read, aliasing across appends, slice composition, shift_front reflection, and clear-then-view.

F.29 Locus-typed param fields with lifecycle cascade

Section titled “F.29 Locus-typed param fields with lifecycle cascade”

Commitment. A locus’s params block may declare a field whose type is another locus (user-defined or stdlib). Construction defaults via a locus literal:

locus WsClient {
params {
sock: Int = -1;
rx_buf: std::bytes::BytesBuilder
= std::bytes::BytesBuilder { initial_cap: 4096 };
last_msg: std::bytes::BytesBuilder
= std::bytes::BytesBuilder { initial_cap: 4096 };
}
fn run() {
// self.rx_buf is the held builder; method dispatch
// works through self.<field>.<method>(...) — same
// shape as any other locus field.
}
}

The owning locus’s lifecycle cascades into the child:

Motivation. A downstream Phase-2 ask — “in-place storage for locus Bytes/String fields” — is what this commitment closes. Producer locus owns the storage (a BytesBuilder field, in practice); consumer reads zero-copy via the contract using b.view() (F.28 Phase-2 (1)); each frame the buffer is reused in place via b.clear() + b.append(...). No per-message allocation against g_bus_payload_arena. The “vertical contract / DMA” idiom Hale’s F.14 design was reaching for.

Equally important: this works for non-stdlib loci too. Any user-defined service locus can compose held sub-loci via param fields with cascade — Cache, RetryPolicy, RateLimiter, whatever the application carves up. The locus axiom (everything named and structural is a locus) gets a working composition story.

Discarded alternatives.

Caveats at v1.

Implementation entry points.

Tests: crates/hale-codegen/tests/locus_field_cascade.rs — 3 cases: method dispatch through a field-held BytesBuilder, ordering of the cascade (outer body → inner cascade → outer arena_destroy), and a 100k-iteration construct-destroy loop exercising the cascade path under load.

Per-child reclamation of accept’d children

Section titled “Per-child reclamation of accept’d children”

Problem. An accept’d child lives in (a subregion of) its parent’s arena and, at v1, was reclaimed only when the parent dissolved. For a daemon — a server whose top locus loops forever and never dissolves — that means never: a parent that accepts one child per connection accumulates one arena per connection for the life of the process (measured ~8.7 KB/child, linear; 6000 connections → ~58 MB and climbing). The leak is in the primary server shape, not a corner.

Why not a manual free. The obvious fix — a free(child) / dissolve self the developer calls when a connection closes — is the C trap: imperative lifetime management bolted onto a region-and-lifecycle model, easy to forget (releak) or double-call (use-after-free). Hale’s whole memory story is that lifetime is structural. So the fix must invoke the existing declarative teardown early, never bypass it.

The model: a child is bound by its parent, but ends with its own flow. A child’s lifetime is nested in the parent’s (it cannot outlive the parent — the parent-dissolve cascade is the upper-bound backstop), but it should be reclaimed when its work ends, not deferred to the parent. Two shapes, distinguished by the parent’s declaration, never guessed:

The verbs.

Safety. Reclaim runs on the child’s own pool worker after run() returns, while its arena is valid — the parent isn’t dissolving. emit_locus_arena_destroy is idempotent (NULLs __arena), so a child reclaimed early and then reached again by the parent’s eventual dissolve is torn down exactly once. A coro parked at teardown time (shutdown, a future parent-drain) is cancelled cooperatively — the wakeable park: a wake eventfd unblocks the pool worker, a cancel flag makes the parked recv/accept return its EOF sentinel, and run() unwinds its own stack. The runtime never seizes a suspended frame.

Known tails (v1). Completion detected inside a handler body (vs run()); slot removal from an iterating parent’s children buffer; the full latch gating drain+dissolve (only the arena free is latched); a typecheck gate confining terminate / release to locus method bodies; and graceful-shutdown reclaim of residents.

Tests: terminate_reclaims_child, release_reclaims_flow, async_io_shutdown_parked.

F.30 BytesView — non-owning view as a distinct type

Section titled “F.30 BytesView — non-owning view as a distinct type”

The Phase-2 view() / Phase-3 text_view() machinery hands back a non-owning pointer that’s layout-compatible with Bytes. The ergonomic win is real (std::bytes::at, len, slice all just work) but the type system can’t distinguish a fresh arena-owned Bytes blob from a non-owning view whose validity ends at the next mutation on the source builder. Fungible call sites, divergent lifetimes; a footgun symmetric to the pre-F.28 “passing a builder where Bytes was expected” hazard the locus lift closed.

Design move: introduce BytesView as a distinct type. It aliases Bytes at runtime (same [i64 len][u8 data] pointer shape, zero allocation) but carries different intent at typecheck:

What this catches:

What this DOES NOT catch (was deferred to F.30b — now closed):

F.30b BytesView / StringView mutation-while-live runtime guard

Section titled “F.30b BytesView / StringView mutation-while-live runtime guard”

The remaining hazard after F.30: The distinct-type work in F.30 catches the fungibility hazard (stored a view where Bytes was expected). It does NOT catch the timing hazard:

let v = frag_buf.text_view();
frag_buf.append(more_bytes); // ← invalidates v silently
let txt: String = v; // ← reads stale bytes; no diagnostic

The view aliases the builder’s buffer; the second append may realloc the buffer or shift its contents, leaving the view observably-broken with no compile-time signal. The Hale v1 language has no borrow checker (compile-time lifetime tracking) to close this at typecheck.

Design move: runtime epoch guard.

Failure routing. Stale-view detection is a runtime panic, not a closure violation. Closures are for recoverable conditions the owning locus can handle (e.g. alloc fail → restart / drain / bubble). A stale view is a programmer error — the code that held the view past a mutation is structurally wrong, no restructuring at the locus level can recover it. Hard panic with a clear diagnostic mirrors how out-of-bounds array reads behave in the rest of the language.

What this catches:

What this still doesn’t catch:

Codegen impact. BytesView and StringView are still distinct types at typecheck (unchanged from F.30). Their LLVM representation is a {ptr, i64} struct passed and returned by value — SysV AMD64’s “two INTEGER eightbytes ≤ 16 bytes” rule puts the view in {rax, rdx} on return and two arg registers on entry, so the hot path moves through SSA without memory traffic. The unpack-and-check helpers are mechanically inserted at every view-accepting consumer site (the view_coerces_to consultation, the len() builtin, the println arms). Other consumers (struct field storage of BytesView / StringView, function arguments declared as view types) are pass-through — the view flows along until it hits a read-coercion site, where the unpack fires.

Allocator. No arena allocation per view() / text_view() call. The 16-byte by-value struct materializes in two SSA registers; the caller’s storage slot (if any) is a 16-byte struct alloca that the existing arena routing already covers. Read-time cost is a one-load epoch check plus a recompute of buf - 8 (Bytes) or buf (Str) from the builder pointer.

F.31 Deployment seams live at main; intrinsic shapes live on the locus

Section titled “F.31 Deployment seams live at main; intrinsic shapes live on the locus”

Hale’s substrate-discipline annotations sort into two families. The split is load-bearing and was implicit before this commitment; F.31 names it.

Intrinsic shapes describe what a locus is. They live on the locus declaration, survive across deployments, and compose through nesting (a child locus inside a parent has its own intrinsic shape independent of where the parent runs):

Deployment seams describe how a locus is wired into a specific binary. They live in main-only blocks, vary across deployments of the same library, and do not nest (only top- level main locus declarations carry deployment blocks; nested loci inherit their deployment context from the containing tower position):

The diagnostic test. When deciding whether a new substrate annotation belongs on the locus or in main, ask: can a library author commit to this without knowing the binary’s deployment context? If yes, it’s intrinsic — a property of the locus’s identity. If no, it’s a deployment seam — a property the binary picks.

A useful corollary: anything that takes “main-only” cleanly is a deployment seam; anything that struggles with the main-only restriction is intrinsic. The proposed @form(scheduler) annotation flunks this test — @form(...) annotations are expected to work on any locus declaration, so a main-only @form(scheduler) would be a form lying about its category. The correct shape is a parallel deployment block, not a form annotation.

F.31a Placement-at-main + M:N cooperative pools

Section titled “F.31a Placement-at-main + M:N cooperative pools”

Schedule is a deployment concern: a std::http::Server should not bake “cooperative” into its locus identity because a consumer binary may want it pinned. F.31 makes this explicit; the v1 surface follows from it.

Surface. Schedule annotations are removed from locus_annotation. A new placement { } block on main locus carries per-locus placement specifications:

main locus App {
params {
gateway_a: Gateway = Gateway { venue: "venue-a" };
gateway_b: Gateway = Gateway { venue: "venue-b" };
metrics: MetricsServer = MetricsServer { port: 9100 };
ui: Renderer = Renderer { };
}
placement {
gateway_a: pinned(core = 1);
gateway_b: pinned(core = 2);
metrics: cooperative(pool = io);
ui: cooperative(pool = render);
// unspecified main-locus params → cooperative(pool = main)
}
bindings {
// ... per-topic transport bindings, unchanged
}
}

Keying rule. Placement entries key on main-locus params field names (snake_case), not on locus type names. This lets two siblings of the same locus type take different placements — exactly the parallelism case that prompted the change (per-venue gateways on distinct cores).

Pool inference rule. The set of cooperative pools is inferred from cooperative(pool = X) references in the placement block. The compiler spawns one OS worker thread per inferred pool name (plus the existing main thread, which is always pool main). No threads { } declaration block at v1 — when per-pool attributes (priority, affinity, realtime hint) become useful, the block lands then as a typed extension.

Nested-instantiation rule. Placement entries apply only to top-level main locus params fields. Loci instantiated nested in another locus’s body (in birth / run / lifecycle methods, or as let-bound children) inherit the parent’s pool. The single-threaded-method invariant (below) makes this inheritance a hard rule, not a default.

Single-threaded-method invariant. A locus’s methods may be invoked only on the OS thread that owns its placement’s pool. Cross-pool method calls and lateral field accesses go through the bus’s existing copy-and-condvar dispatch machinery, which already crosses thread boundaries safely. The typechecker walks the static call graph from each top-level placement entry, propagates pool ownership through method receivers, and rejects calls that cross pools without going through the bus. This is the substrate enforcement that makes M:N safe — without it, multi-pool deployments would silently race on locus arenas (which are unsynchronized bump allocators).

M:N cooperative pools. Each cooperative pool is one OS worker thread running its own lotus_bus_queue_drain loop against its own per-pool queue. Cross-pool bus dispatch: publisher enqueues on the subscriber’s pool’s queue via the existing inline-payload-copy machinery (m28b stage 1); the broadcast wakes the subscriber pool’s drain thread. The condvar+memcpy substrate that handles cooperative→pinned today extends naturally to cooperative→cooperative across pools.

Bimodality revisited. The pre-F.31 bimodality argument (“cooperative or pinned, no third class”) lived at the locus declaration site. Under F.31 it moves to the placement entry site — a placement is still bimodal (pinned or cooperative (pool = X)), but the locus itself doesn’t carry that choice. This is a strict generalization: pre-F.31 deployments expose exactly the prior shape (one main thread + per-pinned-locus threads) by writing the same placement { } entries that were previously : schedule annotations.

Considered and rejected.

Friction items this closes.

Resolved.

Adapter placement interaction. Adapter loci instantiated inline in a bindings { Topic: AdapterLocus { ... }; } entry are NOT main-locus params fields, so they receive no placement { } entry. Their run() recv-loops need a dedicated thread by construction; the substrate places them pinned-equivalent implicitly (same m90 routing + pthread spawn that pre-F.31 fired via the adapter’s : schedule pinned annotation). The annotation is gone but the behavior is preserved automatically because the bindings- inline shape unambiguously signals “this is a transport adapter with a recv loop.” If a future workload needs adapter placement on a cooperative pool, the binding grammar can extend to reference a main-locus field by name (a v2 extension); v1 keeps the inline form with implicit pinned placement.

F.32 Locus working set as a cache-budget primitive (sketch)

Section titled “F.32 Locus working set as a cache-budget primitive (sketch)”

Status: design sketch. No grammar surface, no compiler behavior shipped. Documented here because the locus model already exposes the structural primitives a cache-aware optimizer would need; calling out what’s possible makes the shape easier to evaluate when a workload surfaces friction that justifies the work.

The observation. Cache hierarchies care about partitioning data by which thread touches it and how big the hot working set is. Most languages can’t reason about either at compile time — memory is an undifferentiated heap, threading is opaque, and lifetime is implicit. Hale’s locus model declares all three structurally:

A compile-time cache analyzer running over an Hale program sees the same partitioning the hardware caches do: per- locus working sets, per-thread arena owners, declared cross- thread boundaries. That’s structurally novel for a general- purpose compiled language.

What this already buys, implicitly.

None of this required calling it “cache-aware.” It fell out of the locus model.

What an explicit cache pass would add. Three layers, in ascending invasiveness:

  1. Cache-line padding on known-hot field boundaries. Cheapest, biggest demonstrable win. Phase 4a/4b lit up a producer/consumer cross-pool pattern: multiple producer loci on different cores write to a shared @form(hashmap) of Counter cells (the Prometheus registry shape). Without padding, two cells that happen to land on the same 64-byte line generate false-sharing pressure even though logically each producer writes its own cell. Padding the indexed_by row to a cache-line multiple eliminates the pressure. The substrate has all the info: the cell type’s size, the form layout, and (post-Phase-4a) the fact that cells are cross-pool reachable.

  2. Compile-time working-set budget per locus. A build flag (--target-cache=L1|L2|L3) parameterizes a static analysis: the compiler sums each locus’s projected working-set bytes (arena chunk size + @form(...) cell capacities × cell stride + nested loci’s budgets) and compares against the chosen target. Out-of-budget loci produce a warning naming the tower depth at which the budget overflows. Optional opt-in @locality(L1) / @locality(L2) annotation makes the intent declarative: “this locus is expected to fit in L1; warn if not.” Doesn’t change codegen — just surfaces “this tower won’t fit in L2 on the chosen target” before anyone runs perf stat.

  3. Per-pool arena chunking sized to cache. Today the chunk allocator picks a default chunk size. A cache- aware variant sizes the first chunk = L2_per_core / loci_on_pool so each cooperative-pool worker’s hot loci don’t thrash each other’s L2 slices. Growth chunks land on cache-line multiples; small allocations within a chunk pack contiguously so a single chunk traversal stays prefetcher-friendly.

What it can’t do. Caches aren’t addressable. No CPU exposes “pin this 32 KB region in L1.” All three layers above optimize for probabilistic residency via affinity + size discipline, not deterministic placement. This is not weaker than what real systems achieve — Intel Advisor, LLVM PGO, hand-tuned C++ all live in the same probabilistic world — but it’s worth naming so the design doesn’t get oversold.

Runtime working-set sizes also depend on data: a @form(hashmap) capped at 1 M entries doesn’t usually carry 1 M; the static bound is sound but loose. The budget analysis is most useful when capacities are tight (chunked projection class, recognition pool sizing) — exactly the loci where cache residency matters most.

Comparable landscape. The structural-primitive overlap with other languages:

The combination of (region semantics + lifetime + thread isolation + declared bounds, all visible together at compile time, with vertical-only flow making cross-component access statically distinguishable) is what no general-purpose compiled language ships today. The individual ingredients exist elsewhere; the integration is the structural advantage. Whether that advantage gets turned into a measurable speedup is a function of how much of the cache pass above we choose to implement.

Honest current state. None of layers 1-3 is implemented. The structural foundation is there; the analysis isn’t. What we have today is the implicit alignment described above: locus boundaries happen to match the partitioning caches reward, so well-shaped Hale programs benefit from caches as much as well-shaped C/Rust programs without the programmer reasoning about cache lines. Going beyond that — turning the locus model into an active cache-aware substrate — is a real workload-justified follow-up, not a v1 commitment.

Friction items this would close (when justified).

Friction items this would NOT close.

F.33 Fallible user-supplied bus adapters (sketch)

Section titled “F.33 Fallible user-supplied bus adapters (sketch)”

Status: design sketch. No grammar surface, no compiler behavior shipped. Captured here because the Phase-3 routing-keys on_unmatched: fail impl opened a path that this extension fits into cleanly; documenting now so a future session can pick it up without re-deriving the shape. F.36 (codecs, shipped 2026-05-28) has since landed the companion precedent: codec encode / decode methods declared fallible(E) are now invoked by the bus runtime at publish / receive sites, with the substrate threading fallibility through the synthesized thunk ABI. F.33 reuses the same machinery on the adapter send path — the implementation surface shrinks accordingly once F.36’s thunk-synthesis pattern is in tree.

The observation. A user-supplied bus adapter (bindings { Topic: MyAdapter { ... }; } in main locus) today declares an infallible send:

locus MyNatsAdapter {
params { url: String = ""; }
fn send(subject: String, bytes: Bytes) {
// network — failures must be swallowed or panic'd
// internally; no way to surface to the publisher
}
}

If the underlying transport fails (broker down, queue full, network unreachable, write timeout), the adapter has nowhere to put the error: the contract says send returns nothing, the publisher’s Topic <- value; statement is non-fallible, and Hale has no general “best-effort, may silently drop” metadata. So adapters either swallow errors (publishers unaware), retry internally (latency unpredictable), or call lotus_root_panic (process death on any transport hiccup).

The opening. Phase-3 routing-keys shipped on_unmatched: fail — a topic-level policy that makes the publish-side <- expression fallible-required (K <- value or raise / or discard). Same vocabulary, same disposition machinery, same typecheck enforcement that fallible-method calls have used since v1.x-FORM-1. Extending that mechanism to surface transport failures from user-supplied adapters reuses the same plumbing:

locus MyNatsAdapter {
params { url: String = ""; retries: Int = 3; }
fn send(subject: String, bytes: Bytes) fallible(NatsError) {
// ... may return err
}
}
main locus App {
bindings { Login: MyNatsAdapter { url: "nats://..."; }; }
}
locus Worker {
bus { publish Login; }
fn process(c: Credentials) {
Login <- c or handler(on_nats_err);
// ^^^^^^^^^^^^^^^^^^^^^^
// fires on NatsError from adapter.send
}
}

The Send statement becomes a fallible expression when the target topic’s binding routes to an adapter whose send is declared fallible. The typecheck enforces the or disposition the same way on_unmatched: fail does.

Two design choices to pin down at impl time.

  1. Derived (auto) vs. explicit (on_transport_failure: fail on the topic decl). The routing-key on_unmatched policy is intrinsic to the topic — “no in-process subscriber matched my key” is a logical condition the topic author can reason about up-front. Transport failure is different: it’s intrinsic to the binding, and the same library compiles against different bindings in different binaries (the F.31 deployment-seam point). Two paths:

    • Derived. Typecheck walks bindings → adapter → send at compile time; if the bound adapter’s send is fallible, publishes on that topic require or. Pro: ergonomic; the topic decl doesn’t have to anticipate every transport. Con: same library compiles differently against different bindings — could surprise a reader who didn’t check the main locus’s bindings.

    • Explicit on topic decl. A new clause like on_transport_failure: fail (symmetric with on_unmatched: fail). The topic author commits up-front; adapters that don’t match the contract are rejected at bindings-typecheck. Pro: contract visible at topic decl, symmetric with routing keys. Con: more boilerplate; forces topic authors to anticipate transport fallibility across all bindings.

    Lean toward derived. The deployment-seam philosophy (same library + different bindings → different binary behavior) wants the binding decision to drive the publish- side type. The reader who’s confused by the divergence should be reading the bindings block anyway — that’s where deployment shape lives.

  2. Substrate transports stay infallible at the language surface. unix(...) and shm_ring(...) already swallow IO errors (with on_overflow: discard|panic|... as the shm_ring back-pressure escape hatch). Re-routing them through the fallible-publish surface would force every existing <- value; site to carry or — a sweeping breaking change with no clear win. Keep them as today; the new fallibility is opt-in by user-supplied adapters declaring fallible-typed send.

Composition with routing-key on_unmatched: fail. A topic that’s both keyed-with-fail-policy AND bound to a fallible adapter has two error sources — “no in-process match” and “transport delivery failed.” The cleanest answer is to synthesize a per-topic union err type at codegen (BusSendError = BusUnmatchedKey | <AdapterErr>), have the or disposition address the union, and destructure in the handler. The codegen pattern mirrors the existing fallible- method err-union handling.

Sequencing. This is a v0.3 follow-on, not v0.2 of routing keys. v0.2 of routing keys is “ship or handler(err) / or fail <p> for the routing-key BusUnmatchedKey case” — needs BusUnmatchedKey stdlib type synthesis, mechanical from the existing fallible-disposition machinery (commit message of bus-routing-keys-fail-fallback calls this out). F.33 (fallible adapters) wants v0.2 already in for the err-union composition path; without BusUnmatchedKey synth working, the multi-source case can’t be modeled cleanly.

F.34 Per-epoch field reset (v1.x-WINDOWED)

Section titled “F.34 Per-epoch field reset (v1.x-WINDOWED)”

Status: shipped. Grammar + typecheck + codegen + runtime tree-walker all live. See spec/grammar.ebnf § closure_clause, spec/semantics.md § Per-epoch field reset, and the crates/hale-codegen/tests/closure_resets_per_epoch.rs integration tests.

The problem. Closure assertions can express point-in-time invariants (self.x ~~ self.y within 0) and, post-m46, stream accumulators (sum(self.delta) ~~ 0 within 100). Neither shape expresses a rate budget: “at most N events of type X per minute.” The canonical use is gateway corruption-rate auditing — a parse-error counter that should average to zero over rolling 1-minute windows. Today users either give up the closure framing (track the counter manually, fire violations from inline violate calls) or re-implement per-window reset by snapshotting the counter at window boundaries and computing deltas — both leak the windowing math into application code.

The shape. A new closure clause resets_per_epoch(field1, field2, ...); names locus fields the runtime zeros AFTER the closure assertion fires at a duration(N) epoch boundary. Ordering matters: the assertion sees the window’s accumulated value; the reset prepares the next window.

closure low_corrupt_rate {
self.corrupt_per_min ~~ 0 within 10;
epoch duration(1min);
resets_per_epoch(corrupt_per_min);
}

User code increments / decrements the field as the window accumulates (self.corrupt_per_min = self.corrupt_per_min + 1 in the parse-error path); the substrate keeps the counter honest about which window it belongs to.

Why a closure clause, not a form or library locus.

Typecheck restrictions. The clause is rejected unless paired with epoch duration(N) — tick recurs too fast to be a useful rate-budget window, and birth / dissolve / inline / explicit don’t recur. Each named field must be declared on the enclosing locus and have numeric type (Int / Uint / Float / Decimal); zero is not a meaningful reset value for booleans, strings, or structs.

Considered and rejected.

F.35 Green-I/O cooperative pools (where async_io)

Section titled “F.35 Green-I/O cooperative pools (where async_io)”

Status: shipped. Substrate plumbing in crates/hale-codegen/runtime/lotus_arena.c § lotus_coro_t / lotus_coop_park_on_fd / lotus_coop_pool_drain_one_async. User surface in spec/grammar.ebnf § placement_constraint. Typecheck

The problem. Hale’s cooperative-pool scheduler (F.31) is handler-atomic: each bus cell on a pool runs to completion on the pool’s worker thread before the next cell drains. That’s correct for short-lived handlers (the design assumes “handlers do bounded work between yield points”) but pathological for the TCP / WebSocket server shape, where a handler is a per- connection state machine that blocks on recv for the connection’s lifetime. With M pool threads, you get a hard cap of M concurrent connections — every other connection queues behind a recv() blocked on the kernel.

The workaround pre-F.35 was “pinned per connection” or “per-pool single-locus + many pools.” Neither scales to the Go-shaped “many connections per OS thread” model that the substrate’s lotus framing is otherwise good at.

The shape (option β: deployment-seam, no language-keyword extension). A placement entry may declare where async_io:

placement {
listener: cooperative(pool = ws_accept) where async_io;
worker: cooperative(pool = ws_workers) where async_io;
}

The pool’s worker drain loop integrates an epoll instance. Inside a locus method on this pool, blocking I/O syscalls (recv_bytes, accept_one, send_bytes, …) detect the async_io context via a TLS pool ptr and route through lotus_coop_park_on_fd instead of blocking the OS thread. The park primitive swapcontexts back to the worker’s drain context; the worker services other cells (and other parked coros’ wake-ups) until epoll signals the parked fd is ready, then swapcontexts back into the original coro and the syscall retries. From the user’s perspective, recv_bytes(stream) is the same line of source — only the lowering differs.

Why the deployment-seam shape (not a per-fn @blocking annotation). Same axis as zero_copy on bus bindings (Form K): operational requirements are deployment choices, not author choices. The locus body should be portable across deployments; the deployment author picks the I/O model based on workload shape. The same user code that serves five concurrent connections on a default pool serves five thousand on an async_io pool — with no source edit.

Stackful vs. stackless coros. v0.1 uses ucontext + a 64 KiB mmap-or-malloc’d stack per in-flight handler invocation (lotus_coro_t). Memory cost per concurrent connection ≈ 64 KiB + the per-conn locus arena (typically 4-64 KiB) = roughly 70 KiB per connection. 10k concurrent connections ≈ 700 MB — comfortable for any modern server. A later iteration may replace ucontext with a CPS rewrite (stackless coros á la Rust async fn / Go’s pre-1.4 model) if per-connection memory becomes load-bearing; the user-facing surface (where async_io + transparent recv_bytes) stays unchanged.

The 64 KiB stack is a hard ceiling on what handler code may put on the stack while running in a coro. The runtime’s own hot paths must respect it: the bus dispatch functions (lotus_bus_dispatch{,_keyed} / lotus_bus_dispatch_wire{,_keyed}) formerly held LOTUS_PAYLOAD_MAX (64 KiB) serialize / deserialize buffers on the stack, so a serialized publish issued from inside a coro handler (e.g. Topic <- value in a bus handler on an async_io pool) overflowed the coro stack — dispatch -> dispatch_wire alone is 128 KiB — and segfaulted in the dispatch_wire prologue (2026-05-29 fix). Those buffers are now thread-local statics, off the coro stack; this is safe because a coro never parks between filling and copying out a dispatch buffer (deserialize + enqueue, no I/O) and only one coro runs per worker at a time. Transport reader threads keep stack buffers — they run on full-size pthreads, not coros. Any future runtime addition on a coro-reachable path must keep large scratch off the stack the same way.

Considered and rejected.

Typecheck rules. All entries on the same named cooperative pool must agree on where async_io (the drain loop is one-or- the-other). where async_io is rejected on pinned entries (pinned owns its thread; no shared drain to park on) and on pool main (the main pool runs inline on the binary’s primary thread with no dedicated worker). See spec/runtime.md § where async_io for the running-context semantics.

Diagnostics. std::process::dump_pool_residency() writes one stderr line per cooperative pool with mode (async_io / blocking), parked-coro count, and pending cell-queue depth. Embed in a heartbeat tick on long-running daemons for occupancy visibility — mirrors the dump_arena_residency shape.

F.36 Pluggable codecs on bus bindings

Section titled “F.36 Pluggable codecs on bus bindings”

Status: shipped. Grammar + typecheck + codegen all live. Bindings carry an optional codec(L { ... }) clause; the binding-site assertion enforces both signature shape (encode(v: T) -> Bytes fallible(E) / decode(b: Bytes) -> T fallible(E) where T is the topic payload) and method purity. At publish + receive time, codegen substitutes per-binding __codec_encode_thunk_<Topic> / __codec_decode_thunk_<Topic> fn ptrs (matching the m70 lotus_serialize_fn / lotus_deserialize_fn ABIs) for the default m70 serializer ptrs at the call site — no runtime dispatch changes; the publisher’s <- path, local fanout via lotus_bus_dispatch_wire, and remote fanout all just see a different fn ptr. See spec/grammar.ebnf § binding_entry, crates/hale-codegen/tests/bindings_codec_clause.rs, crates/hale-codegen/tests/codec_instantiation.rs, and crates/hale-codegen/tests/codec_dispatch_roundtrip.rs for the acceptance surface. The companion machinery — compiler- inferred method purity (hale-types::purity) — is the load- bearing piece and is also reusable for several future features (memoization, parallel evaluation of pure helpers, sort comparator verification); F.36 is the headline use case but not the only beneficiary.

The problem. The v1 bus adapter contract (interface __StdBusAdapter { fn send(subject: String, bytes: Bytes); }) is a byte transport, not a codec. The bytes are serialized via the m70 wire format, which is internal and not publicly specified for cross-language consumption. So Hale ↔ Hale works fine over any user-supplied transport (NATS, MQTT, custom-broker-over-TCP), but Hale ↔ anything-not-Hale (Python subscriber over NATS, JSON broker, existing protobuf service) is structurally unreachable. The adapter can’t re-encode because it receives bytes, not values.

The clean answer is to split transport (route bytes between processes) from codec (translate between in-memory values and on-the-wire bytes). Today’s __StdBusAdapter covers transport; F.36 adds a parallel surface for codecs.

The shape. A bindings entry may declare an optional codec(L { ... }) clause naming a locus that provides the encode/decode pair:

type Tick { sym: String; price: Decimal; }
locus TickJsonCodec {
fn encode(v: Tick) -> Bytes fallible(EncodeError) {
let b = std::bytes::BytesBuilder { };
b.append_str("{\"sym\":\"");
b.append_str(v.sym);
b.append_str("\",\"price\":");
b.append_str(std::decimal::to_string(v.price));
b.append_str("}");
return b.finish() or fail EncodeError { kind: "alloc_failed" };
}
fn decode(b: Bytes) -> Tick fallible(DecodeError) {
let w = std::json::Walker { src: std::str::from_bytes(b) };
let sym = w.find_string_at("sym") or fail DecodeError { kind: "missing_sym" };
let price = w.find_decimal_at("price") or fail DecodeError { kind: "missing_price" };
return Tick { sym: sym, price: price };
}
}
main locus App {
bindings {
TickTopic: nats("nats://localhost:4222")
codec(TickJsonCodec { });
}
}

Codegen routes the bus publish path through codec.encode instead of the m70 __serialize_Tick, and the receive path through codec.decode instead of __deserialize_Tick. The adapter’s send(subject, bytes) contract is unchanged — the codec runs before send on publish, after the receive-side adapter on dispatch. Two layers, clean separation.

The compiler obligation: method purity must be inferred and asserted. This is the load-bearing piece — and it’s structurally pure compiler work with no new user-facing syntax beyond the codec(L) clause itself.

The bus reader thread, the publisher’s pool, and any consumer pool may invoke a codec’s methods concurrently with no serialization in scope. Codec methods must therefore be stateless — no self.X writes, no bus publishes, no impure stdlib calls (println, file write, sleep), and no calls to non-pure methods transitively. The same property other languages handle with Sync traits, [Pure] attributes, or trust-the-user comments.

Hale’s answer: the compiler computes is_pure as a derived property of every method during typecheck (alongside the existing F.31 single-threaded-method invariant check and the F.20 structural-interface satisfaction check), then asserts the property at the binding site. The author never writes a pure annotation. The substrate just enforces purity where it matters.

If a codec accidentally has a state-mutating method, the diagnostic surfaces at the binding site (not at the method declaration), pointing at the offending line:

error: codec `TickJsonCodec.encode` is not safe to dispatch
from arbitrary threads
--> bindings { TickTopic: nats("...") codec(TickJsonCodec { }); }
note: codec methods must be stateless — they may be invoked
from the bus reader thread, the publisher's pool, and
consumer pools concurrently.
note: `encode` writes to `self.call_count` at line 47:
47 | self.call_count = self.call_count + 1;
| ^^^^^^^^^^^^^^^^ this mutates the codec instance

The same surgical-diagnostic shape as the v0.8.3 typecheck landings (#18.6 CQRS, #76 nested-long-running, the @form(hashmap) cell-locus rejection): structural rule, error points at the antipattern site, fix path is named in the diagnostic.

Why this works without a pure keyword.

Purity is a derived property, not a declared one. The compiler has full information to compute it from the method body. The author writes natural Hale; the compiler reads the body and marks the method is_pure: bool as an internal property of the typecheck output.

Other compiler-enforced design rules in Hale already follow this pattern: F.31’s pool-placement tracking, the CQRS rule (#18.6 — methods returning loci), F.27’s closure-vs-assertion shape verification. None of these expose a per-method annotation to the user; the compiler just enforces the structural rule where it matters.

Pure-method inference fits the same shape. The codec case is the first feature that needs the property at a binding site, but the inference machinery is reusable for any future feature that benefits — memoization, parallel evaluation across a collection of inputs, sort comparator verification for sortable collections, hash function verification for @form(hashmap) cells. Each gets the property for free once the analysis exists.

Why the locus shape (not free fns).

An earlier design pass considered binding free fns directly:

bindings {
TickTopic: nats("...") encoder = tick_to_json, decoder = tick_from_json;
}

Function types as bindings would also work, kill cliffs around generic-interface satisfaction (just signature matching), and free codecs from instance-lifetime concerns (free fns are static addresses). But the locus shape wins on three counts:

  1. Organization. A codec’s encode + decode + private helpers naturally cluster as a unit. Splitting them into free fns pollutes the module namespace and makes accidental encoder/decoder misalignment harder for readers to spot.

  2. Proven safety, not asserted. With free fns the thread-safety claim is “trust the author” — the function is just a top-level fn that happens to be pure. With locus + inferred purity, the compiler proves the safety property and surfaces violations as diagnostics.

  3. Extensibility. Future codec variants (TickProtobufCodec, TickMsgpackCodec) get their own namespaces; helpers stay scoped; the source organization stays clean as the codec library grows.

The cost: the structural-interface satisfaction check at the binding site has to bind T (the topic’s payload type) against the codec’s method signatures. That’s a small extension to the F.20 structural-interface machinery — manageable, and the purity inference is the larger lift anyway.

Implementation surface.

Total: ~460 lines, 3-4 days.

Considered and rejected.

Sequencing. The purity-inference pass is the load-bearing piece. Build it standalone first (with the F.31 single- threaded-method check as the test harness — purity is a stronger version of the same “method body shape” question). Then layer the binding-site assertion + the codec(L) grammar

The grammar in v0 does not specify:

F.37 The publish contract: binding failure is structural

Section titled “F.37 The publish contract: binding failure is structural”

Decided 2026-07-22, from GH #227 (external reviewer found lotus_transport_create failing on stderr while every publish kept “succeeding” — messages silently dropped).

The contract. T <- value succeeding means the broker accepted the message. What “accepted” obligates the broker to is defined per binding (in-process: dispatched to every born subscriber; unix: handed to the peer connection, boundaries preserved; udp: handed to the local IP stack, lossy from there by declaration; shm_ring: slot committed under the declared on_overflow policy; adapter: the adapter locus’s own contract). The invariant: the broker may never accept a message it already knows it cannot handle under that binding’s guarantee.

Why <- stays infallible. Publishers have no error channel by design (statement-only send, no caller frame — the same narrowed two-channel rule that rejects fallible(E) on substrate surfaces). That is only sound because the broker is obligated to either uphold the binding’s guarantee or fail structurally: the error channel isn’t missing, it’s relocated to the one place it can be acted on.

Consequences.

  1. A binding (or LOTUS_BUS_CONFIG route) that cannot be realized is a birth failure of the declaring locus — bindings live on main, main’s parent is the root, so the unhandled default is the root failure shape (stderr + non-zero exit) via lotus_bus_binding_fail. Listener-side realization is synchronous at registration; only blocking accept/recv runs on reader threads, so failure can never hide on a detached thread.
  2. Per-send transient errors on a transport whose guarantee is lossy by declaration (udp) are logged, not structural — downstream loss is within contract.
  3. Runtime alignment with the static checker: dead-bus-receiver is a compile-time error; a dead route at boot is the same condition materialized at runtime and gets the same severity.

Deferred (needs its own decision): connection loss, resolved via transports-as-loci. Established-connection loss mid-run: today send-failure on a dead stream transport is logged and the reader EOF-terminates — the same accept-while-unable failure mode as the boot case, deferred only because it trades off against rolling restarts.

The direction (2026-07-22 design discussion): substrate transports become real loci — children of main, instantiated by the binding entry, converging with the adapter path that already works this way (adapter-binding loci are already pinned-equivalent by construction in codegen). A transport endpoint has connection state, a realization step, a long-running recv loop, teardown, and failure modes: that IS birth → run → dissolve with structural failure, not a thing that needs its own policy vocabulary.

Explicitly rejected: per-entry policy kwargs (on_loss: etc.) — that rebuilds a lifecycle DSL inside bindings { } when the language already has the singular expression of lifecycle. Binding entries carry only parameters of the guarantee (role:, codec(...), shm_ring’s on_overflow:) — the transport locus’s params, never its lifecycle.

Control plane vs data plane: the locus owns lifecycle and failure; publish fanout keeps calling lotus_transport_send directly against the handle the locus owns (the @form pattern: locus for flow, C for bytes).

Sequencing: (1) transports-as-loci restructure, behavior unchanged (the regression tests above pass verbatim) — SHIPPED 2026-07-22 (GH #233 PR: bindings { T: unix(...) } desugars to __StdBusUnix{Listen,Connect}Transport instantiation; both cooperative — pinned placement was tried and rejected because a pinned locus runs birth on its spawned thread, making realization asynchronous; the serve thread is C-spawned by birth and joined by dissolve); (2) listen-side re-arm — peer EOF loops back into accept() on the already-bound listener, no policy needed, unblocks rolling restarts of connect-side binaries — SHIPPED 2026-07-22 (lotus_bus_unix_serve, shared with LOTUS_BUS_CONFIG reader threads); (3)+(4) loss-is-structural + on_failure-on-main + restart-as-reconnect — SHIPPED 2026-07-22 together, per the guardrail. Implementation notes: loss is detected at publish fanout (any thread), marshaled through a mutex’d pending list, and dispatched at the top of lotus_bus_queue_drain (the owner thread — the only place failure handlers may run); the dispatcher is a codegen-emitted fn registered only when main declares on_failure(t: std::bus::UnixTransport, err: ClosureViolation) (the connect locus’s public name via the rename tables), passes a synthetic link_lost ClosureViolation, detects restart(t) by the __restart_count bump, and reconnects via the stored path; no handler / no restart / failed reconnect all take the structural exit. Down-window sends are dropped (fanout skips lost entries) — the broker never falsely accepts. The loss-as-violate-statement spelling inside the transport locus body was NOT used — the violation is synthesized at the dispatch site instead, since the locus body isn’t executing when fanout detects the loss; the observable semantics (ClosureViolation through on_failure) are as specified.

or wait — the third down-window option (GH #255 phase 1, 2026-07-27). A publish site may attach or wait to a send on a transport-bound topic: instead of taking the counted dropped_lost drop during the loss window, the publisher parks until the window closes (the app’s on_failure ran restart(t) and the reconnect succeeded) and then publishes onto the re-armed binding. This is a delivery-mode modifier, not error handling — the send stays infallible; wait is its own disposition kind, rejected everywhere except a send to a transport-bound topic. Semantics:

Phase 2 SHIPPED (2026-07-27, same day): the two capacity knobs from the GH #255 design. Topic-level bounded(N) + on_full: fail is the publisher-facing refusal contract — publishes to such a topic must carry a disposition (or raise = synchronous BusFull refusal at the send site; or discard = proceed, at-capacity registrations shed the newcomer counted; or wait = park until the drain frees space — queue-full is the second transient-refusal condition feeding the same disposition, exactly as designed). Subscriber-level bounded(N, drop_new|drop_old) is that consumer’s private cap: drop_old tombstones its oldest queued cell (ring semantics), and a consumer bound below the topic bound converts would-be refusal into private shedding. Scope facts: bounds apply to MAIN-queue registrations only at v1 (pool/pinned rings are already bounded MPSC rings with producer-blocking backpressure — GH #125 — so declared bounds there are typecheck-rejected with that explanation); the publish-site refusal pre-check is best-effort under concurrent publishers with the enqueue-side cap as the hard backstop; the err-payload dispositions (or handler(err) / or fail <p>) on full-fail topics are rejected with a pointer until the BusFull-payload slice lands. Per-registration dropped_full counting rides the entry.


F.38 Placement is semantics-free; delivery selection belongs to subscriptions

Section titled “F.38 Placement is semantics-free; delivery selection belongs to subscriptions”

Tested by a real ask (2026-08-12, a webserver tutorial): “partitioned placement” was expected to mean partitioned delivery, and it does not — bus pubsub is broadcast, and no placement axis may change WHO receives a message. The line held, and the resolution is the pattern for future asks of this shape: bridge the axes on the subscription side. where key == replica gives a pinned(..., replicas = K) fan-out sharded delivery with the filter still written on the subscription — placement only decides how many indices exist, so moving or scaling placement entries still never changes semantics. The same ruling closed the matrix’s other gap the ergonomic way: pool affinity (cooperative(pool = X, cores = …)) is placement changing WHERE a pool’s worker runs, never WHAT it receives.

Named non-goals recorded with it: a delivery: one_of competing-consumers mode (real work-queue semantics — ordering and backpressure questions, its own design conversation), and cooperative(..., replicas = K) (K loci on one pool share one thread; parallelism is more single-threaded units, never a multi-worker pool).

F.39 — Locus ownership is resolved before lowering (the owner table)

Section titled “F.39 — Locus ownership is resolved before lowering (the owner table)”

Status: SHIPPED. Approved on GH #921 (2026-09-20), computed and checked in shadow mode by A2 (PR #937), and read by lowering since A3. All seven one-shot flags are gone:

flag what reads the decision now
suppress_fresh_temp the table’s Owner for the factory call’s own node, at the GH #402 and GH #793 hooks
or_field_owner_locus nothing: the or substitute is its own node and carries the field’s decision
defer_next_locus_dissolve Owner::Binding / Owner::FrameTemp — the frame owns it, so the frame’s flush reclaims it
instantiating_for_parent_field Owner::Field (or Owner::Placement) on the node the field’s initialiser names
the field-ownership predicates the same row: the owner’s __locus_ref_owned_mask bit is Owner::Field, whatever the field’s declared type
placement_for_next_locus_instantiation Owner::Placement(entry), claimed by the instantiation the entry names
returns_this_locus / the current_user_fn_ret spoof split: STORAGE stays the declared-return-type fact, OWNERSHIP is Owner::Caller

Reaching a locus instantiation the table has no row for is a CodegenError naming the expression — the answer to this note’s second open question, and the reason the rules below hold by construction rather than by the order things happen to be lowered in. A literal codegen SYNTHESISES states its owner at the site (Cx::declared_owner): the @export singleton’s prelude, a reperspective swap, and the bindings { } transport, adapter and codec preludes.

The observable rules in spec/semantics.md § Dissolve timing rules do not change — this makes them true by construction. Two behaviours they already promised became true here: a perspective(P)-typed param owns a factory’s result exactly as an interface-typed one does, and a carrier or composite let RHS inside a loop is reclaimed per ITERATION like every other loop-bound locus.

Superseded in part by F.55: perspectives were removed, and with them the reperspective swap’s synthesized literal and the perspective(P)-typed param.

The lifetime of a borrow is checked (GH #730, 2026-09-22). The Borrowed row says the holder never reclaims; spec/semantics.md § “A borrow outlives its holder” says who must, and hale check refuses the positions where nothing does — a frame’s let or a handler’s payload into a child of self, a field of self into a returned literal — with the witness call site when a parameter carries the handle in. Decided from position over the owner structure, no annotation, whole program, a witness in every refusal.

Assignment follows initialisation (GH #967, 2026-09-21). The Borrowed row is a rule about a NAME reaching a field, not about the statement it reaches it in: self.<contract field> = <handle> in a method stores a borrow too — the child the field owned is reclaimed at the store, the field’s owned bit and reclaim slot are cleared, and the holder’s cascade leaves the handle to its owner (spec/semantics.md § Reassigning a locus-typed field, the contract-typed paragraph). Until then that store was outside the table’s reach — the mask bit and the GH #871 slot kept the default’s identity — and an assembly reclaimed the journal it was handed.

Why. Every teardown leak and use-after-free fixed in the 2026-09-20 sweep (#711/#812, #750, #789, #793, #815, #836, #837, #853, #871, #883, #890, #893, #895) was one of seven one-shot flags in crates/hale-codegen consumed by “the next literal (or call) lowered”: suppress_fresh_temp, defer_next_locus_dissolve, instantiating_for_parent_field, placement_for_next_locus_instantiation, or_field_owner_locus, returns_this_locus (with the current_user_fn_ret spoof, which also means “nobody owns this”), and the field-ownership predicates (field_init_is_fresh_factory / _impl, or_substitute_transfers_into_field). A flag set at a let or a field init is taken by whichever node lowers first — an argument, a receiver, the wrong branch of an or, the first arm of an if — and the residues still open (#921 A3) are all that shape.

The rule. Before lowering a body, one pass assigns every locus-producing expression an owner:

Owner = Binding(slot) -- `let x = …`, `x = …` into a local slot
| Field(owner, field) -- a param-field initializer, literal or
-- proven-fresh factory (bare / `or raise`
-- / `or fail` / `or <fresh>`), any
-- field type: locus, interface, perspective
| FrameTemp(scope) -- an expression-position value nobody
-- binds: receiver, argument, field read,
-- operand; dissolved at the scope's
-- flush (fn-scope, GH #814; per-iteration
-- slot reuse, GH #824)
| Caller -- the value a `return` hands out, in every
-- arm of an `if`/`match`/block tail
| Borrowed(from) -- a handle passed in (`Mid { leaf: shared }`,
-- an interface value from a parent field,
-- GH #730): mask bit clear, never torn
-- down here
| Placement(entry) -- a `placement { }` entry's instance (pinned
-- thread, program lifetime), incl. the
-- bindings transport (GH #893)

Derivation is syntactic plus one fixpoint: fresh_locus_factories (a fn every one of whose return arms — including if/match/block tails, which today disqualify it — is a freshly built value of the declared locus). A locus-producing expression is: a literal, a call to a fresh factory, an or whose branches are those, a carrier (if/match/block) whose tails are those, or an element of an ascribed array/tuple of those. Each branch and each element gets its own decision; a carrier never “consumes” a decision for its arms.

What lowering does with it. lower_locus_instantiation and the factory-call hooks read Owner from a side table keyed by expression id (assigned by desugar, stable across passes) and emit exactly the disposition the variant names: push a deferred entry (Binding, FrameTemp), write the reclaim slot and set the owner’s mask bit (Field), suppress the frame entry (Caller, Borrowed), register with the placement machinery (Placement). Reaching an instantiation with no entry is a CodegenError — the assertion that turns “the flag was consumed by the wrong node” into a build failure with a span.

How it shipped. A2 computed the table and only checked it against what the flags decided, on every corpus program and every cell of the ownership shape matrix (A4), so a disagreement was a test failure listing the expression and no behaviour changed. A3 then switched the consumers over one flag per commit, each commit deleting its flag and un-marking the matrix cells it closed: suppress_fresh_temp (with or_field_owner_locus, whose only job was to carry the field’s decision into lower_or_expr) → defer_next_locus_dissolve → instantiating_for_parent_field → the field-ownership predicates → placement_for_next_locus_instantiation → the returns_this_locus spoof → the missing-owner rule. The 200 open cells A4 listed went to zero.

Non-goals. No new syntax. No change to when things dissolve (spec/semantics.md stays the contract). let inside a loop stays fn-scoped with per-iteration slot reuse (#824). Struct values are not loci and are outside this table (#713 is a separate ruling).

Answered on approval (2026-09-20). (1) Borrowed(from) is the home for GH #730 and #731: a handle passed in — an interface value from a parent’s field, a designated perspective slot — is never owned by the receiver. (2) An instantiation with no owner is a hard CodegenError. In A2 it was an error under LOTUS_OWNER_SHADOW=strict and a log line otherwise, because A2 changed no behaviour and a build that used to succeed had to still succeed; A3 made it the rule and retired the knob with the shadow. (3) The bindings transport is Placement(entry) — program lifetime, dissolved at main exit — not Binding in fn main’s frame.

What A2 settled that the note left implicit. Five things the shadow forced:

Borrowed’s key. Expr::Ident carries no id, so a field initialised from a NAME is recorded against (owner locus, field) rather than against the expression.

What A3 settled. Three more:

Forward-looking items lifted from the spec files. These are design intent, not current behavior — grouped by the spec area they came from.

F.40 — The compiler is a pipeline of registered semantic families (the registry, the guard, and the graph core)

Section titled “F.40 — The compiler is a pipeline of registered semantic families (the registry, the guard, and the graph core)”

Status: ACCEPTED, IN PROGRESS. Reviewed on GH #1212 (2026-09-28 to 09-30: the compiler team’s round, the differential, the final direction, the lineage note, the implementation plan). Phase 0 ships the registry, its guard and the boundaries below; phases 1 and 2 migrate families onto them, one at a time, behind shadows, on main. The parent is GH #476, which made every verification consumer read one typed model and deleted the second evaluator; F.40 does the same for the producers and for lowering.

The acceptance question. Can a contributor make a correct change to one semantic family by understanding its contract, producer, relevant consumers and focused tests, without reconstructing the rest of the compiler?

Scope. F.40 reorganizes the implementation of existing Hale semantics into authoritative, typed, witnessed results consumed through a shared pipeline. Success is measured by removed duplicate decisions, more consistent enforcement, more localized tests and diagnostics, and less compiler context needed for a correct change. Delivery is one semantic family at a time, with compatibility checks and explicit treatment of semantic corrections. @evented (F.41), the unit dialect (GH #1076), a second emitter, footprints, storage bindings, the authority edge and hale ui are extensions that consume F.40 and get their own review once phase 2 is green; none of their semantics is an acceptance condition here.

The registry. spec/registry.md, rendered from crates/hale-graph/src/registry.rs and held byte-equal by a test, lists every semantic family with its contract: what it answers, what it reads, its authoritative producer, the legacy producers still permitted (each with its removal condition), its consumers, invariants, missing-data policy and focused tests; the spec’s numbered rules with their evaluators; and the frozen list of Debug-string scans. A family is in one of three states — Reserved (a future family or consumer; computes nothing), Migrating (the canonical producer is under development; the legacy list is exact), or Canonical (one production producer; consumers cannot reconstruct its meaning) — so the inventory can be exact without banning what exists today. spec/registry.md carries the inventory and its counts; the reservations are runs_under(locus, principal), transitions, deployment and view, with ui and bundle as reserved consumers.

The guard (crates/hale-graph/tests/registry_guard.rs). Three scans fail the build: a derivation-shaped function (compute_, derive_, infer_, summarize_, classify_, or named exactly like one of the producers the guard lists, phase 1’s mint, handler_rows, child_locus_name and the rest) in a semantic crate that the registry does not name in that file; a reference to a family’s guarded seam (build_bus_graph(, resolve_owners(, …), counted as a whole name, from a file the registry does not list or more times than it lists; a Debug rendering with no prose around it (a ?} placeholder in a formatting macro whose template holds no space) in any of six crates that is not in the frozen list. A registered rule without an evaluator fails the build. Every site the registry names must exist. A scanner cannot prove that no code reimplements a decision under another name; it names the legitimate path and puts friction on the wrong one, which is what made harness_paths_are_unique true the day it existed.

Boundaries, locked before any fact moves.

  1. hale-graph holds generic mechanics only: identity, provenance, typed-table support, shared query machinery, the shadow facility. Row meanings, derivations, invariants and named queries live with each family. The crate depends on nothing; hale-model is rebuilt on it and keeps its own no-syntax law.
  2. Frontend types and LLVM layout types stay distinct.
  3. Identity is (seed, index), minted once after desugar. Snapshot-local uniqueness and reliable provenance are the requirement; persistent identity across editor revisions is a separate problem, and a snapshot identity is not a persistent deployment identity. Addresses are not identities (declarations are cloned) and spans are not (the stdlib’s coordinates overlap user files; desugars stamp one span on several declarations, GH #1140 / PR #1210). During migration the shadow compares through an explicit correspondence, never raw id equality.
  4. Derive once, precisely: one authoritative producer per semantic fact within a resolved compilation snapshot, including entry, configuration and target inputs. Recomputation for another snapshot, and shared indexing over established facts, are not violations.
  5. Unknown is not missing. A hole is a declared unknown with a stated policy. A missing required row at lowering — an instantiation with no owner, a binding entry with no row — is a compiler error. Codegen never guesses and never manufactures a hole. Where absence is itself the fact (a subject no dispatch plan names dispatches dynamically; a locus no restart row names cannot fail), the read is a total answer, said where it is read; the registry states which each family’s reads are (phase 3’s exit).
  6. Lowering reads and never decides: lowering does not rediscover source-level semantic decisions the resolved program is supposed to provide. Target-specific emission choices and walking a typed body are not decisions in that sense.
  7. Semantic source survives emission rewrites. Turning a send into a call must not erase the message relation analysis needs.
  8. Readiness is not completeness. Not requested, blocked by invalid input, and ready with holes are three states. Adequacy is query-specific: roots, direction, relations, horizon, phase and hole policy all matter. Facts, laws, evidence and observations stay separate, and the four verdicts and the evidence ties stand.

Every compiler-recognized structural world has a locus root and an explicit horizon (%DESIGN I8), and its facts stay typed rows.

Rows versus laws. Expression typing, borrow-outlives, bare-fallible, the blocking classification and the effects fixpoint are derivations: they produce rows. Claims judge rows. The registry states which side each family is on. Structural laws are evaluated through model_query with shared witness rendering (superseded in F.40 phase 4, decision 3: a structural law is a function over family rows whose finding is a law::Violation, run by the check); the judgment path stays for user claims; the two converge once hundreds of laws have been measured. constitution Hale remains the direction, but the vocabulary grows incrementally and is not a prerequisite for moving checks. Placement rule 6 (pinned-locus restrictions) had no checker code — its only evaluator was a spanless refusal at lowering, so hale check and the LSP accepted a program hale build refused — and phase 0 corrected it as its own reviewed change: the checker judges the rule at the placement entry, with the entry’s span, and the lowering backstop stays for harness builds that skip the checker and for the one shape the checker does not see, an adapter locus instantiated inline in a bindings { } block, which lowering pins. The correction settled a spec/implementation disagreement by decision rather than by extraction: the rule said “no closure declarations” while lowering refused only epoch birth and epoch dissolve closures (dissolve being the default when no clause is written, by the AST’s one epoch rule that the checker and lowering now both read), and pinned loci with inline, tick and duration closures ship (example 40, the pinned restart tests, DNA’s nerves connection). The rule now says what ships, with one regression test per epoch.

Approximate is legitimate only in layers 5 and 7, where F.38 makes it so; everywhere else a backend lowers or rejects, with the row’s witness. Consolidating today’s target restrictions (the check.rs stdlib table, link_wasm, the per-site skips, target_has_async_io) into one matrix is in F.40; new backends are not.

External contracts are frozen through extraction, in GH #476’s sense: the artifact schema and digests, shape_hash over the model half, the model-diff JSON, the verify findings and the diagnostic wording that DNA pins. Additive and unhashed sections are free; transitions are explicit, versioned, and ship with the DNA edit in the same change. Any semantic change affecting execution stays covered by the executable or evidence identity even when the structural projection is unchanged.

Delivery. A PR series on main behind shadows, one consumer per commit, a prerelease tag per phase; no long-lived feature branch. The shadow’s report is designed for the contributor fixing a divergence: family, source site, old and new fact, deciding witnesses, smallest dependent slice, and a classification — migration regression, known old bug, intentional correction, unresolved spec disagreement. The current compiler is a compatibility reference, not a correctness oracle. The facility is hale_graph::shadow (phase 0): a report over a corpus, a classified fixture beside the test, and the gate “no unexplained divergences”; its first instance runs the checker’s placement map beside the bus graph’s over the whole corpus (crates/hale-types/tests/shadow_placement.rs, since retired into the placement table’s golden, placement_golden.rs, once every legacy producer it compared read the table) over the programs that check clean and classified 20 divergences, all known old bugs: the checker’s map has no row for a qualified locus type, and the bus graph’s walk does not inherit a nested locus’s placement from its owner while direct_call_eligible reads it. Phase 1 migrates ownership first, then handler selection, then bus facts and dispatch. Phase 2 puts every entry point through one frontend: check, build, run, test, replay, --dump-topology and the LSP run the same layers, build stops recomputing, and the demand gate (GH #476 criterion 1) becomes per-family accounting: no family is built that no consumer asked for. Lifecycle normalization is in F.40; the first named decision is that handlers run only on the queue owner’s thread, so cross-thread failure delivery follows spec/runtime.md, and the runtime is verified against the lifecycle table before the table is trusted.

What the phase-0 inventory corrected in the RFC. borrow_lifetime and bare_fallible already run on the build, run, test and replay paths (through check_bundle_for_build); the entry points that skip them are the LSP and bench. The demand-gate criterion is GH #476’s, not “#515” (no such reference exists in the tree). The DNA toolchain cache key covers the compiler’s sources since commit 22a4daf0, not since #1206. The key omits hale-model — as does the replay identity and the stale-binary hash — which is the identity-coverage gap phase 0 closes before any producer moves.

F.42 — A value-returning fn that may violate is fallible(ClosureViolation)

Section titled “F.42 — A value-returning fn that may violate is fallible(ClosureViolation)”

Problem. F.27 says violate exits the method “as a return does” and names no value. In a value-returning method whose owner’s on_failure absorbed the violation, lowering returned an LLVM undef of the declared type, so the caller read garbage: a downstream handoff measured an Int result of 104616817497632 after its supervisor’s on_failure ran, and a pointer-typed result would have been dereferenced. F.27’s own canonical shape (let r = expr or self.handle_io(err); if !self.draining { … }) is that method: it is safe only while every caller remembers the guard.

Decision.

  1. The law. A value-returning fn or locus method whose body may violate is declared fallible(ClosureViolation). A fn may violate when its own body holds a violate statement, or when it calls a value-returning fn that may violate and is not fallible. A violation in a method that returns nothing is not the caller’s failure: a call to one does not make the caller one that may violate. A fn that may violate declared fallible(E) with another E is refused: a fn has one error type, and the violation record is the one a violator carries. Lifecycle bodies, bus handlers and fn main are exempt, the runtime being their caller. Callers follow the bare-call law (GH #738) unchanged: an or disposition is required, and the err it sees is the ClosureViolation.
  2. The lint. A fn returning nothing that may violate and is not fallible is a warning with the law’s wording and “This becomes a law in a later release”. Nothing else changes for it: the method exits as a return does, the caller continues, and self.draining is the violating locus’s own flag, read inside that locus.
  3. The lowering. In a fallible(ClosureViolation) fn, violate reports as before (the drain flag, the record, the owner’s on_failure, which runs in place on the owner’s domain and is posted there and awaited from any other, decision L0-1), then stores the record in the fn’s error slot and takes its failure return. No undef is produced. A fn returning nothing that is not fallible lowers as before.
  4. The stdlib follows the law. BytesBuilder.snapshot and finish become -> Bytes fallible(ClosureViolation), and every caller gains an or.
  5. A stated gap: perspective-served methods. A locus method that implements a perspective fn is exempt from the law and the lint, carries nothing to its callers, and is warned about instead (“… serves P.f and may violate …; a perspective call cannot carry the failure yet, so the method keeps today’s behaviour”). The reason is that no spelling of it both checks and runs: an infallible impl is the law’s refusal; a fallible impl behind an infallible perspective fn passed conformance, which did not compare fallibility, and the perspective call, lowered with the perspective fn’s infallible signature against the fallible body, crashed with SIGSEGV even on a call that never violates; and a fallible perspective fn is refused at the call by the build (“fallible method call on non-locus value”). Conformance now matches a perspective fn’s fallibility both ways, which closes the crash at check time. The exemption goes when a fallible perspective call lowers; build::violate_build’s a_fallible_perspective_call_is_refused_at_the_build pins the refusal so that day is visible. Superseded by F.55: perspectives were removed, and the gap with them.

F.27 stands. Allocation failure is structural: a builder that cannot grow violates alloc_failed, and its owner’s on_failure decides. What changes is that the caller of snapshot() now says what its own activation does: or raise, which ends the process from a fn that is not fallible (the behaviour the bare path had when no handler absorbed the violation), or a fallback where the surrounding code already handles an empty result. The error-check method of F.27’s example is written fn handle_io(e: DbError) -> Row fallible(ClosureViolation), and its caller says what an escalation means: or (self.handle_io(err) or { return; }).

Considered and rejected.

F.43 — Framework vocabulary is contextual

Section titled “F.43 — Framework vocabulary is contextual”

Problem. The lexer reserved forty-odd ordinary English words — run, epoch, restart, capacity, bulk, tier, where, of, publish — so a field, parameter, local or fn named after one was a parse error. Each word introduces syntax in one position only (a hook at locus-member position, a clause inside a closure body, a statement at statement head), and a downstream handoff renamed fields run, epoch and restart to work around the list. F.10 had already admitted the three mode words post-.; the rest stayed reserved.

Decision. Every word whose one position is unambiguous lexes as an identifier and the parser recognizes it in that position (spec/tokens.md § Reserved words gives each word’s position): the locus-member words (params, contract, bus, capacity, as_parent_for, indexed_by), the lifecycle hooks (birth, accept, release, run, drain, dissolve, on_failure), the mode words, the projection classes and tier, the closure clauses (closure, epoch, persists_through, resets_on, resets_per_epoch), the recovery statements (restart, restart_in_place, quarantine, reorganize, bubble), the contract words (expose, consume, inferred), the bus words (subscribe, publish, on, of), the perspective words (stable_when, serialize_as), yield, terminate and where. Two declarations stay refused, each because its name would collide with the syntax at the call: a locus METHOD named like a hook, the failure handler or a mode (fn run() in a locus — that name IS the hook), and a free fn named like a recovery statement (restart(x); at statement head is the recovery).

Superseded in part by F.55: perspectives were removed, and the perspective words (stable_when, serialize_as) with them.

Superseded in part by F.61: modes were removed, and the mode words (mode, bulk, harmonic, resolution) with them, so a locus method may take one of the three former mode names.

The declaration and statement words (locus, type, fn, let, if, match, return, self, …) stay hard: they begin items, statements or expressions anywhere, so no position frees them. trait, impl, async, await and macro stay reserved for the syntax they are held for.

Considered and rejected. An escaped-identifier form (r#run). It makes the author spell around a restriction the parser does not need. Admitting the words as names in declaration positions only. A local named epoch that cannot be read back is not a name.

F.44 — A fleet is a locus kind, and its routes are derived

Section titled “F.44 — A fleet is a locus kind, and its routes are derived”

Problem. A deployment of several programs was a plan JSON naming artifacts and routes by hand (GH #408): a second format beside the source, routes that restated what each program’s topics and bindings already said, and nothing hale check read.

Decision. fleet locus NAME { params placement bindings claims } declares the deployment in source, a locus KIND beside main. It is a locus kind, not a typed param, because a fleet is checked as one graph (the routes between its instances, the claims across them) and never runs itself; a param is a thing a running program holds. Its params are other seeds’ main loci through the seed’s imports, its placement a default host or replica count per instance (the habitat’s allocation rows bind instances to hosts), its bindings the subjects that wire the instances. A route is derived, never written: from every instance whose artifact publishes a bound subject to every instance that subscribes it, each through its own main’s binding. The seeds are composed as artifacts, never merged as source, so the fleet is never a super-main. The deployment family’s rows are the derivation (spec/verification.md § Fleet composition).

Considered and rejected. A fleet as a typed param of a main (the feature-as-param rule): a param is held by a running program, and a fleet has none. Routes written in the fleet: they restate the instances’ own topics and bindings, and the restatement is where a plan and its programs drifted apart.

F.45 — The fleet seed is the one input; the plan is an export

Section titled “F.45 — The fleet seed is the one input; the plan is an export”

Problem. After F.44 a deployment had two inputs, the fleet seed and the plan JSON it replaced, and every consumer (composition, signing, the renderer, the DNA) read the plan. A fleet seed checked as a merged program also merged the seeds it imports, the super-main F.44 rules out: their world law, their constitutions and their wire subjects met in one check.

Decision. A fleet seed is the only input. hale fleet check|dump, [fleets], the DNA’s [dna] fleet and hale deploy render take the seed; the plan JSON is written by hale fleet export <seed> for whoever reads one, and read by nothing. A signature covers the export’s exact bytes. A fleet seed is never merged with the seeds it imports: its laws are judged over its own source and what each import declares, and each instance’s seed is checked as its artifact is cut. Placement is the record’s: the source declares each instance’s default host (one instance per named host, ids <param>-<i>), the habitat’s allocation rows override it per instance, and a render reads both and writes one description per host. The fleet’s binding is the route’s configuration: an instance whose own main does not bind the subject still joins the route (F.44 refused it), and one that binds it must bind it over the route’s transport kind.

Considered and rejected. Keeping the plan as an input beside the seed: two inputs drift, and every consumer pays for both. Binary attestation: a fleet seed names no binaries; what a host runs is the build of the seed, observed at runtime.

F.46 — A 256-bit integer’s arithmetic never wraps

Section titled “F.46 — A 256-bit integer’s arithmetic never wraps”

Problem. U256 and I256 (GH #1934) carry chain values: balances, token amounts, fixed-point prices. Int arithmetic wraps on overflow, and a wrapped balance is a wrong balance, silently.

Decision. +, -, *, /, % and unary - over a U256 or an I256 are checked: an overflow, a division or remainder by zero, I256::min() / -1 and -I256::min() are a runtime violation where they happen (printed, exit 1), as Time’s range is. checked_add, checked_sub, checked_mul, checked_div and mul_div are the forms that fail into an or (ArithError). Shifts are bit operations and drop what they shift out. A 256-bit integer never converts implicitly, to or from Int or the other width; the check names the conversion.

Considered and rejected. Wrapping, as Int does: it is the failure the type exists to prevent. Fallible operators: every expression would need an or, and the arithmetic of a price formula would drown in them; the checked calls cover the sites that expect a failure. Literal suffixes (5u256): a unit may be named u256, so a suffix collides with the unit dialect’s literals.

F.47 — The five future-use words are unreserved before 1.0

Section titled “F.47 — The five future-use words are unreserved before 1.0”

Status: accepted and implemented (2026-11-18). Proposed while the keyword list was frozen behind an RFC; confirmed under the pre-1.0 policy (STABILITY.md), which takes a decision entry and a CHANGELOG fragment for a keyword change. The implementing PR edited spec/keywords.txt, the lexer, keywords.rs, spec/tokens.md and spec/grammar.ebnf together, and unreserved export with the five (see “export” below).

Problem. trait, impl, async, await and macro are hard keywords with no grammar (spec/tokens.md § Reserved for future use): the lexer refuses them as names, and no production uses them. Before 1.0 each is either designed or unreserved (GH #1950); a reservation carried into 1.x is a promise of syntax nobody has designed, kept at the price of five ordinary words.

Decision. Unreserve all five: each lexes as an identifier, free as a field, parameter, local or fn name. Each word’s feature already has a Hale answer that took a different shape:

Unreserving costs nothing later. It accepts strictly more programs, so it can ship in any minor release with Breaking: none. If one of these features is ever designed, it takes its word as a contextual keyword (F.43), recognized only in its position, as topic, fleet and unit were. A hard reservation buys nothing a contextual keyword cannot do, and putting a word back into the hard set after 1.0 would break every program that uses it as a name.

Considered and rejected. Keep the five reserved through 1.x as insurance. Under F.43 the insurance pays nothing, and the words stay unusable as names indefinitely. Design them before 1.0. Each would duplicate a shipped mechanism (F.20, F.35, the annotation families), which the 1.0 promise would then have to keep twice. Unreserve some and keep others (for example, keep async/await for an effect-typed future). Nothing in the effect system (effect classes and budgets) needs a keyword at a call site, and the split would need a reason per word that none of them has.

export. export was a hard keyword too, but the language only ever spells it @export (spec/ffi.md § WASM host interface), and an annotation name needs no reserved word: @form, @ffi, @positional and every other annotation are identifiers read after @. The parser now reads @export the same way, as the identifier export after @, so the annotation is unchanged and export is free as a name everywhere else. Unreserving it accepts strictly more programs, as the five do.

F.48 — A body that returns a value ends in one, and its last statement is its value

Section titled “F.48 — A body that returns a value ends in one, and its last statement is its value”

Problem. hale check had no definite-return analysis (GH #1940). fn sign(n: Int) -> Int { if n > 0 { return 1; } } checked clean and the build refused it, with no file or line, as falling through; so did fn g(x: Int) -> String { match x { 1 -> "one", _ -> "other" } }, which is correct code: the parser keeps a trailing match a statement, and its arms’ values were discarded.

Decision. In a body with a declared return type, the last statement’s arms and tails are the body’s result position: a trailing match, if or block carries the value to its leaves, each the return it means (desugar_tail_returns, in the one desugar sequence before the check), so the check types each leaf against the return type and lowering lowers the returns it already lowers. The check then refuses a body that can still reach its end without a value, at the declaration’s name, the falling-through path as a related location (definite_return). The judgment is structural: a path leaves through return, fail, break, continue, terminate, violate, an if … else / exhaustive match / block every branch of which leaves, or a while true no break of its own leaves; nothing about values. spec/semantics.md § “Definite return”.

Considered and rejected. Make a trailing match an expression in the grammar, as a value-producing trailing if is: a side-effect match ends many bodies that return nothing, and the parser cannot know the return type. Judge only in lowering, with a span: the check is where a program’s shape is judged, and a library seed is checked without being built. Treat a diverging call (std::process::exit) as leaving: the language has no Never type; a call completes, and a body that ends in one says what it returns after it.

F.49 — A bounded local bound from a place is a copy

Section titled “F.49 — A bounded local bound from a place is a copy”

Problem. The ruling of 2026-10-13 (spec/types.md § A local bound from a place is yours, GH #713) made every local bound from a place the frame’s own value: a struct, a String, an array, a tuple, a payload. A bounded[T; N] local was left out. It lowered to the place’s own inline storage, so let mut mine = self.row.tags; push(mine, x) wrote the field, a later push(self.row.tags, y) showed through mine, and the element pushed through the local had to be anchored where the field lived. A bounded could not be returned, built from a literal or assigned whole as a local, because a local had no storage of its own to hold one (GH #1951). Changing this after 1.0 would change what running programs compute.

Decision. A bounded local bound from a place is a copy, by the same rule as the other value types. Writing the local never changes the place, and writing the place never changes the local. The ownership pass keeps reads free, as it does for the others: the local stays the place’s storage until a write into it (a push, set, clear or truncate naming it), which copies the list into the frame first, its storage and its live pointer-shaped elements, behind the local’s copy-on-write flag; a local bound across an in-place write of its place, or handed to a call that may write through its parameter, is bound as a copy. With a local that holds a list of its own, a bounded is a value: an array literal at a declared bounded[T; N] site is that list (a literal longer than N is a check error), a local bound from a literal or a call is owned, a let mut one is assigned whole, and a fn returns one by value through the record return path, copied into the caller’s arena. An intrinsic that writes a local declared with let is refused, so a program written against the view is told where it stopped writing the place.

Considered and rejected. Keep the view and add a separate owned local. Two kinds of bounded local would read the same and behave differently, and the view kept the arena-anchoring rule (an element pushed through it went to the place’s owner) that every other value type had shed. Copy at every binding. A for over self.row.tags through a local would copy the list for nothing; the copy on write costs only where a write happens. Return through a caller-supplied place. A record already returns through the caller’s arena; a list returned the same way needs no second convention.

F.50 — or raise converts: set members on the error channel, and @raise conversion fns

Section titled “F.50 — or raise converts: set members on the error channel, and @raise conversion fns”

Problem. or raise hands the call’s error on as the enclosing fallible(E) fn’s own, so the two had to be one type (GH #1945 made a mismatch a located check error). A fn calling into several layers fails with an error of its own, and every raise across a layer had to be spelled or fail E { … }, copying fields by hand at each site; a set type of the layers’ errors could not be raised into at all, though fail m; already made a member the set’s (GH #1951, item 2).

Decision. An error P raised inside a fallible(E) fn, P not E, is converted, tried in this order:

  1. R2, a set member. E a set holding P: the error is the set’s member. One relation decides fail, or fail <expr>, or raise and a fallible handler’s failure (its implicit or raise).
  2. R3, a conversion. @raise fn conv(e: P) -> E { … } declares one; the raise is or fail conv(err). A @raise fn takes one parameter, is neither generic nor fallible, returns another type, and implies @effects(none: {syscall, publish, spawn, block}) (it may allocate). Orphan rule: it is declared in the seed of P or of E; a builtin error type belongs to no seed. Coherence: every conversion for a pair is then in one of those two seeds, which are what an or raise reaches; two for one pair are refused at the or raise, naming both. No chaining.

Nothing else converts: the or raise is refused, naming both types and the three ways forward (a @raise fn, a set holding P, or fail E { … }). The check records each conversion at its raise (a typed-body row), and lowering writes the raise as the or fail it stands for. spec/semantics.md § “Converting a raised error”.

Considered and rejected. Reach as “this seed and the seeds it imports directly”: the checker’s bundle carries no import graph (the merged program keeps only the rename table), and under the orphan rule the candidates are already exactly the two seeds that declare P and E. Chaining conversions (P to Q to E): a path search whose answer moves when an unrelated seed adds a conversion. A conversion applied wherever a value of P meets an E (an argument, a let): the error channel is where translation is asked for; elsewhere it would hide a call. Letting a conversion fail or do I/O: it runs where an error is already being handed on, and a second failure has nowhere to go. Refusing a duplicate at its declaration: two seeds may each declare one for a pair without either being wrong alone; the conflict exists where an or raise would have to choose.

F.51 — An import list re-exports

Section titled “F.51 — An import list re-exports”

Problem. F.25 made every cross-seed reference qualified (st::ModelRow), and A4 kept an import’s names inside the importing seed. A seed had no way to spell another seed’s declaration bare, and none to hand a declaration it imported on to its own importers except a type ModelRow = st::ModelRow; alias per name, which covers types only. Moving a type from one seed to another was a rename at every use in every seed that reached it (GH #1951, downstream handoffs). Whether a name a seed brings in is reachable through that seed has to be fixed before 1.0: deciding it later either breaks programs that rely on it or makes every list a second, private kind of import.

Decision. An import may end in a list, import "../store" as st { ModelRow, Names as StoreNames };. Each item names a top-level declaration of the imported seed (a type, locus, fn, const, topic, interface or perspective) or a name that seed’s own lists bring in; an unknown item is refused at the item. A listed name is bare in every file of the importing seed, as the import is; as renames; locals shadow it as they shadow any top-level name; a listed name that is also a declaration of the seed, or that another list binds to a different declaration, is refused, naming both. A list re-exports: a listed name is reachable through the importing seed’s alias (api::ModelRow when api lists ModelRow from st), and may be listed again by an importer of that seed. It is the same declaration as st::ModelRow — one mangled symbol — so a value flows between the spellings with no conversion. There are no globs, and the alias itself stays the importing seed’s own (A4). Importing a file of the seed itself stays refused: its names are already bare.

Considered and rejected. A list that does not re-export. A seed that wants to pass a type on would still write the alias per name, and the two forms would differ in a way no reader can see at the use site; the list is where the seed says which names it speaks, which is what its importers want to reach. Globs (st::*). A glob makes the set of bare names a function of another seed’s contents, so adding a declaration there can break a seed that never mentions it; spelling every name keeps each bare name traceable to one line. A visibility modifier (pub). Out of scope for the same reason as before (No pub / export): a list chooses what the importing seed speaks, not what the imported seed hides. Re-export as a separate keyword (export). A new word for what the list already says, and the keyword set is frozen (STABILITY.md).

Superseded in part by F.55: perspectives were removed, so an item no longer names a perspective.

F.52 — Optionality is a property of a record field, not a type

Section titled “F.52 — Optionality is a property of a record field, not a type”

Problem. A record that tells a field left out from one sent spells a presence pair by hand, x: T; has_x: Bool;, and a PATCH field a triple with clear_x (spec/api.md § Codecs). The pair is what the codecs, the description, protobuf and the contract digest read, and it works, but nothing ties the flag to the field: a program that sets x and forgets has_x writes a record whose value is never sent, and every literal that builds an absent field has to spell a value for it anyway (GH #1951, downstream handoff). The fix could be a general optional type, T?, usable anywhere; once programs hold T? locals and return T? from fns, taking it back would break them.

Decision. Optionality belongs to a record field and to nothing else. x?: T in a type declares x and a real field has_x: Bool = false right after it, and x?: T clearable a clear_x: Bool = false after that: the hand-written pair and triple, field for field, so the wire, the description, protobuf and the digest are byte-identical and converting a pair changes no shape hash. A write of x (a literal that spells it, an assignment through any path or into a part of it, a push or set into an optional list) sets has_x and clears clear_x; a literal that leaves x out builds it absent, at its default or its type’s zero. Declaring the synthesized flag beside the mark is a duplicate field. There is no T?: the ? is refused on a parameter, a locus param, a local, a return and an enum payload, and after any type. Absence in a computation stays fallible(E). clearable is a contextual keyword, a word only after an optional field’s type.

Considered and rejected. A general T?. It would be a second protocol for absence beside fallible(E), with its own unwrapping operators, and every analysis that follows a value through a call (the ownership pass, the alloc summary, the codecs) would learn a new shape; the only place a program needs absence to be data is a record crossing a wire, which the field mark covers. Keep the pair hand-written. The flag a program forgets is the bug the mark removes. A flag that is not a field (presence kept out of the record’s slots): the codecs, the .proto and the digest already read the pair as fields, and a hidden slot would change every one of them.

F.53 — A variant has one external name

Section titled “F.53 — A variant has one external name”

Problem. A program that stores, logs or reads back an enum spells its variants as strings by hand, a name function and a parse function per enum (82 and 106 of them across two downstream handoffs and the in-tree dna/ library, RFC #1995 G1), and a codec spells them again: the JSON codecs write the declared name, or the json: tag’s key since GH #1951 item 5. Each hand-written table is a second spelling that drifts from the first, and lowercase variants were declared to make the codec’s spelling come out right, against the style guide (G3).

Decision. A variant has one external name: its json: tag’s key when it has one, else the spelling its enum’s @wire_case(snake | screaming_snake | kebab | lower) gives it, else its declared name. The JSON codecs (record and api), the description, the digest, and the compiler-written E::name(v), E::parse(s) all read that one name, and a catch-all (Other(String) `json:",other"` , or a payload-free one) means the same to E::parse as to the decoder: an unknown name is the catch-all, so parse of such an enum cannot fail. E::variants (a value, [E; N] in declaration order) and E::index(v) (the ordinal) complete the set. They are type-path functions the desugar sequence writes, as T::from_json is, so types still have no methods, and the names are contextual (F.43): an enum with a variant of the name keeps its variant. @wire_case is an annotation applied where it is parsed, as the tags it stands for. Rendering is not a wire: to_string and println keep Enum::Variant. Protobuf keeps the variants’ numbers, and the bus its tags, so neither reads the name.

Considered and rejected. Rendering the external name. println of an enum has printed Enum::Variant since the start, and tests and logs match on it; the external name is asked for where it is meant. E::variants() as a call. The set is a constant of the type, not a computation, and a value reads as one in for v in E::variants; the call spelling is refused with the fix rather than accepted as a second spelling. A keyword or a derive-style list. An annotation the parser applies is enough, and leaves wire_case and its case words free as names. A wire_case that the codecs read beside the tags. Every reader of a variant’s wire name would have had to learn it, and one that did not (a generated client, the digest) would be a second spelling again; applied as tags, it has one.

F.54 — A type’s human rendering is a declared template

Section titled “F.54 — A type’s human rendering is a declared template”

Problem. Every value rendered through one structural rule, Name { field: v } and Enum::Variant(p), and a program had no way to say how its own domain types read: a Money printed Money { dollars: 12, cents: 0, currency: "USD" } where its author meant $12.00 USD (RFC #2035). A Display-style method was the obvious fix and the wrong one: types have no methods (spec/types.md), and turning a value into text (to_string, String + x, an f-string) is pure and total today, which a user function called implicitly by every rendering would undo.

Decision. A type’s human rendering is a declared template on its declaration, never code; :? is recursively structural. @display("${dollars}.{cents:0>2} {currency}") on a record, or before an enum’s variant (@display("other: {0}") Other(String)), is literal text and holes, each a field (a payload position on a variant) with an optional f-string format spec. No expression, call or conditional can be written in one, so rendering stays total. Every rendering path reads it: println, print, to_string, String + x and an f-string’s interpolation; a nested value renders by its own type’s template, or structurally. The template is checked as the f-string it stands for: each hole names a field that exists and renders, each spec fits. It is allowed only on a type that is already printable, so it never widens the printable set, and {x:?}, the structural form at every depth, always exists. It attaches to the declaration: an alias and an import render as the declaration does. Its output is allocated where the rendering is, as the hand-written f-string’s would be, and the allocation summary and the hot-path budget count it so: the template is a function the compiler writes (T::display(v) names it, a value of type fn(T) -> String), and a rendering is a call of it.

Considered and rejected. A Display interface or a method found by name. Types have no methods, and an implicit call by name is a kind of dispatch Hale has nowhere else. Expressions in a template. A conditional or a call is what would let rendering fail or run code. A template that widens the printable set (a record holding Bytes rendering through the fields it names): its :? and an assertion’s message would have nothing to show; left for its own decision. An enum-wide template with a {variant} hole. Whether the hole means the declared name, the wire name (F.53) or another label is a decision of its own; per-variant templates express every case it was for. A template on a set. A set renders as its member does. A template on a locus. A locus is never printable.

F.55 — Perspectives are removed; an interface and generics carry a contract

Section titled “F.55 — Perspectives are removed; an interface and generics carry a contract”

Problem. Hale had two ways to declare a contract a locus provides. An interface is structural: a locus whose methods cover it satisfies it, and an interface-typed param takes whichever implementation the construction names. A perspective P { … } was a second one: bodyless contract fns (with params { }, stable_when { }, serialize_as T; and a bus { } surface as members), conformance declared with locus L : serves P, and holders typed perspective(P) that dispatched through one program-global slot per perspective, designated by a holder’s default or a constructor’s override, or held without designating (GH #731). reperspective self.<field> as <Impl>; re-pointed that slot at another implementation while the program ran, keeping its state. The contract half duplicates what an interface already does, at the cost of a second conformance rule, a second fallibility rule (F.42’s stated gap), slot and vtable machinery in codegen, and five keywords. The live swap was the only thing a perspective did that an interface does not, and its transport-driven path (stable_when, serialize_as, a redeploy from the wire) was never completed.

Decision. Perspectives are removed, without a deprecation cycle. perspective, reperspective, serves, serialize_as and stable_when are no longer keywords: perspective was a hard keyword and is an ordinary identifier now, and the other four were contextual and stop being special anywhere (params stays; loci use it). The perspective declaration, the serves clause, the perspective(P) type, the program-global slot, designation and the reperspective statement are gone, and so are the checks that existed only for them: serves-conformance, the perspective fallibility rule, the warning about a violation in a perspective-served method, and the GH #731 refusal of a slot held without designating. A program that still writes one of the old forms gets a located parse error that names the replacement: “`perspective`: perspectives were removed (spec/decisions.md F.55); declare an `interface` and take it as a param, generic where the implementation’s type matters; `reperspective` has no replacement”, led by the word written (perspective, serves, perspective(P) or reperspective).

Migration. A perspective P { … } becomes an interface P { … } of the same fn signatures. Its implementations drop : serves P and satisfy the interface structurally. A perspective(P) field becomes an interface-typed param (router: Router = RouterV1 { }), which a construction overrides by naming another implementation; a generic param carries the implementation’s type where it matters. Each holder holds its own implementation: there is no program-global slot. reperspective has no replacement.

Considered and rejected. Keep the live swap and drop the rest. The swap is what needs the program-global slot, designation, the one-footprint rule and the bus re-registration; on its own it would keep all of that machinery for a path whose transport-driven half was never completed. A deprecation window. A warning would have carried the slot machinery through a minor release for forms with a direct replacement; the parse error names that replacement at the site. Keep perspective reserved. The word has no other use, and a hard keyword costs every program a field or local of that name.

F.56 — A contextual keyword has a production

Section titled “F.56 — A contextual keyword has a production”

Problem. spec/keywords.txt lists the contextual keywords, and the highlighters and the editor colour what it lists. Five of its words had stopped being keywords anywhere: schedule (the per-locus : schedule … annotation went with F.31), http, principals and roles (the structural bindings { api: … } entry they belonged to was retired with GH #1417; today http is a stdlib module and principals and roles are params of the transports and hubs) and serve (the call api::serve( … ) is recognized by its path, as the std::api fn; the bare word introduces nothing). The list coloured them as syntax although the parser reads each as a plain name.

Decision. A word is in the contextual list only while the parser or the checker recognizes it in some position. The five words leave the list. Every other contextual word keeps a live production, named in the audit that accompanied this decision. Nothing about a program changes: a contextual keyword lexes as an identifier, and these five were already read as names everywhere.

Considered and rejected. Drop words a production still reads but few programs write (the recognition sub-modes, the binding constraints, the rounding policies). The test is whether the word is recognized, not how often it is written: dropping a word whose position still parses would leave the list short of the language.

F.57 — A module is a directory; module { } is removed

Section titled “F.57 — A module is a directory; module { } is removed”

Status: accepted and implemented (2026-11-18).

Problem. Hale had two forms for the same idea. A module is a directory: a seed is the .hl files of one directory, and another seed reaches it by import "<path>" as <alias>;, through which its names are spelled alias::Name (spec/projects.md, spec/semantics.md § “Cross-seed namespace resolution”). module NAME { … } declared a second, in-file namespace beside it, with rules of its own: its declarations were registered under their bare names in the seed’s one flat scope, so it grouped without scoping; a fn main or a main locus inside one was refused as not the entry; a target inside one was a parse error. Every pass that collects declarations had to recurse into module bodies (GH #764, #825, #854, #884, #901, #911), and each one that forgot was a program analyzed at the top level and unanalyzed one brace deeper.

Decision. The module NAME { … } declaration is removed from the grammar, the AST, resolution, the checker, every analysis and lowering. A module is a directory, reached by import; within a seed, declarations live at the top level of its files. module stops being a hard keyword: it lexes as an ordinary identifier, so a local, a field, a parameter or a fn may be named module (spec/keywords.txt and crates/hale-syntax/src/keywords.rs drop it). The removal follows the pre-1.0 policy (STABILITY.md): the break migrates the repository’s own code in the same change and takes no deprecation step.

What a program now gets. module NAME { at top-level declaration position is refused with one located parse error at the word module, and the braced body is skipped whole, so nothing inside it reports again:

parse error: `module` declarations were removed: a module is a directory, reached by `import "path" as name;`. Move the declarations inside `module NAME { }` to the top level, or into their own file or directory and import it (spec/decisions.md F.57)

Migration. Move the declarations out of the braces to the top level of the file (a module never scoped its names, so every use site already spells them bare), or into a file of their own in the same seed directory, which shares the seed’s scope; for a namespace that does scope its names, put them in a directory of their own and import it, spelling each alias::Name. A main locus or fn main that sat inside a module is the seed’s entry once it is moved to the top level.

Considered and rejected. A deprecation warning for a release. The pre-1.0 policy migrates the repository’s own code in the change that breaks it. Keeping module as a reserved word. Nothing is planned for it, and a hard keyword costs every program the name.

F.58 — .Variant names a variant of the matched value’s enum, in patterns

Section titled “F.58 — .Variant names a variant of the matched value’s enum, in patterns”

Status: accepted and implemented (2026-11-20; GH #2069, from RFC #1995 E4).

Problem. A pattern naming an enum’s variant spells the enum every time: Outcome::Result(r) -> r, once per arm, in every if let and let … else. The corpus RFC #1995 counted has 443 enum-constructor arms, and enum names average 10.8 characters; the scrutinee’s type already says which enum the arm is about. A bare Result(r) is not the answer: it is refused against an enum so that a set’s member, which is matched by its type’s name alone (GH #1530, #1971), never reads as a variant.

Decision. Against a value whose type is an enum (directly, through an alias, or a generic enum’s instantiation), a pattern may name a variant with a leading dot: .Variant, .Variant(p, …). It means exactly E::Variant / E::Variant(p, …), E the value’s enum, in every position a constructor pattern is written: a match arm, an alternative of an or-pattern, if let, let … else, a pattern let; inside a tuple pattern or a variant’s values it is the nested pattern E::Variant would be, refused the same way. The dot is written against the name (. Buy is a parse error). The two spellings mix freely in one match, and exhaustiveness, redundancy and the binding rules count a .Variant as the E::Variant it means.

The checker resolves each .Variant against the type it typed the scrutinee with and records the variant per body and span (typed_bodies’ variant_patterns); lowering reads that record and does not name the enum from the spelling. In a generic body whose scrutinee is of a type in its parameters, each specialization resolves it against its own instantiation.

What a program now gets. .Variant against a value of no enum is a located type error saying so: an Int, a set (whose members are matched by their types’ names, Book(b)), a generic body’s type parameter once a call specializes the body. A name that is no variant of the value’s enum is a located type error with the nearest variant, as GH #2023 gives E::Wrok:

type error: `.Wrok(…)`: enum `Place` has no variant `Wrok` — did you mean `.Work`?

With the form, a variant’s pattern that names the wrong number of values (.Work(1, 2) or Job::Work(1, 2) against Work(Int)) is refused by the check at the pattern; the build used to be the first to refuse it.

Not in this decision. .Variant as an expression (let s: Side = .Buy;). It needs an expected type at every value position and can follow separately.

Considered and rejected. A bare Variant(x). It would undo the distinction that keeps a set’s member apart from a variant (GH #1530’s sets, GH #1971). Importing an enum’s variants into scope (use E::*). It makes every variant name a top-level name in the file, where they collide with fns, types and other enums’ variants; the dot is scoped to the one value being matched.

F.59 — A std::str or std::bytes fn is called on the text value it takes first

Section titled “F.59 — A std::str or std::bytes fn is called on the text value it takes first”

Status: accepted and implemented (2026-11-20; GH #2068, from RFC #1995 S4).

Problem. Every string operation is spelled through its namespace: std::str::trim(s), std::str::lower(std::str::trim(raw)). The corpus RFC #1995 counted spells std::str:: about 11.7K times. s.trim() is the first thing a newcomer types (the check pointed at the path since GH #1995 S3), nested calls read inside out, and an editor cannot offer the namespace’s fns after s. because there is nothing there to offer.

Decision. For x of type String, StringView or std::str::ByteView (a String’s byte view) with no field f, x.f(args) means std::str::f(x, args); for Bytes, BytesView or BytesMut, std::bytes::f(x, args); when that fn is public and takes a value of x’s type first. Chains read left to right: raw.trim().lower(). Only these types and only these namespaces: a record type still has no methods, a locus’s methods are its own, and a fn of the program’s is never called on a value (no UFCS). len(s) stays the builtin, and s.len() is refused pointing to it.

The check decides, since only it knows a receiver’s type: it types the call as the path call and records it by the call’s node id (TypingRecord::receiver_calls). The snapshot then writes each recorded call as that path call (hale_types::receiver_calls) and types the program again, so every later pass (the effects, allocation and ownership analyses, the summaries, lowering) reads the path call: a receiver call classifies as the path call because it is one. A program with no method call whose name is a std::str or std::bytes fn is not typed for this; one whose calls resolve none keeps its one walk. The editor settles a snapshot after it is offered the previous one, so its walk reuses what it can.

In a for loop’s source and an element chain’s source, x.split(sep), x.lines() and x.words() on a string are the text sources. Those loops are desugared before the check, and only the check knows whether x is a string, so a loop or a chain over such a receiver call is left as written until the snapshot has written the receiver calls as path calls; then it is desugared, a text source’s scan over a string, and the loop over the method’s result it always was over anything else (a locus’s own words()). The snapshot types again until a walk resolves no receiver call, since a call inside such a loop is typed only once the loop is.

What a program now gets. On a text value, a name that is no fn of its namespace taking that type first is a located type error with the nearest fns:

type error: no fn `trimm` in `std::str` takes a `String` first, so `.trimm` names nothing on it — the nearest are `.trim`, `.trim_end`, `.trim_start`

A fn of the program’s is pointed at its call (shout(x, …)), a value of a record or an Int keeps “no field”, and a receiver call in a generic body on a value of a type parameter calls nothing and is refused once a specialization would make it text. The editor completes the namespace’s fns after x. on a text value.

A ByteView‘s v.find(…) passed the check before this (the stdlib handles’ member sugar, GH #470, named the fn) and lowering refused it as a method call on a value that is no locus; it is now the path call too.

Considered and rejected. Methods for every type, or UFCS for every fn. Either makes the method namespace open-ended, so a call’s meaning depends on every fn in scope, and gives types the methods the language keeps off them; this is two namespaces, on the types they are for. A desugar before the check. It cannot tell a String’s .trim() from a locus’s method trim. Teaching each analysis the receiver form. Each classifier of a call by its callee (the summaries, the effects, the capability uses, lowering) would need the same rule twice; rewriting the call once keeps one.

F.60 — U64 is checked like a 256-bit integer, typed from its literals’ places

Section titled “F.60 — U64 is checked like a 256-bit integer, typed from its literals’ places”

Status: accepted and implemented (2026-11-21; GH #2121).

Problem. A program that holds a hash, a counter past 2^63, or a uint64 a foreign system hands out had no type for it: Int is signed and wraps, and the reserved Uint was a name the parser read and the checker refused, with no representation behind it.

Decision. U64 is a primitive, 0 through 2^64 - 1, the same 8 bytes as an Int read as unsigned, and Uint is gone. Its arithmetic follows F.46, not Int: + - * past either end and / or % by zero are a runtime violation; U64::wrapping_add / wrapping_sub / wrapping_mul (and wrapping_shl / wrapping_shr, the count modulo 64) wrap modulo 2^64 for hashes and bit work, and U64::checked_* fail into an or. Division, remainder, comparison and >> are unsigned. It never converts implicitly, to or from Int or any other type; the check names the conversion (U64::from_int(n), U64::to_int(x) or ..., Float(x), U64::from_float(f) or ...).

Where this decision chose (spec/types.md § U64):

Considered and rejected. Wrapping, as Int does: the issue’s decision; a wrapped counter or balance is a wrong one, silently, and the programs that want modulo arithmetic say so with wrapping_*. A JSON number at or below 2^53 and a string above it: a field whose JSON kind depends on its value is a number to one reader and a string to the next. A literal suffix (5u64): a unit may be named u64, as F.46 found for u256; typing a literal from its place needs no new syntax. U8 / U16 / U32 now: Int { range: 0..256 } covers the small cases.

Deferred & future work

Section titled “Deferred & future work”

semantics — What’s deferred

Section titled “semantics — What’s deferred”

types — What’s deferred

Section titled “types — What’s deferred”

Per notes/open-questions.md and design-rationale §16:

memory — Future work

Section titled “memory — Future work”

forms — Open questions deferred to a future milestone

Section titled “forms — Open questions deferred to a future milestone”

These are spec-level questions that don’t block FORM-4 because the core surface above is independent of them.

  1. Iteration surface. for entry in registry { ... } is natural but the loop construct’s lowering depends on what the existing for over capacity slots does — and a hashmap iteration that visits each occupied slot once needs cluster- aware traversal. Deferred.
  2. Bulk operations. clear(), extend(other), take(key) -> S fallible(KeyError) (get + remove fused). Useful but not foundational. Add after a workload demands.
  3. Additional key types. Bytes, custom structs with a hashable derivation, enum tags. Each adds a key_type_tag to the runtime ABI. Workload-driven.
  4. Capacity hints. @form(hashmap, cap = 64) is rejected in v1; no tuning knobs. Add when a workload demonstrates the 0 → 8 → 16 → … grow cascade is costing measurable time.
  5. Set type. A @form(set) would be a hashmap-without- value variant (the cell IS the key). Not part of FORM-4; revisit if a workload needs it. SHIPPED 2026-08-03 (#353). The trigger fired. It reuses the hashmap slot and the whole lotus_hashmap_* runtime — sync disciplines included — and differs only in the synthesized surface: insert / contains / remove / len / is_empty. The separate surface exists to keep the VALUE off the call site; membership through a hashmap means writing get(k) or false everywhere.

@form(ring_buffer)

Section titled “@form(ring_buffer)”

A fixed-capacity FIFO with push-back and pop-front semantics. The Hale analogue of a bounded circular buffer — same shape as a Go channel of capacity N, or a Java ArrayBlockingQueue, but without the synchronization machinery (the cooperative scheduler already serializes access). Shipped as the third form in v1 via v1.x-FORM-5.

forms — Open questions deferred to a future milestone

Section titled “forms — Open questions deferred to a future milestone”
  1. Iteration surface. for x in recent { ... } is natural but iteration over a ring buffer must respect head/tail wrap — needs the for lowering to know about ring shapes. Deferred.
  2. Bulk operations. clear(), peek() -> T fallible, evict-oldest-on-full mode (cyclic-overwrite as a tuning knob). Useful but not foundational; add when a workload demonstrates demand.
  3. Iteration in pop order without removing. A “drain” or “iter_pop” that visits elements oldest-first as a one-shot.
  4. Bench protocol. A micro/form_ring_buffer_* family in hale-lang/bench, parallel to vec’s and hashmap’s. Ships as a separate milestone after a consumer workload surfaces.

@form(lru_cache)

Section titled “@form(lru_cache)”

A fixed-capacity keyed cache with least-recently-used eviction. The keyed counterpart of @form(ring_buffer): like @form(hashmap) it is intrusively keyed (the cell carries its own key via indexed_by), but like @form(ring_buffer) it is capacity-bounded and NEVER grows. Inserting a new key over cap silently evicts the least-recently-used entry to make room. This is the “cap-bounded, never-flagged” keyed form — the unbounded-allocation analysis (spec/verification.md) treats an @form(lru_cache) locus as bounded, exactly like ring_buffer. Shipped as the fourth form in v1 via v1.x-FORM-6.

forms — Open questions deferred to a future milestone

Section titled “forms — Open questions deferred to a future milestone”
  1. TTL eviction. A ttl = <duration> annotation arg to expire entries by age in addition to LRU by capacity. Deferred — v1 evicts by capacity + recency only.
  2. remove(k) / clear(). Explicit eviction of a named key and bulk clear. Add when a workload demonstrates demand.
  3. Iteration surface. key_at / entry_at-style indexed iteration, parallel to @form(hashmap). Deferred.
  4. Bench protocol. A micro/form_lru_cache_* family in hale-lang/bench, parallel to the other forms’. Ships after a consumer workload surfaces.

F.61 — Locus modes are removed

Section titled “F.61 — Locus modes are removed”

Status: accepted and implemented (2026-11-21, GH #2133).

Problem. A locus could declare mode bulk, mode harmonic and mode resolution, each with optional params and a return type, called as self.bulk() or, through the contract, child.bulk(). The spec promised more than a method: one implementation per declared mode (grammar.ebnf § 7, semantics.md § Mode invocation), optimized per mode, and F.5’s compile-time check that two modes’ writes do not race. None of that was built. A mode lowered as an ordinary locus method named after its kind, so the spec described behaviour the compiler did not have. Completing it had no target either: resolution as a latency contract is what effect assertions already express, harmonic has no checkable definition, and F.5’s race check is moot because mode calls are synchronous on one locus and never interleave. The one real idea is bulk’s, that a kernel must vectorize, and it is a property any function can state (GH #2134), not a member kind. In the repository and the known packages, modes were written only in test and example fixtures (19 declarations); none in dna, iris or the stdlib.

Decision. Modes are removed from the grammar (mode_decl), the AST, the parser, name resolution and the site walks, the checker, the analyses (mangling, ownership, the allocation summary and routing, the model’s function sort, which loses FunctionKind::Mode) and lowering. mode, bulk, harmonic and resolution stop being keywords (spec/keywords.txt, crates/hale-syntax/src/keywords.rs, the highlighters): they are ordinary identifiers in every position, and a locus method may now be named bulk, harmonic or resolution, which F.43 refused while the name was a mode’s. The exposed-mode pull rule goes with them (F.14’s mode clause): an expose bulk: T; entry binds a params field or a fn bulk like any other name. F.5 is withdrawn. The removal follows the pre-1.0 policy (STABILITY.md): the repository’s own code migrates in the same change, with no deprecation step.

What a program now gets. mode NAME followed by (, -> or { at locus-member position (decorated or not) is refused with one located parse error at the word mode; the member then parses on as the fn it names, so nothing in it or after it reports again:

parse error: locus modes were removed in 0.38: write `fn bulk(...)` (a mode compiled as an ordinary method; spec/decisions.md F.61)

Migration. mode X(params) -> T { body } becomes fn X(params) -> T { body }, with the same decorators (@unbounded, @bounded_by(<name>)) and the same calls (self.X(), child.X()). One shape differs: a mode was the one locus member that could return a locus value, and a locus method may not (semantics.md § Locus method dispatch), so a mode returning a locus becomes a free fn over the locus, fn X(l: L, params) -> M { … }, called X(l).

Considered and rejected. Completing modes. Each part either duplicates an existing feature, has no checkable meaning, or checks something that cannot happen (above). Keeping the three words reserved for a later meaning. Nothing is planned for them, and a reserved word costs every program the name.

F.62 — The unit dialect’s base integer is a parameter

Section titled “F.62 — The unit dialect’s base integer is a parameter”

Status: accepted and implemented (2026-11-21; GH #2131).

Problem. F.60 admitted U64 and refused it as a unit-dialect base: every quantity, point, identity and range counted an Int, and the representation, the range checks and the conversion factors were signed Int arithmetic. A wei balance, a nonce or a port held as a U64 could not also be the quantity, identity or range it is, and the fixed-width integers to come (GH #2132) would each have needed the same change again.

Decision. A scalar counts a base integer, a parameter of the dialect (spec/units.md § The base): Int or U64 now, and any machine integer the language adds, with no rule of the dialect’s changed. The base is the machine integer the root of a scalar’s chain is written over (quantity U64 in wei, distinct U64, U64 { range: … }); a refinement, a boundary denomination, a point and a range over a scalar count their parent’s. Every rule reads the base’s width and signedness from the primitive (PrimType::machine_int): its representation, its literals’ and range bounds’ values, its arithmetic (a U64‘s unsigned, an overflow a violation), its conversions’ multiplications and divisions (a U64’s unsigned, a factor held to its range), its wire form, its shape tag, its FFI class and its report’s headroom.

Where this decision chose:

Considered and rejected. A base per quantity, mixed within a component: the stdlib’s time literals and every literal of a unit are their component quantity’s, so a U64 boundary denomination of Duration would make t + 1ms a mix of two integers; the conversion between them would be a second narrowing beside the factor’s, with two policies after one or. Special-casing U64: GH #2132’s integers would each repeat it.

F.63 — @vectorize: a fn’s innermost loops must vectorize, or the build says why not

Section titled “F.63 — @vectorize: a fn’s innermost loops must vectorize, or the build says why not”

Status: accepted and implemented (2026-11-21, GH #2134).

Problem. A hot loop that silently stops vectorizing is a 4–32x regression no test sees: the program computes the same thing, scalar. Fixed-width integers (GH #2132) and the v1 performance targets make which loops vectorize a property worth stating and holding. The one real idea in locus modes was bulk’s, “this kernel vectorizes”, and modes never checked it (F.61).

Decision. @vectorize and @vectorize(min_width: N) are fn contract annotations (spec/semantics.md § Vectorized loops):

  1. Surface: an annotation on the fn, not an effect. Every innermost loop written in the fn’s body is held, an element chain’s loop included. It is its own annotation rather than @effects(vectorized): an effect assertion is a set over what a call may do, closed under the call graph and judged by the check, while this is a property of the fn’s own loops, judged by the build on one target and not inherited by callers. The fn form is fine-grained enough for the kernels it is meant for (one loop, or a few, per kernel fn); a loop that should not be held moves to a fn of its own. A per-loop form was not needed.
  2. How the build knows: LLVM’s own remarks, never syntax. Measured on LLVM 18 through inkwell before the surface was chosen:
    • The loop vectorizer reports every innermost loop it looks at as a remark — vectorized loop (vectorization width: W, interleaved count: I), interleaved loop (interleaved count: I) (VF 1, still scalar) or loop not vectorized[: reason] — and a diagnostic handler on the build’s context receives them in-process once the -pass-remarks* options name loop-vectorize (LLVMParseCommandLineOptions, once per process, before any pass runs: the patterns are process-global). With a callback handler LLVM delivers every pass’s remarks; the build keeps the vectorizer’s by their wording. Turning them on cost nothing measurable (92-build-an-api: 1.2 s of passes either way).
    • A remark starts with its location (file:line:col), the loop’s or the instruction that stopped it, so the build traces it back to the loop by its debug locations: the real ones where the build emits DWARF (hale build), else a synthetic file whose line n is the loop’s number, set on every instruction of the loop and stripped before the object is written. A Hale-source stdlib fn, which carries no DWARF, takes the synthetic form in every build.
    • Spike, @vectorize on five kernels, host apple-m1, O3, the opt tool’s x86-64 run beside it on the same IR: an Int sum over a bounded[Int; 1024] vectorized (width 2, interleave 4, both targets); an element chain .map(it + 1).sum(0) vectorized; a Float sum vectorized on aarch64 (in-order reduction) and not on x86-64 (“cannot prove it is safe to reorder floating-point operations”); .map(it * 3) over Int was interleaved but not vectorized on NEON (“the cost-model indicates that vectorization is not beneficial”) and vectorized on x86-64; a loop calling a fn that prints was refused (“instruction cannot be vectorized”); a loop whose trip count it computes was refused on both (“could not determine number of loop iterations”). llvm.loop.isvectorized metadata survives too, but it marks interleaved-only loops the same and carries no reason, so the remarks are what the build reads.
    • The reason is given in the program’s terms with LLVM’s words beside it.
  3. Check/build agreement. The check refuses what no target’s vectorizer takes, each at its place: a break or return beside the loop’s own exit (LLVM 18 vectorizes a loop with one exit), a call to a fn with effects, an allocation, a locus built, a publish or a send (calls into the runtime), a call to a fn with a loop (inlined, it makes the loop an outer one, which also would pass unseen: an outer loop gets no remark), and a @vectorize fn with no loop. The issue’s other candidates are left to the build, because they do vectorize at times: v.get(j) or raise in for j in 0..v.len() over an unmutated local @form(vec) loses its failure branch to bounds-check elimination and vectorizes (the bench’s form_vec_get), a loop-invariant text read is hoisted (len(name) in an Int sum vectorized, width 2), and a fn value known where the fn is inlined is called directly. What remains is a target-dependent build assertion, and the check/build parity gate counts it apart (Verdict::TargetAssertion), never as a divergence.
  4. Targets and optimization levels. The assertion is judged on the build’s target and CPU (the host’s by default, --target-cpu, a cross target’s generic CPU) at the build’s level. The pipeline vectorizes at O2 and above (measured: default<O1> reports every loop “loop not vectorized” with no reason), so a dev build (--dev, HALE_DEV, hale test, all O1), an AddressSanitizer build (no pipeline) and a wasm build (no simd128) do not check it, and hale build prints a note saying which and why. A cross build reports on the target it builds for, naming it. 4b. Width. min_width: N was cheap: the remark names the width. A loop vectorized narrower than N lanes (in any copy) fails the build with the width it got.

What it does not do. It asks no transformation: no llvm.loop.vectorize.enable hint, which would make LLVM reassociate Float reductions (changing results) and override the cost model, turning an assertion into a behaviour change. A loop the optimizer removed (folded, fully unrolled) passes, and is judged in each inlined copy; a fn nothing calls is not built and asserts nothing.

Considered and rejected. @effects(vectorized) (above). Reading vector types in the optimized IR to decide: it cannot tell a vectorized loop from SLP-vectorized straight-line code nor give a reason. Forcing vectorization at O1 so hale test checks it: the hint changes Float results. Refusing fallible steps and text values at check: unsound, as measured above.

F.64 — The fixed-width integers I32, U32, I16, U16, I8 and U8

Section titled “F.64 — The fixed-width integers I32, U32, I16, U16, I8 and U8”

Status: accepted and implemented (2026-11-21; GH #2132).

Problem. Int is 64-bit everywhere. A bounded[Int; N] of small values is four to eight times larger than its values need, a 128-bit vector register holds two i64 lanes against four i32 or sixteen u8, and aarch64 has no i64 vector multiply at all (F.63’s spike: .map(it * 3).sum(0) over Int is interleaved scalar code there). FFI and binary protocols had no exact-width type.

Decision. Six primitives, I32, U32, I16, U16, I8 and U8, signed two’s complement and unsigned, generalizing F.60’s U64 over width and signedness (spec/types.md § Fixed-width integers). There are no aliases. Each is its declared width wherever it is stored: a record field, a bounded element, a fixed array, a locus field, a topic payload and a local. PrimType::machine_int (F.62) lists them, so the unit dialect takes each as a base with no rule of its own changed, and every rule elsewhere that F.60 wrote for U64 reads the width and the signedness from it: literal adoption, the operator rule, the flow rule, the conversions’ names, the topic tag and the codecs.

Where this decision chose:

Considered and rejected. Aliases (Byte, Word): two names for one type, and type Byte = Int { range: 0..256; } already means something else. Wrapping arithmetic, as Int’s: a byte counter that wraps at 256 is the bug these types are most likely to carry, and the explicit wrapping_* costs nothing where it is meant. Widening at the operators: see above. Packing range types by width (spec/units.md § What the dialect does not do) and F32: separate decisions.