Inventory
This is the definitive index of what currently exists under lib/. Grep this file before designing or implementing anything reusable — a library, prelude, parser, codec, type declaration, util — to find out whether it already exists, partly exists, or is stubbed.
This file is hand-maintained. When you add a new library or _types.lua file, add a line here in the same commit. If the index lags behind reality, spot-check lib/ directly before assuming something doesn't exist.
Duplicate clusters triage: see docs/duplicate_clusters.md for canonical-pick analysis of the ~25 duplicate library pairs/triplets noted inline below (**Parallel to ...**, **Two parallel impls**, etc.).
Status legend:
- stable — substantive code with real tests
- wip — partial, may be missing features or polish
- stub — empty-ish init.lua scaffold, placeholder
- broken — known-bad / abandoned (commented-out code, FIXMEs, no init.lua)
Type preludes
These declare shared types and have no runtime code (or only declaration-side glue). Load via --:: require "...".
lib/js_types/init.lua— DOM, browser, and JS host API surface (DOMTokenList, Element, Event, fetch, history, etc., 2078 lines). Use this before redeclaringElementor any browser/JS type. Status: stable.lib/caps/types.lua— injected I/O capability function aliases (POpenFn, etc.). Status: stable.lib/formats/ccv2/ccv2_types.lua— Character Card v2 format types. Status: stable.lib/http/format_types.lua—http_request/http_responseshape aliases. Status: stable.lib/imap/format_types.lua— IMAP (RFC 9051) flags and capability aliases. Status: stable.lib/platform/apps/system_dashboard/primitive_types.lua— system_dashboard pack output schema. Status: stable.lib/platform/apps/system_dashboard/projections/projection_types.lua— typed environment for projection authors (Children, Style, Props, sealeddomtag table,text,Ctx,Projection). ImportsElement,Text,Eventetc. fromlib/js_types/init.luarather than redeclaring them. Status: stable.lib/taskgraph/taskgraph_types.lua— taskgraph aliases. Status: stable.lib/type/static/ctx_types.lua— typechecker context (ctx) struct, used in self-check. Status: stable.lib/type/static/stdlib_types.lua— Lua 5.1 / LuaJIT stdlib type declarations. Status: stable.
Type system / tooling
lib/type/— runtime schema typechecker (separate from static).lib/type/static/— full static typechecker. v2/v3 design (seedocs/typechecker-v2.md). Includescli.lua,lsp.lua, parser, constrain, narrow, unify, prelude, cdef parser, fuzzers. Status: stable.lib/type/static-v4/— greenfield typechecker rewrite, foundation (Phases 4a–4g). Type representation + simple-sub-style subtyping; equi-recursive μ types; indexed accessT[K]; complement~Twith DNF-based emptiness; match types as bidirectional pattern destructors; rank-N polymorphism via deep-skolemization (Peyton-Jones et al. 2007) with MLstruct#Fskolem tags and transitive-closure escape check; effects as a small named enumeration on function arrows (covariant); content-addressed cache primitives (binary serialize/deserialize, SHA-256 hash, manifest with cri-hash + per-file deps, cache_lookup/store over an injectedio_capscapability — no globalos/ioreach). No AST walker, no CLI yet. Seedocs/typechecker-rewrite-design.mdand the directory README. Status: wip.lib/type/static-v4/walker/— AST walker bridging Lua AST nodes to the v4 core. Sub-phases A–H complete: functional env record + narrowing overlay; two-mode dispatch shell; per-node handlers for literals, identifiers, varargs, calls, functions, returns, control-flow + narrowing, statements, match, indexed access, module pattern, FFI cdef integration, and effect plumbing (error/pcall/xpcall intrinsics, with coroutine.yield riding the standard binding-driven call-effect-accumulation path). Seedocs/typechecker-ast-walker-design.md. Status: wip (A–H of A–J).lib/type/static-v4/driver/— driver for the v4 pipeline (parse → decode → walk → cache). K2 (decoder.lua): eager arena → POJO AST decoder translating the legacy parser's{ nodes, lists, pool, root }arena output into the plain-Lua-table node shape the walker consumes (resolves intern IDs to strings, follows list-pool references into materialised child arrays, maps integer OP_* codes to walker string ops, preserves arena identity via per-decode cache). K1 (driver.lua): end-to-enddrive(source_path, opts)— reads source via injected I/O caps, hashes (sha256), parses via injected parse cap, decodes via K2, builds an env seeded with stdlib bindings (viainject_stdlib) + io_caps + cache_dir + inherited require_chain, walks the chunk's statements sequentially throughwalker.walk_synth(driver owns chunk semantics — no NODE_CHUNK handler registered on the walker, preserving walker_test's "unsupported-tag stub" repro), collects diagnostics, and on a clean walk callsV.cache_storewith the packed(exports, aliases)artifact and the per-require dep map. Recursive cache-miss walks wired via two module-level hooks onwalker/require_resolve.lua(_set_driver_hooks(drive_recursive_fn, deps_sink)) — module-state rather than env-state because WalkerEnv'sclone()does not carry runtime-injected fields. Cycle detection through the existingenv.require_chainplaceholder mechanism. Seedocs/typechecker-v4-driver-design.md§1, §6. Status: wip (K1 + K2 of K1–K6).lib/type/static-v4/stdlib_types_v4.lua— K3 MVP stdlib type declarations for v4 (Option B per driver design §3):{ bindings, aliases, parametric_aliases, intrinsics }record consumed by the driver viainject_stdlib. Hand-builtV.fn/V.rec/V.forall/V.inter/V.unionvalues forerror/pcall/xpcall/require/type/tostring/tonumber/assert/select/next/pairs/ipairs/setmetatable/getmetatable/raw*/unpack/print/_VERSION/_Gand thestring/table/math/coroutine/bit/ffi/jit/packagetables.io/os/debug/dofile/loadfile/loadstring/load/newproxy/collectgarbage/gcinfoare deliberately excluded (CLAUDE.md "Caps-first, everywhere") pending a futurestdlib_types_v4_caps.lua. Parametric aliases (Arr,Ptr,Keys,Values,MetaOf,Open,Closed,PairsReturn,IpairsReturn,PcallReturn,Ctype) are stored as Lua functions because v4 lacks a type-level lambda / deferred-match constructor. Spread function results,selecttail-typing, and$PatternReturn/$FindReturnprecision degrade tounknownper design §7. Seedocs/typechecker-v4-stdlib-design.md. Status: wip (K3 of K1–K6).lib/type/static-v4/cli.lua+cli_compare.lua— K5 CLI surface for the v4 pipeline.cli.lua(K5):bin/cr check --v4 [--summary] [--cache-dir=PATH] <file>...— argv parsing, real io_caps built fromio/osat the legitimate CLI boundary, stdlib injection, driver invocation, K4 default/summary rendering, exit code = 1 iff any error-severity diagnostic or driver-itself failure.cli_compare.lua(K5b):bin/cr check --compare <file>...— invokes legacy via subprocess (black-box, parsesfile:line:col: severity:lines from stdout with ANSI stripped) and v4 via the K1 driver in-process, computes a canonical-position multiset diff (key =file:line:col:severity; messages NOT compared, since taxonomies don't align), and emits per-file verdictsagree/DIVERGE on decision/DIVERGE on details. Exit code reflects agreement (0/1/2) not correctness — agreement is the test. Bin-side dispatch inbin/cr-check.luaselects--compare(priority),--v4, or legacy. Status: wip (K5 + K5b of K1–K6).lib/type/search/— Hoogle-style type search over the registry. Status: wip.lib/type/analysis/— agnostic static-analysis substrate (first mechanization of the agnostic direction; seedocs/agnostic-static-analysis-design.mdand the map's "Agnostic Static Analysis" section).init.lua: the language-agnostic substrate — Id, Artifact, Observation, Claim, Evidence, Dependency, TrustBoundary, AnalysisState, CheckRequest/CheckResult, SemanticsRegistry, and a worklist checker that finds an order-independent acceptance order over arbitrarily-ordered evidence, detects dependency cycles (terminating with a diagnostic, never looping), records dependencies as first-class records, and classifies claims accepted/rejected/unknown (evidence outcomes, not hosted truth; unknown is never consumed as proof). The substrate knows nothing about props/terms/types/binders/substitution: claim predicates and args are opaqueArgValuedata, compared structurally for identity (no name-keyed special cases). Hosted-checker verdicts are surfaced as a visible trusted boundary (unverified_checker_trust) per the design's hosted-checker trust obligation.prop.lua(prop.logic.min) andlambda.lua(lambda.untyped.min) are two independent hosted semantics that import the substrate (never the reverse): propositionalholdsclaims with assumption/trusted_axiom/and_intro/and_elim/modus_ponens/contradiction (contradiction is hosted policy, not explosion); untyped-lambda well_formed/alpha_eq/free_in/not_free_in/steps_to with capture-avoiding outermost call-by-name beta whose capture-avoidance side condition is a checkable cross-evidence dependency on a separately-producedfree_inclaim. Pure Lua. Tests (*_test.lua, 72 assertions) are the spec: every worked example from both validation docs plus claim-identity, scheduling-order-independence, cycle-termination, unknown-propagation, and adversarial probes. Status: wip (propositional + lambda rungs; cyclic-fixpoint and STLC rungs next).
lib/lua2ts/— Lua → TypeScript transpiler over the crescent AST. Status: wip.lib/doc/— docgen (extract typed API docs from Lua source via the typechecker). Status: wip.lib/lsp/— LSP protocol method binding library on top oflib/jsonrpc. Status: wip.lib/mcp/— Model Context Protocol server library on top oflib/jsonrpc. Status: wip.lib/jsonrpc/— JSON-RPC 2.0 dispatcher with pluggable transport. Status: stable.lib/cr/— unifiedbin/crCLI dispatcher. Status: stable.lib/cli/— declarative CLI argument parser. Status: stable.lib/pkg/— package manager. Foundation only (semver, manifest, lock parsers); install algorithm not yet implemented. Status: wip.lib/bundle/— Lua module bundler (resolves staticrequire()s and inlines). Status: stable.lib/edit/— byte-range file edit applier. Used bycr check --fixto apply diagnostic autofixes atomically. Status: stable.lib/embed/— module embedding helper. Status: wip.lib/sandbox/— capability-based script sandbox. Status: stable.lib/stdlib/— stdlib lint CLI. Status: wip.
Test infrastructure
lib/test/— test runner (cli.lua),assert.lua,coverage.lua,fixture.lua(snapshot),fuzz.lua(fast/guided),gen.lua+prop.lua(property),arb.lua(integrated shrinking). Status: stable.lib/bench/— micro-benchmarking framework with statistics. Status: stable.lib/testing_utils/— mocks, spies, parameterized tests, fake clock, HTTP recorder. Status: stable.
Type preludes for tests / props — see Test infrastructure above.
Network protocols
lib/dns/— DNS. Status: stub (entry point is 9 lines).lib/email/— RFC 5322/MIME composition + SMTP client (RFC 5321). Status: stable.lib/epoll/— Linux epoll (and wepoll on Windows) wrapper. Status: wip.lib/exec/— process execution capability wrapper. Status: stable.lib/fuse/— FUSE filesystem bindings. Status: wip (no test file).lib/git/— Git protocol/repository operations (2154 lines). Status: wip (no test file).lib/github/— GitHub REST API client. Status: stable.lib/http/— HTTP server/client. Status: stable.lib/http_static/— static file server with CORS headers, pre-compressed file support (.gz/.br), and optional path-prefix stripping. Wrapslib/http/router/static_full. Status: stable.lib/https/— HTTPS layer. Status: wip.lib/imap/— IMAP RFC 9051 format/parser. Status: wip (no init.lua, no test).lib/inotify/— Linux inotify FFI. Status: wip (no test).lib/jsonrpc/— see Type system / tooling.lib/keyring/— secure API key storage (libsecret > tier fallback). Status: stable.lib/ljsocket/— LuaJIT FFI socket library. Status: stable (no test).lib/mud_cp/— MUD client protocol. Status: broken / wip (no init.lua, TODOs throughout).lib/net/— network address parsing/manipulation (no I/O). Status: stable.lib/oauth/— OAuth 2.0 helpers (URL building, PKCE, JWT decode). Status: stable.lib/oauth2/— OAuth2 client (RFC 6749) with injectable HTTP. Status: stable.lib/realtime/— realtime/subscription primitives. Status: stable.lib/smtp/— RFC 5321 SMTP client with injectable transport. Status: stable.lib/socket/— socket abstraction. Status: stub.lib/tcp/— TCP client. Status: wip (no init.lua, TODOs).lib/tls/— TLS. Status: wip (TODOs noted).lib/websocket/— WebSocket framing. Status: stable.lib/wire/— length-prefixed binary protocol framing. Status: stable.lib/wire_protocol/— varint, TLV, fixed-size, delimited framing. Status: stable.lib/x509/— X.509 cert parser (RFC 5280) on top of asn1+pem. Status: stable.
Codecs / formats / serialization
lib/asn1/— ASN.1 DER parser/writer (pure Lua). Status: stable.lib/base32/— RFC 4648 base32 / hex / Crockford. Status: stable.lib/base58/— Base58 / Base58Check (Bitcoin/IPFS). Status: stable.lib/base64/— RFC 4648 base64 (standard + URL-safe). Status: stable.lib/bencode/— BitTorrent bencoding. Status: stable.lib/bson/— BSON (MongoDB wire format). Status: stable.lib/cbor/— CBOR RFC 7049. Status: stable.lib/codec/— codec wrapper interface;codec/base85/ascii85. Status: stable.lib/crc/— CRC family. Status: stable.lib/crc32/— standalone CRC32. Status: stable.lib/csv/— RFC 4180 CSV. Status: stable.lib/csv_query/— SQL-like in-memory tabular query engine. Status: stable.lib/csv_transform/— CSV transform pipelines. Status: stable.lib/decimal/— exact decimal {coeff,exp}. Status: stable.lib/dotenv/— .env file parser with variable expansion. Status: stable.lib/encode/—base64/,urlencode/,utf8/bytes-level encodings. Status: stable.lib/format/—json/(ffi+pure+simd tiers),cbor/,msgpack/,toml/,yaml/. Status: stable.lib/formats/ccv2/— Character Card v2 (with adapters, lorebook, macros). Status: stable.lib/hex_dump/— hex dump utility. Status: stable.lib/ical/— iCalendar RFC 5545 parser/builder. Status: stable.lib/ini/— INI file parser. Status: stable.lib/json/— RFC 8259 JSON (top-level pure-Lua entry; see alsolib/format/json/). Status: stable. Note: parallel tolib/format/json/— consider using the tiered version underlib/format/.lib/json_patch/— RFC 6901 + RFC 6902 (pointer + patch). Status: stable.lib/json_schema/— JSON Schema draft-7 validator. Status: stable. Note: duplicate oflib/jsonschema/— both exist.lib/jsonschema/— JSON Schema draft-07 validator. Status: stable. Duplicate oflib/json_schema/.lib/markup/— markup AST/parser. Status: stable.lib/mime/— MIME type table (extension → type). Status: stable.lib/mimetype/— mimetype lookup (smaller). Status: stub.lib/msgpack/— MessagePack. Status: stable.lib/multipart/— RFC 2046 multipart encoder/decoder. Status: stable.lib/ndjson/— NDJSON / JSON Lines. Status: stable.lib/netstring/— DJB netstring framing. Status: stable.lib/pem/— PEM RFC 7468 parser/writer. Status: stable.lib/png/— PNG chunk-level reader/writer. Status: stable.lib/proto/— Protocol Buffers 3 wire format (schemas as Lua tables). Status: stable.lib/protocol_buffer/— Protobuf wire format (alternative impl). Status: stable. Parallel tolib/proto/.lib/sexp/— S-expression parser/serializer. Status: stable.lib/struct/— C-style binary pack/unpack (Pythonstructsyntax). Status: stable.lib/svg/— SVG document builder. Status: stable.lib/tar/— POSIX.1-1988 ustar tar reader/writer. Status: stable.lib/toml/— TOML parser. Status: stable.lib/url/— URL parsing. Status: stable.lib/uuid/— UUID v4 + v7. Status: stable.lib/wire/,lib/wire_protocol/— see Network protocols.lib/xml/— XML 1.0 SAX/DOM parser. Status: stable.lib/xpath/— XPath 1.0 evaluator. Status: stable.lib/yaml/— YAML 1.2 (subset). Status: stable.
Compression
lib/brotli/— Brotli RFC 7932 (HTTPbr). Status: stable.lib/compress/— tiered zlib/gzip (system FFI > pure Lua). Status: stable.lib/huffman/— Huffman coding. Status: stable.lib/lz4/— LZ4 block + frame. Status: stable.lib/lz77/— pure Lua LZ77 (raw, custom frame, NOT DEFLATE). Status: stable.lib/rle/— run-length encoding. Status: stable.lib/snappy/— Snappy. Status: stable.lib/zstd/— Zstandard RFC 8878. Status: stable.
Crypto
lib/argon2/— Argon2d/i/id (RFC 9106). Status: stable.lib/auth/— JWT (HS256), session tokens, password hashing. Status: stable.lib/blake2/— BLAKE2b/s (RFC 7693). Status: stable.lib/chacha20/— ChaCha20 + ChaCha20-Poly1305 AEAD. Status: stable.lib/crypto/— tiered AES-256-GCM, ChaCha20-Poly1305, HKDF, random (system-libcrypto > pure). Status: stable.lib/cryptography/— pure Lua SHA-256/512, HMAC, PBKDF2, ChaCha20, Poly1305, ct-compare. Status: stable. Parallel tolib/crypto/; this one is the pure-Lua bag.lib/curve25519/— X25519 RFC 7748. Status: stable.lib/ed25519/— Ed25519 RFC 8032 (libsodium tier > pure). Status: stable.lib/hash/—crc32/,hmac/,md5/,sha1/,sha256/,xxhash/. Status: stable.lib/jwt/— JWT RFC 7519 (HS256 only). Status: stable.lib/murmurhash/— MurmurHash3 x86_32/x86_128/x64_128. Status: stable.lib/pbkdf2/— PBKDF2 RFC 8018. Status: stable.lib/poly1305/— Poly1305 RFC 8439 §2.5. Status: stable.lib/scrypt/— scrypt RFC 7914. Status: stable.lib/shamir/— Shamir's Secret Sharing over GF(256). Status: stable.lib/siphash/— SipHash-2-4 / 1-3. Status: stable.lib/totp/— HOTP RFC 4226 + TOTP RFC 6238. Status: stable.lib/vigenere/— classical ciphers (Vigenère, Caesar, Atbash, Playfair, etc.). Status: stable.
Parsers / grammars / DSLs
lib/aho_corasick/— Aho-Corasick multi-pattern matching. Status: stable.lib/css/— CSS data structures. Status: stable.lib/css_parser/— CSS tokenizer + selector + declaration + stylesheet parser. Status: stable.lib/datalog/— Datalog. Status: stable.lib/diff/— Myers O(ND) diff. Status: stable.lib/expr/— math expression parser/evaluator + symbolic differentiation. Status: stable.lib/glob/— glob pattern matching. Status: stable.lib/grammar/— PEG parser combinators. Status: stable.lib/grammar_gen/— context-free grammar text generation (Tracery-style). Status: stable.lib/graphql/— GraphQL parser + schema DSL + executor. Status: stable.lib/graphql_parser/— GraphQL query/SDL parser + AST printer. Status: stable. Parallel tolib/graphql/parser portion.lib/grammar/,lib/peg/— PEG (parser combinator) impls.lib/peg/is parallel tolib/grammar/.lib/lex/— seelib/tokenizer/.lib/log_parser/— log line parsing. Status: stable.lib/markdown/— Markdown → HTML / plaintext. Status: stable.lib/markdown_it/— high-level Markdown via mdast + hast. Status: stable.lib/merge3/— three-way text merge. Status: stable.lib/parse/— generic parser primitives. Status: stable.lib/parser_combinators/— parser combinators. Status: stable. Parallel tolib/grammar/andlib/peg/.lib/peg/— PEG. Status: stable.lib/prolog/— Prolog (Horn clause + unification). Status: stable.lib/regex/— tiered PCRE2 FFI > pure Lua. Status: stable.lib/regex_builder/— fluent DSL → Lua pattern strings. Status: stable.lib/safe_regex/— JS-regex catastrophic-backtracking validator, hologram-shaped algorithm ("no quantifier on a subexpression containing an unbounded quantifier"); pure Lua. Companionlib/js_safe_regex/ships the JS impl. Status: stable.lib/js_safe_regex/— JS impl of the safe_regex validator (ESMsafe_regex.js), used by the browser realm bootstrap's RegExp / String.match / matchAll / search wrappers;init.luais type-only. Parity-tested againstlib/safe_regex/(static corpus + runtime verdicts via bun). Status: stable.lib/js_realm_sandbox/— allow-list realm lockdown for pack browser realms (ESMsandbox.js);installLockdown(opts)captures intrinsic originals, installs bounded-method wrappers (repeat/padStart/padEnd/join/flat/flatMap/Array(n)/Array.from/Array.of/fromCharCode/fromCodePoint/JSON.parse/JSON.stringify against SIZE_CAP), wrapsRegExpandString.prototype.{match,matchAll,search}vialib/js_safe_regex, neutralises constructor reflection paths (Function/AsyncFunction/Generator/AsyncGenerator/.__proto__.constructor.constructor), strips Error.stack and RegExp legacy statics, prunes/freezes globalThis. Implements docs/platform_isolation.md §3 "Allow-list specification".init.luais type-only. Tests run the full escape-test corpus in freshnode:vmcontexts via bun;parity_test.luaasserts every spec corpus entry is referenced insandbox.test.js. Status: stable.lib/js_pack_validator/— author-side hygiene validator for pack JS (ESMvalidator.js); walks the acorn AST against the pack-JS subset in docs/platform_isolation.md §3 "Pack JS subset (draft)" -- rejects class syntax, generators,with, tagged templates, dynamicimport(), dynamic bracket member access, non-allow-listednewtargets, and banned identifier references (eval,Function,Reflect,Proxy,WeakRef,FinalizationRegistry,SharedArrayBuffer, ...); integrates withlib/js_safe_regexfor regex literal checks. Runs in author dev/CI via bun -- NOT a daemon dependency (per spec rejection of bundling JS parsers in the daemon). Vendorsacornatdep/acorn/.init.luais type-only.parity_test.luaasserts every spec subset rule is exercised invalidator.test.js. Status: initial.lib/js_cap_bridge/— postMessage capability bridge between pack realm and host stub (ESMbridge.js);createRealmBridge({capNames, postMessage, registerMessageHandler})produces non-constructable async cap shells (concise-method syntax) installed ontoglobalThis.__cap__by the sandbox bootstrap, each serialising calls to{id, kind:"call", cap, args}frames and returning promises resolved on host response;createHostBridge({grantedCaps, capImpls, audit, postMessage})validates the cap against the user's grants, invokes the impl viaPromise.resolve().then(() => impl(...args))(foreign-thenable hazard avoidance), and audit-logs every attempt (denied/missing/throw/ok). Args are never implicitly coerced; envelope validation responds withmalformedwhen id is recoverable, drops otherwise. Pure protocol implementation -- transport and message-handler registration are injected so the same code runs innode:vmtest contexts and real iframes. Implements docs/platform_isolation.md §4 "Capability bridge protocol".init.luais type-only.parity_test.luaasserts every protocol rule is referenced inbridge.test.jsand optionally drivesbun bridge.test.js. Status: initial.lib/js_caps/— day-zero browser cap implementations (ESMindex.js); per-cap files (text_encode.js,text_decode.js,compress.js,decompress.js,console_log.js,web_crypto_random.js,set_timeout.js,web_crypto_subtle.js,clipboard_write.js,fetch_api.js,kv.js,ui.js) each export a pure wrap (or, forfetch_api, amakeFetchApifactory; for the kv_* family, amakeKvCapsfactory; for the UI capstoast/dialog/navigate, amakeUiCapsfactory) of the underlying host API with structural arg validation;index.jsaggregates the bare-function caps intodayZeroCaps: Map<string, function>ready to drop intolib/js_pack_host#mountPackasopts.capImpls, exports factory caps (makeFetchApi,makeKvCaps,makeUiCaps) separately so the host page can construct them per manifest entry / per host-app configuration, and exportsbuildDayZeroCapImpls({ fetchConfig?, kvConfig?, uiPrimitives? })to compose the full Map in one call. Implements docs/browser_caps.md §5 "Day-zero exposed cap surface" -- shipped 17/17 (6 trivial pure-wrap caps +set_timeout, cancellable via the cap-bridge AbortSignal extension per docs/platform_isolation.md §4, +web_crypto_subtle, op-discriminated SubtleCrypto wrap withencrypt/decrypt/sign/verify/digest/generateKey/deriveKey/deriveBits/importKey/exportKey/wrapKey/unwrapKey; CryptoKey crosses the bridge via structured clone, +clipboard_write,navigator.clipboard.writeTextwrap with 1 MiB size cap; NotAllowedError propagates as athrowenvelope to the pack realm, +fetch_apifactorymakeFetchApi({ allowed_origins }), attenuated browser-side fetch with origin allowlist bound at host-side instantiation per docs/browser_caps.md §4.1.1; validates URL/method/headers/responseFormat, shapes response into structured-clone-safe{status, statusText, headers, body}, body is ArrayBuffer by default or JSON/text perresponseFormat, AbortSignal propagates via the bridge's signal-marker replacement, + thekv_read/kv_write/kv_delete/kv_keysfamily viamakeKvCaps({ pack_id }), IndexedDB-backed per-pack key-value store (one databasepack_<pack_id>with a singlekvobject store; structured-clone values round-trip Uint8Array / Map / Set / Date directly; per-pack partitioning by database name; keys are non-empty strings up to 1024 chars; the four caps share a backend and are returned together by the factory, + thetoast/dialog/navigatefamily viamakeUiCaps({ renderToast, renderDialog, requestNavigate })per docs/browser_caps.md §4.4.10/§4.10.3/§4.10.4; pure routing layers over host-app-supplied UI primitives -- caps validate structured input (toast: message ≤512 chars, level ∈ info/warning/error, duration ≤30s; dialog: message ≤1024 chars, 1-8 non-empty button strings, host return must match an input button; navigate: path ≤2048 chars, host-app-defined semantics) and forward to the injected primitive).init.luais type-only.caps.test.jscovers happy path / validation failure / boundary per cap plus aggregator shape (kv_* tested against a tiny in-memory IndexedDB mock because bun'snode:vmdoes not exposeindexedDB; UI caps tested against a fakeuiPrimitivesrecording calls);parity_test.luaasserts every shipped cap kind is referenced incaps.test.jsand optionally drivesbun caps.test.js. Status: initial.lib/js_pack_host/— pack iframe pipeline, both halves. Inside-iframe: ESMbootstrap.js;runBootstrap({capNames, postMessage, registerMessageHandler, sizeCap?})builds the realm-side bridge vialib/js_cap_bridge#createRealmBridge, then installs the lockdown vialib/js_realm_sandbox#installLockdownwith the bridge's cap shells, returning{caps, dispatch}so pack source loaded LATER by the outer host page reaches caps throughglobalThis.__cap__. Sequencing is fixed: bridge first (captures vanilla intrinsics in its closures), lockdown second (seals realm and installs__cap__), pack source third (orchestrated by the outer host page). Outside-iframe: ESMhost.js;mountPack({container, packBootstrapUrl, capNames, capImpls, audit, onError?, origin?})creates a cross-origin sandboxed iframe (sandbox="allow-scripts"only,referrerpolicy="no-referrer"), wires the host-side cap bridge (createHostBridge) to the iframe's window viapostMessage/addEventListener("message"), validatescapNames ⊆ capImpls.keys()at mount, enforces both origin (whenopts.originset) and source (event.source === iframe.contentWindow, unconditional) on inbound messages, and returns{iframe, unmount, audit}with audit entries for mount/unmount alongside the bridge's per-cap audit entries. Implements docs/platform_isolation.md §3 "Realm primitive" + "Bootstrap script" + §4 "Capability bridge protocol".init.luais type-only (declaresrun_bootstrapandmount_pack). Tests:bootstrap.test.jspairsrunBootstrap(insidenode:vm) withcreateHostBridge(outside) via callback-routed postMessage;host.test.jspairsmountPack(outside, with a fake DOM exposing only the surface mountPack touches) with the inlined bootstrap inside a vm context, covering cap-validation rejection, mount audit, end-to-end cap round-trip, origin and source enforcement, and unmount listener+iframe cleanup.parity_test.luaasserts every bootstrap contract rule is referenced inbootstrap.test.jsand optionally drivesbun bootstrap.test.js. Real-browser smoke forhost.js(real iframes, real postMessage) is a manual follow-up. Status: initial.lib/regexp/— Thompson-NFA regex with capture groups (pure). Status: stable.lib/sscanf/— C-style scanf/sscanf. Status: stable.lib/text_diff/— character-level diff (diff-match-patch style). Status: stable.lib/tokenizer/— declarative lexer/tokenizer builder. Status: stable.lib/ukanren/— µKanren miniKanren. Status: stable.
Markup / unified pipeline
lib/unified/— unified.js-style pipeline; many submodules:mdast/,hast/,nlcst/,xast/,remark*,rehype*,retext*,unist_util_*,xast_util_to_xml/. Status: wip (some modules empty; seelib/unified/STATUS.md). This is the canonical home for all hast/mdast/remark*/rehype* implementations.lib/template/— HTML template (escape + render). Status: stable.lib/template_engine/— Jinja2-style with inheritance, filters, macros. Status: stable.lib/string_template/— simple string interpolation. Status: stable.lib/mustache/— Mustache renderer. Status: stable.lib/html/— type-safe HTML builder (nominal element types). Status: stable.lib/word_wrap/,lib/text_justify/,lib/text_stats/,lib/spell_check/,lib/porter_stemmer/,lib/soundex/,lib/levenshtein/,lib/fuzzy_match/,lib/markov/,lib/nat_lang/,lib/i18n/,lib/locale/,lib/humanize/— text utilities. Status: stable.
Web / UI
lib/translucent-css-theme/— opt-in glassmorphic design system (translucent panels, layered 3D borders, blue primary). Pure CSS tokens + components plustheme.js(dark/light/system toggle persisted to localStorage). No Lua. Used by ccv2 and library platform apps via symlinks under theirstatic/dirs. Status: stable.lib/web/— web app framework (middleware, routing, cookies, CSRF, static). Status: stable.lib/web/html/— typed HTML builder. Status: stable.lib/web/reactive_dom/— reactive DOM bindings (useslib/js_types/). Status: stable.
lib/js_types/— see Type preludes. Thelib/js_*/prefix is the convention for browser-side libraries (JS type declarations, runtime sandbox, host-bridged cap shims).lib/router/— URL routing (trie-based). Status: stable.lib/canvas/— 2D pixel canvas with PPM/PGM/BMP export. Status: stable.lib/color/,lib/color_palette/,lib/color_space/,lib/gradient_descent/(numerics, see below) — color toolchain. Status: stable.lib/tui/— TUI widget layer on top oflib/ansi. Status: stable.lib/ansi/— ANSI escapes (4/8/24-bit color, cursor, control). Status: stable.lib/widget/— platform-agnostic reactive widget layer. Status: wip.lib/layout/— layout engine. Status: stable.lib/pretty_print/— value pretty printer. Status: stable.lib/qrencode/— QR code encoder. Status: wip (no test).lib/barcode/— Code128/EAN/UPC/Code39 + SVG. Status: stable.
Reactive / state / signals
lib/reactive/— push-based signal/computed/effect/batch. Status: stable.lib/reactive_db/— reactive in-memory relational DB with live queries. Status: stable.lib/reactive_optics/— signals composed withlib/fp/optics. Status: stable.lib/reactive_store/— Redux/Zustand-style store. Status: stable.lib/reactive_stream/— pull-based Rx-style stream combinators. Status: stable.lib/reactive_var/— fine-grained reactive var (MobX/Solid/Vue style). Status: stable.lib/signals/— auto-tracking signals (Solid/Preact style). Status: stable. Note: parallel tolib/reactive/; signals auto-tracks, reactive is explicit.lib/signal/— POSIX signal handling. Status: stable.lib/observer/— push observables with operators (cold, sync) + subject/behavior_subject/replay_subject. Status: stable.lib/event/,lib/event_emitter/— event bus / pub-sub. Status: stable. Two parallel impls.lib/event_sourcing/— event store + aggregates + projections + sagas. Status: stable.lib/pubsub/— pub/sub with topic patterns + middleware. Status: stable.lib/mediator/— mediator pattern (commands/queries/events). Status: stable.
Async / concurrency / scheduling
lib/actor/— coroutine actor model with supervision/links/monitors. Status: stable.lib/async/— promise-based async/await on coroutines. Status: stable.lib/async_queue/— coroutine work queue with priorities/retries/rate limits. Status: stable.lib/chan/— Go-style coroutine channels. Status: stable.lib/promise/— synchronous Promises/A+ inspired. Status: stable.lib/scheduler/— cooperative coroutine scheduler with priorities + timers. Status: stable.lib/semaphore/— semaphore/mutex/event/condvar/channel (coroutine-safe). Status: stable.lib/task_queue/— min-heap task queue. Status: stable.lib/task_runner/— Make-style task runner with topo dependency resolution. Status: stable.lib/taskgraph/— task DAG. Status: wip.lib/workflow/— workflow primitives. Status: stable.lib/pipeline/— lazy data pipeline. Status: stable.lib/pipeline_dsl/— composable lazy DSL. Status: stable.lib/circuit_breaker/— fault-tolerant call wrapper (CLOSED/OPEN/HALF_OPEN). Status: stable.lib/connection_pool/— generic connection pool. Status: stable.lib/rate_limiter/— token bucket. Status: stable.lib/retry/— retry strategies (exp/linear/fib/none) + circuit breaker. Status: stable.lib/cron/— cron scheduler. Status: stable.lib/cron_parser/— cron expression parser (5-field + 6-field). Status: stable. Parallel tolib/cron/.lib/timerfd/— Linux timerfd FFI. Status: wip.lib/notify/— notification dispatch. Status: stable.
Data structures
lib/bigint/— arbitrary-precision integer (base-10^7 chunks). Status: stable.lib/bignum/— BigDecimal-style arbitrary precision decimal float. Status: stable.lib/bin_packing/— bin-packing algorithms. Status: stable.lib/bitarray/— packed bit storage with multi-bit fields. Status: stable.lib/bits/— bitset + Bloom filter. Status: stable.lib/bitset/— auto-growing dense bitset. Status: stable. Parallel tolib/bits/.lib/bloom/,lib/bloom_count/,lib/bloom_filter/,lib/bloom_clock/— Bloom variants. Status: stable. Multiple parallel impls.lib/cache/,lib/lru/,lib/lru_cache/,lib/lru_ttl/— caches. Status: stable. Multiple parallel impls.lib/columnar/— columnar storage / aggregation. Status: stable.lib/consistent_hash/— consistent hashing. Status: stable.lib/count_min/— Count-Min Sketch. Status: stable.lib/cuckoo/— cuckoo filter (with delete). Status: stable.lib/deque/— double-ended queue. Status: stable.lib/disjoint_set/— union-find. Status: stable.lib/fenwick_tree/— Fenwick / Binary Indexed Tree. Status: stable.lib/hamt/— hash array mapped trie. Status: stable.lib/heap/,lib/pairing_heap/— heaps. Status: stable.lib/hyperloglog/— HyperLogLog++. Status: stable.lib/interval/,lib/interval_tree/— interval arithmetic + interval BST. Status: stable.lib/inverted_index/— inverted index. Status: stable.lib/kdtree/— k-d tree. Status: stable.lib/kv_store/— in-memory KV with TTL + namespaces. Status: stable.lib/multimap/,lib/multiset/,lib/ordered_map/,lib/set/— collection variants. Status: stable.lib/patricia_trie/— radix/compressed trie. Status: stable.lib/persistent/— persistent (immutable) data structures. Status: stable.lib/pool/,lib/pool_allocator/— object/arena pools. Status: stable.lib/quadtree/,lib/spatial_hash/— 2D spatial indices. Status: stable.lib/queue/— priority + FIFO + ring buffer. Status: stable.lib/red_black_tree/— RB tree. Status: stable.lib/ringbuf/— ring buffer. Status: stable.lib/rope/— rope structure for big strings. Status: stable.lib/segment_tree/— segment tree. Status: stable.lib/skiplist/— skip list with rank queries. Status: stable.lib/sparse_matrix/— DOK/CSR/COO. Status: stable.lib/suffix_array/— suffix array + LCP. Status: stable.lib/treap/— treap (split/merge). Status: stable.lib/trie/— prefix tree. Status: stable.
Numerics / math / stats / ML
lib/astar/— A*. Status: stable.lib/bayesian_filter/— Naive Bayes spam-style filter. Status: stable.lib/benford/— Benford's Law analysis. Status: stable.lib/bezier/— Bézier curves & splines (2D/3D, Catmull-Rom, Hermite). Status: stable.lib/calendar/— calendar utilities. Status: stable.lib/complex/— complex numbers. Status: stable.lib/constraint_solver/— CSP backtracking + AC-3. Status: stable.lib/convex_hull/— convex hull. Status: stable.lib/datetime/,lib/duration/,lib/time/,lib/time_series/— time arithmetic. Status: stable.lib/decision_tree/— decision tree learner. Status: stable.lib/dice/— dice notation parser/evaluator. Status: stable.lib/dsp/— digital signal processing. Status: stable.lib/easing/— Penner easing. Status: stable.lib/finance/,lib/money/— financial primitives, exact-minor-units money. Status: stable.lib/finite_field/— GF(p) and GF(2^n) + polynomials. Status: stable.lib/flow_network/— Edmonds-Karp max flow + min cut. Status: stable.lib/genetic/— genetic algorithm framework. Status: stable.lib/geo/,lib/geo_hash/— geospatial. Status: stable.lib/geom/,lib/geometry_3d/,lib/game_math/,lib/vec/,lib/matrix/,lib/matrix_ext/— geometry/linear algebra. Status: stable.lib/graph/,lib/graph_algorithms/,lib/graph_coloring/,lib/graph_layout/,lib/graph_query/— graph family. Status: stable.lib/gradient_descent/— GD/Adam/RMSProp/L-BFGS/CG/SGD/line search/numdiff. Status: stable.lib/hamming/— Hamming codes + parity. Status: stable.lib/interpolation/,lib/interpolation_curves/— 1D/2D splines. Status: stable.lib/kalman/— Kalman filter. Status: stable.lib/knn/— k-nearest neighbors. Status: stable.lib/lindenmayer/— L-systems with turtle graphics + named presets. Status: stable.lib/luhn/— Luhn checksum. Status: stable.lib/math/— math utilities:tointeger(x) -> integer | nil. Status: stable.lib/math_ext/— extended math.*. Status: stable.lib/minimax/— minimax + αβ + iterative deepening + MCTS. Status: stable.lib/neural/,lib/neural_net/— feedforward NN with backprop. Status: stable. Two parallel impls.lib/noise_gen/— Value/Perlin/Simplex/Worley + fBm/turbulence/domain-warping/ridged. Status: stable.lib/number_theory/— number theory utilities. Status: stable.lib/particle/— particle systems. Status: stable.lib/physics_2d/— 2D rigid body (semi-implicit Euler, AABB/circle, joints). Status: stable.lib/pid/— PID controller. Status: stable.lib/rand/— RNG. Status: stable.lib/rational/— exact rationals (GCD-normalized). Status: stable.lib/roman_numeral/— Roman numerals (Unicode, vinculum, ordinals, additive notation). Status: stable.lib/sat/— DPLL SAT solver. Status: stable.lib/simulated_annealing/— simulated annealing. Status: stable.lib/stats/— descriptive stats, distributions, hypothesis tests, regression. Status: stable.lib/symbolic_diff/— symbolic differentiation. Status: stable.lib/tfidf/— TF-IDF. Status: stable.lib/units/— unit conversion. Status: stable.lib/voronoi/— Voronoi + Bowyer-Watson Delaunay. Status: stable.lib/wavelet/,lib/wave/— wavelet transforms / waveforms. Status: stable.lib/xgboost/— gradient-boosted trees. Status: stable.
Storage / DB
lib/conversation/— SQLite-backed conversation tree. Status: stable.lib/db/— DB abstraction. Status: stable.lib/ecs/— SQLite-backed entity-component store. Status: stable.lib/entity_component/— in-memory ECS. Status: stable. Parallel tolib/ecs/.lib/mini_orm/— pure-Lua in-memory ORM. Status: stable.lib/query_builder/— fluent SQL query builder. Status: stable.lib/raft/— Raft state machine (no networking). Status: stable.lib/schema/— declarative schema migration DSL. Status: stable.lib/sqlite/— SQLite FFI bindings. Status: stable.
OS / FFI / platform
lib/asm/— CPU feature detection + kernel compilation. Status: stable.lib/caps/— capability type aliases (no init.lua, types only). Status: stable.lib/dynamic_library/— dynamic library loading. Status: wip.lib/env/— environment variable access (capability-injected). Status: stable.lib/env_schema/— typed env var schema validation. Status: stable.lib/cloc/— count lines of code/comments/blank by language extension; capability-injected I/O. Status: stable.lib/expand_c/— C macro expansion viacc -E; capability-injected popen. Status: stable.lib/find_cli/— filesystem search with predicate DSL (name, size, age, bool combinators); capability-injected walk and time. Status: stable.lib/fs/— filesystem ops. Status: stable.lib/linux/— Linux /proc parsing (no init.lua). Status: wip.lib/path/— cross-platform path string ops (no I/O). Status: stable.lib/platform/— platform runner: tarball app loader + sandboxed entrypoints + cap dispatch + daemon + service + session. Status: stable.lib/platform/caps/cap_types.lua— type declarations for all platform cap interfaces (CliCap, TimeCap, DbCap, FsCap, HttpServerCap, HttpClientCap, LlmCap, ShellCap, ExecCap, CreateInstanceCap, HttpReq, HttpRes, etc.). Declarations only. Status: stable.lib/platform/caps/create_instance.lua—create_instancecap: lets a sandboxed app install a new instance of itself by handing the platform raw PNG/tarball bytes; the cap extracts the calling app's runtime from its installed tarball and feeds it throughimport_card. Returns(app_id, launch_url). Designed for the "frictionless new card" cross-origin path (ccv2). Status: stable.lib/platform/platform_types.lua— core platform type declarations (Manifest, CapDecl, EntryDef, AppRecord, TarEntry). Declarations only. Status: stable.lib/platform/manifest_caps.lua— shared cap-declaration helpers:merge_cap_declarations(daemon caps) with shorthand expansion ("required" / "optional") and top-level-plus-per-entrypoint merge. Extracted fromcli.luaso the merge logic can be tested without loading the CLI's auto-main side effects. Status: initial.lib/platform/projection_pipeline/— pure function(source_path, globals_files) -> ts_string | (nil, err)that typechecks a Lua projection against an injected prelude stack and transpiles it vialib/lua2tswithharden = true,module = "esm". Slice 1: no caching/daemon/mtime. Status: wip.lib/platform/xdg.lua— XDG Base Directory path resolution (data/state/config/cache/bin) with cross-platform fallbacks: Unix follows the XDG spec, Windows folds everything under%LOCALAPPDATA%\crescent.CRESCENT_HOMEoverrides the data dir; XDG env vars (XDG_DATA_HOME,XDG_STATE_HOME, etc.) override their respective paths. Convenience accessorsapps_dir(),db_dir(). Status: stable.lib/posix/— POSIX (no init.lua, TODOs noted). Status: wip.lib/process/— process spawning. Status: stable.lib/stb/— tiered stb_image / stb_image_resize2 (vendored binary > libvips > pure). Status: stable.
Apps and demos
lib/crescent_examples/— small demos (3d_view etc.). Not a library — examples only.lib/platform/apps/charactercardv2/— Character Card v2 app (server, presets, import, manifest). LLM access via caps.llm. Status: stable.lib/platform/apps/library/— general-purpose collection browser with adapter interface. Status: stable.lib/platform/apps/sillytavern/— SillyTavern source adapter. Status: wip.lib/platform/apps/system_dashboard/— system dashboard BFF (search, packs, projections, output). Status: stable.
Game / generative / simulation
lib/automata/— NFA/DFA construction + simulation + equivalence + minimization + regex. Status: stable.lib/automata_2d/— advanced 2D CA (Game of Life variants, totalistic). Status: stable.lib/cellular_automata/— 1D Wolfram + 2D totalistic. Status: stable. Parallel tolib/automata_2d/.lib/behavior_tree/— behavior tree. Status: stable.lib/circuit_sim/— analog circuit MNA simulator. Status: stable.lib/logic_circuit/— digital logic + Quine-McCluskey. Status: stable.lib/midi/— Standard MIDI File parser/encoder. Status: stable.lib/network_sim/— network simulator (deterministic LCG). Status: stable.lib/solitaire/— headless Klondike engine. Status: stable.lib/solitaire_cli/— interactive CLI renderer and runner for Klondike Solitaire; wrapslib/solitairewith injected I/O. Status: stable.lib/state/,lib/state_machine/,lib/statemachine/,lib/state_machine_hsm/,lib/fsm/— FSM/HSM family (5 parallel-ish impls;state_machine_hsmandstatemachineare HSM/Harel charts; others are flat). Status: stable.lib/steering/— Reynolds-style 2D steering behaviors. Status: stable.lib/tilemap/— tilemap. Status: stable.
Reliability / observability / config
lib/config/— layered config (args > env > layers > defaults). Status: stable.lib/feature_flags/— feature flags with rollout/rules/variants. Status: stable.lib/log/— structured logging with sinks. Status: stable.lib/metric/— Prometheus-compatible counter/gauge/histogram/summary. Status: stable.lib/openapi/— OpenAPI 3.x parser + request validation + typed routes. Status: stable.lib/pagination/— offset/page/cursor pagination. Status: stable.lib/schema_gen/— JSON Schema inference + validation. Status: stable.lib/schema_validator/— schema validator. Status: stable. Parallel tolib/json_schema/,lib/jsonschema/,lib/validate/,lib/validation/.lib/service_registry/— in-process service registry. Status: stable.lib/tracing/— OTel-inspired spans/traces/exporters. Status: stable.lib/validate/,lib/validation/— validation libs. Status: stable. Two parallel impls.
FP / optics / monads
lib/fp/— typeclass hierarchy:adt/,alt/,applicable/,bifunctor/,chainable/,either/,first/,fn/,foldable/,last/,mappable/,max/,maybe/,min/,monoid/,optics/,product/,profunctor/,semigroup/,sum/,traversable/. Seelib/fp/CLAUDE.md. Status: wip — design in flux.lib/curry/— composition + currying + partial application. Status: stable.lib/either/— top-level Either<L,R> + Maybe<T> with functor/monad. Status: stable. Parallel tolib/fp/either/andlib/fp/maybe/.lib/functional/— comprehensive FP toolkit. Status: stable.lib/iter/— iterator combinators. Status: stable.lib/option/— Option/Maybe. Status: stable. Parallel tolib/fp/maybe/andlib/either/Maybe.lib/result/— Result with Ok/Err sentinels. Status: stable.lib/stream/— stream combinators. Status: stable.
Misc / utilities
lib/agent/— agent (no header — entry is the test file?). Status: wip.lib/ai/— provider registry (lazy-loaded). Status: wip.lib/bayesian_filter/— see Numerics.lib/command/,lib/command_queue/— command pattern. Status: stable.lib/conversation/— see Storage / DB.lib/crdt/— CRDT primitives. Status: stable.lib/deepcopy/— deep copy + table utilities. Status: stable.lib/hot_reload/— hot module reload. Status: stable.lib/image_processing/— image processing. Status: stable.lib/ir/— intermediate representation. Status: stable.lib/memoize/— memoize/once/debounce/lru/ttl/weak/multi. Status: stable.lib/merge/— table merge. Status: stable.lib/merkle_tree/— Merkle tree (build, verify, sparse, diff, concat). Status: stable.lib/search/— search. Status: stable.lib/semver/— Semver 2.0 parser/comparator. Status: stable.lib/string_ext/,lib/table_ext/— extended Lua stdlib utilities. Status: stable.lib/spreadsheet/— spreadsheet grid with formula eval + dep tracking. Status: stable.lib/vm/— stack-based bytecode VM. Status: stable.