About this volume
The Tebako Volume collects, in one reading order, the normative specifications of the tebako packaging ecosystem and the composition calculus that states their model formally. It exists to be cited: each chapter is one specification, carrying the same TBK SPEC number, the same section numbering, and the same text as the standalone series rendering and as the Markdown source of truth in the product repository. A reference of the form "TBK SPEC 02 §1" resolves identically against all three.
The reading order is the order an implementer meets the machinery. The series landing and the system overview set the vocabulary. The wire format and the payload manifest define what a package is. The store, the jail, and the registry and trust specifications define how packages are cached, confined, and believed. The virtual filesystem, the driver contract, and the launcher ABI define how a run composes. The operational specifications — observability, distribution, audit, transparency, and solving — close the series, and the composition calculus states the whole as one small formal system.
The volume is built by the ecosystem's own toolchain: the packed metanorma payload, installed from the official tebako registry, compiles this document, and the PDF is an artifact of every docs publish of tebako.org. The provenance of the build you are reading — source revisions, toolchain versions, artifact checksums — is recorded in the colophon.
TBK SPEC 00 — Tebako Specifications: the series landing
The series
The tebako ecosystem packages applications and runtimes into single executables whose loading behavior is governed by normative specifications: the wire format of the package container, the manifest grammar of a payload, the contract between the loader and a runtime, and the policies for resolution, caching, jailing, trust, and observability. Those normative texts live as Markdown files in the product repository, and an implementer — a runtime factory author, a registry operator, a feedstock maintainer — has until now read them only as raw Markdown source, with no rendered document to cite.
The Tebako Specifications (TBK SPEC) series closes that gap. Each document in the series is one normative text from the repository, converted to a Metanorma standard document and rendered to HTML and PDF as a member of a single collection. The document numbering follows the numbering of the source files: TBK SPEC 02 renders 02-tpkg-wire-format.md, and so on. Section numbering, section titles, tables, and code listings are carried over verbatim, so a reference of the form "spec 06 §4" resolves identically against the Markdown source and against the rendered document.
Source of truth and synchronization
The Markdown files under docs/spec/ in the tamatebako/tebako repository are the source of truth for every document in the series. This series is their rendered form; the AsciiDoc twin of a specification is derived from the Markdown and never edited independently. The Markdown sources themselves are not modified by the rendering process.
Each rendered document records the blob SHA of the Markdown file it was converted from in a comment line of the form // source: docs/spec/NN-name.md @ <sha>. The drift gate at docs/spec-site/tools/sync.rb recomputes the blob SHA of every referenced Markdown source and compares it with the recorded value. The gate exits with status 0 when every rendered twin is current, and exits 1 naming the drifted documents when a Markdown source has moved without its rendered twin being updated. A continuous-integration job runs the gate on every pull request that touches docs/spec/, so a specification edit cannot land without its rendered twin following it.
The conversion from Markdown to AsciiDoc is performed and reviewed by hand; the gate does not regenerate document content. After a specification edit has been carried into its twin and reviewed, ruby docs/spec-site/tools/sync.rb --sync updates the recorded SHAs to bless the new state.
Documents in the series
| Document | Title | Markdown source |
|---|---|---|
| TBK SPEC 01 | System overview | docs/spec/01-overview.md |
| TBK SPEC 02 | tpkg wire format (L0) | docs/spec/02-tpkg-wire-format.md |
| TBK SPEC 03 | Payload manifest (L1) | docs/spec/03-payload-manifest.md |
| TBK SPEC 04 | References and registries (L3) | docs/spec/04-references-and-registry.md |
| TBK SPEC 05 | Resolution and machine cache (L3) | docs/spec/05-resolution-and-cache.md |
| TBK SPEC 06 | Launcher ABI (bootstrap → runtime) | docs/spec/06-launcher-abi.md |
| TBK SPEC 07 | Shims and dispatch | docs/spec/07-shims-and-dispatch.md |
| TBK SPEC 08 | Jails: host-access policy | docs/spec/08-jails.md |
| TBK SPEC 09 | Trust and signing (authentication) | docs/spec/09-trust-and-signing.md |
| TBK SPEC 10 | Encryption (confidentiality) | docs/spec/10-encryption.md |
| TBK SPEC 11 | TFS: the virtual filesystem layer | docs/spec/11-tfs-vfs-model.md |
| TBK SPEC 17 | The runtime driver contract (any language) | docs/spec/17-runtime-driver-contract.md |
| TBK SPEC 18 | The Contract Graph | docs/spec/18-contract-set.md |
| TBK SPEC 19 | The Bootstrap, Distributed: How Tebako Reaches Your Machine Without a Compiler | docs/spec/19-bootstrap-distribution.md |
| TBK SPEC 25 | Trace observability: the interception bus, diagnosis, and coverage | docs/spec/25-trace-observability.md |
| TBK SPEC 36 | Release bundles (the runtime publish unit) | docs/spec/36-release-bundles.md |
| TBK SPEC 37 | The registry book: federation, aliases, credentials, the official seed | docs/spec/37-registry-book.md |
| TBK SPEC 38 | OCI distribution (tfs+oci:) | docs/spec/38-oci-distribution.md |
| TBK SPEC 39 | Lazy range-fetch mounting of runtime images | docs/spec/39-lazy-range-mount.md |
| TBK SPEC 40 | The audit ledger: queries, the anchor, and the auditor's walk | docs/spec/40-audit-ledger.md |
| TBK SPEC 41 | Registry transparency: completeness proofs for the public fabric | docs/spec/41-registry-transparency.md |
| TBK SPEC 42 | Tree solving and lockfiles: one answer for a whole composition | docs/spec/42-tree-solving.md |
Specifications whose number is absent from the table — the internal process documents and the documents outside the public format/contract set — are not part of this series rendering and remain readable in the repository.
TBK SPEC 01 — System overview
What tebako is
Tebako is a packaging and loading ecosystem — not a Ruby tool. Ruby is the first runtime instance. The system is generic across four axes:
Any runtime. A runtime is a payload that provides an interpreter (ruby today; python, julia, qtk, anything later). The loader neither knows nor cares what language it starts.
Any platform. Artifacts are per platform triplet (spec 03 §platform axis); payloads may also be universal.
Any payload. Application code, data, fonts, native tools, runtimes themselves — all images of the same kind, differing only in what their manifests declare.
Any composition. Payloads stitch onto a single binary, and payloads recursively mount other payloads at paths (spec 11 §encapsulation).
Core capabilities
Stitch — N payload images + bootstrap into one executable (fat), or a small executable resolving parts on demand (lean).
Load — mount payloads (recursively) into one VFS; transfer control to the declared entrypoint.
Share — runtimes and payloads download once into a machine-wide content cache; every package on the machine reuses them.
Shim — tebako manages shims for EVERY executable every installed payload provides; one payload may provide MULTIPLE executables, each becoming a registered command (spec 07).
Jail — declarative host-filesystem policy per run, enforced by the VFS layer (spec 08).
Trust — opt-in per package: authentication, signatures, encryption (specs 09, 10). Unsigned stays first-class.
Repositories and languages
Tebako-owned C/C++ exists in exactly one repository: dwarfs-t. (The tamatebako/ruby fork carries upstream ruby's own C source plus patches — vendored upstream, not ours; tebako-runtime-ruby is build orchestration that links the Rust staticlibs tfs + tebako-driver.) Everywhere else: Rust, pure Ruby, or Docker. Owner-locked.
| Repo | Language | Role |
|---|---|---|
| tamatebako/ruby | Ruby tooling + C (ruby) | Patch sets (canonical .patch files + versions.yml); release = patched source tarballs per version × scenario. The source factory. |
| tebako-runtime-ruby | Ruby builder + C/CMake | Builds runtime payloads per version × triplet; release = interpreters + .tfs images + index. The runtime factory (first instance; python/julia factories follow the same shape). |
| tamatebako/dwarfs-t | C++ | The DwarFS-T image format: libdwarfs_c reader + creation-time Writer. The only surviving C++ library; read-only at runtime forever. |
| tamatebako/dwarfs-rs | Rust (FFI) | dwarfs-t / dwarfs-t-sys safe bindings to libdwarfs_c. Standalone by design — not tebako-specific. |
| tamatebako/tebako | Rust only | The product: packager, loader, VFS, formats, trust. (The repo-swap 2026-07-27: formerly tebako-rs; the C++/gem era is archived at tamatebako/tebako-v1.) |
| tebako-ci-containers | Dockerfile | Toolchain images for the three factories. |
| tebako.org | AsciiDoc/Astro | Docs, blog, trust-anchor publication. |
| tamatebako/tebako (gem) | Ruby | RETIRED as orchestrator (2026-07-26); maintenance mode. Endgame: a ~100-line pure-Ruby installer shim that fetches the platform binary (no FFI), or full archival. |
| tamatebako/libtfs (C++) | C++ | LEGACY; superseded by crates/tfs (164-test contract parity). |
tebako-rs crate roles (MECE, open/closed)
| Crate | Kind | Role |
|---|---|---|
| tpkg | lib | L0 wire format, single source of truth (spec 02). #![forbid(unsafe_code)]. |
| tfs | lib (cdylib+staticlib+rlib) | The Rust TFS (spec 11): tebako_fs_* C ABI, mount table, dispatch, backends ZIP/DwarFS/SquashFS. Sole home of future COW/ENC transforms. |
| sqfs-sys | lib (FFI) | libsquashfs-tools-ng FFI, ABI-pinned. |
| tebako-pkg | bin | Container surgery: info/bundle/unbundle/reassemble/insert-image/remove-image/set-runtime/sign/verify. |
| tfs-cli | bin | The tfs image tool: info/ls/tree/cat/stat/extract/find/mkimage (in-process Writer). |
| tebako-cli | bin | The packager: press (lean/fat), cache list/prune. |
| tebako-bootstrap | bin | The loader (spec 06): trailer parse, resolution, verification, ABI-v1 handoff. < 3 MB static, size-gated (unverified-first: rnp/botan feature-gated out; OpenPGP moves to the roadmap-72 crypto toolkit). |
| tebako-driver | lib (staticlib+rlib) | The spec-17 runtime driver: mounts the env image + payload images into the process-global TFS context, applies TEBAKO_JAIL, rewrites argv to the entrypoint. Linked into every runtime executable. The Rust successor of the v1 C++ tebako-main. |
| tebako-http | lib | In-process HTTPS (ureq+rustls, webpki-roots bundled; OS roots opt-in). |
| tebako-signer | lib | OpenPGP via rnp-rs (crates.io, vendored); successor-key rotation. |
| tests/contract | tests | The parity oracle: the C++ c_api suite through the Rust ABI (164 tests). |
Per-language tpkg bindings
The tpkg contract is manipulated per language — never by shelling a foreign binary: crates/tpkg (Rust), tpkg.h (C, cbindgen — lands with its first real C consumer), tpkg.rb (Ruby, formalized from the gem's trailer reading).
TBK SPEC 02 — tpkg wire format (L0)
Normative byte-level specification of the tebako package container. Source of truth: crates/tpkg (byte-exact with the reference C99 include/tebako/tpkg.h; golden vectors pin the layout). All v1 integers little-endian; the trailer header sits at the logical EOF (§1) at fixed size. The container knows nothing about runtimes, entrypoints, or languages — it carries bytes, slots, mounts, and a resolution hint. Authenticated, signed, and encrypted packages: authentication/signing is the v2 extension (§4); encryption is a TFS-layer transform of the slot images (spec 10) — the container itself stays byte-identical either way.
1. File anatomy
[payload bytes][slot table: n × 280][v2 extension?][trailer header: 166 @ EOF]
"EOF" is the LOGICAL end of the package: the physical EOF, except on a package signed post-press. On a Mach-O package codesigned post-press (spec 31 §1.2), codesign appends the code-signature superblob after the trailer, 16-byte aligned with a zero pad. Readers locate the trailer end via the tail slice's LC_CODE_SIGNATURE: when the superblob reaches the physical EOF exactly, the trailer header is the self-validating (magic + crc + bounds) window ending at the superblob's dataoff or at most 15 zero pad bytes earlier; every other shape reads at the physical EOF. On a PE package Authenticode-signed post-press (spec 34 §1.2/§6), the signer appends the WIN_CERTIFICATE table after the trailer and points the security data directory (IMAGE_DIRECTORY_ENTRY_SECURITY, a file offset, not an RVA) at it: when the certificate table reaches the physical EOF exactly, the trailer header is the same self-validating window ending at the table's start or at most 15 zero pad bytes earlier (the table is 8-byte aligned); an absent or zero-length directory entry means unsigned. Writers never produce the suffixed shape — only the platform signer does, and the container bytes it hashes are unchanged by it.
2. Trailer header — 166 bytes, always at the package end
(The package end is the physical EOF, or — on a post-press-signed Mach-O/PE — just before the trailing superblob's or certificate table's alignment pad; §1.)
| offset | size | field |
|---|---|---|
| 0 | 10 | magic "TEBAKOTFS\0" |
| 10 | 4 | u32 version = 1 (extensions ride flags, not version bumps) |
| 14 | 4 | u32 package_flags (bit0 LEAN, bit1 SIGNED_V2, bit2 NO_INSTALL, bit3 QUIET_NOTICES) |
| 18 | 4 | u32 slot_count (1..=8) |
| 22 | 8 | u64 slot_table_offset (absolute file offset of slot 0) |
| 30 | 128 | char runtime_ref[128] — resolution hint (spec 05 §1); empty = classic |
| 158 | 4 | u32 launcher_abi |
| 162 | 4 | u32 crc32 over [0,162) — accident integrity, NOT authenticity |
TPKG_MAGIC_PREFIX_LEN = 4 ("TEBA") discriminates absent vs corrupt.
Bit0's name is the only deprecated thing about it (locked 2026-08-25, tebako#460): read LEAN = 1 as "the package does not carry its runtime pair" and LEAN = 0 as "the runtime pair is carried as ordinary slots" — the shared-runtime and self-contained presets of spec 23 §13.2 (whose lean/fat aliases exist only so older documents stay readable). The BIT itself stays load-bearing exactly as spec 18 S4 requires: flags are never skipped, and an unknown set bit is a named refusal.
3. Slot record — 280 bytes
| offset | size | field |
|---|---|---|
| 0 | 8 | u64 offset (absolute file offset of the image) |
| 8 | 8 | u64 size |
| 16 | 4 | u32 format_id — IMAGE FORMAT ONLY: 0=auto, 1=dwarfs, 2=squashfs, 3=zip, 5=limnifs (spec 20, PLANNED) (4=runtime: legacy role wart, §5) |
| 20 | 4 | u32 flags (0 today; future home of role bits) |
| 24 | 256 | char mount_point[256] (UTF-8, NUL-padded) |
4. v2 chain-of-trust extension (opt-in; flag bit1 SIGNED_V2)
Between slot table and header; all its numerics big-endian (the header stays v1-little-endian). v1 readers ignore the flag and run the package — trust enforcement is a reader capability, not a format barrier.
| offset | size | field |
|---|---|---|
| 0 | 256 | per-slot SHA-256, 8 × 32 B (digest of slot i at i×32; tail zeroed) |
| 256 | 8 | signer keyid (low 64 bits of OpenPGP fingerprint, BE) |
| 264 | sig_len | OpenPGP detached signature (binary packets) |
| 264+sig_len | 4 | u32be sig_len (1..=65536) |
Canonical signed bytes: slot table ‖ ext blocks ‖ digests ‖ keyid ‖ header — everything except the signature and its length field. The extension blocks (§5b) sit inside the signed region: the signature covers them.
5. The installability flag (bit2 NO_INSTALL)
A run is a run — a plain execution never writes payload slices into the local store, with exactly one scoped exception: the lazy seed of spec 05 §4 (a self-contained package MAY seed the cache with the artifacts it carries — best-effort, never blocking the run). NO_INSTALL packages never seed. Installation is otherwise the EXPLICIT verb (tebako install <path>; the bootstrap's --tebako-install refuses or guides, spec 06 §4 exit 76). NO_INSTALL marks a publisher-frozen package: it RUNS standalone but every install attempt is refused with a named error. Absence means installable-on-request, including packages pressed before the verb existed — pass-through like every flag.
5a. The quiet-notices flag (bit3 QUIET_NOTICES; tebako#400, spec 23 §14)
The developer's declaration that the package's runs suppress the unsigned-legacy-trailer warning (spec 09 §v1-legacy) and the progress lines (spec 06 §5) — declared through any registry channel (CLI --quiet-notices, env TEBAKO_QUIET_NOTICES, compose key quiet_notices:), resolved once at press, baked here. Run-time reads only the bit: the package behaves identically on every machine. The bit rides inside the signed region, so it cannot be forged onto a signed package; TEBAKO_REQUIRE_SIGNED=1 is checked FIRST and outranks it, and the audit-journal entry is written regardless. Absence means the default notice behavior — pass-through like every flag.
6. Orthogonality note (normative)
format_id answers exactly one question: how to read the slot's bytes. Whether a slot is a runtime, and which payload carries the entrypoint, are roles — L2 semantics declared by manifests (spec 03), never encoded in the format axis. The v1 format_id = 4 (TPKG_FORMAT_RUNTIME) marks the fat runtime slot so v1 loaders skip handing it over as a mount; it is a role riding in the format field, kept only for backward compatibility. The two-slot era makes the wart obsolete in practice: a self-contained package carries its runtime as ordinary exe + env-image slots (spec 19 §6.1), and presses never emit format 4 anymore. The cleanup path: slot role moves to slot flags / package manifest, and format_id returns to pure image-format semantics. New semantics must never again be smuggled into the format axis.
5b. Typed extension blocks (the L2 home; locked 2026-07-26)
Following OCI's model — the manifest is a separate blob BESIDE the layers, readable without pulling any image — the package-level (L2) manifest lives in the container but OUTSIDE every payload image. The v2 signing extension already proved the mechanism: blocks between the slot table and the trailer header are invisible to v1 readers (they only read the header at EOF and the slot table at its recorded offset; the bounds check never requires the table to abut the header).
Generalized layout:
[bootstrap][payload slots][slot table][ext blocks…][v2 signing ext?][header @EOF]
ext block: [u32be type][u32be length][payload bytes]
type 1 = v2 signing extension (historical: immediately before the
header, self-delimiting from the tail via its sig_len field)
type 2 = package manifest (YAML — spec 03 §6; identity, entrypoint/
suite composition, package-level jail + env, per-entry
runtime refs, per-slot mount modes — exclusive/union,
spec 17 §1)
Rules: blocks walk forward from the end of the slot table (type+length self-delimit); the v2 signing ext, when present, is LAST before the header (unchanged bytes/position); unknown block types are skipped by v1-era-aware readers (forward-compat) but rejected by validate with a named error; a package manifest never duplicates payload manifests — it references slots, and payload manifests (spec 03) stay inside images (self-describing payloads). The 128-byte single runtime_ref remains for v1-era loaders; per-entry runtime references for suites and multi-runtime packages live in the type-2 manifest (no size cap).
6. Absent vs corrupt; validation
Last-166-byte window without the "TEBA" prefix → NoTrailer (classic bundle; callers may fall back to offset auto-detection).
Prefix ok, magic bad → Magic. Magic ok, crc bad → Crc.
Version ≠ 1 → Version. Slot count outside 1..=8 → Slots.
Structural validation mirrors the reference C tpkg_validate(): offset+size non-overflowing, format_id ≤ 5 (spec 20 raised the bound from the C reference's ≤ 4 — the documented parity end: the C99 reader keeps rejecting format 5 with its named invalid error; ids ≥ 6 stay unallocated), runtime_ref and mount points NUL-terminated within their fixed fields; table fits entirely before the header.
v2: flag/extension co-presence; zeroed digest tail; signature non-empty and ≤ 65536; signer keyid non-zero.
7. Errors (Rust TpkgError ↔ C TPKG_ERR_*, 1:1)
NoTrailer, Magic, Crc, Io, Bounds, Slots, Invalid, Arg, Version — strerror strings byte-identical with the C implementation.
TBK SPEC 03 — Payload manifest (L1)
Normative specification of the in-image manifest: every payload is a self-describing artifact, not a blob. Status: SHIPPED (the block + the engine shipped; the §3 press/install gate wiring remains — the checks block's discoverability row).
1. Location and form
Path: /__tpkg__/manifest.yaml — inside the image, at a well-known location. No sidecars, no central service.
Format: YAML (the locked convention for all authored configuration surfaces). The versioned grammar: docs/spec/schemas/payload-manifest.yaml (the registry's authored form; crates/tpkg/src/manifest.rs mirrors it).
Integrity: the manifest is inside the image, so it is exactly as tamper-proof as the content and is covered by the image's digest and signature. Any consumer (bootstrap, dispatcher, tfs CLI, a foreign project) reads it through TFS itself.
2. The three blocks
Every manifest is IDENTITY + PROVIDES + DEPENDS on a common provenance/trust layer.
2.1 IDENTITY (all kinds)
schema_version: 1
kind: app | data | toolkit | runtime | language
name: metanorma
version: 1.2.3
producer: {tool: tebako-cli, tool_version: 0.16.0}
created: 2026-07-26T00:00:00Z
source: {src_sha256: "…", commit: "…", builder: "gha:run:123"}
sbom: {ref: "…"} # optional
digest:
tree_hash: "…" # plaintext merkle root over the tree MINUS the
# manifest path — semantic identity (CAS)
blob_sha256: "…" # transport identity — see the fixed-point rule
signing: {state: unsigned | signed, keyid: "…", mechanism: openpgp}
encryption: {state: none} # or per-part list {paths, algorithm, envelope_refs} — NEVER keys
annotations: {…} # free-form; unknown keys preserved
2.2 PROVIDES (kind-specialized)
app (executable):
entrypoints: # ARRAY — multi-entry suites; N=1 for simple apps
- name: metanorma # the command name (shim registers under this)
path: /app/bin/metanorma # inside the image
args_default: [] # interpreter-side defaults composed BETWEEN interpreter
# and entry by the runtime driver (spec 17 §1 — the single
# owner, tebako#503) — java: ["-jar"]. A ZERO-runtime entry
# has no driver: the shim appends them as the program's
# leading args.
runtime_requirement: {engine: ruby, constraint: ">= 3.3, < 5.0"}
# OPTIONAL — omit entirely for native entrypoints (see below);
# range for pure-language; abi-line "~> 3.3.0" for native-extension payloads.
# engine names the LANGUAGE — mri/jruby/truffleruby are all `ruby`;
# the OPTIONAL `implementation:` narrows to one (spec 28 §8).
# The value may ALSO be a LIST of such maps — `any_of` semantics,
# OR in declaration order — when the admissible set differs per
# implementation (spec 28 §8); an entry without `implementation:`
# matches at the language level (the runtime's language_version).
# native-extension entrypoints ALSO pin the implementation and the
# platform line:
runtime_requirement: {engine: ruby, implementation: mri, constraint: "~> 3.3.0", abi: "arm64-darwin-23"}
# abi = the runtime's own platform string the extensions were built
# against (ruby: Gem::Platform.local.to_s). The version line and the
# platform line are ORTHOGONAL — resolution checks both (spec 05 §5).
# an `abi:` in force REQUIRES `implementation:` — an ABI is
# per-implementation by construction (spec 28 §8).
platforms: [x86_64-linux-gnu, aarch64-macos] # native-ext apps are triplet-bound;
# universal only for pure-language
capabilities: {exec: true, read: true}
capabilities may also carry host (any kind): the host-access jail the payload was built to need — a REQUEST the dispatch surfaces compose with the user's tightening, never a grant to itself. spec 08 §4 is normative for its shape (default, mounts, network, argument_files, and resources — the §2.2 consumption bounds).
Zero-runtime entrypoints (locked): an entrypoint whose executable is native (or self-contained) needs NO interpreter payload — inkscape-class slices, static binaries, shell-free tools. Such apps declare no runtime_requirement and the dispatcher mounts zero runtime payloads. Runtimes (ruby today; python, julia, others tomorrow) are just one payload kind among many — never an assumed layer. A SUITE is one package with N entrypoints — the shim layer exposes one command per entry, each dispatching to its own image and its own runtime requirement (spec 07).
Completeness (locked 2026-08-29): entrypoints declares EVERY command the image carries that a user may invoke directly — it is the payload's command declaration, not a primary-executable field. A bundled CLI (a font manager, a bibliography tool) is as much a provided command as the app's namesake. The declaration is the COMPLETE inventory; exposure is an orthogonal per-entrypoint key:
- name: fontist
path: /bin/fontist
active: false # OPTIONAL (default true) — declared but NOT
# PATH-registered at install
active is the payload author's default exposure. The three tiers of a command's life are distinct and separately owned (tebako#1004):
Declared — the payload author's complete inventory (provides.entrypoints[]). Everything dispatchable lives here; tebako run <name> resolves against this tier alone, so every declared command runs regardless of the other two tiers.
Default-active — the payload author's choice of which declared commands claim a PATH name by default (active: true; absent the key the entry is active). This is a DEFAULT, never a lock: it decides only what an unqualified install links.
Linked — the installing user's per-machine choice of which commands actually hold ~/.tebako/shims/<name>. The installer's default is the default-active set; --only-shims/--no-shims narrow it at install (spec 07 §1), tebako shim hide|expose adjust it afterwards (spec 07 §3), and a hidden name stays hidden across reinstalls. The disable axis (dispatch refusal, spec 07 §0) is orthogonal to all three tiers and composes with them: a command can be linked yet disabled (the shim stands, dispatch refuses) or hidden yet enabled (the PATH name is free, tebako run answers).
An inactive-but-declared command stays dispatchable — tebako shim enable <name> links it on demand, tebako run <name> reaches it directly, and the user's per-machine enable/disable always overrides the manifest default (spec 07 §3). Additive on the wire: pre-flag readers ignore the key and register every entrypoint (the pre-flag behavior). The declared names are also the only set a self-contained package's entries[] may draw from (§6): the L2 entry names mirror the L1 declaration — one SSOT, cross-checked by tebako-pkg validate (tebako#494).
runtime (provides an interpreter):
provides: {engine: ruby, implementation: mri, version: 4.0.6, language_version: "4.0", abi_line: "4.0", platform: x86_64-linux-gnu}
# engine = the LANGUAGE; implementation (REQUIRED for kind: runtime) =
# which ruby this is (mri/jruby/truffleruby — spec 28 §8).
# version = the implementation's OWN version line (jruby: 9.4.8);
# language_version = the language level it implements (jruby 9.4 → "3.1";
# for mri the two are identical). spec 05 §5 matches on both.
built_from: {src_sha256: "…", patch_set: "v0.2.8"}
env: {GEM_PATH: …}
entrypoints: # OPTIONAL (additive — schema_minor 4, spec 30 §2):
- name: jing # the commands this runtime boots as a SEPARATE
path: /bin/jing.jar # process for a consumer's `kind: runtime` edge
args_default: ["-jar"] # `expose:` list — the app-entrypoint grammar minus
# runtime_requirement (a runtime runs on itself).
# Absent/empty = the runtime serves only as a
# primary co-mounted runtime.
windows_boot: materialize # OPTIONAL (additive — schema_minor 11, spec 17 §7):
# the runtime's interpreter cannot consume the
# driver's mounted images on windows (zero-patch,
# no interposition tier) — boot from the extracted
# exec-cache tree instead. Absent = the interpreter
# reads the mounts directly (ruby). POSIX never reads it.
capabilities: {exec: true, read: true, runtime: true}
data (read-only):
mount_semantics: {suggested: /usr/share/fonts}
consumers: [any]
capabilities: {exec: false, read: true}
toolkit (native layer, e.g. gtk/qt): as runtime, minus the interpreter contract; PROVIDES names libraries/tools other payloads DEPEND on.
2.3 DEPENDS (requires:)
requires:
- kind: language # a language runtime edge
engine: ruby
implementation: jruby # OPTIONAL — absent: any implementation of the
# engine whose language_version satisfies the
# constraint (spec 28 §8)
constraint: "~> 3.3.0"
- kind: toolkit # a native toolkit layer
name: gtk-layer
constraint: ">= 3.24, < 3.25"
triplets: [aarch64-macos, x86_64-linux-gnu] # resolves on these hosts
# only — skipped elsewhere
# (the per-edge rule below)
mount: /__layers__/gtk
- kind: data
name: iso-codes
constraint: ">= 2024.1"
mount: /__app__/share/iso-codes
- kind: runtime # a SPAWNED runtime edge (additive — schema_minor 4,
engine: java # spec 30): resolves through the RUNTIME index into the
implementation: temurin # OPTIONAL (spec 28 §8)
constraint: ">= 21" # store's runtimes/ area and is NEVER co-mounted — its
# wrapper exe executes FROM THE STORE.
expose: [java, keytool] # OPTIONAL — the depended entries this payload surfaces
# (spec 30 §3's shim surface)
Dependency edges may also name provided executables (e.g. an app requiring the inkscape command resolves against the PROVIDES of the inkscape payload) — the provides/requires graph resolves capabilities, not just payload names.
A kind: runtime edge is spec 30's spawned dependency: the depended runtime is dispatched as a CHILD process through its store-resident wrapper (never co-mounted, never materialized); resolution placement, the spawn wire, the jail union, and the shim surface are spec 30 §2–§5's. EXCEPTION: when the DECLARING payload is itself kind: runtime and the edge carries NO expose:, the edge is an OWNER edge — runtime-on-runtime composition (spec 33): the depended runtime owns the boot's process, and the declarer contributes a second env image plus the on_runtime argv template.
MOUNT RULE (locked): the mount point is declared in the CONSUMER's manifest (docker-compose volume semantics): the consumer's code knows where it looks for things; the provider never dictates its mount location. The dispatcher resolves the capability, then mounts at the consumer-declared path — top-level or inside the app's memfs namespace.
Resolution algorithm: read manifest → build the graph → topological order (runtime first, layers, app last) → per node: cache hit on (constraint × triplet) → use, else fetch (signature-verified, spec 09) → verify → cache (0444 + markers) → compose the mount stack with the manifest's declared env → exec. The SAME signed .tfs artifact type at every graph level — one coherent algebra.
PER-EDGE PLATFORM CONDITIONING (triplets:, additive — schema_minor 9, locked 2026-09-12, roadmap 86): every edge kind EXCEPT kind: language accepts the OPTIONAL triplets: list — the §3 axis's vcpkg-form triplets, non-empty, no duplicates (validated at parse). This generalizes the toolkit edge's existing spelling to data, runtime, and executable edges — one spelling per axis (spec 00 invariant 10): payload-level coverage is platforms:, edge-level conditioning is triplets:.
Absent = universal. An edge without triplets: resolves on every host — byte-identical with pre-minor-9 behavior.
A host outside the list SKIPS the edge: no resolution, no fetch, no install row, no lock row, no mount, no spawn surface, no exposed-name registration. The skip is LOUD — one journal line (event=edge-platform-skip, the shim's journal convention) plus a stderr note at press / install / dispatch — never silent, never an error. A multi-host compose (spec 23) evaluates coverage per target host: the edge lands in the lock rows of the covering hosts only.
A skipped edge's exposed commands are absent from the shim surface on the skipping host; dispatching one anyway (a stale shim, a hand-written invocation) is a named error — "not available on this platform", exit 69 — never a silent fallback to another provider.
kind: language FORBIDS the key — a skipped language edge would boot a payload with no runtime, an incoherent composition; the payload-level platforms: axis already owns "where this payload runs". A language edge carrying triplets: is a named manifest error at parse, steering the author to platforms:.
critical: interaction: the skip applies regardless of critical: true — critical governs reader-ERA refusal (a pre-minor reader must refuse an edge it cannot interpret), never platform reach. "This host must have the dep" is said with platforms: on the payload, not with critical on the edge.
Reader compatibility: a pre-minor-9 reader ignores triplets: on non-toolkit edges (the unknown-field rule) and resolves the edge universally — the safe direction: an extra dependency resolved, never a needed dependency skipped.
2.4 MATERIALIZE (materialize:, additive — schema_minor 1)
materialize:
- /lib/ssl/certs/cacert.pem # an absolute in-image path, no '..' components
A top-level list (any kind may declare it; old readers ignore it under the unknown-field rule) naming regular files a C library must read through its own IO — the interpreter's patched IO never gets asked, so the bytes must exist on the host filesystem. The OpenSSL CA cert is the canonical entry. The driver extracts each declared path after the mounts and the jail, before the interpreter handoff, to <TEBAKO_EXEC_CACHE>/resources/<image-key>/<P> — whole-file, read-only, digest-verified. A declared path absent from the image, or not a regular file, is the manifest lying: boot fails by name (exit 65), never a skipped entry. The full mechanics and the trust chain are spec 22 §4 (class R); the grammar is registered in docs/spec/schemas/payload-manifest.yaml.
2.5 LIBRARY ALIASES (library_aliases:, additive — schema_minor 2)
library_aliases:
- name: libfoo-3.dll # the exact bare name a loader call presents —
# no path separator, no drive qualifier
# (validated at parse)
path: /lib/libfoo-3.dll # the in-image absolute file the name resolves to
A top-level list (any kind may declare it; old readers ignore it under the unknown-field rule) naming the ONLY bare library names that resolve to the image's own files — the declarative half of the windows Class-L bare-name rule (semantics: spec 22 §2.1). A loader call presenting a bare name matching no entry is a HOST reference and passes through untouched: host-by-default, no probing, no heuristics, no silent fallback. Matching is verbatim and case-insensitive (the windows loader's own comparison); the name is never extension-completed (foo does not match foo.dll). path must be an absolute in-image path of a regular file, no .. components — an absent or non-file target is the manifest lying (a named 65 at boot, the §2.4 precedent). A duplicate name within one image is a named manifest error; two co-mounted images declaring the same name is a named boot error (authoring ambiguity, the spec 17 §2 slug precedent), never a silent winner. No platform filter: native images are triplet-bound (§3), so an alias is platform surface by construction. The grammar is registered in docs/spec/schemas/payload-manifest.yaml.
2.6 CHECKS (checks:, additive — schema_minor 3)
checks:
html-xml: # the check name — [A-Za-z0-9][A-Za-z0-9._-]*
entry: /bin/metanorma # in-image executable; "self" on kind
# runtime only (the runtime exe itself)
argv: ["--type", "iso", "{scratch}/test-iso.adoc", "--agree-to-terms"]
fixtures: /__tpkg__/check/html-xml # exec-only; CONTENTS land at the
# host scratch root
expect: {exit: 0, files: ["test-iso.xml", "test-iso.html"]}
timeout: 180
layout: # no entry ⇒ STRUCTURAL (the data-slice
expect: # shape): the engine mounts and asserts
image_files: [/templates/org/cover.adoc] # in-image, exist + non-empty
A top-level map (any kind may declare checks; old readers ignore it under the unknown-field rule) naming the payload's own acceptance contracts — "given my declared needs, I do my one real thing". ONE key decides the shape (MECE, never a kind: flag): entry present ⇒ an exec check; absent ⇒ a structural check, which declares no argv/fixtures and asserts via expect.image_files. expect.files are scratch-relative existence + non-empty assertions; byte-golden assertions do not exist by construction. A malformed block is a named validation error at press / tfs validate (exit 65), never discovered at run time. The semantics — the engine, the three moments, SKIP/FAIL discipline — are spec 26; the grammar is registered in docs/spec/schemas/payload-manifest.yaml.
2.7 INTERP ENV (interp_env:, additive — schema_minor 8) — IMPLEMENTED 2026-10-07 (tebako#559)
interp_env:
RUBY_YJIT_ENABLE: "1" # interpreter-option defaults, literal strings
RUBY_GC_HEAP_FREE_SLOTS: "500000"
A top-level map (any kind may declare; old readers ignore it under the unknown-field rule) carrying interpreter-option defaults the slice author owns: what options the interpreter starts with is a packaging-time decision (the runtime/payload slice developer's), with the local user always able to override. The dispatcher exports each merged key into the runtime process's environment at dispatch, so the interpreter reads it at its own boot (ruby's RUBY_YJIT_ENABLE, python's PYTHON_JIT, the JVM family's option vars — the channel is generic, never a ruby wart).
MECE against the existing env surfaces: provides.env: (runtime kind) is the runtime's COMPOSED process-env defaults (path-class included, spec 07 §9); interp_env: is the per-slice interpreter-OPTION channel — scalar only, never path-class, never a TEBAKO_* control var (those are dispatcher/driver-owned; both violations are named manifest errors). Values are literal strings: no expansion, no execution, no references — additive and declarative by construction; a malformed block is a named validation error at press / tfs validate (exit 65), never discovered at run time.
The composition chain and the override order live in spec 07 §9; the driver-side application rule in spec 17 §2.2; the audit surface in spec 15 §4. A declaration is a DEFAULT, never a requirement: a pre-minor-8 consumer ignores the key and ships the interpreter's built-in behavior.
2.8 AUGMENTS (augments:) and EXTENSION POINTS (extension_points:) — additive, schema_minor 10
The reverse dependency edge: a slice that extends a base payload it cannot be enumerated BY. The mount rule (§2.3) is unchanged — the CONSUMER declares; here there are two consumers and both keep their say: the BASE declares WHERE extensions land, the SLICE declares WHICH base it extends. Neither touches the other's bytes.
Base side — PROVIDES gains extension_points: (any kind that can host in-process content; practically app):
provides:
entrypoints: [...]
extension_points:
- name: flavors # symbolic; slices reference it by name
mount: /flavors.d # VFS-absolute; the slices mount BELOW it
layout: gem-home # enum: gem-home | files (extensible)
layout: gem-home — each mounted child is a mini GEM_HOME (gems/, specifications/); composition is the language ecosystem's own multi-home search list (GEM_PATH), never a union mount: two slices carrying different versions of one gem stay VISIBLE-and-resolvable (requirement-based activation) instead of one shadowing the other by mount precedence.
layout: files — opaque content the application reads itself (fonts, codelists). The app enumerates <mount>/<slice>/….
Base side, dedup inventory — PROVIDES gains gems: (any payload staging a gem home; REQUIRED when it declares a gem-home extension point):
provides:
gems:
- {name: nokogiri, version: "1.18.9"}
- {name: metanorma-cli, version: "1.16.9"}
Generated, never hand-authored (spec 00 §10): the builder scans the staged gem home's specifications/*.gemspec before the image seals. One generator, two consumers — the dispatcher reads the manifest key (the overlap journal, spec 07 §2 step 3a); the release exports the same inventory as its closure.json asset, the slice press's subtraction source. A second hand-written copy anywhere is a bug.
Slice side — a new top-level block augments: (sibling of requires:):
augments:
- payload: metanorma # the base payload's name
constraint: "= 1.16.2" # vs the base's RESOLVED version
extension_point: flavors # names the base's declared point
built_against: # provenance, written by the press
version: "1.16.2" # tooling — the exact base release
closure_sha256: "…" # whose inventory was subtracted
augments IS a dependency declaration, and the slice is NOT self-contained by construction (a deduped slice's gems resolve against the BASE's gem home at run time). Dispatch semantics live in spec 07 §2 step 3a; the store scan in spec 05 §3. The scope locks:
Root-only. augments attaches slices to the DISPATCHED (root) payload. A slice augmenting a slice is the named NestedAugment error; augments on a root payload's own manifest is ignored (journaled slice-ignored) — attachment is declared by the slice, never claimed by the base.
Content-only. Slices are in-process CONTENT (gem homes, files) — capabilities.exec: false. An extension carrying executables rides the forward requires/expose machinery (spec 30), never augments. MECE.
No runtime of its own. The slice's requires language edge is satisfied by the BASE's resolved runtime (abi line included — a mismatch is the dispatch-time loud skip, never a segfault).
The binding rule. A slice deduped against the base's closure pins EXACTLY (constraint: "= x.y.z" — one slice release per base release, shipped in lockstep): subtraction is sound only against the exact inventory it subtracted, and the slice's tests ran against exactly that base. When the base ships runtime LINES as suffixed versions (spec 28; 1.16.9 and 1.16.9-ruby4.0 of one payload version), the closures differ per line, so the pin names the LINE's exact version (= 1.16.9-ruby4.0 — the schema_minor-12 grammar, spec 05 §5) and one slice release exists per (slice, base LINE) pair. Range constraints remain legal for content that honestly spans (layout: files asset packs); gem-closure slices MUST pin exactly. Pre-minor-10 readers ignore both keys (the slice then simply attaches nothing — loud at install, never silent); pre-minor-12 readers reject a suffixed pin by name (exit 65). Family completion: when the lines' closure INVENTORIES are identical (press-verified at build time against every family row's published closure assets — never assumed), ONE slice release MAY serve the whole family: it carries one exact-pin augments edge per family row (each with its own built_against provenance naming that row), and the dispatcher attaches when any edge matches (spec 07 §2 step 3a). The binding rule is unchanged — every edge pins exactly the row whose inventory the press verified identical to the subtraction source.
The line-split idiom, worked (first production use: the metanorma flavor slices, metanorma/packed-metanorma-bsi and -nist, 2026-09-27 — the living instance to copy). A pure-ruby slice that serves every runtime line of a base family cannot use ONE exact pin: equality clauses are suffix-exact in the versions grammar (= 1.17.0 never matches 1.17.0-ruby3.3). Nor should it reach for a range (>= 1.17.0-ruby3.3, < 1.17.1): a range is legal for content that honestly spans, but a gem-closure slice subtracts a specific inventory, and the binding rule wants each served row named. The shipped spelling is one edge per row:
augments:
- payload: metanorma
constraint: "= 1.17.0"
extension_point: flavors
built_against: {version: "1.17.0", closure_sha256: "…"}
- payload: metanorma
constraint: "= 1.17.0-ruby3.3"
extension_point: flavors
built_against: {version: "1.17.0-ruby3.3", closure_sha256: "…"}Figure 16 Soundness: the press subtracts the INTERSECTION of the family's platform/line closures — a gem is subtracted only if present in every closure the slice will mount beside — and refuses (build error) when the inventories are not identical. One subtraction therefore serves every named row; the dispatcher's any-edge match (v2.8.19) attaches the slice to whichever row the user's version pin selected. A new base line (say -ruby3.5) is a NEW row the slice does not name: dispatch skips loudly (the unattached-flavor journal), and the slice press adds the edge after verifying the new row's closure identity — never a silent range stretch.
Runtime-side grants (locked 2026-11-07; additive — schema_minor 18). The extension-point pattern above attaches a slice to an APP payload's declared point. A slice may instead augment the RUNTIME's own library layout — the shape the other ecosystems' content plugins take (python's site-packages, node's node_modules, ruby's gem home beyond the app's closure). The runtime declares the grant; the slice names the role; neither spells the other's paths:
# the runtime (kind: runtime), PROVIDES gains:
provides:
engine: python
# …
layout_grants:
- role: site-packages # the symbolic name slices augment by
slices_at: /tebako/slices.d # VFS-absolute; slices mount BELOW it
layout: python-site # gem-home | python-site | node-modules | files
search_env: PYTHONPATH # the variable the driver extends per slice
# the slice, `augments:` gains the runtime form (MECE with the payload form):
augments:
- runtime: python # the engine name (spec 05 §5)
role: site-packages # the runtime's declared grant
constraint: ">= 3.11, < 3.14" # vs the runtime's language_version
Rules (each a named error, never a guess):
The grant names the role. A runtime: edge whose role no layout_grants entry of the composition's runtime declares fails dispatch with UnknownLayoutGrant (naming the runtime, the role, and the granted set); an edge naming a runtime the composition does not resolve fails with LayoutGrantRuntimeAbsent. A slice carrying BOTH edge forms is a manifest error (augments[] is exactly one of the payload form or the runtime form per entry).
Below, never at. The slice mounts at <slices_at>/<slice.name> (spec 07 §2 step 3a's multi-mount, appended after the runtime's own mounts). Mounting AT the role's live path is impossible by construction — slices_at is a directory the runtime's env image leaves EMPTY (the factory proves it at build), so a slice never shadows the runtime's own library tree.
*Search order is the runtime's integrity rule. — the driver extends the grant's search_env with each attached slice's mount AFTER any entries the runtime's own environment already set (append, in attachment order). Collision semantics are the engine's own and stay honest: ruby's gem activation is requirement-driven (no order shadow); python's sys.path and node's resolution are first-wins, so a slice CAN shadow there — the factory's grant is the statement that it accepts the role's content shape. The journal records each extension (event=layout-grant slice=<name> role=<role> path=<mount>).
layout: semantics ride the extension-point enum (§2.8): gem-home content is a mini GEM_HOME; python-site / node-modules are flat import-root trees; files is opaque content the runtime's own code enumerates. The runtime's factory picks the spelling that matches the engine's search semantics.
No runtime of its own, unchanged: the slice's language requires edge is satisfied by the SAME runtime it augments (the abi line included) — a slice for a python grant carries requires: [{engine: python, …}] exactly as today.
2.9 MIN RUNTIME TEBAKO (min_runtime_tebako:, additive — schema_minor 15, tebako#666)
An OPTIONAL top-level key naming the minimum tebako tooling version of the runtime this payload runs on:
min_runtime_tebako: "2.8.8"
The author sets it when the payload starts depending on a newer runtime/driver capability (a mount-ancestor route, a spec-32 kind: executable edge, …). The value is 1–4 dot-separated components of the schema_minor-12 component grammar (leading decimals, optional -label suffix); anything else is a named manifest error at parse. Absent = no floor. Old readers ignore the key (the unknown-field rule) — which is exactly why the key exists: the failure mode it retires is a stale cached runtime failing a newer payload with payload-blaming wording.
Semantics (the three consumers, all fail-closed with named errors):
Resolution (spec 05 §5): "newest compatible cached" discards cached runtimes whose own tebako version is below the floor and fetches instead; the miss errors NAME the skipped entries. TEBAKO_OFFLINE=1 keeps fail-closed behavior — cache-or-named-error, with the floor named. A downloaded runtime below the floor (a pinned stale line) is the named stale-runtime refusal.
The driver (spec 17 §8): a runtime whose tooling version is below the floor refuses the manifest by name — "the runtime is too old for this payload's manifest (needs X, have Y)" — both when the manifest parses (the key itself is old-reader-safe) and when the parse FAILED (the manifest uses grammar this runtime predates; the floor is then read by a tolerant top-level scan of the raw YAML). Never "corrupt manifest / self-description lies" for the stale-runtime class.
The floor constrains every runtime the payload's dispatch resolves — its own entrypoint runtime and the spawned runtimes of its requires edges (a provider payload's floor likewise gates the provider's own pair).
The floor is a MINIMUM, not a pin: it never narrows which compatible runtime wins above it, and it never substitutes for the runtime_requirement constraint (the interpreter version axis is the requirement's; the tooling axis is the floor's).
2.10 ENV PASS (env_pass:, additive — schema_minor 16, tebako#737)
The packager's opt-in to the driver's credential scrub. A packaged app must not exfiltrate the packager's credentials by default: at boot's end, after every contract read, the driver BLANKS every TEBAKO_* environment variable that is not part of the boot contract (spec 17 §1/§7's handoff surface, spec 08 §2's jail, spec 22 §6's exec cache, spec 22 §3's child injection, spec 25 §2's trace, and the TEBAKO_MOUNT_* discovery prefix) — TEBAKO_GITHUB_TOKEN above all. The scrub journals each NAME at debug, never a value.
env_pass:
- TEBAKO_FLAVOR_KEY
Every entry is a TEBAKO_-prefixed variable name (uppercase alphanumerics and underscore); anything else is a named manifest error at parse. The opt-in may only name what the scrub itself could take.
The driver reads the list from the FIRST image's embedded manifest (the app payload); an absent/unreadable manifest means NO opt-in — the scrub fails safe. A standalone boot (no images) scrubs with no opt-in.
Old readers ignore the key; the scrub is driver behavior, not a resolution input — the failure mode the key retires is a packaged run silently carrying the press host's credentials.
3. Platform axis (locked, vcpkg-triplet form)
platforms is EITHER "universal" (pure-ruby/data) OR an explicit list:
aarch64-macos, x86_64-macos
x86_64-linux-gnu, aarch64-linux-gnu
x86_64-linux-musl, aarch64-linux-musl
x86_64-windows-ucrt, aarch64-windows-ucrt
(aarch64-windows-ucrt joined the axis at payload-manifest schema_minor 13; pre-13 readers reject it by name — exit 65 — which is the designed fail-closed behavior for a triplet outside an old reader's axis.)
ONE Platform type (tpkg crate) owns the triplet ↔ release-asset-name mapping (aarch64-macos ↔ macos-arm64, x86_64-linux-gnu ↔ linux-gnu-x86_64, x86_64-windows-ucrt ↔ windows-ucrt64, …) — dispatcher, release tooling, and registry consume the SAME mapping.
4. The three tiers (no duplicated authority)
In-image manifest (this spec) — THE rich layer; signed/encrypted with the image.
tpkg trailer (spec 02) — stays minimal: mount/exec directives, per-slot digests, signature; REFERENCES manifests by image digest, never duplicates them.
Registry manifest (tpkg-registry.yaml, spec 04) — MIRRORS only resolution-relevant fields (kind, name, version, constraints, platforms, entrypoints) so the dispatcher resolves without downloading every payload.
5. Production and consumption
tebako press / tfs mkimage embed the manifest at build time (kind inferred: app for pressed apps; data for plain images; runtime for runtime packages — provides filled from the factory's versions data).
Payload exclusion at imaging time (additive, 2026-10-09, tebako#333): tebako press --exclude <glob> (repeatable) and tfs mkimage --exclude <glob> leave matching paths out of the BUILT image — one grammar, one semantics, one implementation shared by both commands. A pattern matches the payload-root-relative path (slash-separated, no leading /): *, ?, and [...] classes follow fnmatch flag-0 semantics (a * run spans /), \ quotes the next character, and a matched directory prunes its whole subtree (a trailing / on the pattern is accepted and stripped — it names the directory). Exclusion is imaging-time only: excluded paths are absent from the image, and the manifest never records the list (the image simply lacks them). The feedstock Tebakofile's exclude: list (spec 13 §9) is the same grammar, handed to the imager verbatim.
tfs info prints the manifest; tfs stat exposes digests.
The dispatcher (spec 07) resolves runtime compatibility FROM the manifest (runtime_requirement vs cached runtimes' provides).
The bootstrap reads entrypoint/requirement from the manifest when present; the trailer stays the minimal path.
6. The package manifest (L2, extension block type 2)
Locked 2026-07-26 (OCI model: manifest beside the layers, readable without backend knowledge — spec 02 §5b). The package manifest is a YAML extension block in the container, OUTSIDE every payload image. It owns composition; payload manifests (this spec) own self-description.
schema_version: 1
package: {name: metanorma, version: 1.2.3, producer: {…}, created: …}
entries: # one per invocable command (N=1 for simple apps)
- name: metanorma
slot: 0 # which payload image
entrypoint: metanorma # which PROVIDES entrypoint inside it
runtime_ref: ruby@3.4.2;tebako=0.15.9 # per-entry — suites/multi-runtime
interp_env: {RUBY_YJIT_ENABLE: "1"} # the press-time
# composition of slot 0's L1 interp_env,
# packager-refined (spec 07 §9's chain)
- name: mn2pdf
slot: 1
entrypoint: mn2pdf
runtime_ref: ruby@3.3.7;tebako=0.15.9
jail: {…} # package-level request (spec 08)
env: {…} # package-level env (composition rules: spec 07)
mounts: # per-slot mount semantics (locked 2026-08-04)
- slot: 0
point: /__tfs__
mode: union # exclusive (default) | union; cow/enc reserved
precedence: after-env # union only: this image shadows the env image
lock: # the press-time composition lock (spec 23 §4/§13)
runtime: {version: 0.16.19, carry: false}
slices: [{name: metanorma, version: 1.2.3, carry: true, slot: 0, sha256: …}]
spawned: # spec 30 edges, press-locked (spec 23 §13.6)
- engine: java
constraint: ">= 21, < 26" # mirrored from slot 0's L1 requires
expose: [java] # mirrored from slot 0's L1 requires
version: "21.0.12" # the press-time pick
tebako: "2.1.5"
carry: true
exe: {slot: 1, sha256: …} # carried pair — never mounted
image: {slot: 2, sha256: …}
runtime_ref per entry kills the 128-byte single-field limit (suites, multi-runtime packages); the trailer's v1 field stays for v1 loaders.
entries[].name / entries[].entrypoint mirror the slot payload's L1 provides.entrypoints[] (§2.2 completeness — one SSOT): every L2 entry names a DECLARED L1 entrypoint of its slot, enforced by tebako-pkg validate (tebako#494). Two entries MAY share one slot — same image, different in-image entrypoints: the multi-command single-payload form (one app slice carrying several CLIs, e.g. metanorma + fontist).
entries[].interp_env (IMPLEMENTED 2026-10-07, tebako#559 — §2.7's L2 face): the press-time COMPOSITION of the slot payload's L1 interp_env with the packager's refinement (a packager key wins over the same L1 key; L1 keys pass through untouched otherwise). The mirror exists because the size-gated bootstrap reads no image bytes: the standalone dispatcher consumes exactly this block, never the in-image L1. tebako-pkg validate cross-checks the composition against the slot's L1 (every L1 key present with its declared or the refined value; a dropped L1 key is a named validation error, the tebako#494 class) — the block is a faithful mirror plus declared overrides, never an independent authority. Managed dispatch (registry payloads, no L2) reads the store's L1 manifest mirror instead (spec 07 §9's chain).
v1-era packages without the block behave exactly as today (stub.rb / local conventions); the block is additive.
mounts is optional; a slot without a mounts row mounts exclusive (spec 17's historical behavior — a duplicate point is a named error). mode: union merges the image over the images already mounted at point with declared precedence — read-only images only, directories merge, file conflicts resolve by precedence order (the env image is always lowest). precedence values: after-env (over the runtime's env image — the pressed-app form) or after:<slot> (over another payload slot). The union set is journaled at boot (spec 17 §1). cow/enc are RESERVED mode spellings on the same axis (the transforms law: overlays exist only in the Rust TFS) and are named errors until their specs land.
lock is optional (absent on pre-spectrum packages — they resolve exactly as before). lock.spawned[] mirrors the app payload's L1 requires[].kind: runtime edges (engine/implementation/constraint/ expose) plus the press-time pick and carry verdict (spec 23 §13.6); tebako-pkg validate cross-checks the mirror against slot 0's L1 (the tebako#494 class), and the bootstrap resolves the rows at dispatch into the store's runtimes/ area + TEBAKO_SPAWN_LOCK (spec 30 §2).
toolkit (native layer, e.g. inkscape/gtk — the distro-ports model, spec 13 §9):
provides:
executables: [{name: inkscape, path: /bin/inkscape, version: 1.3}]
libraries: [{name: xml2, path: /lib, abi: "2.12"}]
exec_tier: dynamic | wrapped | tfs-native | static # spec 07 §8
exec_closure: [/bin, /lib, /share/inkscape] # static tier only
capabilities: {exec: true, read: true}
exec_tier tells the dispatcher HOW to run its executables (preload shim / link-wrapped / already-TFS-native / extract-closure) — consumers never care which path a tool took.
7. The digest fixed-point rule (locked 2026-07-26)
A manifest inside the image it describes CANNOT name that image's sha256 (self-reference has no fixed point). Therefore:
tree_hash is computed over the payload tree EXCLUDING /__tpkg__/ (manifest-excluded merkle root — well-defined, and it is what CAS/dedup/signing use). The construction (SHA-256, 4 KiB chunks, length-prefixed domain-separated serialization) is locked as tfs-merkle-1 in crates/tpkg/src/merkle.rs; tfs mkimage and tebako press stamp it at image creation, tfs info --verify recomputes and compares (roadmap 37, SHIPPED; verification-on-READ inside the VFS is a later milestone).
blob_sha256 is NOT stored inside an embedded manifest: it lives one tier out — in the registry mirror (tier 3) and/or the tpkg trailer's per-slot digest array (tier 2, spec 02 §4). Producers fill it there; consumers verify the image against the OUTER record, never against a self-digest. An embedded manifest carrying a blob_sha256 is read as advisory provenance only (e.g. the digest of the source image it was built from), never as a verification input (spec 15 §5).
8. Executable dependency edges (locked 2026-07-27)
requires gains a fourth edge kind for the provides/requires capability graph (the inkscape case):
requires:
- kind: executable # an executable another payload PROVIDES
name: inkscape
constraint: ">= 1.3"
mount: /opt/inkscape # consumer-declared, as always
Resolution: the dispatcher searches installed + available payloads for a PROVIDES.executables entry matching name + constraint (exact name, never a prefix/guess). Exactly one candidate → use it. Zero → named DependencyNotFound(executable, constraint) with a registry hint. More than one → named AmbiguousProvider listing candidates (payload, version, source registry) — the user pins with a payload-kind edge instead. The providing payload is mounted at the consumer-declared mount; its executables run per its own exec_tier (spec 07 §8).
The edge gains the OPTIONAL expose: list (additive — schema_minor 5, spec 32): an expose-carrying executable edge gains the SPAWNED payload surface — each exposed name dispatches the provider payload's own full spec-17 dispatch as a child process (its own runtime edge, its own mounts, its own jail union). mount and expose are orthogonal axes (VFS surface vs spawn surface; both may hold together), the capability match widens to provides.executables ∪ provides.entrypoints[].name, and every exposed name must resolve to a runtime-carrying entrypoint of the resolved provider (press/install cross-checked — a runtime-less match is a named error, never an exec-tier fallback). An exposed name never takes the exec-tier path — the spawn dispatch owns it. The child plan, the spawn-lock row, the lock's spawned[] payload row, the shim surface, the jail interaction, and the failure modes are spec 32 §2–§7's.
TBK SPEC 05 — Resolution and machine cache (L3)
Normative specification of runtime/payload resolution and the shared machine cache. Status: SHIPPED for runtimes (M6–M8); payload cache PARTIAL (roadmap 07).
1. runtime_ref (the resolution hint in the v1 trailer)
<lang>@<lang-version>;tebako=<tebako-version>[;image][;sha256=<64 hex>]
Language-generic by construction; ruby@… is today's instance.
;sha256= — fat payload checksum (the embedded runtime slot).
;image — bare flag: image-era runtime (interpreter + separate .tfs). The image's expected sha256 comes from the release index — the same trust source as the executable's own checksum. Bare-flag form keeps image-era fat refs inside the 127-byte field budget.
Refs without ;image behave byte-identically to v1: no image lookup, no download, no env.
2. Release index (runtime factory releases)
The index is per-package first (tebako#493): the resolver's preference order is the per-package shard → the derived monolith → the line index. The fallbacks stay forever — pre-shard releases are immutable and remain installable (invariant 7); a missing, unreadable, or triple-mismatched shard falls through to the next form with the URL recorded for the failure message. Post-2026-09-12 release lines ship no monolith at all (spec 13 §2a's de-rendezvous, roadmap 85): on them the shard-first order never misses, and the monolith + line-index forms exist only for the immutable pre-de-rendezvous releases. Range enumeration (choosing the newest COMPATIBLE version line) flows through the factory's in-repo L3 registry (spec 04 §2), never through a release monolith.
<stem>.manifest.json — the per-package shard, the sidecar-era authority. The stem is the exe asset's own name (tebako-runtime-<ver>-<lang>-<lv>-<triplet> — suffix-less, §2's spelling rule below, on windows too). The shard is ONE manifest-entry object (the same fields the monolith's array items carry: the identity triple, filename, sha256, the additive image / dll / contract-set keys). The resolver derives the stem from the requested triple, fetches exactly one small object, and reads the contract gate from it (normalized to the array shape at the resolver boundary — tebako-resolve owns the release-card reader semantics).
manifest.json — derived monolith; the same per-asset entries as an array, plus the additive image-era key image: {filename, sha256, size_bytes} and the additive contract_version key (bootstrap↔runtime contract, spec 06 §6).
The entry's filename is the ONLY authoritative asset spelling (spec 00 §10 SSOT; tebako#456). A consumer matches the entry by the identity triple (tebako_version, <lang>_version, platform) — never by a synthesized name — and flows filename / image.filename / dll.filename+install_as verbatim into the download URL, the cache layout, and the pre-download contract gate. The tebako-runtime-<ver>-<lang>-<lv>-<triplet>[.exe] grammar is the factory's to declare, not the consumer's to derive (the factory publishes the windows exe SUFFIX-LESS). When no entry matches the identity triple (a pre-identity index), the synthesized spelling remains the fallback for the SHA256SUMS-only era, and the missing-entry refusal names the identity triple — the mis-lookup is diagnosed as what it is, never as a contract refusal of a hand-invented name.
The grammar carries the language segment (tebako#716): tebako-runtime-<ver>-<lang>-<lv>-<triplet> — <ver> the tebako line, <lv> the language version, and <lang> the runtime's distribution identity: the registry row's implementation when the factory ships several flavors of one engine (openjdk publishes temurin and graalvm rows side by side in the same release), else the engine name (ruby, python, …). The segment is dash-free [a-z0-9]+ — a tebako line never carries -, so the dash is the unambiguous field separator. A flat directory holding several languages' runtimes is self-describing, and a cross-language version overlap can never collide byte-for-byte. Era law: assets published before this amendment (the ≤ v0.16.32 line) spell tebako-runtime-<ver>-<lv>-<triplet> — immutable, sha256-pinned by live registries and shipped packages, keep-forever (invariant 7). The identity-triple match + verbatim filename flow means consumers never branch on era for FLOWED names; a registry pick likewise flows the row's declared artifact stem into the shard probe verbatim, so the probe is exact in either era and never recomposes the identity. The few places a consumer synthesizes a name behave as follows: a REMOTE probe whose target's era is unknowable (the shard fetch on a registry-less channel, a bundle-sidecar existence probe) tries the new-era spelling first and falls back to the old-era, journaling both; the OCI lane (spec 38) opened after this amendment, so its selector-less default tag composes the new-era spelling only; the INDEX-LESS cache fallback (fat/carried installs, pre-identity manifests — all pre-#716-shaped by construction) composes the old-era spelling permanently.
SHA256SUMS.txt — line-index fallback (<sha> <file>), carries the <asset>.tfs lines in the image era.
Every payload asset also carries its own <asset>.sha256 sidecar (coreutils <sha> <file> — the store marker's exact shape). The sidecar is the per-asset pin; the shard's sha fields are re-anchored to the served bytes at publish time.
Bundle-era lines (additive, 2026-09-24, spec 36): a shard carrying the additive bundle block is consumed as ONE fetch — the <stem>.tar.gz bundle + its sidecar (+ .asc when declared) — verified, then unpacked in-process into the §3 store layout with every member checked against the shard's per-member pins (InvalidBundle, spec 36 §7). A shard without bundle takes the per-file path, forever. A pre-bundle resolver on a bundle-era release fails LOUD at the exe fetch (the asset does not exist — exit-69 class, naming the identity triple), never an exec of wrong bytes.
The download base is PER-ENGINE (the chain below is SHIPPED in tebako-shim's dispatch-time fetch — tebako#567; the CLI's press-time resolver and the bootstrap consult TEBAKO_RUNTIME_MIRROR + the default base only). First hit wins, and every download journals the base AND the channel that supplied it:
runtimes: {<engine>: {source: <base>}} — the authored config pin (spec 07 §0; most specific: an operator who pins an engine's source means exactly that base for that engine).
TEBAKO_RUNTIME_MIRROR (https or file://) — the operator's global override, applying to every engine WITHOUT a source: pin. When a pin shadows a differing mirror value the shadowing is journaled, loud — never silent precedence.
Registry-derived — a registered registry (spec 04 §2) carrying a kind: runtime entry whose engine: (+ implementation: when the edge names one) matches, with a version satisfying the edge's constraint: the base derives from that version's release.ref — or, when the host's row carries the additive per-row release.ref (registry schema MINOR 6, tebako#711), from THAT ref: a version line unioning rows from several per-platform shard tags cannot name the serving tag at the version level, so the row carries it. This is the zero-config path — a third-party runtime becomes resolvable from tebako add-registry <its feedstock> alone, no authored config required.
The product default base https://github.com/tamatebako/tebako-runtime-ruby/releases/download (the ruby factory line — the back-compat floor every pre-chain consumer already speaks).
An edge no channel answers is a NAMED error enumerating the channels tried, each with its own failure reason (tebako#281): a throttled read names the throttle and its retry budget plus the ambient-token remedy (TEBAKO_GITHUB_TOKEN / GITHUB_TOKEN raise the api.github.com budget), a not-found says so, a clean-but-empty read says so — never a silent query of a base that hosts no such engine (a wrong-line 404 is diagnosed as what it is), and never a bare "neither source read".
Signing of the index and the artifacts it names: spec 09 §5 (every consumable index form signed — the same-channel-MITM gap closes) and spec 09 §4's runtime-fetch verification point (the per-artifact signature check, the unsigned-line semantics, the exit codes). The fetch journal records the verification strength alongside the base and the channel that supplied it.
3. Machine cache layout (~/.tebako)
runtimes/<lang>-<lv>-<ver>-<triplet>/
tebako-runtime-<ver>-<lang>-<lv>-<triplet>[.exe] # interpreter (0755)
sha256 / origin # executable markers
tebako-runtime-<ver>-<lang>-<lv>-<triplet>.tfs # image-era runtime (0444)
<image>.sha256 # trust anchor ("<sha> <file>\n")
<image>.origin # source URL
payloads/<name>/<version>.tfs # registry payloads (0444)
payloads/<name>/<version>.tfs.sha256 # trust anchor
payloads/<name>/<version>.manifest.yaml # manifest mirror (embedded wins; else synthesized LOUDLY)
shims/ # spec 07
registries/<sha>.yaml (+.fetched-at) # dispatch-time registry cache (24 h TTL, spec 07; §4's stale-serve)
config.yaml # spec 07 (YAML — never JSON)
keys/ # press-local signing keys (spec 09)
keyring/trusted.pgp # the trusted signer keyring (`tebako keys import`; spec 09 §2)
trust/<FINGERPRINT>.pub # add-registry TOFU pins, read-only (spec 09 §9.1)
trust/ca/<name>.pem # the operator CA store, read-only (spec 22 §4 Rule R4)
Bounding the exec cache (tebako#1102). The tree above is the install-side store; the run-side exec cache (TEBAKO_EXEC_CACHE, spec 22 §6) is bounded per mount: mounts.quota in config.yaml (store-config MINOR 6) caps what ONE mount's keyed materialization namespaces may grow to — a positive byte count (integer bytes or a 1024-based K/M/G string), default 1 GiB, off unbounded. §4's per-mount materialization ceiling owns the enforcement semantics.
The interpreter/image file names in a cache entry keep the index entry's filename / image.filename spellings verbatim (§2 — on windows the exe is suffix-less; the loader execs by full path and CreateProcess needs no .exe). The diagram shows the post-tebako#716 spelling; entries installed from the immutable ≤ v0.16.32 lines keep their <ver>-<lv>-<triplet> spellings forever — the two eras coexist in one store, and the directory name (<lang>-<lv>-<ver>-<triplet>) is era-free. The [.exe] diagram notation marks the synthesized fallback spelling, used only when no index entry is available (fat-payload installs, pre-identity manifests).
3.0a The manifest mirrors and the extension-slice scan
Every installed payload carries its L1 manifest beside the image as <version>.manifest.yaml (the embedded manifest transcribed at install; a legacy image without one gets a LOUDLY synthesized minimal mirror — identity only, no augments). The mirrors are the dispatcher's store-local reading of the extension-slice graph (spec 07 §2 step 3a): the scan for slices augmenting the dispatched payload reads ONLY these files — never the network, never the registry caches (trust was already enforced at install; a run re-verifies nothing). A corrupt or unparseable mirror is a loud skip of that one payload (event=slice-skip reason=manifest-unreadable), never a dispatch failure.
3.1 Home discovery
The store root resolves by precedence (single owner: tpkg::runtime_store::tebako_home; every component — CLI, shim, bootstrap, driver, journal — reads through it):
$TEBAKO_HOME (non-empty) — the explicit override.
The bundle-sibling tier — the process image sits inside a tebako store tree, making that tree the home. Three seats:
<root>/<seat>/<tool> beside a grammar-carrying <root>/home (the bundle layout's bin/; the seat name is irrelevant — the grammar is the witness, so /usr/local/bin never false-triggers);
<home>/shims/<tool> (the windows shim copies; a unix shim is a symlink, resolves to the real binary, and takes the first seat or no seat instead);
<home>/runtimes/<entry>/<exe> (a store runtime — the driver's seat).
The store-grammar markers are: any of config.yaml, shims/, payloads/, runtimes/, registries/, keys/, trust/. A directory carrying none of them is not a home and the tier does not fire.
The platform default — ~/.tebako; windows: %LOCALAPPDATA%\tebako (falling back to %USERPROFILE%\.tebako).
The tier is identity-preserving for managed installs: every managed seat resolves to the home the default tier would pick anyway (or does not fire), so the tier only ever lights up for a foreign tree — a bundle (spec 16 §7's MSI/pkg bin/ + home/ layout). When the bundle tier wins, the shim and the bootstrap export TEBAKO_HOME early so the whole process tree — dispatch execs, the runtime driver, spawned grandchildren — agrees on the one home.
A bundle home may be read-only (installed under Program Files / /opt): runs work (mounts never write), mutating verbs fail with a named IO error naming the unwritable path, and the audit journal degrades to best-effort silence.
4. Install and trust rules (locked)
Per-entry flock (120 s timeout with stale-lock hint); install is tmp + rename — a partial install is invisible.
Commit order (locked 2026-09-16): an install lands in three stages — the image + trust anchor stage first (dispatch-invisible bytes), the payload's requires: closure walks second, and the manifest mirror's save is the commit point. A version whose mirror is absent was never installed, whatever else the record holds: consumers keying on "installed" (the closure's cached-pin short-circuit included) test the mirror, and an aborted attempt's staged bytes re-run the tail from the cache hit — never a re-download, never a half-installed record masquerading as standing.
The .sha256 marker IS the trust anchor: present ⇒ the artifact was sha256-verified at install; re-verify only on re-fetch, never per run.
Image-era cache entries hold artifacts only — no extracted layout/ tree; press seeds its environment by extracting in-process through the TFS ABI and rebuilds per press.
TEBAKO_OFFLINE=1 — cache hit or hard error.
Stale-registry serve on fetch failure (locked 2026-09-12, roadmap 86): the dispatch-time registry cache (registries/<sha>.yaml + .fetched-at, 24 h TTL — spec 07) degrades LOUD, never hard: cache PRESENT but stale + the refresh fetch failed → the stale cache SERVES, with a stderr warning and a journal line (event=stale-registry-serve, naming the ref and the fetch error); cache ABSENT + fetch fails → the named resolution error, unchanged; a fresh cache and a successful refresh are unchanged. TEBAKO_OFFLINE=1 stays cache-or-named-error, unchanged. This is NOT a silent fallback: the registry is an index — the trust anchor is the artifact's .sha256 / .asc verified at fetch time, never the registry's freshness, and a stale index can name only artifacts whose own anchors still verify at install.
tebako cache list (runtimes and payloads) / cache prune [--runtimes] [--payloads] [--all | --older-than Nd] manage the cache. Bare cache prune touches runtimes only; --payloads adds the payload arm, which NEVER removes a pinned version — the protected set (config defaults: pins through the spec 07 §2 toolpin grammar, exact payload@version disable selectors, and each name's newest installed version, the roll-forward floor) binds even under --all: prune never strands a pin. Per-directory .tebako-tools.yaml pins are dispatch-time state and invisible to prune (a reachable one prints the caveat once). Removal deletes the version's whole record — the .tfs, its .sha256 / .origin markers, the .manifest.yaml mirror, a materialized .tree/, the install lock — and the name dir when it goes empty.
A run is a run: executing a package NEVER installs its payload slices. tebako install <path> installs a local package's payload slices explicitly — trailer slot digests are the anchors for signed (v2) packages, the computed digest for unsigned ones (the run's own enforcement strength, never upgraded); the runtime slot is NOT store-installed (it resolves into the runtime cache on first run, as always). Idempotent same-sha skip; same name+version with different content is never overwritten (loud warning + journal). Shims link only via the explicit --shims (spec 07). TPKG_FLAG_NO_INSTALL packages refuse (spec 02 §5).
Lazy seeding (the scoped exception, locked 2026-08-25, tebako#460): a package that CARRIES artifacts (the self-contained preset — spec 23 §13) MAY seed the machine cache with them at run time: the runtime pair (exe + env image) and each carried payload slice, so later packages share them. The exception is exactly this wide and no wider:
best-effort — a seed that cannot complete NEVER blocks or fails the run; the carried artifacts keep serving from the package;
tmp + rename under the entry lock — a partial seed is invisible and the next run re-seeds;
idempotent — a same-sha entry skips;
trust anchors exactly as tebako install: trailer slot digests for signed (v2) packages, the computed digest for unsigned ones — the run's own enforcement strength, never upgraded;
journaled (event=lazy-seed), and shown by tebako cache list with the seeding package as origin;
TEBAKO_OFFLINE=1 does not block seeding (no network is involved);
TPKG_FLAG_NO_INSTALL packages never seed (spec 02 §5).
The shared-runtime preset needs no exception: its artifacts arrive through the ordinary resolve-download-verify-install path.
Per-mount materialization ceiling (locked 2026-11-23, tebako#1102): what ONE mount's keyed exec-cache namespaces (spec 22 §6 — resources/<image-key>, trees/<image-key>[…], tebako-dlcache/<image-key>) may materialize to is bounded by a configured ceiling: mounts.quota in ~/.tebako/config.yaml (store-config MINOR 6 — a positive byte count as an integer, a 1024-based K/M/G-suffixed string, or off; absent binds the documented default, 1 GiB). The runtime driver resolves and arms the ceiling at boot against the boot's exec-cache root; every materialize seam accounts its staged bytes BEFORE they land, and on the crossing the write is refused — the named EX_TEBAKO_IO (74) at the driver seams, EDQUOT (unix; ENOSPC on windows) at the tfs dlcache seam — the staging artifact is abandoned (tmp + rename holds: nothing partial reaches the namespace), and the journal gains event=quota-exceeded with the mount identity and the byte counts. A malformed mounts.quota value is the named grammar error (EX_TEBAKO_MANIFEST, 65) at shim config load AND at driver boot — the ceiling is never guessed. Content already installed is never re-gated: a verified cache hit serves at any ceiling. A bare tfs consumer (tfs-cli, a preload-shim child with no driver boot) is never armed and never enforced — the ceiling is a driver-armed policy.
4a. Run-time payload resolution + lazy seeding (tebako#460, locked 2026-08-25 — the fat/lean unification)
One pipeline, one lock. press resolves the full composition closure at build time — the runtime_ref plus every payload ref, transitively — and locks concrete versions + sha256 digests into the L2 package manifest. What press tested is what runs, always.
The embed dial. -m lean|fat is sugar over an embed set (--embed=all| none|name,…): fat embeds everything (runtime exe + env image + all payload slices, per #458's two-slot shape); lean embeds a subset. Embedding changes byte placement only — non-embedded slices resolve at run time by the locked digests, never by fresh semver resolution, fail-closed on mismatch.
Run-time payload resolution mirrors the runtime's own chain exactly: registry fetch → sha256 verify → tmp+rename into ~/.tebako/payloads/ → co-mount at the declared points. Transitive DEPENDS walk with cycle detection; TEBAKO_OFFLINE=1 is cache-or-named-error. Named errors: an unresolvable slice is the 75 class; a digest mismatch is the trust class; a cycle is 65.
Lazy seeding (the one exception to §4's run-is-a-run). A fat package's carried slices are byte-identical with registry artifacts; at first run the loader MAY copy absent slice regions into the machine cache (tmp+rename, the trailer-slot digest the trust anchor for signed packages / the computed digest for unsigned; journaled; idempotent same-sha skip). Strictly best-effort: never blocks, never fails, invisible when partial. The runtime pair seeds the runtime cache identically. Net: a fat download is a cache prime with a runnable side effect; fat and lean converge byte-for-byte.
Trust uniform: embedded or resolved, the same sha256 anchors, the same unsigned-is-loud + journal rules, the same TEBAKO_REQUIRE_SIGNED=1 fail-closed, verification at fetch/install — never per run.
5. Resolution chains
Runtime for a payload (dispatch time): payload's declared requirement (engine + optional implementation + constraint) → newest COMPATIBLE runtime already cached (no download) → else download the newest compatible from the runtime releases → verify → cache. Swapping runtimes never touches the payload. The min-runtime floor (spec 03 §2.9, schema_minor 15, tebako#666): when the payload manifest declares min_runtime_tebako, cached runtimes whose own tebako version is below the floor are discarded BEFORE the compatible pick (they are named in the miss errors, never silently preferred) and the download path runs instead; a downloaded runtime below the floor (a pinned stale line) is the named stale-runtime refusal. TEBAKO_OFFLINE=1 stays cache-or-named-error with the floor named. The floor gates every runtime the dispatch resolves — the entrypoint's own and the spawned edges' (spec 30/32); a provider payload's floor gates the provider's pair.
Runtime for a shared-runtime package (first run): trailer runtime_ref → cache hit → use; miss → download from the index (per-package shard primary, manifest.json next, SHA256SUMS fallback — §2's order) → sha256-verify → flock'd atomic install. (Preset names per spec 23 §13.2: shared-runtime is the default preset and the successor of the deprecated name lean; self-contained succeeds fat.) Self-contained: the runtime pair is carried as two package slots — the interpreter exe and the env image (spec 19 §6.1): the exe stages into the runtime cache, the env image mounts from the package file through the ordinary <self>:<slot>:<mount> grammar, both verified against the trailer slot digests, and both seed the cache per §4's lazy-seed rule. (Pre-#458 packages carry the runtime as one legacy format_id = 4 slot, extracted and verified against ;sha256= — readers keep serving that form; presses never emit it.)
Compatibility model: pure-language payloads take a range (>= 3.3, < 5.0) — any newer runtime works; native-extension payloads lock to the ABI line they were built against, which is TWO-dimensional: the version line (~> 3.3.0) AND the platform line (abi: arm64-darwin-23 — the runtime's own platform string; ruby: Gem::Platform.local.to_s, from the staging runtime's RbConfig::CONFIG["arch"]). A newer line needs a new payload build (or an SDK rebuild path); a wrong line on EITHER axis produces a named compatibility error, never a segfault. Runtimes publish their platform string as the per-package abi key in the release index (spec 13); cached runtimes installed before the field existed stay eligible (the compat window — a payload's abi check never fails against an unknown line). Registry MINOR 11 (tebako#1047) carries the same line on the aggregate registry's per-triplet platform entries (platforms[<triplet>].abi, stamped by the factory — spec 04 §2), and the registry-walk download pick excludes a row whose entry declares a non-matching abi BEFORE any byte moves: "newest compatible" becomes literally true, and the nothing-matches refusal names the excluded rows on their own axis (excluded by the payload's abi line "…"). A row without the key is unknown, never excluded — the post-download check stays the backstop for pre-MINOR-11 rows and platforms: universal rows alike.
Version ordering (the plain-wins rule — the single owner is tpkg::versions::compare; every consumer flows it). Versions are dot-separated components, missing components zero. Within one component: a leading numeric prefix compares numerically (1.10 > 1.9); at an equal prefix a PLAIN component ranks ABOVE a suffixed one (3.13.15 > 3.13.15-jit — semver's release > prerelease rule), so a factory's build variant (a -jit, -debug, … line) never silently outranks its plain twin in a newest-satisfying pick; two suffixes order lexicographically; a component without a numeric prefix falls back to whole-component string order. Constraint MATCHING is unaffected: a variant version still satisfies an open constraint, so a platform where ONLY the variant exists still resolves — the variant simply never wins a max pick against the plain twin. A variant is SELECTED through the pin surface (the config version: pin, the registry default), which names versions exactly and never compares.
Variant suffixes in constraints (payload-manifest schema_minor 12). The constraint grammar (spec 03) admits the SAME suffixed component shape versions carry — each dot-separated component is leading decimals plus an optional -label ([0-9A-Za-z-]+) — so an exact pin can NAME a variant line (= 1.16.9-ruby4.0 — the spec 03 §2.8 binding rule against a line-split base, one slice per base line). Matching semantics (tpkg::versions, the single owner): equality clauses are suffix-exact — the variant and its plain twin are DIFFERENT versions (= 1.16.9 never matches 1.16.9-ruby4.0); ordering clauses follow compare() unchanged — a plain bound excludes variants ranking below it (>= 1.16.9 does not match 1.16.9-ruby4.0), a suffixed bound admits its own line upward (>= 1.16.9-ruby4.0 matches the variant, the plain twin, and everything newer); ~> computes its upper bound from the numeric core under the same component model as compare() — the label's own dot counts (~> 1.16.9-ruby4.0 is a four-component spelling, so the bound is < 1.16.10; for < 1.17 write the explicit range). Readers older than minor 12 reject a suffixed clause by name (exit 65) — fail-closed, never a misread pin.
The implementation axis (spec 28 §8): engine names the LANGUAGE — mri, jruby and truffleruby are all engine: ruby, told apart by the runtime's provides.implementation. A requirement WITHOUT implementation matches any cached runtime of the engine whose language_version satisfies the constraint (the pure-language case: one build, any implementation — jruby 9.4 declares language_version: "3.1", so a >= 3.3 requirement does not match it and a >= 3.1 one does). A requirement WITH implementation reads its constraint against that implementation's OWN version line ({engine: ruby, implementation: jruby, constraint: "~> 9.4"}) and matches no other implementation. An abi: in force requires implementation — ABI and platform lines are per-implementation by construction; a native requirement naming no implementation is a named manifest error (spec 03 §2.2). Compatibility never crosses implementations silently: the chosen runtime's implementation is journaled with the resolution event.
The python wheel-tag mapping (engine: python — locked 2026-09-08). Python native extensions carry CPython's own two-tag compatibility grammar (the PEP 425/600 wheel tags). Tebako does not invent a second grammar — it maps that one onto the two-dimensional ABI line above, once, here; the resolver and the factory REFERENCE this table and never re-derive it in code comments.
Version line. The wheel ABI tag cp3X (cp311, cp312, …) IS the version line ~> 3.X.0: a native-extension payload baked against CPython 3.X declares runtime_requirement: {engine: python, constraint: "~> 3.X.0", abi: <the built-against runtime's abi>}. Pure-python payloads take the range form exactly as ruby's pure-language case (xml2rfc's requires_python >= 3.10 is the first instance).
The stable ABI (abi3) is a bake-time concern, never a resolver concern (locked). An upstream cp3Y-abi3 wheel is compatible with every CPython line >= 3.Y; the factory consumes that width by baking the abi3 wheel into EACH targeted (line × triplet) payload variant. The baked variant records the TARGET runtime's line and abi exactly like a line-specific build — the resolver's grammar gains no abi3 case and the compatibility width never leaks into the wire.
Platform line. The python runtime's published abi key (spec 13) is the CPython extension-suffix stem (sysconfig EXT_SUFFIX without the leading dot), e.g. cpython-312-x86_64-linux-gnu.so. The payload records the built-against runtime's abi verbatim; comparison is the exact-string rule above, unchanged. macOS's suffix is arch-neutral (cpython-312-darwin.so) — the arch axis rides the triplet alone there; no second arch axis is ever introduced.
Wheel platform tags ↔ triplets — the one table:
Table 7 wheel platform tag (PEP 425/600) tebako triplet manylinux_*_x86_64 linux-gnu-x86_64 manylinux_*_aarch64 linux-gnu-arm64 musllinux_*_x86_64 linux-musl-x86_64 musllinux_*_aarch64 linux-musl-arm64 macosx_*_x86_64 macos-x86_64 macosx_*_arm64 macos-arm64 macosx_*_universal2 split per-arch at bake time — the payload stays per-triplet win_amd64 / win_arm64 RESERVED — the windows python runtime is not yet shipped; readers MUST NOT guess a mapping The musllinux-vs-manylinux (libc) distinction rides the triplet axis ONLY (linux-musl vs linux-gnu) — no wheel-tag axis, no libc key, no ad-hoc second axis anywhere in the grammar. A tag's policy version (manylinux_2_28, musllinux_1_2, …) is a build-floor statement consumed at bake time, never a resolution axis: a runtime built against any floor serves its triplet.
Wrong line = the named compatibility error on either axis, unchanged (never a segfault): the python instance names the selector and lists the available cached variants per spec 28 §4/§10.
6. The fetch pipeline (parallel pulls, streaming integrity — locked 2026-09-18)
Every dynamic pull of ARTIFACT bytes (runtime exe + env image + dll, payload slices, detached .asc signature assets, trust-anchor keys — spec 09 §10) runs through the one fetch pipeline (tebako_resolve::plan), never through ad-hoc per-caller download loops. Release INDEX reads (shards, manifest monoliths, SHA256SUMS, registry YAML) stay small buffered GETs; the pipeline is for artifacts.
The plan. Resolution produces the whole closure up front; the pipeline takes it as an explicit FetchPlan: a subject line (the progress header's <what>) plus one item per artifact carrying {reference, sha256 pin, size hint, tmp dir, commit closure}. The commit closure owns the artifact's install semantics (signature verification, the store's lock + rename + markers) — the pipeline owns transport, integrity, and scheduling; neither crosses over.
Parallelism. A std::thread worker pool — jobs from TEBAKO_FETCH_JOBS (env) over fetch_jobs (~/.tebako/config.yaml) over the default 3 (docker's number); 1 is sequential (the debug shape). An unparseable or zero value is a NAMED error, never a silent clamp. No async runtime, no new dependencies (spec 14).
Streaming integrity (one pass, constant memory). Each worker streams its response body into the item's tmp file WHILE updating a streaming sha256 hasher; the pin compares at end-of-stream. The pre-pipeline shape (buffer the whole body into a Vec<u8>, hash as a second pass — a 200 MB image pinning 200 MB of RAM) is RETIRED: artifact bytes never materialize whole in memory on the download path. A signature verification that needs the bytes reads the staged tmp file once, after ITS download completes — overlapped with the plan's remaining streams — and never after the rename.
Retry discipline, per worker per connection. The existing throttle/backoff law is unchanged (the tebako-http SSOT: Retry-After honored exactly, the 60 s × 2ⁿ hintless exponential, THROTTLE_ROUNDS rounds; DOWNLOAD_ATTEMPTS for transient failures) — it now runs per worker. A mid-stream failure retries the artifact FROM ZERO (tmp truncated, hasher reset): a resumed partial body would fail the pin anyway.
Failure law. Any artifact's transport/hash/signature/commit failure CANCELS THE PLAN: in-flight streams abort at the next chunk, queued items never start, the pool joins, every tmp file of the plan is dropped, and the FIRST named error surfaces (its exit code unchanged — the taxonomy of spec 06 §4 / the caller's table is untouched). A partial install never appears in the store: tmp+rename (§4) already makes the bytes invisible, and the cancel path removes the tmp files — proven by test, not asserted.
The store is concurrency-safe by design (§4's per-entry flock + content-addressed byte-identical artifacts): two workers never share an entry — one plan holds disjoint store slots, and a foreign process installing the same entry serializes on the same flock with the same 120 s stale-lock-hint timeout. Parallel fetch changes nothing there (test-proven).
TEBAKO_OFFLINE=1 keeps its cache-or-named-error semantics, evaluated per item before its stream starts; TEBAKO_REQUIRE_SIGNED=1 gates exactly where it gates today (the commit closure's signature policy is the caller's, unchanged in meaning).
Rendering: spec 06 §5a — the pipeline renders through tebako-term v2 and nothing else prints download progress.
TBK SPEC 08 — Jails: host-access policy
Normative specification of host-filesystem access control for running payloads. Status: SHIPPED (roadmaps 09 + 30 + 35) — the TFS enforcement point (§1–§3) is SHIPPED in crates/tfs (policy model, tebako_fs_host_policy, per-route EPERM/EROFS gating, symlink re-validation, jail acceptance suite); the TEBAKO_JAIL env form of the policy (§1) is SHIPPED with roadmap 30's preload shim (tfs exec --jail carries it to native binaries); manifest integration (§4 — capabilities.host in crates/tpkg), the press/dispatch surfaces (tebako press --jail writing the package manifest's jail: block, tebako run/tebako-shim --jail|--mount|--no-host), the bootstrap's manifest∩user composition at handoff, and the audit-journal logging of violations (event=jail-deny) are SHIPPED with roadmap 35. Enforcement exists because every file access already flows through the TFS layer — one choke point covers every consumer. The RESOURCE axis (§2.2 — bounded consumption: cpu_seconds / memory / processes / wall_seconds) is SHIPPED for the runtime-driver delivery on both arms — POSIX (rlimits
the forked wall watchdog; the 2026-11-22 amendment, closing the 2026-10-26 scar: a jail probe's child ran 96.9 % CPU for 1d21h unnoticed — the jail confined access but nothing bounded consumption) and windows (Job Objects + the watchdog thread; 2026-11-23, tebako#1101). The preload-only (tfs exec) arm is PLANNED, named in §2.2 and §7 — never silently unbounded.
1. Policy model (docker -v semantics)
jail:
default: open | deny # open = today's behavior (cwd + writes pass through)
mounts:
- host: $HOME/sources
mount: /work
access: ro | rw
argument_files: auto-allowed # the input file you hand the command is allowed even under deny
Three profiles: . full access (open) — host cwd + writes pass through (today). . directory-scoped — cwd mapped to /work, rw; nothing else. . file-scoped tight jail (deny + argument files only) — run an untrusted payload against one input, nothing else.
The TEBAKO_JAIL env form (the form the runtime driver and the preload shim consume — the loader's wire spelling of a policy). ABNF:
policy = default *(";" grant)
default = "open" / "deny"
grant = host-grant / argfile-grant / net-grant / resource-grant
host-grant = host-path ":" mount-path ":" access
host-path = 1*(%x21-3A / %x3C-7E) ; any visible char except ';'
mount-path = 1*(%x21-3A / %x3C-7E) ; the in-VFS point, same alphabet
access = "ro" / "rw"
argfile-grant = "@" 1*(%x21-7E) ; an argv file path, read-allowed
net-grant = "net:" net-host [":" port] ; an outbound peer grant (the
; network axis, §2)
net-host = 1*(%x21-29 / %x2B-39 / %x3C-7E) ; a dns name or IP — no ':' or ';'
port = 1*DIGIT
resource-grant = "resources:" assignment *("," assignment) ; §2.2 — the
; consumption bounds
assignment = resource-key "=" resource-value
resource-key = "cpu_seconds" / "memory" / "processes" / "wall_seconds"
resource-value = 1*DIGIT [ memory-unit ] ; decimal; zero is out of range
memory-unit = ("K" / "M" / "G") [ "B" ] ; memory only, case-insensitive,
; 1024-based — a suffix on any
; other key is malformedopen grants host cwd + writes (today's behavior); deny is the default-deny floor. Each ;host:mount:access grants the host path at the mount point with the named access; ;@path auto-allows an argument file even under deny. The grammar's alphabet excludes ; (the grant separator); a windows drive-qualified floor spelling is NOT carried (the right-split cannot — every consumer re-derives the floor at its own bind, §2's inheritance rule). Examples: deny;/home/u/src:/work:rw, deny;/home/u/src:/work:rw;@/home/u/in.csv, open. A network grant is its own form: deny;net:example.com (the host, any port), deny;net:example.com:443 (one port), and the two compose with host grants in any order. The resource grant (§2.2) is one comma-separated directive — deny;resources:cpu_seconds=60,wall_seconds=300, open;resources:memory=256M,processes=64 — order-free with every other grant form, duplicate keys a named error. Like net:, a resources: token is never host:mount:ro|rw (a RELATIVE host path literally starting resources: is pathological and loses the token).
2. Semantics
Writes to an ro mount fail EROFS; paths outside every mount fail EPERM. Payload images themselves are always ro (spec 11).
Symlinks resolve inside the granted view: realpath checked at bind time, re-validated on each open.
Precedence (locked): the package's manifest REQUESTS access (capabilities.host); the user can always TIGHTEN it (tebako run --jail pkg, --mount src:/work:rw, --no-host) — user policy always wins. Signed/trusted payloads may get wider latitude by policy choice, never by bypass.
Violations are logged to the tebako audit journal with path + syscall class.
Network (the second axis — §1's grammar gains net: grants): an outbound connect to an ungranted peer fails the policy's named refusal and journals the peer, exactly the fs axis's shape. Deny is the floor: with no net: grant, every outbound connection is refused. DNS resolution is allowed unconditionally — a query leaks a name, never payload bytes, and a grant names hosts whose addresses must resolve (the documented carve-out, in the manifest). User tightening intersects the manifest's network request exactly as on the fs axis: the tighter answer for every peer survives; the preload shim judges, never the payload.
2.1 The platform floor (locked 2026-08-14)
Every policy bound under the deny default gains the platform floor: a fixed per-platform set of read-only grants covering the surface a spawned interpreter or runtime physically cannot boot without. The floor exists because the failure mode for a missing platform grant was never a policy verdict — under a scratch-only jail (deny;<scratch>:<scratch>:rw) the JVM crashed with a SIGSEGV at getMacOSXLocale (its locale/framework init NULL-derefs when reads under /usr are denied; spec 22 phase-E dogfood, 2026-08-13). A jail whose denial crashes the child in someone else's library is wrongly constructed: denying the platform surface never produced a working process, so the floor grants it always.
Entries (evidence-driven):
macOS — /usr, /System, /Library (the proven set above).
windows — %SystemRoot%\System32 (the loader's DLL root; no process resolves its imports without it), %SystemRoot%\SysWOW64 (the 32-bit view for 32-bit children), %SystemRoot%\Fonts (the GDI font tree GUI runtimes enumerate — the JVM's AWT init reads it). %SystemRoot% resolves at bind (C:\Windows when unset).
Other unix — none today; an entry joins a list only with a proven platform-process consumer, cited by run. The lists are amended by evidence, never by anticipation.
Supersede rule: an authored mount covering a floor path (same or an ancestor prefix) supersedes the floor entry — the floor never narrows what the author allowed. Widening a floor path to rw is therefore one authored grant away; there is no way to drop a floor path short of not denying (see below) — that is the point of a floor.
Bind semantics: the floor applies at HostPolicy::bind (§3's single choke), only under the deny default — under open it grants nothing the default does not already allow, so the no-policy path stays byte-identical (never_denies keeps its exact meaning). A floor path absent on the host is skipped silently (it is a courtesy surface, not an authored request whose absence must fail the bind).
Ancestor traverse (locked 2026-08-14; extended 2026-10-08): every bound grant — authored mount, floor entry, or @file argument-file grant — implies its strict ancestors are traversable: each ancestor answers an exact-path READ — never a prefix (no sideways exposure), never a write. Canonicalization walks are universal: the JVM reads its cwd and every ancestor at VM init, and the factory's jailed_exec leg died with "Could not determine current working directory" when the chain was denied (PR #95 macOS legs). The deny:arg profile's file grants join the same rule (2026-10-08, tebako#539): a granted input file you cannot stat your way to is unusable — the JVM died at VM init under deny:arg with a granted file in a denied cwd chain. The set is derived at bind — never authored, never serialized. It is what makes an authored $CWD-style grant sufficient in practice: the payload names the directory it works in; the platform walk to reach it passes by construction.
Inheritance: floor mounts are NOT serialized into TEBAKO_JAIL — the env grammar's host:mount:ro|rw right-split cannot carry a windows drive-qualified floor spelling, and it never needs to: every consumer re-derives the floor at its own bind (supersede makes that idempotent), so a spawned child's inherited spec plus its bind yields a policy identical to the parent's. Enforcement treats authored and floor mounts as one longest-prefix set.
The boundary (what never joins): the floor is SYSTEM surface only. The workload's own tool tree (a JRE, a third-party install) and the user's home stay authored grants — an operator's deny must not silently read-expose private data, and the prefix grammar cannot express the "stat-only" grant the macOS CFPreferences home probe needs (spec 22 §3.4's journal-pinned chain, 2026-08-14: floor → named jvm.cfg error → named InternalError → boot with <jre>:ro
<home>:ro). The floor's promise is the end of the segfault
class: every missing grant surfaces as the workload's own named error, pinned in the audit journal — never a crash in someone else's library.
2.2 The resource axis — bounded consumption (locked 2026-11-22; the windows arm, 2026-11-23)
The jail's first axis confines ACCESS (fs, network). The resource axis bounds CONSUMPTION. The evidence for requiring it is ours: on 2026-10-26 a jail probe's child ran 96.9 % CPU for 1 day 21 hours before anyone noticed — the jail held, nothing bounded the runaway. Hermetic is confined AND bounded; docker has cgroups, and the jail needs the userland equivalent or "safer than a container" is false. Like the jail, bounding is opt-in: a policy without resources: is byte-identical to before (unbounded — today's behavior, always).
The four bounds (MECE; the only spellable keys). The YAML block form (the payload manifest's capabilities.host and the package manifest's jail: block, §4):
resources:
cpu_seconds: 60 # CPU time ceiling, seconds
memory: 256M # address-space ceiling, bytes — bare integer or
# a K/M/G (1024-based, case-insensitive, optional
# trailing B) suffix; both forms are bytes
processes: 64 # process-count ceiling
wall_seconds: 300 # wall-clock ceiling, seconds
The env form is one directive of comma-separated assignments (resources:cpu_seconds=60,memory=256M,processes=64,wall_seconds=300), order-free; any key may appear alone. Malformed input is a named error, exit 73 (EX_TEBAKO_JAIL) — unknown or duplicated keys, empty or non-numeric values, zero, u64 overflow, a unit suffix on a non-memory key — never a guess.
Enforcement (the runtime driver — SHIPPED on POSIX and windows; the preload-only arm PLANNED below). The runtime driver installs the resource arm in apply_jail — the same boot moment as the jail itself (after the mounts, before the interpreter handoff), so the limits cover the interpreter and every descendant it spawns (on POSIX the rlimits inherit across fork/exec; on windows every child the interpreter spawns is inside the parent's Job Object — either arm's preload-delivered native child of a bounded tree is therefore kernel-bounded and never re-applies). The mapping:
| key | POSIX mechanism | windows mechanism | the payload-visible answer at the bound |
|---|---|---|---|
| cpu_seconds | setrlimit(RLIMIT_CPU) soft = hard | JOB_OBJECT_LIMIT_PROCESS_TIME (per-process user-mode) | POSIX: SIGXCPU death (128+24 from the parent); windows: the kernel terminates the process at the ceiling (no signal spelling — the kernel's chosen exit) |
| memory | setrlimit(RLIMIT_AS) — Linux (the macOS kernel refuses realistic values, below) | JOB_OBJECT_LIMIT_PROCESS_MEMORY (per-process commit) | address-space growth fails — the interpreter's own allocator error (ruby: NoMemoryError) |
| processes | setrlimit(RLIMIT_NPROC) | JOB_OBJECT_LIMIT_ACTIVE_PROCESS (per-JOB — the per-tree primitive POSIX lacks) | POSIX: fork/spawn fails EAGAIN; windows: children past the ceiling are terminated at creation |
| wall_seconds | the driver's watchdog (below) | the driver's watchdog thread (below) + JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | the named stderr line + the tree's kill (POSIX: the process group's SIGKILL; windows: TerminateJobObject at exit 137 — one verdict on both arms) |
The windows mapping is deliberate where the primitives do not line up: cpu_seconds rides the per-process user-mode clock (JOB_OBJECT_LIMIT_PROCESS_TIME) because Windows offers no user+kernel ceiling — the job-wide aggregate (JOB_OBJECT_LIMIT_JOB_TIME) would let one hungry child spend the tree's whole budget, and CPU rate control throttles where the axis promises death (a throttled runaway is still running at the deadline). memory is per-process commit (JOB_OBJECT_LIMIT_PROCESS_MEMORY), never the per-job aggregate (JOB_OBJECT_LIMIT_JOB_MEMORY): a sibling's footprint must not kill an innocent process — the POSIX arm's per-process shape. processes is the one bound where windows is the stronger arm: JOB_OBJECT_LIMIT_ACTIVE_PROCESS is per-JOB — genuinely per-tree, the primitive POSIX lacks without cgroups — so a bound at or below the tree's current size forbids exactly the new children, never the uid's unrelated processes. The job's KILL_ON_JOB_CLOSE flag arms exactly when the watchdog arms (wall_seconds, below): the job's sole handle is the arming process's, so the root's exit closes it and the kernel reaps the tree — the windows spelling of die-with-root.
A setrlimit the kernel refuses (e.g. a spawned-runtime child whose composed union would exceed the tree's inherited hard limit) fails the boot by name, exit 73 — a bound is never silently loosened; on windows the same posture covers the Job Object calls (a create, limit-set, or assign the kernel refuses — e.g. a spawned-runtime child nesting under the ancestor's job).
Platform reality (macOS). The macOS kernel refuses setrlimit(RLIMIT_AS) for any value below its address-space floor — 2^39 bytes on arm64, the user map's maximum extent (measured 2026-11-22: 2^38 → EINVAL, 2^39 accepted; RLIMIT_DATA and RLIMIT_RSS share the refusal and enforce nothing) — and nothing at or above the floor is a bound. A memory declaration that cannot hold therefore fails the boot by name (exit 73 — never a silent clamp): the axis is enforceable on Linux; on macOS the named refusal IS the answer (§7 row 30), and row 26's control arm declares its memory bound on Linux only.
The honesty notes (what the bounds ARE):
cpu_seconds counts CPU, not wall: a sleeping payload never reaches it. Pair with wall_seconds for runaways that do not burn. On windows the clock charges user-mode time only (JOB_OBJECT_LIMIT_PROCESS_TIME); kernel-mode time is uncharged — Windows exposes no user+kernel ceiling.
memory covers the WHOLE process — the runtime's own footprint is inside the budget (a runtime that needs 300 MB dies under memory: 256M at boot; budget the interpreter).
processes is RLIMIT_NPROC, a per-real-uid ceiling, not a per-tree one (linux counts tasks, macOS processes) — POSIX userland has no per-tree process primitive without cgroups (the named non-goal, §5). Declare it against the uid's current count; a bound at or below that count forbids ALL forking. On windows the same key is per-JOB — genuinely per-tree (JOB_OBJECT_LIMIT_ACTIVE_PROCESS, the table above).
wall_seconds is the tree's wall-clock budget (below). Clock-set jumps skew the cross-process inheritance note below by their jump — wall is not a precision instrument across adjtime.
The wall watchdog (the wall_seconds mechanism, POSIX). The tree-root driver — the first driver boot in the process tree that sees the bound — ensures process-group ownership (setpgid(0,0) when not already a group leader; a group leader cannot re-group and does not need to), then forks a watchdog child and exports TEBAKO_RESOURCE_DEADLINE=<unix seconds> (a contract variable — it survives the tebako#737 scrub and flows to every descendant). The watchdog polls on a 50 ms slice and fires on either condition:
Deadline — the named line (tebako-driver: resource bound exceeded (wall_seconds=<n>) — the payload process group was killed) on stderr, an event=jail-resource bound=wall_seconds op=kill cause=wall line in the audit journal (best effort, raw open(2)/write(2) — the watchdog is a post-fork child and touches no shared state), then SIGKILL to the process group.
Root exit — the arming process is gone (the watchdog watches its parent's pid): the same kill with cause=root-exit. A bounded run's tree dies with its root — the orphan class of the 2026-10-26 scar closed by construction, transitively: every armed watchdog watches its own armer, so a middle layer's death reaps its subtree.
The wall watchdog, windows. The same plan algebra and the same TEBAKO_RESOURCE_DEADLINE contract variable; the mechanism is a thread inside the arming process, not a fork. The tree-root driver creates the Job Object with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, assigns itself, exports the deadline, and spawns the watchdog thread, which sleeps to the deadline and fires: the same named stderr line (tebako-driver: resource bound exceeded (wall_seconds=<n>) — the payload process tree was killed (the job object)`), the same `event=jail-resource bound=wall_seconds op=kill cause=wall journal line, then TerminateJobObject(job, 137) — 137 because it is the POSIX arm's observed number (128+9): one verdict on both arms. The root-exit reap needs no watcher and writes no journal line: the job's sole handle is the arming process's, so the root's exit closes it and the kernel kills the tree (KILL_ON_JOB_CLOSE) — die-with-root enforced below userland; nothing survives the root to journal cause=root-exit, and nothing needs to.
Deadline inheritance. A descendant driver boot (the spec 30 spawned-runtime child) reads the inherited deadline: a descendant whose composed wall_seconds is TIGHTER than the inherited remaining budget re-groups its own subtree (a setpgid on POSIX, a nested Job Object on windows) and arms its own watchdog at min(own, inherited); a descendant without a tighter wall arms nothing (the root's watchdog covers it). The tree's ceiling therefore holds through every composition — no spawn chain outlives the root's declared wall. A malformed TEBAKO_RESOURCE_DEADLINE is a named error (exit 73): the inheritance channel never degrades silently. wall_seconds is the only inherited bound; the rlimits are kernel-inherited by construction and the per-process composition (union, §4) still applies — clamped by the kernel's inherited hard limits (above).
Named boundaries (never implied):
A payload that calls setsid(2) deliberately leaves the watched group. POSIX userland without cgroups cannot hold a determined escapee; the escape requires the payload's own syscall and is OUT OF SCOPE (§5), exactly the static-binary class on the fs axis.
A wall-bounded payload that LEADS a job-control pipeline group cannot re-group (POSIX forbids a group leader setpgid), so its watchdog's kill covers the whole job group — wrap it (( pkg )) to isolate.
When the arming process was not already a group leader (a CI supervisor's child), re-grouping moves the payload out of the supervisor's signal group: the supervisor's SIGTERM/Ctrl-C no longer reaches it and the declared wall remains the ceiling. This is the tree-kill mechanism's price; it engages only when wall_seconds is declared.
Windows: SHIPPED (2026-11-23, tebako#1101) — Job Objects with JOB_OBJECT_LIMIT_PROCESS_TIME / JOB_OBJECT_LIMIT_PROCESS_MEMORY / JOB_OBJECT_LIMIT_ACTIVE_PROCESS (+ JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE when the watchdog arms) and the watchdog thread's TerminateJobObject(…, 137) wall verdict. The honesty deltas against the POSIX arm: cpu_seconds charges user-mode time only; memory is per-process commit, never the per-job aggregate; processes is per-JOB — genuinely per-tree, the primitive POSIX lacks; and the setsid escape class has no windows spelling — the arm grants no breakaway (JOB_OBJECT_LIMIT_BREAKAWAY_OK / JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK are never set), so a windows payload cannot leave its job. The grammar is stable across both arms.
The preload-only delivery (tfs exec): PLANNED — the preload constructor is the named seam for the same rlimits; today the tfs exec surfaces REFUSE a resources:-carrying spec by name (never a silent drop), and a preload-delivered child of a driver-rooted bounded tree is kernel-inherited-bounded (it re-parses the spec, so the directive parses there by design).
record composes with resources: (bounds are not grants — the record rejection covers mounts, net grants, and argument files only); the watchdog's kill lands in the same journal.
3. Enforcement point (the single choke)
New TFS C ABI entry:
int tebako_fs_host_policy(int default_open /* 0 = deny */,
const tebako_host_mount_t* mounts, size_t n_mounts,
const char* const* arg_files, size_t n_arg_files);
The host-passthrough path of every IO route consults the policy: prefix match + access bit per mount. tebako_fs_stat/open/opendir/… return EPERM (denied) / EROFS (ro write).
The policy is about HOST paths; memfs mounts are unaffected.
Implemented in the Rust TFS (crates/tfs) — the same layer that owns routing, so bootstrap, runtime driver, tebako run, and tfs all enforce identically with no per-app work.
Shipped semantics (crates/tfs, roadmap 09)
The policy is process state, not namespace state: tebako_fs_unmount does not reset it (fail-closed); a later tebako_fs_host_policy call replaces it. Install it after the payload mounts are established — the mount family's image read is itself policy-gated once a policy is active.
Gated host-passthrough decisions: open (read and write modes), stat, opendir, dlmap2file, extract_all's destination (a host write), and the mount family's image read. An allowed host path keeps the historic answer ENOENT ("not ours, pass through") for reads AND writes — under open a host write attempt therefore answers ENOENT, not EROFS, so the consumer's pass-through can perform the write (profile 1: "cwd + writes pass through"). Held memfs content is byte-for-byte unchanged (write opens on it stay EROFS).
The per-process materialization tree is NOT a host path for policy purposes (tebako#502, 2026-08-30): a dlmap-marker path (…/tebako-dl-<hex>/… — closure copies and the home-layout whole-tree roots tebako-home-<handle>/…) the image does not answer is the runtime's own extraction served by its host copy. Every route (open/stat/opendir/dlmap2file) answers it ENOENT without consulting the policy: the hex leaf is per-process (unauthorable at bind — the path does not exist to canonicalize), the content rode in through the ungated extraction writes, and the tree is removed at process exit. This is what lets a wrapper-pattern runtime (spec 22 §3's exec cache) compose with a deny jail.
"Host path" means any path the mounts do not hold — outside every mount, or covered by a mount but absent from its image (spec 11 §2): the app payload mounts at / and the host filesystem stays reachable exactly through this rule.
The consumer must route, not just the engine (tebako#917): a runtime whose IO shims call this family only for the paths the mounts COVER hands every uncovered path to the kernel, where this policy cannot see it. Such a shim asks int tebako_fs_host_guard(void) — 1 when the installed policy judges an uncovered path (a deny or record default) — and routes every absolute path through the family while it answers 1. An allowed path still answers ENOENT, the pass-through signal these shims already honour, so an unguarded run is unchanged and a guarded one denies where it said it would. Coverage is a namespace test; a namespace test is not an enforcement point.
A mount's access bit applies even under an open default (an ro bind is ro in an otherwise open namespace, docker-style); longest host prefix wins on path-component boundaries; argument files are an exact read-only grant, even under deny.
Bind-time realpath covers mount sources and argument files (a missing one fails the install with its errno); every gated decision re-canonicalizes the target, so symlinks swapped in after install resolve to their target and escapes fail EPERM.
4. Manifest integration
The payload manifest (spec 03) gains capabilities.host — the access the payload was built to need (e.g. metanorma: read the input file's directory, write the output directory) — whose block carries a network: list of outbound peers the payload was built to need (deny-by-default with explicit grants; a data-only payload needs no network). Dispatch surfaces (spec 07) compose: manifest request ∩ user policy = effective jail, on both axes.
Since the 2026-11-22 amendment the block also carries resources: (§2.2 — the four consumption bounds), authored in the YAML block form. The composition rules on the resource axis mirror the access axes' locked precedence: intersect (request ∩ user tightening) is per-key MIN — the tighter bound wins; a key present on either side survives (the user's silence is not a tightening; the manifest's silence keeps the user's bound) — and union (the spec 30 §4 spawn bridge) is per-key MAX, because the child must be able to do what EITHER side declared, still clamped by the kernel's inherited hard limits and by the inherited wall deadline (§2.2).
Shipped surfaces (roadmap 35)
Model: crates/tpkg/src/jail.rs owns the authored shape (YAML block ↔ TEBAKO_JAIL env form ↔ --jail cli spec: open | deny | deny:arg | a YAML file | the env grammar) and the locked precedence algebra (intersect / effective): deny defaults win; each side's grants are capped by the other side's allowance at the same prefix (ro is sticky, a user --no-host drops request grants); argument files union and auto-allowed resolves argv files into read-only grants at dispatch. The payload manifest's capabilities.host and the package manifest's jail: block are both this type.
Press: tebako press --jail <spec> writes the policy into the type-2 package manifest's jail: block (spec 02 §5b / spec 03 §6); block-less packages are byte-identical to before.
Bootstrap: composes package jail: ∩ TEBAKO_JAIL at handoff and exports the effective policy as TEBAKO_JAIL (+ TEBAKO_JAIL_SOURCE = manifest | user | manifest+user, + TEBAKO_JAIL_JOURNAL → $TEBAKO_HOME/journal.log). Malformed policy fails closed, exit 73 (EX_TEBAKO_JAIL). No policy: nothing exported (legacy byte-identical).
Dispatch: tebako run <pkg> [--jail <spec>] [--mount <host:mount:ro|rw>]... [--no-host] [--] [args...] and the same flags on tebako-shim (consumed before --; the payload mirror carries capabilities.host from install time).
Audit journal (§2): every denial in the TFS layer appends <ts> event=jail-deny path=<p> op=read|write source=<s> to the tebako journal (TEBAKO_JAIL_JOURNAL > $TEBAKO_HOME/journal.log > ~/.tebako/journal.log), best-effort — journaling never fails the operation it audits. One exception, at policy-install time (locked 2026-11-14): when TEBAKO_JAIL_JOURNAL explicitly names the journal and that file cannot be opened for append, a policy that can deny refuses to install — a named error, not a run — because a denial without its record is indistinguishable from a policy that never engaged. The implicit default-home journal keeps the best-effort shape, and per-event write failures on an opened journal never fail the audited operation.
5. Scope (honest, locked 2026-07-26; the network axis joins, 2026-11-07; the platform spawn boundary, 2026-11-11)
Jails cover the FILESYSTEM and the NETWORK. The network: list is the enforcement contract: deny-by-default with explicit grants, judged in-process at the preload's socket family — the §1 net: grant names an outbound peer, and a connect to an ungranted peer fails the policy's named refusal and journals it, exactly the fs axis's shape. Coverage: every IO route through TFS — all interpreted payloads AND native binaries running under the preload interposition shim (spec 07 §8 tier 1, whose IO flows through the same host_policy); the exe shape (spec 22 §3.6) exports the socket family, so an interpreted payload's own connect binds to the judgment. The judged family is connect/sendto/sendmsg plus the getaddrinfo observation (the name → address bridge a name grant judges a numeric peer through). NOT covered: statically-linked binaries (direct syscalls, no interposition point), any process that escapes the shim, DNS resolution (allowed unconditionally in v1 of the axis: a query leaks a name, never payload bytes, and a grant names hosts whose addresses must resolve), AF_UNIX peers (the fs axis's territory, never net-judged), the legacy resolver (gethostbyname — a payload resolving through it judges by numeric spelling only), macOS's connectx (no importer observed), and INBOUND service (bind/listen/accept — the axis is outbound peers; a jailed payload that listens is v2 territory) — all stated honestly in the manifest and docs. OS-level confinement (seatbelt/seccomp/WFP) stays a possible later layer, never claimed.
The shim's coverage is SYMBOL-level (tebako#439): a jail holds only for the libc entry points the shim interposes — the named list in crates/libtfs-preload (lib.rs "Interposed surface"), which includes the LFS64/fortify/versioned twins (open64/openat64/fopen64, __read_chk/__openat_2, the __xstat family through __fxstatat64) because glibc hands _FILE_OFFSET_BITS=64/_FORTIFY_SOURCE/pre-2.33 callers DISTINCT symbols that never touch the plain names (the #439 hole: OpenSSL's o_fopen.c defines _FILE_OFFSET_BITS=64 itself, so every BIO_new_file/X509_LOOKUP_load_file bound fopen64 straight to libc). The WRITE class rides the same gate (tebako#444, closing the pre-existing hole the #439 read-class audit left): open/openat with O_WRONLY/O_CREAT/O_RDWR were policy-gated by the engine's open from the start, and fopen's write/append/update modes (w/a bases, every + update form including r+, the x-forms) plus creat now route through host_policy BEFORE the real libc call touches the host — a jailed write outside an rw grant is EPERM by name, a write against an ro grant EROFS, and a write naming a memfs-held path is EROFS under any policy (payload images are always read-only). Known-uncovered at this layer: the remaining fortify open family (__open_2/__open64_2/__openat64_2 — no importer observed in the 0.16.6 linux-gnu runtime) and raw syscall(2) IO. Separately, the runtime EXE's own statically-linked native libraries are gated only for symbols the exe itself defines (spec 22 §2: dlopen/dlerror today — defining the file-IO family in the exe is follow-up wiring in the runtime factory, tebako-runtime-ruby); an interpreter's patched IO and preload-delivered children are covered.
The platform spawn boundary (tebako#1021): a jailed payload's UNPLANNED host child — an arbitrary host binary the interpreter spawns outside any declared edge (ruby's IO.popen(["cat", secret])) — is the one place the two platforms diverge today. On POSIX the preload tier (LD_PRELOAD / DYLD_INSERT_LIBRARIES, spec 22 §3) inherits into the child: the interposed exec judges the exec target and the child's own reads route through the same bound policy, so the shell-out vector is judged exactly like an in-process one. Windows has no injection tier yet (spec 22, phase W): a spawned host child would run plain-host with the bound policy invisible to it, so under any non-trivial policy the unplanned spawn boundary is FAIL-CLOSED — the interpreter's spawn path asks int tebako_fs_spawn_host_permitted(void) and refuses the spawn by name when it answers 0. The export answers 1 exactly while the bound policy is TRIVIALLY OPEN — the open default with no mounts and no argument files, i.e. there is nothing to enforce; a process that never bound a policy is trivially open by construction — and 0 under any non-trivial one. The refusal is strictly narrower than POSIX by necessity: POSIX can judge the exec TARGET and permit a granted binary, while on windows the child's READS would escape, so the whole unplanned spawn is refused. PLANNED children are unaffected: the spec 30/32 spawned runtime/payload edges re-apply their own jail union in-process from the TEBAKO_JAIL trio (spec 30 §4), so no inheritance is needed. The divergence is tracked as tebako#1021 until the windows injection tier lands.
6. Executor-layer trust (locked 2026-07-27)
Tebako is the EXECUTOR of everything it runs — the parent that spawns and owns the child. Mediating a child's syscalls (preload interposition for dynamic children, seccomp user-notification for static children on Linux) is the execution contract, not hijacking: a hostile party would have to become the executor or the kernel to hold the same position, and both are outside the jail's threat model by definition. Jails bind the CHILD downward; they claim nothing about the executor or kernel upward.
7. Conformance: the attack matrix (locked 2026-10-23)
A jail is only as good as the attacks it has been shown to stop. Every vector below is either blocked and proven by a named test, or named out of scope with the reason — there is no third state. The host-filesystem vectors live in crates/tfs/tests/jails.rs; the environment vector lives beside its implementation (crates/tebako-driver/src/env_scrub.rs); the resource axis's grammar lives beside its owners (crates/tpkg/src/jail.rs the authored model, crates/tfs/src/policy.rs the engine mirror — one grammar, one message set) and its platform mechanisms beside their armer (crates/tebako-driver/src/resources.rs), with the end-to-end arms (fork bomb, infinite looper, under-bounds control) in the release-gate suite's resource arm (ci/jail-conformance.sh). All run on every platform leg of every CI run and therefore on every release: a regression reddens the release matrix, not a dashboard nobody reads.
| # | vector | verdict | the proof |
|---|---|---|---|
| 1 | lexical escape: .., doubled separators, . components inside a grant | blocked | dot_dot_paths_normalize_lexically |
| 2 | symlink escape: a link inside a granted tree pointing at a denied sibling (directory and file level) | blocked (EPERM) | symlink_escape_attempt_fails |
| 3 | TOCTOU: the tree is swapped for a symlink AFTER the policy was bound | blocked (EPERM) | symlink_swap_after_bind_fails_on_revalidation — every open re-validates through realpath |
| 4 | case folding: a denied path asked for with different case on a case-insensitive host | blocked (EPERM) | case_variants_of_a_denied_path_are_denied — the decision is taken on the canonical path (macOS realpath returns the on-disk case), so it never depends on what the filesystem thinks about case |
| 5 | write into a held (image) tree | blocked (EROFS) | ro_mount_refuses_writes_with_erofs |
| 6 | write outside every grant under an rw mount | blocked (EPERM) | directory_scoped_mount_rw_works_and_sibling_denies |
| 7 | enumeration of a denied host directory | blocked (EPERM, nothing listed) | deny_all_cannot_enumerate_or_read_but_memfs_is_unaffected |
| 8 | reads/stats of a denied host file | blocked (EPERM, never ENOENT — the denial is a decision, not a miss) | deny_all_cannot_enumerate_or_read_but_memfs_is_unaffected |
| 9 | extract-all as an ungated host write | blocked (gated) | extract_all_is_a_gated_host_write |
| 10 | covered-but-not-held path under a / mount (the mount must not become a hole) | gated (the host decision runs) | covered_but_not_held_paths_fall_through_to_the_host_decision |
| 11 | image reads through the policy | gated | mount_family_reads_the_image_through_the_policy |
| 12 | unmount under a live policy | fail-closed | policy_survives_unmount_fail_closed |
| 13 | malformed policy spec | fail-closed (named) | policy_install_validates_its_arguments |
| 14 | argument-file grant: only the declared file, nothing beside it | blocked | tight_jail_allows_only_the_argument_file |
| 15 | packager/CI credentials reaching the payload: TEBAKO_GITHUB_TOKEN and every other packager-side TEBAKO_* variable past the handoff | blocked (blanked, never logged; env_pass is the explicit opt-in) | the_packager_token_is_scrubbed_and_the_contract_kept, the_env_pass_opt_in_carries_its_declared_names, the_factory_smoke_contract_survives_the_scrub (spec 03 §2.10, tebako#737) |
| 16 | Windows alternate data stream (file.txt:stream) on a denied base | PLANNED — the decision rides the base path (a stream suffix is not a path component), and the proof lands with the windows leg that can exercise it | — (named, not claimed) |
| 17 | statically-linked binary, or raw syscall(2) IO | OUT OF SCOPE — no interposition point; §5 states it in the manifest and the docs | §5 |
| 18 | fortify open family still uncovered (__open_2/__open64_2/__openat64_2) | OUT OF SCOPE — no importer observed in the shipped runtimes; the symbol list is the interposed surface's SSOT | §5 |
| 19 | the runtime EXE's own statically-linked stat/open definitions | OUT OF SCOPE today — gated only for the symbols the exe defines (spec 22 §2); follow-up wiring lives in the runtime factory | §5 |
| 20 | a payload's own sockets (network confinement) | blocked (EPERM) from the 2026-11-07 amendment — the §1 net: grant + the preload's socket family (connect/sendto/sendmsg judged, getaddrinfo observed for the name bridge; DNS itself never gated); a connect to an ungranted peer is the policy's named refusal | net::tests::deny_judges_by_numeric_and_observed_name, net::tests::ipv6_peers_judge_by_observed_name, policy::tests::net_check_denies_only_under_deny_and_matches_port, policy::tests::jail_spec_parses_net_grants + net_grants_env_round_trip, needs::tests::network_lines_draft_peer_entries_preferring_the_name |
| 21 | a jailed payload opening a listener (inbound service: bind/listen/accept) | OUT OF SCOPE in v1 — the axis judges OUTBOUND peers; inbound confinement is a later layer, named here so nobody reads the axis as bidirectional | §5 |
| 22 | an unplanned spawned HOST child (ruby's IO.popen(["cat", secret])) reading what the policy denies the parent | blocked — POSIX by the inherited preload tier (the exec target and the child's own reads are both judged); windows by the fail-closed spawn boundary (§5): under any non-trivial policy the spawn itself is refused. The end-to-end windows leg rides the runtime-side patch (tebako#1021; the conformance suite's shellout line carries a named KNOWN-GAP until a published runtime pair calls the export) | spawn_host_permitted_is_the_platform_spawn_boundary, policy::tests::trivially_open_is_exactly_the_unauthored_open_default, the contract C harness's spawn_host_permitted=1 line |
| 23 | a fork bomb under a declared processes bound | bounded — fork fails EAGAIN at the RLIMIT_NPROC ceiling; the bomb dies by name at the bound and the watchdog reaps its sleeper children with the root (§2.2's die-with-root) | the conformance suite's resource arm (ci/jail-conformance.sh — POSIX, --pair); resources::tests (the rlimit mapping + the syscall-level fork probes) |
| 24 | an infinite-looper under a declared wall_seconds bound | killed at the bound — the watchdog's named stderr line, the event=jail-resource journal line, the process group's SIGKILL; the observed exit is the signal | the conformance suite's wall arm; resources::tests::the_watchdog_kills_the_group_at_the_deadline |
| 25 | an infinite-looper under a declared cpu_seconds bound | SIGXCPU death at the RLIMIT_CPU ceiling | the conformance suite's cpu arm; the resources::tests rlimit mapping |
| 26 | an under-bounds control run (generous cpu_seconds/memory/processes/wall_seconds declared, nothing stressed) | passes byte-identically to the unbounded run — the axis never perturbs an in-budget payload (the memory declaration rides on Linux only; macOS omits it — the kernel's RLIMIT_AS floor, §2.2) | the conformance suite's control arm |
| 27 | windows resource enforcement | SHIPPED (2026-11-23, tebako#1101) — Job Objects (§2.2): PROCESS_TIME / PROCESS_MEMORY / ACTIVE_PROCESS (+ KILL_ON_JOB_CLOSE when the wall arms), the watchdog thread's exit-137 wall verdict, the kernel's close-at-exit reap; the fail-closed stub is gone | the conformance suite's windows resource arm (ci/jail-conformance.sh — windows, --pair); resources::tests (the job-limit mapping, the shared deadline algebra) |
| 28 | the preload-only delivery (tfs exec) of the resource axis | PLANNED — the preload constructor is the named seam; today the tfs exec surfaces refuse a resources:-carrying spec by name, and a driver-rooted bounded tree's native children are kernel-inherited-bounded (§2.2) | §2.2 |
| 29 | a payload calling setsid(2) to escape the wall group | OUT OF SCOPE — POSIX userland without cgroups cannot hold a determined escapee (the escape needs the payload's own syscall); cgroup-grade per-tree accounting is the named non-goal (§5) | §2.2 |
| 30 | a declared memory bound on macOS | refused by name at boot (exit 73) — the kernel refuses RLIMIT_AS below its 2^39-byte address-space floor (arm64); never a silent clamp | the conformance suite's macOS memory-refusal arm; resources::tests' rlimit mapping |
| 31 | a memory hog under a declared memory bound (Linux) | address-space growth fails at the RLIMIT_AS ceiling — the interpreter's own allocator answer (ruby: NoMemoryError, or its fatal-allocation abort), never a silent overshoot | the conformance suite's Linux memory arm |
Row 16 is the one open vector that is IN scope and not yet proven: it is named here so nobody reads the matrix as "done", and it does not close until a windows test stands behind it. Row 28 names the resource axis's remaining open arm the same way — the axis ships driver-first (POSIX and windows) and says so.
TBK SPEC 04 — References and registries (L3)
Normative specification of how payloads are named, located, and listed. Status: syntax LOCKED (multi-artifact + repo/release-class rules locked 2026-07-26); resolver + registry listing + tebako install SHIPPED (roadmap 07/28.1); tebako publish SHIPPED (roadmap 41 — GitHub releases + file:// mirrors; the GitLab/Bitbucket write legs and the brew/install.sh channels remain PLANNED).
1. The reference syntax (MECE, no default service)
One scheme family; the adapter is explicit in the scheme, never inferred:
SERVICE adapters (the service's ARTIFACT storage — never the git tree):
tfs:github:owner/repo:version[#artifact] → GitHub releases API
tfs:gitlab:owner/repo:version[#artifact] → GitLab releases/packages API
tfs:bb:owner/repo:version[#artifact] → Bitbucket downloads API
PROTOCOL adapters:
tfs+git://host/owner/repo.git@<ref>#<path-in-repo>
(the GIT SOURCE — any host incl. github/gitlab/bitbucket, LFS-aware;
#path selects the file when a repo holds many images; optional when
the repo IS the registry)
tfs+https://cdn.example.com/tool.tfs → verbatim fetch
LOCAL:
file:///opt/images/tool.tfs
DIGEST PIN (any class, query form — never clashes with #artifact/#path):
...?sha256=<hex>
Repo vs releases is a class distinction, never a flag. The git tree is addressed ONLY by tfs+git:; release artifacts ONLY by tfs:<service>:. Both are supported by design — a service form never means "the repo", a git form never means "the release".
Multi-artifact releases (locked — no magic):
#artifact-name selects one artifact within the release (same # convention as #path-in-repo).
No #: the candidate class is .tfs images. Exactly ONE candidate → used (there is no choice to guess). ZERO → AssetNotFound. MORE THAN ONE → AmbiguousAssets naming every candidate so the user re-runs with #name. The adapter NEVER auto-picks by host triplet — platform selection is the registry's declarative job (§2).
Dispatch rule (deterministic, exactly one home per reference):
| scheme | adapter |
|---|---|
| tfs:github: / tfs:gitlab: / tfs:bb: | that service's releases API |
| tfs+github:// / tfs+gitlab:// (spec 37 §4) | that host's releases API (GHE / self-hosted) |
| tfs+git: | git protocol adapter |
| tfs+oci:// (spec 38 §2) | the OCI Distribution registry |
| tfs+https: (or bare http(s)) | http fetch |
| file:// | local file |
| tfs+bb:// / tfs+bitbucket:// (Data Center) | the named UnsupportedService refusal — never a guess |
| tfs+git+ssh:// | the named SshTransportUnsupported refusal |
| anything else | named error listing the classes |
There is NO default service or namespace anywhere: every reference is fully explicit. (Superseded forms — tfs://github.com/owner/repo:version and any host-inferred shorthand — are rejected, never guessed.)
Manifest requires entries (spec 03) resolve through {ref, constraint, mount}.
2. The registry (developer-hosted, zero central infrastructure)
A registry is ANY git host repo carrying tpkg-registry.yaml. The git host's releases ARE the storage — no server to run.
Registry resolution (locked): tfs:<service>:owner/repo (no version) resolves the registry file from the repo's DEFAULT-BRANCH ROOT; the pinned-immutable form tfs:<service>:owner/repo:version#tpkg-registry.yaml reads it as a release artifact (versioned with its payloads); tfs+git://…#path reads it from any git ref/path. No other locations, no search, no fallback chain — exactly one location per form. The default-branch form's TRANSPORT is a build-shape-and-credential selection, never a runtime fallback chain (tebako#980): with the git feature on and the read anonymous, the fetch rides the git protocol (push-fresh — refs move atomically at push, the raw-CDN staleness that rules out raw.githubusercontent.com does not exist — and spends no api.github.com budget, the 60 req/h wall that shared-egress machines hit); credentialed reads and the git-less bootstrap keep the service contents API (the authed budget is high and private registries answer nowhere else).
schema_version: 1
payloads:
- name: metanorma
kind: app
versions:
- version: 1.2.3
platforms: # per-triplet for native-ext apps;
x86_64-linux-gnu: # "universal" for pure-language
artifact: metanorma-1.2.3-linux-gnu-x86_64.tfs
sha256: "…"
aarch64-macos:
artifact: metanorma-1.2.3-macos-arm64.tfs
sha256: "…"
release: {ref: tfs:github:metanorma/metanorma:1.2.3}
signature: {keyid: "…", asc: "…"} # opt-in
runtime_requirement: {engine: ruby, constraint: "~> 3.3.0"}
entrypoints: [metanorma]
default: 1.2.3
Mirrors on the row (additive, shipped 2026-10-22; registry MINOR 10): a version entry, or one of its per-triplet platforms entries, may carry mirrors: — an ordered list of ordinary references naming other places that serve the SAME bytes. The row's sha256 remains the only anchor: the primary is tried first, each mirror afterwards, and every attempt is verified against that pin, so a mirror can only serve the same bytes or fail by name. The anchor is computed ONCE from the primary (the registry pin, else the primary's own ?sha256=): a mirror's own ref never replaces or weakens it. A single-locator row that fails keeps its own error class and wording; a chain that is exhausted fails with every attempted locator listed, carrying the most specific refusal class (a trust mismatch outranks plain unavailability). This does not soften the locked rule above: a REFERENCE still names exactly one location and there is still no resolver-side search; the list lives in the document the publisher authored, and it is read only after the primary fails. tebako registry validate names a mirror list on a universal row with no pin, a list on a per-triplet row at the version level, an empty list, and a mirror whose reference does not parse, as producer-gate violations.
The registry MIRRORS only resolution-relevant fields (spec 03 §4 tier 3) — the dispatcher resolves without downloading every payload.
The mirror's runtime_requirement.abi rule (additive, 2026-10-07, tebako#440): the abi is per-triplet by construction, so a version entry's mirrored requirement carries abi only when one value holds for the WHOLE entry (a universal row or a single-platform per-triplet row). A multi-platform per-triplet entry omits it — one platform's abi on an entry serving every triplet is wrong for every platform but one. The authoritative per-platform abi always lives in each slice's embedded manifest; dispatch reads it there, never from the mirror. tebako registry validate names a multi-platform row's abi a producer-gate violation (2026-10-08) — the reader stays lenient so already-published registries keep resolving.
The per-triplet runtime abi line (additive, registry MINOR 11, tebako#1047): a platforms[<triplet>] entry of a kind: runtime row may carry abi: — the platform line THAT row's artifact was built against (arm64-darwin-24), stamped by the factory from its own manifest at publish (SSOT flows from the factory; the registry renderer never hand-writes it). This is the runtime-side half of the abi contract: the payload's runtime_requirement.abi says what it needs, the runtime row's platforms[<triplet>].abi says what the artifact IS, and the download pick excludes a non-matching row BEFORE any byte moves (spec 05 §5). An absent key is unknown, never excluded — pre-MINOR-11 rows stay eligible and the post-download check remains the backstop; a platforms: universal row carries no per-triplet entries, so the filter cannot evaluate there either. Present but empty is a named producer-gate violation.
The variant dimension (additive, 2026-10-09, tebako#557; spec 28 §2–§3): a version entry carries EITHER the shorthand above (top-level platforms: + runtime_requirement: — exactly the single-variant form) OR variants: — a list of {runtime_requirement, platforms} arms, one per (runtime_requirement × platforms) build of the same version — never both. Each variant is keyed by its requirement alone (the variant id derives, spec 28 §2); a duplicate key inside one version, both forms at once, or a default_variant: (payload level) naming no variant of the default version are named registry validation errors. With no selector in force, resolution picks the declared default_variant, else the variant whose requirement's line is newest (spec 28 §4 rule 1). Pre-variant readers see a variants-only entry as a version with no top-level platforms: and refuse it loudly — a clean break, never a mis-resolution.
The per-row shard release.ref (additive, 2026-10-07, tebako#711): a platforms[<triplet>] entry may carry its own release: {ref: …} naming the shard release tag serving THAT row's bytes. A version line that unions rows from several per-platform shard tags (the runtime factory's shape) cannot name the serving tag at the version level — the row carries it. The same grammar discipline as the version-level ref under per-triplet platforms applies (no #artifact, no ?sha256= pin, a service release); MINOR-6 readers prefer the row's ref over the version-level one, pre-MINOR-6 readers ignore the key (the version-level ref must then name a tag serving every row — the pre-shard shape).
The head signing: block (additive, 2026-10-07, tebako#617): the registry's signing-key self-description (spec 09 §9.1) — key: (armored OpenPGP public key), fingerprint: (the key's own primary, 40 hex), optional url: (https cross-check). tebako add-registry verifies the block against its own key, then TOFU-pins it (prompt, or --expect-fingerprint unattended); pre-MINOR-7 readers ignore the block.
status: withdrawn (additive, 2026-09-12, roadmap 85): the entry is YANKED — resolvers refuse it with a named WithdrawnPayload error (never a silent skip, never a fallback to it), and listing surfaces render it as withdrawn. Release assets are immutable (spec 13 §2a's immutability rule): withdrawal is the ONLY remedy for a bad published artifact, and the fix ships as a new version line.
Host-triplet selection happens HERE, declaratively: the dispatcher reads platforms[host_triplet].artifact (or universal), fetches THAT artifact from the named release. Never adapter-side guessing.
Concrete rows only (locked 2026-08-25, tebako#460). A version carries a universal: row OR per-triplet rows — never patterns (linux-*-* is rejected at validation), never both. Identical bytes under multiple rows dedup naturally (content-addressed cache). A composition's platforms: assertion (spec 23 §13.3) CONSTRAINS the mirrored coverage — checked fail-closed against it — and NEVER extends it.
kind: runtime entries are edge-discoverable (schema MINOR 1; SHIPPED 2026-09-25, spec 37 §8): the entry carries engine: (+ optional implementation:), and a payload's kind: runtime DEPENDS edge (spec 30 §1) discovers it by (engine, implementation?, constraint); the matched version's release.ref derives the download base (spec 05 §2's per-engine chain, the zero-config path for third-party runtimes). Runtime entries predating MINOR 1 carry no engine: and stay invisible to edges. The payload-level spelling is the one authored grammar (2026-10-08, tebako#549, MINOR 8): the version-level implementation: remains a compat READ (MINOR 2 — already-published registries keep resolving) but is never authored anew, and a version-level engine: parses to nothing; tebako registry validate names the old spelling, a mix of both spellings, and the misplaced engine: key as producer-gate violations, so a registry PR fails its own CI leg instead of publishing a decorative axis.
Bundle-era runtime rows name the bundle (additive, 2026-09-24, spec 36): platforms[<triplet>].artifact is <stem>.tar.gz and the row's sha256 pins the bundle, whose members unpack into the runtime store (spec 36 §4). Per-file-era rows keep naming the exe — the mirror is faithful to what the pinned release serves, era by era, and status: withdrawn means the same on both.
tebako add-registry <ref> registers one; shipped config has ZERO registries (explicit only — spec 16).
Install = resolve the registry → select the host entry → download → verify (sha256 and/or OpenPGP signature, spec 09) → content-addressed cache (~/.tebako/payloads/<name>/<version>.tfs) → register shims (spec 07). An install whose selected entry is kind: runtime refuses BEFORE any download (2026-10-07, tebako#672): the named RuntimeKindNotInstallable error (exit 65) points at the working paths — tebako install <the app that needs it> (its runtime_requirement resolves the runtime) or tebako use --runtime <engine>@<langver>[:<tebako>]. Runtimes flow through the runtime cache, never the payload store.
A developer's release flow: press → sign → upload payloads → commit tpkg-registry.yaml (a tebako publish helper later; manual first).
3. Fetch discipline
In-process HTTP only (spec 01): ureq + rustls + webpki-roots bundled; OS roots opt-in via TEBAKO_TLS_PLATFORM_ROOTS; file:// mirrors for tests and air-gapped sites.
Git protocol via gix (gitoxide) when tfs+git: needs smart-protocol fetch — never the git CLI.
The capability is per-binary, not per-ecosystem. The shipped tebako-bootstrap (the 3 MiB-gated loader) links tebako-resolve with the git feature OFF: tfs+git: lock sources fail closed with the named GitAdapterDisabled error (steer to managed mode — tebako install / the shim — or mirror to tfs+https:). The toolchain (tebako CLI, tebako-shim, tfs CLI) always carries the full surface. General rule: an optional capability is a cargo feature on the owning crate — default ON for the toolchain, OFF for the bootstrap, named error when compiled out.
Atomic fetch: download to tmp, verify digest, rename; concurrent fetchers coordinate via the cache lock (spec 05); a partial fetch is invisible. TEBAKO_OFFLINE=1: cache hit or hard error.
Private GitHub repos (2026-09-15 amendment): with TEBAKO_GITHUB_TOKEN/GITHUB_TOKEN ambient, the GitHub adapter resolves assets to their API URL (/repos/{o}/{r}/releases/assets/{id}) instead of browser_download_url — private repos answer 404 on the anonymous browser URL. The fetch requirements the choice implies are declared ON the asset descriptor the adapter returns (accept — the API serves JSON metadata without application/octet-stream; authenticate — credential-eligibility), never inferred from URL text downstream; the bearer rides api.github.com ONLY (never the browser or CDN hosts, never a redirect target). Anonymous transports keep the browser URL: the CDN path spends no API rate budget and carries no credential. A private asset with NO token is the ordinary named NotFound, never a fallback chain.
Digest mismatch → the named sha error (exit 70); nothing enters the cache.
3a. Run-time payload resolution grammar (tebako#460)
The L2 package manifest's resolution rows carry the SAME reference grammar as §1 plus the press-locked pin: ref (the registry/source reference), version (the locked concrete version), and sha256 (the locked digest). Run-time resolution consumes the locked pair ONLY — the ref locates, the digest decides; a version resolved fresh that disagrees with the lock is the trust-error class, never a silent swap. Registries, offline mode, and the fetch discipline (§3) are identical with the runtime's own chain.
4. Enterprise networking — proxies and trust anchors (2026-09-06 amendment)
Every fetch the loader or the toolchain makes rides ONE client (tebako-http::build_agent); the policy below is resolved once per process from the environment merged over the network: section of ~/.tebako/config.yaml — env wins per key — and installed before the first request (agent construction caches the transport). The resolution is journaled (event=network-config …) with proxy credentials REDACTED (http://***@host:port). There is no verify-off spelling, and there never will be.
Proxy.
Env: HTTPS_PROXY / HTTP_PROXY / ALL_PROXY / NO_PROXY (both cases), the de-facto grammar: comma list, suffix match, *; localhost is always direct. Config mirror: network.proxy: <url>.
Precedence: env → config → direct. Credentials ride the URL (http://user:pass@host:port) — the only auth spelling.
HTTPS rides CONNECT through the proxy; TLS terminates at the TARGET. An inspecting proxy re-encrypts — that is what the trust half below is for.
Named errors, never a silent fallback: ProxyUrlInvalid, ProxySchemeUnsupported (no SOCKS), ProxyAuthRequired (a 407 the URL's credentials did not satisfy). Configuration errors are deterministic: retry loops return them immediately, never as IndexUnavailable, never retried.
Trust anchors — three spellings, all fail-closed:
webpki (default, unchanged): the bundled Mozilla roots.
platform: the OS store (GPO/MDM-pushed enterprise roots) — env TEBAKO_TLS_PLATFORM_ROOTS (since v2.0.0) or network.tls_roots: platform.
Additive: network.extra_ca: [<pem>…] / TEBAKO_EXTRA_CA (os-path-list separator) — the PEMs parse at client build INTO the bundled store (never instead of it). Combining platform with extra_ca is the named ExtraCaWithPlatformRoots error (the OS verifier trusts exactly the OS store — push the CA there instead). A malformed or unreadable PEM is ExtraCaMalformed / ExtraCaUnreadable at startup — never a silently skipped file.
The eMudhra distrust policy (2026-10 amendment). eMudhra's intermediate CA private keys were generated with recoverable entropy (one key is literally the integer 4). tebako excludes the CA outright from every trust set this stack assembles:
| Assembled set | Owner | Distrust effect |
|---|---|---|
| bundled Mozilla roots (webpki / default) | tebako-http distrust | every eMudhra/emSign root is dropped before install; RootCerts::WebPki is never used (it would bypass the filter) |
| additive extra_ca PEMs | tebako-http netconfig | a file carrying a distrusted cert is the named ExtraCaDistrusted — never a silent drop |
| operator CA store ($TEBAKO_HOME/trust/ca) | tebako-driver materialize | a store file carrying a distrusted cert is a named 65 naming tebako trust remove |
| driver platform enumeration (merged runtime bundle) | tebako-driver materialize | every distrusted DER is dropped before the merge; the drop is debug-journaled; a store that reduces to zero is a named 65 |
Identity is lexical over the certificate DER (subject/issuer DN markers eMudhra / emSign, case-insensitive) — it survives re-issues, cross-signs, and the Microsoft-only emSign Root TLS/CS CA - G3 pair. The compromised intermediates (including the AAA-cross-signed ones) are additionally blocked at verification time by rustls-webpki ≥ 0.103.16's SPKI blocklist; the bundled-root floors are webpki-root-certs / webpki-roots ≥ 1.0.10 (which drop emSign ECC Root CA - G3 upstream). Platform mode trusts the OS store as-is at the TLS verifier (the OS owns its own distrust); the driver still filters the enumerated blocks it merges into a runtime bundle.
Capability gating (§3's general rule applied): network is a cargo feature on tebako-http — default ON for the toolchain, OFF for the size-gated bootstrap. Compiled out, a set proxy env or TEBAKO_EXTRA_CA fails closed with the named NetworkingCompiledOut error identifying the variable; the bootstrap never silently ignores a policy the operator asked for. TEBAKO_TLS_PLATFORM_ROOTS is NOT part of the feature — the platform-verifier opt-in shipped in v2.0.0 and stays always-on in every build, bootstrap included. The config mirror is read by the toolchain (shim / CLI) at startup; the size-gated bootstrap reads env policy only — enterprise fleets push policy as system env (GPO/MDM), which both channels honor.
# ~/.tebako/config.yaml — every key optional; env wins per key
network:
proxy: http://user:pass@proxy.corp:3128 # CONNECT proxy
tls_roots: platform # default: webpki
extra_ca: [/etc/pki/corp-root.pem] # additive; not with platform
The payload side (a packaged Ruby/Python process making its OWN TLS connections) is out of the loader's scope: it rides the runtime's SSL_CERT_FILE semantics — spec 22 §4.
TBK SPEC 09 — Trust and signing (authentication)
Normative specification of integrity and authenticity for every binary part: bootstrap, runtime payloads, data payloads, and release indexes. Status: signing machinery SHIPPED (M29 phase 2); the classical root key ceremony EXECUTED 2026-09-09 (§7); release signing SHIPPED — each platform leg's publish invocation signs its own released parts and index shards behind TEBAKO_RELEASE_SIGNING_ENABLED (§6; the finalize-pass sign step was retired by spec 13 §2a's de-rendezvous, 2026-09-12). Runtime FETCH-TIME verification (§4's resolve-path point, §5's signed index forms, spec 13 §2a's per-artifact signature) is SHIPPED in the CLI's press-time resolver and the shim's dispatch-time fetch (roadmap 80/G1, tebako#567's chain); the bootstrap's first-run runtime download is the remaining leg (PLANNED — until it lands, the bootstrap verifies sha256 only and never reads signature declarations: the pre-G1 behavior, landing together with the openpgp-verify capability flip of the rollout note below). Payload verification (§4's install-time point, extended 2026-09-13 to the press-time compose-closure and spawn-walk payload fetches) is SHIPPED; the store-side anchor stays the .sha256 sidecar.
Rollout phase — unverified-first (roadmap 72). The shipped tebako-bootstrap is built WITHOUT OpenPGP verification (the openpgp-verify cargo feature is off): signed packages execute with a loud UNVERIFIED warning + audit journal, unsigned packages with the legacy warning; TEBAKO_REQUIRE_SIGNED=1 fails closed (exit 71) because a strict-mode request must never silently downgrade. OpenPGP verification returns via the crypto toolkit payload (tebako-crypto, rnp+botan full+PQC, fetched on demand and Ed25519-verified by the bootstrap) — this spec is the TARGET model; the phase-1 deltas live in spec 06 §3.
1. Threat model
Parts travel over mirrors/CDN and are shared between machines. HTTPS + sha256 against a same-channel manifest protects the TRANSPORT, not the OBJECT: whoever swaps the artifact swaps the manifest too. The tpkg crc32 is integrity-vs-accident only — documented as non-authentic (spec 02 §2). For the relationship to the OS-level trust gates (Gatekeeper, Authenticode) — who validates the bootstrap versus what tebako validates below it — see spec 12 §5.
2. The chain of trust
Root of trust: the tamatebako release signing keypair (OpenPGP via rnp-rs — the ONE signature mechanism for trailers, manifests, and release indexes alike: one keyring, one verify path). Root fingerprint published on tebako.org AND embedded in the loader/CLI at release time (EMBEDDED_ROOT_FINGERPRINT; dev override TEBAKO_TRUSTED_ROOT). The CLI additionally embeds the root PUBLIC KEY (tebako_signer::ROOT_PUBLIC_KEY, byte-identical with https://www.tebako.org/.well-known/tebako-key.asc), so first-party signature verification needs no key distribution at all (§9's zero-interaction rule); the size-gated bootstrap stays fingerprint-only, the public key reaching its keyrings through the normal channels.
Production (releases): every released part (runtime payloads, bootstrap, src tarballs, libraries) ships a detached .asc per artifact PLUS a signed release manifest — one verify path for all.
Packages: the tpkg v2 extension (spec 02 §4) carries per-slot SHA-256 + signer keyid + the OpenPGP signature over the canonical trailer bytes.
Rotation: a signed successor-key statement (TEBAKO-ROOT-SUCCESSOR-V1 — canonical lines binding predecessor → successor fingerprint, detached signature from the predecessor) lets any machine forward trust with no out-of-band step: the loader applies the statement chain from a trusted root and TOFU-registers the successor. Revocation procedure documented and rehearsed.
3. Opt-in rules (locked)
Signing is per-package opt-in: tebako-pkg bundle --sign[=keyid]. Without it the package is plain v1, byte-identical to pre-signing — no key, no prompt, no ceremony. A press-local key is generated and cached under $TEBAKO_HOME/keys only on the first explicit --sign.
Rewrite operations (insert-image/remove-image/set-runtime/reassemble) preserve the input's signing state.
Only the presence of a signature is optional — verification of signed packages is always strict (exits 71/72, spec 06 §4).
v1-legacy rule: unsigned v1 packages exist in the wild and stay runnable — accepted as LEGACY with a loud stderr warning on first acceptance per machine (marker $TEBAKO_HOME/warned-legacy/<sha256(path|size|mtime)>; a re-pressed or replaced binary warns again) plus an audit-journal entry on every acceptance (tebako#400: the per-run repetition was unactionable noise; the durable remedy is tebako press --sign — v2-signed trailers never warn). A package whose developer declared quiet_notices (spec 23 §14) carries TPKG_FLAG_QUIET_NOTICES (bit 3) and suppresses this warning and the spec 06 §5 progress lines on every run — the bit rides inside the signed region, so it cannot be forged onto a signed package, and the journal entry is written regardless. TEBAKO_REQUIRE_SIGNED=1 is the explicit opt-in hard-fail for hardened environments — never the default; it is checked FIRST and outranks the quiet bit.
Fail closed everywhere: no insecure-skip flag.
Encryption is likewise per-image opt-in (spec 10).
4. Verification points
Press time: the CLI verifies release signatures before using any part (fail closed). Trusted keyring in $TEBAKO_HOME; our root key embedded (the fingerprint in the loader, the full public key in the CLI); additional keys TOFU-registered with a named prompt. The point covers every part a press CONSUMES: the runtime pair (the runtime-fetch point's press leg, above) and every registry payload the compose closure (spec 23 §13) or the spawn walk (spec 23 §13.6, spec 32 §6) fetches — a declared signature verifies BEFORE the bytes enter the payload cache and before the press pins their digest into the lock, so a tampered slice can never be laundered into a lock pin that downstream installs and runs then trust. The matrix is the install-time point's, unchanged: signed verifies strict (71 invalid / 72 untrusted / 72 signer-key-changed); unsigned warns loud + journals (event=legacy-unsigned-accepted) and fails closed (71) under TEBAKO_REQUIRE_SIGNED=1; a cache hit stands on its trust anchor (spec 05 §4 — verified when the bytes entered, never re-verified per use). This is spec 23 §13.4's trust uniformity made literal: carried and shared slices pass the same gate at the same moment.
Install time: registry-pinned payload signatures verify against the trusted keyring PLUS the embedded root public key — a tamatebako-signed payload verifies Trusted on a fresh machine, no registration step.
Runtime fetch (resolve time — the per-binary fetch paths: the shim's dispatch-time download and the CLI's press-time resolver SHIPPED (roadmap 80/G1); the bootstrap's runtime download is the remaining leg, PLANNED): the resolver verifies the consumed index form's detached signature (§5) BEFORE trusting its digests, then verifies each fetched artifact whose entry declares signature (spec 13 §2a) — always strict: an invalid signature → exit 71; a signer keyid whose primary is not in the trusted keyring → exit 72; a declared .asc that does not fetch → exit 71 (a signing declaration without its signature asset is an invalid signing state, never a skip). The sha256 check then runs as today (exit 70). An entry with NO signature anywhere (a pre-signing release line — those releases are keep-forever, spec 13 §8) is accepted with a loud stderr warning + audit journal (event=unsigned-runtime-fetch) on every fetch — the download moment IS the trust decision here (§9's two-models rule) — and refused with exit 71 under TEBAKO_REQUIRE_SIGNED=1. A bootstrap built without openpgp-verify treats declared runtime signatures exactly as it treats signed trailers (spec 06 §3): loud UNVERIFIED warning + journal, sha256 enforced as integrity-only, exit 71 under TEBAKO_REQUIRE_SIGNED=1 naming the missing capability. The store markers keep their spec 05 §4 semantics — verification happens at fetch/install, never per run.
First run: the loader verifies the trailer signature against the keyring, then each slot's sha256 before mounting/extracting (streaming, one pass at install time; the trust-anchor marker avoids re-hashing every run — spec 05 §4).
Runtime driver: re-verifies an image's sha256 against the trailer before mount (integrity; authenticity already established by the trailer signature).
5. Release index authentication
Every index form a resolver can consume ships a detached .asc from the factory's release key, and the resolver verifies the signature of the form it consumed BEFORE trusting its hashes — closing the gap where a MITM swaps both package and unsigned manifest. Same keyring, same verify path. Per runtime factory release (spec 13 §2a): each per-package shard <stem>.manifest.json ships <stem>.manifest.json.asc (the sidecar-era authority is signed first), every per-asset <asset>.sha256 sidecar ships <asset>.sha256.asc, and every payload asset (the interpreter exe, the env image, a windows dll) ships its own <asset>.asc. No artifact is ever "covered by" another artifact's signature (2026-09-12, roadmap 85): every served name carries its own .asc on signing-enabled lines, signed by the invocation holding the fresh bytes. Bundle-era lines (additive, 2026-09-24, spec 36) keep the rule exactly: the served names are the bundle, its sidecar, and the shard — three .ascs per leg — and the bundle's MEMBERS are not served names; their authenticity flows from the signed shard's per-member pins verified post-unpack (spec 36 §4), never from an assumption about the container. The monoliths are never release assets (spec 13 §2a's de-rendezvous), so no manifest.json.asc / SHA256SUMS.txt.asc exist on a release; a consumer-side derived index verifies by re-derivation from the signed shards. The entry's signature: {keyid, asc} fields name the per-artifact sidecars — the same SSOT rule as filename: the factory declares the spellings, consumers flow them verbatim and never synthesize. keyid names the signer's PRIMARY keyid (§9's primary-vs-subkey rule). All of it is additive: pre-signing releases carry none of it and stay installable under §4's unsigned-fetch rule (keep-forever, spec 13 §8); a release that declares a signature for an artifact MUST ship that .asc — a declaration without its signature asset is an invalid signing state (§4: exit 71 at fetch, and the factory's publish fails before that, spec 13 §2a).
6. Tooling
tebako-pkg sign (detached .asc per artifact + signed SHA256SUMS) and tebako-pkg verify (Trusted/Untrusted/Invalid per artifact). Factory release flows invoke tebako-pkg sign in CI (secrets-held armored root export; the private key never leaves CI secrets/hardware).
7. Ceremony status (roadmap 10)
The production root key ceremony was executed 2026-09-09: the classical Ed25519 root 9E210CA8E9FDE9E6587740B2EFC3C250F7862A48 exists in the offline store, EMBEDDED_ROOT_FINGERPRINT is filled, the fingerprint and public key are published on tebako.org (the trust-anchor page and /.well-known/tebako-key.asc), the CI secrets are wired (the finalize job signs releases behind TEBAKO_RELEASE_SIGNING_ENABLED), and the sign/verify drill was rehearsed against a released tebako-pkg before go-live (trusted and tamper-invalid both proven).
Recorded deviations from the docs/root-ceremony.md runbook (roadmap 36), each with its follow-up: no PQC root and no pre-made successor statement yet (the rnp line in use lacks ML-DSA — lands with the tebako-crypto toolkit, roadmap 72); the CI signing-subkey export is unprotected (tebako-signer passphrase-unlock follow-up); software storage in place of hardware tokens; the encryption subkey is X25519 in place of day-one ML-KEM; the revocation certificate is the tool-generated self-revocation. The full deviation record lives with the offline key store.
8. Revocation (locked 2026-07-27)
Rotation (successor statement) moves trust forward; REVOCATION kills a key with no successor — for compromise or retirement:
-----BEGIN TEBAKO REVOCATION STATEMENT-----
format: TEBAKO-ROOT-REVOCATION-V1
fingerprint: <40-hex revoked root>
created: <unix seconds>
reason: compromise | retired | superseded
-----BEGIN PGP SIGNATURE-----
<detached signature from the REVOKED key itself (self-revocation)
— or from the surviving PREDECESSOR root in a chain>
A self-revocation is proof of possession; a predecessor-signed revocation covers a lost key (the predecessor authorized the chain).
Consumers apply revocations from the successors dir alongside rotation statements: a revoked fingerprint is rejected even if it previously verified (fail-closed, named RevokedKey → exit 72).
Revocations are additive files (<fingerprint>.revoke.asc), never edited history; the audit journal records every application.
The ceremony doc (roadmap 36) includes rehearsing this once.
9. Third-party identity and key distribution
First-party slices verify against the embedded tamatebako root (§2). Third-party authors are not tamatebako; their slices and fat/slim binaries verify against THEIR OWN keys, and the question that decides everything is how a user's machine learns the right fingerprint. The method is the three-channel pattern — no channel alone is trusted, two channels agreeing are the trust event:
The registry (location-as-identity, primary channel). A registry ref pins an authenticated location (tfs:github:metanorma/metanorma is GitHub's guarantee that this is the metanorma org). The registry index carries a signing: block at its head: armored public key, fingerprint, and an optional canonical key URL. tebako add-registry fetches the index, verifies the block's key IS its declared fingerprint (an inconsistent block is the registry's malformation, exit 65 — never a trust question), displays the fingerprint and the cross-check URLs, and asks for confirmation (TOFU). On confirmation the key is pinned to $TEBAKO_HOME/trust/<FINGERPRINT>.pub and the registry's config book entry records the fingerprint (signing_fingerprint:) so re-adds short-circuit and tebako keys list shows the binding [shipped — tebako#617]. An already-trusted key (embedded root, keyring, an earlier pin) asks nothing. Non-interactive flows supply the expected fingerprint out of band via --expect-fingerprint <hex> — never a blind yes; a mismatch is the trust class (exit 72) printing both fingerprints.
Out-of-band confirmation (second channel, never auto-trusted). Authors publish the same fingerprint where their audience already trusts them: https://<author-domain>/.well-known/tebako-key.asc (the well-known convention), their docs/README, and for GitHub-hosted projects the org's .github repository (zero new infrastructure). The CLI prints these URLs for the user to compare; it never upgrades trust from the second channel silently.
Fingerprint-addressed directories (no trust needed). OpenPGP keyservers are used as directories: fetch BY fingerprint, authenticate the fetched key against the channels above. A swapped key has the wrong fingerprint by construction, so the directory itself needs no trust.
Continuity is the security property. After the first confirmation, every artifact from that identity must verify against the pinned key. A key mismatch fails closed (SignerKeyChanged, exit 72) and displays both fingerprints; a valid successor chain (§8 rotation) forwards automatically after displaying the chain proof, re-pinning the new key.
A signature pin names the PRIMARY keyid — the identity, not the instrument. A well-formed release key signs data with a signing SUBKEY (a certify-only primary never signs; the 2026-09-09 root is this shape), so the signature's issuer keyid is the subkey's, while the identity a registry pins is the primary's (its low 64 bits, 16 lowercase hex). Verification therefore resolves the verified issuer to its primary through the keyring before comparing (tebako_signer::primary_keyid_of); a pin naming the issuer subkey directly also matches (exact compare first). Consequence: rotating the signing SUBKEY under an unchanged primary never invalidates existing registry pins. Publishers pin the primary — tebako-pkg sign and tebako publish both report it (the sign line names the primary keyid; when a subkey did the signing, the issuer is reported alongside for transparency).
Per artifact class:
Registry index: verified against the pinned registry key on every refresh.
Payload slices: signed trailer verified against the author's pinned key; per-slot digests chain off it (§4).
Runtime slices (tamatebako): the embedded root — nothing to register.
Runtime slices (third-party — discovered through a registry's kind: runtime entry, spec 05 §2's registry-derived base): the publishing registry's pinned key — the channel that supplied the download base also anchors the key, so a third-party runtime adds no ceremony past the add-registry TOFU. The entry's signature.keyid must resolve to that pinned primary (mismatch → SignerKeyChanged, exit 72).
Third-party fat/slim binaries: verified at install/import against the pinned author key (the same verify path); the author may ALSO OS-codesign with their own Developer ID — Apple/Microsoft gates then vouch at execution time, orthogonally and complementarily (spec 12 §5).
The two distribution models decide what a warning is worth (tebako#400). Who made the trust decision, and when, differs by package shape — the notice policy follows from it:
Fat binary (bootstrap + payload downloaded as ONE artifact). The user's trust decision is explicit and happens ONCE, at download time — fetching the binary from a location they chose, like any binary download. A per-run signature warning on such a package is unactionable noise: the user cannot re-verify at run time what they already decided to fetch and run. The developer may therefore declaratively suppress it for every run of the package (quiet_notices, spec 23 §14 — shipped; the bit rides inside the signed region, and TEBAKO_REQUIRE_SIGNED=1 still outranks it).
Separately-resolved lean payloads. The package names its runtime and slices; the loader RESOLVES them at first run from whatever the registries serve at that moment. The download-time decision no longer covers the payload bytes — here the signature IS the trust mechanism (§4's verification points), and the warnings on unsigned resolutions stay justified and loud.
Press signing (shipped — tebako#400 S1). Signing stays per-package OPT-IN (§3): a press with no signing declaration on any channel produces the v1-unsigned trailer, byte-identical to pre-signing output, and never touches key material. The declaration rides the sign registry setting (spec 23 §14) through three channels, resolved CLI → env → compose document → default (unsigned) — auto-sign must never surprise:
tebako press --sign signs the produced package with the press-local key (generated and cached under $TEBAKO_HOME/keys on first explicit use, auto-registered into the local trusted keyring); --sign=<keyid> signs with the named secret key from $TEBAKO_HOME/keys — a keyid matching no key is a NAMED error raised before any heavy work, never a silent fallback to the default key.
TEBAKO_SIGN=1 is the machine-wide declaration and the compose document's sign: true the repo-carried one; both sign with the press-local key (a keyid is per-machine material and never rides a git-shared document).
--no-sign (or TEBAKO_SIGN=0) wins over every lower channel. An opt-out that overrides a lower channel's sign declaration is LOUD — a stderr warning plus an audit-journal entry (event=press-sign-opt-out) — because silently dropping an authored signature declaration would be a quiet trust downgrade (invariant 9).
Developer ergonomics (target UX; status in braces). tebako keygen creates a keypair in $TEBAKO_HOME/keys/ and prints the fingerprint with the exact text to paste into docs + the well-known location [partial: key creation exists]; tebako press --sign[=<keyid>] signs the produced package, with TEBAKO_SIGN / the compose sign: key as the machine-wide and repo-carried declarations and --no-sign as the loud opt-out [shipped]; tebako publish signs every artifact + the index and writes the signing: block into the registry index automatically [shipped in install-UX]; tebako key rotate creates + signs + publishes a successor statement in one command [planned]; revocation follows §8 [format locked].
User ergonomics. First-party: zero interaction, ever (embedded root — the CLI carries the root public key, so first-party artifacts verify Trusted on a fresh machine). Third-party: one informed consent per author (the TOFU prompt), then silent verification forever. tebako keys list|remove manage the signing-key trust inputs (the keyring and the add-registry pin store) [shipped — tebako#617; the trust verb family is the TLS CA store, spec 22 §4]; tebako doctor re-verifies installed artifacts against pinned keys [roadmap 50]. Unverified artifacts always produce the loud warning + journal (§3); TEBAKO_REQUIRE_SIGNED=1 refuses them outright.
10. Key retrieval from the trust-anchor channel (locked 2026-09-18)
A signed artifact whose pinned signature.keyid is absent from the local keyring used to be a dead end ("register the publisher's key, then retry"). For keys ON THE TAMATEBAKO ROOT CHAIN the machine can now close that gap itself: the pubkey is fetched from the trust-anchor publication (§2's tebako.org channel) and admitted ONLY through the chain — trust never extends silently, and never extends by TOFU.
The well-known grammar (the tebako.org publication owns these spellings; consumers flow them, never re-derive):
https://www.tebako.org/.well-known/tebako-keys/<keyid>.asc — the armored public key whose PRIMARY keyid (16 lowercase hex) is <keyid>. The root's own key answers here as well as at the legacy tebako-key.asc (which stays the human-facing spelling).
https://www.tebako.org/.well-known/tebako-successors/<predecessor-fingerprint>.asc — the TEBAKO-ROOT-SUCCESSOR-V1 statement (§2's rotation format) rotating FROM <predecessor-fingerprint> (40 uppercase hex).
The directory is a DIRECTORY (§9.3's keyserver rule): a fetched key authenticates by chaining, never by the channel that served it. TEBAKO_ANCHOR_BASE overrides the publication base (air-gapped mirrors, tests) — an AVAILABILITY knob, never a trust knob: admission still requires chaining to the embedded root.
The admission rule. A retrieved key is usable — for this verification and for registration into the trusted keyring — iff:
its primary fingerprint IS the embedded root (EMBEDDED_ROOT_FINGERPRINT / TEBAKO_TRUSTED_ROOT); or
it chains to a locally trusted root through verified successor statements: starting at the embedded root fingerprint, each hop fetches tebako-successors/<current>.asc and verifies the statement against the current root's key (the embedded public key, the trusted keyring, or a key retrieved and admitted earlier in the same walk); the walk ends at the retrieved key's fingerprint (admitted, basis = the verified path) or where no further statement exists (NOT admitted). The walk is bounded (8 hops) — a cycle is a dead end, not a hang; or
it is already in the trusted keyring (no fetch at all).
Anything else is the NAMED error KeyRetrievalFailed (exit 72, the trust-failure class): the message prints the retrieved key's fingerprint LOUDLY for out-of-band confirmation and names the manual path (tebako keys import <file>) — the same refusal shape as today, now with the fingerprint to compare. A tebako-keys URL that does not resolve (404) is the same named error class naming the URL.
Concurrency. Retrieval is a tiny independent fetch and runs CONCURRENT with the plan's artifact streams (spec 05 §6); an artifact's signature verification starts when both its bytes and its key are present. A retrieved-and-admitted key is registered into the trusted keyring (§2's rotation rule: the loader TOFU-registers a verified successor) so the next verification is local.
The audit journal records every retrieval: one row per event with the pinned keyid, the admitted fingerprint, the source URL, and the chain basis (embedded-root / successor:<path> / already-trusted) — trust events are exactly what the journal is for. Failed retrievals journal too (event=key-retrieval-failed).
TEBAKO_OFFLINE=1 skips retrieval entirely (no network): the verification keeps the pre-ceremony outcome — the pinned keyid is absent, the named untrusted-signer error (exit 72) stands.
TBK SPEC 10 — Encryption (confidentiality)
Normative specification of encrypted volumes: selective, in-memory-only decryption. Status: v1 SHIPPED (roadmap 37: EncBackend + tfs encrypt/decrypt/mount, SUITE-1; PQC suites, metadata hiding and merkle verify-on-read remain PLANNED). Encryption is per-image opt-in, never default.
1. Model
Encryption is a stacking transform like COW, not a format: EncBackend { base: dyn Backend, key_source } — reads decrypt on demand, in memory only; plaintext blocks never touch disk. Compose freely: Enc(COW(base)), COW(Enc(base)), nested encapsulated encrypted images. Per the transforms law (spec 00): EncBackend lives ONLY in the Rust TFS — backends and dwarfs-t stay ignorant of it.
Primitive: OpenPGP via rnp-rs (AES-256/SHA-2; botan backend). Encrypt AFTER compress (ciphertext doesn't compress; dwarfs blocks are individually compressed → individually encryptable). Optional padding to blur per-block sizes.
2. Key model (locked)
DEKs (data keys) encrypt content blocks. A DEK IS a persisted OpenPGP session key — rnp's native wrap/unwrap (PKESK packets to N recipients) is the envelope; no custom crypto anywhere.
Identity lives at the PLAINTEXT layer. Manifests carry TWO digests (spec 03 §2.1): the plaintext TREE hash (semantic identity — CAS addressing, dedup, sign/verify, audit-without-access) and the ciphertext blob hash (transport identity). Encryption is a per-audience transform; CAS never keys content-identity to any one wrapping.
Session keys are grant envelopes. Sharing = wrapping the DEK to a recipient (ephemeral ECDH per OpenPGP) — offline, accountless, auditable. A wrapped DEK + manifest digest IS a capability: possessing it grants exactly that subtree, nothing else.
Revocation is prospective: re-issue the manifest without the recipient (no new envelopes), or rotate the DEK for FUTURE versions (full re-encrypt, only on suspected DEK compromise). You cannot un-read what was read — documented honestly.
Hierarchical derivation: subtree keys derive from a root DEK via HKDF with the path as info — K(/a/b) grants /a/b/** but not /a/c or /a (one-way). Sharing a directory subtree = handing over its derived key. Layered composites: per-layer DEKs for coarse audiences, HKDF subtrees for fine-grained ones.
Composition rules: JOIN/squash of layers with different DEKs = authorized re-encryption under a new joined key, OR preserved per-layer key domains in the joined manifest (lazy join). Encapsulated images keep INDEPENDENT key domains — outer may be readable while inner stays sealed (transport vs payload audiences).
Selective disclosure: per-directory/per-layer recipient mapping in the manifest → ONE artifact, N audiences; each key opens only its slice.
Metadata hiding option: encrypt the metadata block as a unit — structure/filenames invisible until keyed.
3. Memory discipline
Decrypted blocks live in heap buffers that are mlock'd + zeroized on free. Keys via agent / passphrase / PKCS#11 hardware — never written to disk, never in swap. Confidential-computing memory (SGX/SEV/TDX) is a documented future tier, not v1.
4. Serving
Prefer ciphertext end-to-end (clients decrypt locally; the server/CDN never sees plaintext). Session wrapping per online client only when the server is trusted with keys. Block-access patterns leak regardless (PIR out of scope) — documented.
5. PQC readiness (locked)
Algorithm agility from day one: every manifest/envelope/signature carries a CIPHER-SUITE id from a versioned registry — nothing hardcoded. Unknown ids fail with a named error, never a guess.
SUITE-1 = X25519 + Ed25519 + AES-256-GCM + SHA-256 (classical).
SUITE-2 = HYBRID: ML-KEM-1024+X25519 composite KEM, ML-DSA-87+Ed25519 composite signatures, AES-256-GCM, SHA-384 — secure if EITHER family holds (the transition form).
SUITE-3 = SLH-DSA (hash-based signatures) maximal-conservatism tier.
HNDL: long-lived encrypted images SHOULD use hybrid envelopes NOW. AES-256 keeps ~128-bit post-Grover strength; the merkle/hash layer is PQC-safe by construction. Signatures are the migration surface, envelopes the confidentiality surface — both suite-versioned, so migration is additive.
Implementation path: botan 3 (rnp's backend) via rnp-rs PQC tracking + OpenPGP PQC drafts; recipients may hold classical AND PQC keys (multi-recipient envelopes are native).
6. Cyber/admin algebra (why this changes the game)
Object security > channel security: artifacts self-protect over ANY transport/mirror (untrusted CDN, USB, email).
Leak containment: disk snapshots/caches hold ciphertext only.
Crypto-shredding / kill-switch: destroy a data key (or re-issue the manifest without a recipient) → content unrecoverable everywhere, provably — no mirror-purge problem.
Immutable golden bases + auditable COW deltas (the overlay IS the change record) + signed provenance = compliance-grade fleet management.
Honest risks: access-pattern side channels on serve; key-agent UX is the hard part; mlock/zeroize is the baseline, not a panacea.
7. CLI surface (SHIPPED v1)
tfs encrypt / decrypt / mount --recipient / --key — encryption at image-creation time through the same Writer path; mount requires the recipient key; wrong key → named EKEY-class error, never garbage. SHIPPED (roadmap 37): tfs encrypt (root grant --recipient, subtree grants --subtree <path>=<pubkey>; --rewrap --key rotates grants to a new recipient set with the bulk ciphertext byte-identical), tfs decrypt (plaintext to a tar stream — never a staging tree), tfs mount --key (the unlock/grant report; FUSE/serve mounts remain spec-11 §6 PLANNED). tfs sign is spec 09's surface. The v1 crypto construction (per-block AES-256-GCM, HKDF-SHA256 subtree keys, PKESK DEK envelopes, the /__tpkg__/envelopes.yaml grant manifest) is documented normatively in crates/tfs/src/backends_enc.rs and crates/tpkg/src/envelope.rs.
4a. The wire format (normative — the byte layout an independent implementation must match)
Directory structure, names, symlink targets and the /__tpkg__/ metadata directory stay plaintext (metadata hiding is this spec's deferred option); every other regular file's CONTENT is replaced by its encrypted form:
offset size field
0 8 magic "tfsenc01"
8 8 u64le plaintext_size
16 — per block i (block = 4096 bytes; full-block slot 4112):
ciphertext_i (block_len bytes) || GCM tag_i (16 bytes)
Per block, AES-256-GCM with:
key = the file key FK(path) (below),
nonce = u32le(0) || u64le(block_index) (12 bytes) — unique per (key, block): file keys are unique per file, block indexes never repeat within a file, and images are immutable, so no (key, nonce) pair ever seals two different plaintexts. A CHANGED tree's re-encryption MUST rotate the DEK (§2's prospective rotation), which re-keys every nonce domain.
AAD = "tfsenc01" || u64le(plaintext_size) || u64le(block_index) — binds each block to its file size and position (blocks cannot be relocated, truncated away silently, or transplanted between files of different sizes).
Keys: one root DEK per image (32 random bytes), with HKDF-SHA256 path keys for selective disclosure (§2):
K("") = DEK (the image root key)
K(dir/name) = HKDF-SHA256(ikm = K(dir), salt = none,
info = "tfs-enc-1/dir\0" || name)
FK(dir/file) = HKDF-SHA256(ikm = K(dir), salt = none,
info = "tfs-enc-1/file\0" || name)One-way per level: K(/a/b) opens /a/b/** but not /a/c or /a. Sharing a subtree = wrapping THAT subtree's key to the recipient. The DEK (or a subtree key) is wrapped to recipients as OpenPGP PKESK packets and recorded in /__tpkg__/envelopes.yaml (tpkg's EnvelopeManifest); the payload manifest's encryption.parts reference grants by id and NEVER carry keys (spec 03 §2.1).
TBK SPEC 11 — TFS: the virtual filesystem layer
Normative specification of the userland VFS. Status: core SHIPPED (crates/tfs, contract suite 164 tests); tar adapter and the COW composite (HostDir overlay + whiteout journal, mount-mode flags) SHIPPED (roadmap 12/13); the ENC transform (spec 10, EncBackend) SHIPPED (roadmap 37); the fd-based write family PLANNED.
1. The model
TFS is a userland VFS over bulk-storage images — the kernel-VFS shape (vfs → fs drivers → block layer) with image-in-file (or in-binary region) replacing the block device. It is self-similar: images are files, any file is mountable (including files inside other mounts — §5), mounts compose and stack, and each process owns its namespace object (Plan 9 per-process namespaces, delivered as a library).
Product line: libtfs (the engine, tebako_fs_* C ABI — the Rust TFS is the shipping implementation) · tfs CLI (human-facing: tfs : libtfs :: sqlite3 : libsqlite3) · tebako-pkg (tpkg trailer surgery — tebako's concept, not TFS's).
2. Mount table and dispatch
N concurrent mounts: handles (tebako_mount_t, monotonic, never reused), each with mount point + backend instance.
Longest-prefix dispatch (path-component boundary); nested mounts shadow outer ones; duplicate mount point → EEXIST.
Coverage is not presence: a path a mount covers but its image does not hold takes the host-passthrough decision (spec 08) — open, stat, and opendir fall through to the (policy-gated) host answer instead of surfacing the backend's ENOENT. With the app payload mounted at / (the v2 dispatch shape), this is what keeps the host filesystem reachable: held content serves from the image (read-only), everything else behaves as if no mount claimed it.
fd/dir tables record the owning mount; unmount-by-handle force-closes only that mount's fds/dirs (later use → EBADF).
Legacy init* single-mount semantics layered on top (EEXIST when anything is mounted; unmount() tears down everything).
Extraction rule: 1 mount → dest root; N mounts → per-mount mount-point-basename subtrees. Extraction preserves mtime + permissions (best effort).
3. Backends and capabilities (open/closed)
Backends are pluggable drivers; new formats are additive. Capability model is honest per format — no uniform-RW pretense:
| format | RO | RW in-place | rebuild (creation-time) |
|---|---|---|---|
| dwarfs-t | ✓ | — | dwarfs-t Writer (in-process) / mkdwarfs-t for humans |
| squashfs | ✓ | — | mksquashfs-class |
| zip | ✓ | ✓ (add/delete) | — |
| iso9660 | ✓ (PLANNED) | — | genisoimage-class |
| tar | ✓ | append-only | repack |
| extN | ✓ (PLANNED) | ✓ (PLANNED) | mkfs |
| FAT | ✓ (PLANNED) | ✓ (PLANNED) | mkfs |
Per-platform backend availability (build-time, gated per-target in the consumers): dwarfs-t, zip, and the tar family build EVERYWHERE; squashfs is POSIX-only (squashfs-tools-ng is autotools/vcpkg-!windows), so Windows builds ship without it. A mount attempt against a gated-off backend fails with the NAMED ENOTSUP — never a silent re-route, never a crash.
Detection chain: strong magic first (zip EOCD, dwarfs, squashfs, iso9660 CD001@0x8001, ext 0xEF53@0x438, FAT BPB), weak heuristics (tar) last, with per-candidate confidence; the claimed backend is reported.
Mounts carry explicit mode flags: TEBAKO_MOUNT_RO (default), _COW, _RW. Writes on RO mounts → EROFS.
4. COW: the composite backend (transforms law)
CowBackend { base: dyn Backend, overlay: dyn Backend } — stacking, not a format: reads fall through to base unless shadowed; writes/deletes/attr changes land in the overlay; whiteouts (a small journal) hide base entries. Exists ONLY in the Rust TFS — dwarfs-t and all backends stay read-only (spec 00, invariant 5). SHIPPED: CowBackend over HostDirBackend, whiteouts masking base entries only (an overlay entry of the same name wins — upper-replaces-whiteout, overlayfs semantics).
First overlay: HostDirBackend (a host directory exposed as a TFS backend — independently useful) + whiteout journal. Disposable by deleting the dir. SHIPPED (journal: .tfs-whiteouts inside the overlay, strict v1 text format, atomic rewrites — the delete-side audit delta).
Stackable, swappable, self-contained: an overlay may itself be a CowBackend (layer stacks); an overlay may be a portable image file (detach, ship, re-attach); a base image may CARRY its overlay inside itself.
Write-side lifecycle: writes target the fast store during use (no compression in the hot path); heavyweight compression is a POST-PROCESS at unmount or live: compress the overlay into a dwarfs layer (algo per content), JOIN/squash layers (resolving whiteouts), or CHECKPOINT (squash the overlay into a new RO layer beneath and reset — running snapshots). Export any layer/overlay/composite view to any output format via the Writer. The whiteout journal IS the audit delta.
5. Encapsulation (namespace closed under mounting)
Mount-source kinds: host-file, memory, file-region (offset+length), and VFS-file-region — tebako_fs_mount_from_vfs(vfs_path, mount_point, …) mounts an image addressed by a path INSIDE an existing mount; the new backend reads its bytes through the owning mount's pread. "An FS includes another FS at a directory path" is a primitive; every file in the namespace is a potential filesystem.
6. Access-mechanism matrix (by transparency)
link — in-process via libtfs (fastest, deepest; the packaged-app model).
fuse — tfs mount image /mnt --fuse (PLANNED): real system-wide mount wherever FUSE exists; multi-backend + multi-mount (nested mount points appear as directories). The ONE mechanism with a host dependency.
serve — --serve=nfs|webdav (PLANNED): userland server; the OS's native client mounts it — no FUSE anywhere.
shell — interactive browse + one-shots (tfs ls/cat/tree/stat).
exec — tfs exec image -- cmd (SHIPPED, roadmap 30): VFS injected via the preload interposition shim (spec 07 §8, tier 1) — the MAINLINE native-exec mechanism, and a TFS consumer like any other. macOS and linux-gnu first-class; windows later.
extract — materialize to disk (exists; the honest fallback).
Trade-off stated plainly: without the kernel there is no system-wide transparent mount for unmodified arbitrary processes; TFS trades that for zero privileges, every platform, in-process speed.
7. ABI surface (additive-only rule)
Current: mount/multi-mount family, stat/pread/dir family (incl. rewinddir, telldir/seekdir index cookies, dir_is_embedded), extract_all, dlmap2file (memfs path → host cache for dlopen), tebako_fs_host_policy + tebako_host_mount_t (spec 08 jails — gates the host-passthrough path of every IO route; additive), tebako_fs_host_guard (spec 08 §3 — answers whether the installed policy judges an UNCOVERED host path, so a runtime's IO shim can widen its route predicate from coverage to "coverage, or the host namespace is guarded"; additive), tebako_fs_spawn_host_permitted (spec 08 §5 — the platform spawn boundary: a constant 1 on POSIX, where the preload tier carries the policy into spawned children; on windows 1 only while the bound policy is trivially open, the unplanned-spawn fail-closed gate; additive), abi_version() = 1, plus the additive mount-with-mode entry points (tebako_fs_mount_from_{file,file_at,memory}_with_mode taking TEBAKO_MOUNT_RO/_COW/_RW; SHIPPED — RO semantics unchanged, COW stacks the composite, RW is ENOTSUP). Write family (gated by mount mode): write/pwrite/mkdir/rmdir/unlink/rename/chmod/utimens/truncate/ fsync — ADDITIVE; RO-only consumers see zero change; abi version bumps per spec 14. Exported symbols: exactly tebako_* (nm-verified).
8. libtfs for everyone
The C ABI is the product: ONE engine (Rust), ONE machine contract, thin per-language adapters in their own ecosystems (SQLite/zlib/libgit2 model). Shared + static libs, pkg-config, embedding guide, per-backend license statement (dwarfs-t: GPL-3.0; zip: BSD; squashfs-tools-ng: LGPL-3.0 — backend selection changes a consumer's obligations; stated, never softened).
9. Symlink semantics (locked 2026-07-27)
Images contain symlinks; resolution is rule-bound:
Relative targets resolve within their own mount (never escape the mount's tree).
Absolute targets resolve through the ROUTER: the longest-prefix mount table — a symlink /__app__/share/x → /opt/inkscape/share/y lands in the /opt/inkscape mount when present (cross-mount links WORK — that is the point of composition).
Targets outside every mount are host-passthrough, subject to the SAME host_policy as any host path (spec 08): denied under a deny policy (EPERM), read-only under an ro grant, open otherwise. A symlink can never widen a jail.
Backends without symlink notions (zip-era) treat links as regular entries (stat serves the target per the stat-serves-lstat rule).
The ABI surface for links (three verbs, POSIX-shaped): lstat reports the entry itself (S_IFLNK, st_size = target length), readlink returns the stored target verbatim (relative stays relative; an undersized buffer is ERANGE, never a silent truncation), and stat follows. open follows unless O_NOFOLLOW is set; opendir follows a link to a directory; access follows. Resolution is bounded at 32 hops with ELOOP, in-process and per-call. The preload shim maps the libc spellings onto these verbs — stat/stat64/__xstat follow, lstat/lstat64/__lxstat and readlink do not.
10. Whiteout journal format (v1, locked)
The COW overlay's .tfs-whiteouts (spec 11 §4): strict v1 text, one record per line — <op> <path> where op ∈ {rm, rmd} (file, subtree); paths are %-escaped (space, newline, % itself); the journal is rewritten atomically (tmp+rename) on every mutation; ANY malformed line fails the mount with EINVAL (strict, never lenient). Whiteouts mask BASE entries only; an overlay entry of the same name always wins.
11. The debug contract (tebako-log, locked)
One facility (crates/tebako-log), every component wired through it — no ad-hoc eprintln! anywhere in the stack.
TEBAKO_DEBUG — the level: off (default) / error / warn / debug / trace, plus per-component overrides (debug,preload=trace,tfs=warn). The legacy boolean TEBAKO_DEBUG_TFS maps to debug for back-compat.
TEBAKO_DEBUG_FILE — the sink: stderr by default (stdout belongs to the payload, never to the log); a path opens append-mode with %p → pid expansion so exec'd children don't clobber one file; parents created; unopenable → stderr with one warn line.
TEBAKO_DEBUG_COMPONENTS — comma filter of component names (default: all). Components are crate names: preload, tfs, driver, shim, bootstrap, cli, pkg, resolve.
Format: one parseable line per event — tebako[<pid>] <level> <component>: <event> <k=v>…
Discipline: zero cost when off (the config reads once, the gate runs before any formatting); paths, decisions, and digests are loggable — payload contents and key material never are.
The write gate's discriminator is path_is_held (§3): a path is held when the image holds an entry at it OR at any existing in-image ancestor (implied parents count — zip has no explicit dir entries, dwarfs always does; Backend::has_entry_or_children answers per backend). Writes into a held tree are EROFS; covered paths with no in-image ancestor pass to the host, policy-gated (§6, spec 08).
TBK SPEC 17 — The runtime driver contract (any language)
Normative contract between a tebako runtime (the interpreter binary a runtime payload provides) and the tebako loader/dispatcher. Language- agnostic: ruby is the first implementation; python/julia follow this exact contract (roadmap 22's "add a language" playbook). The driver executes LINKED into the interpreter exe (factory-built runtimes) or as the WRAPPER exe of spec 29 (repacked runtimes — upstream bytes tebako does not compile); the wire is identical, and the launcher ABI never learns which pattern a runtime uses.
1. Invocation surface
<runtime> --tebako-image <self|image-path>:<slot|->:<mount> ...
[--tebako-trace <host-path>]
--tebako-entry <argv0> <user args...>
--tebako-image triples mount payloads BEFORE the interpreter starts: <self> = read the image from the running executable's own tpkg slot <slot>; <image-path> = read from a file. Slot tokens: a bare file (no trailer) mounts whole — slot 0 ≡ -; a packaged file mounts the numeric slot's trailer-described region, and - on a packaged file is a named error. A runtime-role slot (format_id = TPKG_FORMAT_RUNTIME) is never mounted. (The image-era TEBAKO_RUNTIME_IMAGE case is a bare path mounted whole — the - semantics without a triple.)
Mount order: the env image first — on a runtime-on-runtime boot (spec 33) the OWNER's env image, immediately followed by the DEPENDING runtime's env image as the first triple — then payload triples in argv order; the table is longest-prefix and nested mounts are legal; any failure unmounts everything — never a partial mount. A mount whose ancestors exist in no mounted image MATERIALIZES them as synthesized read-only directories: stat/readdir/realpath walk the boundary (a gem-home slice's point dir enumerates its mounted children with plain Dir, and Gem.paths='s component-wise realpath resolves each mounted home); a readdir at a boundary merges the image's own entries with the mounted-children names, the image's entry winning a name collision. The synthesis is read-path only — it writes nothing and changes no image.
The uniform VFS namespace (locked 2026-08-06): declared mount points are POSIX absolute paths on every platform — in manifests, in trailer slot records, and on this wire. On windows the namespace presents on its own drive: the driver qualifies every declared mount <mount> onto the runtime root's drive (<drive><mount>) before any mount, union, or entry computation. The runtime root is a per-platform baked default owned by the runtime factory (ruby: /__tfs__ on POSIX, A:/t on windows — short by owner decision, MAX_PATH headroom on every in-image path). An interpreter's C-level path expansion re-roots drive-relative paths (/...) onto the process cwd drive; only drive-qualified paths are stable across expansion, so qualifying is what keeps payload paths inside the VFS. The wire grammar therefore never carries a drive letter: <mount> is always the declared form, and a declared mount naming a drive is malformed. Lexical normalization inside the VFS treats a drive prefix as absoluteness itself: A:/ is the drive ROOT — it normalizes to A:/, never to the relative-looking A: no mount holds (a collapse would drop the query off the dispatch table, and a sibling mount at A:/t would answer in the drive root's place).
Run-time root override (TEBAKO_MOUNT_ROOT, locked 2026-08-08): the baked root is the default, never the only spelling. When TEBAKO_MOUNT_ROOT is set in the runtime's environment, the driver mounts the env image at that root instead and reports it from tebako_mount_point (the io-routing patches and the interpreter's rbconfig follow — era-2 rbconfig emits ENV["TEBAKO_MOUNT_ROOT"] || <baked>). The override is validated before any mount — an absolute path (/… or drive-qualified X:/…), no trailing slash, no .. — a malformed value is exit 65 naming the variable. The override is then gated post-mount on the env image's layout grant (mount_root_override: true, layout schema_minor 1): an image without the grant predates the override era (its rbconfig is pinned to the baked root), so the driver refuses with exit 78 naming both the override and the image — never a boot whose load paths point at an unmounted root. Declared payload mounts qualify onto the override's drive exactly as they do the baked root's.
Mount modes (locked 2026-08-04): every mount is exclusive (default) or union, declared per slot in the package manifest's mounts: block (spec 03 §6). An exclusive mount onto an occupied point is a named error (EEXIST). A union mount onto an occupied point merges the trees: directories combine, file conflicts resolve by the declared precedence (after-env — over the env image — or after:<slot>); union members are read-only and the union set (point + members + precedence) is journaled at boot. The driver reads the mode from the running package's OWN trailer (the <self> manifest block) — mount semantics never ride the argv grammar, so the launcher ABI is unchanged and drivers predating this section refuse a union package loudly (EEXIST), never silently. Payloads handed over without a package manifest (shim dispatch, bare images) are always exclusive.
Carried and shared payloads are indistinguishable on this wire (spec 23 §13, additive 2026-08-25): a SHARED slice the loader resolved into the machine cache is handed over as an ordinary <image-path>:-:<mount> triple — a bare cache file, mounted whole; a CARRIED slice is the <self>:<slot>:<mount> form. Mount order, longest-prefix dispatch, union/exclusive modes, and unmount-all-on-failure apply identically — the driver neither knows nor cares where the bytes physically live. Resolution is loader-side (spec 05 §5): an unresolvable shared slice is the loader's named error BEFORE the handoff, never a driver case; and resolution follows the press-time lock (spec 23 §4) by locked digest, never fresh semver.
--tebako-entry separates loader args from user args; argv0 is the entrypoint inside the mounted tree, resolved against the FIRST --tebako-image mount (the app payload) — or against the runtime root when no image spec is given. On a runtime-on-runtime boot (spec 33) the FIRST triple is the depending runtime's env image: the entry resolves against the first triple whose mounted manifest is not that env image — with no payload triples, against the depending runtime's own mount (the self-boot smoke form) — and a bare NAME resolves against the DEPENDING runtime's provides.entrypoints, not the env image's. The driver verifies the entry's presence against the mounts the boot itself established (named error 65 when absent); an entry outside them belongs to the interpreter's own startup. A bare NAME (no /) is the keyword form. self is the reserved interpreter keyword: the boot starts the interpreter itself with the user's args and drops the keyword (the deploy shims' re-entry form). Any OTHER bare name (spec 30 §2's spawned-dependency dispatch) resolves against the ENV image's own provides.entrypoints (spec 03 §2.2's runtime block): the declared args_default composes exactly as an app entry's would and the declared path is verified against the mounts THIS boot established; an undeclared name is the named error 65. With images but NO --tebako-entry at all, the boot mounts and starts the interpreter with its own args (the smoke form).
--tebako-trace <host-path> (spec 25 §2, additive): arm the interception trace bus at boot, BEFORE any mount — the channel file is opened once and appended for the process's life. The TEBAKO_TRACE env names the same channel; the argument wins when both are set. A channel that cannot be opened is a loud stderr note and a disarmed bus, never a boot failure (spec 25 law 1: observability never gates). The consumed flag never reaches the interpreter's argv.
The interpreter's own args are skipped (and --tebako-extract stays theirs); an unknown --tebako-* flag is a named error, never silently ignored.
Everything before the first --tebako-* is the loader's; everything after --tebako-entry is the user's, verbatim. On success the driver replaces the process argv with [<original argv0>, <args_default…>, <entry resolved in the VFS>, <user args…>] — the entrypoint's declared args_default (spec 03 §2.2), read from the app payload's own manifest, composes between the interpreter and the entry, and the program name stays at index 0 so the interpreter parses its argv conventionally and takes the entry as its script. args_default has ONE owner (tebako#503, 2026-08-31): the runtime side — this rewrite, linked and wrapper patterns alike (spec 29 §1). Loaders (the shim's dispatch, the bootstrap's handoff) never carry it; a zero-runtime entrypoint (no driver exists) is the exception — there the shim appends them as the program's leading args.
2. Environment
| var | meaning |
|---|---|
| TEBAKO_RUNTIME_IMAGE | image-era: absolute path of the runtime's own .tfs (driver mounts it instead of any embedded image) |
| TEBAKO_SPAWN_LOCK | spec 30 §2: the dispatcher's spawn-time pins for the payload's kind: runtime edges — engine=language_version:tebako_version, ;-joined in manifest order. The driver consumes it at spawn (cache-only resolution to the pinned pair) and never propagates it to a spawned child |
| TEBAKO_TFS_MOUNTS | image[:slot]:mount,… — mounts to establish (preload-shim path); grammar in §2.1 |
| TEBAKO_JAIL | jail policy env form (spec 08) — the driver/preload enforces it |
| TEBAKO_JAIL_SOURCE | audit label of the policy's origin (manifest / user / manifest+user, or the exporting surface) — journaled with every denial (spec 08 §2) |
| TEBAKO_JAIL_JOURNAL | explicit audit-journal path (default: $TEBAKO_HOME/journal.log) |
| TEBAKO_TRACE | spec 25 §2: the interception trace bus's channel file (JSONL). Opened at boot before any mount, appended for the process's life, never policy-gated; children re-derive it from the inherited env. --tebako-trace wins when both are set |
| TEBAKO_EXEC_CACHE | spec 22 §6: the boot's exec-cache root — materialized binaries/libraries live under it (per-process on POSIX; leave-in-place and content-keyed on windows, spec 22 §2.1); read-only to payloads |
| TEBAKO_RUNTIME_DLL | spec 22 §2.1 (windows only): the runtime's own PE module basename (e.g. x64-ucrt-ruby340.dll), flowed from the factory record — the single owner — and exported by the driver at boot. The tfs PE closure walk excludes a bare import name matching it (case-insensitive, bare names only); POSIX legs never read it |
| TEBAKO_PRELOAD_SHIM | spec 22 §3: the preload shim's in-VFS path, flowed from the env image's preload_shim layout grant — the interpreter's spawn hook reads it (never a hand-written copy); the driver additionally arms LD_PRELOAD (ELF) / DYLD_INSERT_LIBRARIES (macOS) with the materialized host copy |
| TEBAKO_MOUNT_<SLUG> | spec 22 §6 + v2-1/20: per co-mounted payload image, its physical mount point (drive-qualified on windows). SLUG is the mount's mechanical uppercase form: /tools/inkscape → TEBAKO_MOUNT_TOOLS_INKSCAPE; two mounts slugging alike is a named boot error (65). The root mount / exports nothing — TEBAKO_MOUNT_ROOT stays the mount-root override (§1). Under the §7 materialize tier the value is the extracted HOST dir, never the VFS point |
| TEBAKO_MATERIALIZE_BOOT | spec 17 §7 (windows only): the materialize tier's respawn marker, exported together with the rewired TEBAKO_MOUNT_ROOT; a boot finding it scrubs both before §1's override is read and re-derives the tier from the env image's grant |
| PATH | spec 22 §3.2: led by the launcher dir (<exec-cache-leaf>/wrap-bin/) when the env image delivers the preload shim — every declared dependency executable materialized as a self-injecting wrapper (unix; the SIP-strip answer) — then every co-mounted DEPENDENCY image's declared bin dirs (the dirname of each provides.entrypoints[].path / provides.executables[].path in the image's own /__tpkg__/manifest.yaml, joined under its mount, in triple order). The first triple (the app payload) never contributes; an image without a readable manifest declares no bins; a corrupt manifest or an unmaterializable declared executable is a named 65. On windows the boot-materialized library-alias directories complete the same lead (spec 22 §2.1's bare-name rule) — every co-mounted image contributing, the env image and the app payload included; the lead order is locked: launcher dir → dependency bin dirs → alias dirs → the inherited PATH. Under the §7 materialize tier the dependency bin dirs name the extracted HOST trees (<trees>/<key>/<bin> — the same mount→host map the TEBAKO_MOUNT_<SLUG> export consumes), never the VFS points: the host loader's PATH search cannot resolve the VFS spelling |
| SSL_CERT_FILE | spec 22 §4 (the cert convention's env surface — driver-owned, the driver being the single owner of the materialized host path): when a mounted image declares a materialize: entry ending ssl/cert.pem, the driver exports the cert's materialized HOST path at boot, in both boot shapes. An unset/empty value is set; a value lexically under the effective runtime mount root (a stale in-VFS spelling — A:/t/ssl/cert.pem — resolved by the patched IO but unreadable by libcrypto's native CRT IO) is rewritten; a real host path is the user's own configuration and always wins. No declared cert → nothing is set (the POSIX no-op) UNLESS the operator CA store is non-empty (tebako#541, spec 22 §4 Rule R4): then the bundle is the enumerated platform store plus the store PEMs under the exec cache's resources/store-trust/ namespace, and this var names it. When the trust bridge (§2.3) is in force the exported path names the MERGED bundle, content-keyed by the merge inputs |
2.1 The TEBAKO_TFS_MOUNTS grammar (the preload re-mount wire form)
mounts = entry *( "," entry )
entry = image-ref ":" mount
image-ref = image-path [ ":" slot ]
image-path = absolute host path (may itself contain colons)
slot = 1*DIGIT / "-"
mount = "/" *path-char ; a VFS-absolute mount point
Parse from the right. Per entry: the mount is the field after the last : (it MUST start with /); the slot is recognized ONLY when the remainder's rightmost field is all digits or exactly - — then the image path is what is left. Anything else after a colon stays part of the image path: host paths may contain colons, and the grammar never rejects them.
Slot meaning. Absent ≡ - ≡ the whole file (a bare image — the pre-slot behavior, unchanged). A numeric slot names a package slot: the consumer resolves slot → byte region against the file's tpkg trailer (spec 04). On a trailer-less file a numeric slot is a named error; a slot out of range is a named error; a runtime-role slot (format_id == 4) is never mounted — a named error.
Windows. Right-parsing keeps drive colons intact: C:\pkg.tebako:0:/__tfs__ is package C:\pkg.tebako, slot 0, mount /__tfs__; C:\image.tfs:/data is the bare image C:\image.tfs, whole file, mount /data.
No <self>. The CLI triple form's <self> token (§1) is NOT meaningful in the env form — the consuming process is a different executable from the one that was stitched. The emit side always spells the package's absolute host path.
Emit rule. A mount established from a whole bare image serializes as image:mount; a mount established from a package slot serializes as image:slot:mount. Consumers re-exporting their mount table to a spawned child MUST preserve the slot form, so the child mounts the same region — never the whole package file (mounting a packaged file whole sniffs the trailer and fails; spec 22's spawn re-entry is the victim).
Union serialization. A union mount (§1's mode: union) serializes as MULTIPLE entries at the same mount point: the incumbent first, then each member in shadow order (the order they were unioned on). A consumer that can union (the preload shim) MUST treat a repeated mount point as a union member — layered over the earlier declaration with this spec's §1 semantics — never as a duplicate-point error. A consumer that cannot union MUST fail closed with a named error. Serializing only the incumbent is a wire bug: the child boots with half the tree (the packed-mn POSIX failure — the app payload unioned over the env image at the runtime root never reached spawned children).
2.2 Interpreter-option env (interp_env, IMPLEMENTED 2026-10-07 — tebako#559)
The spec 07 §9.1 chain's product is ordinary process env, not a driver wire var: the dispatcher (the shim in managed mode, the bootstrap in standalone) computes the effective interpreter-option map and exports each winning key BEFORE the exec/handoff, so the interpreter's own option processing reads it at boot (RUBY_YJIT_ENABLE, PYTHON_JIT, JAVA_TOOL_OPTIONS, …). Consequences on this contract:
The driver applies nothing and never touches these vars. They are not TEBAKO_* control vars, not in the M7 scrub list, and not rewritten by any boot pass — a value the driver finds set is the chain's outcome by construction.
Boot order is safe by construction: the driver's boot exports (the §2 table's own vars) and the materialization passes all run before the interpreter initializes, and none of them name an interp_env key (the manifest grammar forbids TEBAKO_* there — spec 03 §2.7).
Spawned children (specs 30/32) inherit the parent process's environ, so a spawned entrypoint sees the parent's effective map. A spawned PROVIDER's own L1 interp_env does NOT apply on that path in this phase (the driver merges nothing) — that axis is a later amendment; a payload needing it is dispatched through the shim, which runs the full §9.1 chain.
The auditability requirement is served at dispatch: the effective map and each key's provenance layer render through the spec 15 §4 surface; no per-run journal entry exists in this phase.
2.3 The trust bridge (roadmap 81, IMPLEMENTED 2026-09-12)
The loader plane's network configuration (spec 04's network: grammar — the single resolution owner) already trusts the enterprise proxy story for its OWN fetches: tls_roots: platform / TEBAKO_TLS_PLATFORM_ROOTS (the OS store, where the GPO/MDM-pushed proxy CA lives) and additive extra_ca: / TEBAKO_EXTRA_CA (org PEMs parsed into the bundled roots). This subsection is the bridge that makes the RUNTIME's TLS stacks follow the same resolution — one config, every plane; the canonical runtime images stay pristine (trust material flows at run time, never a per-org rebuild).
The wire. The dispatcher (shim / bootstrap) resolves netconfig ONCE per process and conveys the verdict to the driver by exporting TEBAKO_TLS_PLATFORM_ROOTS / TEBAKO_EXTRA_CA into the handoff env — env inheritance is the wire (spec 00 §10: no second hand-written copy, no second config read in the driver).
The PEM planes (ruby / python / everything openssl- or curl-fashioned). When either var is in force, the driver's cert convention (§2's SSL_CERT_FILE row, spec 22 §4) materializes a MERGED bundle instead of the image's bare cert.pem: the image roots
the enumerated platform store (rustls-native-certs; the driver is
not size-gated) in platform mode, or the image roots + the parsed extra_ca PEMs in additive mode. The merged bundle lives under the same resources cache with the same digest discipline (spec 22 §4's write-once + per-boot rehash), content-keyed by the merge inputs. Precedence is the §2 row's unchanged: a user's real host-path SSL_CERT_FILE always wins; the stale in-VFS spelling is still rewritten. Platform + additive simultaneously is the netconfig layer's named error, never the driver's.
The operator CA store (tebako#541; spec 22 §4's Rule R4 owns the mechanics). The machine-wide $TEBAKO_HOME/trust/ca/*.pem store merges into the same bundle WITHOUT a conveyed verdict too — an image cert + the store merges when no verdict exists; no image cert (the POSIX case) + a non-empty store builds the bundle from the enumerated platform store plus the store PEMs. The wire is unchanged (the driver reads the store itself — it is not size-gated; the loader plane conveys nothing new). The same fail-closed rule covers a corrupt store file.
The java plane. The JVM is a spawned child (spec 30), not a driver boot — its bridge rides the §2.2 interp_env chain on the dispatcher side: in platform mode on windows the chain additively appends -Djavax.net.ssl.trustStoreType=Windows-ROOT to JAVA_TOOL_OPTIONS (the JVM trusts the OS store natively; additive merge, never a stomp). The extra_ca-on-java shape (a materialized PKCS12 truststore + -Djavax.net.ssl.trustStore) is the open sub-item of roadmap 81 — until it lands, extra_ca with a spawned java edge in force yields a loud journal line naming the gap, never a silent partial-trust boot.
Fail closed. A malformed extra_ca PEM, an unenumerable platform store, or an unwritable merge destination is a named boot error (65 class) — never a silent fall back to the image bundle alone, which would surface as inscrutable TLS errors deep in the payload. There is no verify-off spelling.
3. File IO semantics
The runtime's IO MUST route mounted paths through the TFS layer (tebako_fs_* or an equivalent in-process VFS): read-only payload images; host paths pass through subject to the jail policy; writes to payload images fail EROFS. Two implementation patterns (spec 07 §8): patched-interpreter io-routing (ruby) or the preload interposition shim (unmodified dynamic binaries).
4. Exit codes
The runtime preserves the loader's named codes (65–74) when the failure is loader-side; runtime-side failures use the interpreter's own codes. --tebako-extract is the runtime-side option riding the user-arg passthrough: dump mounted images to disk and exit 0.
5. Provenance
A runtime payload's manifest (spec 03) declares provides {engine, version, abi_line, platform} + built_from — the dispatcher's compatibility check consumes exactly these fields.
6. Implementation and contract version
The reference implementation is crates/tebako-driver (Rust, staticlib * rlib) — the v1 C++ tebako-main driver is retired. The driver executes in one of two patterns: LINKED into the interpreter exe (factory-built runtimes — the reference form) or as the WRAPPER exe defined in spec 29 (repacked runtimes); both patterns declare the same contract. Runtimes whose driver implements this document's widened grammar (image-path triples, bare-file slot tokens, env-image-first multi-mount, direct --tebako-entry execution) declare contract_version 2 in their release manifest (spec 06 §6); the compiled-in constant (tebako_driver_contract_version()) and the manifest must agree.
7. The windows materialize tier (locked 2026-09-17)
A runtime whose interpreter CANNOT consume the driver's mounted images — the zero-patch contract: no io-routing patches, and windows has no preload interposition tier (spec 22 §2) — boots on windows from EXTRACTED host trees instead. This section is a boot-time behavior tier, not a wire change: §1's grammar, the mount table, and every verification step are untouched, and POSIX is unchanged — the tier never engages there (POSIX runtimes read the mounts directly, ruby's patched IO being the reference case).
The trigger is a grant, never a heuristic. The runtime's env image manifest (/__tpkg__/manifest.yaml, kind runtime) declares provides.windows_boot: materialize (spec 03 §2.2, payload-manifest.yaml schema_minor 11 — old readers ignore the key and keep the mounted-boot behavior, which for such a runtime is its standing named refusal). On windows, after the env image and payload mounts are established and verified exactly as §1 describes, the driver reads that manifest: the grant present selects this tier; absent, the boot proceeds exactly as before.
Extract. Every mounted image of the boot — the env image first, then each payload triple in order — is extracted as a TREE (not per file; spec 22 §4's class-R per-file discipline is the per-file ancestor of this one) into the exec cache:
<TEBAKO_EXEC_CACHE>/trees/<tree-key>/ the extracted image tree
<TEBAKO_EXEC_CACHE>/trees/<tree-key>.tfs-digest the verification record
<tree-key> is the image's own content key — the store sidecar's sha256 prefix (the exec cache's segregation idiom, spec 22 §6), with the slot number appended (-<slot>) when the image is a package region, so two slots of one package never share a tree; a no-store dev boot keys the path, exactly as the cache root itself does.
Write-once, tmp+rename, per-entry flock. Extraction streams the mounted tree into a per-process staging dir (.<tree-key>.part-<pid>), hashing in flight (per file the tfs-merkle-1 file construction; the tree digest is the sha256 over the sorted walk's D <rel>/ / F <rel> <merkle> lines), then renames the record into place BEFORE the tree — content without a record is foreign by construction, and a partial tree is never visible at the final path. Installed files are read-only (Rule R3). Concurrent boots serialize on the per-entry flock (120 s timeout, then a named error with the stale-lock hint — the store's spec 05 §4 discipline). The walk lists each image's OWN entries (the image-native listing, not the interpreter-facing mount-merged one): a sibling mount BELOW the walked point — the env image at A:/t beside a payload at the drive root A:/ — extracts into its own tree by its own key, and its boundary name never joins this walk (or the walked image's tree).
Digest-pinned reuse. A cached tree is served only after it re-verifies against its record (the host tree re-walked and re-hashed to the recorded digest). A match is served with zero extraction — the second boot is free. A mismatch, a missing record, or a corrupt record is the cache tampered or corrupt: the tree is wiped and re-extracted ONCE from the (mounted, verified) image; a tree that still fails verification after re-extraction is the named 70 (EX_TEBAKO_SHA), never a silently served corruption. Extraction IO failures mid-tree are named 74s with the staging dir abandoned (never renamed into place). A tree holding a symlink or a special entry is a named 74 — the tier extracts regular files and directories only.
The trust chain is untouched. Images are verified at fetch/install (spec 09) and mounted exactly as before; the tier only changes WHERE the interpreter's bytes are read from. The record pins the cache tree to the bytes the verified image served; the per-boot re-walk pins the tree to the record.
Rewire. With the trees in place the driver rewires the handoff for the interpreter's plain host IO:
TEBAKO_MOUNT_ROOT is set to the extracted env-image tree (a drive-qualified host path) — the era-2 rbconfig pattern (ENV["TEBAKO_MOUNT_ROOT"] || <baked>, generalized to any runtime) then resolves every runtime-relative path onto plain host files. This is the tier's own rewiring, NOT a §1 user override: the mount_root_override layout grant does not gate it (the runtime opted in by declaring the tier), and the driver's own mounts were already established at the baked root before the var is set.
The mount-discovery surface (§2's TEBAKO_MOUNT_<SLUG> table) points at the extracted HOST dirs, not the VFS points — a consumer reading a co-mounted payload's files reads host files, as the interpreter must.
The §3.2 dependency bin dirs on PATH (spec 22 §3.2) name the extracted HOST dirs too (<trees>/<key>/<bin> per dependency mount, through the same mount→host map the discovery export consumes) — the host loader's PATH search cannot resolve the VFS spelling, so a VFS-spelled lead silently resolved nothing (the xml2rfc windows leg's mingw DLLs, which only a beside-the-pyd staging could reach before this).
The rewritten argv's entry (§1) resolves to its host path inside the extracted tree of the image that mounted it.
Respawn. The driver also exports TEBAKO_MATERIALIZE_BOOT=1 with the rewired root. A boot that finds the marker present treats an inherited TEBAKO_MOUNT_ROOT as the tier's own state — both are scrubbed BEFORE §1's override is read (the child's driver mounts at the baked root, re-derives the tier from the env image's grant, and serves the cached trees). Without the marker an inherited root keeps §1's semantics exactly.
The mounts stay established for the driver's own reads (manifests, spawn planning) for the process's life; the interpreter simply never consults them.
The jail deviation (documented, loud). Host IO under an extracted tree cannot be interposed, so on a windows-materialize boot TEBAKO_JAIL does not confine the payload's reads of host files — there is no VFS on the consumption path to enforce it. POSIX mounts enforce the jail exactly as spec 08 describes. A boot under the tier emits a LOUD notice to stderr naming the deviation, once, before the interpreter handoff.
Exit codes stay inside the loader's named allocation: 65 (a tier declared on a corrupt/lying manifest surfaces through the existing manifest checks), 70 (a tree that fails verification after its one re-extraction), 74 (extraction IO failure, a symlink/special entry in the tree, the flock timeout). Runtime-side failures keep the interpreter's own codes (§4).
7a. The invoked program name (tebako#237)
The driver exports TEBAKO_PROGRAM_NAME on every entry handoff: the NAME the dispatch selected — the bare --tebako-entry keyword verbatim, or the entry path's basename (the gem-binstub convention) for the path form. The ruby patch assigns $0/$PROGRAM_NAME from it at interpreter start, so CLI frameworks that read the program name (the Thor/option-parser class) see the program the user ran, not the resolved in-VFS script path. The variable is a read-once handoff: it sits on the boot-contract side of the credential scrub (spec 03 §2.10) and payloads cannot flip it for children.
7b. Co-mounting run-time-resolved payloads (tebako#460)
A payload slice the boot needs but the package did not embed resolves at first run per spec 05 §4a, then co-mounts EXACTLY like an embedded slot: the loader hands the driver the same --tebako-image <path>:<slot>:<mount> triple — the driver cannot tell an embedded slot from a cache-resolved one, and never may (one code path, spec 05 §4a's rule). The resolution happens BEFORE the handoff (bootstrap standalone / shim managed); a named 75-class error (unresolvable), a trust error (digest mismatch), or 65 (a DEPENDS cycle) fires at resolution time — the driver's mount contract is unchanged.
8. The min-runtime floor (spec 03 §2.9, tebako#666)
Every payload manifest the driver reads at boot — the app payload's, a spawned provider's, the env image's own — is gated on the declared min_runtime_tebako floor against the runtime's own tooling version (the driver crate version the factory built the exe from; the store grammar names the runtime by it):
Clean parse, floor above the runtime: the boot refuses with the named stale-runtime error — "the runtime is too old for this payload's manifest (needs X, have Y); update the runtime — the payload is not at fault". The key is additive and old-reader-safe, so a manifest can parse fine and still be too new for the runtime's semantics.
Parse failure, floor above the runtime: the manifest almost certainly uses grammar this runtime predates. The driver reads the floor by a tolerant top-level scan of the raw YAML (PayloadManifest::declared_min_runtime_tebako) and rewords the refusal to the same stale-runtime message — NEVER "corrupt manifest / self-description lies", which blames the wrong artifact (the tebako#666 failure class: mount-ancestor routes on pre-#616 runtimes, spec-32 kind: executable edges on pre-spec-32 runtimes).
No floor, or a satisfied floor, or an unreadable scan: the existing wording and codes stand unchanged.
The refusal keeps the manifest class's exit code (65, EX_TEBAKO_MANIFEST) — the wording, not the code, is the contract change; the loader-side resolution floor (spec 05 §5) is what keeps a stale runtime from being picked in the first place.
TBK SPEC 06 — Launcher ABI (bootstrap → runtime)
Normative specification of the handoff contract. Version: 1. Status: SHIPPED (macOS/Linux; Windows exec/lock port PARTIAL — roadmap 02).
1. The handoff
<runtime> --tebako-image <self>:<slot>:<mount> ...
--tebako-entry <argv0> <user args...>
One --tebako-image triple per payload slot to mount: <self> = the package's own path, <slot> = slot index, <mount> = the slot's mount point.
Slots whose role is runtime are never handed over as mounts.
--tebako-entry separates loader-consumed args from user args; <argv0> is the entrypoint name inside the mounted tree.
--tebako-extract is a runtime-side option riding the user-arg passthrough (the loader never interprets it).
2. Image-era addition (additive, ABI stays 1)
When the runtime_ref carries ;image (spec 05 §1), the loader exports:
TEBAKO_RUNTIME_IMAGE=<absolute path of the cached .tfs>
The runtime driver prefers the env image over any embedded image (one-file driver patch, docs/tebako-main.cpp.30b.patch); v1 runtimes ignore the env and use their embedded image — graceful degradation, no republish of v1-era runtimes needed.
3. Loader behavior contract (tebako-bootstrap)
1
Read own trailer (spec 02; absent → classic-bundle error path).
2
Require launcher_abi == 1 (else exit 66).
2a
--tebako-install verb: after the chain + ABI gates — the package's TPKG_FLAG_NO_INSTALL refuses (exit 76); any other package answers with the named guidance to tebako install <path> (exit 76 — the manifest read needs the TFS engine the size-capped bootstrap deliberately does not carry). A run is a run: the verb is the ONLY way slices reach the store.
3
Trust handling, by build and trailer flag:
TPKG_FLAG_SIGNED_V2, verification ENABLED (openpgp-verify feature): verify the OpenPGP signature against the trusted keyring and each slot's SHA-256 — always strict (spec 09).
TPKG_FLAG_SIGNED_V2, verification DISABLED (unverified-first, the shipped default until roadmap 72's crypto toolkit): loud UNVERIFIED warning + audit journal, then enforce each slot's SHA-256 as integrity-vs-corruption (the anchor is unverified — documented, spec 09 §7). TEBAKO_REQUIRE_SIGNED=1 here fails CLOSED with exit 71 naming the missing capability ("built without OpenPGP verification") — a strict-mode request is never silently downgraded to unverified.
Unsigned (v1): loud warning + audit journal (or exit 71 under TEBAKO_REQUIRE_SIGNED=1).
4
Resolve the runtime per spec 05 §5 — negotiating the contract version (§6) fail-closed before any checksum acceptance.
5
Image-era: ensure <asset>.tfs + trust markers in the cache entry (fetch + verify on miss — authenticity per spec 09 §4's runtime-fetch point first, then sha256 integrity as today), install read-only.
6
Exec the handoff. Never returns on success.
4. Exit codes (named, stable)
| code | name | meaning |
|---|---|---|
| 65 | EX_TEBAKO_MANIFEST | trailer missing/corrupt/invalid |
| 66 | EX_TEBAKO_ABI | launcher_abi mismatch |
| 67 | EX_TEBAKO_RUNTIME_REF | unparseable/unsupported runtime_ref |
| 68 | EX_TEBAKO_OVERLAY | overlay/decrypt binding failure: unbound retained store, missing or non-opening key material, unwritable store, orphan binding, malformed TEBAKO_OVERLAYS / TEBAKO_DECRYPT (spec 24 §7; code constant tpkg::EX_TEBAKO_OVERLAY) |
| 69 | EX_TEBAKO_UNAVAILABLE | runtime unresolvable (offline miss, download failure) |
| 70 | EX_TEBAKO_SHA | sha256 mismatch (runtime or image) |
| 71 | EX_TEBAKO_SIGNATURE | invalid signature; or unsigned under TEBAKO_REQUIRE_SIGNED=1 |
| 72 | EX_TEBAKO_TRUST | signer key not in the trusted keyring |
| 73 | EX_TEBAKO_JAIL | jail policy could not be applied (malformed TEBAKO_JAIL; fail-closed — spec 08) |
| 74 | EX_TEBAKO_IO | filesystem/lock/install failure |
| 75 | EX_TEBAKO_CONTRACT | runtime declares an unsupported contract_version (§6) |
| 76 | EX_TEBAKO_INSTALL | --tebako-install refused (TPKG_FLAG_NO_INSTALL) or needs the CLI |
| 77 | EX_TEBAKO_CONTRACT_ERA | the runtime declares a contract ERA newer than the loader speaks (§6; code constant tpkg::EX_TEBAKO_CONTRACT_ERA) |
| 78 | EX_TEBAKO_LAYOUT | the TEBAKO_MOUNT_ROOT override is ungranted by the env image's mount_root_override layout grant (spec 17 §1; code constant tebako-driver's EX_TEBAKO_LAYOUT) |
| 79 | EX_TEBAKO_CHECK | a payload check FAILed — the tebako check aggregate (spec 26 §2; code constant tpkg::EX_TEBAKO_CHECK) |
| 80 | EX_TEBAKO_LEDGER | a ledger finding — tebako audit --verify met a chain mismatch or an invalid seal signature, the seal file holds an unparseable record, or --strict met unparseable journal lines (spec 40 §6; code constant tpkg::EX_TEBAKO_LEDGER) |
| 81 | EX_TEBAKO_SOLVE | a tree-solve finding — a named conflict, lockfile drift under --locked, an open runtime seam, or a malformed requirement set (spec 42 §5; code constant tebako_cli::solve::EX_TEBAKO_SOLVE) |
stderr body: tebako-bootstrap: <message>\n — message bodies match the C++ reference bootstrap 1:1 (golden parity).
5. Progress UX (locked 2026-07-26)
When the loader fetches a runtime or image, the user SEES the work and the benefit. Rules:
TTY-only: full progress rendering iff stderr is a TTY and TERM != dumb; otherwise exactly two single lines (start + done), CI/ log-safe. Opt-outs: NO_COLOR, TEBAKO_NO_PROGRESS=1, and the package's baked TPKG_FLAG_QUIET_NOTICES (bit 3 — spec 23 §14).
Phases, one line each: resolving <runtime_ref> → downloading <asset> (<size>) with the live bar → verifying sha256 → installing (locked) → done.
The bar (hand-rolled ANSI, no deps — the size gate forbids indicatif-class crates): \r[=====> ] 62% 14.2/23.0 MB 3.1 MB/s throttled to ≤ 10 redraws/s; unknown content-length → spinner frames + byte count.
The benefit is stated: on completion — installed ruby-3.4.2-0.15.9-linux-gnu-x86_64 (23.0 MB) — cached at ~/.tebako/runtimes/… and shared by every tebako app on this machine. A cache HIT prints one quiet line: runtime ruby-3.4.2 (cached). TEBAKO_NO_PROGRESS=1 silences these informational lines entirely (the cache-hit, installed …, and downloading … lines — progress is not results; tebako#400); the mode selection rule above still applies. TPKG_FLAG_QUIET_NOTICES (bit 3 — the developer's press-time declaration via the spec 23 §14 registry) applies the same silence to every run of the package, on every machine.
Progress output goes to stderr, never stdout (stdout belongs to the payload).
Implementation: a tiny tebako-term micro-crate (TTY detect, bar, spinner, phase lines) consumed by tebako-bootstrap; tebako-shim and tebako-cli reuse it (no third copy). tebako-http gains an on_progress(bytes_so_far, content_length) callback hooking the stream — the bar is transport-accurate, not estimated.
5a. The fetch-plan rendering (tebako-term v2, locked 2026-09-18)
The spec 05 §6 fetch pipeline downloads a plan's artifacts CONCURRENTLY, and the user sees that concurrency — the docker-pull look. tebako-term v2 adds the plan surface (ProgressSet); the single-artifact contract above is its one-slot case.
The plan header (both modes, one line, printed before the first artifact starts): fetching <what>: <N> artifacts, <total> total where <what> names the resolution subject (e.g. runtime ruby 3.3.12) and <total> sums the known size hints (unknown when none are known). A cache hit for the whole plan prints no header — the hit lines stand alone as before.
One live line per concurrent worker (TTY mode): the set renders as a fixed block of N slot lines at the bottom of the scrollback, repainted in place (\x1b[<N>A up + erase-line per slot), throttled to ≤ 10 redraws/s for the WHOLE block (not per slot). Each slot runs the phase sequence download bar → verifying (spinner) → done; the done state keeps its line in the block until the plan completes (✓ <asset> (<size>)), a failed slot renders ✗ <asset> and the plan's named error follows on a fresh line.
The bar grows up: fractional unicode blocks (▏▎▍▌▋▊▉█ — eighth-cell resolution), an EMA-smoothed rate (3.1 MB/s, α = 0.3 per redraw) plus an ETA (eta 12s, shown only once the EMA has converged past its warmup), the byte pair in the total's unit. Unknown content-length → a braille spinner (⠋⠙⠹⠸⠼⠴⦦⦧⦇⦏)
byte count. Colors: cyan for an active slot, green for done, red
for failed — decorative only, and absent whenever the mode rule above selects plain (NO_COLOR included).
Plain mode grammar (pipe/CI/opt-out — byte-stable, testable): exactly the plan header, then per artifact the pair downloading <asset> (<size>) / installed <asset> (<size>) (or downloading <asset> when the length is unknown), then the summary line fetched <what>: <N> artifacts, <total> in <secs>s. No control sequences, ever. TEBAKO_NO_PROGRESS quiets the whole grammar (the header included) — progress is informational, never results; failures are named errors on stderr regardless of the gate.
The wiring rule (locked): every network artifact transfer — runtime pair downloads, payload slice fetches, registry index refreshes, trust-anchor key retrievals — renders through tebako-term; no caller prints its own download progress. A registry YAML fetch (small, unknown length) renders as a one-line spinner phase in TTY mode and a single fetching registry <ref> start line in plain mode (its done line is the resolution's own output). Callers that today emit nothing (the shim's dispatch-time fetch, the CLI's press resolver) gain the same surface — the download moment is one UX everywhere.
6. Bootstrap↔runtime contract negotiation (roadmap 45)
The launcher ABI (§1–§2) is the wire format; the contract version is its semantics version, declared by the runtime and enforced by the bootstrap. It exists so a future handoff change (env names, argv shape, image-handoff semantics) can be introduced without old bootstraps silently mis-executing new runtimes.
| contract | semantics |
|---|---|
| 1 | this document, §1–§5: --tebako-image/--tebako-entry argv, TEBAKO_RUNTIME_IMAGE env handoff, trailer/ABI gating as in §3 |
| 2 | spec 17: image-path triples, bare-file slot tokens (0 ≡ -), env-image-first multi-mount, direct --tebako-entry execution (no /local/stub.rb convention) |
Bump rule. Any change to env/argv/handoff semantics — a renamed or repurposed variable, a new loader-consumed flag, a change in image precedence — increments the contract version by exactly 1. Additive payload-side changes that v1 runtimes may ignore (like §2's env image for v1 runtimes) do NOT bump the contract.
Declaration. The runtime release manifest's per-package entry carries the contract SET — "contract_era", "contract_version", "mount_root" — (spec 05 §5's manifest.json; the set is additive — older consumers ignore it). The runtime driver has the same values compiled in (TEBAKO_CONTRACT_VERSION and its siblings); the runtime repo's CI fails any release where the manifest and the driver disagree.
Negotiation rule (bootstrap, fail-closed — spec 18's era vocabulary). During runtime/image resolution, before any checksum acceptance, the loader reads the entry's contract set (crates/tebako-resolve/src/contract.rs is the implementation of record; the current spoken values are era 2 and contract 2 — the spec-17 argv/env grammar):
The manifest carries NO entry for the asset → not a contract question (the checksum path names that failure) → proceed.
The entry's contract set is present and matches the loader's spoken era + contract → proceed (the declared, acceptable set).
Any of the three fields absent, unparseable, zero, or empty → a pre-era entry — a NAMED refusal (ContractError::PreEra, exit 75) listing the missing fields, never a proceed.
A declared era NEWER than the loader's → refused (ContractError::EraTooNew, exit 77 — EX_TEBAKO_CONTRACT_ERA) naming both generations and the remedy; a contract NEWER or OLDER than the spoken one → refused (ContractTooNew/ContractTooOld, exit 75) naming both.
A negotiation failure is never a crash and never a silent accept: it is a clean, explained refusal.
TBK SPEC 07 — Shims and dispatch
Normative specification of executable registration and version management. Status: PARTIAL — the dispatcher and version manager (§2–§4) ship as crates/tebako-shim in tebako-rs (roadmap 08; retires mnenv). Remote registry fetch ships with tebako add-registry | install (roadmap 28.1 — the CLI resolves every registry form of spec 04 §2), and the dispatch-time registry cache ships with roadmap 33 (the registry-default chain link resolves every registry form through tebako-resolve behind ~/.tebako/registries/<sha>.yaml — 24 h TTL, tebako update-registries, TEBAKO_OFFLINE = cache-or-named-error; tebako add-registry primes the cache with the bytes it fetched; a STALE cache + a failed refresh serves the stale bytes LOUD — stderr + journal — rather than failing, spec 05 §4's stale-serve, roadmap 86). The 2026-09-05 routing amendment (qualified pins, per-payload disable, tebako-shim use) SHIPS with this spec's PR-A — the status lines below reflect it. Still PLANNED: jail application (spec 08), and a runtime registry (v1 downloads resolve through the runtimes: preference in config.yaml as the exact ref).
0. v1 concrete choices (normative where the sections above were open)
Project pin file .tebako-tools.yaml is a FLAT YAML mapping of command name → pin; a nearer file that does not pin the command does not shadow a farther one that does.
The chain-value grammar (2026-09-05 amendment): every link of the version chain — TEBAKO_<TOOL>_VERSION, .tebako-tools.yaml, config.yaml defaults: — carries [payload@]version (split on the FIRST @; tpkg::toolpin::ToolPin is the ONE parser — spec 00 invariant 10). payload@version makes the named payload THE provider (§2 step 0.5); bare version keeps today's scan. A payload-only pin (payload@) does NOT exist — route-out rides disable, never an incomplete link. An unparseable chain value is the NAMED grammar error (EX_TEBAKO_MANIFEST, naming the link and value), never a silent skip.
~/.tebako/config.yaml keys: defaults: (command → [payload@]version; tebako#667: a KEY of the form <registry>/<payload> is the payload-level pin — it covers every entrypoint the payload declares, and a command-level pin beats it for its own command, §4), registries: (spec 04 refs), runtimes: (engine → {version, tebako, source?} runtime preference; source: pins the engine's download base — spec 05 §2's per-engine chain, SHIPPED in the shim's dispatch-time fetch, tebako#567). The shim never writes this file — except through tebako-shim use, the explicit verb (tmp + rename, the same discipline as add-registry; a structural edit that preserves keys, not comments).
Disabled state is shim-managed state, not authored config: ~/.tebako/shims/.disabled.yaml (command → selector list). The selector grammar (2026-09-05 amendment — tpkg::toolpin:: DisableSelector is the ONE parser): all gates every claim of the command; version gates that version of ANY claim; payload@all gates the named payload's claim; payload@version gates exactly that (payload, version) claim. An unknown selector string in the file is a NAMED parse error at load, never silently ignored (invariant 9).
Installed payload record (the dispatcher-visible manifest mirror, spec 03 §4 tier 3 rationale): payloads/<name>/<version>.tfs, <version>.tfs.sha256, <version>.manifest.yaml.
Zero-runtime dispatch (spec 03 §2.2): the payload image itself is the program — the self-launching-image contract; dependency mounts still ride the ABI v1 argv shape minus the runtime prefix.
Registry payload mounts are bare images: slot 0 (whole image), mount point / of the jail namespace.
1. The model
Tebako manages shims for every executable every installed payload provides (spec 03 entrypoints). One payload may carry MULTIPLE executables — each is dispatchable; the ACTIVE subset (spec 03 §2.2's per-entrypoint active, default true) is PATH-registered at install, and an inactive-but-declared command links on demand (tebako shim enable <name>). A payload's kind: runtime edge (spec 30) adds one more source of names: the edge's expose: list registers one shim per exposed depended-runtime entry under the same active-flag and enable-on-demand rules — dispatch of such a shim IS spec 30 §2's spawned dispatch (argv0 → the payload's version chain → the depended runtime's resolution), never a direct store-path exec.
+ The three tiers, separately owned (spec 03 §2.2's ladder, restated at the dispatch surface): a command's life is declared (the payload author's complete inventory — the only set tebako run resolves against) → default-active (the author's choice of what an unqualified install links; active: false marks the rest) → linked (the installing user's per-machine choice: the default-active set minus the hidden set, narrowed at install by --only-shims/--no-shims and adjusted afterwards by hide/expose). Each tier is a subset of the previous; the first two are the slice owner's, the third is the installer's. The disable axis (§0) is orthogonal to all three and composes with them.
Four artifacts, four jobs:
payload — a signed .tfs image (versioned, runtime-independent).
runtime — a signed runtime payload (versioned, cached, machine-shared).
registry — a developer-hosted tpkg-registry.yaml (spec 04 §2).
dispatcher (tebako-shim, a tiny static Rust binary in tebako-rs) — the thing on PATH that picks version + runtime per invocation and hands off.
Provider routing (2026-09-05 amendment): two installed payloads may provide the SAME command (forks, alternative distributions, a suite and a standalone tool). Provider resolution consults two LOCAL surfaces — the version chain's payload-qualified pins (§2 step 0.5) and the disabled-state file's payload-qualified selectors — never the registry: a registry's default: stays payload-keyed, and a registry NEVER routes commands (routing is local state by design; a future registry default_payload: cold-start hint is a separate extension point, not this spec). The version chain itself is a DYNAMIC per-tool family (TEBAKO_<TOOL>_VERSION — an unbounded name set) with its own four-link chain (§2.1); it is NOT a citizen of spec 23 §14's settings registry (§14 owns FIXED-NAME press/machine knobs) — the two surfaces never drift into each other.
argv0 integrity (locked 2026-08-29): command selection rides argv0 — the invoked name must reach the process as its own argv[0]. Symlinks, hardlinks, and byte copies preserve it. Wrapper generators that spawn the target under the TARGET's own path (chocolatey's shimgen — Install-BinFile; a shell wrapper that execs the real path) silently defeat selection: every invocation then falls back to the primary entry (entries[0]) and the other declared commands are unreachable. A distributor exposes a multi-command package as real links or copies, one per declared entrypoint name — never as re-exec wrappers.
2. The dispatch chain (per invocation of ~/.tebako/shims/<tool>)
0
argv0 is the selector. One tebako-shim binary, linked per command name; it maps name → entrypoint in the payload's manifest. Multi-command suites: one package with N entrypoints installs N shims — each dispatches to its own image AND ITS OWN runtime requirement; two commands in one package may run different runtime versions simultaneously.
0.5
PROVIDER ROUTING (2026-09-05 amendment): the chain VALUE grammar is [payload@]version (tpkg::toolpin is the SSOT parser). A payload-qualified value makes the named payload THE provider — it must be installed and declare or expose the command, else the named NotAProvider error. The provider scan skips claims disabled at <payload>@all or <payload>@version, so disabling all-but-one claims routes without a pin. Unqualified values fall through to today's scan (payload-of-command-name fast path → suite scan → expose scan). A registry never routes commands: routing is local state.
1
Payload VERSION resolution (first match wins): TEBAKO_<TOOL>_VERSION env → nearest .tebako-tools.yaml walking up from cwd (per-project pinning) → user default (tebako-shim use <tool> <pin>) → registry's default.
2
RUNTIME resolution: the entrypoint's runtime_requirement → newest COMPATIBLE cached runtime (no download) → else download newest compatible (spec 05 §5). Swapping runtimes needs no payload change — the payload is immutable; only the dispatch-time choice changes (tebako use --runtime ruby@3.4.2, or a per-project pin).
3
EXTENSION-SLICE scan (additive — schema_minor 10, spec 03 §2.8): when the resolved root payload declares extension_points:, the dispatcher scans the STORE's payload manifest mirrors (payloads/*/*.manifest.yaml, spec 05 §3) for slices whose augments[].payload names the root — store-local, never a network fetch. Per candidate: bind extension_point → mount <point.mount>/<slice.name> (an unknown point name = loud skip); check the slice's constraint against the RESOLVED base version and its language edge against the RESOLVED runtime (engine + abi line). A slice MAY carry several augments edges naming the root — the suffixed-line family (spec 03 §2.8) ships one exact-pin edge per family row; the candidate attaches when ANY such edge matches. Newest compatible version per slice name attaches (the store layout makes same-version duplicates impossible); an auto-discovered mismatch = loud skip + journal (event=slice-skip slice=… reason=…); a successful attach journals event=slice-augment slice=… base=… mount=…. Compatible slices append --tebako-image <slice-path>:-:<mount> triples AFTER the app's (spec 17 multi-mount — nested under the app's / mount, longest-prefix dispatch; a mount failure is the driver's all-or-nothing teardown). Config-pinned slices (§4) override auto-discovery per slice name, fetch on miss (parity with the runtime fetch; TEBAKO_OFFLINE=1 = cache-or-error), and a pinned mismatch is the named SliceIncompatible error, never a skip. When base and attaching slice both carry provides.gems, a same-name gem pair journals event=slice-overlap slice=… gem=… — informational only (gem homes compose by requirement-based activation; the fix is a slice rebuild against the newer base).
4
Hand-off: mount payload + ZERO OR MORE runtime payloads (native entrypoints need none — spec 03) + declared dependency mounts (spec 03 §2.3), apply the jail view (spec 08), exec the entrypoint. Signed payloads are verified at install time, not per run. When the payload declares kind: runtime edges (spec 30), the dispatcher resolves each edge NOW (cache or download per spec 05 §5) and exports the pins as TEBAKO_SPAWN_LOCK (spec 17 §2) — the driver's spawn-time picks are locked to the dispatch-time resolution and a store GC cannot re-pick mid-process.
3. Shell integration (no per-shell magic)
ONE directory on PATH: ~/.tebako/shims. One-time setup; tebako shim install-shell [--shell bash|zsh|fish|csh] [--position prepend|append] inserts a managed BEGIN/END block into the right startup file (.profile/.bash_profile/.bashrc/.zshrc/.cshrc); prepend is the default (a shim you install answers), --position append defers to existing resolutions (a version manager keeps its lead); re-running with the other position rewrites the block in place; idempotent; uninstall-shell removes exactly its block.
Shim links are always an explicit act: registry installs register the payload's provides (that IS the install's point); a local-package install (tebako install <path>) links only with the explicit --shims; a run — of any package, ever — links nothing. A one-off act never claims PATH names. The install-time selection (tebako#1004 §2): a registry install narrows the claim with --only-shims a,b (exactly those commands link; an undeclared or hidden name is the named usage error) or claims nothing with --no-shims — dispatch through tebako run <name> stands either way, and the choice rides the whole closure (the payload's own dispatchables, its dependencies', and the spawned runtimes' expose: commands). A hidden name stays hidden through reinstalls, with the subtraction printed once at install.
NO eval-init hook for switching: the dispatcher reads the project file itself (the mise model, not the rbenv eval "$(… init -)" model).
tebako-shim use / disable / enable / list / which / doctor manage shims (link/remove/inspect/diagnose); enable/disable specific versions. The verbs spell identically through the CLI: tebako shim <verb> … ≡ tebako-shim <verb> … (tebako-cli calls the shim crate as a library — never a shell-out).
use <tool> <pin> writes the user-default link (config.yaml defaults: — the explicit authored-config write verb beside add-registry, tmp + rename, keys preserved); the pin is the [payload@]version grammar of §0. use --clear <tool> removes exactly that key; use --runtime <engine>@<langver>[:<tebako>] writes runtimes:.
enable|disable <tool>[@<version>] [--of <payload>] edit the disabled-state selectors of §0: bare → all; @<version> → version; --of <payload> alone → payload@all; with @<version> → payload@version.
which <tool> names the provider payload and provider kind (own / exposed / pinned) beside the version and its source.
list [--json] shows per command the provider payload, provider kind, resolved version + source, and disabled marks; --json emits one "info_schema": 1 document (mirroring tebako cache list --json).
doctor additionally reports: commands with MORE THAN ONE enabled claim (collisions), dangling pins (project-file/config pins naming an uninstalled payload or version), and disabled-but-pinned conflicts. Doctor stays diagnose-only: findings print, the exit code is unchanged (0 / 1 with problems).
Enable links on demand (locked 2026-08-29): enable <tool> whose command is declared by an installed payload but was never linked (spec 03 §2.2's active: false default) materializes the shim link then — the dispatcher links ITSELF (argv0 integrity above); enabling an undeclared command is the suite scan's named error, never a dangling link. disable gates per version (.disabled.yaml) without removing the link.
4. Configuration
User config: ~/.tebako/config.yaml (YAML — the locked convention; supersedes the earlier config.json note). Contents: defaults, registries, runtime preferences. (IMPLEMENTED 2026-10-07 — tebako#559: a per-tool env: map, store-config schema minor 3 — the user-config layer of the §9.1 interp_env chain, set by hand or by tebako-shim env; never written implicitly by a dispatch.)
Project pins: .tebako-tools.yaml at any directory — the dispatcher walks up from cwd; nearest wins.
Extension slices (schema_minor 10): per-tool keys in the same two documents (project file wins over user config, as with versions):
metanorma:
version: "1.16" # the existing chain, unchanged
slices: [metanorma-bsi@1.2.0] # explicit pins: fetch-on-miss, a
# constraint mismatch = SliceIncompatible
auto_slices: true # false kills the §2 step-3 store scanFigure 40 One-off env: TEBAKO_<TOOL>_SLICES=metanorma-bsi@1.2.0,… (prepended to the pinned set). Pins override auto-discovery for the same slice name; a pin naming a slice installed at a DIFFERENT version attaches the pin exactly.
Payload-level pins (store-config schema_minor 5, tebako#667): a defaults: KEY of the form <registry>/<payload> pins every entrypoint the payload declares — the one-line form of "this machine runs metanorma 1.16.9" for a 31-entrypoint suite:
defaults:
"metanorma/metanorma": {version: 1.16.9} # all 31 entrypoints
metanorma-iso: {version: 1.16.8} # specific beats generalFigure 41 Version selection is a property of the payload, not of the command name; the payload pin sits in the user-default tier (env and project pins — per-tool by design — still beat it, as does a command-level defaults: entry for its own command). The registry alias rides the KEY (the value's registry: field would duplicate it — a payload pin carrying one is the named grammar error); the value carries version: only (slices: is per-tool). A version-less payload pin only scopes the payload's registry-default lookup (link 4) to the key's alias — the same rule as the tool form's registry-only entry. Two payload pins naming the same payload with different versions are the named ambiguity error, never a silent winner; a /-carrying key outside the grammar is the named grammar error at dispatch. tebako-shim doctor checks payload pins for dangling payload/version references exactly like qualified tool pins.
5. Distribution forms (both produced by tebako press)
Standalone tpkg (always per-platform): self-contained executable for users WITHOUT tebako.
Registry payload (.tfs + registry metadata): for dispatcher users — ONE universal image when pure-language; per-triplet variants only for native-extension apps.
6. Retirement gate
When tebako-shim ships, mnenv retires; metanorma becomes the first dogfood consumer (heavy native-ext app proving the whole stack: press → signed .tfs per (version × ruby line) → registry → dispatcher).
7. Errors (named)
No compatible cached/downloadable runtime → the spec 06 exit 69 shape.
Native-ext payload on a wrong-ABI-line runtime → named compatibility error, never a segfault.
Shim target payload missing/corrupt → named error pointing at tebako doctor.
More than one ENABLED claim for a command (2026-09-05 amendment) → EX_TEBAKO_MANIFEST, naming every claiming payload; the hint names the routing verbs: pin <cmd>: <payload>@<version> in .tebako-tools.yaml, or disable one claim (tebako-shim disable <cmd> --of <payload>).
A payload-qualified chain value whose payload is not installed, or is installed but neither declares nor exposes the command → the NotAProvider named error (EX_TEBAKO_MANIFEST), naming the pin, the payload, and the chain link the pin came from.
A payload-only pin (payload@, empty version) → the grammar error (EX_TEBAKO_MANIFEST, §0): route out with tebako-shim disable <cmd> --of <payload>, never with an incomplete pin.
An unparseable chain value at ANY link (env, project file, config default) → the grammar error, naming the link and the value (spec 23 §14's env-parse rule, extended to every chain link) — never a silent skip to the next link.
A command whose only claims ride platform-skipped edges (spec 03 §2.3, schema_minor 9 — the edge's triplets: list does not cover this host) → the named "not available on this platform" refusal (EX_TEBAKO_UNAVAILABLE, 69), naming the claiming payloads — never the generic no-provider error, never a silent fallback.
Extension slices (schema_minor 10):
A CONFIG-PINNED slice whose augments constraint fails the resolved base, whose language/abi edge fails the resolved runtime, or whose named extension_point the base does not declare → SliceIncompatible (EX_TEBAKO_MANIFEST), naming the slice, the pin's source link, and the failed check. (Auto-discovered slices fail SOFT — loud skip + journal; only pins fail hard.)
augments on the root payload's own manifest, or a slice whose mount would nest under another slice → NestedAugment (EX_TEBAKO_MANIFEST). Slices attach to the root payload, full stop.
A slice fetch that misses offline (TEBAKO_OFFLINE=1, pin not in the store) → the spec 05 cache-or-error shape, naming the slice.
8. Native exec from inside an image (the whole-chain model, locked)
Running a NATIVE executable from a mounted payload raises two problems: the exec'd binary loses the VFS view (it sees the host), and its dynamic dependency chain must resolve. Old tebako never solved this (its memfs was ruby-only; metanorma-on-tebako required host-installed inkscape). The locked model is three tiers — interposition-first, never FUSE:
Dynamic native tools (the mainline): the preload interposition shim — libtfs-preload, injected via LD_PRELOAD (ELF), DYLD_INSERT_LIBRARIES (Mach-O), or DLL injection (Windows), mapping the libc/dyld file-IO family (open/stat/opendir/pread/dlopen…) onto tebako_fs_*. The launcher seeds the mount table via env (TEBAKO_TFS_MOUNTS=image[:slot]:mount,… — grammar in spec 17 §2.1); the binary AND its whole dynamic chain see the mounted image — no extraction, no chain problem. retrace (in-family: linux/macOS/windows CI, v2 config-driven interception) is the reference technique. Bonus: interposed IO flows through the same host_policy — jails extend to these binaries (spec 08). Limit: dynamic binaries only; the shim is a TFS consumer, never a format. SHIPPED (roadmap 30): crates/libtfs-preload + tfs exec <image>[:mount] [--image …] [--jail <spec>] -- <cmd> in tfs-cli — macOS and linux-gnu first-class, windows later. Coverage (roadmap 39): interposed surface open/openat/creat(the tebako#444 audit's adjacent-write finding: creat(3) IS open(O_WRONLY|O_CREAT|O_TRUNC) spelled as its own libc symbol — glibc builds it over libc-internal open aliases and libSystem gives it its own stub, so un-interposed it bypassed the write gate everywhere; it routes exactly like a write-mode open: a memfs-held path is EROFS, a host path is policy-gated before the real creat runs)/stat/ lstat/fstat/fstatat(+fstatat64/statx/_xstat/_lxstat/fxstat/ fxstatat and the LFS open64/stat64/lstat64/fstat64/pread64/lseek64 family and the pre-2.33-glibc versioned _xstat64/_lxstat64/ fxstat64 forms and the _FORTIFY_SOURCE read_chk wrapper on linux)/access/faccessat/opendir/readdir(+readdir64)/ readdir_r/rewinddir/telldir/seekdir/dirfd/closedir/pread/read/lseek/ mmap(memfs fd → private anonymous mapping pre-filled from the VFS, +mmap64 on linux)/ close(+the plain and $NOCANCEL spellings on x86_64 darwin — the libc crate maps libc::close to close$NOCANCEL there, C binaries (the JVM's libjava/libjli/libzip) import plain close; both route to the shim)/dup/dup2(tebako#534 — libxml2's xmlInputFromFd calls dup(fd) unconditionally, so every VFS fd died EBADF there: the clone lands on a shim-managed flagged fd carrying the SAME open-file description — the offset is shared, per POSIX; dup and fcntl(F_DUPFD) leave FD_CLOEXEC off the clone, F_DUPFD_CLOEXEC sets it; dup2 atomically closes a live memfs target and rebinds the number to the source's description (the target resolves to the same VFS file), and dup2(fd, fd) is the liveness-checked no-op; a memfs source with a HOST-numbered dup2 target is the named error ENOTSUP — the fd routing keys on the flag bit, so a host number can never name a memfs description — never EBADF-by-default; a dead memfs fd is EBADF, the kernel's own answer; host-numbered dup/dup2 sources pass through untouched)/fcntl(the descriptor commands on a memfs fd are served from the shim's own fd table — open/openat seed the close-on-exec bit from O_CLOEXEC, F_GETFD/F_SETFD read/write it, F_GETFL answers the truthful read-only status word, F_SETFL is an accepted no-op, a flagged-but-closed fd is EBADF, the dup-class commands F_DUPFD/F_DUPFD_CLOEXEC clone the open-file description exactly like the dup/dup2 shims above, host fds pass through untouched — CPython's io.FileIO boot path fcntls every fresh source fd with raise=1, so unshimmed the interpreter died importing encodings before any user code)/fopen(tebako#444: read-only modes (r with no +) materialize the memfs original through dlmap2file exactly like dlopen — stdio's internal open path never touches the interposed open; the write-ish modes (w/a bases, every
update form incl. r+, the x-forms) ride the SAME spec 08 write
gate as open(O_WRONLY|O_CREAT|O_RDWR) BEFORE the real fopen touches the host — a memfs-held path is EROFS, a jailed write outside an rw grant is EPERM by name; pre-fix the write modes sailed through ungated and r+ was misclassified as a read)/mkdir/unlink/rename + dlopen + execve/posix_spawn/posix_spawnp
the realpath family (realpath, plus macOS's realpath$DARWIN_EXTSN;
canonicalize_file_name and the fortified __realpath_chk on linux): glibc's realpath(3) walks the path with libc-INTERNAL stat/readlink aliases no PLT interpose sees, so a covered path MUST be answered by the shim with the MOUNT spelling — the in-image link hops resolved (spec 11 §9's rule: ELOOP past 32, a dangling link ENOENT) and the result lexically normalized. The host resolver's canonicalization must never rewrite a VFS path (the 2026-09-03 dogfood linux-gnu jing ClassNotFound: usrmerge /lib→usr/lib leaked into the JDK's URLClassPath on a root-mounted payload, and the jar lookup silently dropped a byte-perfect jar); covered-but-not-held paths still pass to the host realpath (the /etc/localtime discipline); TEBAKO_JAIL carries the spec 08 §1 env form (open|deny + host:mount:ro|rw grants + @ argument files); the ENTRYPOINT (when in-image) is materialized through dlmap2file (execve needs a host path — one copy per exec, gc later), and execve/posix_spawn of MEMFS paths materialize the same way (a tool spawning an in-image helper needs no extraction; environ propagates, so grandchildren stay in the VFS); every *at shim gates its fd branch on dirfd >= 0 (AT_FDCWD carries the fd-flag bit — the runtime-builds regression class, pinned by tests); the mmap shim gates on fd >= 0 and !MAP_ANONYMOUS (fd -1 carries the same bit — the JVM PaX-check regression class); exec of a HOST binary is not policy-gated (not an IO route in the policy's op classes — the child's own IO stays jailed via env propagation); SIP platform binaries strip DYLD_* and leave it; a mount at / is legitimate under the union mount model (spec 03 §6 / spec 17 §1 — the app payload mounts there): covered-but-not-held paths fall through to the host with the jail consulted; fork is not interposed but its child side is GUARDED — a pthread_atfork child handler arms a process-global flag and every shim's engine entry passes through to the real libc while it is set (the backends are not fork-safe: dwarfs-t's block-cache worker pool dies at fork, so a backend-touching call in the child — e.g. the execve materialization probe under a / mount — would wait on threads that no longer exist; the 2026-08-22 git-clone deadlock, runtime 0.16.4); glibc runs NO atfork handlers for vfork(2), and a vfork child shares the parent's whole address space with the parent thread suspended in the kernel, so the guard carries a PID backstop — the constructor records the initializing pid, and an engine entry under a different pid is a fork/vfork child in its pre-exec window and passes through exactly like the atfork flag's child (the 2026-09-03 dash vfork deadlock in the dogfood repro; exec preserves the pid, so the exec'd image's constructor re-stores the same value and the gate re-opens at exec); and a fork child that execs re-enters a fresh shim through the inherited preload env, so the grandchild rule above is unaffected; not interposed: fork, dup3 (linux-only, no tier-1 consumer — its flags argument would need the cloexec plumbing the POSIX dup class already has), openat2 (glibc exposes no wrapper or symbol on linux-gnu — nothing to interpose; a raw syscall(2) caller bypasses userland interposition by construction), fstatat64 on macOS (the legacy 32-bit-inode layout), __fxstatat64 and the write-side pwrite64/ftruncate64/statvfs64 family plus readv/preadv/sendfile/copy_file_range on memfs fds on linux, fdopendir (memfs directories are never fd-opened), the internal-walk family glob/nftw/ftw/wordexp (UNAUDITED — their path walks ride libc-internal aliases, the same bypass class as realpath; no importer observed on the JDK/ruby boot paths, so this is pinned debt, never silently assumed covered), and syscall()-direct IO (raw syscalls bypass userland interposition by construction); dirfd of a memfs stream answers -1/ENOTSUP; getdents64 on a memfs fd answers ENOTDIR (VFS directories enumerate via opendir, never fds).
Static/self-contained tools: tebako is the EXECUTOR, not an injector — it spawns and owns every child, so mediating a child's syscalls is the execution contract itself, not hijacking (a side-loader would need to BECOME the executor or the kernel to hold the same position — outside the threat model by definition). As the executor, tebako mediates statics two ways: (a) Kernel-mediated VFS (Linux, tier 2a): SECCOMP_RET_USER_NOTIF — the executor installs a seccomp filter at spawn; the kernel forwards the child's file syscalls (openat/statx/…) to the executor, which serves them from the mounted TFS images and enforces the same host_policy (spec 08) — full VFS + jails for static binaries, no extraction, child unaware. Cost: per-syscall user/kernel round trips (io-heavy tools notice); platform: Linux only (the API does not exist elsewhere). (b) Extract-to-exec-cache (everywhere, tier 2b): ~/.tebako/exec/<sha256>/…, 0755, verified at install — the manifest-declared closure, content-addressed, shared. On macOS/Windows (no executor-side syscall mediation API) this is the static path; such binaries see only the host FS (no VFS, no jails — a platform-API statement, not a trust statement). Nuances: a static binary BUILT against the tebako_fs_* ABI carries the VFS inside itself (the "libtfs for everyone" embedding story — build-time property, not imposable on an arbitrary binary). Prefer tier 1 (dynamic) for io-heavy tools; tier 2a covers the rest on Linux.
Interpreted payloads (ruby): in-process io-routing patches virtualize file IO — the existing mechanism, no exec at all.
FUSE is NOT an exec mechanism. It remains an optional, host-dependent HUMAN convenience (tfs mount, spec 11 access matrix #2) — never on the package/exec path. (Correction 2026-07-26: tebako has never used FUSE; interposition is the tebako way.)
ptrace/syscall-tracing (retrace-v1-style tracing for vulnerability research) is a debugging tool, not an exec foundation.
8a. The virtual cwd (tebako#734)
Decision: virtual-cwd, named-limitation floor. The process's cwd is tracked as a VFS-aware value: chdir(2) into a mounted path SUCCEEDS (the preload interposes it and records the VFS point); every relative-path interposition resolves against the tracked cwd — a VFS cwd makes relative paths route into the image, a host cwd keeps today's behavior. The floor until each surface lands: a surface that cannot yet honor a VFS cwd fails with a NAMED EXDEV-class error naming the cwd ("cwd is a VFS path this operation does not serve"), never a bare ENOENT that reads as image corruption.
press -c/--cwd: the generated stub may Dir.chdir into the VFS (the feature was broken-broken before — bare ENOENT on its own stub); the stub's chdir now succeeds and the interpreter's relative loads resolve in-image.
The pre-existing assumption retires (route.rs: "the cwd is always host"): every current_dir()-based relative resolution in the preload joins the VIRTUAL cwd when one is set.
Bundler's git source (the #119 reporter): SharedHelpers.chdir into the checkout now works in-image.
Host escapes: chdir("..") past the VFS root reaches the host parent exactly as a path op would (the jail policy governs); no new wall is invented.
9. Environment composition (locked 2026-07-27)
Env across the mount stack (runtime + toolkit layers + data layers + app) composes by RULE, never by accident:
Path-class vars (GEM_PATH, PATH-in-image, TEBAKO_LD_PATH): app payload first, then toolkit layers in requires order, then the runtime — earlier wins. The runtime's own defaults come LAST (it is the fallback, not the override).
Scalar vars: the app's manifest wins over toolkit, toolkit over runtime; the dispatcher's computed values (TEBAKO_RUNTIME_IMAGE, TEBAKO_TFS_MOUNTS, jail env) always win over every manifest.
Host env scrub: on handoff the dispatcher removes the variables the press scrubbed (RUBYOPT/RUBYLIB/BUNDLE_* — the M7 scrub list) so the host environment never leaks semantics into the payload; other host vars pass through unless the jail says otherwise.
Per-entrypoint overrides (suite entries, spec 03 §6) apply last for that entry only.
9.1 The interp_env chain (IMPLEMENTED 2026-10-07 — tebako#559; spec 03 §2.7)
Interpreter-option defaults compose by their own chain, parallel to the rules above and NEVER through the M7 scrub (interp_env keys are interpreter options, not rubygems semantics — they are never scrubbed). Per dispatched entry, per declared key, FIRST SET wins, highest layer first:
User process env — the operator's invocation environment. A key already set there is the user's explicit choice: it always wins and is never rewritten.
User config — ~/.tebako/config.yaml's per-tool env: map (spec 07 §4; store-config schema minor 3): the operator's standing local policy for one tool.
Package manifest — entries[].interp_env (spec 03 §6), the standalone/package form only: the packager's press-time refinement (already composed with the slice's L1 declarations by the press). Managed dispatch has no L2 — this layer is absent there by construction.
Payload manifest — the slice author's L1 interp_env: (spec 03 §2.7), read from the store's manifest mirror in managed dispatch.
Interpreter built-in — what the interpreter does when nothing declares the key (the declaration is a default, never a requirement).
The dispatcher computes the effective map at dispatch and exports each winning key that is NOT already in the process env (layer 1's win is passive: the variable is simply there). No key is ever scrubbed, rewritten, or guessed; an unset-declared key stays unset (never a synthesized "0"). The effective map and each key's provenance layer are reportable through the spec 15 §4 surface — resolution is auditable, never silent. The standalone bootstrap reads no store config — the managed shim owns that tier — so a stitched package's chain is process env over the package manifest (layers 1 and 3; layers 2 and 4 are absent by construction).
10. The runtime-own command surface (DRAFT — the user-direct grammar)
A runtime's own tools (the interpreter itself, its package manager, its loaders) are first-class commands, not only what a payload's expose: edge re-exports. The factory's env image declares the runtime's entrypoints (the additive entrypoints list — spec 30 §2; the node factory declares node/npm/npx/corepack; the bun factory bun/bunx; the openjdk factory java/keytool/…); the user reaches them directly:
tebako run <engine>[:<command>] [<args>…]
The bare form (tebako run node) runs the runtime's DEFAULT entry (the interpreter — the env image's layout.interpreter), with the args handed verbatim.
The command form (tebako run node:npm) resolves the named entrypoint in the runtime image's declared entrypoints — an undeclared name is a named error listing the declared set, never a guess.
The run target grammar (MECE, locked). tebako run has exactly two target classes, decided on the first positional token, in this order:
A token naming an existing file is a package — the §2/pkg surface of this verb, unchanged. (A windows drive path always lands here while the file exists; spell the engine form for the engine.)
Otherwise the token parses as <engine>[:<command>] — the engine grammar: <engine> is the runtime payload's engine key (spec 04 §2 MINOR 1 — bare lowercase name), <command> one of the resolved runtime's declared entrypoints. A token that is neither an existing file nor a well-formed engine reference is the §7 usage error, naming the token.
A token is never both: the file reading is total (a file either exists or not), the engine reading applies only when no file answers. A bare engine name shadowed by a same-named file in the cwd is reached by the command form (tebako run node:node) — deterministic, journaled, never a silent pick.
Resolution: the engine resolves against the store FIRST (the newest compatible cached runtime), then the registries (download, verify, cache — the same fetch path as every payload's runtime requirement). The version chain per engine: TEBAKO_<ENGINE>_VERSION env → the nearest .tebako-tools.yaml → ~/.tebako/config.yaml's defaults: → the registry's newest. All local surfaces, never a registry-side route (the provider-routing rule above). The engine name matches a registry entry's engine key, never a display name; no configured registry carrying the engine is the §7 no-such-engine error.
Dispatch: the handoff is the spec-17 wire exactly — the wrapper exe with TEBAKO_RUNTIME_IMAGE=<env image> + --tebako-entry <command> (or the bare form's default) + the user args; the driver composes [interpreter, <the entrypoint's args_default…>, <entry>, <args>…] per spec 29 §1. This surface parses NO flags: every token after the engine reference is the engine's own argument, verbatim (a --jail there reaches the engine, never tebako). The jail posture is the user's own policy riding TEBAKO_JAIL in the inherited environment (the driver enforces it per spec 17), open by default — a runtime-own command is the user's own process, not a payload's.
The shim surface: tebako install <engine>[:<command>] registers shims/<command> (the default entry's name for the bare form — node, bun, java) dispatching argv0 → the engine's runtime resolution → the same spec-17 wire. The install target's engine reading WINS a bare engine-shaped token it answers (a cached runtime of the engine, a config runtimes: preference, a registered registry's kind: runtime entry carrying the engine, or the ruby default); a same-named payload stays reachable through its qualified forms (<alias>/<name>, the reference forms). Collision rule (MECE): a PAYLOAD-provided name wins over a runtime-own name of the same spelling (the payload declared the tool; the runtime surface is the fallback when no payload provides it) — the provider-routing surfaces of §2 answer collisions locally, never by registry. A runtime-own shim records its engine class in the shim metadata (shims/.runtime-own.yaml, command → {engine, entry} — the entry is the wire token: self for the bare form, the command name otherwise), so tebako shim list/disable answer the class explicitly and a later payload install claiming the name displaces the runtime-own claim with a loud notice (never a silent shadow). The §0 disable selectors gate a runtime-own claim through the engine riding the payload slot: all and <engine>@all refuse the dispatch by name; a bare version selector has no axis to gate (the engine's version chain owns versions).
The presses stay honest: a runtime-own shim name never ships a binary — the shim is the link; a press that bundles its own tool keeps the payload-provided name (the payload wins the name by the collision rule above).
Errors (named, §7's table extended):
No configured registry carries the engine, and the store holds no runtime declaring it → EX_TEBAKO_UNAVAILABLE (69), naming the engine and every registry consulted — the no-default-service rule makes "unknown engine" and "known but unreachable" the same shape.
The command form naming an entrypoint the resolved runtime's env image does not declare → EX_TEBAKO_MANIFEST, naming the engine, the asked command, and the declared set.
TEBAKO_OFFLINE=1 with no compatible cached runtime → the spec 05 cache-or-error shape, naming the engine.
A malformed engine reference (node:, :npm, an engine name outside the name grammar) → the §7 usage error, naming the token.
TBK SPEC 18 — The Contract Graph
Status: normative · supersedes the compatibility parts of specs 06 and 17 Date: 2026-08-01
The law: nothing is read until it breaks. Every interface in the ecosystem has exactly ONE owner, ONE declarative YAML contract (a versioned schema), and ONE verification point. Consumers verify fail-closed before execution; a mismatch is a named error naming both sides. Anything undeclared is pre-era (era 1) and is refused by name — never assumed, never silently served.
This document is the complete map: every component, every interface between them, the declarative contract on each interface, the evolution law for every schema, and the scenario catalog that each rule must answer. Nothing cross-component may exist outside this map.
1. The full contract graph
Boxes are components (artifacts or actors). Every arrow is a contract edge labeled with its declaration document. Edges are directed: owner → consumer.
┌────────────────────────────────────────────────────────────────┐
│ tamatebako/ruby — SOURCE FACTORY │
│ out: patched src tarball (tebako-mount-root, SHA256SUMS) │
└───────────────┬────────────────────────────────────────────────┘
│ C1 tarball-layout.yaml
▼
┌──────────────┐ C19 ┌───────────────────────────────────────────────┐
│ vcpkg │───────▶│ tebako-runtime-ruby — RUNTIME FACTORY │
│ baseline │ tags │ builds: runtime exe + env image │
└──────────────┘ │ in: link unit (tebako-rs artifact) │
│ out: runtime release (exe, image, manifest) │
└──────┬───────────────┬───────────────┬────────┘
│ C2 release- │ C3 exe↔image │ C4 link-time
│ manifest.yaml │ (layout.yaml) │ (c_api.h, fs TU)
▼ ▼ ▼
┌──────────────┐ ┌─────────────┐ ┌───────────────┐
│ registries / │ │ runtime exe │ │ static libs │
│ release idx │ │ (driver in) │ │ (driver, tfs) │
└──────┬───────┘ └──────┬──────┘ └───────────────┘
│ C12 │ C5 handoff (spec 17,
│ registry.yaml │ argv/env — contract_version)
▼ │
┌─────────────┐ C13 store ┌─────────────────▼───────────────────────┐
│ store │◀──────────────│ LOADER FAMILY │
│ (~/.tebako) │ │ bootstrap · shim · cli · tfs-cli │
└──────┬──────┘ └───┬────────┬─────────┬────────┬─────────┘
│ C13 │ C6 │ C7 │ C8 │ C9
▼ ▼ ▼ ▼ ▼
everything local package payload registry runtime
trailer manifests release manifest
┌────────────────────────────────────────────────────────────────────────┐
│ PAYLOADS (all slices share the L1 in-image manifest contract) │
│ ┌──────────────┐ ┌──────────────┐ ┌───────────────┐ │
│ │ executable │ │ data │ │ feature/ │ │
│ │ payload │ │ payload │ │ toolkit │ │
│ │ (entrypoints)│ │ (no entries) │ │ (libs/exes │ │
│ │ │ │ │ │ at paths) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬────────┘ │
│ │ C10 runtime_requirement │ C11 provides-C-ABI │
│ ▼ ▼ ▼ │
│ runtime consumers consumers │
└────────────────────────────────────────────────────────────────────────┘
┌────────────────────────────────────────────────────────────────────────┐
│ TRUST: signer → package (C14 v2 signature block) │
│ verifier → trust anchors / keys (C15 key ring + rollover) │
└────────────────────────────────────────────────────────────────────────┘
The driver inside the runtime exe mounts the env image (C3) and each payload image (C7), installs the jail, and hands the interpreter its argv — the interpreter's io shims consume the tfs C API (C4), whose header is the pinned contract both sides compile against.
2. The declarative contract model
2.1 Every interface has a YAML contract document
Two kinds of YAML exist and must not be conflated:
Schemas — the grammars themselves, versioned, living in ONE registry: docs/spec/schemas/<name>.yaml in the product repo. Each schema file carries schema: <name> and schema_version: <int> and the evolution metadata (§3). This directory is the single source of truth for every grammar in the ecosystem.
Declarations — the per-artifact YAML instances conforming to a schema (in-image manifests, layout.yaml, release manifest, tpkg-registry.yaml, the package L2 block, config.yaml).
Every producer validates its declarations against the schema it owns in its own CI; every consumer validates before use and refuses invalid input with a named error.
2.2 The contract set per component type
| Component | Declares (schema in docs/spec/schemas/) |
|---|---|
| tebako-bootstrap (binary) | an embedded self-description block (artifact-info.yaml appended at build): era, version, launcher_abi spoken, contract_version spoken |
| runtime exe | runtime-manifest.yaml (in the release): era, contract_version, mount_root, abi, image_layout, interpreter + version, built-from (source release + sha) |
| env image | in-image /lib/tebako/layout.yaml: era, image_layout, mount_root, interpreter api version |
| executable payload | L1 payload-manifest.yaml: era, identity, provides (entrypoints × per-entry runtime_requirement × abi facets), requires (closure edges × mount points), jail defaults |
| data payload | L1 payload-manifest.yaml: era, identity, version, content class, mount suggestions, requires |
| feature/toolkit payload | L1 as executable plus provides_abi (C ABI name+version at an in-image path, e.g. the crypto toolkit) |
| package (tpkg) | header (binary, unchanged) + L2 package-manifest.yaml block: era, pressed_by, reader_era required, composition summary |
| registry | tpkg-registry.yaml: schema_version, entries (name, versions, artifacts × abi, refs, defaults) |
| store | ~/.tebako/layout-version + config.yaml schema |
| source tarball | tebako-mount-root + versions.yml schema + SHA256SUMS |
| release manifest (product) | manifest.json per tebako-rs release: platforms, sizes, sha256, era |
| vcpkg baseline | tag grammar + canonical-root map (restore script) — not YAML, owned grammar |
| dwarfs_c ABI | dwarfs_c_abi_version() — C header, not YAML, version export |
| tfs c_api | c_api.h with layout asserts — C header, compile-time contract |
| handoff (spec 17) | TEBAKO_CONTRACT_VERSION env export + this spec — argv/env, machine version via env |
3. The schema evolution law
Every schema in the ecosystem obeys these rules. No exceptions, no local dialects.
Two numbers, one meaning. schema_version is a single integer MAJOR; schema_minor an additive counter. MAJOR breaks, MINOR adds.
Readers ignore unknown fields within their MAJOR — but must not invent semantics for them. A field you do not understand changes nothing you do.
Unknown MAJOR is a named refusal. Message: artifact, its schema
version, consumer, its max spoken version, "upgrade". Exit code per §7.Missing schema_version = era 1. A named refusal — "pre-era document; regenerate with a current tool" — never a silent default.
Type changes are MAJOR. No silent coercion (string→list, int→string, kebab→snake). Authors wanting a rename: see the deprecation window.
Deprecation window. To rename/retype a field inside one MAJOR: writers emit BOTH old and new for two consecutive MINOR versions (deprecated: <field> noted in the schema); readers prefer new and warn on old; after two MINORs the old field is dropped in the next MINOR. The schema records the window dates.
Critical extension. Any container that skips unknown entries (tpkg extension blocks, manifest provides/requires entries, jail rules) supports critical: true on an entry: a reader that does not understand a critical entry must refuse with a named error instead of skipping it.
Lists stay lists. No keyed-maps for ordered/multiplicity data (owner rule, existing convention) — entries carry their identity fields (e.g. version:), never map keys.
YAML for everything authored (invariant 6 unchanged); JSON Schema documents the shape; CI validates producers against it.
3.1 The field lifecycle
MINOR +1 MINOR +2 MAJOR +1
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ field added │ rename? │ old+new both │ after │ old dropped │
│ (additive, │ ───────▶ │ written; old │ 2 MINORs │ entirely; │
│ readers skip)│ │ deprecated │ ───────▶ │ readers of │
└──────────────┘ └──────────────┘ │ old MAJOR │
│ are refused │
└──────────────┘
4. Every interface, in full
For each edge: owner → declaration (schema) → consumer verification → refusal. (C-numbers match the graph.)
C1 · source tarball → runtime factory
Owner: tamatebako/ruby. Declaration: tebako-mount-root + the versions.yml schema + SHA256SUMS. Verify: factory source fetcher at configure — manifest absent/corrupt → exit 132 ("pre-era or corrupt source tarball — roll a new one with tamatebako/ruby ≥ v0.2.13").
C2 · runtime factory → loader (the release card)
Owner: tebako-runtime-ruby. Declaration: runtime-manifest.yaml (era, contract_version, mount_root, abi, image_layout, interpreter+ver, exe sha ↔ image sha, built-from). Verify: loader before download — era-1 manifest → refusal; contract_version > spoken → exit 75; abi mismatch → resolution keeps searching, then named error.
C3 · runtime exe ↔ env image (the pair)
Owner: the factory. Declaration: in-image /lib/tebako/layout.yaml (era, image_layout, mount_root, interpreter api). Verify: driver, post-mount, before ruby init — layout missing → era-1 refusal; layout mismatch vs the exe's compiled expectation → exit 78.
C4 · exe ↔ static libs (tebako_main, mount point, c_api)
Owner: the factory + c_api.h. Verified at build: layout asserts both sides (compile = the check) + factory CI nm provenance assert (tebako_main resolves from the fs TU, never the stub). No runtime dimension (one exe bundles both).
C5 · bootstrap → runtime (the handoff)
Owner: spec 17 (unchanged grammar). Machine version: TEBAKO_CONTRACT_VERSION export + the release manifest (C2). Verify: the negotiation (era/contract) happens in C2's step, before download — never after exec.
C6 · loader → package trailer
Owner: tpkg. Declaration: header (format, launcher_abi, flags) + L2 package-manifest.yaml (era, pressed_by, reader_era, composition). Verify on open: unknown format/launcher_abi/flag → named error; era mismatch → exit 77 both directions; unknown critical extension block → refusal (invariant 7 covers only non-critical).
C7 · driver → payload images
Owner: the package's L2 composition + each slice's L1. Verify: duplicate mount → EEXIST; any failure → unmount-all + named error (spec 17 unchanged); unknown format_id → named error; encrypted with no toolkit → capability refusal.
C8 · loader → registry
Owner: the registry schema. Declaration: tpkg-registry.yaml (schema_version). Verify on read: missing version → era-1 refusal; newer MAJOR → upgrade refusal; entry abi mismatch → filter.
C9 · loader/shim → runtime release manifest
= C2 (the release card is the complete pre-download contract).
C10 · executable payload → runtime
Owner: the L1 manifest. Declaration: per-entry runtime_requirement (version range for pure-language; ABI line for native-extension)
abi facets. Verify at dispatch: unsatisfiable → named error naming the entrypoint and the requirement (never a segfault).
C11 · feature payload → consumers
Owner: the L1 manifest. Declaration: provides_abi (name, version, in-image path) — a consumer (e.g. the bootstrap loading the crypto toolkit) binds only when the ABI matches, with both versions printed on mismatch.
C12 · everything → registries
= C8 plus publisher-side validation: tebako publish validates the registry against the schema before pushing (producer-side CI).
C13 · everything local → store
Owner: the store-layout module (one crate). Declaration: ~/.tebako/layout-version + config.yaml schema. Verify on first access per process: newer → upgrade refusal; older → the named migration (never a silent mixed layout).
C14 · signer → package
Owner: tebako-signer. Declaration: the v2 signature block (in the canonical signed region) + key ids. Verify: strict whenever signed (unchanged); unsigned is loud-but-first-class (unchanged); TEBAKO_REQUIRE_SIGNED fails closed (unchanged).
C15 · verifier → trust anchors
Owner: the root ceremony (trust dir layout, key rollover). Declaration: key ring with per-key ids + validity eras; old artifacts verify against the key that signed them; revoked key → strict failure naming it.
C16 · feedstock → product tools
Owner: tebako-packages/index. Declaration: Tebakofile (schema_version) + the product release the feedstock pins (currently tracks main — a drift bomb; pin the 2.0 release tag).
C17 · jail declaration → enforcement
Owner: tpkg::jail + the driver. Malformed → exit 73 (unchanged); unknown jail directive → named error (no silent drops).
C18 · preload shim ↔ driver (spawn re-entry)
Owner: the driver (TEBAKO_TFS_MOUNTS grammar — the slot form included, spec 17 §2.1; the trailer data source is tpkg::read_from). Verify: unparseable → fail closed, never a half-mounted child; a packaged payload's slot survives the hand-off (the child mounts the slot region, never the whole package file).
C19 · vcpkg baseline → consumers
Owner: dwarfs-t. Grammar: tag + canonical-root map (the restore script is the single reader). Verified: tag presence + SHA256SUMS.
C20 · dwarfs-rs ↔ dwarfs-t FFI
Owner: dwarfs-t header. New: dwarfs_c_abi_version() checked at bind with both numbers printed on mismatch.
5. The scenario catalog
Each rule above is accountable to these cases. Each names the expected behavior. (S-numbers are the e2e/test ids to implement.)
5.1 Bootstrap × package
S1 package era > bootstrap era → refuse: "package from a newer tebako (era 3) — upgrade your tebako (speaks era 2)".
S2 era-1 package (no L2 contract block) → refuse: "pre-era package — re-press with tebako ≥ 0.16.1 or run with tebako v1".
S3 launcher_abi unknown → named error, both values.
S4 unknown flag bit set (e.g. a future ENC_V3) → refuse: flags are load-bearing, never skipped.
S5 slot format_id unknown → named error.
S6 TEBAKO_OFFLINE=1 and the runtime is uncached → named error (cache-or-error, exists).
S7 signed package, no toolkit → unverified-first loud warning
journal; TEBAKO_REQUIRE_SIGNED=1 fails closed (both exist).S8 two slots declare the same mount → EEXIST, no partial mount.
S9 a slot mount == the runtime root → named collision error.
S10 unknown critical extension block → refusal; unknown non-critical block → skipped (invariant 7).
5.2 Loader × runtime
S11 release manifest lacks contract fields (era 1) → refusal before any download: "runtime release is pre-era — rebuild with the current factory".
S12 runtime contract_version newer than the loader speaks → exit 75, both numbers.
S13 payload slot mount == runtime root → the C7 collision error (surfaces at boot, named).
S14 env image layout ≠ exe expectation → exit 78 (C3).
S15 sha256 mismatch on download → exit 70 (exists).
S16 locally built runtime (side-loaded directory): must carry the same manifest fields, else era-1 refusal — no special pleading.
5.3 Driver × env image
S17 layout.yaml absent → era-1 refusal.
S18 layout.yaml newer MAJOR → upgrade refusal.
S19 layout.yaml mount_root ≠ exe fs_mount_point → exit 78 (mismatched pair, never a ruby LoadError).
S20 missing stdlib content inside a well-formed image → content bug (factory boot-smoke's domain), NOT a contract case — the contract layer does not mask it.
5.4 Driver × payloads
S21 duplicate mount across payloads → EEXIST, unmount-all.
S22 payload mount nested INSIDE another mount's tree → legal (spec 17); longest-prefix dispatch; jail sees the union.
S23 payload image backend this driver lacks → named error ("format X unavailable in this build").
S24 encrypted payload, crypto toolkit absent → capability refusal (named; install the toolkit).
S25 entrypoint missing in the image → named error with the expected path.
S26 entrypoint's runtime_requirement unsatisfiable → named error (never a crash).
5.5 Shim × payloads
S27 two installed payloads PROVIDE the same command → the registered owner wins; tebako install of the second names the conflict; explicit tebako shim enable/disable overrides (exists).
S28 version chain: TEBAKO_<TOOL>_VERSION → nearest .tebako-tools.yaml → config defaults: → registry default (exists, unchanged).
S29 shim points at a removed payload version → named error listing installed versions.
S30 entrypoint needs a runtime with no compatible cached copy → download+verify+cache, or offline named error.
S31 one package with two entrypoints needing DIFFERENT runtimes (e.g. ruby tool + java tool) → per-entry resolution against each entry's own requirement (grammar already supports it; e2e proves it).
5.6 Payload × payload
S32 requires cycle (A→B→A) → named cycle error at install.
S33 unsatisfiable range (B >= 2, only B 1.x published) → named error naming both.
S34 nested composition (A mounts B, B mounts C inside) → legal; resolved deepest-first.
S35 required entrypoint renamed upstream → unsatisfiable named error at install (the closure check is content-aware).
S36 abi facet mismatch (abi: arm64-darwin-23 on x86_64) → resolution filters, then named error if nothing remains.
S37 data payload version requiring newer registry schema → C8's refusal.
S62 shared slice unresolvable at run time (uncached + offline, or no compatible artifact) → the loader's named resolution error BEFORE the handoff; the boot never starts (carried slices have no such case).
S63 locked-digest mismatch on a shared slice (registry bytes ≠ the press-time lock) → fail-closed trust refusal (exit 70 class): the lock is the pin, never fresh semver (spec 23 §4/§13).
S64 crash mid-lazy-seed → tmp+rename keeps the partial seed invisible; the run is unaffected; the next run re-seeds (spec 05 §4).
S65 a requires: edge whose triplets: list does not cover the host (spec 03 §2.3, schema_minor 9, roadmap 86) → the edge is SKIPPED (no resolve/fetch/install/lock row/mount/spawn surface) with a loud journaled note (event=edge-platform-skip), never an error; dispatch of its exposed name → the named "not available on this platform" refusal (exit 69), never a silent fallback. kind: language carrying triplets: → named parse error steering to platforms:.
5.7 Press × inputs
S38 TEBAKO_BOOTSTRAP override with an era-1 bootstrap binary → the press reads the binary's embedded artifact-info.yaml and refuses; a package is only ever stitched from a declared bootstrap.
S39 image format the writer can't embed → named error.
S40 output path exists → named error unless --force.
5.8 Store
S41 layout newer than the binary → upgrade refusal.
S42 layout older → the named migration runs or refuses explicitly; never a silent mix.
S43 lock held past 120 s → stale-lock hint (exists).
S44 crash mid-install → tmp+rename keeps it invisible (exists).
5.9 Registry
S45 schema newer MAJOR → upgrade refusal.
S46 no schema_version → era-1 refusal ("republish the registry").
S47 entry abi has no host match → filtered, named if empty.
S48 registry unreachable, cache older than 24 h TTL → the stale cache SERVES with a loud stderr warning + journal line (event=stale-registry-serve; spec 05 §4, roadmap 86) — the trust anchor is the artifact's .sha256/.asc at fetch time, never the registry's freshness; cache ABSENT → named error (exists).
5.10 Factory
S49 tarball without tebako-mount-root → exit 132.
S50 manifest with conflicting roots → named error (exists).
S51 link unit vs patches ABI drift → compile error + the nm provenance assert (the stub-shadow class).
S52 release publish with an incomplete asset set → the completeness gate fails (exists).
5.11 Trust
S53 signed artifact, key revoked → strict failure naming the key.
S54 root rollover → old artifacts verify against their signing key's era; new artifacts the new root; both declared in the key ring.
S55 TEBAKO_REQUIRE_SIGNED=1 with unsigned → fail closed (exists).
S56 tampered extension block inside the signed region → signature failure (canonical region covers it, exists).
5.12 Evolution (the schema lifecycle cases)
S57 reader meets unknown MINOR field → ignores it, semantics unchanged (regression-tested per schema).
S58 unknown MAJOR → refusal (S1's shape) per schema.
S59 field rename: two MINORs of dual-write, readers prefer new and warn on old, then drop (a schema records the window).
S60 field type change → MAJOR bump; no coercion anywhere.
S61 critical: true entry a reader doesn't know → refusal; non-critical → skip (S10's rule generalized).
6. The verification sequences
6.1 Run of a stitched package
bootstrap
├─ read trailer: format/abi/flags (C6) ───────── refuse(77)/named
├─ resolve runtime: registry (C8) → store (C13) → release card (C2)
│ ├─ era/contract check ───────────────────── refuse(75)
│ └─ download + sha256 + cache (trust at fetch, never per run)
└─ handoff (C5, unchanged grammar)
driver
├─ mount env image at exe root
├─ layout.yaml check (C3) ───────────────────── exit 78
├─ mount payloads (C7) ──────────────────────── EEXIST/unmount-all
├─ jail install (C17) ───────────────────────── exit 73
└─ argv → interpreter
6.2 Shim dispatch
argv0
├─ resolve payload + entrypoint (C12) ───────── S27/S29 errors
├─ version chain (S28)
├─ per-entry runtime_requirement (C10) ──────── S26/S30
├─ runtime release card (C2) ────────────────── refuse(75)
└─ exec runtime (C5 handoff)
6.3 Install / publish
tebako install <ref>
├─ registry read (C8) ───────────────────────── S45/S46/S48
├─ dep-walk the requires closure (C13) ──────── S32–S36
├─ download + verify + tmp/rename (S44)
└─ register shims (S27)
tebako publish
├─ validate declarations against schemas (C12)
├─ sign if configured (C14)
└─ push artifacts + registry entry
7. Exit codes (allocation)
| Code | Meaning | Raised by |
|---|---|---|
| 65–74, 76 | (existing loader codes) | bootstrap/resolve |
| 75 | runtime contract mismatch / pre-era runtime | loader, pre-download |
| 77 | package/payload contract-era mismatch (either direction) | any trailer/manifest reader |
| 78 | env image layout mismatch | driver |
| 79 | payload check FAIL aggregate (EX_TEBAKO_CHECK, spec 26 §2) | tebako check |
| — | ABI mismatch (C11 provides_abi, C20 FFI): named refusal, both versions printed; exit code unallocated — pinned at implementation | binder |
| 73 | jail malformed | driver |
| 132 | pre-era/corrupt source tarball | runtime factory |
8. Locked non-goals
No old-path readers. Era 1 is refused, not adapted.
No silent skipping of load-bearing fields. Non-critical skips are for decoration, never semantics (the critical rule).
No type coercion in readers.
No second grammar for the handoff (spec 17 stands; this is the declaration layer around it).
No per-run trust checks (fetch/install only, unchanged).
9. Implementation map (owner → work)
| # | Work | Owner |
|---|---|---|
| 1 | docs/spec/schemas/ registry: every schema above, with schema_version + evolution metadata | tebako-rs |
| 2 | tpkg L2 package-manifest.yaml block (era, pressed_by, reader_era) + reader enforcement (77) | tebako-rs |
| 3 | runtime release runtime-manifest.yaml full card (+ mount_root, image_layout) | tebako-runtime-ruby |
| 4 | in-image layout.yaml + driver check (78) | tebako-runtime-ruby + tebako-driver |
| 5 | loader pre-download refusal on missing contract fields | tebako-bootstrap/resolve |
| 6 | tebako inspect: the contract card + verdict for any artifact | tebako-cli |
| 7 | dwarfs_c_abi_version() + bind check | dwarfs-t + dwarfs-rs |
| 8 | store layout-version + read check | tebako-rs |
| 9 | registry schema_version enforce (publish validates, resolve refuses) | tebako-cli + resolve |
| 10 | factory nm provenance assert; exit 132 | tebako-runtime-ruby |
| 11 | feedstock product pin (post-2.0 tag) | tebako-packages |
| 12 | scenario catalog → e2e suite (S1–S65) | tebako-rs + factory |
| 13 | tebako info embeds artifact-info.yaml in the bootstrap binary (S38) | tebako-rs release |
TBK SPEC 19 — The Bootstrap, Distributed: How Tebako Reaches Your Machine Without a Compiler
Status: normative · user- and developer-facing Audience: everyone who runs, builds, or distributes tebako packages Related: spec 00 (invariants), spec 17 (the runtime driver contract), spec 18 (the contract graph)
1. What this document is about
A tebako package is a single executable file you can copy to a machine and run. It is made of three parts:
┌────────────────────────────────────────────────────────────┐
│ A · the bootstrap (a tiny Rust loader, < 3 MB) │
│ B · the runtime (the interpreter, e.g. Ruby) │
│ C · the payload slice(s) (your app and its data, as images)│
└────────────────────────────────────────────────────────────┘
This document answers one question completely: where does part A come from, and why will it run on your machine?
The short answer: we build it, you never do. The bootstrap is a precompiled artifact we publish for every supported platform, alongside the rest of the tebako release. A press stitches it onto your payloads — from a local Rust bootstrap when one is present (--bootstrap, $TEBAKO_BOOTSTRAP, or the tebako-bootstrap binary next to the tebako executable), and otherwise from the release-store flow of §4: the per-triplet bootstrap published with the press's own release, resolved into the store once, verified, and cached. There is no C compiler, no CMake, no Rust toolchain, no vcpkg anywhere in that path — and there never will be.
Shipped behavior. The CLI sources the bootstrap from local binaries first and otherwise resolves the published per-triplet Rust bootstrap into the store (§4 — once, verified, cached). The retired v1 C++ tebako-bootstrap release download — whose argv0-verbatim handoff the image-era runtime driver rejects — is gone for good: no silent network fetch of a v1 artifact remains on the press path. The per-triplet Rust bootstrap assets this document describes are published with every tebako release (§3.3).
2. The audience rule (who needs what)
| Who you are | What you need on your machine |
|---|---|
| You run tebako packages | Nothing. Download, run, done. No compiler, no libraries. |
| You build data-only payloads (docs, fonts, datasets, archives) | Nothing. tfs mkimage works in-process; no toolchain. |
| You build runnable payloads (your app, a gem with native extensions) | A compiler for your own code only. The entire tebako stack — bootstrap, runtime, imager — arrives as binaries we built. |
| You work on tebako itself | The full toolchain (the factories, the Rust workspace, vcpkg). This is the only audience that ever compiles tebako. |
Prebuilt artifacts flow downward; compilation never flows outward. If your use of tebako ever asks you to compile part of tebako, that is a bug in our distribution, not a requirement.
3. Why "just build it anywhere" does not work
3.1 The glibc trap (Linux)
You might assume a Linux binary built on a recent distro runs everywhere Linux runs. It does not:
$ ./tebako-bootstrap # built on Ubuntu 22.04 (glibc 2.35)
./tebako-bootstrap: /lib/x86_64-linux-gnu/libc.so.6:
version `GLIBC_2.34' not found (required by ./tebako-bootstrap)
Why: glibc versions every public symbol. A binary built against glibc 2.35 records symbol versions like GLIBC_2.34 in its dynamic section. The dynamic loader on Ubuntu 20.04 (glibc 2.31) looks for those versions, doesn't find them, and refuses to start the program.
glibc's compatibility promise is one-directional: binaries built on old glibc run on newer glibc, never the reverse. So the build host's glibc is the floor below which the binary cannot go.
3.2 What each platform's "floor" means
| Platform | The floor question | Our answer |
|---|---|---|
| linux-musl (x86_64, arm64) | None. musl is fully static — the binary carries everything and runs on any Linux kernel ≥ the baseline. | The universal Linux artifact. When in doubt, this is the one to ship and to use. |
| linux-gnu (x86_64, arm64) | Oldest glibc we promise to support. | The floor decision is Ubuntu 20.04 (glibc 2.31): built there, the binary runs on 20.04 and everything newer. We never build the shipping artifact on a newer glibc. (Honesty note: the linux-gnu release legs are being moved to the 20.04 container to make this true; the musl legs already carry the universal promise.) |
| macOS (arm64, x86_64) | MACOSX_DEPLOYMENT_TARGET — the oldest macOS the binary may load on. | Pinned per arch (currently 11.0); the linker stamps it and the OS enforces it. |
| Windows (x86_64, ucrt64) | The Universal CRT is part of Windows 10+. | ucrt64 with the C/C++ runtimes statically linked (no mingw DLLs to find); floor is Windows 10 / Server 2016. |
3.3 Yes, that means the bootstrap comes in triplets
There is no single "Linux binary." Every tebako binary artifact — the bootstrap first among them — is published per platform triplet:
linux-gnu-x86_64 linux-gnu-arm64
linux-musl-x86_64 linux-musl-arm64
macos-arm64 macos-x86_64
windows-x86_64
The matrix is deliberate and small: each triplet is a real CI leg with real tests, not a combinatorial explosion. The loader picks exactly one for your machine; you never pick anything.
4. How a press gets its bootstrap (no compiler involved)
Shipped behavior: tebako press sources the bootstrap from local Rust binaries first, in this order:
--bootstrap <path> — an explicit binary;
$TEBAKO_BOOTSTRAP — the environment override;
the tebako-bootstrap executable next to the tebako binary (the dogfooding/installed-pair layout).
With none of these present the press resolves the bootstrap through the release-store flow below — the published per-triplet Rust bootstrap into ~/.tebako/bootstraps/, with the same verification discipline the runtime cache already has (a press never fails closed for want of a bootstrap unless the store flow itself fails with a named error; TEBAKO_OFFLINE=1 is cache-or-named-error, exit 138). (The historical fallback downloaded the v1 C++ bootstrap release; its handoff predates the spec 17 driver contract and produced packages that fail at run time, so it is retired, not merely refused. The interim fail-closed refusal, exit 136, is superseded by this flow.)
tebako press app.rb -o myapp
│
▼
1. resolve the bootstrap for the target triplet — the release
matching the press's own version (the bootstrap and the CLI
ship in one release, so the two never drift)
├── store hit: ~/.tebako/bootstraps/<version>-<triplet> → use it
└── miss: download from the tebako release page
├── sha256-verified against the release's
│ manifest.json / SHA256SUMS
└── tmp + rename into the store under the entry lock
(a partial download is invisible — never used)
│
▼
2. read the bootstrap's embedded contract card
(artifact-info.yaml: era, version, launcher_abi, contract_version)
├── era mismatch → named refusal BEFORE stitching
└── ok → proceed
│
▼
3. image your payload(s) with tfs (in-process — no compiler,
no external tools of any kind)
│
▼
4. stitch: bootstrap + payload slots + trailer → `myapp`
Every artifact in this flow is one we built and sha256-published. The only bytes of yours are the payloads.
A custom bootstrap (TEBAKO_BOOTSTRAP=/path/to/binary) follows the same contract card check — a press will refuse to stitch an era-1 or mismatched bootstrap rather than produce a package that fails later on a user's machine (spec 18, S38).
5. Why we don't ask users to compile the bootstrap
Four reasons, in descending order of how much they matter to you:
It would put a compiler on every user's machine — the exact complexity tebako exists to remove. "Install Xcode/Build Tools/a cross-gcc" is not an acceptable prerequisite for packaging a script.
Determinism. A bootstrap built on your machine is untraceable: your toolchain version, your flags, your libc. Ours is built in one pipeline, on a pinned floor, with the size gate enforced (currently 2.50 MiB against the 3 MiB budget on every triplet, checked per release).
Trust. Every published bootstrap is sha256-anchored in the release and verified at download. There is one artifact to audit, not a million local variations.
The size budget needs the pipeline. The 3 MB gate is a release-time discipline (opt-level z, fat LTO, one codegen unit, panic=abort, stripped symbols). It is not something we can ask of a casual local build.
6. Keeping a package's bootstrap current
Packages are immutable: once stitched, a package's bytes don't change. When a new bootstrap ships, old packages keep their old bootstrap — that is by design (a package is a reproducible artifact, not a living install).
If you want the new bootstrap on an existing package there is one honest path: re-press from the payload. The payload images are the durable part; stitching is cheap. The tebako-pkg set-runtime in-place region swap is retired: with the runtime carried as ordinary package slots (§6.1) a region swap would have to re-layout the whole file — which is re-pressing by another name. The decision stays explicit, and tebako inspect <package> always tells you which bootstrap era and version a package carries.
6.1 The carried runtime: two ordinary slots (tebako#458)
A self-contained package (spec 23 §13.2) carries the runtime as TWO ordinary trailer slots: the interpreter exe and the env image — never the legacy single format_id = 4 runtime slot (spec 02 §6). At first run the bootstrap:
stages the exe slot into the runtime cache — tmp + rename under the entry lock, verified against the trailer slot digest (signed v2) or the computed digest (unsigned), exactly the lazy-seed rule of spec 05 §4;
hands the env-image slot to the driver through the ordinary <self>:<slot>:<mount> grammar (spec 17 §1) — embedding changes byte placement, never semantics.
The staged exe IS the cache entry: a later shared-runtime package resolving the same runtime version finds it already cached — the seed converges the two presets onto one cache. The legacy single-slot form keeps READING as before; presses never emit it.
6a. Fat redefined: the embed dial over #458's two-slot runtime (tebako#460)
"Fat" is --embed=all — the runtime rides as its TWO ordinary trailer slots (the interpreter exe + the env .tfs, per #458); "lean" is a subset embed with run-time resolution by locked digests (spec 05 §4a). The set-runtime region-replace path is RETIRED: a runtime is slots like any slice, placed by the same composition pipeline. --mode remains as sugar over the dial for compatibility.
7. The contract card inside every bootstrap
Every bootstrap binary we ship carries an embedded artifact-info.yaml block (appended at build, marked and readable):
schema: artifact_info
schema_version: 1
era: 2
name: tebako-bootstrap
version: 2.0.0
triplet: linux-musl-x86_64
launcher_abi: 1
contract_version: 2
sha256: <of the enclosing release entry>
This is what tebako inspect reads to answer "which tebako can open this?" for the bootstrap itself, and what a press verifies before stitching. (spec 18, S38 — the same declaration model as every other artifact in the ecosystem.)
8. FAQ
"I built tebako on Ubuntu 22.04 and it won't start on 20.04. Broken?" No — that's glibc working as designed (§3.1). Use our prebuilt artifacts: they're built on the floor distro or musl, and they start everywhere we promise.
"Can I just use the musl bootstrap everywhere on Linux?" Yes. It's the universal Linux artifact. The linux-gnu variants exist for environments that specifically want glibc-linked binaries (some monitoring/injection tooling expects glibc behaviors), not because musl is second-class.
"Do I need Rust or Cargo installed to use tebako?" No. Only people hacking on tebako itself do.
"I'm building a gem with a C extension. What do I compile?" Your extension, and only your extension. tebako's runtime (which your extension links against) is a prebuilt artifact; you never rebuild it.
"What happens if the download is interrupted mid-press?" Nothing bad. Downloads land in a tmp area and are renamed into the store only when complete and verified; a partial file is invisible and is simply re-fetched next time.
"My company's policy requires building everything from source." You can — every repo is public and the factories are reproducible — but it's a supported-you're-on-your-own path, not our recommendation. If you rebuild, keep the era/contract fields intact so the artifacts still verify against each other (spec 18).
9. Summary in one paragraph
The bootstrap is ours, precompiled, per-triplet, verified, and cached — built once in our pipeline on deliberately old floors (or musl, which has no floor), published with sha256 anchors, sourced by the press from local binaries when present and otherwise resolved from the release into the store (§4 — once, verified, cached), and stitched onto your payloads by a press that checks its contract card first. You never compile it, you never pick it, and it always starts.
TBK SPEC 25 — Trace observability: the interception bus, diagnosis, and coverage
Status: PARTIAL (phase T1 shipped 2026-08-19: the tfs::trace interception bus + docs/spec/schemas/trace-event.yaml + tebako trace run; phase T2 shipped 2026-08-20: the spawn/resolve emission — the preload's posix_spawn surface and the driver's image-triple resolution; phase T3 shipped: tebako trace cover (§6.3) 2026-08-20 — the escapes report, golden-parity with retrace's shared correlate fixtures — and 2026-08-21 the procmon converter (tebako trace import procmon, §6.2), byte-parity with upstream procmon2retrace on the golden 06 fixture; phase T4 shipped 2026-08-21: tebako trace explain (§5) — the capture replay with the signature table in data. All four phases' CODE is on main; the PARTIAL remainder is dogfood, not code: the §8 legs (retrace libc-layer on both platforms; the kernel-layer leg as §6.4 lands) and the real incident-13 captures' archival into the explain fixtures. Owner-signed 2026-08-19 — architecture A: the in-tfs event bus + tebako trace front-ends; outside capture rides the three-layer producer model of §6.1, with retrace as the libc-boundary layer on BOTH platforms).
A payload author virtualizing an application on tebako must answer three questions, and today each is answered by hand-rolled one-off diagnostics (the incident-13 msys dogfood chain: four CI rounds of eprintln gates and in-probe bisection to name one Windows loader failure):
Discovery — what does my application touch, so what must I declare? (mounts, needs:, materialize:, entrypoints)
Diagnosis — my packaged application fails; which hop failed? (mount → manifest → resolve → materialize → OS bind)
Coverage — is anything my application does NOT virtualized? (raw syscalls, unpatched IATs, loader-internal probes — the escapes)
This spec defines one substrate and three front-ends:
The interception bus (§2): every tebako interception point emits one structured event. The bus lives in the Rust tfs crate — the shipping VFS implementation on every platform — so it is cross-platform and runtime-independent by construction: events name syscall/loader-level facts (paths, verdicts, errnos), never language facts. Ruby, Julia, and Python payloads are equally covered because every runtime bottoms out at the same libc/loader boundary the bus instruments.
tebako trace run (§4): discovery — collect a run's events and emit a suggested manifest.
tebako trace explain (§5): diagnosis — replay a capture into the hop chain and name the first red hop.
tebako trace cover (§6): coverage — correlate the inside stream with an outside capture and report what escaped.
1. Laws
Observability never gates. A trace-channel failure degrades to a loud stderr note; the payload run proceeds and its exit code is unaffected. A tracer must never become a failure mode.
Runtime-independent. Events name OS-level facts only. No event may carry a language-runtime concept (a gem, a module, a Julia package) — runtimes are payloads; the bus sits below them.
Cross-platform inside; layered outside. The inside stream is identical on linux, macOS, and windows. The outside view is the three-layer producer model (§6.1): the libc boundary is retrace's on BOTH platforms (preload on POSIX; the preload-msvc / preload-mingw inline-hook backends on windows, retrace ADR-0009); kernel-level producers (ptrace, eBPF, ETW/procmon) join ONLY as retrace-shaped JSON, via bridges or offline converters (§6.2). Every outside source is an import format, never a runtime dependency.
No shell-outs. Captures are files parsed in-process. Arming or reading a trace never spawns a tool (spec 00 invariant 1).
The correlation law. The inside stream can never prove its own completeness: an escape is invisible from inside by definition (macOS 15's dyld rpath probes never reach the interposed open — the exec-closure walk exists because of this). "What isn't tebako intercepting" is answerable ONLY by subtracting the inside stream from an outside capture — and only up to the outside capture's own layer (§6.1).
MECE with spec 23 §8. The record policy mode already owns host-path needs discovery (the audit journal → tfs needs --from-journal). This spec does not re-invent it: the jail channel of the bus IS that journal, formalized; §4's discovery extends the draft to the axes §8 does not cover (materialize:, entrypoints, runtime deps).
Human gate. A generated suggestion never edits a manifest by itself (spec 23 §8's law, unchanged).
2. The interception bus (tfs::trace)
Emission points — exactly the interception points the driver/TFS already implements, one event per decision:
| op | emitted where | verdict values |
|---|---|---|
| mount | mount table insert/remove | ok / error:<errno> |
| open / stat | path dispatch (spec 11) | image:<mount> / host / denied:<rule> / error:<errno> |
| dlopen | dlmap2file / dlalias2file | materialized:<host-path> / host / error:<errno> |
| exec / spawn | exec routing (spec 17/22) — one routing decision, two syscall surfaces: exec is the execve surface (process replacement), spawn the posix_spawn surface (a child is created — the correlator's process-tree signal) | routed:<entry> / host / error:<errno> |
| materialize | exec-cache extraction | ok:<host-path> / cache-hit / error:<errno> |
| jail | policy bind / check (spec 08, 23 §8) | allow:<rule> / deny:<rule> / record |
| resolve | the driver's --tebako-image <path>:<slot>:<mount> resolution (trailer probe → whole file or slot region — the payload/slot identity the correlator matches outside reads against). PLANNED: the L3 runtime/payload cache resolution (tebako-resolve — loader-side, outside the runtime process; its channel story lands with the phase that needs it) | whole / slot:<n> / error:<errno> — PLANNED L3 half: cache / fetched / error |
The dlopen event's detail carries the closure walk as structure — the parsed format, the dep list, each dep's resolve verdict (materialized / host-system) — what incident 13's round 4 added as eprintln lines. Those gates convert to events; TEBAKO_DEBUG_TFS remains as the human-readable degraded view over the same emission points.
Arming. TEBAKO_TRACE=<host-path> (env) or --tebako-trace <host-path> on the driver argument grammar (spec 17 — the env-scrubbed handoff rides the argument, the lesson of incident 13 round 5). The flag is an additive optional driver argument: spec 17's grammar extends by option, never by version bump (the trailer-flags rule, spec 02). Both set: the argument wins. The channel is opened and pre-registered at driver boot, before any mount — writes are append-only, process-internal, and NEVER policy-gated (the journal channel's discipline, crates/tfs/src/journal.rs, already proven under deny).
Cost when off. Disarmed, an emission point is one Option::is_none() branch. The bus compiles into the runtime/driver side only; the bootstrap's < 3 MB size gate is untouched (spec 00 invariant 2).
Children. Spawned children re-derive the channel at their own driver boot on BOTH platforms: TEBAKO_TRACE is in the inherited environment, the child's driver arms, and its events append to the same file. (The fd-inheritance spelling this section used to carry is not the mechanism — env re-derivation covers both platforms uniformly. On fork, the already-open fd IS inherited until the child's own arm, so pre-arm child events still land in the same channel.) All writers append atomically; events may interleave — every event carries pid/tid so the front-ends regroup.
3. The event envelope (schema v1)
One JSON object per line (JSONL; streamable, diffable, robust to a crashed tail). Authored configs stay YAML (invariant 6); the event STREAM is telemetry and is JSON. The versioned schema lives at docs/spec/schemas/trace-event.yaml (lands with phase T1); the normative shape:
v: 1 # envelope version — additive only, never bumped
ts: <rfc3339μs> # driver clock
pid: <int> ; tid: <int>
op: <table §2>
path: <vfs-or-host path, exactly as dispatched>
verdict: <table §2>
detail: { ... } # per-op: dlopen deps, jail rule, exec argv0, …
dur_us: <int> # the interception's own cost
errno: <int, optional> # when verdict names an error
CI validates every emitted event against the schema (a property test drives the whole op matrix and validates the stream).
4. tebako trace run — discovery
Runs an application composition under policy: record with the bus armed, then synthesizes a suggested manifest — a commented YAML fragment, never applied (law 7):
host reads → needs:/jail: ro grants (this half is spec 23 §8's generator, unchanged — the bus's jail channel feeds it);
host writes → rw grants (strongest-observed-op wins, §8's rule);
a VFS-resident file read through a RAW host fd (a native library's own fopen — the exec-cache answer consumed it) → a materialize: candidate — the sassc class-R case, caught automatically instead of discovered by a failing import;
an in-image dlopen whose deps all resolve in-image → a NOTE "closure-covered — nothing to declare";
a spawned host-absolute executable → an entrypoint/runtime-dep note;
floor, store, and exec-cache paths are excluded (§8's exclusion law).
Output: the draft fragment on stdout (or --out), each entry carrying its why: evidence line (observed: <n> events, first at <ts>). The author reviews, flips ro↔rw, deletes noise, fills why.
5. tebako trace explain — diagnosis
Replays a capture (or a live run's stream) into the hop chain — mount → manifest read → resolve → materialize → OS bind — and prints the first hop whose verdict is red, with the signature table seeded from the incident corpus:
| signature in the stream | named hop |
|---|---|
| no mount event for the env image + prelude-class child stderr | env image never mounted (handoff env lost) |
| dlopen verdict naming the OS loader's module-not-found (windows error 126; the POSIX dlopen ENOENT analogue) with every dep materialized|host-system | the OS bind itself — bisect candidates printed |
| jail deny immediately preceding a dependent open error | policy denial (the EACCES class) |
| materialize error | exec-cache write failure |
The table lives in data (a YAML map in the CLI crate), extended as incidents teach new signatures — never hard-coded into the bus.
6. tebako trace cover — coverage
The escapes report (law 5). Inputs: an inside capture (the bus) and an outside capture of the same run.
6.1 The three-layer model (normative)
| layer | POSIX | windows | who sees it |
|---|---|---|---|
| inside the VFS | the tfs bus (§2) | the tfs bus (§2) | tebako |
| libc boundary | retrace preload | retrace inline hooks (preload-msvc / preload-mingw, retrace ADR-0009) | retrace — both platforms |
| kernel syscall | retrace ptrace backend; strace → strace2retrace (converter, §6.2); eBPF bridge | ETW / procmon (via converter, §6.2) | kernel tracers |
Escapes split into two classes at the libc boundary:
libc-routed escapes — the application called open(2) / CreateFileW directly, below tebako's interposition but through libc. Visible to retrace on BOTH platforms today.
sub-libc escapes — raw syscall(2) / NtCreateFile, loader-internal probes (the macOS dyld rpath class). Invisible to libc hooks by construction; only a kernel-layer producer sees them.
A coverage report is only as strong as its outside capture's layer: a libc-boundary capture certifies libc-routed escapes only; sub-libc certification requires a kernel-layer capture. The report MUST name the producing layer of its outside input.
6.2 The outside format — retrace-shaped JSON (SSOT: retrace)
The outside capture format is the retrace trace document, owned and versioned by the retrace project (riboseinc/retrace). Tebako never authors a competing outside format. Every producer normalizes INTO that shape; the correlator stays format-uniform:
retrace preload / inline hooks — native JSON output today (one JSON array document per capture).
retrace ptrace backend — native, POSIX kernel layer.
eBPF bridge (ebpf-bridge/) — emits retrace-shaped JSON.
procmon / ETW (windows kernel layer) — an OFFLINE converter (procmon CSV/XML export → retrace JSON), the same decision as the Frida/eBPF bridges: producers normalize into the format, never the reverse. The converter ships in the tebako CLI as an import verb (tebako trace import procmon <csv>), pure Rust, in-process (law 4).
6.3 The correlator — self-contained Rust
tebako trace cover implements the correlation IN the tebako CLI, in safe Rust: canonicalize host paths on both sides (same atoms as spec 23 §8's generator); subtract every outside-observed op that an inside event already accounts for; the remainder is the escapes list, grouped by surface class (fs / exec / dlopen / spawn), with a per-class coverage percentage and the producing layer named (§6.1). Exit code 0 = no escapes, 1 = escapes found — CI-gateable. Intentionally-unserved surfaces (documented passthroughs, e.g. the platform floor) are declared in the composition so the report separates KNOWN-UNSERVED from ESCAPE.
The shipped surface (phase T3, the correlator half).
tebako trace cover --inside <tfs.json|jsonl> --outside <retrace.json>
--prefix <path> [--pid N] [--window SECS]
[--exclude-probes] [--json] [--layer libc|kernel]
stdout is the golden contract: one escape <path> func=<f> tid=<t> pid=<p> class=<probe|read|write|none> line per escape (retrace's report grammar since its v2.9.0), or retrace's escape array under --json. Byte-compared in CI against retrace's shared golden tree (tools/correlate/golden/, copied byte-verbatim to crates/tebako-cli/tests/fixtures/correlate/) — every case, stdout bytes and exit code. Nothing else ever writes stdout for this subcommand (the version banner rides stderr).
stderr (outside the golden contract) carries the summary (inside=N entries, M paths; prefix=P; escapes=E), the escapes grouped by surface class with per-class coverage percentages, and the producing layer named by --layer (default libc — §6.1's honesty rule: the report certifies its named layer only; sub-libc escapes are UNCERTIFIABLE under a libc-boundary capture).
Exit codes are retrace-correlate's: 0 no escapes, 1 escapes found, 2 usage or I/O error.
The kernel is retrace's (the retrace-correlate port): the tolerant stream scan (array document / JSONL / truncated tail), any-depth path extraction, NT-form normalization (\??\, //?/, \\?\, the \Device\HarddiskVolumeN drive guess), drive-letter- insensitive path comparison with a case-SENSITIVE component-boundary prefix test, pid/time-window coverage (a pid-less entry is a wildcard; the bus's string ts never feeds --window — window mode takes retrace-shaped inside captures with numeric time), the name-keyed probe/write classification (a NAME-NOT-FOUND probe on an unserved under-prefix path IS an escape — existence is information), one escape per outside entry (the first under-prefix uncovered path in field order), --exclude-probes for the jail-grant policy. Documented deviations, error paths only: a non-numeric --pid/--window and an unknown --layer are named usage errors (exit 2) where upstream's atol/atof silently read 0 (spec 00 law 9).
The correlator is tebako-owned because the invariants leave no other home: invariant 1 (no shell-outs in shipped artifacts) forbids invoking a retrace binary; invariant 3 (C/C++ only in dwarfs-t) forbids linking one. The correlation kernel (normalize + set difference + threshold) is small and pure. If the retrace project ships its own retrace-correlate for the generic market, the two implementations assert parity on shared golden fixtures in CI — invariant 10's parity escape hatch: the FORMAT is retrace's single source; the ALGORITHM has two implementations that must agree. (retrace's retrace-correlate landed ahead of this phase — the golden tree above is that parity hatch, exercised.)
6.4 The contract with the retrace project
Verified against riboseinc/retrace @ v2.6.1 (d06c6af); later shipments tracked below the table (the full correspondence lives in the work queue). Tebako phases coverage features as these land upstream; none block T1/T2:
| prerequisite | state today | tebako impact until it lands |
|---|---|---|
| retrace-audit + path_contains policy op | SHIPPED (tools/audit-converter; property-tested — P-POLICY-CONTAINS-SOUNDNESS) | the policy-matching half of coverage exists; usable on outside captures immediately |
| pid + tid per log entry | SHIPPED (v2.7.0) — the correlator joins on pid/tid when present | multi-process compositions regroup the outside stream |
| ntdll-depth hooks (NtCreateFile / NtOpenFile / LdrLoadDll) + NT-path normalization (\??\C:\…) | ABSENT at v2.6.1 — the windows backends interpose at the ucrt layer; a native payload calling Win32 directly already escapes that layer TODAY (libsass's importer reads via raw CreateFileW with \\?\ prefixes — invisible at ucrt) | windows sub-libc escapes stay invisible until both the hooks and a converter exist |
| streaming / JSONL output | today one JSON array document per capture (leading-comma emission; a crashed tail invalidates the document) | the correlator tolerates a trailing partial record |
| retrace-correlate (the set-difference tool) | SHIPPED (v2.7.0, with the shared golden tree incl. 06-libsass-importer; the report grammar stabilized in v2.9.0) | tebako ships its own (§6.3) and asserts byte-parity on the shared tree in CI — the parity hatch is exercised |
| ptrace-backend param deref (arch_spec) | ABSENT at v2.14.0 — the ptrace backend ships no arch_spec of its own: aarch64 entries carry the syscall NAME with NIL params (openat(AT_FDCWD, "/tmp/x", O_RDONLY) arrives as "path":"(nil)"), and on x86_64 the wild frame deref SIGSEGVs on attach (tebako CI run 32451535675, job 96680888031) | the linux kernel-layer dogfood rides strace + upstream's OWN strace2retrace converter (the §6.2 normalizer pattern — same kernel truth, real paths) until this lands or the eBPF bridge ships |
| windows live capture (win-run injection + ucrt inline hooks) | NEVER smoke-tested upstream at v2.14.0 (msys.yml exercises only the library scaffold + headers); BROKEN on windows-latest in tebako CI (run 32453723170, job 96686997021): the hook installation completes in the child (hooked 'fopen' … diagnostics print), then LoadLibraryA(retrace.dll) fails inside retrace_core_boot() — the loader converts a DllMain crash into ERROR_DLL_INIT_FAILED, the inject thread's exit code reads 0, and win-run reports "failed to launch" (win_common/inject.c:73) | the windows libc-layer dogfood is a prerequisite probe: a standalone control isolates our half, a RETRACE_LOGGER_RING=0 candidate pin gets the full chain gates when it captures (the MinGW build compiles the lock-free ring the MSVC build stubs out), and otherwise the leg pins the documented broken signature — drift in either direction fails it. The procmon converter (§6.2) carries the windows chain certification meanwhile |
7. Testing and gates
Golden fixtures: the incident-13 dogfood captures (real [tfs] streams) converted to the schema must round-trip through the validator and through explain (whose red hop must match the incident's hand-derived answer).
Property: driving the public tfs op matrix emits exactly one schema-valid event per op.
Correlator: synthetic inside/outside pairs with deliberate escapes — a libc-routed fixture (a direct fopen below the interposition) under a retrace preload capture, and a raw-syscall(2) fixture binary (built by CI, not shipped) under a KERNEL-layer capture — must be caught at 100%. The raw-syscall fixture paired with only a libc-boundary capture must report the escape as UNCERTIFIABLE, not as covered (§6.1's honesty rule).
Converter: a procmon CSV fixture converts to retrace-shaped JSON the correlator consumes identically to a native retrace capture.
Parity (when retrace-correlate lands upstream): the shared golden fixtures produce identical escapes reports from both correlators.
The factory's msys dogfood converts from TEBAKO_DEBUG_TFS gates to the bus as phase T1's dogfood — the harness stops hand-rolling diagnostics.
Size/hygiene: bootstrap gate untouched; no new dependencies outside the workspace (tebako-json for emission); unsafe nowhere (the bus is safe Rust over the journal's fd).
8. Phasing
| phase | contents | dogfood |
|---|---|---|
| T1 | the bus + schema + run (discovery) | the msys dogfood rides the bus; a payload author onboards a fresh gem without hand diagnostics |
| T2 | the spawn/resolve emission: the preload's posix_spawn surface reports spawn (a child-process decision — the correlator's process-tree signal), and the driver emits one resolve event per --tebako-image triple (the payload/slot identity: whole / slot:<n> + offset/size/mount, or the named failure class) | a traced boot of a broken composition names the failing triple in the capture itself — no stderr spelunking; a traced run's spawns regroup by pid |
| T3 | cover (certification) + the procmon converter | cover SHIPPED 2026-08-20 (the §6.3 correlator + the shared golden tree green in CI); the converter (import, §6.2) SHIPPED 2026-08-21 (byte-parity with procmon2retrace on the golden 06 case, the converted stream driving cover to expected.txt/exit.txt). Remaining dogfood: a leg under retrace on both platforms (libc layer); a kernel-layer leg (ptrace/eBPF on linux, procmon-converter on windows) as the §6.4 prerequisites land; escapes report in CI |
| T4 | explain (diagnosis) | SHIPPED 2026-08-21: the replay + the signature table in data (explain-signatures.yaml), fixtures replaying the incident classes to their hand-derived answers (§7's gate shape). Remaining dogfood: replay the real incident-13 captures; the named hop matches history |
(Re-phased 2026-08-20: emission completeness precedes the front-ends — the original T2 (explain) is T4, the original T3 (cover + the converter) stays T3, and T2 is the spawn/resolve emission the correlator's inputs depend on.)
Each phase ships behind its own PR chain against this spec; the spec moves PLANNED → PARTIAL → SHIPPED per phase (spec 00's status law).
TBK SPEC 36 — Release bundles (the runtime publish unit)
Status: PLANNED (locked direction 2026-09-24; ships with tebako-release v0.2.0 + the tebako-resolve bundle fetch path — the v0.16.28 line-shard recovery runs the per-file shape to completion, and pre-bundle releases stay installable forever, spec 13 §8).
Normative specification of the bundle: the single distribution artifact that carries one runtime leg's bytes (interpreter exe + env image + platform support files) as one gzipped tar. The bundle replaces the per-file asset enumeration of spec 13 §2a on bundle-era release lines; it changes what a factory PUBLISHES and what a resolver FETCHES, never what the store holds (spec 05 §3's layout is unchanged — the bundle unpacks into it).
1. Why (the two budgets, measured 2026-09-23/24)
The 1,000-asset ceiling. GitHub caps a release object at 1,000 assets (422 … file_count limited to 1000 assets per release). The ruby factory's catalog is 23 versions × 7 platforms; at the per-file shape's ~10–14 assets per leg (exe, image, both .sha256, the shard, windows DLLs, and an .asc of each on signing-enabled lines) a catalog publish is ~1,800 assets — it cannot converge on one release object. The v0.16.28 recovery line-sharded the catalog onto per-line tags (v0.16.28-ruby4.0, …) via TEBAKO_RELEASE_TAG; that plumbing stays as the migration-time escape hatch (§6).
The API budget. Every asset is REST calls (upload, list, sign, re-list). The same recovery exhausted the tebako-ci identity's 5,000 req/h sliding window mid-fleet (tebako-release#3). The per-leg asset count is the multiplier of BOTH budgets; consumption is always paired (the loader fetches exe and env image together), so the per-leg bundle is the natural unit.
Budget table (per leg / catalog of 23 × 7):
| shape | unsigned | signing-enabled |
|---|---|---|
| per-file (today) | ~5 / ~800–1,100 | ~10–14 / ~1,800 |
| bundle (this spec) | 3 / 483 | 5 / 805 |
The bundle brings the whole catalog back under the ceiling even on signing-enabled lines; line shards (§6) remain the headroom, not the routine.
2. The bundle (wire format)
<stem>.tar.gz where <stem> is the package stem (tebako-runtime-<ver>-<lang>-<lv>-<triplet> — suffix-less, spec 05 §2's spelling rule and era law, on windows too). A gzipped tar whose members are named by their served spellings, in this fixed order (deterministic bytes — a re-run of identical inputs yields a digest-identical bundle, so the write-once digest-match skip stays cheap):
<stem>[.exe] # the interpreter exe (mode 0755)
<stem>.tfs # the env image (mode 0444 at install)
<stem>.dll … # windows support DLLs under their staged basenames,
# zero or more, sorted (today: the one runtime DLL)
SHA256SUMS # coreutils "<sha> <file>\n", one line per member
SHA256SUMS is the LAST member and pins every other member; the per-member digests mirror the shard's sha fields (§3) exactly.
gzip headers carry mtime=0 and no original-name field. Tar headers carry no uid/gid/uname/gname; modes as above.
Members are regular files only. No directories, symlinks, device nodes, absolute paths, or .. segments — a bundle violating the member grammar is InvalidBundle (§7), never a best-effort unpack.
The bundle is built ONCE per leg by the publish invocation from the leg's staged bytes (tebako-release owns the builder — in-process Gem::Package::TarWriter + Zlib::GzipWriter; no shell-outs), after the leg's gates pass, from the same bytes the per-file shape would have uploaded.
3. The publish shape (bundle-era lines)
Per leg, the publish invocation writes — write-once, spec 13 §2a's immutability rule unchanged:
<stem>.tar.gz # the bundle
<stem>.tar.gz.sha256 # the per-asset sidecar (coreutils shape)
<stem>.manifest.json # the per-package shard (the authority, §2's role)
plus, on signing-enabled lines, an .asc of EACH of the three (spec 09 §5's every-served-name rule — three signatures where the per-file shape needed eight or more).
The shard keeps today's identity anchors and gains ONE additive key:
{
"tebako_version": "0.17.0", "contract_version": 2,
"ruby_version": "4.0.7", "platform": "macos-arm64",
"filename": "tebako-runtime-0.17.0-ruby-4.0.7-macos-arm64",
"sha256": "…", "size_bytes": 38683544,
"abi": "arm64-darwin-23",
"image": {"filename": "….tfs", "sha256": "…", "size_bytes": 7658081},
"bundle": {"filename": "tebako-runtime-0.17.0-ruby-4.0.7-macos-arm64.tar.gz",
"sha256": "…", "size_bytes": 46012377,
"signature": {"keyid": "efc3c250f7862a48", "asc": "….tar.gz.asc"}}
}
filename stays the EXE's spelling and the per-member sha fields (sha256, image.sha256, dll.*) keep pinning the UNPACKED members — the store verifies members against them post-unpack (§4), and old readers keep matching the identity triple exactly as today.
bundle is additive: pre-bundle readers ignore it (the additive rule); bundle-era readers prefer it. A shard declaring bundle without the bundle's assets on the release is an invalid publish — the leg fails before it ships, exactly like a signature declaration without its .asc (spec 09 §4's invalid-signing-state rule extended to the bundle block).
The windows dll metadata block (install_as et al.) is unchanged: DLLs ride the bundle as members and install by the shard's declared spellings.
Co-publish (the lazy arm's serving requirement, spec 39 §7). A bundle-era line whose consumers include a lazy-mount loader ALSO serves the per-file assets of spec 13 §2a's enumeration — the bare exe under its historical spelling, <stem>.tfs, <stem>.dll (windows) — each with its own .sha256 sidecar, plus an .asc of each on signing-enabled lines. The shard's grammar is otherwise unchanged: the per-file blocks already pin exactly these bytes (the member pins ARE the standalone pins — one staged file, one digest, two serving forms); the shard gains ONE additive witness, top-level "per_file_assets": true (runtime-manifest MINOR 2), and declares the entry/facet signature blocks exactly as the per-file era does (the every-served- name rule covers the standalone set again). A shard carrying the witness without the assets on the release is the same invalid publish as a bundle block without its bundle — the leg fails before it ships and the audit names the gap. The bundle stays the ONE fetch of the default eager path (§4) — co-publish changes what the release SERVES, never what the bundle carries or how it verifies. The §4 compat window closes on co-published lines: a pre-bundle reader ignores bundle (the additive rule) and takes the per-file path against the same pinned bytes. Asset budget: the union is 9–11 assets per leg unsigned (18–22 on signing-enabled lines); line tips (5 rubies × 7 platforms) stay far under the 1,000-asset ceiling, and catalog republications ride §6's line shards as always. The mode is the factory's declared policy (the release tooling's adapter seam), never an env knob — a factory opts in when its consumers include the lazy arm.
4. The resolver path (spec 05 §2 amendment)
Preference order is unchanged (shard → derived monolith → line index); the era branch happens INSIDE the shard case:
bundle present ⇒ bundle fetch: download bundle.filename + its .sha256 sidecar (+ .asc when bundle.signature declares it) → verify the detached signature FIRST when declared (spec 09 §4's runtime-fetch point, always strict: 71 invalid / 72 untrusted) → verify the bundle sha256 (exit 70 on mismatch) → unpack in-process (Rust tar + flate2; no shell-outs, invariant 1) with the §2 member-grammar validation → verify EVERY member against the shard's per-member pins (InvalidBundle on mismatch — a bundle whose members disagree with the signed shard is an attack surface, never a tolerance) → write the spec 05 §3 store layout exactly as today (exe 0755, image 0444, the sha256/origin markers from the member pins) via tmp + rename — a partial install stays invisible.
bundle absent ⇒ the per-file path, forever (keep-forever, spec 13 §8). The era branch is per-release, never global.
Old resolver, bundle-era release (the compat window): the shard matches, filename flows verbatim, and — on a bundle-only line — the exe asset does not exist on the release, so the fetch fails with the named not-found error (exit-69 class) naming the identity triple and hinting that the line requires a bundle-era tebako. Never an exec of wrong bytes, never a silent fallback: old readers break LOUD, which the additive-key design makes the ONLY failure mode. On a CO-PUBLISHED line (§3) the window closes: the per-file assets exist again and the old reader's per-file path installs the same pinned bytes.
One fetch replaces three or more: the journal records the bundle base and channel exactly as today (spec 05 §2's per-engine chain applies unchanged — the bundle is just the asset the chain supplies).
5. The registry mirror (spec 04 §2 amendment)
A bundle-era runtime entry's platform rows name the BUNDLE: artifact: <stem>.tar.gz, sha256 pins the bundle. The rows stay the resolution mirror and audit pin; the runtime download itself flows the shard (§4). Per-file-era rows keep naming the exe — the registry is a faithful mirror of what the pinned release serves, era by era, and a status: withdrawn mark means the same thing on both. A CO-PUBLISHED line's row is unchanged — it still names the bundle (the preferred eager fetch): the row's blksum pin (spec 39 §3) is the lazy wire's only registry mirror, and the standalone per-file asset names derive from the stem (spec 05 §2's spelling rule), so the row grammar carries nothing new.
6. The release-topology policy (spec 13 amendment, locked 2026-09-24)
Tips by default. A routine factory release publishes the full set (line tips: 5 rubies × 7 platforms ≈ 385 per-file assets, ≈ 175 bundle assets) — comfortably under the ceiling on either shape.
Catalog republication is for migrations only (a format switch like dwarfs→limnifs), and a catalog run DERIVES its shard tags itself: v<ver>-<engine><line>-<platform> per (ruby line × platform group) — the platform group's vocabulary is linux-gnu / linux-musl / macos / windows (one shard serves both arch legs of its group) — no operator input (the v0.16.28 manual TEBAKO_RELEASE_TAG input remains as the override). A per-platform shard tag is the publish unit because concurrent platform legs never share one release object (the ghost-release race); a version's line-level tag MAY also exist (the 0.17.0 shape) but is never required. Consumers derive: a registry's version-level release.ref names any one published shard of the version; a reader substitutes its own platform group's segment (v0.17.1-ruby3.3-windows read on macOS → v0.17.1-ruby3.3-macos), and a line-level pin probes its per-platform shard first, the line tag second, the monolith last. A row carrying the additive per-row release.ref (registry schema MINOR 6, tebako#711) names its serving shard tag EXPLICITLY — it wins over the version-level derivation (spec 04 §2). The grammar's ONE code owner is tpkg (Platform::shard_tag_segment, shard_tag_substitute, shard_tag_append); a tag outside the vocabulary is opaque and never rewritten. The AUDIT rides the tail of each (platform × shard) run — the duty is per-platform by construction, and the platform run owns the matrix truth (its own compute outputs; never a recomputation, never a cross-run stale read); the coordinator's release job keeps only the registry renders, one bot PR per shard tag.
Withdrawal bounds growth (spec 04 §2): a superseded patch version takes status: withdrawn at the line's next publish rather than being re-hosted on every migration. The catalog is the historical record; the registry is what resolvers walk.
7. Named errors (new class; existing classes unchanged)
InvalidBundle — member-grammar violation, member-set mismatch vs the shard, member checksum mismatch, or an undecodable tar/gzip stream. Exit 70's integrity class at fetch; the message names the member and the shard it disagrees with. Never a partial store write (tmp + rename), never a skipped member.
Bundle fetch/signature failures reuse the spec 09 §4 classes unchanged: 69-class not-found, 70 sha256, 71 invalid/absent signature, 72 untrusted keyid.
TBK SPEC 37 — The registry book: federation, aliases, credentials, the official seed
Status: SHIPPED — §2's registry book (the config model, alias grammar + derivation, DuplicateRegistryAlias / DuplicateDefaultRegistry, add-registry --name/--require-signed/ --default, the list-registries book rendering), §2.2's per-registry fail-closed signature policy (UnsignedRegistryPayload, exit 70), §3's qualified form (alias/name + the registry: pin scopes), §4's federation grammar (the explicit-host tfs+<svc>://host/… forms, the tfs+https:// registry location, the UnsupportedService / SshTransportUnsupported refusals), §5's credential model (the two-tier book, the locked confinement, the fetch journal, CredentialRequired / InvalidCredentialEntry / DuplicateCredentialSelector), §6's official seed (tebako setup and the installer's written config; the tebako-packages/registry aggregate flowing the feedstocks' authored rows), §7's origin binding (the .tfs.registry marker, the confined version chains, the journaled rebind), §8's private runtimes (the DEPENDS-edge registry: pin — payload-manifest schema_minor 14 — the federated release-download locator deriving kind: runtime rows on GitHub/GHE/GitLab, and require_signed riding runtime rows), and §9's three operator tiers (their resolution paths — tfs+https://, explicit-host git services, file:// + bundles — all ride the shipped grammar; the tier how-tos live on tebako.org). (Locked direction 2026-09-24; design reviewed with the owner across the 2026-09-24 session — the alias grammar, the credential confinement model, and the federation forms below are the agreed shape). Nothing here changes what shipped resolvers do with a config that carries none of the new keys.
Normative specification of the registry book: the named, policy-bearing list of registries in ~/.tebako/config.yaml that turns spec 04 §2's "any git host repo" into a federation — public official payloads and private runtime/executable/data payloads resolving side by side on one machine, with leak-proof credentials and confusion-proof names. The registry stays developer-hosted zero-infrastructure YAML; this spec adds the bookkeeping that makes MANY of them safe to mix.
1. Why (the two hosting worlds, one machine)
A real deployment mixes two worlds: public payloads from the official registry (Homebrew's core-tap role) and private payloads from an operator's own instance (Docker's enterprise-registry role) — a consultancy's GitHub for public tools, their own GitLab for client work; Ribose's public tebako-packages org, plus gated flavor registries where BSI's tokens must never read NIST's repos. Today's model already fails-closed on ambiguity (spec 04 §2: N registries carrying one name is the named AmbiguousRegistries, never a priority pick) — but it has no aliases for ergonomic scoping, no per-registry policy, credentials only for github.com, and no grammar for a service API at an operator's OWN host. This spec closes exactly those four gaps. What it never adds: a resolution priority, a default service compiled into any binary, a silent fallback.
2. The registry book (the config model)
registries: entries gain OPTIONAL keys; a bare string entry keeps meaning what it means today (spec 04 §2, schema-compatible — old readers see the same refs):
# ~/.tebako/config.yaml
registries:
- name: official # the local alias (§3's handle)
ref: tfs:github:tebako-packages/registry
default: true # publish/UX anchor ONLY — §2.1
- name: nist
ref: tfs:github:metanorma/metanorma-flavor-nist
require_signed: true # fail-closed trust policy — §2.2
Alias grammar: name matches [a-z][a-z0-9-]*, unique across the book; when omitted, the alias DERIVES from the ref's owner/repo as repo (a collision with an existing alias is the named DuplicateRegistryAlias at config load, listing both entries — never a silent rename). Aliases are LOCAL names for local config — they are never published, never embedded in payloads, never part of any wire format.
2.1 The default flag is a publish/UX anchor, never a resolution tiebreaker. Exactly one entry MAY carry default: true (two → DuplicateDefaultRegistry, config-load time). The default registry is (a) the target of tebako publish when --registry is absent, (b) rendered first in listings and in the registry-listing body of named errors. Resolution has NO default: §3's rules are identical whether or not a default exists. (Invariant 9 stands: no default SERVICE; a default LABEL on user-owned config is not a service.)
2.2 require_signed: true makes every install whose plan resolves through that registry fail-closed unless the resolved row carries a signature: block that verifies against the machine's trust anchors (spec 09) — the registry-level form of TEBAKO_REQUIRE_SIGNED=1, scoped so a private operator can demand signatures on THEIR payloads without unsigned public payloads becoming second-class. A per-registry keyring: <ref> (PLANNED with the trust-anchor distribution work, spec 09 §10) pins WHICH keys count; absent it, the machine trust store decides.
tebako add-registry grows --name <alias>, --require-signed, --default; list-registries renders the book (alias, ref, policy flags, cache freshness). The shipped config still has ZERO registries (§6's seed is the installer's authored content, not a compiled-in value).
3. Name resolution (bare, qualified, pinned)
Three forms, each with exactly one home — the ambiguity law is unchanged:
Bare name — searches EVERY registered registry (shipped behavior, locked): zero hits → the named not-found error listing the registered registries; exactly one → plan; more than one → AmbiguousRegistries naming every carrier. No priorities, no first-hit, in either direction — a public registry can never shadow a private name NOR the reverse.
Qualified alias/name (NEW) — scopes resolution to the one registry whose alias is alias. Unknown alias → the named UnknownRegistryAlias listing the book's aliases. This is the ergonomic disambiguator short of a full reference (the Cargo registry = "…" / Homebrew tap/formula role): tebako install nist/metanorma-bsi can never touch the official registry's rows.
Full reference — unchanged (spec 04 §1); no registry involved at all.
Pin surfaces (.tebako-tools.yaml, the config's per-tool version: pins, spec 23 composition edges) gain an optional registry: <alias> key naming the registry the pin resolves through — the same scoping, authored. A pin naming an alias not in the book is UnknownRegistryAlias at pin-resolution time, fail-closed.
4. The federation grammar (spec 04 §1 amendment)
The service adapters' canonical SaaS hosts stay the bare forms; the operator's own host is EXPLICIT in the scheme — the adapter is still never inferred:
tfs:github:owner/repo:ver[#asset] → github.com (unchanged)
tfs+github://ghe.corp.internal/owner/repo:ver[#asset]
→ the GitHub API shape at that host (GitHub Enterprise Server;
base https://<host>/api/v3). ALSO the Gitea/Forgejo form — those
services implement the GitHub releases/contents API; a CI
conformance leg proves the claim, the grammar never special-cases
them.
tfs+gitlab://gitlab.corp.internal/group/sub/repo:ver[#asset]
→ GitLab API v4 at that host (self-hosted; nested groups unchanged)
tfs+https://artifacts.corp.internal/tebako/tpkg-registry.yaml
→ NEW REGISTRY LOCATION: the registry file itself over plain HTTPS
(spec 04 §2's "no other locations" is amended by THIS form only —
a static server, an S3 bucket behind a CDN, an Artifactory/Nexus
generic repo). Artifact refs inside such a registry are ordinary
spec 04 references — typically sibling `tfs+https:` URLs.
Bitbucket Data Center is NOT a host variant of tfs:bb: — its API differs from Bitbucket Cloud's. It is the named UnsupportedService ("bitbucket data center is not bitbucket cloud; host the registry over tfs+git: or tfs+https:") until a real consumer funds the adapter.
SSH is the named SshTransportUnsupported ("git over ssh needs the system ssh binary — forbidden by the no-shell-outs law; use a token over https, or file:"). A pure-Rust SSH transport (russh-class) can land later behind the SAME tfs+git: grammar with no reference change; until then, fail closed by name.
Host-parameterized adapters are ONE code path with a base-URL parameter — the SaaS forms are the parameter's canonical value, never a second implementation to drift.
5. The credential model (locked confinement)
credentials:
- registry: nist # tier 1: exact registry-alias match
token_env: NIST_GH_TOKEN
- host: ghe.corp.internal # tier 2: host fallback
token_env: GHE_PAT
Two tiers, most-specific-wins, exactly one match. A fetch looks up tier 1 by the alias of the registry whose row directed the fetch (registry-file fetches match their own alias), then tier 2 by the URL's host, then anonymous. There is no third tier and no chain.
The registry is the trust unit, the host is the convenience. The decisive case: two flavor registries on github.com whose tokens must not cross-read — per-host keying cannot express it, per-alias can. Two registries sharing one token name the same token_env twice; repetition is the price of a match rule with zero precedence ambiguity.
Config holds env var NAMES, never secrets. A credential whose env var is unset behaves as absent (the fetch goes anonymous → the service's ordinary 401/403 → CredentialRequired naming the registry and the env var it looked for).
Confinement (locked, generalizing the 2026-09-15 GitHub amendment to every adapter): a credential is presented ONLY to the host it was minted for — tier 1 credentials to the registry ref's own host (plus that service's API host, per the service's documented mapping), tier 2 to the named host — NEVER to a redirect target, NEVER cross-host. A registry row whose release.ref points at a DIFFERENT host falls to that host's own tier-2 entry or fails named; the directing registry's credential does not follow.
The adapter owns the header shape by service class (GitHub/GHE: Authorization: Bearer; GitLab: PRIVATE-TOKEN; Bitbucket Cloud: basic). Authored config never spells header mechanics.
Every fetch journals host + credential CLASS (token:env:NIST_GH_TOKEN, anonymous) with the value REDACTED — the mixed-federation audit trail. The ambient TEBAKO_GITHUB_TOKEN/GITHUB_TOKEN amendment is unchanged and ranks as tier 2 for github.com when no tier-1 entry matched.
6. The official seed (spec 16 amendment)
The installer's written config (and tebako setup on a config-less machine) SEEDS the official entry — authored, user-visible, user-removable config content:
registries:
- name: official
ref: tfs:github:tebako-packages/registry
default: true
No binary carries this value; tebako built from source with no installer still ships zero registries. The seed is DISTRIBUTION content (spec 16's install.sh / setup flow), exactly how Homebrew's installer clones the core tap without brew hardcoding it.
The official registry repo is a GENERATED AGGREGATE: each feedstock repo's own tpkg-registry.yaml remains the authored authority (SSOT); the aggregate is CI-flowed from them with parity asserted per row — never hand-edited. Removal/withdrawal flows the same way (status: withdrawn rows aggregate verbatim).
tebako bundle --config <org.yaml> (spec 16 §4) overlays registries as today — the airgapped/enterprise image-builder path is untouched; its overlay can REPLACE the seeded book wholesale.
7. Origin binding (upgrade confinement)
A store entry's markers already record WHERE bytes came from; the book adds WHICH REGISTRY resolved them — the .tfs.registry marker beside .tfs.origin, carrying the resolving registry's canonical REFERENCE (never an alias; aliases are local and volatile). Dispatch-time version chains (spec 07 §1's chain, spec 05 §5) and unscoped install-time name searches alike consult the payload's ORIGIN registry only: a same-named payload appearing in another registered registry is never a silent "upgrade" of an installed one (the confusion attack that priority-based ecosystems — rubygems sources, docker's implicit docker.io — leak by construction). An authored registry: scope (§3) outranks the binding. Switching registries is an explicit act: tebako install <alias>/<name> reinstalls and rebinds the origin; the journal records the rebind (event=origin-rebind). A rebind whose registry-declared digest disagrees with the cached bytes is refused (Sha256Mismatch, exit 70) — the cache never overwrites a standing entry, so bytes are never re-tagged to a registry that never published them: uninstall first, then install from the new registry.
8. Private runtimes (schema MINOR 1, shipped by this spec)
Spec 04 §2's kind: runtime registry entries move PLANNED → SHIPPED: a registry row of kind runtime carries engine: (+ optional implementation:), and a payload's kind-runtime DEPENDS edge (spec 30 §1) discovers it by (engine, implementation?, constraint) across the REGISTERED book under §3's rules (qualified form included: runtime_requirement gains no alias field — the EDGE carries registry: per §3's pin-surface rule). The matched version's release.ref derives the download base exactly as spec 05 §2's per-engine chain; the trust pipeline (sha pins, bundle-era rows, require_signed) is identical to the factory index's. A private ruby or openjdk line is thereby hostable next to public payloads with zero product-side special cases.
9. Internal instances (the three operator tiers)
The grammar above makes three hosting tiers first-class; the HOW-TO lives on tebako.org, the normative part is only that these resolve:
Zero software — a static HTTPS server (nginx, S3+CDN, Artifactory/Nexus generic repo) serving *.tfs + sidecars + one tpkg-registry.yaml, registered as tfs+https://…/tpkg-registry.yaml.
The git host they already run — GHE / self-hosted GitLab / Gitea / Forgejo via §4's explicit-host forms; releases are the artifact storage exactly as on the SaaS hosts.
Airgap — file:// mirror or a tebako bundle pre-seeded store (shipped; spec 16 §4), no network surface at all.
All three compose with the enterprise-networking amendment (spec 04 §4: proxies, custom CA roots) unchanged — internal TLS inspection is a transport concern the federation grammar never sees.
10. Named errors (new or re-scoped here)
| Name | Exit class | Moment |
|---|---|---|
| UnknownRegistryAlias | 65 usage | alias/name or registry: pin names no book entry — lists aliases |
| DuplicateRegistryAlias | 65 | config load; both entries named |
| DuplicateDefaultRegistry | 65 | config load; two default: true |
| AmbiguousRegistries | 65 | (shipped) bare name in >1 registry — the anti-confusion anchor |
| UnsupportedService | 65 | Bitbucket Data Center refs — the tfs+git:/tfs+https: steer |
| SshTransportUnsupported | 65 | any ssh/git@ URL — the token-over-https steer |
| CredentialRequired | 69 unavailable | 401/403 with no matching credential — names the registry + env var looked for |
| InvalidCredentialEntry | 65 usage | config load; a credentials entry names both registry: and host:, neither, or a malformed token_env |
| DuplicateCredentialSelector | 65 | config load; two entries key the same alias or host |
| UnsignedRegistryPayload | 70 integrity | require_signed row without a verifying signature — fail-closed |
| Sha256Mismatch | 70 integrity | (re-scoped from spec 04 §3) a rebind whose registry-declared digest disagrees with the cached bytes — uninstall first |
Each maps to exactly one CI tier's assertion; none is a fallback — a failure here changes NOTHING about what is installed or resolved elsewhere.
TBK SPEC 38 — OCI distribution (tfs+oci:)
Status: SHIPPED — the grammar, the artifact model, and the credential amendments are implemented (crates/tebako-oci/ + crates/tebako-resolve/src/oci.rs); the resolver speaks tfs+oci:// (crates/tebako-resolve/src/reference.rs).
Normative specification of the OCI distribution channel: payload images, runtime bundles, and registry indexes published to any OCI Distribution Spec v1.1 registry (GHCR, Harbor, zot, ECR, ACR, GitLab CR) as generic artifacts, resolved through one new reference class beside spec 04 §1's family. The channel is an ADAPTER — the store layout (spec 05 §3), the trust pipeline (spec 09), and the declarative platform-selection law (spec 04 §2) are untouched.
1. Why (the ceiling, again — and the self-hosted tier)
The per-tag asset ceiling. Spec 36 §1 measured the GitHub release ceiling (1,000 assets per release object; the ruby catalog is ~1,800 per-file assets and forces the line-shard choreography). An OCI registry has no per-release asset concept at all: every artifact is blobs + a manifest, addressed by tag or digest. The catalog publishes flat.
The fourth operator tier. Spec 37 §9's three tiers (static HTTPS, the git host they run, airgap) miss the shop that already runs Harbor/ECR/ACR and wants "our own internal payload instance" off the shelf — with the registry's own RBAC, retention, and replication. OCI is that tier, and it needs no tebako-side service (spec 00 invariant 9 stands: no default service, no server to run).
What this never adds: a resolution priority, a default registry host compiled into any binary (docker.io is NOT privileged — a reference names it explicitly or not at all), a silent fallback between channels, a second signature mechanism.
2. The reference grammar (spec 04 §1 amendment)
One new PROTOCOL-class form. The host is ALWAYS explicit — there is no canonical OCI SaaS — so the form is the tfs+<svc>://host shape of spec 37 §4, never the bare tfs:<svc>: SaaS shape:
OCI adapter:
tfs+oci://<registry>[:port]/<repo>[:<tag>|@<digest>][?sha256=<64 hex>]
tfs+oci://ghcr.io/tebako-packages/metanorma:1.2.3-linux-gnu-x86_64
tfs+oci://harbor.corp.internal/team/metanorma:1.2.3
tfs+oci://ghcr.io/tamatebako/tebako-runtime-ruby@sha256:<64 hex>
tfs+oci://127.0.0.1:5000/fixtures/tool:1.0 (loopback — §8)
DIGEST PINS (two distinct pins, never conflated):
@sha256:<64 hex> pins the MANIFEST digest (the OCI-native immutable form)
?sha256=<64 hex> pins the ARTIFACT bytes (the layer blob — the same
anchor vocabulary every other reference class uses)
ABNF (normative; the OCI distribution-spec name/tag grammars are incorporated, not re-invented):
oci-ref = "tfs+oci://" host [ ":" port ] "/" repo
[ "@" digest | ":" tag ] [ "?" "sha256=" 64HEXDIG ]
host = <lowercase DNS name | IPv4 | "[" IPv6 "]" | "localhost">
repo = component *( "/" component )
component = [a-z0-9] *( [a-z0-9] | ( "." | "_" | "__" | "-" ) [a-z0-9] )
tag = [A-Za-z0-9] *( [A-Za-z0-9] | "." | "_" | "-" ) ; ≤ 128 chars
digest = "sha256:" 64HEXDIG
MECE (locked): the tag splits at the LAST : (a host:port never collides — the host came off at the first /, exactly the tfs+github:// rule); @ selects the digest form; a reference carrying both :tag and @digest is Invalid. Repo names are lowercase-only per the distribution grammar — an uppercase byte in repo is a parse-time Invalid (65), never a downcasing guess.
The bare form tfs:oci:… is the named Invalid steering to the hosted spelling: "the OCI form is tfs+oci://<registry>/<repo> — there is no canonical OCI host; name the registry explicitly" (the UnsupportedService pattern of spec 37 §4: a refusal that teaches, never a guess). docker.io is reachable only as an explicit host (tfs+oci://registry-1.docker.io/library/…).
No #artifact concept. The tag/digest IS the selector; there is no multi-asset listing to disambiguate (the AmbiguousAssets class never fires on this adapter). Repo layout (one repo per payload, one repo per factory line) is publisher policy; the grammar fixes only the tag derivation (§3).
Both pins may ride one reference. Each is verified fail-closed at its moment: the manifest digest at manifest read (69/70 class below), the byte pin against the layer descriptor BEFORE the stream starts and again inline at end-of-stream (Sha256Mismatch, exit 70 — spec 04 §3's discipline, unchanged).
Spec 04 §1's dispatch table gains one row:
| scheme | adapter |
|---|---|
| tfs+oci: | the OCI distribution adapter (this spec) |
| anything else | named error listing the classes (the list gains the OCI form) |
A pre-OCI tebako reading a registry whose release.ref is tfs+oci: fails at parse with the named classes-listing error (65) — loud, never a guess (the additive rule does not cover a PRIMARY ref in an unknown class; that is exactly the spec 36 §4 compat-window behavior).
3. The artifact model (locked)
One OCI artifact per served file. Every artifact is an OCI image manifest (distribution-spec v1.1 form) with artifactType set, the empty config (application/vnd.oci.empty.v1+json, the canonical {} bytes), and EXACTLY ONE layer — the file's raw bytes. No tar wrapping, no compression: the layer blob IS the file, so the layer digest IS the artifact's sha256 — the .sha256 sidecar's exact equivalence (spec 05 §2/§4's anchor transfers without a second pin file). A manifest violating the shape (≠1 layer, a foreign artifactType, a missing required annotation) is the named OciArtifactMalformed (69), never a best-effort read.
| artifact class | artifactType | layer media type |
|---|---|---|
| payload image (.tfs) | application/vnd.tebako.tfs.v1 | application/vnd.tebako.tfs.v1+layer |
| runtime bundle (spec 36) | application/vnd.tebako.runtime-bundle.v1 | application/vnd.tebako.runtime-bundle.v1+tar.gz |
| registry index (tpkg-registry.yaml) | application/vnd.tebako.registry.v1 | application/vnd.tebako.registry.v1+yaml |
| detached OpenPGP signature | application/vnd.tebako.signature.v1 | application/vnd.tebako.signature.v1+asc |
| blksum sidecar (spec 39 §3) | application/vnd.tebako.blksum.v1 | application/vnd.tebako.blksum.v1+json |
Annotations mirror resolution fields only (the spec 03 §4 tier-3 rule — the registry mirrors, never duplicates authority). The full L1 manifest stays in-image (tier 1, authoritative); annotations carry the L3 subset, so a dispatcher never pulls a blob to resolve:
| annotation | content |
|---|---|
| org.opencontainers.image.title | the served file name (the shard's filename spelling for bundles — flowed, spec 05 §2's SSOT rule) |
| org.tebako.name / org.tebako.version / org.tebako.kind | the L1 IDENTITY mirror |
| org.tebako.triplet | the host triplet, or universal |
| org.tebako.entrypoints | comma-separated names (payloads) |
| org.tebako.runtime-requirement | the requirement object, JSON-encoded (payloads) |
| org.tebako.runtime.shard | the per-package shard JSON VERBATIM (runtime-bundle artifacts only — one manifest read replaces the shard fetch of spec 36 §4) |
| org.tebako.signature.keyid / org.tebako.signature.subject | the signer's PRIMARY keyid (spec 09 §9's primary rule) / the digest of the signed blob (signature artifacts only) |
| org.tebako.blksum.subject | the digest of the image blob the sidecar serves (blksum artifacts only — the sibling the tag is keyed by) |
Tag derivation (locked — the single owner of both rules is this section):
payload: <version> for universal, <version>-<triplet> per triplet (tebako version/triplet characters are a subset of the OCI tag grammar by construction).
runtime bundle: the bundle STEM verbatim (tebako-runtime-<ver>-<lang>-<lv>-<triplet> — spec 36 §2's spelling; the factory declares it, consumers flow it). The OCI lane opened with the post-tebako#716 grammar: pre-#716 (per-file-era) lines never publish to OCI, so a selector-less locator composes the new-era spelling only.
registry index: latest by convention; publishers MAY add version tags; operators pin with the @sha256: form.
signature: sha256-<64 hex of the SIGNED BLOB's digest>.asc — keyed by the signed bytes, derived deterministically from the layer descriptor the fetcher already holds. No listing, no guessing.
blksum sidecar (added with spec 39 §8's OCI arm): sha256-<64 hex of the IMAGE blob's digest>.blksum.json — the same sibling digest-tag rule as the signature's, keyed by the image bytes. The artifact's layer digest IS the sidecar document's own sha256 — the seed descriptor's blksum_sha256 pin (spec 39 §3) binds it with no second file.
Per-triplet tags, never an OCI image index (locked — the tebako#695 DECIDE). Platform selection in tebako is the REGISTRY's declarative job (spec 04 §2, locked: "the adapter NEVER auto-picks by host triplet"). An OCI index manifest would import a second, adapter-side platform matcher — and its os/arch vocabulary cannot express tebako triplets (linux-gnu vs linux-musl is a libc axis OCI has no word for; spec 05 §5's wheel-tag table rides the triplet axis alone for the same reason). One artifact per image under a per-triplet tag keeps the declarative law absolute, keeps byte-identity with the GitHub-releases artifact trivially auditable (same blob, same digest), and keeps the payload case and the runtime-pair case on ONE shape. A future multi-file need ships as a new artifact CLASS, never a second layer meaning and never an index.
Signatures ride sibling digest-tags, not the referrers API (locked). The v1.1 referrers API is the semantically rich form, but the issue's target set (ECR, ACR, Harbor, zot) is exactly where referrers coverage is uneven in 2026, and a referrers-required design would re-introduce per-registry capability negotiation — a silent capability matrix, the opposite of named errors. The sibling-tag form is distribution-spec v1.0-clean, deterministic, and preserves spec 09 §5's every-served-name rule literally: the served name (the tag) has its own .asc artifact, one signature covers exactly one artifact, nothing is ever "covered by" a container's signature. Referrers MAY be added later as an additive MIRROR (publish both); resolvers never require it. For tfs+oci release refs the registry row's signature.asc locator is DERIVED by the tag rule — an authored asc field on such a row is a named registry validation error (a locator that would be ignored is an authoring bug), while signature.keyid pins identity exactly as today.
4. The registry index over OCI (spec 04 §2 / spec 37 §4 amendment)
A tpkg-registry.yaml published as a §3 registry-class artifact is a REGISTRY LOCATION — the third location form, beside the git-host forms and spec 37 §4's tfs+https:// registry file:
tebako add-registry tfs+oci://harbor.corp.internal/team/tpkg-registry[:tag]
tebako add-registry tfs+oci://harbor.corp.internal/team/tpkg-registry@sha256:…
The alias derivation, the book model, require_signed, the official seed — all of spec 37 §2 applies unchanged (the alias derives from the ref's repo component).
TTL mapping (locked): a TAG-pulled OCI registry rides the dispatch-time cache exactly like the git-host default-branch form — registries/<sha>.yaml + .fetched-at, 24 h TTL, spec 05 §4's stale-serve on refresh failure (the manifest digest is recorded in the cache sidecar; a refresh that resolves the same digest re-serves the cached bytes, saving the blob pull). A DIGEST-pulled OCI registry is the pinned-immutable form — the analog of tfs:<svc>:owner/repo:version#tpkg-registry.yaml: cached forever, never re-fetched, TTL inapplicable.
TEBAKO_OFFLINE=1: cached-within-TTL serves; anything else is the named offline error. Unchanged semantics, new adapter.
5. The resolve/fetch path (spec 05 §2/§4/§6 amendment)
Manifest reads (and the shard/registry-YAML blobs they name) join the "small buffered GETs" class; the artifact blob is a spec 05 §6 FetchPlan ITEM — the pipeline owns transport, integrity, scheduling:
Manifest read. GET /v2/<repo>/manifests/<tag|digest> with the §6 credential decision; a ?sha256= byte pin is checked against the layer descriptor digest BEFORE the blob stream starts (a fail-fast 70, never a wasted pull); an @sha256: reference verifies the returned manifest against the pin (the registry's Docker-Content-Digest and the body digest must agree — 70 class).
Blob pull. GET /v2/<repo>/blobs/<digest> streams through the pipeline's HashWriter — one pass, constant memory, the inline sha256 compared against the layer digest AND any byte pin. The layer digest is the registry-supplied trust anchor; the store's .sha256 marker is written from it, byte-identical in shape to today's sidecars.
Commit. The commit closure owns install semantics exactly as today: the store's per-entry flock (120 s, stale-lock hint), tmp + rename, the spec 05 §4 commit order (the manifest mirror is the commit point — a version whose mirror is absent was never installed), signature verification per spec 09 BEFORE the bytes enter the cache. A partial pull is invisible by the same proof.
Runtime bundles. A kind: runtime row whose release.ref is tfs+oci: resolves through spec 37 §8's chain: the locator derivation (release_download_locator) gains the OCI arm, and the fetch runs the bundle flow below. OCI runtime distribution is bundle-era only: per-file-era lines stay on their git-host releases forever (keep-forever, spec 13 §8) and never publish to OCI.
The fetch tag. A selector-less locator tags the bundle STEM (tebako-runtime-<ver>-<lang>-<lv>-<triplet> — §3's tag rule, the factory's spelling flowed verbatim; the OCI lane is post-tebako#716, so only the language-carrying spelling exists here); an authored :tag or @sha256: selector rides exactly as written (spec 37 §8's authored-selector law).
One manifest read replaces the shard fetch. The per-package shard comes from the bundle manifest's org.tebako.runtime.shard annotation (§3) and is gated THREE ways before any blob streams: the shard's identity triple (<engine>_version / tebako_version / platform) must match the runtime being resolved — a mismatch means the tag resolved another runtime's publish (69); the shard MUST declare a bundle block — a per-file-era shard over OCI is the named bundle-era-only refusal (69), never a per-file fallback; and the layer descriptor digest — which IS the bundle's .sha256 sidecar (§3) — must agree with the shard's bundle pin (a disagreement is 70, nothing installed).
The plan re-resolves by digest. The FetchPlan item re-reads the ALREADY-RESOLVED manifest by its digest — the tag's mutability never reaches the stream — and streams the one bundle layer under the RuntimeBundle shape law; spec 36 §4 then runs VERBATIM (the signature verified FIRST — the .asc sibling digest-tag derived from the signed blob's digest, a declared-but-unfetchable signature refused 71 exactly like the git-host lane — then bundle digest → in-process unpack → per-member pins → the spec 05 §3 layout). The staged store entry is indistinguishable from a git-host bundle install, the origin markers excepted (point 5's digest-pinned form).
The lazy mode degrades loud. OCI serves the bundle whole — there is no per-file arm and no blksum probe on this channel — so the lazy mount mode against an OCI source is the loud eager fallback (event=lazy-fallback reason=oci-bundle-era-only) and the install completes eager.
channel: oci covers runtime rows. A book entry declaring channel: oci (§11) routes the picked runtime row through its per-triplet oci: mirror field — fail-closed exactly like the payload lane: a universal row, a host-covered row lacking the mirror, or an unparsable one is a named 65 error naming the registry and the row; never a fallback to the primary release.ref.
The origin marker records the concrete digest-pinned form (tfs+oci://<host>/<repo>@sha256:<manifest digest>) even for tag pulls — spec 37 §7's origin binding and tebako cache list work unchanged, channel included.
The retry/throttle law is tebako-http's, per worker per connection, unchanged; the plan-cancel failure law is spec 05 §6's, unchanged (first named error surfaces, every tmp dropped, nothing partial in the store).
6. The credential chain (spec 37 §5 amendment)
The two-tier book is untouched in shape; the OCI adapter adds one fallback tier and the distribution-spec token flow:
Tier 1 — the directing registry's alias, confinement included (the tier-1 allowed_hosts set for an OCI registry is its registry host; derivation rides the same base-URL construction SSOT).
Tier 2 — the URL's exact host.
The docker/config.json fallback (NEW, OCI-class URLs only): static auths[<host>] entries (the base64 user:pass pair) from ~/.docker/config.json (plus $DOCKER_CONFIG), journaled as token:docker-config:<host>. credHelpers/credsStore entries covering a referenced host are the named DockerCredentialHelperUnsupported (65) — helpers are shell-outs, forbidden by the no-shell-outs law, and the steer says so (move the token into a credentials: entry's env var). An unparsesable docker config is DockerConfigMalformed (65), never a silent skip.
Anonymous.
The Bearer token flow (normative): every registry call runs the distribution-spec challenge dance — on 401 with WWW-Authenticate: Bearer realm=…,service=…,scope=…, GET the realm with the basic credential (user:password; the token_env value MUST carry the pair — a value without : is CredentialRequired naming the expectation, never a username guess), then ride the returned bearer. Anonymous pulls challenge identically without credentials (GHCR's anonymous-token shape). Tokens cache per process keyed by (realm, service, scope, credential class); a 401 against a cached token re-challenges ONCE, then fails named. A malformed or Basic-only challenge is OciTokenChallengeInvalid (69).
Confinement (locked, spec 37 §5's rule extended): the basic credential is presented to the challenge REALM via the ordinary book lookup on the realm URL's host — a realm whose host is not the registry host matches its own tier-2 entry or is the named OciCrossHostAuthRefused (69) steering the operator to add one (this covers docker.io's auth.docker.io with zero special cases and zero hardcoded hosts). The returned bearer rides ONLY to the registry host — never cross-host, never to a redirect target (ureq's RedirectAuthHeaders::Never stands).
The header shape by service class gains the OCI row: Authorization: Basic <base64(user:pass)> to the realm, Authorization: Bearer <token> to the registry — the adapter owns the shape; authored config never spells header mechanics.
Every fetch journals host + credential class, values redacted — spec 37 §5's audit trail, new classes (token:docker-config:<host>) included.
7. The publish path (spec 04 §2 / spec 16 §5 amendment)
The normative publisher is tebako publish — the OCI leg is in-process (blob mount attempts first, monolithic POST+PUT upload, manifest PUT), never the ORAS CLI (the no-shell-outs law binds shipped artifacts and tests; ORAS in a CI workflow is permitted sugar, never the contract).
tebako publish … --oci tfs+oci://<host>/<repo> uploads each payload's §3 artifact (plus signature artifacts when signing, plus the blksum sidecar sibling for every payload the staged sidecar exists for — spec 39 §8) from the SAME staged bytes the git-host release leg uploads, and writes the additive oci: mirror field into the registry row it maintains:
platforms:
x86_64-linux-gnu:
artifact: metanorma-1.2.3-linux-gnu-x86_64.tfs
sha256: "…"
oci: tfs+oci://ghcr.io/tebako-packages/metanorma:1.2.3-linux-gnu-x86_64Figure 64 Write-once (the release-immutability rule transferred, spec 13 §2a): publish refuses to point an existing tag at a DIFFERENT digest — OciTagConflict (69) naming the tag and both digests. Re-publish of identical bytes is the idempotent skip, as today. Tags are mutable in the OCI model; tebako treats them as immutable by policy, and withdrawal stays status: withdrawn (spec 04 §2), never a tag delete.
Feedstock adoption is additive and non-disruptive: the publish invocation gains the flag; without it, bytes, rows, and workflows are exactly today's. Pre-OCI readers ignore the oci: field (spec 37 §2's forward-compat leniency for unknown registry keys).
Runtime factories: the tebako-release publish leg pushes the §3 bundle artifact + shard annotation + signature artifact per leg on bundle-era lines (spec 36 §6's topology unchanged — the OCI push is the same invocation's second sink, and the line-shard escape hatch is RETIRED on OCI-published lines: there is no ceiling to shard against). The factory-side wiring lives in the factory repos; the wire shape is §3's and lands with the product PRs.
8. Security and trust invariants
HTTPS-only (locked). A non-https OCI URL fails at parse/fetch with OciInsecureTransport (65) — there is no insecure-registry spelling and there never will be (spec 04 §4's no-verify-off law). The single carve-out is LOOPBACK (localhost, 127.0.0.0/8, ::1) over plain HTTP, existing for the §9 test fixture and local development; it can never name a remote host.
TLS roots ride tebako-http's one agent (spec 04 §4): webpki-roots default, TEBAKO_TLS_PLATFORM_ROOTS, additive extra_ca — internal registries under an enterprise CA are the extra_ca case, and the proxy policy (CONNECT, 407 naming) applies to token and blob calls alike. No second client anywhere in the adapter.
Signature strictness is spec 09's, unchanged: a declared signature verifies strict (71 invalid / 72 untrusted keyid, the primary-keyid resolution of spec 09 §9 included); a declaration whose .asc artifact does not fetch is the invalid-signing-state 71; unsigned fetches warn loud + journal and fail closed under TEBAKO_REQUIRE_SIGNED=1; require_signed on the book entry binds OCI rows exactly as git-host rows (spec 37 §2.2). The store markers keep their semantics — verification at fetch/install, never per run.
Trust-anchor equivalence (locked): the layer digest IS the artifact sha256. A registry row's sha256 pin, a ?sha256= reference pin, and the layer descriptor must agree or the fetch fails (70) — three spellings of one anchor, never three anchors.
9. Failure semantics, offline, and the named errors
TEBAKO_OFFLINE=1 is cache-or-named-error per adapter: cached store entries serve; any manifest/tag resolution is the named offline refusal. The plan-cancel law (spec 05 §6) makes every partial pull — manifest half-read, blob half-streamed, signature missing — invisible: tmp files dropped, nothing renamed, the first named error surfaced.
| Name | Exit class | Moment |
|---|---|---|
| Invalid (re-scoped; OCI reasons) | 65 usage | parse: uppercase repo, bad tag/digest, :tag+@digest, bare tfs:oci: (steers to the hosted form) |
| OciInsecureTransport | 65 | non-HTTPS registry URL off loopback |
| DockerConfigMalformed | 65 | the docker-config fallback consulted and unparsesable |
| DockerCredentialHelperUnsupported | 65 | a credHelpers/credsStore entry would answer — the no-shell-outs steer |
| OciManifestNotFound / OciBlobUnknown | 69 unavailable | NAME_UNKNOWN / MANIFEST_UNKNOWN / BLOB_UNKNOWN / TAG_INVALID mapped by name |
| OciArtifactMalformed | 69 | §3 shape violation — ≠1 layer, foreign artifactType, missing required annotation |
| OciTokenChallengeInvalid | 69 | malformed or Basic-only WWW-Authenticate; unusable token endpoint |
| OciCrossHostAuthRefused | 69 | challenge realm host ≠ registry host and no book entry covers the realm — steer: add a tier-2 host: entry |
| CredentialRequired (reused) | 69 | 401/403 with no usable credential — names registry + env var looked for |
| OciAdapterDisabled | 69 | tfs+oci: reached a build with the oci feature off (§10) |
| OciTagConflict | 69 | publish: tag exists at a different digest — write-once |
| Sha256Mismatch (reused) | 70 integrity | pin/layer/bytes disagreement — nothing cached |
| spec 09 classes | 71 / 72 | signature invalid / signer untrusted / declared .asc unfetchable |
Each maps to exactly one CI tier's assertion; none is a fallback.
10. Capability gating (spec 04 §3's general rule, applied)
The adapter is a cargo feature oci on tebako-resolve (backing the new tebako-oci client crate) — default ON for the toolchain (tebako CLI, tebako-shim, tfs CLI), OFF for the size-gated tebako-bootstrap, where a tfs+oci: reference fails closed with the named OciAdapterDisabled (the GitAdapterDisabled precedent: steer to managed mode). The bootstrap's own runtime base stays the spec 05 §2 default + TEBAKO_RUNTIME_MIRROR (https/file) — OCI runtime distribution enters through the toolchain's registry-derived channel, and the 3 MiB gate never pays for it.
11. Migration and coexistence (locked)
Dual publish is the norm during migration: the same bytes ride the git-host release AND the OCI repo from one publish invocation; the row carries both locators. The sha256 pin binds both — a mirror serving different bytes is a 70, so the channels can never silently diverge.
Channel selection is DECLARED, never probed. The primary release.ref resolves by default (today's behavior, unchanged bit for bit). A registry-book entry MAY declare channel: oci (spec 37 §2's config model): rows then resolve through their oci: field, and a row lacking one is a named error naming the row — fail-closed, never a fallback to the primary. There is no both-fetch, no race-the-channels, no failover.
The ambiguity law is untouched. A payload name in an OCI-hosted registry AND a git-host registry is AmbiguousRegistries exactly as spec 37 §3 (the oci: row field is not a registry and adds no ambiguity axis); origin binding (spec 37 §7) confines version chains to the resolving registry and records the channel in the origin marker; a rebind across channels follows the same explicit reinstall
journaled origin-rebind discipline.
12. Test plan (the tiers of spec 14; each failure above maps to one tier)
Unit (tebako-resolve): the §2 grammar — round-trip parse/display for every form (tag, digest, both pins, port, loopback, IPv6), every malformed class by name; tag and signature-tag derivation; the §3 annotation map; challenge parsing; docker-config parsing and the helper refusal; the credential chain order (tier-1 confinement into OCI hosts, realm-host lookup).
Property (proptest, the crate's existing harness): arbitrary valid references round-trip; arbitrary garbage never panics and never parses silently (a named error, always); tag derivation injective per (version, triplet).
Contract (the Transport mock, canned distribution-API answers): challenge→token→manifest→blob happy path; the error-code map (NAME_UNKNOWN→OciManifestNotFound, …); media-type/shape refusals; cross-host realm refusal; token re-challenge-once; store-equivalence — an install from OCI and from file:// of the SAME bytes yields identical store records except the origin marker (the parity arm of spec 00 invariant 8).
E2e (ci/, tiered): a zot fixture — a pinned zot binary (CI tooling, fetched at workflow time, never a shipped dependency) configured in-tmp on 127.0.0.1:<port> over plain HTTP, exercising exactly the §8 loopback carve-out. Legs: publish payload + signature → add-registry over OCI → install → run the entrypoint; digest-pinned pull; offline refusal; TEBAKO_REQUIRE_SIGNED=1 pass/fail; tag write-once conflict on re-publish; (with spec 36) the runtime-bundle leg — factory-shaped bundle push → dispatch-time runtime fetch → run. A nightly live-GHCR smoke leg mirrors the existing live-GitHub legs.
13. Open questions (each with this spec's recommendation)
The issue's tfs:oci: sketch vs tfs+oci://. Recommended and locked: tfs+oci:// — spec 37 §4 puts every explicit host in the tfs+<svc>:// shape, and tfs:<svc>: names a canonical SaaS host, which OCI deliberately lacks. The bare form is the teaching refusal.
Referrers API for signatures. Recommended: sibling digest-tags (locked, §3); referrers as a later additive mirror once ECR/ACR/ Harbor coverage is uniform. Revisit no earlier than the first registry-conformance survey.
docker credHelpers/credsStore. Recommended and locked: refuse by name (65). Helpers are process shell-outs; invariant 1 admits no exception, and the env-indirection book already expresses every static case.
Plain-HTTP internal registries. Recommended and locked: refuse; loopback only. Internal CAs are the extra_ca feature's case (spec 04 §4) — an insecure-registry knob would be the verify-off spelling that spec bans.
?sha256= on tfs+oci: references. Recommended and locked: pins the ARTIFACT bytes (the layer blob), keeping the cross-class anchor vocabulary; @sha256: pins the manifest. Both fail-closed.
Chunked/resumable blob upload. Recommended: monolithic POST+PUT in v1 (bundles are ≲150 MB; tebako-http already carries UPLOAD_TIMEOUT); chunked upload lands only when a measured publish needs it.
OCI as TEBAKO_RUNTIME_MIRROR. Recommended: out of scope. The bootstrap keeps https/file bases (§10); OCI runtime distribution enters through the registry-derived toolchain channel.
Tag mutability. Recommended and locked: write-once by publish policy (OciTagConflict); the digest form is the pin; withdrawal stays status: withdrawn, never a tag delete.
Image indexes for multi-triplet artifacts. Recommended and locked: rejected (§3) — platform selection is the registry's declarative law; OCI's os/arch vocabulary cannot speak tebako triplets.
One repo per payload vs shared repos. Recommended: publisher policy (one repo per payload name is the convention); the grammar fixes only tag derivation, so no resolver behavior depends on the choice.
Implementation plan (spec PR first; each PR independently mergeable)
PR 1 — the spec. This document + 00-INDEX.md entry + the registry JSON Schema's additive oci: field. No code.
PR 2 — the pull path, end-to-end. tebako-oci crate (model + auth + client), Reference::Oci grammar, fetch/pipeline integration, credential chain (docker fallback, realm confinement), registry-YAML-over-OCI (add-registry), the oci cargo feature + OciAdapterDisabled, and the full unit/property/contract tier + zot e2e pull legs. Readers accept and resolve oci: row fields (primary-ref resolution only; channel: declaration not yet).
PR 3 — the publish path + mirror coexistence. tebako publish --oci (artifacts, signature artifacts, write-once OciTagConflict, oci: row mirror write), the book's channel: oci declaration with fail-closed row errors, zot e2e publish→install→run legs, tebako.org tier-4 how-to (separate repo).
PR 4 — runtime bundles over OCI. Shard annotations, the release_download_locator OCI arm, dispatch-time runtime fetch through spec 37 §8's chain, e2e bundle legs. Sequenced with spec 36's landing; if 36 slips, PRs 1–3 still deliver the full payload/registry value of the issue.
TBK SPEC 39 — Lazy range-fetch mounting of runtime images
Status: SHIPPED (locked direction 2026-09-30, tebako#696 — spec-first per spec 14). PRs 1–6 shipped the spec + schemas, the Range transport (tebako-http), the byte-source seam + caching remote source + lazy store record (tfs/tpkg), the loader + driver wire (resolve plan lazy arm, shim/bootstrap wire, the state-detecting env-image mount, the background seal thread, tebako cache seal + the listing/doctor surfaces), the publish path (in-process blksum generation + the additive image.blksum index field), and the OCI range arm + the bench arms (§8, spec 27 §10.5). Since then the downstream legs have landed: the lazy-capable runtime releases, the §10 parity data, the default flip (§7 — lazy-on by default, locked), and the cached-blksum arm (§3 — the install-time sidecar prefetch that keeps the mount-open zero-network). Nothing here changes what a shipped loader, driver, or resolver does with a store that carries none of the new artifacts: a sidecar-less release takes the loud eager fallback and every published image remains runnable exactly as today.
Normative specification of lazy mounting: the runtime env image is mounted over HTTPS with HTTP Range reads, the machine cache is seeded block-group by block-group on demand, and a background seal pass turns the partially-seeded entry into an ordinary, fully-verified store entry. This spec owns the remote-locator hook recorded in spec 20 §7 ("Remote locators (http/s3/ipfs) → a future streaming spec").
1. Why — and why LimniFS fits lazy pull better than eStargz fits tar
First run of a lean (shared-runtime) package downloads the whole runtime pair (100–300 MB) before one user byte executes. Containerd's lazy-pull line (eStargz/SOCI/nydus) proved the fix at the format level; Harter et al. (FAST'16) measured pulls at 76% of container start time while only 6.4% of pulled bytes are ever read.
eStargz needed a format change to make lazy pull possible: tar is a streaming format with no index, so stargz added a TOC, per-member gzip streams, and landmark headers — a new wire shape that only new images carry. LimniFS needs none of that. It is seekable by construction (spec 20 §4): the inline metadata blob resolves path → inode → drop slices; the slab record tables carry each drop's byte offset and length; pread materializes only the drops intersecting the requested window (a seekable-container drop decodes only the covering 256 KiB frames). Every LimniFS image ever published is already a lazily-fetchable set of byte ranges. The lazy feature is therefore a READER-side change only — no format change, no new in-image section, no republication of image bytes (§9).
Scope, locked for v1: the runtime env image (TEBAKO_RUNTIME_IMAGE) in managed dispatch (tebako-shim) and standalone dispatch (tebako-bootstrap). The interpreter exe is always fetched whole — the kernel execs a file, not a mount. Payload slices ride the same machinery later (§11).
2. The seam: a mount-source kind, NOT a format backend
The issue's sketch ("a new TFS backend http-range beside zip/dwarfs-t/squashfs/tar") is refined against the shipped seam. The spec 11 Backend trait (crates/tfs/src/backend.rs) is path-addressed and format-keyed: stat/pread/read_dir/read_link by in-image path, selected by magic detection (spec 20 §3). Transport is not a format — format_id answers only "how do I read these bytes" (orthogonality law, spec 00). An HTTP Range transport placed at the Backend seam would either fake a format (wrong) or re-implement one (duplicated authority).
The correct layer is the one below the format backend. Spec 11 §5's mount-source kinds (host-file, memory, file-region, VFS-file-region) all serve positioned byte reads into the mount constructors (crates/tfs/src/mount.rs). This spec adds a fifth mount-source kind: remote-range, behind a byte-source abstraction:
transforms (COW / ENC — Rust TFS only, spec 00 invariant 5, spec 11 §4)
→ format backend (limnifs; detection unchanged)
→ ByteSource: host file | memory | file region | VFS region | REMOTE-RANGE
The transforms-law answer (precise): the lazy source sits UNDER the format backend, at the byte layer. COW and ENC stack ABOVE the format backend exactly as today — a COW overlay over a lazily-mounted env image writes to its HostDir store and never touches the network; an ENC transform decrypts bytes the source already supplied. The transforms law is untouched: the remote source is read-only, and no backend learns to write.
The Backend trait is unchanged. No new trait methods; detection unchanged (the 512-byte sniff is one small range read at open); writable() stays None.
The limnifs adapter gains a sourced open beside LimnifsBackend::from_image(Vec<u8>) (crates/tfs/src/backends_limnifs.rs): mount-open fetches, through the caching byte source, the manifest prefix (header → feature flags → metadata reference + inline metadata blob → slab index → history — the self-delimiting walk the adapter already performs) and each slab's record table; slab drop payload bytes are fetched on demand at pread time. Prerequisite (upstream, limnifs repo): limnifs-core gains a paged SlabSource variant (today: Memory/Mapped only) and a record-table parse over a positioned reader. Reader-side only — no format change. The dwarfs backend's in-place positioned reads make a dwarfs-over-range source possible later across the C++ callback boundary; recorded, NOT committed (§11).
Feature gating (spec 20 §5's rule applied): the remote-range source is a cargo feature backend-remote on tfs, default ON for tebako-driver and the toolchain, never in tebako-bootstrap (which never mounts, spec 20 §1 — §9). A lazy mount attempted on a build without the feature fails with the NAMED ENOTSUP — the compiled-out rule, unchanged.
3. The trust decision (locked): per-block-group digests at read, whole-file sha256 at seal
The issue's open question — whole-file sha256 at seal vs per-block-group digests at read — is decided: per-block-group digests at read is the PRIMARY design; the whole-file sha256 verifies at seal as the mandatory second anchor. The rejected alternative (whole-file verify only at seal) is rejected on the threat model, not on convenience.
Threat model. Today's law (spec 05 §4): verification at fetch/install, never per run — the payload never executes a byte that was not verified against the .sha256 trust anchor first. A seal-only lazy design breaks that law for the entire seeding window: a malicious or compromised registry (or a TLS-intercepting path the enterprise roots admit, spec 04 §4) could serve self-consistent bad blocks, and the payload would EXECUTE them on first run; the seal would fail loudly only afterwards. That is a strict weakening of the shipped trust posture and is unacceptable. (The image's own content addressing — LimniFS drop ids are BLAKE3(plaintext), spec 20 §1 — detects corruption and bit-rot but is NOT a trust root: a hostile registry serves a self-consistent evil image whose ids match its own evil metadata.)
The design.
Fetch unit = the block group, a locked 4 MiB span of the IMAGE bytes (the wire bytes — format-agnostic, so the same source later serves dwarfs; the final group is short). Groups align all cache, verification, and progress accounting (§4, §7).
The digest sidecar — <image>.blksum.json, published beside the image by the PUBLISHER (the runtime factory / the feedstock publish leg; tebako publish generates it in-process in the same invocation that stages the release bytes): a versioned JSON document (schema/tpkg-blksum-v1.schema.json) carrying schema_version, group_size, size_bytes, the whole-image sha256, and one sha256 per group. A resolver NEVER derives it (derivation would require the whole file — pointless — and would arrive unanchored). Three callers reach the ONE emitter (tpkg::lazy::write_sidecar): tebako publish (in-process, for payloads it stages), tebako blksum and tfs blksum. The last two exist because a runtime factory images with tfs and publishes through its own tooling — without a verb on the binary the leg already runs, a runtime pair can ship with no sidecar and lazy seeding can never engage (tebako#868). No second implementation of the group scheme exists, by construction.
The sidecar's own anchor rides the existing channel, additively: the release shard/registry row gains image.blksum: {filename, sha256} (mirror-only, spec 03 §4's tier-3 rule); where the index is signed (spec 09 §5) the field is covered exactly like image.sha256. The sidecar is fetched and verified against that pin BEFORE the first range read; a sidecar whose bytes do not match its pin is the named Sha256Mismatch (70) — nothing mounts.
Trust at read (the protection point, exactly): every Range GET's bytes are sha256-verified against the sidecar's group digest BEFORE they enter the block cache and BEFORE any byte is served. A group whose digest mismatches is dropped, refetched once, and on a second mismatch is the named Sha256Mismatch (70) — the mount fails closed, never a silent serve. This is today's verify-at-fetch law at group granularity; the per-run law holds unchanged (a cached group serves without re-verification — the cache is trusted once written, exactly like today's sealed entries). The user is therefore protected from the FIRST byte of the FIRST run — no execution of unverified bytes, ever.
Whole-file sha256 at seal (mandatory second anchor): the seal pass (§5) assembles the entry's .tfs from the verified groups and verifies the whole-file sha256 against the original pin before the entry flips to SEALED. The .sha256 sidecar written at seal is byte-identical in shape and meaning to today's anchor. Defense in depth, and what makes a sealed entry indistinguishable from an eagerly installed one.
Missing sidecar → LOUD eager fallback (locked). Lazy is requested but the release publishes no sidecar (every pre-2026 image): the loader fetches the whole image exactly as today (whole-file sha256 verify — EQUAL trust strength, no downgrade), with a stderr warning + journal line (event=lazy-fallback reason=blksum-missing) naming the artifact. Never a hard error — every published image must stay runnable — and never silent (invariant 9; the spec 05 §4 stale-serve precedent for loud degradation).
The cached-blksum arm (locked, with the §7 flip). The loader fetches and pin-verifies the sidecar at INSTALL time regardless — the seed decision needs it — so the install also writes it into the entry (<image>.blksum.json, tmp+rename, BEFORE the descriptor's commit rename). The mount-open consults the cache FIRST: a verified hit is a zero-network open (nothing the exec phase owes the wire); a miss fetches as before and writes through (best-effort — the verified blksum is already in hand, so a cache-write failure never fails the mount); a cached file off its pin or torn is the named Sha256Mismatch (70) / BlksumInvalid (65), never a silent drop-and-refetch — the cache is a publisher-anchored document's copy. Two consequences the flip needs: the offline refusal for a FRESH seed fires at the install/pull phase (pre-exec) instead of surfacing as a mount-open 69 mid-exec, and the mount-open of every entry seeded after this arm performs no sidecar GET at all.
4. Cache design and the store-state amendment
Layout (inside the existing runtime entry, spec 05 §3 — LAZY_SEEDING state only):
runtimes/<lang>-<lv>-<ver>-<triplet>/
tebako-runtime-<ver>-<lang>-<lv>-<triplet>[.exe] # exe — always whole, always verified (0755)
sha256 / origin # exe markers, unchanged
<image>.lazy.json # the seed descriptor — present ⇔ LAZY_SEEDING
<image>.blksum.json # the install-time sidecar cache (§3's cached-blksum arm)
<image>.blocks/<NNNNNN>.blk # verified group payloads (0444)
<image>.tfs # appears ONLY at seal (0444)
<image>.tfs.sha256 / <image>.tfs.origin # written at seal — today's shapes, unchanged
The seed descriptor (<image>.lazy.json, versioned JSON, the blksum schema's sibling schema/tpkg-lazy-seed-v1.schema.json): source URL (the concrete origin), the whole-image sha256 pin, the blksum sidecar's sha256, group_size, size_bytes, group count. Written tmp+rename under the entry's flock (spec 05 §4) by the loader INSTEAD of the image download. A descriptor that fails validation at open is the named LazyDescriptorInvalid (65) — never a guess.
The block map IS the directory. Present *.blk files are the seeded set; no separate bitmap, no journal. Open scans the directory and validates each group's size against the descriptor; a size-mismatched or unparseable group file is discarded and refetched.
Crash consistency: per group, fetch → verify → write tmp → rename, under the entry's flock. A crash mid-write leaves a .part that the next open drops. A group file present = verified, by construction.
The store-law amendment (scoped, locked): spec 05 §4's "a runtime is either fully installed or not" gains exactly one middle state. A LAZY_SEEDING entry (exe + markers present and verified, descriptor present and valid, image ABSENT) IS runnable — that is the feature — and counts as INSTALLED for resolution (the newest-compatible-cached pick, spec 05 §5, must see it, or every run re-resolves and re-seeds), but is reported distinctly by every listing surface (§7). The commit point for the lazy install is the descriptor's rename; the commit point for the SEALED entry stays the .sha256 anchor's rename. No other store invariant moves: tmp+rename everywhere, per-entry flock (120 s, stale-lock hint), read-only artifacts, a run re-verifies nothing that is cached. cache prune removes a lazy entry like any other (descriptor, blocks, and all).
The exe is never lazy and the runtime store entry's exe half installs exactly as today (the spec 05 §5 chain, the spec 06 §3 contract gate, the spec 09 §4 verification point — all before the seed descriptor is written).
5. The seal path and the state machine
States (named, on disk):
EMPTY → (loader: exe install + descriptor rename) → LAZY_SEEDING
LAZY_SEEDING → (seal: all groups present → assemble → whole-sha ok
→ .tfs + .sha256 rename → blocks + descriptor + blksum
cache removed) → SEALED
SEALED ≡ today's ordinary entry — byte-identical layout, anchors, semantics
The background seal thread lives in the DRIVER (inside the runtime exe — the process that holds the mount): spawned after the env image mounts, it fetches the missing groups in index order, one at a time, on the same byte source (and therefore the same verification). Its scheduling law: on-demand reads always preempt — a touching read's group fetch jumps the queue; the seal fills gaps around demand. It renders NO progress inside a running payload (stderr belongs to the payload after handoff — spec 11 §11 discipline; seal activity logs to tebako-log at debug, component driver).
Cancellation and resumption: process exit simply stops the thread — the block cache persists; the next run (any package sharing the entry) resumes from the directory scan. Seal is best-effort forever: a run NEVER blocks on it, never fails because of it (a seal-side fetch failure logs and retries next run). TEBAKO_LAZY_SEAL=0 disables the background thread (the debug/airgap shape; on-demand seeding still works).
The commit: with all groups present, seal assembles <image>.tfs by concatenation into a tmp file, streams the whole-file sha256 over it (one pass, constant memory — the spec 05 §6 discipline), compares the original pin (mismatch → named 70, the assembled tmp dropped, the groups kept — a group verified against a publisher-anchored sidecar cannot silently disagree with the pin; a disagreement is evidence of a publisher-side or anchor-side fault and is reported, never healed), renames .tfs (0444), then .tfs.sha256 + .tfs.origin (the anchor's rename is the commit point), then removes the blocks and the descriptor. A crash anywhere before the anchor rename leaves LAZY_SEEDING, fully resumable.
The explicit verb: tebako cache seal [<entry>|--all] runs the same pass synchronously from the toolchain — full tebako-term ProgressSet rendering (§7). Operators who want first-run-lazy but warm-cache-complete run it at their convenience.
Subsequent mounts of a SEALED entry take the ordinary whole-file path — the lazy machinery is out of the loop entirely.
6. Failure semantics (named, never a partial mount)
Mount-open failures (prefix or record-table fetch fails, sidecar pin mismatch, descriptor invalid): the env image mount fails BEFORE the boot proceeds — the driver's existing unmount-everything law (spec 17 §1; crates/tebako-driver/src/driver.rs) applies verbatim: never a partial mount, the named error surfaces.
Network partition mid-mount: a touching read whose group cannot be fetched after the retry law exhausts returns EIO on that read (the errno channel), named on the tebako-log with URL, group index, and the transport cause. The payload sees an ordinary IO error; the mount and every cached group remain valid; the next run resumes. Never a fabricated zero-fill, never a silent short read of unverified bytes.
Retry/backoff: tebako-http's law, unchanged and unrepeated — Retry-After honored exactly, the 60 s × 2ⁿ hintless exponential, THROTTLE_ROUNDS, DOWNLOAD_ATTEMPTS (spec 05 §6, crates/tebako-http). A mid-stream group failure retries THE GROUP from zero (a partial group would fail its digest anyway — the pipeline's artifact rule at group scale).
TEBAKO_OFFLINE=1: cache-or-named-error at group granularity. Cached groups serve (a fully-seeded-touched working set runs offline); a miss is EIO on the touching read, or — at mount-open, when the prefix is not yet cached — the named offline refusal. Unchanged semantics, finer grain.
Exit codes (reuse, never extend — the 65–79 space stands):
Table 32 condition class descriptor invalid, lazy config malformed, non-HTTPS source 65 usage mount-open fetch failure; offline miss; server unusable 69 unavailable sidecar pin mismatch; group digest mismatch (2nd); whole-sha mismatch at seal 70 integrity cached blksum torn (65) / off its pin (70) — the §3 cache arm 65 / 70 store IO (lock, block write, assemble, rename) 74 IO spec 09's 71/72 bind the sidecar's signed-index chain exactly as they bind the image's today; TEBAKO_REQUIRE_SIGNED=1 fails closed before the first range read, unchanged.
HTTPS-only (locked): the source URL is https:// or file:// (the test/airgap spelling), enforced by tebako-http's existing refusal — plus the spec 38 §8 LOOPBACK carve-out (localhost, 127.0.0.0/8, ::1 over plain HTTP) for the §10 fixture only. There is no insecure-source spelling and never will be. TLS roots, proxy policy, and credentials ride tebako-http's one agent (spec 04 §4/§5) — no second client, and the credential book confines range requests exactly like whole-file GETs.
7. UX: mount mode, progress, doctor
The mount-mode chain (the flip LOCKED 2026-10-07, spec-00-style note). The default is lazy-on: a runtime install on a release serving the lazy wire seeds the env image instead of fetching it whole. Resolution: TEBAKO_RUNTIME_LAZY (env) over runtime_lazy in ~/.tebako/config.yaml over the product default ON — env wins per key (the TEBAKO_FETCH_JOBS / spec 04 §4 precedence rule), an unparseable value is a NAMED error (65), never a silent clamp. Eager stays first-class as the opt-out (TEBAKO_RUNTIME_LAZY=0, runtime_lazy: false). The division of authority is locked: the PUBLISHER controls enablement only — it ships the blksum sidecar or not (§3; there is no publisher forcing knob and never will be, because correctness is mode-independent); the USER/MACHINE controls the effective mode through the chain above. Hard rules outrank every tier, unchanged: TEBAKO_OFFLINE=1 is cache-or-named-error (a fresh seed refuses at the pull phase, §3's cached-blksum arm); fat packages never fetch; a sidecar-less release takes the loud eager fallback. The flip's gate was §10's parity data; the landed numbers are recorded there.
The bundle-era gate (spec 36 §3's co-publish). Both loaders (shim and bootstrap) evaluate the lazy arm BEFORE the spec 36 §4 era branch. On a shard declaring bundle, the arm engages ONLY when the shard also carries the co-publish witness (per_file_assets: true, runtime-manifest MINOR 2 — the exe/image/dll are then served standalone by construction); a bundle-declaring shard without the witness stays eager by construction (its one tar fetch IS the runtime). When the arm engages on a bundle-declaring shard, the install fetches the exe (+ the windows DLL) by the shard's per-file pins and seeds the image; the bundle is never fetched. Every other rule of this section is unchanged: a missing sidecar is the loud eager fallback, a torn pin the named error, a mismatch exit 70. The eager default on bundle-era lines stays the bundle fetch.
The host-tier gate (tebako#853). The lazy wire is chosen only where the HOST's boot tier can read a seeded entry (tpkg::lazy::host_boot_reads_lazy — the single owner of that answer, consulted by the shim and both bootstrap planners). The POSIX tiers read through the lazy byte source and qualify; the windows materialize tier (spec 17 §7) extracts a host tree from the env image FILE, and a seeded entry has none until the seal commits — so on windows the opt-in takes the loud eager fallback (event=lazy-fallback reason=windows-materialize-tier, the journal line included) and the first run works; an OCI source names its own host-independent cause first (reason=oci-bundle-era-only). A seeded entry that arrives on a windows store by other means still refuses by name in the driver, unchanged.
Progress. The loader's lazy first run renders through tebako-term (the spec 06 §5/§5a wiring rule — nothing else prints download progress): the exe's ordinary artifact bar, then one line — runtime env image <name> (<size>) — lazy: seeding on demand, sealing in background. tebako cache seal renders the block map as a ProgressSet slot — sealing <image> [<bar>] 62% (groups 831/1340, 3.1 MB/s) — group-accurate, not estimated. Plain mode and TEBAKO_NO_PROGRESS=1 behave per spec 06 §5a, unchanged.
tebako doctor (spec 35) store section gains the seed state per runtime entry: LAZY_SEEDING — 231/1340 groups (17%), source <host>, seal resumable or SEALED; a descriptor/block-dir inconsistency is reported by name (never healed silently).
tebako cache list marks lazy entries ((seeding 17%)); the origin marker carries the source URL as today.
8. Interaction with spec 38 (OCI)
The byte source is transport-shaped, not URL-shaped: it consumes a range-fetch closure. An OCI blob GET (/v2/<repo>/blobs/<digest>, spec 38 §5) supports Range on every conformant registry, and the blob digest IS the artifact sha256 (spec 38 §3's trust-anchor equivalence) — so a range source over an OCI blob needs NO grammar, NO divergence: the OCI adapter supplies its closure (Bearer flow and confinement of spec 38 §6 included), the blksum sidecar publishes as one more §3 artifact class.
The closure arm (locked 2026-10-01 with PR 6). The OCI client's blob fetch carries the range arm: one positioned GET (Range: bytes=<offset>-<end>, the caller-decided credential header attached verbatim per dance attempt), answering 206 with a Content-Range validated against the request (exact start, exact length) or 200 — the §3 loud-eager-fallback signal, byte-identical in meaning with the plain-HTTPS transport's. A range window carries no whole-blob digest check by construction: the per-group digests of §3 are the integrity layer, exactly as over plain HTTPS. The blksum sidecar's OCI spellings are spec 38 §3's (that section owns the class table and the tag rules): artifactType application/vnd.tebako.blksum.v1, layer media type application/vnd.tebako.blksum.v1+json, the sibling digest-tag sha256-<64 hex of the IMAGE blob's digest>.blksum.json with the org.tebako.blksum.subject annotation naming the image digest. The sidecar's layer digest IS the blksum document's sha256 — the seed descriptor's blksum_sha256 pin binds it with no second file, and a resolve of the sibling tag that finds nothing is the §3 blksum-missing signal (the loud eager fallback), never an error.
Recorded, not committed (the run-time wiring). PR 6 ships the transport arm, the sidecar class, the resolve-side sidecar resolution, and the publish push — the pieces any OCI-staged lazy entry needs. The two downstream legs land with their own specs' PRs: OCI runtime distribution itself is spec 38's PR 4 (runtime bundles over OCI), and the driver's mount-open OCI arm (state-detecting an OCI-sourced seed descriptor, the run-time credential chain for a mount that outlives the install) is designed with that leg — this spec commits the closure shape only.
9. What does NOT change (locked)
Published image bytes. No format change, no new in-image section, no format_id, no trailer field. Every LimniFS image ever published is lazily mountable as-is (§1).
The .sha256 anchor. Sealed entries are byte-identical in layout, anchors, and semantics with eagerly installed ones (§5).
The mount-table law. Longest-prefix dispatch, duplicate-point EEXIST, unmount-everything on failure (spec 11 §2, spec 17 §1) — lazy changes where bytes come from, never how mounts compose.
The transport window. A demand fetch runs with the engine's read lock held, and the fetch's OWN machinery may call back into the interposed libc surface — on macOS the resolver reads networkd_settings through open, which would re-enter the engine behind the lock: a deadlock (tebako#851: one thread in the VFS read, the other in getaddrinfo → … → open_impl). While a fetch is in flight the shim therefore PASSES EVERY interposed call THROUGH to the host; the window is PROCESS-WIDE (the resolver runs on its own thread), not thread-local. The window is the transport's own machinery, never a payload's read; a concurrent payload read on another thread during a fetch is the known narrow exposure, and the follow-up is a lock-free mount-prefix fast path that scopes the bypass to paths outside every mount.
The mount-table identity. A lazy env-image mount serializes into TEBAKO_TFS_MOUNTS by its entry path, exactly like a file mount. A re-establishing consumer — the interpreter's preload shim, and every exec'd child — state-detects that path the same way the driver does: the sealed file mounts whole, the ABSENT file with a valid descriptor beside it mounts the caching range source, and neither file nor descriptor keeps the ordinary named open error. The lazy promise holds at both layers: only the groups demand touches are fetched.
The handoff grammar. TEBAKO_RUNTIME_IMAGE=<path> and the --tebako-image triples are byte-identical (spec 17 §1); the path names the entry whose on-disk state (§4) the driver reads. No contract-version bump: TEBAKO_RUNTIME_LAZY is an operator env in the TEBAKO_MOUNT_ROOT / TEBAKO_JAIL class (spec 17), not a handoff-semantics change (spec 06 §6's bump rule). A pre-lazy driver handed a LAZY_SEEDING entry fails CLOSED — the image file is absent, the existing named unavailable error (69) fires, and the remedy is an eager run or a runtime rebuild; never a mis-mount.
The 3 MiB bootstrap gate. The mount happens in the DRIVER inside the runtime exe (spec 17; the bootstrap never mounts and never links TFS — spec 20 §1). The lazy machinery (byte source, block cache, seal thread) lives in tfs + tebako-driver + tebako-http — compiled into the runtime exe and the toolchain, neither size-gated. The bootstrap's only new code is the seed-record arm of its existing resolve-install path (write the descriptor instead of streaming the image — a tebako-resolve plan item with a lazy commit closure); the CI size gate measures and enforces the delta, as always (invariant 2). The same machinery is also linked into the preload shim (the interpreter's own engine instance re-establishes the mount, §9's identity rule), which is not size-gated either.
10. Test plan (the tiers of spec 14; each failure above maps to one tier)
Unit (tfs / tpkg / tebako-http): range math and group indexing (edge: short final group); descriptor and blksum schema round-trips, every malformed class by name; Content-Range parsing, 206-vs-200 detection, ETag/If-Range revalidation; the directory-scan block map (size-mismatch discard, tmp drop); the state machine's transitions and commit points; config/env precedence.
Property (proptest, the existing harnesses): arbitrary read patterns over a mock byte source answer IDENTICALLY to whole-image reads of the same bytes (the parity property); arbitrary crash points (kill between every fsync/rename) leave a resumable LAZY_SEEDING or a complete SEALED, never a third state; arbitrary garbage descriptors never panic and never parse silently.
Contract (in-process HTTP fixture — CI tooling, never shipped; the spec 38 §8 loopback carve-out): a Range-capable fixture server with artificial latency, injected 500s/429s, mid-stream kills, truncated bodies, 200-instead-of-206, and byte-level corruption per group. Legs: cold mount → on-demand seeding → answers equal the file-mounted golden tree (spec 20 §8's backend-pair parity class, the dwarfs/limnifs oracle extended to lazy-vs-file); group digest mismatch → refetch → named 70; partition mid-boot → named 69; partition mid-run → EIO on the touching read only; offline with partial cache; seal from partial, seal resumption after kill, seal commit ordering; the 200-fallback (whole body arrives — loud eager path).
E2e (ci/, tiered): shim dispatch with lazy on — first cold run boots the entrypoint against a fixture-hosted runtime, second run serves touched paths with the fixture DOWN (touched-set offline proof), tebako cache seal completes and the third run is ordinary; the standalone bootstrap leg (size gate asserted); the touch-everything pathology (a full-tree walk: total fetched bytes ≤ eager bytes + one sidecar + per-group request overhead, bounded and recorded — never worse than eager × (1 + ε)); the blksum-missing image takes the loud eager fallback; TEBAKO_REQUIRE_SIGNED=1 pass/fail legs per spec 09.
Parity data for the default flip (spec 27) — LANDED. The tebako-bench harness's lazy arm ran the full 7-leg platform matrix green (bench run 37517037555, zero failed runs): warm second-run parity 1.00× everywhere; cold one-time streaming overhead bounded at +0.56 s (windows) to +5.5 s (linux-musl-x86_64) on the loopback fixture — the ε of the pathology law (total fetched bytes ≤ eager bytes + one sidecar + per-group request overhead), and the number a real network inverts, since first run fetches only the touched groups; lazy cold RSS below eager's (e.g. 25 vs 34 MiB at boot). No regression class in the warm or pathology arms. On this data the §7 flip shipped (locked 2026-10-07): the default is lazy-on, the eager opt-out is TEBAKO_RUNTIME_LAZY=0 / runtime_lazy: false.
11. Open questions (each with this spec's recommendation)
Backend vs byte source. Recommended and locked (§2): a mount-source kind below the format backend. The issue's "http-range backend" is the right instinct at the wrong layer — transport is not a format.
Whole-file sha at seal vs per-block digests at read. Recommended and locked (§3): per-group digests at read (publisher-authored, channel-anchored sidecar) + mandatory whole-file verify at seal. Seal-only verification executes unverified bytes — rejected on the threat model.
Group size. Recommended and locked: 4 MiB of image bytes. Smaller multiplies request count against rate-limited hosts; larger wastes fetch on sparse touches. One constant, tunable only by a measured follow-up (the §10 bench arms).
Missing sidecar. Recommended and locked (§3): loud eager fallback (equal trust, warned, journaled) — never a hard error against the long tail of already-published images.
Lazy payload slices. Recommended: env image v1; payloads ride the identical machinery behind the same flag later (their registry rows already carry sha256 anchors; the sidecar field is additive). Recorded, not committed.
Dwarfs over range. Recommended: recorded hook only (§2) — the C++ callback boundary is real work and limnifs is the default; decided by measured demand, not speculation.
Seal assembly. Recommended and locked (§5): assemble from the verified groups (no second network pass) — the whole-file sha is computed over the local concatenation.
The exe. Recommended and locked: always eager (kernel exec needs a whole file). The exe is the minority of the pair's bytes; the env image is the win.
A second verification algorithm (BLAKE3 groups). Recommended: no. sha256 everywhere keeps ONE anchor vocabulary with the store, the sidecars, and spec 38's layer digests; LimniFS's BLAKE3 ids remain image-internal integrity (spec 20 §7's recorded addendum, unchanged).
Implementation plan (spec PR first; each PR independently mergeable)
PR 1 — the spec. This document + the 00-INDEX.md entry + schema/tpkg-blksum-v1.schema.json + schema/tpkg-lazy-seed-v1.schema.json. No code.
PR 2 — the transport. crates/tebako-http/src/lib.rs: the Range GET entry point (Range header, 206/Content-Range validation, If-Range/ETag revalidation, the loopback carve-out), unit + contract tiers with the fixture server.
PR 3 — the byte source and the lazy store record. crates/tpkg/src/lazy.rs (descriptor + blksum models, the store-record read/write/scan under tpkg::runtime_store), crates/tfs/src/source.rs + crates/tfs/src/source_remote.rs (the byte-source seam, the caching remote source, backend-remote feature), crates/tfs/src/mount.rs (the fifth mount-source kind), crates/tfs/src/backends_limnifs.rs (the sourced open — prefix + record-table fetch), the limnifs-core paged-SlabSource pin (upstream first). Unit/property tiers + the parity class.
PR 4 — the loader + driver wiring. crates/tebako-resolve/src/plan.rs (the lazy commit closure writing the seed record), the shim/bootstrap resolve paths (TEBAKO_RUNTIME_LAZY + config), crates/tebako-driver/src/driver.rs (state-detecting env-image mount, the seal thread, EIO mapping), crates/tebako-cli/src/doctor.rs
the cache list/seal surfaces. E2e legs of §10.
PR 5 — the publish path. crates/tebako-cli/src/publish.rs (blksum generation in-process), the shard/registry additive image.blksum field (validation + schema), the factory release legs (factory repos, stacked on PR 5's product half).
PR 6 — OCI range + the flip data. The spec 38 §5 closure arm; the tebako-bench lazy arm (spec 27 harness); the default-flip PR only after §10's rule is met.
TBK SPEC 40 — The audit ledger: queries, the anchor, and the auditor's walk
Status: SHIPPED. The event vocabulary predates this spec (the writers own their events, §2.3); this spec owns the READ contract and the anchor: the filter grammar, the output documents, the chain, the named errors — and the walk an auditor with no tebako knowledge follows to prove, offline, what ran on a host.
1. The ledger and its one job
Every tebako process writes one append-only line per decision worth auditing into a single host-local file:
$TEBAKO_HOME/journal.log (TEBAKO_JAIL_JOURNAL overrides the path)
The line shape is shared by both writers — the bootstrap (the loader's fetch / verify / mount / exec decisions) and tfs::journal (the driver's and preload's policy, VFS, overlay and decrypt decisions):
<unix seconds> event=<name> <key>=<value> …
The ledger answers exactly one question — "what ran here, and why did it run?" — for one host, from one file, with no network and no other tebako artifact. It is not aggregated, not sharded, not rotated by the tools (an operator may rotate it; --seal before rotation is the discipline that keeps the seam auditable).
The read-only law. A query (tebako audit … without --seal) creates nothing, appends nothing, stamps nothing, migrates nothing. It runs on a host whose ~/.tebako was written by an older tebako, and it must not move that store's layout forward on the way in. The single writing verb is --seal, and the only file it writes is the anchor (§4).
2. Reading rules (normative)
2.1 Line grammar
The first space-delimited token is the timestamp: unix seconds, decimal. 0 is legitimate (a clock failure never fails the audited operation).
Every following token is key=value, split at the FIRST =, so a value may itself contain = (URLs with query strings, base64).
A token that carries no = CONTINUES the previous value, joined by one space. Writers record paths, and paths contain spaces: a legitimate path=/a b/c must not turn into damage. A leading token without = before any key exists is damage.
event= is the required key: a line without it, or with an unreadable timestamp, is malformed (§2.2).
A trailing newline terminates the record; a final record without one is still a record (the bytes are the record).
Duplicate keys: the FIRST statement stands (§5's fields_map_rule) — a writer's second mention of a key never retroactively rewrites what it already said.
2.2 Damage is surfaced, never swallowed
A line that does not parse is a malformed record: it is counted, carries its 1-based line number, and appears in the JSON document's malformed array with its raw bytes. A ledger that quietly drops what it cannot read is worse than one that admits damage. A query's exit code stays 0 for malformed lines unless --strict is given (§6) — the default posture is "show me everything, including the damage", because an operator diagnosing a host should not have to guess what was hidden.
A malformed line is still a LINE: it occupies its position in the file and it is covered by the anchor's chain exactly like a readable one (a deleted line moves every later record, readable or not). "Record" and "line" are therefore interchangeable in the anchor's vocabulary (§4).
2.3 The vocabulary (by the question it answers)
The writers own their event names — this table is the census, and it exists so an auditor can phrase a filter. It is not exhaustive: an unknown event= value is a first-class record, filterable like any other (forward compatibility is the point of a ledger).
| question | events |
|---|---|
| What did we fetch, and from where? | fetch, delta-fetch, mirror-materialized, payload-mirror-served, bundle-staged, bundle-runtime-warm, key-retrieval |
| Did it verify, and against what? | runtime-fetch-verified, runtime-index-verified, bundle-fetch-verified, bundle-fetch-unverified, payload-signature-trusted, bundle-trusted-root, bundle-trusted-forwarded, legacy-unsigned-accepted, unsigned-runtime-fetch, trust-bridge-java-gap, key-retrieval-failed |
| What got installed, bound or retired? | payload-installed, payload-uninstalled, runtime-own-install, runtime-own-shim, origin-rebind, trusted-key-removed, trust-ca-added, trust-ca-removed, registry-row-retired, registry-key-pinned |
| What was mounted and composed? | composition, overlay, decrypt, lazy-seed, lazy-fallback, slice-augment, slice-overlap, slice-skip, visibility |
| What was resolved and executed? | runtime-edge-resolved, provider-runtime-resolved, executable-edge-resolved, unlocked-pick, spawn-shim-note |
| What did the policy decide? | jail-deny, jail-allow, vfs-deny, vfs-write, lib-load, network-config |
| What did a press decide? | press-sign-opt-out, stale-registry-serve, edge-platform-skip |
3. The query surface
tebako audit [filters] [--count] [--json] [--strict]
3.1 Filters
| flag | meaning |
|---|---|
| --since <t> | keep records with ts >= t. t is unix seconds or RFC 3339 UTC (YYYY-MM-DDTHH:MM:SSZ). |
| --until <t> | keep records with ts <= t. Same grammar. |
| --event <e>[,<e>…] | keep records whose event= is one of the listed names. Repeatable; the union of all occurrences. Exact match, never a prefix. |
| --artifact <needle> | keep records whose body (everything after the timestamp) CONTAINS needle — the artifact reference as the writer recorded it: a payload name, a version, a sha256, a URL fragment. Case-sensitive, documented as a substring so nobody mistakes it for a structured field. |
| --tail <n> | after filtering, keep only the last n records. |
Filters compose with AND across flags, OR within --event. No filter means the whole ledger. A time filter's grammar is exact: local time is never inferred, because a silently shifted window is a silently wrong answer.
--seal takes NO filters (an anchor covers the whole file or it is not an anchor) and --seal with --verify is refused by name: one writes, the other checks.
3.2 Output
Default (line mode). The matching records, verbatim — the ledger's own bytes, in file order — so a reader can pipe them to sha256sum and compare against a seal. A one-line summary (N of M record(s)) goes to STDERR, never into the stream: the stdout of a query is a ledger excerpt, not a report about one.
--count. Exactly the match count on stdout, nothing else.
--json. The audit_schema: 1 document (§5) on stdout alone; the version banner moves to stderr, like every other machine contract in this toolchain.
File order is preserved in every mode. A ledger's order IS evidence; re-sorting it would destroy the only thing the file cannot be rebuilt without.
4. The anchor: tamper evidence
An append-only file with no anchor proves nothing — anyone can edit a line, or delete a run's records entirely, and the file still looks like a ledger. The anchor is a chained digest, sealed on demand and verified on demand, stored BESIDE the journal it covers and named by it:
<journal>.seal e.g. $TEBAKO_HOME/journal.log.seal
Beside, not inside: the journal stays a pure record stream, every reader of it keeps working, and an explicit TEBAKO_JAIL_JOURNAL override carries its seal along instead of splitting the pair across two homes.
4.1 The chain
h_0 = SHA-256("tebako-ledger-v1\n") (32 bytes)
h_i = SHA-256(h_{i-1} ‖ line_i) (32 bytes)where ‖ is byte concatenation of the raw 32-byte digest with the line's exact bytes INCLUDING its terminating newline. Any edit, any deletion, any insertion shifts every subsequent digest — the anchor's whole value is that it cannot be recomputed without re-sealing, and a re-seal is itself a new record (§4.3).
The terminator is normalized: a final record whose newline an editor added or stripped is the same ledger. That one cosmetic difference is the only edit the anchor does not report, and it is reported as nothing because it changes nothing an auditor reads.
4.2 Seal records
One line per seal, appended to the seal file:
<unix seconds> head=<sha256 hex> lines=<n> key=<keyid hex|-> sig=<hex|->
head — the chain digest over the journal's first lines lines.
lines — how many lines the seal covers (the file's state at seal time; later lines are the unsealed tail).
key / sig — the seal's authenticity. When a signing key is available (the machine's press-local key, spec 09), the canonical payload
tebako-ledger-seal-v1\n<head>\n<lines>\n<ts>\n
Figure 74 is signed detached (OpenPGP — the one mechanism this project uses) and sig carries the armored signature hex-encoded. With no key, both fields are -.
The unsigned seal is honest about what it is. It detects edits (a changed line no longer hashes to the sealed head) but not forgery (somebody with write access can rewrite the log and re-seal). The verb says so on stderr every time it writes one:
tebako: WARNING: ledger sealed WITHOUT a signature — this detects
edits, not forgery (configure a key with 'tebako keys')
A signed seal, verified against the trusted keyring or a pinned key, is the enterprise answer.
A seal that cannot be produced because the key store refuses is a LOUD unsigned seal, never a failed seal: an unanchorable ledger is worse than an unsigned anchor. A TEBAKO_SIGN that is not a boolean is a named usage error, never a silent choice.
4.3 Verification
tebako audit --verify [--json] [--strict]
Recompute the chain over the WHOLE journal and compare it against the seals. The LAST seal speaks for the file; the earlier ones LOCATE the damage.
Walking the seals in order: the newest seal whose recomputed chain still matches marks the end of the known-good prefix, and the first seal after it names the interval that changed. That interval — [known_good+1, failing.lines], 1-based and inclusive — is what the report prints, because "records 411–812 changed" is actionable and "the head differs" is not.
A seal covering more lines than the file holds is not a prefix mismatch but a REMOVAL: the report says records are gone, and names the same interval.
Three outcomes: sealed (the last seal matches), tampered (it does not, or a signed seal's signature does not validate → exit 80), unsealed (no seal file: named, exit 74, with the remedy — "run tebako audit --seal").
A signed seal's signature is checked against the trusted keyring and the pinned trust store. An unknown signer is reported as unknown-key and the outcome stays sealed (the chain matched) with the authenticity gap NAMED, never quietly upgraded. An invalid signature is tampered, whatever the chain says — a valid chain under a forged seal is exactly what a re-seal looks like.
A seal file with an unparseable line is a finding (exit 80), never a skipped line: corrupting the anchor is an attacker's first move, so damage there is never noise.
5. The JSON contract (audit_schema: 1)
{
"audit_schema": 1,
"journal": "/home/u/.tebako/journal.log",
"matched": 3,
"total": 812,
"records": [
{"line": 12, "ts": 1761000000, "event": "fetch",
"fields": {"origin": "…", "sha256": "…"}, "raw": "…"}
],
"malformed": [{"line": 411, "raw": "…"}],
"verify": {
"outcome": "sealed",
"seal_ts": 1761000123,
"sealed_lines": 812,
"head": "…",
"tail": 0,
"divergence": null,
"signer": "abcdef0123456789",
"signature": "valid",
"detail": "the chain matches the signed seal of …"
}
}
| field | meaning |
|---|---|
| matched / total | records selected by the filters, and lines the file holds |
| records[].fields | the record's k=v tokens as a map, first-wins on duplicate keys |
| records[].raw | the record's exact bytes without the newline |
| malformed[] | unparseable lines, always present (empty array when clean) |
| verify | null for a query; the object above for --verify; absent for --seal, whose document carries seal instead |
| verify.divergence | {"from_line": N, "to_line": M} when the outcome is tampered, else null |
| seal (on --seal) | {path, ts, head, lines, signer} — signer is null when unsigned |
records is capped by --tail and by the filters; total always reports the file, so a filtered document can never be mistaken for the whole ledger. audit_schema is 1 forever: extensions add keys, never retype or rename one.
6. Named errors and exit codes
| code | name | meaning |
|---|---|---|
| 80 | EX_TEBAKO_LEDGER | --verify found a mismatch or an invalid seal signature; an unparseable seal record; or --strict with malformed journal lines |
| 74 | EX_TEBAKO_IO | the journal or seal cannot be read or written; a query on a host with no journal yet; --verify with no seal yet |
| 64 | EX_USAGE | unparseable filter or time, unknown flag, --seal with filters, --seal together with --verify |
Every message names the file and the remedy — never "invalid input".
7. The auditor's walk
The arc's acceptance, spelled out as the steps an auditor with no tebako knowledge performs. Each step is offline and needs only public artifacts plus this document:
tebako audit --json > ledger.json — the host's decisions.
tebako audit --event fetch,runtime-fetch-verified --json — every byte source and its verification verdict.
Take any sha256 from step 2 and check the artifact against the registry row and its attestation (gh attestation verify), then reproduce the payload image per spec 14's reproducible-press rule.
tebako audit --verify — the ledger's own integrity, against the seal the host wrote; or tebako audit --seal first on a host that never anchored.
Confirm the mount set (--event composition,overlay,decrypt) matches the package's declared dependency tree (tebako closure).
Archive ledger.json + the seal file; a later --verify on the archived pair proves the archive is what the host wrote.
8. What this spec does not own
The event names and their field vocabularies — the writers own those (§2.3 is a census, not a registry).
Rotation, retention, remote shipping: operator policy. The seal is the seam that makes rotation auditable, and that is all this spec says about it.
The signature mechanism itself: spec 09 owns OpenPGP, the keyring and the pinned trust store; this spec only names where a seal's signature is checked.
TBK SPEC 41 — Registry transparency: completeness proofs for the public fabric
Status: PLANNED (the design is locked here first; §5's verbs ship together with this spec in the same change).
1. The property nobody has
A signature over a registry proves that whoever holds the key wrote those bytes. It says nothing about what was there last month. Yanking a row and re-signing is indistinguishable from the row never existing, and that is the one attack a mirror cannot detect: every mirror is happy to serve the smaller file.
Completeness is the missing property, and it needs machinery rather than good intentions:
append-only: the registry's history is a log that only grows;
provable: one row's presence is provable without shipping the log;
auditable: a row that disappeared without saying so is a NAMED alarm, not a diff somebody has to notice.
The machinery is an RFC 6962-shaped Merkle log (Certificate Transparency's shape) because it is the one construction third-party tooling already implements: inclusion proofs of log2(n) hashes, and a chain of heads that proves the log only grew.
2. The canonical snapshot
tebako registry snapshot <alias|path> renders every row of a registry document as ONE canonical line. Determinism is the premise — a snapshot that shifts when nothing changed is worthless as evidence:
<kind> <name>@<version> <platform> <sha256|-> <state> <keyid|->
| field | rule |
|---|---|
| kind | the document's kind: value, verbatim |
| name@version | verbatim from the document (one line per row, so a version entry with N platform legs is N lines) |
| platform | the triplet, or universal; a variant arm renders <variant-id>:<universal|triplet> — the arm id never stands alone, so a universal arm can never be mistaken for a triplet |
| sha256 | the row's anchor digest, lowercase hex; - when the row declares none (a runtime index row) |
| state | active, or withdrawn — spec 04's status: value verbatim, never a second spelling (§6) |
| keyid | the row's declared signer keyid when present, else - |
Order: (kind, name, version, platform) — byte order, never document order. No timestamps, host names, comments or map iteration order enter a line: an author may reorder the YAML, rewrite its comments, or re-indent it, and the snapshot does not move. Two authors producing the same set of rows produce the same snapshot.
2.1 Where each column comes from (SSOT, never a re-derivation)
platform — a variants: arm renders its id from tebako_resolve::registry::variant_id() (spec 28 §2's one derivation). A second implementation of that derivation would produce snapshots that disagree with resolution, which is the one thing a transparency log cannot survive.
sha256 — the platform row's own sha256. A platforms: universal row carries NO digest column in the registry model (ReleaseRef holds a reference, not a hash; the anchor is the release's SHA256SUMS plus its attestation). Such a row renders -, and that is the honest value: this log proves the ROW SET is complete, while the release's own sums and attestations prove the BYTES. A ?sha256= pin inside the ref, when present, is rendered as that pin.
state — spec 04's status: verbatim (withdrawn when yanked), active when absent. Never a second vocabulary (§6).
keyid — the row's declared signer (signature.keyid) when present, else -.
--json emits the registry_log_schema: 1 document:
{"registry_log_schema": 1, "registry": "official", "rows": 412,
"lines": ["…"], "root": "…", "head_hash": "…"}
3. The tree
Leaves and nodes are domain-separated, so a leaf hash can never be mistaken for an interior node:
leaf(line_i) = SHA-256(0x00 ‖ line_i bytes)
node(l, r) = SHA-256(0x01 ‖ l ‖ r)
empty = SHA-256("") (a registry with no rows)
The fold is RFC 6962's: the largest power of two strictly smaller than the leaf count splits the tree, recursively. An odd tail is carried up, never padded — padding is what breaks third-party verifiers.
Inclusion proof for leaf i of n: the sibling hashes bottom-up, serialized as a JSON array of lowercase hex, plus the leaf's index and the tree's leaf count. A verifier recomputes the root from the line and the proof; nothing else is needed.
4. The log head and the chain law
Each snapshot is appended to the registry's log as one head record:
<seq> ts=<unix> root=<hex> rows=<n> prev=<hex|-> key=<keyid> sig=<hex|->
seq — 0, 1, 2, … ; strictly increasing, no gaps (a gap is a named error: the log was edited).
prev — the previous head's root (- for seq 0). A head whose prev does not match the previous head's root is a fork, named as such: the log diverged and nothing after that point can be trusted.
rows — the snapshot's leaf count; monotonic non-decreasing unless tombstones account for the difference (§6).
sig — detached OpenPGP over
tebako-registry-log-1\n<seq>\n<ts>\n<root>\n<rows>\n<prev>\n
Figure 82 signed by the registry's declared head key (spec 09 §9.1's signing: block — the key the registry already carries; no new key class). The signature is verified against the pinned trust store, and an unknown signer is unknown-key (reported, never upgraded to trusted).
The log file is a head record per line, in seq order:
<registry>.log (beside the registry it describes)
5. The verbs
tebako registry snapshot <alias|path> [--json] [--out <path>]
tebako registry log verify <log> [--registry <path>] [--json]
tebako registry log prove <log> --registry <path> --row <name>@<version>
[--json] [--verify-root <hex>]
snapshot renders §2's lines and root. --out writes them beside the registry for publication; without it they go to stdout (--json emits the document).
log verify checks, in order: every head's signature; the seq continuity; the prev chain (a fork is named at the head where it happens); and — when --registry is given — whether the document IS the row set the newest head sealed, by RECOMPUTING THE ROOT from the document's canonical rows. One number answers both halves: if the roots agree, no row could have been added, removed or edited without moving it. A rows decrease is reported separately (the chain alone cannot see tombstones), and a forced deletion therefore surfaces by name.
log prove emits the inclusion proof for --row against the newest head, and one proof per matching row: a version is often several rows (one per platform), and hiding all but one would understate what the registry says. It needs --registry as well as --row, because the canonical line cannot be reconstructed from a name alone — the line IS what is proved. --verify-root <hex> checks the proof against a root the caller obtained out of band: a user holding ONE 32-byte value can prove a row's membership without trusting the download that carried it.
Output discipline follows the toolchain's rule: --json documents on stdout alone (banner to stderr), human lines on stdout otherwise, exit codes per §7.
6. The tombstone law
A row may leave a registry; it may not leave silently. The vocabulary for leaving already exists and this spec does not invent a second one: spec 04's status: withdrawn (roadmap 85) is the tombstone — the resolver refuses a withdrawn row by name (WithdrawnPayload), listing surfaces render it as withdrawn, and release assets stay immutable.
Under the completeness law the ROW STAYS: tebako registry retire sets status: withdrawn on the version instead of deleting it, so the next snapshot renders the row as withdrawn and keeps it in the tree forever. A registry whose rows only ever disappear is a registry nobody can audit.
Withdrawal is the only legal way for a name to vanish from a snapshot or for rows to fall. --force still removes a row outright — an operator may need it — but the next log verify reports the disappearance by row name, and a forced removal is precisely the alarm the log exists to raise: never quiet.
7. Named errors and exit codes
| code | class | meaning |
|---|---|---|
| 71 | EX_TEBAKO_SIGNATURE | a head's signature does not validate |
| 72 | EX_TEBAKO_TRUST | a head's signer key is not in the trust store (unknown-key in JSON; the chain is still reported) |
| 80 | EX_TEBAKO_LEDGER | an integrity finding: a seq gap, a fork, a prev mismatch, a proof that does not verify, a row missing without a tombstone, or a tree/file inconsistency (spec 40 §6's ledger class — both streams are record streams whose integrity findings are one kind of event) |
| 74 | EX_TEBAKO_IO | a log or registry cannot be read or written |
| 64 | EX_USAGE | unknown flag, unparseable row reference, --verify-proof without a proof source |
Every message names the row, the head, or the file — never "invalid input".
8. What this spec does not own
Registry document grammar and the signing: block: spec 04 and spec 37.
The signature mechanism and the trust store: spec 09.
Publication cadence and hosting: spec 13 and spec 37. This spec says what a published log must satisfy, never when to publish one.
Rotation of the head key: spec 09 §11's successor statement — a log signed under a successor key chains through prev like any other head.
TBK SPEC 42 — Tree solving and lockfiles: one answer for a whole composition
Status: PARTIAL (the payload-edge solve, the named-conflict contract and the lockfile ship with this spec; the runtime-edge seam is spec 05's resolver and is refused by name until it is wired — §2 states it).
1. What resolution does today, and what it cannot do
Resolution today answers ONE question at a time: an entrypoint declares runtime_requirement, the dispatcher picks the newest COMPATIBLE runtime (spec 05 §4). That is a per-edge decision, and it is correct for what it covers — a single app over a single runtime.
A composition is not one edge. A press names payloads; each payload's requires: names more payloads, runtimes, toolkits and data; each of those resolves against a different registry row. Today each edge is satisfied independently, in traversal order, and two edges that cannot both be satisfied are discovered as a runtime failure — a mount EEXIST, a runtime that does not match — after the package was built. First-fit over a tree is an accident that usually works.
The tree is a constraint problem, and it has one honest answer: the maximal assignment that satisfies every edge at once, or a named conflict that says which requirement, which candidates, and why.
2. The requirement closure
The solver's input is a requirement set: the edges declared by the press recipe, closed over the edges of every payload it selects.
closure(R0):
R = R0
repeat
for each r in R whose candidate is already fixed by the assignment:
R += the chosen payload's own requires: (spec 03 §2.3)
until R is stable
| edge kind | candidate space | skipped when |
|---|---|---|
| language | spec 05's resolver, not a second copy of it: the solver calls the dispatcher's own runtime-edge pick (engine + optional implementation + constraint against the runtime index), so a runtime edge has exactly one implementation in the ecosystem (invariant 10) | never |
| runtime | same seam, spec 30's spawned shape | never |
| toolkit, data | kind: rows with that name, constraint on version | the host triplet is absent from the edge's triplets: list |
| app | kind: app rows with that name | same as above |
The runtime seam is named while it is open. The first implementation of this spec solves payload edges; a language or runtime edge is refused with solve-runtime-edge (exit 81) and the message points at spec 05's resolver, rather than carrying a second matcher that would drift from the dispatcher's. Closing the seam is a change to this spec's status, not a silent behaviour.
Two closure rules that are not negotiable:
A cycle is a named error, not a stack overflow: an edge whose target is already on the current path fails with solve-cycle, naming the path as declared (it can be legitimate to repeat a payload in two branches — that is a DAG, not a cycle, and it resolves once).
A skipped edge is recorded, not silent. The lockfile carries skipped: [{edge, triplet, reason}] so a reader can see that the tree on this host is smaller than the tree in the manifest.
Where the per-payload edges come from. They are not in the registry, and that is the layer model working as designed: L3 mirrors resolution fields only, while DEPENDS is L1 (spec 03 §2.3). The caller — the press, which holds the payloads or has just read their in-image manifests — supplies each candidate's edges as a closure map keyed <kind> <name>@<version>. The solver's answer is therefore a function of three inputs: the seed edges, the closure map, and the registry documents. Nothing is fetched; a candidate whose edges are absent from the map is a named solve-closure-missing, never an implicit "assume no dependencies".
3. The candidate space is the registry, as published
Candidates come from the registry document(s) the press is configured with (spec 04), never from a network probe:
status: withdrawn rows are not candidates, and a conflict whose only satisfying rows are withdrawn names them as withdrawn — "nothing satisfies" and "the only candidate was yanked" are different findings;
a row is a candidate for a triplet only if that triplet appears in its platforms: (or the row is universal);
the constraint language is the one already specified (spec 05 §4): ranges (>= 3.3, < 5.0) for pure-language edges, ABI lines (~> 3.3.0) for native-extension edges. The solver uses the same parser the dispatcher uses — one grammar, two callers.
4. The assignment law
An assignment is a map (kind, name) -> (version, triplet, artifact sha256). Among all assignments satisfying every edge of the closure, the solver returns the maximal one, ordered by:
higher version is preferred for the first (kind, name) in canonical order (kind, then name — byte order, no locale);
then higher version for the next entry;
then the lexicographically smaller artifact digest.
Consequences worth stating as laws, because they are the properties the tests must hold:
Determinism. The answer is a function of (closure, registry bytes). Not of hash-map iteration order, not of traversal order, not of which mirror served the document. Two runs over the same inputs produce the same assignment and the same lockfile bytes.
No silent downgrade. A lower version is chosen only when no higher one is part of any satisfying assignment, and the lockfile records the chosen version — a reader can always see what was picked.
One version per name. The model has no side-by-side versions of the same payload; a requirement set that would need two versions of one name is a conflict, not a multiply-mounted tree.
5. Conflicts are named, and they exit 81
solve-conflict: <edge as declared>
needs <kind> <name> <constraint> on <triplet>
candidates: <v1>, <v2>, <v3>
excluded: <v1> — <reason>; <v2> — <reason>
fix: <the smallest change that would satisfy it>
| reason | meaning |
|---|---|
| constraint | the version exists but does not satisfy this edge's constraint |
| platform | the version exists but publishes no artifact for this triplet |
| withdrawn | the only satisfying rows are withdrawn (and this is printed) |
| pinned | another, already-required edge forces a different version of the same name |
| closure | the chosen candidate's requires: are absent from the closure map (solve-closure-missing) — the press must supply L1 |
Exit code 81 (EX_TEBAKO_SOLVE) for a conflict, 81 for lockfile drift (§6), 64 for a malformed requirement set. All three are named; none is a silent fallback. (81 is the first code above the allocated 65–80 range; the table in spec 06 gains the row in the same change.)
6. The lockfile
tebako.lock — YAML, one document, written by the solver and read by the press. Its bytes are a function of the assignment alone:
lock_version: 1
assignments: # canonical order: kind, then name
- kind: data
name: iso-codes
version: "2024.2"
triplet: universal
sha256: "…" # the artifact's own anchor
- kind: language
name: ruby
version: "4.0.7"
triplet: aarch64-macos
sha256: "…"
skipped:
- edge: "toolkit gtk-layer"
triplet: x86_64-linux-musl
reason: triplet-not-listed
registries: # content, never a URL
- snapshot: "…" # spec 41 §2's canonical snapshot root
Laws:
No URLs, no timestamps, no host names. A mirror URL in a lockfile would make the same tree lock differently depending on where it was solved. The registries: rows carry the snapshot root (spec 41 §2) of the document the assignment was solved against, which is a content identity and is comparable across mirrors.
Round-trip. solve(closure, registries) followed by solve(closure, registries, lock) returns the same assignment and re-renders byte-identical bytes (lock-roundtrip in the test names).
--locked. A press under --locked refuses to change the assignment: any difference between the lockfile and the solve is lock-drift, exit 81, printing the two assignments line by line. That is the flag CI uses, and the reason a green run stays green.
Invalidation is explicit. A lockfile from a different lock_version, or one whose registries: snapshot no longer matches the document in hand, is refused by name — never "re-solved silently and rewritten".
7. What this does not cover
Inside a payload's own ecosystem. A payload carrying Gemfile.lock or package-lock.json is authoritative for what it vendors (spec 26's press already requires a lockfile for node). The solver resolves payloads and runtimes; it does not resolve gems.
Signature and trust policy. Selection happens before verification; a verified-failed artifact fails the fetch, not the solve (spec 09).
Deltas and transfer. The lockfile records digests, so a fetch can plan deltas from them (spec 39) — planning is downstream of solving.
Cross-registry fetching. A tree spanning two registries solves under this spec today only if both documents are configured inputs; the transport story is spec 04's.
The composition calculus
Abstract
A tebako package is a composition of three kinds of independently distributable part, executed as one process. This paper states the composition as a small calculus: a set of objects, a relation that mounts them, a closure rule that closes a declared requirement set over the requirements of what it selects, and an assignment law that either satisfies every edge at once or names the conflict. The calculus is not a description of intent. Each of its laws is the statement that one shipped test or one recorded run already establishes, and the boundaries section records what the draft does not claim, including the one seam that is refused by name rather than approximated.
1. The problem the calculus answers
The three parts of a package are the bootstrap, a runtime, and one or more payload slices, and they are glued by a trailer that sits at the end of the file. The trailer carries a 166-byte header and a sequence of 280-byte slot records, each naming an offset, a size, a format identifier, and a mount point, while the header carries the runtime reference, the launcher ABI version, and the package flags.
A package therefore contains several filesystems at once, and the interpreter inside it sees them as one tree. Two questions follow immediately, and neither is answered by the wire format. The first question is which of the several thousand paths that a run may open belongs to which slice, and the second is what a package must do when the slices it was asked to compose require versions that cannot all be true at the same time. The first question is answered by a dispatch rule, and the second by a solver; this paper states both as parts of one system, because a composition that resolves correctly and then mounts ambiguously is not a composition.
The deployed alternative to a written calculus is traversal-order first fit. It works whenever the tree is shallow and the registry is small, and it fails as a mount collision or a version mismatch discovered after the package was built, which is to say at the worst possible moment and with the least possible diagnosis.
2. The objects
The calculus has three object classes, and the classes are disjoint by construction.
Object 1, the slice. A slice is a filesystem image with a manifest inside it, at a fixed in-image path. The manifest declares the slice's identity, what it provides, and what it depends on. A slice is self-describing, so a reader that holds the image holds everything needed to decide how the slice may be used. The image format is an implementation detail of the slice and is named by the format identifier in the trailer; seven formats are admitted, and the orthogonality law of the system states that the question of whether an object is a runtime and the question of where its entrypoint lives are both independent of that identifier.
Object 2, the runtime. A runtime is a slice of kind runtime, and it physically consists of two artifacts, which are the interpreter executable and an environment image holding the files that the interpreter's load paths expect. The pair is a unit of resolution and a unit of verification. In the image era the environment image is mounted whole rather than extracted, and the mount root is a value that flows from the patched interpreter's own build metadata downstream, never re-authored by a consumer.
Object 3, the package. A package is a bootstrap, a set of slots, and a trailer. A fat package carries its runtime as a slot, and a lean package resolves the runtime at run time from a registry and a machine-wide cache. The distinction is a packaging decision and is not visible to the mounted filesystems.
The three classes are sufficient because a run has exactly one process owner. A payload that needs a second language runtime inside its own process is not a fourth class; it is the runtime-on-runtime edge of section 3.3, and a payload that needs a separate process is a spawned edge, which the platform treats as a declared dependency rather than as an object of this calculus.
3. The composition relation
The composition relation is written M ⊢ p ⇝ t, read as "the mount table M resolves path p to the slice tree t". A mount table is a finite set of triples, each naming a slice, a slot within it, and a mount point.
3.1 Mounting is ordered, and the order is declared.
The driver mounts the environment image first, at the runtime root, and then mounts each payload at its declared mount point, in the order that the invocation names them. Every triple must be well formed: a bare image file is mounted whole, a packaged file mounts the region that its trailer describes, and a slot whose format identifier declares the runtime role is never mounted as a payload.
A duplicate mount point is a failure with a named error, EEXIST, and the failure is not partial: any failure unmounts everything already mounted, so a process never observes half of a composition.
Theorem 1, determinacy of dispatch. Given a mount table whose mount points are distinct, the relation is a function, and it is computed by longest matching prefix.
The proof is the duplicate rule together with the definition of the relation. Because no two mount points coincide, the set of prefixes of a path that are also mount points has a unique longest element, so the relation assigns exactly one slice tree to each path. The distinctness premise is not an assumption that the platform hopes for; it is the EEXIST rule, which turns a colliding composition into a refused mount rather than a last-writer-wins table.
Theorem 2, locality of unmount. Removing one mount point from the table does not remove any other, and a path that matched a deeper mount still matches it.
This theorem is what makes a composition safe to dismantle in any order, and it is the statement that a test in the filesystem crate proves directly: a middle level of a five-level table is unmounted, and the deeper levels continue to serve their own content. The practical consequence is that a failure in the middle of a run's teardown cannot silently expose the runtime root's copy of a path in place of the payload's.
3.2 Entry resolution is anchored to the first image.
The entrypoint is resolved against the mount of the first image that the invocation names, which is the application payload. When the invocation names no image at all, the entrypoint is resolved against the runtime root. The rule is stated as an anchor rather than as a search because a search would make the entrypoint a function of whatever happened to be mounted, and a package whose entrypoint depends on its neighbours is not a package.
3.3 The runtime-on-runtime edge closes the relation under composition.
A Java-implemented Ruby, and a Ruby implemented on a Java virtual machine, both need a second runtime to own the process. The platform does not invent a third artifact class for this case. The edge is declared by the depending runtime's manifest, the process owner is the runtime that the edge names, and the depending runtime contributes an environment image and an entry rewrite. The spawned edge and the spawned payload edge are the two other classes of "one thing runs inside another", and the three classes are mutually exclusive and collectively exhaustive by construction, which is the property that keeps the model from growing a fourth case with every new language.
4. The requirement closure
A requirement set is the set of edges declared by a press recipe. The closure of that set adds, for every edge whose candidate the assignment has fixed, the edges that the chosen payload declares. The closure is computed to a fixed point, and the three edge kinds have three candidate spaces: a language edge is resolved by the dispatcher's own runtime resolution, a toolkit or data edge is resolved against registry rows of that kind, and an application edge is resolved against rows of the application kind. An edge whose declared triplets do not include the host is skipped, which is the rule that lets a package carry a platform-specific dependency without failing on the platforms it does not name.
Theorem 3, termination. The closure reaches a fixed point in finitely many steps for every finite payload universe.
The proof is monotonicity over a finite lattice. Each round adds only the edges of payloads that the assignment has already fixed, the set of payloads in a registry is finite, and an edge is never removed, so the sequence of requirement sets is monotone and bounded above by the edge set of the universe. A cyclic dependency therefore does not diverge; it either closes or produces a conflict in section 5.
One design decision in this rule is worth stating, because it is the invariant that a second implementation would violate. The language edge does not re-implement runtime resolution inside the solver. The solver calls the dispatcher's own resolution, so a runtime edge has exactly one implementation in the ecosystem, and the two code paths cannot drift into disagreement about what "compatible" means.
5. The assignment law and the named-conflict contract
The assignment is the maximal set of choices that satisfies every edge at once.
Law 1, no silent downgrade. The solver either returns an assignment that satisfies the closure, or it returns a conflict. It never returns an assignment that satisfies a subset and reports success.
Law 2, the conflict is a diagnosis. A conflict names the requirement, the candidates that were considered, and the reason each was rejected. The process exits 81, which is the solver's own code and is distinct from the loader's codes and from the interpreter's.
Law 1 is the property that first-fit traversal lacks, and law 2 is what makes law 1 usable. The implementation is exercised by thirteen tests, which cover the maximal assignment, the named conflict, the lockfile round trip, the refusal of a drifted lockfile under a locked install, and the requirement that the answer not depend on the order in which registry rows happen to be listed.
6. The lockfile
The solved assignment serializes to a lockfile, and re-solving from that lockfile reproduces it byte for byte. The round trip is a test rather than an aspiration because a lockfile that is merely stable in content would let a rebuild reorder rows and thereby change the pressed bytes, which would break the reproducibility property that the rest of the trust story rests on.
The reproducibility property itself is measured at the image layer, where it is achievable: the same content pressed by two hosts, on two architectures, at a fixed source epoch, produced the identical payload image digest 2416ccdbe60eff25c4805c1c4c6e5777dda7ebcbe13fa25fe355845c75b934a4 and the identical size of 806 bytes, recorded in run 39890850505 with both hosts compared in one job. The package digest is deliberately not claimed across hosts, because a package embeds its host's runtime pair and bootstrap; that boundary is measured and stated in the trust arc rather than papered over.
7. Worked instance: five levels
The recursive case is the statement that the relation is closed under composition, and it is proven at depth rather than asserted. Five payloads are mounted at /a, /a/b, /a/b/c, /a/b/c/d and /a/b/c/d/e, each carrying its own copy of a file of the same name, and the composed package is executed as one process. Every level prints its own content, the deepest path is not shadowed by its ancestors, and the fixture ends with its own assertion that five levels were each served from their own mount. The library proves the same property with five tests over the mount table, and the driver proves it through argument parsing, the mount loop and entry resolution with seventy-three tests, five image triples in one process, and the entry resolving against the first image.
8. Boundaries of the draft
Four boundaries are stated here so that the draft cannot be read as claiming more than it establishes.
The runtime edge of the solver delegates to the dispatcher's resolver, and the seam is named in the specification as such rather than duplicated. Slices are today generalized to the layouts that the shipped runtimes use, and the per-runtime layout grant that other ecosystems' content plugins need is specified but not complete. Cross-registry composition within one solved tree is designed and not yet exercised end to end. The resource-bound half of hermeticity, which would bound what a composition may consume, is open: mounts carry no quotas, and the content pool's bounds are the only limit that exists today.
9. Why the calculus is worth writing down
Three properties follow from the statements above and from nothing else. A composition has one answer, because the assignment law excludes the alternative. A failure is diagnosable before the process starts, because the closure and the conflict are computed before the mount and because the mount itself is all-or-nothing. And an answer is portable, because the lockfile reproduces it byte for byte and the image bytes are reproducible across hosts.
None of these properties is a performance claim, and none of them requires trust in a build server. They are the reason a package can be verified by a party who did not build it, which is where the next paper in this sequence begins.
Sources
The normative statements are in the product repository, and each is public: declarative composition, runtime-on-runtime composition, tree solving and lockfiles, the runtime driver contract, and the wire format. The measurements cited above are recorded in the test suites named in sections 3, 5, 6 and 7, and in the runs named inline.
Colophon
This volume was assembled and rendered by the ecosystem's own toolchain. Nothing in it is hand-copied: every chapter is transformed mechanically from the source recorded below, and the build fails closed on any drift it can name.
| Layer | Provenance |
|---|---|
| Spec chapters | the AsciiDoc twins at docs/spec-site/sources/ in tamatebako/tebako, commit e50ed3cbf34eaa1934a4eb90df0c2a4268a66539 (main at build time). Each twin is the rendered form of the Markdown specification its // source: marker names; the build verified every marker. |
| Architecture chapters | _docs/architecture/ in tamatebako/tebako.org, commit 709e4904f214be56ffe906bc83bd8a29085c16c0 |
| Toolchain | the packed metanorma payload, version 1.18.6 (tebako install metanorma@1.18.6 from the official registry, tfs:github:tebako-packages/registry), dispatched through the tebako shim layer. Build command: npm run book. |
| Build date | 2026-11-23 (UTC) |
| Chapter | Source | Source blob SHA |
|---|---|---|
| TBK SPEC 00 | tamatebako/tebako:index.adoc (the series landing — no Markdown source) | — |
| TBK SPEC 01 | tamatebako/tebako:docs/spec/01-overview.md | eb9547c5b153b4c3831ecc2247cd841db6b1e2b1 |
| TBK SPEC 02 | tamatebako/tebako:docs/spec/02-tpkg-wire-format.md | df19f89d78d6a72d551b92fc9f54b356c4a8366f |
| TBK SPEC 03 | tamatebako/tebako:docs/spec/03-payload-manifest.md | 4dc30fb24b5bed7a549cb0dbd6f07b1dcd4a3fa4 |
| TBK SPEC 05 | tamatebako/tebako:docs/spec/05-resolution-and-cache.md | 142f1d78f09370032df0b983ef4f70446277a361 |
| TBK SPEC 08 | tamatebako/tebako:docs/spec/08-jails.md | 93e1d51ad2d93c1f7fffb313ba78c9ba0d05cb40 |
| TBK SPEC 04 | tamatebako/tebako:docs/spec/04-references-and-registry.md | 1a3411704744ca72f9d761e97b05211c891c2b30 |
| TBK SPEC 09 | tamatebako/tebako:docs/spec/09-trust-and-signing.md | d4678b1c9a3d99777fab771966fccc37d7d5e89e |
| TBK SPEC 10 | tamatebako/tebako:docs/spec/10-encryption.md | 9b63eb6932841b0e4cbab58efe779698b43d8607 |
| TBK SPEC 11 | tamatebako/tebako:docs/spec/11-tfs-vfs-model.md | fdba8a1872059ac6a61a4fb38786325b3097d492 |
| TBK SPEC 17 | tamatebako/tebako:docs/spec/17-runtime-driver-contract.md | aff190a28434cfced6a28594f49dd801f6c30093 |
| TBK SPEC 06 | tamatebako/tebako:docs/spec/06-launcher-abi.md | 55588ee3f8ba633e78a79fca9d6116b68c647ee1 |
| TBK SPEC 07 | tamatebako/tebako:docs/spec/07-shims-and-dispatch.md | aaf9c82a648940aa5056bc608e8696189ef81070 |
| TBK SPEC 18 | tamatebako/tebako:docs/spec/18-contract-set.md | 7317dfef1618a0f57953c22433e27584fd608a8b |
| TBK SPEC 19 | tamatebako/tebako:docs/spec/19-bootstrap-distribution.md | b972be19816a08cd68eb266c7cdd16ba48cc3265 |
| TBK SPEC 25 | tamatebako/tebako:docs/spec/25-trace-observability.md | d9574f1ebce51ec62aa05c72b1e354ebf5852992 |
| TBK SPEC 36 | tamatebako/tebako:docs/spec/36-release-bundles.md | 96f0016c33b7f98d097592156376a0a0eb2d2932 |
| TBK SPEC 37 | tamatebako/tebako:docs/spec/37-registry-book.md | 2926ce8218a0817ee668a2849f2ee925fb703bde |
| TBK SPEC 38 | tamatebako/tebako:docs/spec/38-oci-distribution.md | 7825fdb704e57a5170dcb8b810f88fd491d240cb |
| TBK SPEC 39 | tamatebako/tebako:docs/spec/39-lazy-range-mount.md | 080bd3dcbd52fd4d6830dc189f85687a45952731 |
| TBK SPEC 40 | tamatebako/tebako:docs/spec/40-audit-ledger.md | 0c4e2f64e39766eb0bb134fe82478f4a664ef5fb |
| TBK SPEC 41 | tamatebako/tebako:docs/spec/41-registry-transparency.md | 2b612c1cfbf76eb0a15df28fc61b544eeb55809f |
| TBK SPEC 42 | tamatebako/tebako:docs/spec/42-tree-solving.md | dfa76638756f1f8aa6ff37084fbd2dfd0f536db3 |
| The composition calculus | tamatebako/tebako.org:_docs/architecture/composition-calculus.adoc | — |
The artifact checksums of this build (the single-page HTML and the PDF) are recorded in build-manifest.json alongside the artifacts.