Files
aji/docs/rfcs/0021-package-source-modules.md
T
dev ad75ffe021
ci / build (ubuntu-latest) (push) Successful in 4m52s
ci / extended (push) Failing after 3h0m2s
ci / build (macos-latest) (push) Canceled after 0s
docs: adopt intermediate standard library foundation
Record the owner-requested STD-0..7 merge boundary and adoption of implemented
RFCs 0016-0035, whose normative rules and vertical implementations land together.
Update repository and std status; keep remaining Std 0.1 and service milestones
in the backlog. Track Q-034/P6-11 as the next source-language task and retain
the existing P7/P8 gate.

Implementation checks are recorded in RFC 0035 and the std plan; this change
updates adoption metadata and planning only.
2026-10-07 13:42:50 +03:00

13 KiB

RFC 0021: Explicit package source modules

Status: Implemented Scope: STD-3 / P6-3; source language 0.1, AIR format 0 unchanged Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.

The branch contains the proposed normative text, implementation and tests. Only the language owner changes RFC acceptance status.

Motivation and decision

Reusable library types need module identity, local name binding and explicit compiler inputs before generics or owning collections can have stable contracts. Extend the existing compiler-pinned standard import mechanism to an explicit source provider. The CLI obtains this provider solely from a selected manifest's [modules] map; the frontend accepts source bytes and diagnostic paths, without filesystem access. General package dependency resolution is separate work.

Spec 12 §1.3 defines the manifest and loading contract; spec 15 §14 defines the graph and namespace rules. The standard registry remains compiler-pinned and cannot be shadowed. Every declaration and field is available through a direct import. All reachable declarations, including unused helpers, lower and verify. There are no aliases, re-exports, visibility modifiers or executable module initialization.

Imports form an acyclic graph. Header mismatch, duplicate imports/mappings and cycles reject; unreachable mapped files must be readable explicit inputs but are not parsed. Fixed limits are 1,024 mapped modules, graph depth 256, 1 MiB manifest and 64 MiB aggregate source snapshot. Cached graph heights count shared tails toward the depth limit. Modules append in lexicographic order, declarations in source order, using existing collision-free AIR mangling. Entry AIR names remain unchanged; only its unqualified main is the entry.

Each module sees its own short names and directly imported full names. Linked transitive declarations do not become name-visible. A function can return a type inferred by its caller without the caller importing that type's module, but explicitly naming/constructing it requires a direct import. Qualified names resolve independently of local values with the same prefix. Module identity is carried separately from diagnostic filenames, so identical file labels cannot alter binding. Imported function main is an ordinary qualified function.

Qualified struct literals use app.model.Pair { left: 20, right: 22 }, retaining the existing uppercase-final-component and condition-brace grammar rules. task.spawn(s, app.work.run, args) resolves a static function and emits the existing task.spawn instruction with its actual mangled AIR name. Built-in namespaces remain reserved for provider bindings; legacy entry names and built-in precedence stay compatible.

Memory, ownership and concurrency invariant

Importing does not create authority, allocate program heap, retain borrows, share mutable storage, change resource consumption or introduce implicit cleanup. Every cross-module call has the same explicit signature and ownership/effect obligations as a local call. Named linear arguments still require move; mutable borrows remain exclusive and within lifetime; task lends remain unavailable until join; all linear values/resources are consumed on every path.

Verifier rule

The frontend binds nominal types and static functions, then submits one combined ordinary AIR module. The existing type, call, initialization, alias, lifetime, resource, effect, Send/Share and task transfer functions apply unchanged. Imported code is never trusted simply because it is imported. Every reachable function is checked even if unused. No new verifier state, transfer function, AIR instruction or feature is introduced; the combined module declares existing feature dependency closure. Format-0 meaning is unchanged.

Runtime rule and deterministic behavior

