Link manifest-selected source graphs with module-local names, qualified structs/enums/functions and task workers through ordinary AIR verification. Keep source inputs bounded, reject source symlinks and preserve explicit grants, diagnostics and deterministic canonical lowering. Integrate spec 12/15, RFC 0021, source reference budgets, roadmap, examples and CI coverage. Validate 579 conformance tests, unit tests, 76 source constructs, hosted smoke, 36 package CLI checks and task schedule stress.
17 KiB
Standard library implementation plan
Non-normative. Started on feat/std-bootstrap, 2026-10-06, at the owner's request. Normative contracts live in spec 16 and the relevant source/runtime specifications. This track gives reusable libraries priority; P7/P8 remain on hold for B1 analysis. B1 frozen inputs and private held-out tasks do not guide API design and MUST NOT be inspected or changed by this work.
Target and design constraints
Without external source dependencies, Aji should support ordinary CLI tools, storage components, network services and structured concurrent programs. The mandatory semantic surface stays small.
- Prefer safe
.ajiover new AIR opcodes or opaque runtime implementations. - One canonical API for a common operation; effects, borrows, moves, failure and allocation budgets remain visible.
- Caller-provided slices first; owning/growing buffers request
cap<mem.alloc>and expose failure and explicit consumption. - Separate features (implementation support), effects (behavior) and capabilities (authority). Importing a module grants none.
- Avoid a broad trait hierarchy. Begin with concrete adapters; add abstractions only when they reduce contracts and repair work.
- Library functions use the existing verifier. A trusted crypto/TLS boundary is a separate audited dependency with a deterministic-profile model. Do not implement homemade cryptography.
- Runtime capabilities and primitive coverage must be specified through every layer before a wrapper promises them. No implicit cleanup, detached tasks, reflection or ambient environment access.
Current prerequisites
| Capability | Current state | Consequence |
|---|---|---|
| Scalars, structs/enums, slices/arrays, explicit borrows | implemented | pure fixed-storage algorithms can start now |
| Heap/regions, I/O, files, TCP, clock/random, structured tasks/channels/mutex | implemented primitives | wrappers can reuse them, but their presence does not imply the complete APIs below |
| Built-in standard imports and enum types | STD-0/1a/2a/2b branch implementation | compiler-pinned, closed registry; six modules; qualified enum types/constructors/patterns; no package lookup |
| General modules/imported struct literals | STD-3 branch implementation (P6-3; RFC Proposed) | explicit manifest mapping, direct qualified names, ordinary verifier |
| User generics/structural constraints | P6-4 pending | needed for reusable Vec<T>, HashMap<K,V>, option/result |
linear_aggregates |
reserved, unscheduled | independent vertical RFC/phase gate for owners/resources in containers |
| Extended filesystem, IPv6/DNS, args/env, TLS/crypto | not promised by current runtime | audit each primitive, authority, error and profile model before implementation |
A Vec<u64> prototype is not completion of Vec<T>. The collection gate requires valid and rejected examples for Vec<File>, HashMap<Key, Own<Value>> and Vec<sender<Job>>, plus cleanup and failure paths. No linked list is planned.
Milestones
| Milestone | Deliverable | Exit criterion |
|---|---|---|
| Bootstrap | std.math, std.bytes, compiler-pinned import, normative API, source tests and bundle entry |
all functions lower to existing AIR, verify and run; bad calls/aliases reject; import order does not affect canonical AIR; no hidden allocations or authority |
| Std 0.1 — system utilities | core bytes/math/mem/slice/hash, option/result, buffer and owning collections, UTF-8/fmt, hex/base64, small I/O/fs/path/time/random/log APIs | a CLI and bounded storage utility written in .aji use only std, explicit grants, documented failure/cleanup and deterministic fixture tests |
| Integration gate | public, independently chosen 5–10k LOC application | ownership, cancellation, bounded memory and error cleanup work together; API/documentation costs recorded; defects become general repairs |
| Std 0.2 — network services | TCP, IPv4/IPv6, DNS, task/channel helpers, JSON DOM, URI, bounded HTTP/1.1 | a local concurrent JSON/HTTP service passes deterministic fixtures and hosted smoke tests without external source packages |
| Std 0.3 — internet services | audited secure random, SHA-256/SHA-512/HMAC/constant-time compare, TLS client/server, complete HTTP client/server and buffered I/O | verified caller contracts, audited trusted boundary, certificate validation, explicit network authority, bounded buffers and deterministic failure fixtures |
CLI args/env move before the Std 0.1 exit, rather than waiting for Std 0.3: they are required by the CLI target. Their capabilities and startup contracts need a vertical feature. Secure entropy is distinct from deterministic test randomness. Typed JSON schema generation waits for an independently justified compile-time facility; the DOM comes first.
SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protobuf, GUI, templating, regex and broad compression suites remain package-ecosystem work. TLS may initially depend on a vetted host crypto library; “no external source dependencies for callers” does not mean “no trusted native dependency.”
Tasks
| ID | Status | Work | Depends | Done when |
|---|---|---|---|---|
| STD-0 | done (branch implementation; RFC Proposed) | bootstrap spec, source std, closed imports, conformance, documentation and complexity measurement | existing source frontend | bootstrap exit criterion above and required repository checks pass |
| STD-1a | done (branch implementation; RFC Proposed) | endian u16/u32/u64 and qualified standard enum results | STD-0 | recoverable short-input/output failure, no partial mutation; all short lengths, empty/maximal values, fixtures and rejected alias examples pass |
| STD-1b | done (branch implementation; RFC Proposed) | bounded copy/search, split composition and recoverable arithmetic for u64/usize | STD-1a | contracts define capacity/overflow failure, no partial mutation, empty inputs and aliasing; independent fixtures pass |
| STD-2a | done (branch implementation; RFC Proposed) | UTF-8 next/validate and supplied-buffer hex/base64 | STD-1a/1b | malformed text and insufficient capacity are explicit, output unchanged on returned errors; independent vectors and boundary cases pass |
| STD-2b | done (branch implementation; RFC Proposed) | decimal u64/i64/usize/isize formatting into supplied buffers | STD-2a | minimal explicit format contract, no implicit heap, capacity/empty/maximal scalar tests and caller example |
| STD-3 | done (branch implementation; RFC Proposed) | general modules and imported type names (P6-3) | STD-0 | deterministic resolution, collisions/cycles and diagnostics specified and covered |
| STD-4 | todo | source generics (P6-4), constraints and option/result | STD-3 | deterministic specialization and rejected constraint examples; source/AIR budgets measured |
| STD-5 | todo | independent linear_aggregates RFC and vertical implementation phase |
STD-3/4 for its source surface | spec → AIR → verifier → interpreter → source/lowering → Quick Reference → AIR/source tests; linear elements consumed on every path |
| STD-6 | todo | buffer, Vec, Deque, HashMap, HashSet, BinaryHeap | STD-4/5 | allocate/grow/remove/free contracts, allocation failure leaves documented state, linear elements survive moves and are consumed; no hidden destruction |
| STD-7 | todo | concrete I/O adapters, buffered I/O and lexical paths | STD-1b/2a/2b; STD-3 for public types | short reads, EOF, capacity and write failures covered; paths never grant filesystem authority |
| STD-8 | todo | filesystem gaps, args/env capability RFC, time/random distinctions and structured log | STD-3/7; vertical runtime feature where needed | CLI/storage milestone examples work in deterministic and hosted profiles; all authority is granted at entry |
| STD-9 | todo | independent integration application and API review | STD-6/7/8 | integration gate; public application is not private benchmark material |
| STD-10 | todo | IPv4/IPv6/TCP/DNS contracts and runtime gaps; task/channel helpers | STD-9 | bounded service fixtures, deterministic scheduling and schedule stress pass |
| STD-11 | todo | JSON DOM, URI and bounded HTTP/1.1 | STD-6/10 | depth/size/header/body limits, malformed-input errors, streaming/EOF and cleanup tests |
| STD-12 | todo | vetted crypto backend and TLS vertical RFC | STD-10/11 | explicit trusted dependency, certificate/trust/entropy inputs, audit and deterministic model |
| STD-13 | todo | HTTP client/server integration and Std 0.3 review | STD-12 | internet-service exit criterion |
Each task can be split into reviewable increments; only executable exit criteria mark it done. Owning containers are the next semantic priority, but pure byte/text operations need not wait for them. P7 is reconsidered after B1 analysis and the integration gate; this plan does not unilaterally reopen it.
API review and Model Capability Compression
For each increment record public signatures, conceptual additions, syntax forms, diagnostics, required verifier state, allocations/budgets and cleanup obligations. Run zig build agent-reference and tools/agent_bundle_tokens.py --source; report Quick Reference and Source Reference Bundle growth by group. Library reference pages are read on demand.
Use general public use cases and fixtures to measure documentation read, output size, verifier failures, repair cycles and ownership visibility. Performance and allocations also matter, but an API with five overlapping forms needs evidence. No language/API design decision is made from tasks M/C or the private corpus, and no compression benefit is claimed before measurement.
Bootstrap verification
Required: zig build, zig build test, zig build conformance, zig fmt --check build.zig build.zig.zon src tools tests/extended, python3 tools/source_coverage.py, and zig build agent-reference. Because imported code reaches the ordinary CLI, also run python3 tests/hosted/smoke.py. Run tests use fuel, never wall-clock termination.
The bootstrap does not add ownership or concurrency semantics. Preserved invariant: shared slices only read, exclusive slices only write, no borrow escapes or resource is consumed. Existing borrow/bounds transfer functions and interpreter rules apply; valid and rejected source fixtures exercise that boundary. Existing E7001, E7002, E7005, E7006, E2101, T0002 suffice. AIR format 0 remains unchanged and existing programs without imports lower identically.
Bootstrap result: nine APIs implemented; full conformance, unit/Quick Reference, formatting and source coverage checks pass. Hosted file/stdin/TCP smoke tests and evaluation harness self-tests pass (22 tests; one environment-dependent skip). The documented example returns 42 with no grants; invalid clamp bounds report std/math.aji:20. RFC 0016 remains Proposed for owner review. Token growth (cl100k): Quick Reference +4.8%; source bundle excluding AIR +6.6%; AIR unchanged.
STD-1a verification
Twelve additional endian functions and four ordinary Copy enums lower to existing AIR. The invariant remains: no access outside the supplied slice, no escaping borrow, no hidden allocation, and no mutation on insufficient output capacity. The capacity branch precedes every access. Existing verifier/interpreter rules and diagnostics apply; valid/rejected source examples and hand-written AIR fixtures exercise payload typing and read behavior. AIR format 0 is unchanged. Qualified standard enum names implement only a closed-registry subset of STD-3; user modules, imported struct literals, dependencies and generics remain open.
Run the same required checks as bootstrap. Endian fixtures include independent LE/BE byte vectors, every short length, zero/maximal values, every bit, nonzero offsets, extra input/output bytes, returned enum records, compound types, name collisions, exhaustive matches and forbidden mutable aliasing. RFC 0017 records final checks and complexity measurements.
STD-1b verification
Eight further pure functions reuse existing primitives: std.bytes.copy and find_slice, plus checked add/sub/mul for u64 and usize. Copy reuses WriteResult; three additional ordinary Copy enums represent substring matches and arithmetic results. Wrapping remains an operator. Splitting composes a search with explicit caller-bounded slice operations; no borrowed aggregate, iterator, cursor, compiler/runtime change or hidden allocation is added.
The preserved invariant is shared-read/exclusive-write access only within the supplied slices, no escaping borrows and no mutation on short output. Existing verifier/call/alias/enum rules and interpreter behavior suffice. Valid/rejected source fixtures and hand-written AIR twins cover the contracts; current diagnostics and AIR format 0 are unchanged. Tests include all 81 input/output length pairs through eight, disjoint split borrows, overlapping and empty short-output aliases, 428 search cases, seven split cases and 320 independently computed arithmetic operand pairs exercised through both widths. The interpreter's numeric vectors use its default air64; library usize limits are computed with target-width wrapping subtraction. RFC 0018 records the final repository checks and complexity measurements. STD-2 can now start with UTF-8 and supplied-buffer encodings.
STD-2a verification
Six functions and six ordinary result enums add UTF-8 next/validate and supplied-buffer hex/Base64 to the closed registry. UTF-8 returns a scalar plus consumed bytes; caller offsets carry iteration state. Hex accepts both ASCII letter cases and emits lowercase; Base64 accepts canonical padded standard text with zero unused bits. Decode validates all input before capacity/mutation, so malformed input wins over insufficient output and every returned error preserves the destination. Size guards avoid intermediate overflow.
All algorithms are safe source using existing verifier/runtime rules, fixed frame storage and explicit slice borrows. No borrow escapes, owner/resource is consumed, heap allocation is hidden, AIR meaning changes or authority is granted. Valid/rejected examples, stable existing diagnostics, deterministic interpreter tests and compatibility are specified in spec 16 §2.5–§2.7 and RFC 0019. The registry embeds three additional modules without a resolver or dependency extension. Tests cover independent Python scalar/byte vectors, UTF-8 boundaries/truncation/surrogates, all input byte values, canonical pad bits, every relevant capacity, late invalid bytes, output suffixes, disjoint same-allocation buffers, namespace collisions and hand-written AIR equivalence. Formatting remains STD-2b; this increment does not mark the original whole text/formatting task complete.
STD-2b verification
Four safe decimal writers and one ordinary result enum complete the supplied-buffer formatting increment. No heap, retained cursor, format-string language, runtime primitive or syntax is added. Counts include a negative sign, suffixes remain unchanged and insufficient capacity preserves the complete destination. Counting precedes mutation; signed magnitude uses -(value + 1) then an unsigned increment, avoiding signed-minimum negation. Explicit caller offsets and std.bytes.copy compose a record; failure preserves the individual call's destination, not earlier successful calls.
Spec 16 §2.8 and RFC 0020 specify the invariant, existing verifier/runtime rules, valid/rejected examples, diagnostic impact, deterministic execution and unchanged AIR format 0. Independent Python decimal vectors exercise zero, all small values, decimal/binary transitions, seeded scalar inputs, both 64-bit limits and every capacity from zero through 22, checking all guard/suffix bytes. Target-width fixtures guard conversions against the target limits; the current interpreter executes at air64. Source/AIR result equivalence, explicit record composition, disjoint borrows, qualified types/collisions and rejection of conflicting borrows (including short output), missing imports, invalid payloads/types and incomplete matches cover the public boundary. RFC 0020 records required checks and source/AIR documentation budgets. Next semantic prerequisites for owning buffers and containers remain STD-3/4/5; a decimal writer does not complete general formatting or owning strings.
STD-3 verification
P6-3 now links explicit package sources through the same frontend as compiler-pinned std. Manifest mappings supply source bytes; pure linking checks an acyclic graph, module identity and direct-import visibility, then emits collision-free deterministic AIR. Imported functions, structs, enums and qualified task workers use existing ownership, lifetime, effect and scheduler rules. Check/lower/report instantiate no grants; run/explore use explicit manifest grants and overrides. Package sources have portable bounded paths, no symlink traversal and a 64 MiB aggregate source budget; file-only commands never discover manifests.
RFC 0021 records invariants, diagnostics, compatibility, complete validation and documentation growth. General modules and imported struct literals are implemented on this branch; dependencies and external package resolution are separate work. The next semantic step is STD-4/P6-4 generics and structural constraints, followed by the independent linear-aggregate gate. Owning collections still require both gates.