jig-harness/jig
M15

Contracts & error handling

Failures keep their cause and travel on three typed channels, callers branch on type or code, one boundary maps errors to responses, a merged migration never changes, an interface is internal by default
1 · The idearead this first

A system’s callers, its stored data and its own modules depend on contracts that nothing checks by default, and the quietest breakage is in error handling. A catch that returns null turns a failed network call into “no result”, and whoever debugs it an hour later finds an empty list, not the failure. A child process runs with its error output discarded, so when it fails the reason it printed is gone. One module signals “not found” by returning undefined, the next by throwing a plain Error, a third by returning { success: false }, and a caller that needs to react to “not found” ends up testing the error’s message text, which breaks the day someone rewords it. At the edge of the system an unexpected error reaches the caller as a stack trace with an internal path, a secret’s name or another account’s identifier in it. Each of these passes every test and surfaces as an incident. This module states the contract: a failure keeps its cause and travels on one of three declared channels, callers branch on its type or code, and errors reach the outside through one boundary with a fixed, safe shape. The contracts that stored data and published interfaces depend on (one registry of error codes, migrations that never change once applied, an interface that is internal by default) are the module’s other pieces; see Status.

Invariantthe rule, independent of any tool

A failure is either propagated or reported with its original cause attached; no code path turns an error into a default value, an empty result or silence. Every failure travels on one of three failure channels: an expected outcome the caller branches on is returned as the one result type, a failure that crosses a module boundary is thrown as a typed domain error carrying a registered code, and a bug or broken invariant is raised through one defect primitive. Callers branch on type or code, never on message text. Errors reach callers only through one error boundary that maps them to a fixed response shape, and nothing internal leaves it on a server-side failure.

Each piece below is a tool-independent rule; the tools that implement it in each ecosystem are in mappings.md. Terms in bold are defined in the glossary.

2 · The practicewhat each level asks of your repository

M15 Lite — minimum useful

the error contract is written where agents and people read it (the three channels, never swallow and keep the cause, branch on type or code, the transaction rule, the boundary), the typed error family with codes exists, and the codes are declared once in one registry, in one format; where the repository has database migrations, the migration discipline is written beside them (immutable once merged, structure only, the ledger entry each needs, the review marker); where it serves an interface, the interface policy is written beside the contract (internal by default, the consumer question, a bound on every input, the failure statuses declared); enforcement may be convention.