No runtime module loader, dispatch, initialization or new primitive exists. The interpreter executes ordinary mangled function calls, struct/enum operations and structured tasks. The same explicit source bytes and bindings produce identical canonical AIR across mapping/import orders, directories, diagnostic filenames and execution profiles. First graph errors follow source import order. Imported diagnostics and traps name the supplied source file. Existing interpreter fuel, deterministic scheduler and hosted profiles remain unchanged.

The CLI snapshots explicit package input files relative to the selected manifest directory. Portable .aji paths reject absolute paths, empty/dot/parent components, backslashes, colons and NUL. Descent keeps directory handles open and uses no-follow opens; source leaves must be regular files, checked before open and again on their handles. Symlinks, directories and static pipes reject rather than execute or block on input. These checks do not promise an atomic filesystem snapshot under concurrent writes; compilation is deterministic from the bytes actually read. Legacy manifests without [modules] retain their loading contract.

Check/lower/report select source inputs without instantiating grants. Run/explore merge only explicitly selected manifest grants and command-line overrides. A file-only command never discovers a manifest. lower --stats compares entry source bytes against the combined AIR; it is explicitly not a whole-package compression metric.

Valid examples

examples/modules/aji.toml maps app.model to model.aji. The model defines a plain Copy struct and an ordinary function:

module app.model
struct Pair { left: u64, right: u64 }
fn total(pair: Pair) -> u64 effects [] { return pair.left + pair.right; }
module app.entry
import app.model;
fn main() -> u64 effects [] {
    let pair = app.model.Pair { left: 20, right: 22 };
    return app.model.total(pair);
}

aji run --fuel 1000000 --manifest examples/modules/aji.toml returns 42 without grants. Source conformance also passes an owner with explicit move to an imported disposal function and lends disjoint slices to two qualified task workers. The latter has a hand-written AIR twin and deterministic/stress schedule coverage.

Rejected examples and diagnostics

With the same mapping, constructing app.model.Pair without a direct import app.model; is E7002; linking it through another module does not grant name visibility. Repeatedly lending one mutable buffer to qualified workers rejects with the existing race code:

module app.entry
import app.workers;
fn main() -> u64 effects [task.spawn] {
    var buf: [u64; 2] = zero;
    {
        mut s = buf;
        scope sc {
            let a = task.spawn(sc, app.workers.bump, s);
            let b = task.spawn(sc, app.workers.bump, s);
            task.join(move a);
            task.join(move b);
        }
    }
    return buf[0];
}

The independently checked fixture rejects E4101. Borrow conflicts reject E2101; omitted owner moves use E7003; absent declared effects use E3101. Names/imports use E7002; graph/header/duplicate/input-depth errors use E7006; source syntax uses E7001 with expected/found fields at the imported source. Type mismatch remains E7005/E1001. CLI manifest/path/I/O/budget errors use stderr and exit 2 before verification; source rejection uses JSON Lines and exit 1. No new diagnostic code or envelope is added.

Compatibility and integration

Spec 15 §2, §5, §7, §11, §13–§14 and spec 12 §1 integrate the rules. Reference grammar, Quick Reference, source bundle, Q-032 and both implementation plans track the increment. The six standard modules still expose 39 functions and 14 ordinary enums, with no API change. Existing file-only, AIR-only, standard-only and legacy-manifest programs preserve meaning and lowering. Previously unknown package names become valid only with explicit inputs. Short names remain local; distinct module types are nominally different. No migration or semantics-changing flag is needed.

Agent complexity impact

  • New concepts: explicit module-to-file inputs, module-local short names, direct qualified visibility and an acyclic source graph. All declarations are available; there is no separate export list or privacy state.
  • Source forms: existing import path;, qualified calls/types/enum variants extend to package modules; qualified struct literals and a qualified static worker are supported. Manifest adds one [modules] map. No new source keyword, lifetime/ownership syntax, AIR syntax, effect, capability or diagnostic code.
  • Frontend state: module identity on spans, direct-import scope table, graph visit/cache/depth state and existing nominal type/static signature binding. Verifier/runtime state: none.
  • Interactions: structs/enums/arrays, local functions, std imports, collision handling, borrow projections, owner moves, effectful calls, task return types and lent buffers. Imported files remain explicit untrusted source inputs through the ordinary verifier.
  • Repairability: missing imports, cycles, header mismatch and inaccessible members have stable diagnostics; imported source locations point to the actual repair file. No ambient resolution, transitive namespace effects, initialization order or privileged library magic must be reasoned about.
  • Existing AIR primitives suffice. Textual source concatenation would lose scope and nominal identity; a runtime loader or a new AIR module instruction would add trusted complexity without improving this contract. Generics and linear aggregates remain independent prerequisites for owning containers.

