# 05. Effects and Capabilities ## 1. Rationale Effects answer: **what can this function do?** Capabilities answer: **what authority does this invocation possess?** Both are part of the program contract. ## 2. Effects Every function has an effect set. Pure example: ```aji fn checksum(data: slice) -> u32 effects [] ``` Representative effects: ```text mem.alloc mem.map fs.read fs.write io.read io.write net.connect net.listen net.read net.write clock.read random.read task.spawn thread.spawn thread.block atomic atomic.weak process.spawn ffi unsafe ``` A caller's effect set must cover transitive callee effects. Effects are flat atoms and format 0 has no discharging boundary (§9). ## 3. Capabilities Capabilities are unforgeable values created by the host/runtime or delegated by existing authority. Example: ```aji fn load( fs: cap, path: slice ) -> Result effects [fs.read] ``` Without the capability, the operation cannot be performed even if the function declares the effect. ## 4. Narrowing Capabilities may be narrowed but not widened. A broad filesystem capability may yield a capability limited to: - read-only access; - a path prefix; - a mount; - an already-open resource; - a bounded operation set. ## 5. Capability transfer Capabilities may have ownership semantics: - copyable/read-only authority; - move-only authority; - local-only authority; - delegatable authority. The capability type defines its transfer rules. ## 6. Build/runtime separation Compilation does not imply runtime authority. A program may compile with a declared effect set yet fail to instantiate because the host does not grant matching capabilities. ## 7. Auditability The toolchain should be able to emit: - declared effect graph; - capability requirements per entry point; - effective transitive authority; - unsafe/FFI authority boundaries. ## 8. Relation to AIR features AIR features (spec 07 §8.1) are a third, separate concept. A feature says which semantics the implementation must understand; it grants no authority and adds no effect. Declaring `features [capabilities, effects, ownership]` does not let a program read a file: the function still needs `effects [fs.read]` and a `cap` value. ## 9. Effects in AIR (feature `effects`) Decision record: RFC 0006. Invariants of the authority model: 1. **No ambient authority.** An operation that acts outside the program's own memory requires a capability value as an operand. There is no global, implicit or default authority. 2. **Unforgeability.** A capability value can only originate from the host (as an argument of the entry function) or from an existing capability by an explicit, verifier-known narrowing. No instruction creates one from integers, bytes, constants or other values, and no instruction inspects its representation. 3. **No widening.** Narrowing never yields more authority than its input, and never changes the kind of authority. 4. **Effect soundness.** If a function can perform effect `E`, directly or through any callee, then `E` is in its declared effect set. 5. **Separation.** Features say what the implementation must understand; effects say what code does; capabilities say what an invocation may do. None implies another, and not every effect needs authority. 6. **Monotone authority graph.** The only operation that transforms authority is `cap.narrow`. Authority flows from the host down through narrowings; it is never widened, combined, forged or cast. 7. **Instance lifetime.** A capability is valid only within the execution instance that received it from the host. ### 9.1 Effect names Effect names come from a closed registry, `reference/effects.md`, initially the list of spec 05 §2. The registry records for each effect whether exercising it requires authority, and which capability kind provides it: | Effect | Authority | |---|---| | `mem.alloc`, `mem.map` | `cap`, `cap` | | `fs.read`, `fs.write` | `cap`, `cap` | | `io.read`, `io.write` | `cap`, `cap` | | `net.connect`, `net.listen`, `net.read`, `net.write` | `cap`, `cap`, `cap`, `cap` | | `clock.read`, `random.read` | `cap`, `cap` | | `process.spawn`, `process.env` | `cap`, `cap` | | `task.spawn`, `task.wait`, `thread.spawn`, `thread.block` | none | | `atomic`, `atomic.weak` | none | | `ffi`, `unsafe` | none (governed by unsafe boundaries, spec 13) | An effect says what a function does; a capability gives power over an external resource. The relation is not one-to-one: effects such as `atomic` or `thread.block` need no authority. In a module that declares `effects`, an unregistered name in an `effects [...]` list is `E0004`. New names are added to the registry by the feature that introduces their operations. ### 9.2 Effects are flat (Q-011) Effects are atoms. The dotted spelling is organizational only: `atomic` does not imply `atomic.weak`, `io.write` does not imply `fs.write`, and no effect implies another. A function that performs two effects lists both. Reason: implication rules are a second semantics agents must model; a flat set is checked by set inclusion and diagnosed by naming the missing atom. It also keeps weaker mechanisms visible across the call graph: a function declaring `[atomic]` cannot call one declaring `[atomic.weak]` without saying so. ### 9.3 Checking rule In a module that declares `effects`: - For every `call @g(…)` in function `f`: `effects(g) ⊆ effects(f)`, otherwise `E3101` for each missing effect. - For every `intrinsic` in `f` (§11): the intrinsic's effect is in `effects(f)`, otherwise `E3101`. - For every other instruction whose contract names an effect (for example `task.spawn`, `channel.make`, and in a module declaring `cancellation` every suspending operation, spec 04 §37.4): that effect is in `effects(f)`, otherwise `E3101`. - Because every function is checked against its direct callees, the rule holds transitively, including for recursion. - Each `E3101` carries `suggested_effects`: the function's declared effects plus every missing one, sorted. Effects stay declared by the programmer; the suggestion only makes the repair mechanical. **Indirect calls (normative for future features).** When function values are introduced, the effect set MUST be part of the function type, for example `fnptr<(u8) -> void effects [io.write]>`, and an indirect call is checked against that set exactly like a direct call. Otherwise dynamic calls would break transitivity. There is **no effect discharge** in format 0 except one: a `trusted` function (feature `unsafe`, spec 13 §6.3) discharges the effect `unsafe`. No other construct removes an effect from what a caller must declare; a later feature may introduce another discharging boundary only by specifying it explicitly (Q-011). In a module that does not declare `effects`, `effects [...]` lists are recorded and not checked ([`../reference/air-features.md`](../reference/air-features.md)). Such a module cannot contain an effectful operation, because every intrinsic belongs to `capabilities`, which depends on `effects`. ## 10. Capabilities in AIR (feature `capabilities`) ### 10.1 Type `cap` is the type of a capability of **kind** `K`. Kinds come from a closed registry, `reference/capabilities.md`, which lists for each kind the effects it authorizes (see §1.1) and its narrowing forms. An unregistered kind is `E0004`. A capability value is an **unforgeable reference to one runtime authority object** held by the host. Copying a capability copies the reference, not the authority: all copies denote the same authority object and share its state. For example, two copies of a `cap` narrowed to a 64 MiB budget draw on one shared 64 MiB budget, not 64 MiB each (RFC 0008). A capability is **opaque**: - it is copyable: it may be passed, returned, stored in structs, enums and arrays, and copied; - it cannot be cast to or from an integer or any other type, bit-cast, compared (`eq`/`ne` do not accept it), zero-initialized, given as a constant, serialized or inspected as bytes; - its accounted size (spec 08 §7.1) is 8, but those 64 bits are not a number, an address or a serializable representation. **Authority-bearing types.** A type is authority-bearing if it is `cap` or an aggregate or array containing an authority-bearing type. Every rule above is transitive: an authority-bearing type is not zeroable, and any future instruction that exposes the bytes of a value (a `bytes`-of-value view, bit-casts, by-value FFI) MUST reject authority-bearing types. A `struct @Logger { out: cap }` can therefore never be turned into `slice`. Copyable authority keeps format 0 simple: a capability is shared by copying it, and authority is limited by narrowing, not by tracking copies. Move-only (one-shot) and revocable capabilities are not part of format 0; they can be added later as new kinds or a new feature. ### 10.2 Origin: the entry function (Q-012) Capabilities enter a program only as parameters of the entry function `@main`: ```text fn @main(%out: cap, %src: cap) -> void effects [fs.read, io.write] ``` - `@main` parameters MUST all be capability types in format 0; the runner rejects other signatures before execution. - Grants are bound **by parameter name**, so two parameters of the same kind can receive different scopes: ```bash aji run app.air --grant config=fs.read:/etc/app --grant data=fs.read:/var/data ``` For packages the same bindings come from `aji.toml` `[capabilities]`, applied only when the operator runs `aji run --manifest`; a command-line `--grant` for the same parameter replaces the manifest entry (spec 12 §1). - Before execution the host **instantiates** the program: every capability parameter of `@main` must have exactly one grant whose kind matches, and every grant must name a parameter. Otherwise the program does not start. This is an **environment outcome**, not a trap and not a verifier error; `aji run` exits with code 6 and reports, for the first problem in parameter order: ```json {"status":"not_instantiated","reason":"missing_capability","parameter":"data","kind":"fs.read"} ``` with `reason` one of `missing_capability`, `kind_mismatch` (fields `parameter`, `kind`, `granted`), `unknown_parameter` (an extra grant, field `parameter`; typos are not ignored) and `invalid_scope` (the host cannot represent the requested scope, fields `parameter`, `scope`). - Compiling or verifying a module never grants authority (spec 05 §6). **Startup data (future).** RFC 0006 defines capability instantiation only. Future features MAY allow immutable non-authority startup values (for example `port: u16`) as `@main` parameters; such values are input data, are recorded in the execution record for replay, and grant no authority. Command-line arguments are startup data of this kind. The host environment is not: it often holds secrets, so reading it requires `cap` and an intrinsic. ### 10.3 Lifetime A capability obtained at instantiation, and every copy and narrowing of it, is valid from the start of the execution instance until its end. Because capabilities cannot be serialized (§10.1), none can be stored and used by a later run. ### 10.4 Narrowing `cap.narrow` is the only instruction that transforms authority. It is fallible and is a **terminator**, delivering its result to block parameters as `enum.switch` delivers payloads, so a failed narrowing can never be mistaken for a usable capability: ```text cap.narrow.
%c, %arg…, ok -> @ok, err -> @err ok(%n: cap): ; same kind K, at most the authority of %c err(%e: cap_error): ; why the restriction was refused ``` `cap_error` is a built-in enum with the variants `invalid_restriction` (the argument is malformed or forbidden, for example a path containing `..`), `not_subset` (the requested scope is not within the current one, for example `/etc` below `/data`) and `unsupported_restriction` (the host cannot enforce this restriction for this capability). It is used with `enum.switch cap_error %e, …`. Built-in enums are spelled without `@` and have registered variants; they are values like any enum. The capability registry lists, per kind, which narrowing forms exist and what they mean; for example (specified with the kinds in RFC 0007 and RFC 0008): | Kind | Form | Meaning | |---|---|---| | `fs.read`, `fs.write` | `prefix` | restrict to a path below the current scope (`slice` operand) | | `mem.alloc` | `budget` | restrict to at most N bytes (`usize` operand) (RFC 0008) | - A form not listed for the operand's kind is `E3202` (`capability.widen`): there is no instruction that changes kind or adds authority, so any attempt is reported as widening. - Narrowing never traps and never produces a capability with more authority than its input. There is no "empty capability" in format 0: a refused restriction goes to the `err` target. - `ok` and `err` targets follow the block-parameter rules of `enum.switch`: `@ok` takes exactly one parameter of type `cap`, `@err` exactly one of type `cap_error` (`E5002` for the count, `E1001` for the type). - There is no `cap.combine`, union, widening or kind conversion in format 0. ### 10.5 Using a capability An effectful operation takes its capability as an explicit operand (§11). If the operand's kind differs from the kind the operation requires, the error is `E3201` (`capability.missing`) rather than a generic type mismatch, so an agent sees that authority, not data, is missing. ## 11. Intrinsic calls (feature `capabilities`) ```text [%r =] intrinsic (%a1, …, %an) ``` - `` is a dotted name from the intrinsic registry (`reference/intrinsics.md`); an unknown name is `E0004`. - Each registry entry specifies, as for any instruction (spec 07 §4): operand types, which operand is the capability and its kind, result type, required effect, ownership and borrow effects on operands, memory read/write set, trap cases, failure model, blocking behavior, and behavior in the `deterministic` profile. - Verification: operand types (`E1001`), capability kind (`E3201`), effect (`E3101`), borrows as for `call` (spec 08 §11.2). - Execution: the interpreter forwards to the host through the capability; the capability's scope is enforced by the host, never by trusting the program. This RFC registers no I/O intrinsic yet. RFC 0007 adds the catalogue (console, files, sockets, clock, random) together with the error representation. ### 11.1 Fallible intrinsics Two forms extend RFC 0006 §3: ```text [%r =] intrinsic (%a…) ; infallible intrinsic (%a…), ok -> @ok, err -> @err ; fallible: a terminator ``` A fallible intrinsic delivers its results as the parameters of `@ok` (count and types per registry; `E5002`/`E1001`) and a single `io_error` to `@err`. The registry says which form each intrinsic has; using the other form is `E1001`. Resource operands consumed by an intrinsic are consumed on both edges. The catalogue of intrinsics is [`../reference/intrinsics.md`](../reference/intrinsics.md). ### 11.2 Allocation budgets The authority object of a `cap` carries a budget of simultaneously live bytes, shared by all copies and charged along the chain of narrowings; see spec 03 §18. ## 12. Runtime - A capability is represented as an index into a host-owned table of (kind, scope) entries. The index is not observable by the program. - Narrowing appends a new table entry. Entries are never removed during a run. - In the `deterministic` profile, grants refer to virtual resources (an in-memory file system, a captured stdout, a seeded clock and random source), so runs are reproducible. ## 13. Atomic effects (feature `atomics`) The rule of spec 04 §25, checked like any other named effect (§9.3): ```text seq_cst atomic operation → effects [atomic] non-seq_cst atomic operation → effects [atomic, atomic.weak] atomic.fence (any ordering) → effects [atomic] atomic.new, atomic.take → no effect ``` For compare-exchange, the operation is non-`seq_cst` if either ordering is. A missing atom is `E3101`. If `atomic.weak` is not among the transitive effects of `@main`, every atomic access is `seq_cst`, and every execution of the safe program is explainable as an SC interleaving (spec 04 §22). ## 14. Explicit error values (feature `error_values`) An error is Copy data, not authority or proof that an operation occurred. Safe code MAY create any registered payload-free variant of `alloc_error` (spec 03 §18), `cap_error` (§10) or `io_error` (spec 06 §7). Creating an error MUST NOT allocate, perform I/O, narrow a capability, change resource state or grant authority. Actual fallible operations retain their specified outcome rules. In AIR, `%e = error.const B.variant` has two static operands: a built-in error family `B` and one of its registered variant names. It takes no SSA operands or payloads and produces exactly one Copy value of type `B`. The module MUST declare `error_values` and its full dependency closure (`capabilities`, `effects`, `heap`, `ownership`, `resources`). These dependencies make all three existing error families available; they grant no capabilities. The verifier MUST validate the family and variant (`E0004` for an unknown name in text), result uses (`E1001` for a type mismatch) and feature declaration (`E0006`). Its transfer function introduces one available Copy value; it changes no ownership, borrow, memory, concurrency or authority state. Effects and capabilities required: none. Instruction-specific traps: none. The interpreter deterministically binds the selected family/tag as ordinary built-in error data; the instruction consumes normal fuel. The payload syntax is not permitted (`E0001`). Source uses the existing variant expression `alloc_error::budget_exceeded`, `cap_error::not_subset` or `io_error::invalid_input`, lowering to `error.const`; the frontend MUST include the feature closure. Every registered variant is constructible; errors cannot be converted into capabilities. Source rejects unknown variants with `E7002`, payloads with `E7005`, and wrong result types with `E7005`. Valid: a pure function returning `alloc_error::budget_exceeded` before overflowing an allocation size. Rejected: returning that value from a function returning `cap` (`E7005` / AIR `E1001`). Existing `enum.make` remains restricted to declared enums. This is an additive format-0 feature; no existing instruction, error tag, fallible outcome or authority rule changes.