Files
aji/docs/plan/standard-library.md
T

13 KiB
Raw Blame History

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 .aji over 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 branch implementation compiler-pinned, closed registry; qualified enum types/constructors/patterns; no package lookup
General modules/imported struct literals P6-3 pending needed before publishing owning collection types
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-2 todo UTF-8 validation/iteration, hex/base64 and formatting into supplied buffers STD-1a/1b malformed text and insufficient capacity are explicit; no implicit heap; standard vectors and boundary cases pass
STD-3 todo 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/2; 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.