1 · What SIR is
SIR is the format a rederive package ships instead of trusted bytes. Where npm hands you a prebuilt implementation and a name to trust, a rederive package hands you a contract: a structural spec (the .sir file) plus a differential oracle (the oracles/ vectors). You verify the shipped code against it, or re-derive the code from it.
A SIR artifact is one recursive tree of KIND-discriminated nodes. It describes a single unit of behavior — a function, a handler, a leaf — at the level of what crosses its boundaries and what shape its control flow takes, not at the level of source syntax. Two implementations in two languages with the same choreography have the same SIR body.
Crucially, SIR is not a proof system and the prose in it is not load-bearing. The ground truth of a unit's behavior is its oracle — input→output (or input→trace) vectors whose expected values were produced by executing the original. The .sir text orients a human and a re-emitter; the oracle is what a build is graded against.
2 · The four invariants
Everything below is downstream of four rules. They hold for every unit, every package, every version.
i. The discriminator leads
KIND is declared in every unit's header and is never inferred from shape. A reader (human or machine) knows whether they are looking at a pure computation or a world effect before parsing anything else.
ii. The firewall
iii. The oracle is the substrate
A SIR artifact is self-contained = spec + frozen differential vectors. Prose fields (INVARIANT, NOTES) are an unverified prior — useful, optional, never load-bearing. (Proven twice on held-out repos: structural skeleton + coverage reaches 18/18 held-out with the prose stripped — and prose can be outright wrong.)
iv. Expecteds are differential, earned with the original deleted
Expected outputs are produced by running the original implementation, never hand-authored. A unit's verified status is earned by passing the held-out round-trip gate after the original source has been deleted — the re-emitter reconstructs from the contract alone, so a pass is evidence of the contract, not a copy of the source.
3 · The unit header
Every primary .sir file opens with a header of directives, one per line at column 0; an indented line continues the directive above it. Fields in grey are placeholders. This is the v0.5 strict register, the one the toolchain writes and the validator enforces.
primary header (v0.5 strict register)UNIT <name> KIND FUNCTIONAL | STATE | EFFECT FIDELITY package | spec ANCHOR <what the contract is anchored to: package@version and function, or a spec> ORACLE-CLASS deterministic | trace SIG <name>(<arg>: <abstract type>, …) -> <abstract type> ENVELOPE <the verified input scope> DEPENDS-ON none | <named dependencies> DESCRIPTION <what the unit is for — prose> BEHAVIOR R1 <one numbered rule about the abstract signature> PINNED <kind> <name> = <literal> CITED <why> ORACLE value -> oracles/<unit>.json CANONICAL-SHA256 <64 hex>
| Field | Meaning |
|---|---|
| UNIT | The unit's name — snake_case, and a "name worth saying": it should appear in algorithm literature, an RFC, a spec, or a canonical library API. Nameable is oracle-able. Supersedes the v0.1 SIR header, which is still read but never written. |
| KIND | The discriminator: FUNCTIONAL (pure), STATE (mutates an argument; the oracle observes {result, post}) or EFFECT (touches the world). Leads every unit. |
| FIDELITY · ANCHOR | Whether the contract follows a package's real behavior (accidents included) or a written spec, and the exact authority it is anchored to. |
| SIG | The signature over the closed abstract types (text, i64, f64, json, list[T], record[…], …) — never a language's type declaration. Each language file carries its own native SIG. |
| ENVELOPE | The verified input scope. Behavior outside it is not claimed. |
| BEHAVIOR · Rn | Numbered rules a blind engineer could implement — never a narration of the original's control flow. The oracle pins the edges. |
| PINNED | A literal the behavior genuinely rides on (a grammar, a code-point set), with a citation. In the primary a pin is language-neutral; a dialect regex belongs in a language file. |
| ORACLE | The oracle file and the hash of its vector set. A verifier checks both the file's hash and this declaration before grading anything. |
# outside a literal is a parse error. Prose has named, parsed, metered homes — DESCRIPTION, NOTE, RATIONALE — and citations are attributes (CITED, EARNED round-n heldout v, ANCHOR). The census that forced it: 89% of the lines in the shipped corpus were comments, including load-bearing pins with nowhere else to live. Older bundles are still read (legacy mode reports each # as a warning); generation targets the strict register.
4 · Kinds & the firewall
There are three kinds: FUNCTIONAL (pure), STATE (mutates an argument it was handed; the oracle observes {result, post}) and EFFECT (touches the world). STATE sits on the pure side of the firewall — mutating a caller's value is not a world effect. The firewall (invariant ii) keeps the pure side and EFFECT from mixing. But "is this unit pure?" has a third, honest answer — when a unit looks pure but calls something the analyzer can't see through.
The tri-state firewall
| Bucket | Meaning |
|---|---|
| EFFECT | Direct or transitive world effect detected. |
| FUNCTIONAL | Pure — all external calls on the known-pure allowlist (or none). |
| FUNCTIONAL? | Pure-shaped, but has OPAQUE dependencies not on the allowlist. Suspect. |
The third bucket exists so that unknown externals never silently pass as pure (the soundness fix) and never falsely claim a world effect (the noise fix). A suspect unit whose value-oracle round-trip passes is behaviorally pinned even though its purity is only assumed — the passing oracle upgrades trust, not kind.
The known-pure allowlist is a versioned artifact (it starts with language builtins, path.*, semver, minimatch, …). Opaque dependencies must be named — see DEPENDS-ON OPAQUE in §5.
Reachability (REACH)
The decompiler computes reach from the export table and call graph. Off-path units are kept, not dropped — an exported-but-uncalled function is still part of the public behavior surface, and silently dropping it is API loss in a migration.
| entry | On a public path from the module surface. |
| internal | Called only by other units. |
| off-path | Exported but uncalled on any module path. Kept and marked. |
5 · Control & data nodes
STATE — accumulators are declared once, at unit level
A LOOP gets no first-class accumulator binding. A unit that reads or writes an accumulator declares it once:
STATE <name> (in) | (out) | (in/out) NOTE e.g. STATE map (in/out) · STATE cache (out)
The oracle carries the fold semantics — a unit-level STATE marker plus differential vectors is enough to round-trip a stateful fold (proven on dotenv's parse and editorconfig's caches). A caller-provided accumulator (a passed-in Map/array) is STATE, not a world effect — it stays on the pure side of the firewall, never EFFECT. When the mutation is the unit's observable, the header says KIND STATE and the oracle observes {result, post}; a unit that only folds into a local accumulator stays KIND FUNCTIONAL.
BRANCH — including on-error
A BRANCH selects an arm by a predicate. Error handling is not a separate kind — on-error is sugar that desugars to a BRANCH with an error predicate, because an error arm carries the same verification obligation as any branch arm (arm coverage by captured inputs).
BRANCH on-error(<op>) { <arm> -> … } NOTE desugars to BRANCH with an error predicate
DEPENDS-ON — and the OPAQUE rule
In-module dependencies are named so the call graph is explicit. External calls that are not on the known-pure allowlist must be named as OPAQUE — this is what makes the firewall's blind spot visible (the unit becomes FUNCTIONAL?).
DEPENDS-ON <unit>, <unit> NOTE in-module units DEPENDS-ON OPAQUE(<module>.<symbol>), … NOTE external, not on the known-pure allowlist
6 · Effects & the boundary
An EFFECT unit's behavior is its sequence of boundary crossings. Outbound calls are EMIT (recorded, not performed during verification); inbound reads are REQUEST (injected at verify time from the captured trace).
boundary grammarEMIT <boundary.op>(<args>) -> <name> NOTE outbound WITH a meaningful reply: one node EMIT <boundary.op>(<args>) NOTE outbound, fire-and-forget REQUEST <boundary.op>(<args>) -> <name> NOTE purely inbound (fs.read, env.read, clock, rand)
An outbound call that returns a meaningful reply (a spawn whose stdout you read) is one protocol step — the trace records the emission and the injected reply together, so there is no artificial ordering ambiguity.
Boundary descriptors are <domain>.<verb>, two levels
Not per-API-function. fs.readFileSync and fs.readFile are both fs.read — sync/async is calling-convention metadata, proven irrelevant to the trace. The args stay on the node, so finer-grained audit is still possible.
| domain ∈ | (closed set, versioned) |
|---|---|
| fs env net proc | filesystem · environment · network · process |
| db time rand log | database · clock · randomness · logging |
| ipc ui | inter-process · user interface |
The verb is an operation class: read · write · stat · spawn · query · exec · fetch · set · timer · … A new net.fetch edge appearing in a review diff is exactly the red line an auditor must see.
Reading the clock vs. owning it — the scheduler is a control effect
A clock read (REQUEST time.now) returns a value and is injected like any other inbound read. Scheduling against the clock is a different effect. A timer (time.timer — setTimer / clearTimer) and the microtask scheduler are not point reads; they are a control effect that decides when deferred work runs relative to everything else. A timer race — does a timeout fire before the awaited reply settles? — is nondeterministic on the wall clock, so it is verified on virtual time: the event loop is injected as a scheduler the harness drives (schedule for microtasks, setTimer/clearTimer/advance for timers), making resolution order a deterministic, replayable function of the timeline. (Specimens: q's delay/timeout and its microtask core.)
Ordering, PAR & concurrency
A trace is an ordered sequence of EMIT/REQUEST records. Canonicalization may normalize representation (key formatting, serialization) but never ordering. The one exception is an explicit concurrent window:
PAR { … } NOTE a concurrent window: sub-traces whose relative order is not fixed
A PAR block's canonical form depends on whether its sub-traces are independent. When they commute (touch no shared state — order is observationally irrelevant), the canonical form is the sorted multiset of sub-traces and verification collapses to one representative. When they are dependent (a shared resource — order changes the observable), sorting is unsound: the unit is verified over the space of interleavings against the retained reference's reachable-outcome set + invariants (safety, ordering, conservation), with the message-delivery order injected as the boundary the harness owns.
Coverage of that space is reported on a ladder: exhaustive (small inputs — proven over all interleavings) → sampled (coverage-counted, when the space explodes) → partial-order reduction (one representative per equivalence class of independent reorderings — cheap exactly when the unit is correctly order-independent, thorough exactly when a refactor is not). A control effect additionally carries a resource-lifecycle channel (§7). (Specimens: p-map's concurrency contract — interleaving-invariant output + a max-concurrency bound — verified exhaustively for small inputs and POR-scaled past 10¹² interleavings; a two-account transfer whose outcome is interleaving-dependent; request's redirect state machine.)
A third option collapses the space at design time: a token RING. When the unit coordinates through a single circulating permission — only the token-holder acts — the interleaving reduces to a deterministic schedule (one outcome per token order; fixed-rotation is one schedule, verified in O(1)). It is the design-time dual of partial-order reduction: POR detects independence to shrink the space; a ring imposes coordination to shrink it. A ring is a behavior refinement — R_ring ⊆ R_free always (every ring run is a valid free run, so it can only drop outcomes, never invent one). The decomposer may recognize a ring (verify R_ring = R_free, behavior-preserving) or be directed to impose one — a behavior-changing transform that emits a mandatory divergence report, the dropped outcomes split into benign-determinization, safety-fix (a dropped outcome violated an invariant — a race removed), and narrowed-nondeterminism (a valid alternative dropped — confirm or refactor). (Specimen: ringbuf.js's SPSC producer protocol, modeled at Atomics-operation granularity — its single-producer contract is the ring; two-producer use admits the lost-write race the ring drops.)
TRIGGER is metadata, never structure
TRIGGER lines. A Next→Nest migration is a re-emit with a rewritten TRIGGER, verified against the same frozen trace oracle.
7 · The oracle
Each unit names exactly one oracle mode: the mode on its ORACLE line, matched by the class its header declares in ORACLE-CLASS (§3).
Mode (ORACLE) | ORACLE-CLASS | Asserts | Used for |
|---|---|---|---|
| value | deterministic | Output equality: input -> expected (for KIND STATE, the pair {result, post}). | FUNCTIONAL and STATE units (pure computation). |
| trace | trace | The ordered sequence of emissions and injected replies. | EFFECT units (world choreography). |
Both are differential: the expected value (or trace) is captured by instrumenting and running the original. An oracle asserts behavior — wire bytes, claims, status, the trace shape — and never the source library's representation (error-string wording, object-vs-string body). Freezing representation is a trap; freezing behavior is the contract.
For greenfield units with no original to run, the oracle can instead be a (generator, properties) pair — round-trip, idempotence, determinism, conservation — verifying correctness-of-contract rather than identity to a reference. (This property mode is part of the rederive toolchain; the frozen .sir grammar above covers the value/trace migration case that ships in today's packages.)
A control effect — a timer, a subscription, a lock — carries a second observable beyond value-and-order: its resource lifecycle (armed / fired / cancelled; subscribed / torn-down). Cancellation is invisible to the trace: a leaked timer still fires, but its effect is a no-op on already-settled state, so the emit/reply sequence is byte-identical while a real resource leak goes uncaught. The oracle for such a unit therefore also asserts the lifecycle channel — timers cleared, handles closed. (Specimen: request's redirect timeout — a dropped clearTimer passes value+order but leaks; caught only on the lifecycle channel.)
8 · One contract, many languages
Since v0.5 a unit can ship in more than one language without its behavior being written more than once. The behavior lives in a language-neutral primary; each target language gets a language file holding only what that language needs. Every language is graded against the same oracle, and the languages are checked against each other.
a unit's contract familysir/<unit>.sir the PRIMARY: behavior, once, over abstract types sir/<unit>.js.sir one LANGUAGE FILE per target language sir/<unit>.ts.sir sir/<unit>.rust.sir oracles/<unit>.json the one held-out oracle, sir-canonical-v1 oracles/<unit>.js.json optional: the js envelope extension (§10)
The firewall, both ways
The primary may not contain language mechanism: a dialect regex, a built-in's name or a host value name in a primary is an error. A language file may not contain behavior: no BEHAVIOR, no rules, no INVARIANT. A language file holds only its native SIG, an ABI (how abstract types map to native ones), MECHANISM notes (which built-ins realize which rules, and what an emitter in that language would otherwise get wrong), dialect pins, and an optional ENVELOPE — a narrowing for what the language cannot represent, or, for js only, a widening graded from the js extension.
Binding
A language file carries PRIMARY-SHA256: the hash of the primary's canonical text (a formatting-only normalization — line endings, trailing blanks, indentation). Reformatting the primary never breaks a binding; any content change does. A language file bound to an older primary is stale: declared, not a claim, and never graded. The toolchain stamps the binding; an author never computes it. Languages come from a closed, versioned registry: js, ts, rust, php, csharp, python.
The abstract types
| Type | Meaning |
|---|---|
| text | Unicode scalar values |
| bytes · bool · none | a byte string; true/false; the absent value, equal only to itself |
| i64 · u64 | 64-bit integers, compared exactly |
| f64 | an IEEE-754 double, compared on its bits |
| json | none | bool | f64 | text | list[json] | map[text, json] |
| tuple · list · map · record · T | U | composites and unions; T | none is the optional form |
Verification rungs
A language variant records the highest rung it earned; none is implied by another language's. type-checked — the artifact satisfies its language file's SIG under that language's own checker (tsc --strict with any rejected; cargo check). harness-verified — frozen and held-out vectors pass through a verifier-owned harness. cross-verified — two or more languages agree on held-out vectors and on a differential against each other. oracle-anchored — the oracle comes from a reference implementation in another language (ANCHOR ref(<lang>:…)), so agreement is not self-consistency.
9 · Worked example: cmp_ver in three languages
cmp_ver compares two dotted version texts. It is one of the 42 units of rederive's own verifier, which rederive re-derived from itself. The function is the real cmpVer in cli/features.mjs; these are the actual contract files, abridged only where marked.
sir/cmp_ver.sir — the primary (NOTE, SCOPE and PROVENANCE lines omitted)UNIT cmp_ver KIND FUNCTIONAL FIDELITY package ANCHOR rederive@b15b56613f9d cli/features.mjs cmpVer and isVersion — the spec-version comparison behind rdv's coarse gate ORACLE-CLASS deterministic SIG cmp_ver(a: text, b: text) -> i64 ENVELOPE any two well-formed Unicode texts (no lone surrogates). A text that is not a VERSION (PINNED below) throws (R1); every pair of VERSIONs yields -1, 0 or 1. Non-text arguments are out of the envelope (the js file says they throw). DEPENDS-ON none DESCRIPTION Compare two dotted version texts as sequences of non-negative integers and return the sign of a minus b: -1 when a is older, 0 when equal, 1 when a is newer. rdv refuses a bundle when cmp_ver(specVersion, supported) is 1. BEHAVIOR R1 VALIDATE — a is checked, then b: if either text is not a VERSION -> throws. The WHOLE text must match, with nothing before or after: no whitespace or line break at either end, no sign, prefix, suffix, exponent, empty segment, leading or trailing full stop, leading zero ("0" alone is the only segment that may start with 0), or non-ASCII digit. The throw message is not graded. R2 SEGMENTS — a VERSION is cut at each full stop "." into segments; each segment is a non-negative integer of ANY size, read exactly (no rounding, no width limit: "9007199254740993" is greater than "9007199254740992"). R3 PAD — when one version has fewer segments, its missing trailing segments count as 0 ("0.5" equals "0.5.0"). R4 ORDER — walk positions from the first; at the first position whose integers differ the result is -1 if a's is smaller and 1 if larger; if none differs the result is 0. R5 The result is always exactly -1, 0 or 1. INVARIANT cmp_ver(a, b) = -cmp_ver(b, a) on versions, and cmp_ver(a, a) = 0. PINNED grammar VERSION = SEG ( "." SEG )* CITED R1 — SEG = "0" | NZDIGIT DIGIT*; DIGIT = the ten ASCII digits, NZDIGIT = "1".."9"; the grammar covers the whole text ORACLE value -> oracles/cmp_ver.json CANONICAL-SHA256 fa0b26db62debb57c18b54882bb03c800470f0573183e991db0825c03d42cce4
Everything above is about the abstract signature cmp_ver(a: text, b: text) -> i64. There is no regex flavor, no BigInt, no parseInt in it — those belong to the languages:
sir/cmp_ver.ts.sir — the TypeScript language fileUNIT cmp_ver LANG ts PRIMARY-SHA256 b2087b4c7c8740ff879851f7acb0fbd2767c3584f9eb5f2dd8f3e7abf547ad8b SIG export function cmpVer(a: string, b: string): number ABI TypeScript compiles to the js runtime: text = string (UTF-16); the result = number, exactly -1, 0 or 1; a throw (R1) is a thrown Error, message not graded. STRICT: the artifact must type-check under strict: true against this SIG, with no any, no non-null assertions (!), and no @ts-ignore / @ts-expect-error. BigInt needs target ES2020 or later. ENVELOPE as the primary: string arguments only. MECHANISM (restated from js — language files are self-contained) R1 = the VERSION pin below with test(); an unflagged $ matches only at the very end, so a trailing line feed fails. R2 = split('.') then BigInt(segment); never Number or parseInt. R3 = a missing index is 0n. R4 compares the BigInts. DEPENDS-ON none PINNED regex VERSION = /^(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*))*$/ CITED R1 — features.mjs VERSION
sir/cmp_ver.rust.sir — the Rust language fileUNIT cmp_ver LANG rust PRIMARY-SHA256 b2087b4c7c8740ff879851f7acb0fbd2767c3584f9eb5f2dd8f3e7abf547ad8b SIG pub fn cmp_ver(a: &str, b: &str) -> i64 ABI crate shape: a LIBRARY crate ([lib], src/lib.rs exporting pub fn cmp_ver), no main, no I/O, no dependencies; the verifier owns the harness. text = &str; result = i64 in {-1, 0, 1}. A throw (R1) is a panic; the message is not graded. Return a plain i64, not a Result (the harness records a panic as the throw). MECHANISM R1 needs no regex crate: split on the byte '.', and require every piece to be non-empty, all is_ascii_digit bytes, and not to start with '0' unless it is exactly "0". Do NOT trim, and do NOT use char::is_numeric or char::to_digit with a Unicode notion of digit. MECHANISM R2/R4 without a bignum: segments are digit strings with no leading zeros, so compare by length first, then byte-lexicographically; a missing segment (R3) is "0". Never parse to u64 or u128 — segments may be hundreds of digits. DEPENDS-ON none
Reading it as a contract:
- One behavior, three renderings. The rules (R1–R5) are written once. The ts file says to read segments with
BigInt; the Rust file says to compare digit strings by length and then bytes, with no bignum crate. Both realize R2's "integers of any size, read exactly". - The hard parts are named in advance. Each
MECHANISMline exists because an emitter in that language would otherwise get it wrong:parseIntrounds past 253;char::is_numericaccepts non-ASCII digits. - The result. Built blind from these files alone: js 3/3, ts 4/4, Rust 3/3 independent emissions passed every frozen and held-out vector, and the three languages agreed on 2000/2000 differential inputs.
The earlier worked example, strip.sir from @rederive/colors, is written in the v0.1 register (a SIR header and # comments). Bundles in that form remain valid and verifiable; new contracts are written as above.
10 · The canonical encoding (sir-canonical-v1)
One oracle grades every language, so its values cannot be any one language's. Every value is tagged with its abstract type, keyed by the primary's SIG:
| Tag | Rule |
|---|---|
{t:'text', v, cu} | Unicode scalar values (cu:'utf8'). A lone surrogate has no neutral form. |
{t:'i64'|'u64', v} | a decimal string, exact, range-checked, one spelling per value |
{t:'f64', v, bits} | the 16 hex bits are normative; v is only a display hint. Every NaN is one NaN; -0 ≠ +0; no tolerance. |
{t:'bytes', v} | canonical base64 |
{t:'list'|'tuple'|'map'|'record', v} | map entries in one order (text keys by UTF-16 code units); record fields in declared order |
{t:'throw', msg} | a throw is an observation, not a value: that it threw is the claim, the message is a hint |
Equality everywhere is equality of canonical strings, and an oracle file declares the SHA-256 of its vector set — the same hash the primary's ORACLE line carries. Two independent implementations (JavaScript and Python) produce identical bytes.
Depth, throws and escaping
- One depth cap, counted one way. The whole value is depth 0 and each child value is one deeper; a value deeper than 100 is refused by every encoder, decoder and escape step alike — a grammar rule, never a stack overflow. A type nests at most 16 composites.
- A throw is exactly one key. A map is a throw marker only if its single own key is the marker; anything else is a value.
- Returned values are escaped. Before encoding a result, a verifier escapes every map that carries a marker key, at any depth, through Maps and Sets — so an artifact that returns
{"__threw": "x"}is graded as the map it returned, never as a throw.
The js envelope extension
Some JavaScript units take or return values with no language-neutral meaning: a BigInt, undefined, a sparse array, a lone surrogate, a Map or Set. Those vectors live in oracles/<unit>.js.json, are graded only for the js variant, and are declared by the js file's ENVELOPE widening — so the neutral form never absorbs JavaScript quirks. The expected values are escaped exactly as results are; an expected value the verifier cannot encode is the verifier's fault, refused when the oracle is written. A unit whose result depends on its input's key order keeps those probes here, because the shared oracle carries every map in canonical order.
11 · Module-level SIR
A multi-unit package also carries a MODULE.sir — the auditor's one-page surface. It draws the firewall cut explicitly, lists every unit and its .sir file, sketches the call tree (marking ║CALL across the firewall and · dependencies within FUNCTIONAL), and — the key line for a security review — declares the effect surface: the complete set of inbound injections and outbound emissions the whole module's traces may touch. Nothing outside SURFACE is allowed to appear in a trace.
MODULE.sir — the shape (abridged from dotenv-core, the first EFFECT-tier decompile)MODULE dotenv-core FIREWALL FUNCTIONAL ⊅ EFFECT pure (FUNCTIONAL): parser.ts, common.ts, utils.ts — no fs / env / process shell (EFFECT): index.ts — every effect lives here UNITS EFFECT load effect/load.sir index.ts:DotEnv.load FUNCTIONAL parse functional/parse.sir parser.ts:Parser.parse … one row per unit, with its .sir file and provenance … SURFACE inbound (REQUEST, injected at verify): fs.readFileSync ; child spawn stdout outbound (EMIT, recorded not performed): process.env[set] ; fs.writeFileSync ; console.error
This is the artifact a PR reviewer or a compliance auditor reads first: a new edge in SURFACE — a module that suddenly emits net.fetch — is the diff that must not pass silently.
12 · The bundle & the verification contract
A self-contained, shippable rederive unit is a bundle:
bundle layout (v0.5)bundle/ sir.manifest.json specVersion, units, one variant per language, every hash sir/<unit>.sir the primary sir/<unit>.<lang>.sir one language file per language oracles/<unit>.json the held-out oracle, sir-canonical-v1 oracles/<unit>.js.json the js envelope extension, when the unit has one src/<unit>.mjs · .ts · -rs/ the shipped implementations (a Rust one is its crate)
Each language is a variant in the manifest (lang:js, lang:ts, lang:rust) with its own language-file, oracle and source hashes, and the rung it earned. A js variant whose unit has an extension names it and its hash; it is verified only if both the shared oracle and the extension pass, and a named extension that is missing or altered fails the variant. A variant without src is spec-only: shipped for the consumer to re-derive locally. Toolchains are the consumer's own; a missing one halts the check with an install hint rather than skip a language.
Three rules make the bundle verifiable rather than merely descriptive:
- Frozen + held-out. Vectors are frozen at capture. Coverage rounds may append fresh inputs, but a disjointness guard refuses any held-out string that leaked into the set the re-emitter sees. Train and test never overlap.
- The original is deleted. The re-emit gate consumes only the bundle. The implementation is reconstructed from the contract, never copied from the source.
- Closure by density, not by a single pass. A round closes only when (a) the full held-out set is re-run — a new vector can regress a previously-passing seam — and (b) N≥2 independent emissions agree. One passing emission on an uncovered class is luck; agreement is evidence. Priors are outvoted by evidence density, never overridden by a single contradiction.
How a verifier calls and judges an artifact
These rules were forced by rederive re-deriving its own verifier. Each one closed a way a correct artifact was rejected or a wrong one accepted.
- The export is the one the
SIGnames — the default forexport default function f,fforexport function forexport const f = …. Never "the first function": a verifier that guesses can type-check one function and grade another. - TypeScript conformance runs in the artifact's own scope, so a
SIGmay name types the artifact declares. TheSIGis one declaration and may not useany,never,typeof,importorinfer; a deliberately foreign canary must fail to conform, or the check itself is broken. - The any-ban is a lexer and fails closed. It reads code positions only, as whole words, honoring every directive tsc honors; where it must guess whether a
/is a regex or a division, it reads the source both ways. - A result outside the shared envelope is narrowed, never compared across languages — comparing values one language cannot represent proves nothing either way.
- Rust: every harness line is an
{ok}/{throw}envelope, a scalar result is pinned to the declared type, and crates build with--locked. - One judge. Anything that grades — a factory, a lab, CI — must use the shipped verifier's own modules, generated from them and hash-locked. A verdict from a different judge is not a claim.
rdv check re-runs on your machine.
13 · Non-normative annotations
Decompilers emit human-facing prose to orient a reader: ABOUT, INVARIANT, NOTES, CONTROL, CHOREOGRAPHY, TRACE-INVARIANT. These are annotations, not contract. By invariant iii they carry no verification weight — they can be incomplete, and they have been observed to be wrong. A re-emitter may read them; a verifier ignores them. If an annotation and the oracle disagree, the oracle wins, every time.
The practical consequence: never encode a behavioral guarantee in a comment and expect it to hold. If a behavior matters, it belongs in a vector, where execution proves it and the held-out gate enforces it.
14 · Conformance & governance
This specification is normative. The key words MUST, MUST NOT, SHOULD, and MAY are interpreted as in RFC 2119. SIR is intended to develop as an open, royalty-free standard for verified software contracts — implementable by anyone, in any language, without license or fee.
Conformance classes
Three independent conformance targets. An implementation may conform as any one of them.
| Target | Requirements |
|---|---|
| conforming bundle | MUST contain a primary sir/<unit>.sir per §3–§6 and, per language, a language file bound to that primary (§8); MUST carry an oracle with disjoint frozen and held-out vectors in sir-canonical-v1 (§10, §12); MUST record the schema version it targets; every expected value MUST be execution-derived (§2.iv), never hand-authored. |
| conforming checker | Given a bundle, MUST verify every recorded hash and binding, and MUST re-run the held-out oracle — and the js extension where one is named — for each language variant through its own harness (§12); MUST fail on any miss, mismatch or stale binding; MUST NOT treat a frozen / in-prompt pass as evidence of conformance; MUST halt, not skip, on a language it cannot harness. |
| conforming producer | MUST reconstruct an implementation from the bundle alone, with the original deleted (§2.iv); MUST report a unit "verified" only when N≥2 independent emissions agree on the full held-out set; MUST grade with the checker's own judge (§12). |
The whole pipeline — bundle, checker, and producer — is in scope of the open standard. The standard defines what conformance is; it does not mandate how a producer reconstructs an implementation (the quality of that engine is where implementations compete).
Standardization & licensing posture
SIR is developed as an open, royalty-free standard. The format and the rdv reference checker are licensed Apache-2.0 and free to implement — in any language, by anyone, with no fee, no license negotiation, and no patent assertion against conforming implementations. The format is not encumbered, and our commitment to keep it that way is written down and binding in The rederive Promise.
Versioning
The normative schema lives at github.com/rederive/sir-spec, currently v0.5 (2026-10-23, revised 2026-10-28). v0.5 splits a unit into a language-neutral primary and one language file per target language, adds the sir-canonical-v1 encoding and the js envelope extension, freezes the practiced directive vocabulary, and — in the 2026-10-28 revision — the rules for how a verifier calls and judges an artifact, learned by rederive re-deriving its own verifier (42/42 units — js and ts for all 42, rust for 38). The lineage: v0.1 frozen 2026-06-10; v0.2 (2026-06-26) — KIND STATE's {result, post} observable, fidelity variants (package- vs spec-anchored), decision-table fidelity, and the specVersion'd bundle contract; v0.3 (2026-07-01) — ORACLE-CLASS/TRACE-SEAM declarations, export-shape SEAMs (data-object & chainable-constructor exports), the verified-scope ENVELOPE, and carried-data authority attestation; v0.4 (2026-07-01) — the concurrency layer: validated PAR semantics, the scheduler control effect + virtual time, the resource-lifecycle oracle channel, and the token-coordinated RING shape. (Renumbering note: the concurrency layer was previously described on this page as "v0.2/v0.3 of 2026-06-22" — the schema evolved on two parallel workstreams that were unified 2026-07-01; shipped bundles pin specVersion of the unified lineage, so nothing in the wild changes meaning.) Each addition is forced by a named specimen (lodash.pullat, aws4, p-map, q, a two-account transfer, request's redirect, ringbuf.js, the boxen terminal stack). Every decision still cites the specimen that forced it — nothing is resolved from taste alone. Changes are versioned, never silent; a conforming bundle records the version it targets.
Deferred (named, not frozen)
- Transactions / compensation; multi-process effects across machines — the wire (message loss, partial failure, cross-machine clocks). Intra-process concurrency is addressed in §6; the network boundary stays record/replay-or-bespoke.
- Optimal source-set DPOR for the interleaving ladder (§6) — sleep/persistent-set reduction is validated; the optimal variant (one explored execution per class) is future.
- An ambient-read tier (
env.cwd, locale, timezone). - The
uidomain verbs (a frontend target is a non-goal at this phase). - Cross-language oracle anchors (
ANCHOR ref(<lang>:…)) are declared but not yet executed; carried data inside a language variant is supported by the factory, not yet by the checker. - Grading the ts variant on the js envelope extension; language-file inheritance (
tsfromjs).
SIR comes from Semcom's verified-recompose method. All of it is open (Apache-2.0): the format, the rdv checker, and the loop that produces contracts — sir-factory and the Claude Code plugin. Anyone may build a competing implementation; it competes on quality, never on access.
15 · The two modes — re-derivation & verified normalization
The verified-recompose method runs in two modes, differing in what plays the oracle and whether the original survives. Both produce the same SIR units under the same firewall (§4); only the source of ground truth differs.
Mode 1 — catalog re-derivation
What §12's bundle describes: a unit with a compact spec and a frozen, held-out oracle. The original is deleted before re-emit; N isolated rebuilds must agree on the full held-out set (quorum). This is how the catalog ships verified packages.
Mode 2 — verified normalization
For a monolith whose behavior won't compress into a compact contract — a large stateful class, an async state machine, a concurrent coordinator — the original is retained as a live differential oracle. You propose a firewall-clean factoring (the same kinds and FUNCTIONAL ⊅ EFFECT firewall as §4) and verify it reproduces the original on generated, held-out scenarios it never saw. Mode 1 guards against hallucination; Mode 2 guards against an incomplete refactor (regression). A Phase-0 feasibility gate decides normalizable vs. genuinely bespoke before any cut: if no faithful, deterministic oracle can be captured, the honest answer is to stop.
Effects, time & concurrency under Mode 2
The boundary descriptors of §6 are injected and replayed: net/fs/env via record/replay, the clock as a value, and the event loop itself as an injectable scheduler. Timers verify on virtual time (a timer race is nondeterministic on the wall clock, deterministic once the loop is owned). Genuinely concurrent units are verified by owning the message scheduler and checking the space of interleavings — exhaustively for small inputs, and partial-order-reduced beyond (one representative per equivalence class of independent reorderings). A control effect additionally carries a resource-lifecycle channel — a cancelled timer, a torn-down subscription — that value-and-order observation alone is blind to.
The honest ceiling
Mode 2 is testing, not proof: a normalized unit is proven-equivalent on the exercised, coverage-reported scenario distribution — dramatically stronger than a blind rewrite, never "provably identical everywhere." The coverage rung reached — exhaustive, sampled, or partial-order-reduced — is reported, never silently assumed.
16 · Lineage (non-normative)
SIR is assembled from well-understood pieces, not invented whole. Each construct is named here with its origin — both as intellectual honesty and because a named, classical construct is one an implementer and a verifier can actually reason about. The recurrence is no accident: the abstractions that are verifiable are the ones with small, explicit, well-defined semantics — exactly what the classics, born under tight constraints, were forced to produce.
- The kind-discriminated tree (§3–5) — compiler intermediate representations and the AST; structured / stepwise refinement (Dijkstra; Wirth).
- The
FUNCTIONAL ⊅ EFFECTfirewall & injected boundaries (§6) — effect systems and algebraic effects & handlers (Plotkin & Power; Plotkin & Pretnar); monads (Moggi; Wadler). "Inject, never ambient" is the object-capability model (Dennis & Van Horn; Miller) and least privilege (Saltzer & Schroeder, 1975). - The oracle — behavior over text (§7) — denotational semantics (Scott & Strachey); observational equivalence and bisimulation (Milner; Park); property-based testing (QuickCheck — Claessen & Hughes, 2000).
- Quorum re-emission (§12) — N-version programming (Avižienis): independent implementations accepted on agreement; held-out grading is cross-validation.
- PAR & concurrency (§6) — CSP and refinement (Hoare, 1978); Petri nets (Petri, 1962) for the token and place-invariants; model checking (Clarke & Emerson; Queille & Sifakis) and TLA+ (Lamport) for interleaving + refinement + invariants; Mazurkiewicz traces (1977) and partial-order reduction (Godefroid; Peled; Abdulla et al.) for the independence collapse.
- The actor shape — the actor model (Hewitt, Bishop & Steiger, 1973); E-language vats (Miller).
- The ring shape — token-passing mutual exclusion (Le Lann; Suzuki & Kasami); Kahn Process Networks (Kahn, 1974) for FIFO determinism-by-construction; the single-writer discipline as linearity (linear logic — Girard; ownership types).
- Verified normalization (Mode 2, §15) — term rewriting and confluence / Church–Rosser; Knuth–Bendix completion; the refinement calculus (Back; Morgan).
- The contract & content hashes (§12, §14) — Design by Contract (Meyer / Eiffel) and Hoare logic (1969); content-addressed code (Unison); reproducible builds (Nix — Dolstra).
- The runtime — Forth (Moore) for the concatenative dictionary; Smalltalk (Kay; Goldberg & Robson) for message passing and
doesNotUnderstand:, the literal trigger for synthesis.
On the roadmap — definition hardening: lift invariants and refinement into a small declarative property language on the contract (TLA+ / refinement-calculus style), so more verification — and more deterministic codegen — keys off the definition than off hand-written checks; and abstract interpretation (Cousot & Cousot, 1977) as the soundness theory for when sampled coverage is sound.