What the audit checks at Lite convention-only is enough must be mechanically enforced
  1. The error contract is written where agents and people read it: the three failure channels and which situation takes which, never swallow and keep the cause, branch on type or code and never on message text, a failure inside a transaction aborts it (rolls it back, by the path the transaction tool rolls back on), and errors reach callers only through one boundary.
    error-contract-writtenWhat the audit looks for (2)
    • an error-handling doc, rule file or the instruction file states the three channels (a result type for expected outcomes, a typed error with a code at module boundaries, a defect primitive for bugs), the cause rule, the type-or-code rule, the transaction rule (a failure inside a transaction rolls it back, with the path that does so for the tool in use) and the boundary
    • the instruction file points at it
  2. One shared module defines the typed error that crosses module boundaries, carrying the tag a caller branches on (the registered code and its metadata, severity, message key and recovery hint, where the system emits codes), and the one defect primitive beside it; a result type, where one is used, is one type whose error arm carries a tag (expected-absent where no failure crosses a module boundary to a caller that branches on it: a command-line tool whose every failure ends the process with a status and a message).
    typed-error-with-codeWhat the audit looks for (2)
    • a module defines the base error type with a code or kind field (and the code's metadata where codes exist), and the defect primitive (invariant() or a defect error type)
    • the result type, where present, is a single tagged union, not several shapes ({ success }, { ok }, an outcome union) across the codebase
  3. Every error code the system can emit is declared once, in one registry (a data file or one code module), with its metadata (severity, message key, recovery hint, transport status) and in one declared code format; the error contract names the registry as the only place a code is minted (expected-absent where the system emits no codes because it reports failures to no caller beyond an exit status or a thrown typed error: a library, a command-line tool).
    error-code-registryWhat the audit looks for (2)
    • one registry file or module declares every code with its metadata, and the code format is declared once (a pattern the registry and its scanners share)
    • the error contract or the registry's own header says no code is constructed anywhere else and names what is generated from it
  4. Where the repository has database migrations, the discipline is written beside them or in the instruction file: a merged migration is never edited, renamed or deleted and is corrected by a new one, a migration changes structure only, each migration's ledger entry lands with it, and a migration's commit carries a review marker (expected-absent where the repository has no database migrations).
    migration-discipline-writtenWhat the audit looks for (2)
    • a document beside the migrations directory, or the instruction file, states the four rules: immutable once merged with fix forward, structure only, the ledger entry each migration needs, and the review marker
    • the instruction file points at it, or is it
  5. Where the repository serves an interface (HTTP, RPC, GraphQL), the interface policy is written beside the contract or in the instruction file: an operation is internal unless a named external consumer justifies publishing it, a change that publishes one names its consumer, every request input declares a bound, and an operation declares every failure status its code can produce (expected-absent where the repository serves no interface).
    interface-policy-writtenWhat the audit looks for (2)
    • a document beside the contract, or the instruction file, states internal by default with the consumer question, the bound on every input (and the named schemas that carry the bounds), and the declared failure statuses
    • the pull-request template or the review checklist asks who the external consumer of a newly published operation is

M15 Standard — production teams

a lint rejects the swallowing forms (a default-returning catch, discarded error output, an unchecked cast), blocking in CI directly or under a ratchet; errors reach callers through one boundary with the fixed shape; a test proves a server-side failure carries no internal detail; detached work goes through one reporting helper and each entry point installs the unhandled-rejection listener; every other copy of the codes is generated from the registry and drift-gated, a code without its message in a locale fails CI, and a gate rejects a code constructed outside the registry; a merge-time gate rejects an edit, rename or deletion of a merged migration, the runner refuses an applied file whose hash changed, and a check holds the ledger and the files one to one in strictly increasing order; the published and the internal contract documents are generated from one source and a gate fails an internal operation in the published one, and the count of unbounded request inputs runs under the ratchet.

What the audit checks at Standard convention-only is enough must be mechanically enforced
  1. A lint run in CI flags the forms that turn a failure into a default value, an empty result or silence: a catch that returns a default without looking at its error, a child process whose error output is discarded, and a parsed input cast to a concrete type; it blocks the merge directly or under a ratchet on its count.
    swallowing-forms-lintedWhat the audit looks for (2)
    • lint rules (GritQL plugins, no-restricted-syntax selectors, Ruff BLE001/S110/B904, errcheck/nilerr, clippy unwrap_used, Error Prone CatchAndPrintStackTrace) cover the three forms
    • they run in the CI gate set and block, or a ratchet fails a change that adds a finding
  2. Errors reach callers only through one boundary per transport (an error-handler plugin, a top-level middleware, an interceptor, the exit code boundary of a command-line tool) that writes one fixed shape and maps an error it does not know to an opaque generic failure: on a transport that carries codes, a response of code, message key, severity, recovery hint and correlation id, with an unknown error mapped to a registered generic code; on a command-line transport, or where the system emits no codes, an exit status per outcome and one message line, with an unknown error mapped to the generic failure status. No route or command builds an error response or exit of its own.
    one-error-boundaryWhat the audit looks for (3)
    • one error handler is registered on each transport's entry point and is the only place that maps an error to a status
    • an unknown error maps to a registered generic code (or, on a command-line transport or where no codes exist, to the boundary's generic failure status), not to the error's own status or shape
    • no route or command writes an error body or exit code of its own (a lint or a grep gate over the handlers, or a count under a ratchet, is what makes this mechanical)
  3. On a server-side failure the boundary sends no internal detail (no exception text, no interpolated template, no identifier), logs the detail through an allowlist keyed by the correlation id, and a test run in CI sends an unknown error through the boundary and asserts that the body holds the public field set (code, message key, severity, recovery hint, correlation id) with the generic code, and that no internal detail (stack, cause, query text, file path, the internal message) is in it (expected-absent where the repository serves no network interface).
    server-failures-hide-detailWhat the audit looks for (2)
    • the boundary strips details on a 5xx or INTERNAL status and the framework's own stack traces are off in production (debug=False, include-stacktrace=never, or the equivalent)
    • a test in the CI gate set asserts the body of an unknown error holds the public field set with the generic code and carries no stack, cause, query text, file path or internal message
  4. Work nobody awaits goes through one helper that reports a failure with its cause and never rejects, and each long-running entry point installs one process-level handler for unhandled rejections that reports the same way, falls back to standard error and never throws (expected-absent where a lint rejects un-awaited promises and the repository starts no detached work).
    detached-work-reportedWhat the audit looks for (2)
    • a helper (runDetached, a task set with a done callback, a spawn wrapper that recovers a panic) is the way detached work starts; a lint for un-awaited promises (noFloatingPromises, no-floating-promises) still accepts a promise started with void, so the helper with that lint alone scores convention; it scores mechanical only when a check in CI also rejects a detached start outside the helper's module (for TypeScript, Biome noVoid or ESLint no-void with that module excluded, or no-floating-promises with ignoreVoid: false)
    • each server or worker entry point installs the unhandled-rejection handler (or the ecosystem's equivalent: loop.set_exception_handler, a panic hook, setDefaultUncaughtExceptionHandler) once, and on Node runs in the default unhandled-rejection mode, with no --unhandled-rejections=strict in its start command or NODE_OPTIONS
  5. Every other copy of the codes (the client's code union, each locale's message catalog, the public error reference) is generated from the registry and carries a drift check in CI that regenerates through the generator's own function and compares the whole text; a registered code with no message entry in a locale, or with a placeholder entry, fails the check (expected-absent where no client, locale catalog or public reference holds a copy of the codes).
    error-code-copies-generatedWhat the audit looks for (2)
    • each copy of the codes is a generated file with a regenerate command and a --check (or diff) step in the CI gate set; none is hand-edited
    • the catalog check fails on a code with no entry in a locale and on a placeholder entry, in the working tree or already merged
  6. No code is constructed outside the registry: the constructor is not reachable from elsewhere, or a gate in CI rejects a construction outside the registry over every package that depends on the error module, with an allowlist that is empty or lists existing debt by identity (file and code) rather than by count (expected-absent where the system emits no codes because it reports failures to no caller beyond an exit status or a thrown typed error: a library, a command-line tool).
    no-inline-error-codesWhat the audit looks for (2)
    • the registry module does not export the constructor, or a gate (a grep gate, a lint rule on the constructor call, an architecture test) runs in the CI gate set over every dependent package and blocks
    • the gate's allowlist, where one exists, names each tolerated construction by file and code, and a stale entry fails the gate
  7. A gate in CI fails a change that modifies, renames or deletes a migration file the base branch already holds, allowing only a restoration to content the file held before on that branch, and the migration runner records each file's hash when it applies it and refuses to run while an applied file's hash differs or the file is gone (expected-absent where the repository has no database migrations).
    applied-migrations-immutableWhat the audit looks for (2)
    • a script in the CI gate set diffs the migrations directory against the merge base and blocks on a modified, renamed or deleted migration file, with a restoration to a prior state the one allowed edit
    • the runner (the tool's own validation, or the repository's wrapper) compares the hash recorded at apply with the file and refuses to continue on a difference or a missing file, in every environment
  8. A check in CI holds the migration ledger and the files one to one, in strictly increasing order with no gap in the sequence and every field the runner reads explicit on each entry, so no migration is skipped silently or left without an entry (expected-absent where the repository has no database migrations).
    migration-ledger-integrityWhat the audit looks for (2)
    • a script in the CI gate set reads the ledger (a journal, a changelog, a revision chain, the files' own numbering) and the files, and blocks on a file without an entry, an entry without a file, a duplicated or non-increasing order key, a gap in the index, or a missing field
    • where the tool's own validation refuses a behind or unlisted migration (Flyway validate, Alembic with more than one head, goose without -allow-missing), that validation runs in CI and is the check
  9. The published and the internal contract documents are generated from one source in which each operation is marked once (a tag, an extension field, a path prefix, a package or a schema directive), and a gate in CI fails when the published document holds an operation carrying the internal mark (expected-absent where the repository serves no interface).
    published-contract-filteredWhat the audit looks for (2)
    • one generator writes the published document without the marked operations and the internal one with only them, from the route schemas or the schema source, and a drift check keeps both fresh
    • a script in the CI gate set reads the published document and blocks on an internal tag, path, extension or package in it
  10. A check in CI counts the request input fields of the contract that declare no bound (a string with no maximum length, pattern or format; a number with no maximum; an array with no maximum item count; a field with no type) and fails when the count exceeds the base branch's or a committed ceiling, with a field that is unbounded on purpose marked by a reason in the contract (expected-absent where the repository serves no interface).
    input-bounds-ratchetedWhat the audit looks for (2)
    • a script in the CI gate set walks the contract document, or the request schemas, and blocks when the count of unbounded fields rises above the merge base's or a ceiling, or is above zero
    • an exception is a reason beside the field in the contract or the schema, not a count, and an exception without a reason fails the check

M15 Strict — regulated / compliance posture

lint rules reject a thrown native error outside the typed family and the defect primitive, and a branch on message text; error telemetry is keyed on code and type, with an outcome dimension for result arms, and structured logs carry a message or a cause chain only through redaction; an audit reports orphans against a baseline by identity, and reverse orphans in hand-written documents; a parser-based check rejects a data change in a migration, with its allowlist outside the files; the count of unbounded request inputs is zero, and each operation’s declared failure statuses are checked in review against the codes its handler throws.

What the audit checks at Strict convention-only is enough must be mechanically enforced
  1. A lint flags a thrown native error (throw new Error and the built-in siblings) outside the typed error family's own module and the defect primitive, blocking the merge directly or under a ratchet on its count.
    native-throw-lintedWhat the audit looks for (2)
    • a lint rule (GritQL plugin, no-restricted-syntax, Ruff TRY002, a grep gate on errors.New / fmt.Errorf outside the error package) covers the thrown native error, with the typed family's module and the defect primitive excluded by path
    • it runs in the CI gate set and blocks, or a ratchet fails a change that adds a finding
  2. A lint flags a branch on an error's message text (equality, prefix, substring, a regular expression on .message, str(e), err.Error(), getMessage()) in a catch clause, blocking the merge directly or under a ratchet on its count.
    message-branch-lintedWhat the audit looks for (2)
    • a lint rule or grep gate covers the message test inside a catch clause, in the forms the language allows
    • it runs in the CI gate set and blocks, or a ratchet fails a change that adds a finding
  3. An audit in CI reports every registered code that nothing outside the registry references (an orphan) against a baseline that names each accepted orphan with its reason and fails on a stale entry, and every code-shaped literal in a hand-written document that no registry entry declares (a reverse orphan) (expected-absent where the system emits no codes because it reports failures to no caller beyond an exit status or a thrown typed error: a library, a command-line tool).
    error-code-orphans-auditedWhat the audit looks for (2)
    • an audit script runs in the CI gate set over the source packages and the hand-written documents and blocks on an orphan outside the baseline or on an unregistered code in a document
    • the baseline lists accepted orphans by code with a reason each, and an entry for a code that is referenced or not registered fails the audit
  4. Error metrics and span attributes are keyed on the error's code and its type, never its message; structured logs carry the code and type as fields and a message or cause chain only as diagnostic detail that passes through redaction; and a method that returns a result type records the arm it returned as an outcome rather than as an error (expected-absent where the repository emits no telemetry).
    telemetry-keyed-on-codeWhat the audit looks for (2)
    • the telemetry wrapper or the boundary records error.code and error.type (the class name) as metric labels and span attributes and never error.message there; a structured log carries code and type as fields, and a message or cause chain in it goes through the redacting allowlist and is not a field anything aggregates on
    • a returned error arm is recorded as an outcome dimension, with span status ERROR reserved for a thrown error
  5. A check in CI parses each migration with the database's grammar and blocks on a data statement (insert, update, delete, merge) anywhere in the statement tree, a procedural block or a function body included, fails a file whose dynamic statements it cannot read, and takes its exceptions from an allowlist outside the migration files that names each statement by identity under a reviewer's reason (expected-absent where the repository has no database migrations).
    migrations-structure-onlyWhat the audit looks for (2)
    • a script in the CI gate set parses the migrations through a grammar parser (libpg_query bindings, sqlglot, ScriptDom, or the language's syntax tree for migrations written as code), not a regular expression over the text, and blocks on a data statement at any depth
    • an unreadable dynamic statement fails the file as could not check, and the allowlist lives outside the migrations, lists statements by file and identity with a reason each, and a stale entry fails the check
  6. The count of request input fields of the contract that declare no bound is zero, and a check in CI holds it there by failing on any unbounded field (expected-absent where the repository serves no interface).
    unbounded-inputs-zeroWhat the audit looks for (2)
    • the unbounded-input check in the CI gate set runs with a ceiling of zero (count-unbounded-inputs.ts --max 0, or a committed ceiling of 0) and blocks
    • running it over the current contract document reports a count of zero
  7. Each operation's declared failure responses name every status its code can produce: the boundary's generic server-side status, the validation status, the authentication and authorization refusals where those layers run, and the transport status of each domain error the handler throws; the review checks the list against the handler (expected-absent where the repository serves no interface).
    failure-statuses-declaredWhat the audit looks for (2)
    • the contract's operations declare the generic server-side failure, the validation failure and each domain error's status, and every success response carries a schema
    • the review checklist or the review skill checks a changed operation's declared statuses against the codes its handler throws, or a generator derives the list from the codes the route declares

Some criteria are expected-absent by shape: a library or a command-line tool serves no network interface, so the server-side-detail rule has nothing to apply to, a repository whose lint rejects un-awaited promises and has no detached work has nothing to route, one with no database has no migrations to hold, one that reports failures to no caller beyond an exit status or a thrown typed error (a library, a command-line tool) emits no codes, so it has no registry to hold, no constructor to keep out of reach and no orphans to audit, and its boundary writes an exit status rather than a coded response, and one that serves no interface (a library, a command-line tool, a static site) has no surface to publish or bound. The audit calibrates by repository shape.

Adoption steps

  1. Copy templates/ERROR-HANDLING.md into your docs tree, fill in the typed error, its code format, the boundary and the three channels, and point your instruction file at it. Define the domain error base with a code and the defect primitive, and derive the result type’s tag from the code. Declare the codes once, in one registry (templates/error-codes.yaml, or a code module with the same fields). Where you have database migrations, copy templates/MIGRATIONS.md beside them and fill in the format, the ledger entry and the review marker. Where you serve an interface, copy templates/INTERFACE-SURFACE.md beside the contract and fill in the mark, the named schemas and the consumer question. This is Lite.
  2. Wire the three swallowing rules (reference/lint-rules/, or the ecosystem’s equivalents in mappings.md) under M1’s ratchet; keep the cause in every wrapper the fixes introduce.
  3. Put one error boundary in front of every transport; map an unknown error to the generic code; strip every detail on a server-side failure and log it through an allowlist; write the test that sends an unknown error and asserts that the body holds the public field set (code, message key, severity, recovery hint, correlation id) with the generic code, and that no internal detail (stack, cause, query text, file path, the internal message) is in it.
  4. Route detached work through the helper (reference/detached/) and install the listener in each entry point, run in the runtime’s default mode for unhandled rejections.
  5. Generate every other copy of the codes from the registry under M2’s triad, with the catalog check failing on a placeholder; keep the constructor out of reach, or gate it (reference/error-registry/check-no-inline-codes.ts) with the allowlist at zero.
  6. Where you have migrations, run the merge-time gate (reference/migration-immutability/) in CI and pre-push against the branch the work merges into, turn on the runner’s hash check or add one in your wrapper (mappings.md says which runners have none), write the ledger check for your tool’s ledger, and set M1’s commit-msg marker on the migrations directory. Where you serve an interface, mark each internal operation at its source, have the generator write the published and the internal documents from it, and run both gates of reference/interface-surface/ in CI: the internal check over the published document, the unbounded-input count against the base branch. This is Standard.
  7. Add the two Strict rules (a thrown native error, a branch on message text) under the ratchet, excluding the typed family’s module and the defect primitive by path; promote each to an error when its count reaches zero.
  8. Key error telemetry on code and type, and record a result arm as an outcome. Run the orphan audit (reference/error-registry/audit-error-codes.ts) in CI, over the hand-written documents too, with a baseline by identity. Add the structure-only check over the migrations through your database’s parser, with its allowlist outside the files and empty. Bring the unbounded-input count to zero and hold it there (--max 0), and have the review check each operation’s declared failure statuses against the codes its handler throws. This is Strict.
3 · The mechanicsopen what you need
Core piecesOpen
  1. Never swallow, keep the cause. A failure is either propagated to the caller or reported with its original cause attached. No code path turns an error into a default value, an empty result or silence: not a catch that returns null, not a child process run with its error output discarded, not a parsed input cast to the type it is hoped to have, not an empty .catch(). Wrapping is fine, and often right, as long as the wrapper carries the original as its cause: the wrapper’s message (“query failed”) hides the fault its cause names. Work that nobody awaits, detached work, fails where nothing is listening, so it goes through one helper that reports a failure with its cause and never rejects; reference/detached/ is one. Each long-running entry point installs one process-level listener for unhandled rejections that reports them the same way, falls back to standard error when the logger itself fails, and never throws. The entry point runs in the runtime mode where that listener handles the rejection rather than one that exits first (mappings.md names the mode and its settings per runtime). With the listener in place the process no longer stops on an unhandled rejection, so the fix for a reported one is to route that work through the helper, never to remove the listener. The syntactic half of this rule is a lint: reference/lint-rules/ flags the default-returning catch, the discarded error output and the unchecked cast.

  2. Three failure channels. Every failure travels on one of three failure channels, and which one is a rule, not a taste:

    SituationChannel
    An expected outcome the caller branches on: a parse that can fail, a lease not acquired, a record not readyreturned as the one result type: a tagged union of a success arm and an error arm whose error carries a tag
    A failure that crosses a module boundary, expected or not: not found, forbidden, a conflict, an upstream unavailablethrown as a domain error: a typed error carrying a registered code and the metadata the code declares (severity, message key, recovery hint)
    A bug or a broken invariantraised through one defect primitive (invariant(condition, message) or a defect error type), so “defect” is a mechanical property rather than an author’s judgment; it maps to a generic server-side failure and is never caught to drive control flow

    One result type, not several: a repository with { success } here, { ok } there and an outcome union elsewhere has three channels for one thing, and callers handle each differently. The error arm’s tag is derived from the domain error’s code, not written by hand beside it, so there is no third discriminant to keep in step. A thrown native error (throw new Error(...)) is on no channel: it carries neither type nor code, so a caller can only read its message. A module that cannot import the shared domain error (a leaf package the shared one depends on) keeps its own tagged error family, and the adapter that calls it converts that family into domain errors at the call boundary; the family never reaches a route. A failure inside a database transaction aborts it: the transaction rolls back, and none of its partial work commits. The failure therefore leaves the transaction through its rollback path, never as a value the transaction’s mechanism reads as success (mappings.md names that path per tool). Conversion between the channels happens outside the transaction.

  3. Branch on type or code, never on message text. The message is for people. A caller branches on the error’s type (instanceof), its code or its tag; a test of err.message (startsWith, includes, equality, a regular expression) breaks when the text is reworded or translated, and on the wire the message is a key for localization, not a sentence. The lint in reference/lint-rules/ catches the forms it can see; review catches the rest.

  4. One error boundary. Errors reach callers only through one error boundary: an error-handler plugin on a web server, the exit-code boundary of a command-line tool. It maps each error to a fixed response shape: a code, a message key, a severity, a recovery hint and a correlation id, which together are the complete public field set, plus, when the failure is the caller’s (a 4xx), structured details such as field errors. An error the boundary does not know (not a domain error, not one of the framework errors it enumerates) becomes an opaque generic code with a server-side status. Nothing “error-shaped” is trusted by its shape: a look-alike can pass a guard and still carry an unregistered code and status onto the wire, so the boundary asks for the registered type. On a server-side failure (5xx) no internal detail is sent at all: no exception text, no stack, no cause, no query text, no file path, no interpolated template, no identifier; the body holds the public field set and nothing more. The detail is logged through an allowlist of keys known to be safe, and the correlation id is what support uses to find it. A system with no network transport and no codes (a command-line tool) writes the same rule in its own shape: an exit status per outcome and one line on standard error, with an unknown error mapped to the generic failure status. A route never builds an error response by hand, and never returns a result type’s error arm as a success body: it maps every error arm, exhaustively, to a thrown domain error.

  5. Telemetry keyed on code and type. Error metrics and span attributes are keyed on the error’s code and its type (the class name), never its message: a message as a metric label or a span attribute is unbounded cardinality and a leak of whatever the message interpolated. A structured log carries the same code and type as its fields, and may also carry diagnostic detail (the message and the cause chain) for the person debugging, but only through redaction: the allowlist of keys the boundary logs through, with secrets and identifiers masked, and never as a field anything aggregates on. An expected failure returned as a result arm is recorded as an outcome of the operation, not as an error, so a dashboard tells “the parse said no” from “the service broke”. M11 measures the delivery process the same way, by typed events and never by log text.

  6. One error-code registry. Every code a system can emit is declared once, in one error-code registry, with its metadata (severity, message key, recovery hint, transport status) and in one declared format. Everything else that names codes is a generated artifact of the registry, never a second declaration: the client’s exhaustive code union (so a switch over the codes narrows to never, and a new code fails the client’s build until it is handled), each locale’s message catalog, and the public error reference. Each copy carries M2’s freshness triad, and its drift check regenerates through the generator’s own function and compares the whole text, so there is no second recognizer to drift. The catalog generator owns the catalog’s structure, not its words: it keeps every authored entry byte for byte, inserts a visible placeholder for a registered code that has no entry yet, and drops the entry of a code no longer registered; the check fails on any difference and on a placeholder, in the change or already merged, so a code minted without its message in every locale fails CI. No code is constructed outside the registry: the strongest form is visibility, a constructor the registry’s module does not export; where the language cannot hide it, a gate rejects the constructor elsewhere (reference/error-registry/), over every package that depends on the error module, a set derived from the dependency graph rather than listed by hand. The gate’s allowlist is kept at zero, and while debt remains it is listed by identity (the file and the code), checked for exact equality, never as a count: a count stays the same when one construction is fixed and another added. The registry and the code that throws must agree both ways, so an audit reports orphans, registered codes nothing references, against a baseline by identity, and reverse orphans, code-shaped literals in hand-written documents that no registry declares: a generated reference cannot hold one, a hand-written page can. M2 leaves the error-code catalog out of its worked examples because its values are domain-bound; this piece is the mechanism without the values, and templates/error-codes.yaml holds neutral ones.

  7. Migration discipline. The structure a system stores its data in changes through migrations, and three contracts hold them. Immutable once merged. A migration that has merged is never edited, renamed or deleted; a wrong one is corrected by a new one (fix forward). The rule is held twice, because each half misses what the other catches. At merge time a gate diffs the migrations directory against the merge base and fails on a modified, renamed or deleted file, allowing one thing: a restoration to content the file held before on the base branch, which repairs an earlier illegal edit (reference/migration-immutability/). At apply time the runner records each file’s hash when it applies it and refuses to run while an applied file’s hash differs or its file is gone, so an edit that slipped past the gate stops before the next migration runs, not after; a tool whose runner records no hash gets one in the repository’s own wrapper. Ledger integrity. The migration ledger, the record of what exists to apply (a journal file, a changelog, a revision chain), and the files match one to one, in strictly increasing order with no gap in the sequence, and each entry spells out every field the runner reads. A runner that applies “everything after the last applied” silently skips an entry whose order key is behind the latest; a file with no entry never runs, and an entry with no file fails the deploy at the one moment it matters. Structure only. A migration changes structure (tables, columns, indexes, constraints, functions, policies), never data: a data change is a backfill with a runtime, a lock and a rollback story of its own, and belongs in a seed, a job or a reviewed one-off. The check parses the SQL grammar and walks the statement tree, so an INSERT inside a WITH query, a DO block or a function body is found, where a regular expression over the text finds the shapes its author thought of; a statement built dynamically at run time, which no parser can read, fails the file closed rather than reading as clean. A data change that must ride in a migration needs a reviewed allowlist entry outside the file, bound to the statement’s identity, because an applied file cannot gain a marker later. Mandatory review. A migration’s commit carries a review marker that a commit-msg hook checks and CI re-checks; M1’s commit-msg marker is that mechanism, with a migration review as its default example. Which runners record a hash, which skip silently and which parser reads each database’s grammar are in mappings.md; templates/MIGRATIONS.md is the contract to keep beside the migrations.

  8. Published interface surface. Three contracts hold the interface a system serves. Internal by default. An operation is internal unless a named external consumer justifies publishing it: a published operation is a commitment to its shape for as long as anyone integrates against it, un-publishing one costs a deprecation cycle and a migration window, while marking one internal is reversible the day a consumer asks. Each operation is marked once, at its source (a tag suffix, an extension field, a path prefix), and one generator writes two documents from that source: the published interface, without the marked operations, and the internal one, with only them. A gate reads the published document and fails on any mark of the internal kind (reference/interface-surface/). A change that publishes an operation answers three questions where the reviewer reads them: who the external consumer is (a named role or system, not a future one), what they get that they cannot get another way, and why now; “someone might want it”, “its sibling is public” and “it would be inconsistent otherwise” do not answer them, and the reviewer’s default is “internal until a consumer asks”. Bounded inputs. Every request input field declares a bound in the contract: a maximum length, a pattern or a format on a string, a maximum on a number, a maximum item count on an array, a closed shape on an object, a type on everything. A field with no bound accepts whatever a caller sends, and what the interface accepts the system stores, indexes, logs and forwards; a bound in the contract is one the validator enforces and the consumer reads. A named schema per kind of value (a name, a short text, a search query, an address) carries its bound once, so a bare string in a request stands out. A contract already carrying unbounded fields does not become clean in one change, so their count is held under M1’s ratchet: measured over the contract document, not the route source, since a declaration split across lines or built from a spread is one node in the document and a hole in a text scan; it may fall, never rise, and a field unbounded on purpose carries its reason beside it in the document. Declared failure statuses. An operation’s declared failure responses name every status its code can produce: the boundary’s generic server-side failure, the validation failure, the authentication and authorization refusals where those layers run, and the transport status of each domain error the handler throws, which the error-code registry already holds. A generated client then handles what can arrive, and a status the contract does not declare is a finding in review, not a surprise in production. The forms of the mark, the bound and the status list per contract technology are in mappings.md; templates/INTERFACE-SURFACE.md is the policy to keep beside the contract.

In your toolsThe same rule, wired into a specific CI provider, hook manager or tracker. Shows only your stack.Open

The module invariant is tool-independent: a failure keeps its cause, travels on one of three channels, is branched on by type or code, and reaches callers through one boundary. This page maps each piece onto concrete languages, libraries and frameworks. Replace <placeholders> with your values. The module’s reference implementations are its own: reference/detached/, reference/error-registry/, reference/interface-surface/ and reference/migration-immutability/ are TypeScript for Bun and Node, and reference/lint-rules/ holds GritQL rules for Biome; the rest of this page is a feature of the named tool.

Never swallow, keep the cause

EcosystemKeeping the causeLint against swallowing
TypeScript / JavaScriptnew DomainError(code, { cause: error }); the standard Error cause option, read by loggers that print the chainreference/lint-rules/ (catch-return-default, stderr-ignore, json-parse-cast) as Biome GritQL plugins; on ESLint, no-empty with allowEmptyCatch: false, preserve-caught-error (a rethrown wrapper must pass cause), and no-restricted-syntax selectors for a default-returning CatchClause and for stdio: "ignore"
Pythonraise DomainError(code) from error, which sets __cause__; logging.exception(...) inside except records the tracebackRuff: BLE001 (a blind except Exception), S110 (try-except-pass), B904 (raise without from inside except), TRY400 (logging.error where logging.exception keeps the traceback); subprocess.run(..., stderr=subprocess.DEVNULL) found by a grep gate
Gofmt.Errorf("open ledger: %w", err) wraps with %w; errors.Join keeps severalgolangci-lint: errcheck (an error return dropped), nilerr (an error checked, then nil returned), errorlint (%w, and errors.Is/As instead of == and type assertions), wrapcheck (an error from another package returned unwrapped)
Rust? propagates; thiserror’s #[source] and #[from] keep the inner error; anyhow::Context adds a message while keeping the chain#[must_use] on Result is built in (unused_must_use); clippy let_underscore_must_use for let _ = fallible(); clippy unwrap_used and expect_used in library code
JVMnew DomainException(code, cause); the Throwable cause chainError Prone CatchAndPrintStackTrace, UnusedException; SpotBugs DE_MIGHT_IGNORE; Checkstyle EmptyCatchBlock
.NETthrow new DomainException(code, message, inner); InnerExceptionRoslyn analyzers CA1031 (a catch of a general exception type), CA2200 (rethrow that loses the stack); throw; not throw ex;

Whatever the language, the wrapper’s message says what was being done (“open the ledger”), and the cause says what went wrong.

Failure channels

EcosystemThe result type (expected outcomes)The typed error with a code (module boundaries)The defect primitive (bugs)
TypeScript, hand-rolledtype Result<T, E extends { readonly _tag: string }> = { ok: true; value: T } | { ok: false; error: E } with ok, err, isOk, map and unwrapOrThrow beside it; nothing moreclass DomainError extends Error holding an ErrorCode value object (code, severity, message key, recovery hint, transport status); the _tag derived from code with a literal type, so an exhaustive switch narrows to neverinvariant(condition, message) throwing a DefectError, in one shared module
TypeScript, neverthrowResult<T, E> and ResultAsync<T, E> with ok(), err(), .match(), .andThen(); eslint-plugin-neverthrow’s must-use-result fails a dropped resultthe same DomainError, carried in Ethe same primitive
TypeScript, EffectEffect<A, E, R> with Data.TaggedError for the error channel and Effect.catchTag to branch; defects are Cause.Die, never in Ea tagged error class per code, or the domain error wrapped in Data.TaggedErrorEffect.die / Effect.dieMessage
Pythona Result from the returns library (Success/Failure), or a small @dataclass union; an exception is never the expected channelan exception base with a code attribute and the code’s metadata, raised across module boundaries (raise NotFoundError(code=...) from error)assert is stripped under -O, so a dedicated invariant() raising DefectError
Go(T, error) is the result channel: an expected outcome returns a sentinel or typed error the caller tests with errors.Is / errors.Asa struct type implementing error with a Code field, returned across package boundaries, wrapped with %w on the waypanic with a dedicated type, recovered only at the top-level handler
RustResult<T, E> is the language; an expected outcome is an enum variant in Ean error enum per crate derived with thiserror, each variant carrying its code; anyhow only at the binary’s boundaryassert!, unreachable!, or panic! with a dedicated message prefix or payload type, all of which run in optimized builds too; debug_assert! is compiled out of an optimized build, so it is only for a check the program does not depend on
JVMa sealed interface Result<T, E> (Kotlin sealed class, Java sealed records)a DomainException holding an ErrorCode enum or recordIllegalStateException thrown only through an Invariants.check(...) helper

A failure inside a database transaction aborts it, in every ecosystem: the transaction rolls back and none of its partial work commits. Which path rolls back is the tool’s:

Transaction mechanismThe path that rolls backWhat commits by mistake
A callback helper that commits when its callback returns: Drizzle’s and Prisma’s interactive transactions, SQLAlchemy’s with session.begin():a throw out of the callbacka returned error arm, which the helper reads as success
Spring @Transactionalan unchecked exception; a checked one only when rollbackFor names ita checked exception without rollbackFor, and a returned error value
Go database/sqldefer tx.Rollback() and an early return err; tx.Commit() only after every step succeededa Commit reached after an error was recorded rather than returned
Rust SQLxa Transaction dropped without commit() rolls back, so an early return through ? is safe; Connection::transaction rolls back on ErrOk holding an error value, which commits

In each case an expected outcome the caller branches on is converted to the result type outside the transaction, after it has rolled back or committed.

Branch on type or code

EcosystemBranch onLint
TypeScripterror instanceof DomainError, error.code, result.error._tag; assertExhaustive(x: never) in the default of a switch over the tagreference/lint-rules/ no-message-branch and no-bare-throw-error; on ESLint, @typescript-eslint/only-throw-error (no thrown non-errors) plus a no-restricted-syntax selector on MemberExpression[property.name="message"] inside a CatchClause
Pythonexcept NotFoundError as e:, e.code; match on a Result unionRuff TRY002 (a raised bare Exception), TRY003 (a long message built at the raise site instead of in the exception class); a grep gate on str(e) and e.args[0] comparisons
Goerrors.Is(err, ErrNotFound), errors.As(err, &notFound)errorlint (err == ErrX and err.(*T) instead of errors.Is / As); a grep gate on strings.Contains(err.Error(), ...)
Rustmatch on the error enum; downcast_ref::<E>() at an anyhow boundarythe compiler: an unmatched variant fails the build; clippy wildcard_enum_match_arm where exhaustiveness matters
JVMcatch (NotFoundException e), e.getCode(); an exhaustive switch over a sealed typeError Prone CatchFail; a grep gate on getMessage().contains(

The error boundary

StackThe one boundaryThe shape it writesServer-side failures hide detail
Express / Koathe last (err, req, res, next) middleware; Koa’s app.on("error") plus one try/catch middleware{ code, message, severity, recovery, correlationId, details?, detail? }, with details and detail on a 4xx only; a Content-Type of application/problem+json and the Problem Details fields (type, title, status, detail, instance) are the standard wire form when the shape must be publicthe handler strips details and detail when status >= 500, logs them through an allowlist, and maps an unknown error to the generic code
FastifysetErrorHandler on the root instance; setSchemaErrorFormatter for validationthe samethe same
Elysia.onError() in one plugin registered firstthe samethe same
FastAPI / Starlette@app.exception_handler(DomainError) and one for Exceptiona Pydantic model for the bodythe Exception handler returns the generic code and logs; debug=False in production so Starlette never writes a traceback
Djangoone middleware’s process_exception, or Django REST Framework’s EXCEPTION_HANDLER settingthe sameDEBUG = False; the handler writes the generic code
Go net/httpa handler wrapper func(w, r) error that maps the returned error oncea response struct written by one functionerrors.As to the typed error, else the generic code and status 500; the internal error only to the log
gRPC (any language)one server interceptor that maps the typed error to a status code and detailsgoogle.rpc.Status with ErrorInfo (reason as the code, domain, metadata)an unknown error maps to INTERNAL with no message text
Rust axum / actiximpl IntoResponse for AppError; actix’s ResponseErrorone error enum to one body typethe Internal variant writes the generic code; the source only to tracing
Springone @RestControllerAdvice with @ExceptionHandler methodsProblemDetail (Spring 6) with the code in its propertiesthe Exception handler returns the generic code; server.error.include-stacktrace=never, include-message=never
Command-line toolsone exit-code boundary the entry point runs through (lib/cli.ts in Jig)an exit status per outcome (0 passed, 1 findings, 2 could not check) and one line on standard errorthe boundary prints the message, never the stack, unless a debug flag asks

Whatever the stack, the boundary is the only place that knows the transport: the domain error carries no status code of a particular transport, the boundary maps its code’s metadata to one. The public field set is the same everywhere: the code, the message key, the severity, the recovery hint and the correlation id, plus the 4xx-only details. The test that proves the rule sends an unknown error, carrying a recognizable internal message, a cause and a stack, through the boundary, and asserts that the body holds the public field set with the generic code and that no internal detail is in it: not the stack, the cause, query text, a file path or the internal message.

Detached work and unhandled rejections

EcosystemDetached work through one helperThe process-level backstop
TypeScript (Bun, Node)reference/detached/ runDetached; Biome noFloatingPromises or ESLint @typescript-eslint/no-floating-promises finds the un-awaited promise that should go through it, but both accept a promise started with void, so the helper is the only way only when a second rule rejects void outside the helper’s module: Biome noVoid or ESLint no-void, with that module excluded, or no-floating-promises with ignoreVoid: falseinstallUnhandledRejectionListener from the same file, once per entry point, in the runtime’s default mode (--unhandled-rejections=throw, which Bun follows), where the listener handles the rejection and the process keeps running; under --unhandled-rejections=strict the rejection is raised as an uncaught exception first and the listener does not prevent the exit, so the entry point sets no strict flag in its start command or NODE_OPTIONS
Python asynciotasks kept in a set and given a done callback that reports (task.add_done_callback(report)); a task with no reference is collected mid-flightloop.set_exception_handler(report): the “Task exception was never retrieved” warning is what it replaces
Goa go func() started through one spawn(name, fn) that recovers a panic and reports it with the namenone exists: an unrecovered panic in a goroutine ends the process, which is why every goroutine starts through the helper
Rust tokioJoinSet or a JoinHandle that is awaited; a tokio::spawn whose handle is dropped reports nothinga panic hook (std::panic::set_hook) that logs; the task’s JoinError is read where the handle is awaited
JVMan ExecutorService wrapper that submits through Callable and logs a failed Future; Kotlin CoroutineExceptionHandler on the scopeThread.setDefaultUncaughtExceptionHandler

Telemetry keyed on code and type

SignalKeysNever
Metrics (a counter of errors, a duration histogram)error.code (the registered code), error.type (the class name, as the OpenTelemetry semantic conventions name it), outcome (ok or err for a method returning a result type)error.message, an account or user identifier (unbounded cardinality: the OpenTelemetry metrics SDK merges combinations past its per-instrument limit into one overflow bucket, silently)
Spansspan status ERROR only when the method threw; error.code and error.type as attributes; the err arm’s tag as outcomethe message or the stack as an attribute
Structured logsthe fields code, errorName and correlationId; the diagnostic detail (the message and the cause chain’s messages) through the redacting allowlist, with secrets and identifiers masked, and never as a field a dashboard groups bythe request body; a message or a cause chain that has not passed through redaction

The boundary and the telemetry wrapper read the same fields of the same typed error, so a code renamed in the registry changes both, and a dashboard built on codes outlives any rewording.

The error-code registry

The registry is one declaration per code, in data (templates/error-codes.yaml) or in a code module with the same fields; the generators below read it, and each copy they write carries M2’s freshness triad, with a --check that regenerates through the generator’s own function and diffs the whole text.

EcosystemThe registryThe client’s code unionA message catalog per localeThe public reference
TypeScripta module of new ErrorCode(code, metadata) constants, the class unexported where it can bea generated file holding a string-literal union and a runtime array of the codes, so a switch narrows to never and a new code fails the client’s build until it is handledJSON per locale for i18next, next-intl or react-intl, where the generator keeps authored entries, inserts a visible placeholder entry for a new code and drops a retired one, and --check fails on a difference or a placeholder; typesafe-i18n derives types from the base locale so a key missing elsewhere fails the builda generated Markdown page in the docs site (Docusaurus, Starlight), validated by regenerating through the same function
Pythonan Enum whose members carry the metadata, or the data form read by the generatorsa generated Literal[...] type in the client packagegettext .po per locale; msgfmt --check validates the files, and a test that resolves every code’s key in every locale fails on a gap (gettext returns the key itself when it is missing, so the test asserts inequality)a generated page under Sphinx or MkDocs, with --check
Goa const block of codes and a var table of metadata in one packagea generated file in the client module, go generate with stringer for the string formgolang.org/x/text/message catalogs from gotext update, which reports untranslated messagesa generated Markdown page; CI runs go generate ./... and git diff --exit-code
Rustan enum ErrorCode with a metadata() match and strum for the namesthe crate shared with the client, or a TypeScript union generated with ts-rs or spectaFluent .ftl per locale; i18n-embed-fl’s fl! macro checks at compile time that a message id exists in the fallback languagea generated Markdown page; CI regenerates and git diff --exit-code
JVMan enum ErrorCode with a field per metadata itemgenerated from the specification’s enum with openapi-generator, or the enum shared in a client moduleResourceBundle properties per locale, with a test over ErrorCode.values() for every locale; Spring’s MessageSource with useCodeAsDefaultMessage=false throws on a missing keya generated page from an annotation processor or a test that writes and compares
Railsa model of codes with config/locales/*.yml keyed by codea generated TypeScript union from a Rake taski18n-tasks missing fails CI when a locale lacks a key the base locale hasa generated page from the same Rake task
On the wirethe response schema’s code property is an enum generated from the registry in the OpenAPI document, so a client generated from the specification carries the union; gRPC carries the code in google.rpc.ErrorInfo.reason, with a generated protobuf enum beside it
EcosystemNo code constructed outside the registryOrphans and reverse orphans
TypeScriptvisibility: the registry module exports the codes and not the class; where the class must be exported, reference/error-registry/check-no-inline-codes.ts, a Biome GritQL rule on new ErrorCode($args) with the registry left out of its includes, or ESLint no-restricted-syntax on NewExpression[callee.name="ErrorCode"] turned off for the registry in an overrides entryreference/error-registry/audit-error-codes.ts over the packages and the docs; Knip reports a registry constant nothing imports as an unused export
Pythona module-private constructor (_Code) and import-linter’s forbidden contract against importing it outside the registry package; otherwise a grep gate on ErrorCode( outside the registrythe audit; vulture for a constant nothing reads
Goan unexported constructor (newCode) in the registry package: the compiler enforces it; forbidigo where it must be exportedthe audit: an unreferenced exported variable is not something staticcheck reports across packages
Rusta private constructor in the registry module: ErrorCode keeps a private field, so no other module can build one with a struct literal, its new is private to the module, and the codes are associated constants (ErrorCode::ORDER_NOT_FOUND) declared beside it; the compiler enforces it. pub(crate) is not enough, since every module of the crate can call itthe audit; the dead_code lint reports only a constant that is not pub
JVMa package-private constructor; ArchUnit’s noClasses().that().resideOutsideOfPackage("..errors.registry..").should().callConstructor(ErrorCode.class, ...)the audit
Documents, any stackthe audit’s --docs over the hand-written pages; i18n-tasks unused (Rails) for catalog keys nothing resolves

Whatever the stack, the set of packages the gate scans is derived from the dependency graph (every package that depends on the error module: pnpm --filter "...^<errors package>" exec pwd, cargo tree -i <crate>, go list -deps), not listed by hand, so a new dependent is covered the day it appears. The allowlist is kept at zero; the baseline of accepted orphans names each code with its reason and only shrinks.

Migration discipline

A migration that has merged is never edited, renamed or deleted; the ledger and the files match one to one in strictly increasing order; a migration changes structure only. The merge-time gate is one script for every tool (reference/migration-immutability/): it reads git, not the database. The apply-time hash check and the ledger are each tool’s own, and differ in what they refuse.

ToolThe ledger and its orderThe hash at apply, and what refuses driftWhat the repository adds
Flywaythe versioned files’ own numbering; validate (run by migrate by default, validateOnMigrate) fails on a resolved migration older than the latest applied that never ran, so a behind migration is refused, not skipped; outOfOrder=true is the setting that lets it run, off by defaultflyway_schema_history records a checksum per versioned migration; validate fails on a changed one; repair rewrites the recorded checksums and is the escape hatch to keep out of CIthe merge-time gate, so the edit fails in review rather than at the deploy
Liquibasethe changelog file is the ledger and runs changesets in its order, so a changeset file no include names never runs: a check that every file under the directory is includedDATABASECHANGELOG records a digest per changeset; update fails on a changed one (checksum validation); runOnChange, validCheckSum and clearCheckSums are the escape hatchesthe merge-time gate; the inclusion check
Rails (Active Record)schema_migrations records the versions applied; every pending version runs in version order, older ones included, so nothing is skipped; db:migrate:status prints NO FILE for a recorded version with no filenone: the table records versions onlythe merge-time gate is the only guard against an edit; a hash check in a Rake task that records the digests it applied; strong_migrations stops an unsafe structure change and a raw execute without safety_assured; data changes go to data_migrate’s own directory
Alembicthe revision chain in the files (down_revision) is the ledger; alembic heads returning more than one revision, which upgrade head refuses, is the integrity check; alembic_version records the current head onlynonethe merge-time gate; a hash check in the migration command’s wrapper; a data change (op.bulk_insert, op.execute with a data statement) found by walking the Python syntax tree (ast) and parsing the SQL it carries
Prisma Migratethe migration directories’ names, applied in name order; migrate status lists them against _prisma_migrations_prisma_migrations records a checksum per migration; migrate dev refuses an applied migration that changed; migrate deploy applies pending migrations and compares no checksum; migrate resolve is the escape hatchthe merge-time gate is the production guard, since deploy checks nothing
Drizzlemeta/_journal.json: an entry per migration with idx, tag, when and breakpoints; the migrator applies entries whose when is greater than the last applied created_at, so an entry with an earlier when is skipped silently; a ledger check holds idx dense, when strictly increasing, tag and file one to one, and every field explicit on every entry__drizzle_migrations records a hash per applied entry and the migrator compares noneboth checks are the repository’s: the ledger check above, and a drift check in the migration wrapper that pairs the recorded hashes with the journal’s entries by position, hashes each file the same way, and refuses to run on a difference or a missing file; the migrator applies every pending entry in one transaction, so a statement PostgreSQL will not run inside one (CREATE INDEX CONCURRENTLY) or whose effect waits for the commit (ALTER TYPE … ADD VALUE) needs its own path outside the migrator
golang-migratethe files’ version numbers; up applies the versions above the recorded one, so a version behind it never runs: a check that the files’ versions are strictly increasing and that every file above the recorded version is pendingschema_migrations records the current version and a dirty flag, no checksumthe merge-time gate; a hash check in the wrapper; goose, the near relative, refuses a missing migration before the current version by default (-allow-missing is the setting that lets it through) and records no checksum either

A runner with no hash check gets one in the repository’s own wrapper: on first apply it records a digest of each file in a table beside the tool’s own; on every run it recomputes the digests of the applied files and refuses to continue on a difference or a missing file, naming the file, the recorded digest and the file’s. The recovery is always the same: restore the file, or reset an environment that never applied it, or add a new migration.

DatabaseThe parser for the structure-only checkWhat to walk
PostgreSQLthe libpg_query bindings: pg_query (Ruby), pglast (Python), pg_query_go (Go), @pgsql/parser (TypeScript)every InsertStmt, UpdateStmt, DeleteStmt and MergeStmt anywhere in the tree, a WITH query’s included; the body of a DO block and of a CREATE FUNCTION through the procedural-language parser (pglast.parse_plpgsql); an EXECUTE of a constant string re-parsed, any other EXECUTE fails the file
MySQL, MariaDB, SQLitesqlglot (Python) with the dialect namedexp.Insert, exp.Update, exp.Delete found by find_all over each parsed statement
SQL ServerScriptDom (TSql160Parser)a visitor over InsertStatement, UpdateStatement, DeleteStatement, MergeStatement
Migrations written as code (Alembic, Rails, Knex)the language’s own syntax tree for the data operations (op.bulk_insert, op.execute, execute, update_all, insert), then the database’s parser for the SQL strings they carrythe same statement kinds

The allowlist for a data change that must ride in a migration is a file outside the migrations, one entry per statement by identity (the file and the statement with its whitespace normalized), each under the reviewer’s reason; an entry whose statement is no longer there fails the check (M1’s stale-exceptions rule). An in-file marker cannot do this job: the file that needs it has already applied, and gaining a marker is an edit.

The review marker is M1’s commit-msg marker with REVIEW_PATHS_RE set to the migrations directory and REVIEW_MARKER to the migration-review tag, re-checked in CI over the pull request’s commits.

Published interface surface

An operation is internal unless a named external consumer justifies publishing it; every request input declares a bound; an operation’s declared failure responses name every status its code can produce. The two reference gates read an OpenAPI document (reference/interface-surface/); for another contract form, the same checks are written over its own document.

Contract formThe mark at the sourceTwo documents from one sourceThe gate over the published document
OpenAPI (REST)a tag suffix on the operation (Orders (Internal)), an x-internal: true extension, or a path prefix (/internal/), set where the route is declared so the generator reads it from the route schemathe generator runs twice with the filter inverted: the published document without the marked operations, the internal one with only them; over a bundled document, redocly bundle --remove-x-internal or an openapi-filter pass apply the same filtercheck-no-internal-in-published.ts with the mark as its option; the server’s own filter on what it serves at its contract endpoint is tested where the server is
gRPC / protobufa package per audience (<org>.orders.v1 published, <org>.orders.internal internal), or the google.api.visibility method option (restriction: "INTERNAL"), which protoc-gen-openapi and the generated-client generators honourone module, a buf generate template per audience, each built from its package (buf build --path)a check over the published descriptor set (buf build -o) that no internal package and no INTERNAL-restricted method is in it; buf breaking --against on the published package holds its shape
GraphQLa schema directive on the field or type: Apollo Federation’s @inaccessible, which composition drops from the supergraph’s API schema, or a @tag per audience read by a schema contract; a plain @internal directive the build filtersone subgraph schema; the published schema is what composition or the contract filter leavesgraphql-inspector validate with a rule, or a short script over the published schema’s syntax tree, that no field or type carrying the mark remains; graphql-inspector diff against the base holds the shape
Typed RPC (tRPC and kin)a router per audience (publicRouter, internalRouter), mounted at different paths; the client types are generated per routerthe type generation per routera type-level test that no internal procedure is assignable to the public router’s exported type

The consumer question travels with the change: a pull-request template field, or a line in the review checklist, asks who the external consumer of a newly published operation is, what they get, and why not another way. Jig’s review skill asks it in its contract tier.

Schema toolThe boundNamed schemas with their boundsThe count under the ratchet
OpenAPI / JSON SchemamaxLength, pattern, format on a string; maximum, exclusiveMaximum on a number; maxItems on an array; additionalProperties: false or a schema on an open object; enum, const on anythingcomponents/schemas entries (ShortText, EntityName, SearchQuery) referenced by $refcount-unbounded-inputs.ts --base over the document
TypeBox (TypeScript)t.String({ maxLength }), t.String({ pattern }), t.Number({ maximum }), t.Array(..., { maxItems }); the OpenAPI document generated from the route schemas carries themone module of named schemas (const ShortText = t.String({ maxLength: 500 })), a refinement by spread ({ ...ShortText, minLength: 1 }) keeps the boundthe document count; a numeric query parameter declared as a string is a bound in name only, so it is t.Numeric({ maximum })
Zod.max(), .regex(), .email(), .url(), .array().max(), .number().max(); zod-to-openapi and zod-openapi carry them into the documentnamed schemas exported from one modulethe document count, or a lint rule on z.string() and z.number() with no refinement in a request schema
Pydantic (Python)Field(max_length=, pattern=, le=), conlist(max_length=), constr, conint; FastAPI’s generated document carries themAnnotated[str, Field(max_length=255)] aliases in one modulethe document count
Protobufprotovalidate (buf.validate) field options: (buf.validate.field).string.max_len, .repeated.max_items, .int32.lte, .string.patterna message per kind of value, or a shared custom optiona buf lint plugin, or a script over the descriptor set, counting request fields with no constraint
GraphQLgraphql-constraint-directive (@constraint(maxLength: 255, pattern: ...)) on input fields and arguments; a custom scalar per kind of value (ShortText)the custom scalarsa script over the schema’s syntax tree counting String, Int and list inputs with no constraint
Go (validator)struct tags on the request types (validate:"max=255", validate:"dive,max=100"), max= on slicesa named type per kind of value with its own Validatea go vet analyzer, or a grep gate over the request structs, for a string or slice field with no max tag
Contract formWhere the failure statuses are declaredWhat the list holds
OpenAPIthe operation’s responses mapthe boundary’s generic server-side status; the validation status; the authentication and authorization refusals where those layers run; the transport status of each domain error the handler throws, which the registry holds per code, so a generator can derive the list from the codes the route declares; a 2xx with a schema, never an untyped success
gRPCthe method’s comment (// Errors: NOT_FOUND, FAILED_PRECONDITION) and the google.rpc.Status details, with ErrorInfo.reason carrying the registry’s codethe status codes the handler returns and the boundary’s INTERNAL; the generated client’s documentation reads the comment
GraphQLan enum of errors[].extensions.code in the schema, and each field’s description naming the codes it raisesthe registry’s codes, so the client’s exhaustive switch over the enum narrows to never

Source: modules/M15-contracts-errors/mappings.md

4 · Statuswhat is built, and what is left out on purpose

What the module provides

PieceWhat it is
templates/ERROR-HANDLING.mdA copyable error contract: the channels, the rules, the boundary’s shape, the telemetry keys and the checks that hold them
reference/lint-rules/GritQL rules for Biome with fixtures and a self-test: a default-returning catch, discarded child error output, an unchecked parse cast, a thrown native error, a branch on message text
reference/detached/The detached-work helper and the unhandled-rejection listener, with a self-test
templates/error-codes.yamlA neutral error-code registry as data: the code format, the copies generated from it with their commands, and each code’s metadata
reference/error-registry/Two gates with fixtures and a self-test: no code constructed outside the registry, with an allowlist by identity; and the audit for orphans, against a baseline by identity, and reverse orphans in hand-written documents
templates/MIGRATIONS.mdA copyable migration contract to keep beside the migrations: the file format, the ledger entry, the rules (immutable once merged, structure only, ledger integrity, mandatory review) and the checks that hold them
reference/migration-immutability/The merge-time gate against an edit, rename or deletion of a merged migration, allowing a restoration to a prior state, with fixtures and a self-test over scratch repositories
templates/INTERFACE-SURFACE.mdA copyable interface policy to keep beside the contract: internal by default with the consumer question, the mark and the two documents, the named schemas and their bounds, the failure statuses, the checks
reference/interface-surface/Two gates over the contract document with fixtures and a self-test: no internal operation in the published document, and the count of unbounded request inputs held against the merge base or a ceiling
mappings.mdPer language: cause-keeping, result types, typed errors and defect primitives, the boundary per framework, detached work, telemetry keys; per migration tool: the ledger, the hash at apply, the parser per database; per contract technology: the visibility mark, the two documents, the bounds, the status list
maturity criteriaThe criteria the audit skill scores

Jig runs these rules on its own code under the ratchet (biome.json and tools/quality/ratchet.jsonc); its scripts’ exit-code boundary is lib/cli.ts.

Left out by design

  • A result type as reference code. The type is five lines in any language and the helpers around it are a taste; mappings.md names the hand-rolled shape and the libraries per ecosystem instead.
  • Retry and resilience. A domain error’s recovery hint says what a caller may do; how a service retries is its own policy, not this module’s.
  • The wording of messages and their translation. The module fixes that the message is a key on the wire, not what the key says.
  • A ledger check and a structure-only scanner as reference code. The ledger’s format is each tool’s (a journal file, a changelog, a revision chain) and the structure check needs the database’s own grammar; mappings.md names the check per tool and the parser per database.
  • Row-level security, role grants, vendor-bound objects and per-environment schema names in migrations. Each is a policy of one database and one deployment, not a contract a caller depends on.
  • A library’s export surface. The interface rules are for an interface a system serves to callers over a transport; what a package exports is its own versioning’s concern.

Future

  • A checker for declared failure statuses: a comparison of each operation’s declared failure responses with the statuses its handler can produce (the boundary’s, the validator’s, the registry’s for each code it throws). The rule is doctrine and a review lens until a checker has settled on how it reads the handler.
  • A rule against a second error family: class X extends Error outside the typed family’s own module, so a look-alike cannot grow beside it.