The source bundle adds an on-demand language/modules.md containing the two normative contracts; Quick Reference gives the manifest, one checked source example and navigation. No additional AIR documentation is needed. Measurements and final checks are recorded below.

Alternatives and remaining work

Convention-based file lookup, parent manifest search and environment paths hide compiler inputs. Transitive visibility or import aliases add ambiguous bindings; private/public modifiers and re-exports add concepts before the minimal library need demands them. Lazy runtime loading adds authority and initialization ordering. Dependency fetching and lockfiles require their own package tooling contract. STD-4/P6-4 next addresses deterministic generics and structural constraints; owning collections also require a separate vertical linear-aggregates feature.

Documentation measurements

Measured against STD-2b with zig build agent-reference and HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source:

Group cl100k before → after o200k before → after Qwen2.5 before → after
Quick Reference 6,220 → 6,501 (+4.5%) 6,241 → 6,522 (+4.5%) 6,415 → 6,704 (+4.5%)
Other source docs 37,128 → 38,822 (+4.6%) 37,248 → 38,940 (+4.5%) 38,154 → 39,889 (+4.5%)
Full source docs without AIR 43,348 → 45,323 (+4.6%) 43,489 → 45,462 (+4.5%) 44,569 → 46,593 (+4.5%)
AIR docs in source bundle 42,454 → 42,454 42,602 → 42,602 43,827 → 43,827

Standalone AIR remains 160,797 bytes, 48 sections and 19 files. The new module page is 1,566/1,567/1,599 tokens; library/std.md remains 7,730/7,766/7,955. Front-door growth is 281/281/289 tokens. The precise graph, type binding, input bounds and package loading contracts live on demand. Cumulative cl100k growth since pre-stdlib is 33,981 → 45,323 (+33.4%) for full source docs and 5,511 → 6,501 (+18.0%) for Quick Reference. The existing 20% source-doc review crossing remains explicit for owner review. The additional cost buys deterministic modules and nominal types for reusable libraries; it does not establish empirical Model Capability Compression. API-reference splitting and selective reading remain necessary as std grows.

Branch validation

zig build, zig build test, full conformance (579 passed, zero failed/pending), zig fmt --check build.zig build.zig.zon src tools tests/extended, source coverage (76/76), agent-reference, hosted file/stdin/TCP smoke and package CLI integration (36 checks) pass. The module example returns 42. The 35 added conformance cases include source runs/rejections, two hand-written AIR tests and the checked Quick Reference example. All source runs check canonical repeat lowering and deterministic repeat execution. Qualified workers additionally pass 32 schedule-stress seeds across quanta 1, 2 and 7; mutable lends, explicit joins and repeated-lend rejection use existing rules.

Unit checks cover provider/import-order independence, nominal types when diagnostic file labels coincide, imported syntax/unused-function verifier provenance, bounded shared-tail graphs and names longer than the built-in path buffer. Conformance covers local binding collisions, imported main, qualified types/struct fields/enums, lack of short/transitive names, effect/owner/alias/race rejection, header mismatch, duplicate maps/imports/members, cycles, syntax, absent inputs and unreachable malformed sources. CLI checks cover all five commands, grants and overrides, hosted result/output behavior, source trap locations, no ambient manifest discovery, forbidden path components, leaf/ancestor/entry symlinks, nonregular files and aggregate source limits. The integration script is included in CI. No private held-out evaluation material was consulted or changed.