# Module Reference The full feature list and module table for `linen`. See [README.md](../README.md) for the project overview and quick start. ## Features ### `Data.Functor` — functor constructions missing from core - `Compose F G`, `Product F G`, `FunctorSum F G` — composition, product and coproduct of functors, with `Functor`/`Applicative` instances and verified `map_id` / `map_comp` laws. - `Const α` — the constant (phantom) functor, the building block for `foldMap`. - `Contravariant` / `LawfulContravariant` — contravariant functors, with `Predicate` and `Equivalence` instances. - `Data.Base64` — RFC 4648 Base64 `encode`/`decode` over core `ByteArray`, written as structural recursion (no `partial`, no `while`); the alphabet is computed arithmetically and roundtrips are exercised in the tests. - `Data.Bifunctor` / `LawfulBifunctor` — map over *both* type parameters (`bimap`, `mapFst`, `mapSnd`), with `Prod` / `Sum` / `Except` instances and verified identity & composition laws. - `Data.ByteString` — a slice over core `ByteArray` (`data`/`off`/`len` with a proof `off + len ≤ data.size`) giving **O(1) `take`/`drop`/`splitAt`**; a broad Haskell-`Data.ByteString` API (pack/unpack, folds, scans, search, group/inits/tails, prefix/suffix/infix, file & handle I/O) plus `BEq`/`Ord`/ `Hashable`. All loops are structural (no `partial`/fuel). - `Data.ByteString.Char8` — a Latin-1 `Char` view of `ByteString` (`String ↔ ByteString`, char-wise `map`/`filter`/`fold`/search), with `lines`/`words`/ `unlines`/`unwords` as structural recursions over the byte list. - `Data.ByteString.Lazy` — chunked lazy byte strings: non-empty strict chunks with a `Thunk`-deferred tail (structural recursion through `Thunk`), with `fromChunks`/`toStrict`, O(1) lazy `append`, chunk-spanning `take`/`drop`, folds, and content-based `BEq`/`Ord`/`Hashable`. - `Data.ByteString.Lazy.Char8` — a Latin-1 `Char` view of `LazyByteString` (`String ↔ LazyByteString`, char-wise `map`/`filter`/`fold`/`elem`). - `Data.ByteString.Short` — `ShortByteString`, a thin `ByteArray` newtype with `pack`/`unpack`/`index` and `toShort`/`fromShort` conversions to the strict slice, with a verified `length_toShort`. - `Data.ByteString.Builder` — a difference-list (`LazyByteString → LazyByteString`) builder with O(1) `append`: byte/word (BE/LE)/UTF-8/decimal/hex encoders, `toLazyByteString`/`toStrictByteString`, and verified monoid laws. - `Data.CaseInsensitive` — a `FoldCase` class and a proof-carrying `CI α` wrapper whose `BEq`/`Ord`/`Hashable` compare a folded copy (case-insensitively) while `ToString`/`Repr` keep the original; `String`/`Char` instances. - `Data.Conduit.Internal.Pipe` — conduit's core streaming `Pipe` type, ported **without `unsafe`**: a Freer-style `pipeM` (strictly positive) and a strict spine make it a total, kernel-checked `Functor`/`Monad` for any effect `m`. - `Data.Conduit.Internal.Conduit` — the `ConduitT` CPS/codensity wrapper over `Pipe` (O(1) monadic bind): `await`/`yield`/`leftoverC`/`liftConduit`/ `awaitForever`, the `.|` fusion operator, `runConduit`/`runConduitPure`/ `runConduitRes`, and `bracketP` for resource-safe streaming (built on `Control.Monad.Trans.Resource`). Marked `unsafe`: `awaitForever` recurses on a runtime `await` result with no structural or well-founded measure — a genuine unbounded corecursion, the same one Haskell accepts through laziness. - `Data.Conduit.Combinators` — the conduit combinator library over `ConduitT`: sources (`sourceList`/`sourceArray`/`unfoldC`/`repeatC`/`replicateC`/ `enumFromToC`), sinks (`sinkList`/`sinkArray`/`foldlC`/`foldMC`/`headC`/ `lengthC`/`sumC`/`allC`/`anyC`/`findC`/`maximumC`/…), and transformers (`mapC`/`mapMC`/`filterC`/`takeC`/`dropC`/`takeWhileC`/`concatMapC`/ `scanlC`/`intersperseC`/`chunksOfC`/…). - `Data.Configurator.Types` — a typed config `Value` (string/number/bool/list) with a structural (no-`partial`) `toString`, and `Config = HashMap String Value`. - `Data.Configurator` — a `key = value` config loader/parser (comments, dotted keys, quoted strings + escapes, numbers, booleans) with `lookup`/`require`/ `load`; parsers are structural recursions (no `Id.run`/`while`). - `Data.Default` — the `Default` typeclass (Haskell's `Data.Default`): sensible default values (`false`/`0`/`""`/`[]`/`none`/…), distinct from `Inhabited`. - `Data.IntMap` — Haskell's `Data.IntMap` API (`union`/`unionWith`/`intersection`/ `difference`/`adjust`/`toAscList`/`lookupMin`/`Max`/`isSubmapOf`/…) over `Std.HashMap Nat v`. - `Data.Map` — Haskell's ordered `Data.Map k v` over `Lean.RBMap` ($O(\log n)$): the same combinator surface as `IntMap`, plus `mapKeys`, ascending `toList`/`keys`/`elems`, and verified empty-map laws. - `Data.Set` — Haskell's ordered `Data.Set` (`Set'`) over `Lean.RBMap _ Unit`: `member`/`insert`/`union`/`intersection`/`difference`/`isSubsetOf`/`mapSet`/ folds/`findMin`/`Max`, ascending dedup `toList'`, and empty-set laws. - `Data.Bits` / `FiniteBits` — a Haskell-style bitwise typeclass over `UInt8/16/32/64`: `and`/`or`/`xor`/`complement`/shifts, plus `testBit`, `bit`, `popCount`, `setBit`/`clearBit`/`complementBit`, and width-bounded `countLeadingZeros` / `countTrailingZeros` (carrying `≤ finiteBitSize` proofs). - `Data.Bool.guard'` — the list-valued guard (`[x]` / `[]`) that core lacks (`Data.Bool.bool` is already Lean core's `bool`, so it isn't re-ported). - `Data.Char'` — the Haskell `Data.Char` predicates core lacks (`isAscii`, `isLatin1`, `isControl`, `isPrint`, `isOctDigit`, `isAsciiUpper`/`Lower`, `isPunctuation`) plus `digitToInt` (proof-carrying `{n // n < 16}`) and `intToDigit`, with a verified hex roundtrip. - `Data.Complex α` — complex numbers over any numeric type: `Add`/`Sub`/`Mul`/`Neg` instances, `conjugate`, `magnitudeSquared`, with `conjugate`-involution and addition-commutativity proofs. - `Data.Fixed` — fixed-point decimals with **type-level precision** (`Fixed 2` ≠ `Fixed 4`): exact `Add`/`Sub`/`Neg`, rescaling `Mul`, `ToString`, and exact `toRat`, with `add_exact`/`sub_exact`/`neg_neg` proofs. - `Data.Function.on` / `applyTo` — the two `Data.Function` combinators core lacks (`flip`/`const` already exist); `applyTo` is the function form of the `|>` pipe. - `Data.Ix` — an index typeclass (Haskell `Data.Ix`): `range`, `rangeSize`, `inRange`, and a proof-carrying `index` (`{n // n < rangeSize bounds}`), with `Nat`/`Int`/`Char`/`Bool`/product instances. - `Data.List.NonEmpty` — a non-empty list (`head`/`tail`) with total `head`/`last`, `length : {n // n ≥ 1}`, folds (`foldr1`/`foldl1`), and `Functor`/`Monad` instances; length-preservation proofs for `reverse`/`map`. - `Data.List'` — the `Data.List` operations core lacks: `transpose` (structural, no fuel), `tails`/`inits` (as `NonEmpty`), `subsequences`, `permutations`, `mapAccumL`/`mapAccumR`, `sortOn`, `maximumBy`/`minimumBy`, `unionBy`/ `intersectBy`, `insertBy`. - `Data.Foldable` — a `Foldable` typeclass (`foldr`/`foldl`/`toList`) with derived `foldMap`/`null`/`length`/`any`/`all`/`find?`/`elem`/`sum`/`product`/`minimum?`/ `maximum?` and total `minimum1`/`maximum1`; instances for `List`/`Option`/`NonEmpty`/`Sum`. - `Data.Newtype` — the Haskell monoid/semigroup wrappers `Dual`, `Endo`, `First`, `Last`, `Sum`, `Product`, `All`, `Any`, each with an `Append` instance and a verified associativity law. - `Data.Ord` — `Down` (reversed `Ord`/`BEq`, for descending sorts) and a proof-carrying `clamp` returning `{y // lo ≤ y ∧ y ≤ hi}` (`comparing` is core's `compareOn`). - `Data.Proxy` — a phantom-type proxy (no runtime data) with `Functor`/`Monad` instances and verified functor/monad laws. - `Data.Rat.round` — round-half-away-from-zero for core `Rat` (Haskell `Data.Ratio` is core's `Rat`, which already has the arithmetic, `floor`/`ceil`/`abs`). - `Data.Scientific` — arbitrary-precision scientific notation $c \times 10^{e}$ (Haskell's `scientific` package): `normalize`/`isZero`/`isInteger`, `toRealFloat`/`fromFloatDigits`, `toBoundedInteger`, `toDecimalDigits`, and `Add`/`Sub`/`Mul`/`Neg`/`BEq`/`Ord`/`OfScientific` instances, with verified `isZero_iff`/`normalize_zero`/`neg_neg` laws. - `Data.String` — Haskell's `Data.String`: the `IsString` class for overloaded literals, plus `String.words`/`unwords`/`unlines` (`lines` is core's `splitOn "\n"`). - `Data.Traversable` — a `Traversable` typeclass (`traverse`/`sequence`) over core `Functor`/`Applicative`, with `List`/`Option`/`NonEmpty` instances, a `LawfulTraversable` law class, and the verified `traverse pure = pure` law for `Option` (Haskell's `Identity` is core's `Id`). - `Data.Unique` — globally unique identifiers (Haskell's `Data.Unique`): `newUnique : IO Unique` hands out distinct, strictly increasing values from a process-global `IO.Ref` counter, with `BEq`/`Ord`/`Hashable`/`hashUnique`. - `Data.Void` — the uninhabited type (Haskell's `Void` is core's `Empty`, `absurd` is `Empty.elim`): adds the vacuous `BEq`/`Ord`/`Hashable`/`ToString` and `Inhabited (Empty → α)` instances plus the `Empty → α` singleton law. ### `Control` — applicative & monad combinators missing from core - `Control.Applicative.asum` — fold a list of alternatives with `<|>`. - `Control.Monad.join`, `replicateM`, `replicateM_`, `when`, `unless` — flatten, repeat, and conditionally run monadic actions (with the `join_pure` law). - `Control.Monad.Except` — `mtl`-named `throwError`/`catchError`/`liftEither`/ `mapExceptT`/`withExceptT`/`runExceptT` over core's own `ExceptT`/`Except`. - `Control.Monad.Reader` — the `Reader` alias plus `mtl`-named `ask`/`asks`/ `local`/`runReaderT`/`runReader`/`mapReaderT` over core's own `ReaderT`/ `read`/`ReaderT.adapt`. - `Control.Monad.State` — the `State` alias plus `mtl`-named `put`/`gets`/ `runStateT`/`evalStateT`/`execStateT`/`runState`/`evalState`/`execState` over core's own `StateT` (`get`/`set`/`modify` are core's `MonadState` names already — used directly, not re-wrapped). - `Control.Monad.Trans` — the `mtl`-named `lift` over core's own `MonadLift`/`monadLift`, with the `lift_pure`/`lift_bind` laws restated generically (core's `MonadLift`/`LawfulMonadLift` already generalize Haskell's `MonadTrans` class, with lawful instances for `ExceptT`, `ReaderT`, and `StateT`). - `Control.Monad.Trans.Resource` — deterministic, exception-safe LIFO resource cleanup: `ResourceT = ReaderT (IO.Ref CleanupMap)` over core's own `ReaderT` (only a `MonadLift IO` instance needed on top), `allocate`/`release`/ `runResourceT` (cleanup runs via `try`/`finally`, even on an exception), and a verified `releaseKey_eq` law. - `Control.Category` / `LawfulCategory` — categories with identity and associative composition (`≫`, diagrammatic), with the lawful `Fun` instance. - `Control.Arrow` / `ArrowChoice` — arrows over a `Category`: `arr`, `first`, `second`, `split`, and (over `Sum`) `left`, `right`, `fanin`, with `Fun` instances. - `Control.Exception.bracket` / `onException` — the IO resource/cleanup patterns core lacks as functions (`try`/`catch`/`finally` map to `IO.toBaseIO`/`tryCatch`/ `tryFinally`), built on `tryFinally` / `tryCatch`. - `Control.AutoUpdate` — periodically refreshed cached values: a non-blocking getter backed by a dedicated OS thread and a `Std.CancellationToken` for clean shutdown. - `Control.Concurrent.MVar` — a promise-based synchronisation variable (empty or full) with FIFO-fair waiters that are dormant tasks, not blocked OS threads. - `Control.Concurrent.Chan` — an unbounded FIFO channel with `dup` (broadcast to independent readers); blocking reads are dormant promises, not blocked threads. - `Control.Concurrent.QSem` — a quantity semaphore (`wait`/`signal`/`withSem`) with a `Nat` count that can't underflow and FIFO-fair, promise-based waiters. - `Control.Concurrent.QSemN` — a generalised semaphore that acquires/releases arbitrary quantities (`wait n`/`signal n`/`withSemN`), greedily waking waiters. - `Control.Concurrent.Green` — a fair green-thread monad: awaiting a `Task` frees the pool thread (via `BaseIO.bindTask`, never `IO.wait`), with cancellation, error handling, and `MVar`/`Chan`/`QSem` integration. - `Control.Concurrent` — thread management built entirely on the `Green` model: `forkIO`, `forkFinally`, `forkGreen`, `killThread` (cooperative), `waitThread`, `threadDelay`, `yield`, and a monotonic `ThreadId`. All forks run as fair green threads started on Lean's task pool. - `Control.Monad.STM` — software transactional memory: `STM α = BaseIO (STMResult α)`, with every transaction serialized on a single global `Std.Mutex` (`atomically`/`retry`/`orElse`/`check`); `atomically`'s retry-until-commit loop is a plain `while`, not `partial def`. - `Data.OpenUnion` — an open union over a row of effect functors: `Union effs α` holds a value of exactly one effect drawn from `effs`, and `Member eff effs` (`inj`/`prj`) witnesses membership by instance search. Ported safe-by-construction — upstream `freer-simple` backs `Union` with an `unsafeCoerce`d `(Int, Any)` pair for GHC dispatch speed, which buys nothing in Lean. - `Control.Monad.Effect` — the `Eff` monad over an open effect row, so a signature is an effect whitelist: `Eff [Reader Config] α` provably cannot touch state, the filesystem or the network. `send` lifts one operation given `Member`; `interpret`/`reinterpret`/`raise` reshape the row; `run`/`runM`/ `interpretM` discharge it. Upstream's `Data.FTCQueue` is dropped (a GHC-only guard against quadratic left-nested `>>=`; the direct Freer encoding is behaviour-identical) and `Control.Monad.Freer.TH` with it (no Template Haskell in Lean). - `Control.Monad.Effect.Reader` / `.State` — the reader and state effects expressed over `Eff`, illustrating the row mechanism and composing in a single computation. Not replacements for the mtl-style `Control.Monad.Reader`/`State`, which remain the recommended API for ordinary environment/state threading. - `Control.Monad.Effect.Error` — failure in the row: `throwError`/`runError` (into `Except`)/`catchError`, the last built on `interpose` so recovery does not remove the effect. The request answers with `Empty`, recording that a throw never returns. - `Control.Monad.Effect.Writer` — accumulate output: `tell`, with `runWriter` taking the monoid's unit and append explicitly (Lean has no `Monoid` class) and `runWriterAppend` covering `[Append ω] [Inhabited ω]`. - `Control.Monad.Effect.NonDet` — branching search: `mzero`/`mplus`/`select`/ `guard`, collected by `makeChoiceA`. A choice is one request answered with a `Bool` *both ways*, so the continuation runs once per branch. `msplit` is not ported — it is not structurally recursive and genuinely diverges on an infinite search tree. - `Control.Monad.Effect.Coroutine` — suspend and resume: `yield`, and `runC` reporting a `Status` that is either `done` or will `continue` given a reply. `Status` is self-referential *through* `Eff`, which is why `Eff`'s payload is universe-polymorphic; driving a coroutine to completion is the caller's job, since one may yield forever. - `Control.Monad.Effect.Fresh` — hand out distinct `Nat`s: `fresh`/`runFresh`. - `Control.Monad.Effect.Trace` — diagnostics in the row, so `Eff [Trace] α` announces that a computation logs and a row without `Trace` provably does not: `trace`, with `runTrace` printing to stdout and `runTracePure` collecting purely. - `Control.Monad.Effect.FileSystem` — a capability-restricted filesystem effect, `linen`-original, showing what an effect system gains from dependent types, at two strengths. **Permissions:** `FileSystem cap` is indexed by a `Capability` **value** (`canRead`/`canWrite`/`canDelete`) and each operation carries a `Prop`-valued proof that `cap` grants it, demanded via the `CanRead`/`CanWrite`/`CanDelete` classes — so `writeFile` under a read-only capability fails to elaborate, and read/write/delete are separately grantable *within one effect*. **Path scope:** the capability's `scopes` confine every operation to paths beneath a matching root, as an obligation `cap.permits op p = true` discharged by `decide` at the call site — so a sandboxed capability rejects `readFile p!"/etc/passwd"` too, constraining the effect's *arguments* and not just its operation set. Each `Scope` carries its own operation list, so a single capability can be read-write under one directory and read-only under another; scopes union, and `Capability.union` is proved to take nothing away (`permits_union_left`/`_right`). Neither is expressible with Haskell's type-level rows, which name effects but carry no structure. Paths are component lists (`List String`, written with the `p!` macro) both because Lean's `String.startsWith` does not reduce under `decide` and because component-wise containment is the correct meaning of "under this directory" — a string prefix would wrongly admit `/tmp/sandbox-evil` under `/tmp/sandbox`. Runtime paths go through `ScopedPath.check?`, which validates and returns the evidence. The handler re-checks nothing: every proof is in the constructor, so enforcement happens once, statically. - `Control.Monad.Effect.HTTP` — the same capability idiom applied to an HTTP client, `linen`-original. **Method permissions:** `HTTP cap` is indexed by a `Capability` value whose `canGet`/`canHead`/`canPost`/`canPut`/`canPatch`/ `canDelete` bits are demanded as `Prop`-class instances, so `post` under a read-only web capability fails to elaborate. **URL scope:** the capability's `scopes` confine every request, as an obligation `cap.permits m url = true` discharged by `decide`, and each scope carries its own method list — so one capability expresses "GET anywhere under `/v1`, POST only to `/v1/events`", which is a restriction on *(method, argument)* pairs that no type-level row can reach. `Url` is structured for the reason `Path` is: a host is DNS labels and a path is segments, so `api.example.com.evil.com` is a different host rather than a string-prefix extension of `api.example.com`, and `/v1-admin` is not under `/v1`; scheme and port are matched exactly too. Literals use the `u!` macro, runtime URLs `ScopedUrl.check?`. Query strings are passed separately and deliberately take no part in scoping, not being part of the path hierarchy. `runHTTP` dispatches through `Network.HTTP.Client`; `runHTTPWith` takes the transport as a parameter, so the effect is testable without a network. - `Control.Monad.Effect.PostgreSQL` — the idiom over a database, restricting in three parts of decreasing strength, `linen`-original. **Connection target:** `host`/`port`/`database`/`user` are capability fields and `runPostgreSQL` builds its connection string from them alone, so a computation cannot name another database or authenticate as another role — structural, with no obligation to discharge because no term could express the alternative. **Statement kinds:** `canSelect`/`canInsert`/`canUpdate`/`canDelete` as `Prop`-class instances. **Table scope:** `tables`, as a `decide`-discharged obligation, so a reporting capability admits `orders` and refuses `users` while granting the same `SELECT`. Queries are an AST rather than strings, for exactly the reason paths are component lists — a `String` of SQL is opaque to `decide` — and the rendered SQL is derived from the checked value, so the two cannot disagree; every literal is bound as a `$n` parameter, so there is no injection surface either. There is deliberately no `rawSql` escape hatch, which would weaken every guarantee to "cannot be written without lying". `runPostgreSQL` goes through `Database.SQL.Session`; `dryRun` interprets purely into the SQL a computation would send, so tests need no live server. - `Control.Concurrent.STM.TVar` — a transactional variable over `IO.Ref`: `newTVarIO`/`newTVar`/`readTVar`/`writeTVar`/`modifyTVar'`. - `Control.Concurrent.STM.TMVar` — `TVar (Option α)`: `newTMVar(IO)`/ `newEmptyTMVar(IO)`/`takeTMVar`/`putTMVar`/`readTMVar`/`tryTakeTMVar`/ `tryPutTMVar`/`isEmptyTMVar`. - `Control.Concurrent.STM.TQueue` — a transactional, amortized-O(1) FIFO over two `TVar`-held lists: `newTQueue(IO)`/`writeTQueue`/`readTQueue`/ `tryReadTQueue`/`isEmptyTQueue`/`peekTQueue`. ### `Data.Json` — a tiny JSON library - `Value` AST with predicates, accessors and object field access. - `ToJSON` / `FromJSON` typeclasses. - `encode` / `encodePretty` and `decode` / `decodeAs`, with proven encode→decode **roundtrip theorems**. ### `Time` — the `time` package, over `Std.Time` A port of Hackage's [`time`](https://hackage.haskell.org/package/time) (v1.15), per [`docs/imports/Time/dependencies.md`](imports/Time/dependencies.md). Lean's own `Std.Time` (ships with the pinned toolchain) already covers `time`'s core job — Gregorian/ISO-week/ordinal calendar arithmetic, clocks, durations, IANA-tzdata timezones, and locale-aware `strftime`-style formatting/parsing — so this import is mostly a documented substitution; `Linen.Data.Time.Calendar`/ `.Clock`/`.LocalTime` (added ad hoc during the `sqlite-simple` import, before `Std.Time` was known) are now rebuilt on `Std.Time.Date.PlainDate`/ `Std.Time.Duration`/`Std.Time.Zoned` respectively, fixing a bug where `Data.Time.Clock.getCurrentTime` read a *monotonic* clock instead of real wall-clock time. The bespoke `Linen.System.Time`/`ffi/time.c` wall-clock FFI shim is retired outright — subsumed by `Std.Time.DateTime.Timestamp.now`. - `Linen.Time.Calendar.CalendarDiffDays` — a `(months, days)` calendrical period, `Semigroup`/`Monoid` under addition, `calendarDay`/`calendarWeek`/ `calendarMonth`/`calendarYear` constants, scale-by-integer. - `Linen.Time.Calendar.Month` — an absolute month counter since a fixed origin, `addMonths`/`diffMonths`, and `DayPeriod`-style `periodFirstDay`/`periodLastDay`/`dayPeriod` relating it to `Std.Time.Date.PlainDate` — a standalone counter type `Std.Time`'s per-date `Month.Ordinal` field doesn't provide. - `Linen.Time.Calendar.Quarter` — the same shape one level up: `QuarterOfYear` and an absolute `Quarter` counter, `addQuarters`/`diffQuarters`, `monthQuarter`/`dayQuarter`. - `Linen.Time.Calendar.Julian` — the proleptic Julian calendar: its own leap-year rule (no Gregorian century correction), month lengths, and `addJulianMonthsClip`/`RollOver`/`addJulianYearsClip`/`RollOver` etc. arithmetic — a genuinely different calendar system from `Std.Time`'s Gregorian-only implementation. - `Linen.Time.Calendar.Easter` — the Gregorian and Orthodox Easter-date algorithms (`gregorianEaster`/`orthodoxEaster`, `sundayAfter`), per Reingold & Dershowitz's *Calendrical Calculations*. - `Linen.Time.CalendarDiffTime` — the time-valued sibling of `CalendarDiffDays`: `(months, Duration)` instead of `(months, days)`. - `Linen.Time.UniversalTime` — `UT1` mean solar time as a Modified-Julian-Date-plus-fraction rational, with longitude-parameterised conversion to/from `Std.Time`'s civil wall-clock time — `Std.Time` only models UTC/civil time, never earth-rotation-based UT1. - `Linen.Time.Clock.TAI` — `AbsoluteTime` (a TAI instant) and day-keyed leap-second-map conversions `utcToTAITime`/`taiToUTCTime`/`utcDayLength` (`LeapSecondMap = Day -> Option Int`, caller-supplied, matching upstream's own refusal to bundle a hardcoded leap-second table). ### `System.Console.Ansi` — terminal styling - `Color` / `Intensity` enums and the ANSI escape-code builders (`setFg`, `setBg`, `colored`, `bold`, …). ### `System.Exit` — process termination - `ExitCode` (`success` | `failure n`) with `toUInt32`/`isSuccess`/`ToString` and the verified `isSuccess_iff` law, plus `exitWith`/`exitSuccess`/ `exitFailure` wrapping core `IO.Process.exit`. ### `System.Log.FastLogger` — buffered logging - `System.Log.FastLogger` — a thread-safe buffered logger (`Std.Mutex`-protected buffer, auto-flush on full / on close) to stdout/stderr/file/callback: `newLoggerSet`/`pushLogStr`/`flushLogStr`/`withFastLogger`. ### `System.Keychain` — OS credential-store access - Ports the Rust [`keyring`](https://crates.io/crates/keyring) crate (`keyring-rs`), Lean-ified: the crate name only makes sense as a registry identifier, so the stdlib's own `System.…` convention is used instead of mirroring it (`AGENTS.md`'s `WaiAppStatic` → `WebApp.Static` treatment). - `Entry`/`Credential` façade over a small handle identifying a secret by `(service, account)`: `setPassword`/`getPassword`/`deleteCredential` (UTF-8 text) and `setSecret`/`getSecret` (raw bytes), dispatching in C (`ffi/keychain.c`, symbols `linen_keychain_*`) to whichever native store the platform provides — macOS Security.framework Keychain, Linux D-Bus Secret Service (via libsecret, only linked when its `.pc` file is present), or the Windows Credential Manager. Only the macOS backend is exercised by this repository's CI; Linux/Windows are written against the real APIs but unverified in this environment. - All three operations raise a plain `IO.Error` on failure (matching every other native FFI module here), including on a missing entry — mirroring upstream's `Err(Error::NoEntry)` rather than degrading to `Option`. ### `Network.HTTP` — HTTP wire framing - `Network.HTTP.Chunked` — HTTP/1.1 chunked transfer encoding over `ByteArray`: `chunkedTransferEncoding` / `chunkedTransferTerminator` / `encodeChunked`, with the hex chunk length via core `Nat.toDigits`. - `Network.HTTP.Date` — HTTP date parsing/formatting (RFC 7231): `HTTPDate`, `parseHTTPDate` (IMF-fixdate + asctime), and `formatHTTPDate` (IMF-fixdate with the day-of-week from Zeller's congruence). - `Network.HTTP.Types.Header` — case-insensitive header names (`HeaderName = CI String`), the `Header`/`RequestHeaders`/`ResponseHeaders` aliases, and the ~50 standard header-name constants (`hContentType`, `hHost`, …). - `Network.HTTP.Types.Method` — `StdMethod`/`Method` (standard or custom), `parseMethod`/`renderMethod`, and the RFC 9110 §9.2 `isSafe`/`isIdempotent` predicates with verified laws (incl. safe ⇒ idempotent). - `Network.HTTP.Types.Status` — proof-carrying `Status` (a `statusValid : 100 ≤ code ≤ 999` field, erased at runtime), ~50 named codes + aliases, the `isInformational`/…/`isServerError` class predicates, and the RFC 9110 §6.4.1 `mustNotHaveBody` rule with verified theorems. - `Network.HTTP.Types.URI` — query-string `parseQuery`/`renderQuery` (over `Query = List (String × Option String)`) and percent-encoding `urlEncode`/`urlDecode` (the latter a structural recursion over the char list). - `Network.HTTP.Types.Version` — `HttpVersion` (major/minor) with lexicographic `Ord`, `ToString` (`HTTP/1.1`), the `http09`/`http10`/`http11`/`http20` constants, and well-formedness theorems. - `Network.HTTP.Client.Types` — HTTP/1.1 client core types: the transport `Connection` (read/write/close callbacks abstracting TCP vs TLS), the wire-level `Request`, and the parsed `Response` with case-insensitive `findHeader`, `contentLength`, and `isSuccess`. - `Network.HTTP.Client.Request` — HTTP/1.1 request serialization (`serializeRequest`): request line + headers, auto-adding `Host` (with non-default port), `Content-Length` (when a body is present), and `Connection: close`, plus `sendRequest` over a `Connection`. - `Network.HTTP.Client.Response` — HTTP/1.1 response parsing: status line, headers, and bodies via Content-Length / chunked / read-until-close (`receiveResponse`, `performRequest`). The network read-loops are condition-driven `while`s — no `partial`. ### `Network.HTTP2` — HTTP/2 framing (RFC 9113) - `Network.HTTP2.Frame.Types` — core framing types: a `StreamId` carrying an (erased) 31-bit proof, the `FrameType`/`ErrorCode`/`SettingsKeyId` closed inductives with total `UInt8`/`UInt16`/`UInt32` conversions (provably inverse for defined values), `FrameFlags` bit ops, `FrameHeader`/`Frame`, and a `Settings` record whose fields carry RFC value-range proofs. - `Network.HTTP2.Frame.Decode` — wire-format parsing: big-endian integers, `decodeFrameHeader`, SETTINGS (`decodeSettingsPayload` via fuel-free `List.mapM`, `applySettings` with proof-carrying updates), GOAWAY / WINDOW_UPDATE / RST_STREAM / PRIORITY / padding, and `validateFrameSize`. - `Network.HTTP2.Frame.Encode` — wire-format serialisation: big-endian integers, `encodeFrameHeader`/`encodeFrame`, frame builders (SETTINGS/PING/GOAWAY/WINDOW_UPDATE/RST_STREAM/HEADERS/DATA/CONTINUATION), `encodePriority`/`encodePadding`, and `splitHeaderBlock` (fuel-free chunking). - `Network.HTTP2.HPACK.Huffman` — a complete HPACK (RFC 7541 Appendix B) Huffman codec: the fixed 257-entry code table, `huffmanEncode` (MSB-first bit packing with EOS-`1`s padding) and `huffmanDecode` (prefix-trie walk with padding validation), verified against the RFC's published test vectors. Total (structural fold over the bit list — no `partial`/fuel). - `Network.HTTP2.HPACK.Table` — the HPACK header tables: the 61-entry RFC 7541 Appendix A static table, and a `DynamicTable` FIFO with size-based eviction (entry size `|name|+|value|+32`, fuel-free), plus `find`/`indexLookup`/ `findInTables` over the combined static + dynamic index space. - `Network.HTTP2.HPACK.Decode` — HPACK header-block decoding: the variable-length `decodeInteger` (bounded structural fold) and `decodeString` (raw + Huffman) primitives, and `decodeHeaders` dispatching the indexed / literal / size-update representations (well-founded on the unconsumed input), threading the dynamic table. Tested against the RFC 7541 Appendix C wire vectors. - `Network.HTTP2.HPACK.Encode` — HPACK header-block encoding: `encodeInteger` (prefix varint, recursing on a strictly-decreasing value), `encodeString`, the `HeaderRep` representations (`encodeHeaderRep`), and `encodeHeaders` (greedy indexing), verified by encode→decode round-trips. - `Network.HTTP2.Types` — connection-level types: `ConnectionError` (→ GOAWAY) and `StreamError` (→ RST_STREAM), the `HeaderBlockState` machine assembling header blocks across HEADERS + CONTINUATION frames, and an `HTTP2Result` three-way result with `map`/`bind`. - `Network.HTTP2.Stream` — the stream lifecycle (RFC 9113 §5.1): the `StreamState` machine, per-stream `StreamInfo` (windows + priority), and a `StreamTable` over `Std.HashMap` with `openClientStream`/`updateState`/ `updatePriority`/`activeStreamCount` and stream-id classification. - `Network.HTTP2.FlowControl` — flow-control windows (RFC 9113 §5.2): `FlowWindow` with `increment` (WINDOW_UPDATE, zero/overflow checks), `consume`/`available`, and signed `adjust` for SETTINGS changes; plus `ConnectionFlowControl` and per-stream window updates. - `Network.HTTP2.Server` — the server-side connection handler: preface validation, SETTINGS/PING/WINDOW_UPDATE/GOAWAY handling, HEADERS + CONTINUATION assembly and HPACK decode, response encoding (`sendResponse`), and the `runHTTP2Connection` frame loop (driven by EOF/GOAWAY — no fuel counter). ### `Network.HTTP3` — HTTP/3 over QUIC (RFC 9114) - `Network.HTTP3.Error` — the `H3Error` error-code enum (RFC 9114 §8.1, `0x100`–`0x110`) with total `toCode`/`fromCode` conversions and verified round-trip laws. - `Network.HTTP3.Frame` — HTTP/3 framing (RFC 9114 §7): `FrameType`, the QUIC variable-length integer codec (RFC 9000 §16, minimal encoding, fuel-free decode), `Frame.encode`/`decode`, and `H3Settings` encode/decode. - `Network.HTTP3.QPACK.Table` — the 99-entry QPACK static table (RFC 9204 Appendix A, 0-indexed) with `staticLookup` and `staticFind` (exact then name-only). - `Network.HTTP3.QPACK.Decode` — static-table-only QPACK decoding (RFC 9204): the prefix integer (`decodeQInt`, bounded fold) and string-literal primitives, and `decodeHeaders` for indexed / literal-with-name-reference / literal-name field lines (well-founded loop; rejects dynamic-table references). - `Network.HTTP3.QPACK.Encode` — static-table-only QPACK encoding: `encodeQInt` (prefix varint, recursing on a strictly-decreasing value), `encodeStringLiteral`, and `encodeHeaders` (compact indexed form where possible), verified by encode→decode round-trips. - `Network.HTTP3.Server` — the HTTP/3 request/response layer on top of a QUIC connection: `H3Request`/`H3Response`, the `H3Handler` handler type, `sendResponse` (QPACK-encodes and frames a response over a `QUICStream`), and `handleRequestStream`/`handleConnection` (decode HEADERS, dispatch, reply). `handleConnection` is stubbed pending QUIC stream-accept support. ### `Network.Socket` — POSIX sockets & event multiplexing - `Network.Socket.Types` — the type layer for a phantom-typed socket API: `Family` / `SocketType` / `ShutdownHow` enums with their FFI tag encodings, an `EventType` readiness bitmask (kqueue/epoll), `SockAddr` / `AddrInfo`, and a `Socket (state : SocketState)` handle whose POSIX lifecycle (`fresh → bound → listening`, `connecting → connected`, `closed`) is **enforced at compile time** (15 state-distinctness theorems; `close` carries a `state ≠ .closed` proof obligation that makes double-close a type error). Non-blocking operations return `Accept` / `Connect` / `Recv` / `Send` / `Poll` outcome sum types. - `Network.Socket.FFI` — `@[extern]` bindings to a portable C shim (`ffi/network.c`): socket create / bind / listen / accept / connect, blocking and non-blocking send / recv, UDP `sendto` / `recvfrom`, socket options, `getAddrInfo`, a buffered `RecvBuffer`, and an event loop over **kqueue (macOS) / epoll (Linux)**. The shim is compiled and linked by `lakefile.lean` (`extern_lib linenffi`); the `Linen` library is `precompileModules`-enabled so the bindings are callable from `#eval`. - `Network.Socket` — the safe, high-level API over the FFI: `socket → bind → listen → accept` (and `connect`/`connectFinish`, `send`/`recv`, `sendAll`, UDP `sendTo`/`recvFrom`) with each transition's pre/post state in its signature, a `close` whose `state ≠ .closed` proof obligation makes double-close a type error, `withSocket` / `withListenTCP` / `withEventLoop` bracket helpers, `listenTCP`/`listenTCP6`, address introspection, and an `EventLoop` (kqueue/epoll) wrapper. - `Network.Socket.EventDispatcher` — the bridge from socket readiness to the green-thread model: a **sharded** set of dispatch threads (fds partitioned by `fd % N`, each shard its own kqueue/epoll loop + waiter map) resolves an `IO.Promise` when a socket is ready, so `waitReadable` / `waitWritable` (and `recvGreen` / `sendAllGreen`) **suspend a `Green` thread as a heap object instead of holding an OS thread**. This is what lets one worker pool serve many thousands of IO-bound connections. - `Network.Socket.Blocking` — blocking-style `accept` / `connect` / `send` / `sendAll` / `recv`, retrying on `wouldBlock` for tests, scripts, and code that doesn't need event-loop integration (production non-blocking I/O should use `EventDispatcher` instead). Every retry loop is a plain `while`, so the module needs no `partial def`. - `Network.Sendfile` — a portable `sendFile`/`sendFileSimple` for transferring a file (or `FilePart` range) over a connected socket, via chunked read + `Blocking.sendAll` (no platform `sendfile(2)` zero-copy syscall). - `Data.Streaming.Network` — Haskell's `Data.Streaming.Network`: `AppData`, `bindPortTCP`/`getSocketTCP`/`mkAppData`/`runTCPServer`, and `acceptSafe` (retry-on-transient-accept-error), with its retry loop a plain `while` instead of the upstream `partial def`. ### `Network.Mime` — MIME type lookup - `Network.Mime` — a port of Haskell's `Network.Mime` (`mime-types`): a `defaultMimeMap` (Apache/nginx/IANA extensions → MIME types), `mimeByExt` and `defaultMimeLookup` for resolving a file name to its content type, and a `fileNameExtensions` that yields the multi-part extensions most-specific-first (`"foo.tar.gz" ↦ ["tar.gz", "gz"]`) — rewritten from the upstream `partial` helper into **structural recursion** over the dot-separated components, and using `List.lookup` / `List.findSome?` instead of a bespoke assoc scan. ### `Network.URI` — RFC 3986 URI parsing, rendering, and resolution - `Network.URI` — a port of the `network-uri` package's `Network.URI`: the `URI`/`URIAuth` types, `parseURI`/`parseURIReference`/`parseRelativeReference`/ `parseAbsoluteURI`, `isURI`-style classifiers, percent-encoding (`escapeURIString`/`unEscapeString`), rendering (`uriToString`, a password-masking `ToString` instance), `pathSegments`, dot-segment removal, and relative-URI resolution (`relativeTo`/`relativeFrom`, matching every case in RFC 3986 section 5.4's worked example table). The upstream parser is built on `parsec`; here the grammar is a direct structurally-recursive recursive-descent parser over `List Char` instead. Two documented simplifications: bracketed IP-literal hosts (`[::1]`) are accepted at the character-class level rather than RFC 3986's full IPv6 group-count grammar, and `unEscapeString` decodes each `%XX` to its raw byte rather than reassembling multi-byte UTF-8 (unneeded by anything currently in `linen`). ### `DataFrame` — typed tabular data - `DataFrame.Internal.Types` — a `DataFrame` with a **proven rectangular invariant** (`columns_aligned`: every column has exactly `nRows` elements, carried as a runtime-erased proof field). A heterogeneous `Value` (int/float/str/bool/null) with `Ord`/conversions, named `Column`s with a `ColumnType` tag, and smart constructors (`fromColumns`/`fromRows`/ `fromNamedColumns`) that discharge the alignment proof; safe proof-carrying row access (`getRow?`), plus `GroupedDataFrame`. - `DataFrame.IO.CSV` — RFC 4180 CSV read/write (`parseCsv`/`toCsv`/`readCsv`/ `writeCsv`/`readTsv`): a finite `for`-loop state machine (quoted fields, doubled-quote escapes, CRLF), `Value` type inference, and a pure float parser. - `DataFrame.Internal.Column` — column ops: `inferType`/`mk'`/`mapValues`/ `reInferType`/`filterByMask`/`toFloats`/`toStrings`/null counts/`take`/`drop`/ `unique` (all pure). - `DataFrame.Display` — render a frame as an aligned plain-text table (`toString`, with truncation + ellipsis) or a Markdown table (`toMarkdown`), plus `ToString`/`Repr` instances; pure `.map`/`.flatMap` rendering. - `DataFrame.Operations.Join` — inner/left/right/outer joins on shared key columns (`join`/`innerJoin`/`leftJoin`/`rightJoin`/`outerJoin`); the result's rectangular invariant is re-established via `map_column_aligned`. - `DataFrame.Operations.Sort` — `sortBy`/`sortByMultiple` (asc/desc, multi-key with tie-breaking) via `List.mergeSort` over a row-index permutation, with a proof the permuted columns stay aligned. - `DataFrame.Operations.Statistics` — column stats: `sum`/`mean`/`variance`/ `std`/`median`/`min`/`max`/`minValue`/`maxValue` and `count`/null counts (numeric stats `Option Float`, skipping non-numeric/null). - `DataFrame.Operations.Aggregation` — `groupBy` into a `GroupedDataFrame` (pure `foldl` find-or-append) and `aggregate` with `AggFunc` (`sum`/`mean`/`count`/`min`/`max`/`first`/`last`/`std`/`var`). - `DataFrame.Operations.Subset` — `select`/`exclude` columns, `take`/`drop`/ `head`/`tail`/`slice` rows, `filterBy`/`filterWhere`, and `rename` — each re-establishing the rectangular invariant. - `DataFrame.Operations.Transform` — `addColumn`/`derive` (computed columns), `mapColumn`, `dropColumn`, `renameColumn`, and `dimensions`/`info`. ### `Web.Cookie` — HTTP cookies - `Web.Cookie` — RFC 6265 cookie parsing/rendering: `parseCookies`/`renderCookies` for `Cookie:` headers, and a `SetCookie` record (`path`/`domain`/`maxAge`/ `secure`/`httpOnly`/`sameSite`) with `renderSetCookie`/`parseSetCookie` for `Set-Cookie:` (pure parsers, no `Id.run`/`while`). ### `Web.Css` / `Web.Html` — typed CSS and HTML5, illegal constructs are compile errors - `Web.Css` — every declaration comes from a typed smart constructor (`color`/`margin`/`display`/…) that pins down both the property name and the Lean type of its value; `Declaration`'s `private` constructor makes an arbitrary `property := value` pairing a compile-time error. `Length` (`px`/`pct`/`em`/`rem`/`vw`/`vh`/`auto`/`zero`) rules out unit-less values, and `FontWeight.numeric`'s `by decide` proof rejects out-of-range weights. Selectors, `Rule`s, and `Stylesheet`s compose, with `rule!` macro sugar for building a `Rule` from a selector and a list of declarations. - `Web.Html` — `Html` is indexed by a `Category` (flow/phrasing/list-item/ table-row/table-cell) that encodes HTML5's content model: each element constructor fixes the category of children it accepts, so a `
` inside a `

`, a `

  • ` outside a `