Contract-driven development for TypeScript

One declaration.
Every artifact.

Decorators adorn a function with its contract — what its inputs must satisfy, what has to hold before and after. Runtime enforcement, JSON Schema, documentation, tests and telemetry are all derived from that one declaration instead of maintained by hand, so they can't drift apart. The contract that guards the code also tests it: generated inputs, counterexamples and breaking-change checks come from the same declaration. An LLM tool schema is one of those derived artifacts, not the point.

0.5, pre-1.0, MIT. Strict by default: objects are exact, every parameter is typed, and a call past the signature is refused, constructors included. A typed lint catches contract mistakes in the editor. The only runtime dependency is tslib. It's backed by a large test suite, and the public surface is pinned by a test so it can't drift unnoticed.

weather.ts
@Contract()
class WeatherService {
    getWeather(
        @Name('location') @Describe('the city to look up') @NotEmpty() location: string,
        @Name('unit') @OneOf(['celsius', 'fahrenheit']) unit: string,
        @Name('days') @GreaterThanEqual(1) @LessThanEqual(7) days: number, // ◆
    ): string { /* the body only ever sees valid arguments */ }
}
derived from the same descriptors, not written twice
new WeatherService().getWeather('Lisbon', 'celsius', 99)
// throws before the body runs: a caller asked for 99 days
Value Error: WeatherService.getWeather(location, unit, days)
  parameter 'days' expected a number less than or equal to 7
  but received [REDACTED] instead

// values are redacted by default, with no annotation needed
Change one line@LessThanEqual(14) moves the schema a consumer reads and the check its input faces together.
Tested by its own contractThe fuzzer reads the same descriptors the validator runs, and contractDiff tells CI when a change breaks callers.
Total predicatesnull, NaN or the wrong type is reported as a contract violation, never a bare TypeError.
Redacted by defaultEvery path adorn emits through prints [REDACTED] unless you opt in.

Why adorn

Intent belongs with the declaration, not scattered around it.

A function's intent is usually spread across a check buried in the body, a schema in another file, a sentence in the docs and a hand-written test. Each one is maintained by hand, so each one drifts.

01 · DRIFT

Copies disagree

Raise a limit in the validator and forget the schema, and the schema promises one thing while the code enforces another. A drifted doc misleads a human who can compensate; a drifted tool schema silently corrupts every call.

02 · DATA

Constraints are data, not closures

@GreaterThanEqual(1) records an identity plus JSON-serializable params, and the predicate is derived from them. A schema keyword, a docs row, a fuzzer generator and the runtime check are all read from that one record.

03 · BOUNDARY

Enforced at every call

@Contract() wraps each contracted method, so a call with invalid arguments is rejected before the body runs. adorn validates and never coerces: a malformed argument is a violation, not something to quietly patch up.

This is contract-driven development

Declare what inputs are valid. Declare what must hold before the call, and what the function promises after. Then implement the body. The contract isn't documentation about the implementation — it's part of the program: enforced at the boundary, and read by every artifact that needs to know what the function expects.

Tests from the contract

The contract that guards the code also tests it.

You've already written down what the inputs must satisfy and what the result must promise. adorn/test turns that same declaration into property-based tests, so the test can't drift from the check it exercises. When a generated input makes a body break its own promise, the run finds a counterexample instead of a passing suite.

billing.ts
import { contract, Contracts, RelationContracts as R } from 'adorn';
const { Arg, Result } = R;

// The first 500 calls in a month are free.
export const monthlyBill = contract(
    {
        params: [{
            descriptor: [Contracts.number.integer(), Contracts.number.between(0, 100_000)],
        }],
        returns: Contracts.number.greaterThanEqual(0),
        ensures: [R.Implies(R.LessThanEqual(Arg(0), 500), R.Equal(Result(), 0))],
    },
    function monthlyBill(calls: number) {
        return calls < 500 ? 0 : 5 + (calls - 500) * 0.01; // ◆ off by one: 500 should be free
    },
);
billing.test.ts
import { setValueDisclosure } from 'adorn';
import { fuzzFunction, formatFuzzReport } from 'adorn/test';
import { monthlyBill } from './billing';

setValueDisclosure('all'); // local run: show the counterexample, redacted by default
const report = fuzzFunction(monthlyBill, { seed: 42 });
console.log(formatFuzzReport(report));
if (!report.passed) throw new Error('monthlyBill broke its contract'); // ◆ fail the run
fuzzFunction(monthlyBill, { seed: 42 }), the body above
adorn fuzzing report (contract oracle — Phase B)
================================================

Fuzzed 1 method(s); declined 0; findings 1.

- monthlyBill(): FOUND (postcondition-violation) — postcondition "if args[0] <= 500 then result == 0" did not hold; returned 5
    broke postcondition: if args[0] <= 500 then result == 0
    counterexample: [500]
    reproduce: seed 42, path 1
    coverage:
      [0]: parametric (sound by construction)  {integer ∧ between}
    boundary candidates from relational clauses (mixed in, still filtered): [0] 3 value(s)
    implication premises (how often each premise held, NOT correctness):
      [ensures] "args[0] <= 500" held on 1 of 2  (in: if args[0] <= 500 then result == 0)

Warnings:
  ! Fuzzing runs the REAL method with generated inputs, many times. If it sends email, charges a card, or writes to a database, those effects are real and irreversible (foundation §7.2).
  ! A clean run means "no generated input crashed it, broke a field invariant, or broke a checked postcondition" — NOT "correct" and NOT "proved". Property-based testing samples; it does not verify (foundation §7.1).
BOUNDARIES

Edges from the rule itself

A random integer up to 100 000 almost never lands on exactly 500. A clause that compares an argument with a literal feeds that literal and its neighbours into the generator (<= 500 gives 499, 500 and 501). The only failing input above is exactly 500, and that is why the run found it.

SOUND

Generate soundly, or decline

Every generated input satisfies the parameter's descriptors and the precondition, boundary candidates included. Named formats, literal text and timestamps are built from their own definitions. A descriptor the fuzzer can't generate for is declined and named in the report, never guessed at.

HONEST

Clean is not proved

A clean report means no counterexample was found, and it says so every time. Its coverage names how each position was generated, so you can see how far to trust it.

PREMISES

Implications that never fired

An Implies(p, q) holds whenever p is false, so a run that never makes p true never checks q. The report counts how often each premise held, and warns when one never did.

DETERMINISM

Run twice, compare

Opt in with determinism: true: each passing case runs again on a deep clone of its arguments, and a different result is a nondeterministic-result finding, kept apart from contract findings.

STATEFUL

Sequences, not just calls

fuzzSequence drives generated call sequences against one evolving object, built from generated arguments to its own constructor contract, skips calls its guards don't enable, and re-checks every invariant after each step. See it below.

Breaking changes, caught in CI

Diff the contract you shipped against the one you're about to ship.

contractSnapshot turns a contract into plain JSON you can keep with a release. contractDiff compares it with the current code, position by position: accepting less or promising less is breaking, and every breaking answer carries a witness call that was run through the real checks of both versions. Renaming a declared parameter is breaking too, for a caller that sends arguments by name, as a model calling a tool does. What it can't prove, it reports as unknown with the reason.

snapshot.ts
import { writeFileSync } from 'node:fs';
import { contractSnapshot } from 'adorn/introspection';
import { monthlyBill } from './billing';

// Run once per release: keep the shipped contract with the release, as JSON.
writeFileSync('contracts/monthlyBill.json', JSON.stringify(contractSnapshot(monthlyBill), null, 2));
contracts.test.ts
import { readFileSync } from 'node:fs';
import { contractDiff } from 'adorn/introspection';
import { monthlyBill } from './billing';

// Every CI run: diff the contract stored at the last release against the current code.
// The output shown is after a change to billing.ts: calls capped at 50 000, and
// returns: Contracts.number.finite(), so a credit can take the bill below 0.
const shipped = JSON.parse(readFileSync('contracts/monthlyBill.json', 'utf8'));
const diff = contractDiff(shipped, monthlyBill);
console.log(JSON.stringify(diff, null, 2));
if (diff.verdict === 'breaking') throw new Error('monthlyBill: breaking contract change'); // ◆ fail CI
Reading the diff

params[0] is a narrowed input: a caller of the shipped version could send 100000, and the new version refuses it. returns is a widened output: for 50000 the new contract allows a result of -1, which the shipped version promised never to return. ensures[0], the free tier, is unchanged, and the diff proves it compatible.

contracts.test.ts output, after the change
{
  "verdict": "breaking",
  "positions": [
    {
      "position": "params[0]",
      "band": "params",
      "index": 0,
      "verdict": "breaking",
      "direction": "narrowed-input",
      "witness": {
        "args": [
          100000
        ]
      }
    },
    {
      "position": "returns",
      "band": "returns",
      "verdict": "breaking",
      "direction": "widened-output",
      "witness": {
        "result": -1,
        "args": [
          50000
        ]
      }
    },
    {
      "position": "ensures[0]",
      "band": "ensures",
      "index": 0,
      "verdict": "compatible"
    }
  ]
}
Three paths, one set of answers

adorn enforces a contract three ways: the decorator weave, contract(), and contract.checked, which returns each call's verdict as data. Its band semantics (order, blame, value-free facts, old, missing paths) live in language-neutral verdict vectors, and every case runs through all three paths, which must agree with the file and with each other. See test/vectors/verdict.json.

Contract mistakes, caught at build time

The lint reads the contract before it runs.

Some contract mistakes only show at runtime, or not at all: a parameter with no type, a clause above @Validate() that is never enforced, constraints on a class nothing installs. adorn/eslint is a typed typescript-eslint plugin that reports them in the editor and in CI, with the same ADN id the runtime's warning for that problem carries.

eslint.config.mjs
import tseslint from 'typescript-eslint';
import adorn from 'adorn/eslint';

export default tseslint.config(
    ...tseslint.configs.recommended,
    { languageOptions: { parserOptions: { projectService: true } } },
    adorn.configs.recommended, // ◆ or strict, or ...adorn.boundary(['src/tools/**'])
);
the hero's method with @OneOf removed from unit
[ADN0001] Parameter 'unit' of contracted method 'getWeather' has no type-bearing decorator, so it is past the signature and a call passing it is refused (DEC-119). Type it (a constraint, or @Defined() for any value; with @Optional() if it may be absent).

An opt-out of a strict default says why, in an // adorn-allow: <reason> comment the lint checks and the contract never stores. Every rule, with examples.

How it works

Record, install, project.

A TypeScript parameter decorator runs once, when the class is defined, and never sees an argument value. adorn bridges that gap by splitting the work: decorators record descriptors, the class decorator installs enforcement, and projections read the same registry.

  1. DeclareParameter, field and method decorators, or plain descriptors with no decorator at all.
  2. RecordEach constraint is stored as a reified descriptor against (prototype, method, index).
  3. Install@Contract() runs after every member decorator and wraps each method with the recorded checks.
  4. ProjectDocs, schemas, tool schemas, telemetry and fuzzers all read the same registry.
core

Runtime validation

Runs on every call. A guard contract is kept in production; an assert is an internal self-check that's stripped there.

core

LLM tool schema

toolSchemaForMethod produces the parameters object a JSON-Schema-style function-calling API wants, subject to the provider's dialect, with OpenAI strict mode via {provider: 'openai', strict: true}.

core

JSON Schema 2020-12

schemaForClass describes what enforcement will accept. When unsure it falls back to the weaker true statement, because an over-claiming schema is worse than none.

core

Documentation

Markdown generated from the same statement that's enforced: documentClass → renderMarkdown, or adorn docs from the CLI.

core

Observability

A neutral, zero-dependency sink receives value-free violation and completion facts. adorn/otel maps them onto OpenTelemetry.

adorn/test

Property-based tests

fast-check generators derived from the contract. Generation is sound: it produces only inputs the contract accepts, or declines and says so. See a run.

Playground · real adorn, in your browser

Edit the declaration. Watch every artifact move.

A StackBlitz sandbox installs adorn from npm and runs it in a real Node toolchain — the decorator syntax above, not a mock-up. Change a constraint and re-run: the schema a consumer reads and the runtime check its input must pass move together.

One descriptor, many consumers

Write the constraint once. Every consumer reads the same record.

A constraint is a reified descriptor — an identity plus JSON-serializable params, with the predicate derived from them. Here is days from the method above, traced mechanically into each thing adorn produces. Nothing is written twice.

The validator is the real guard

Run locally with no network: a bad nested date-time is rejected at ["when"], and so is a missing required field. Nullable(NotEmpty()) accepts null and still rejects "".

The tool schema, checked against a real provider

Because a machine produces malformed input the instant a schema is wrong, the tool-schema projection was round-tripped end to end through OpenAI's live function-calling API (gpt-4o-mini, temperature 0): schema accepted, tool call returned, its arguments validated against the same declaration — nested objects, nullable-optional fields and strict mode included. Evidence: docs/q31-capstone-results.md.

Beyond the decorator

Same descriptors, no decoration point needed.

Decorators are the ergonomic form, not the foundation. A raw unknown off the wire, a tool whose enum is known only at session start, or a codebase with no classes can use the same descriptors directly and get the same enforcement and projections.

BOUNDARY

Verify.check

Non-throwing. It narrows unknown to the constraint's output type and reports the failing path.

const r = Verify.check(member, 'body', json);
if (!r.ok) return res.status(400).json(r);
r.value.roles; // typed
PER-SESSION

toolSchemaFrom

A runtime enum that no decorator could express. One const feeds both the schema and the validator.

const params = {
  slotId: EnumContracts.OneOf(openSlots),
};
toolSchemaFrom({ name: 'book', params });
ZERO CLASSES

contract(spec, fn)

The functional twin of @Contract, @Requires, @Ensures and @Returns. params is its signature, one typed slot per parameter. It's async-aware and runs the same oracles.

const score = contract(
  { params: [NumberContracts.Finite()],
    returns: NumberContracts.Between(0, 100) },
  async (seed: number) => seed,
);

Design by contract, for stateful objects

Preconditions that read state, and a tester that respects them.

@Requires relates a call's arguments. @EnabledWhen also receives the instance, so "withdraw is enabled only while the balance covers it" is a declared contract instead of an if hidden in the body. fuzzSequence then drives generated call sequences against one evolving instance. It skips calls that aren't enabled yet and checks that invariants survive every transition.

wallet.ts
@Contract()
class Wallet {
    @Enforce.greaterThanEqual(0) balance = 0;

    deposit(@GreaterThan(0) amount: number) {
        this.balance += amount;
    }

    @EnabledWhen((self: Wallet, amount: number) =>
        amount <= self.balance, 'balance covers it')      // ◆
    @Returns(NumberContracts.GreaterThanEqual(0))
    withdraw(@GreaterThan(0) amount: number) {
        this.balance -= amount;
        return this.balance;
    }
}
wallet.test.ts
import { fuzzSequence, formatSequenceReport } from 'adorn/test';

// No subject needed: the start state comes from Wallet's own constructor.
const report = fuzzSequence(Wallet, {});
console.log(formatSequenceReport(report));
What a clean run means

No generated sequence broke an invariant or a postcondition, which isn't the same as "correct". The tester samples rather than proves, and its report says so. A guard that throws instead of returning false is reported as a defect.

Construction is part of the contract

A constructor takes the same parameter decorators as a method, and @Requires / @Ensures on the class. At the end of construction, every required field contract must hold: a contracted class whose constructor leaves a required field unset fails with an Invariant Error naming the field. A field a plain subclass sets after super() is accepted, and its value is still checked on assignment. The fuzzers build their receivers from that contract, and report a constructor that crashes or breaks an invariant. Constructor contracts.

Honest project status

What works, what's rough, what's next.

adorn is a focused, deliberately narrow pre-1.0 library. This page aims to make its limits as easy to find as its features.

  • shipped
    Constraint vocabularyNumeric, string (lengths in code points, literal text, named formats), @OneOf/@Const, @ArrayOf, @Dictionary, @Shape, Fields, @Nullable, dates, timestamps and durations (TimeContracts), plus defineConstraint for your own. @Defined() / Contracts.defined() types a value adorn can't type further, and Contracts.func() a function.
  • shipped
    Strict by defaultFields and @Shape are exact: an undeclared key is refused at its path, and the schema emits additionalProperties: false. {extra: 'allow'} opens one object. Every parameter of a contracted method is typed, and a call past the typed signature is refused (extraArgs: 'allow' opts out).
  • shipped
    Constructor contractsConstructor parameters take the same decorators as a method's, with @Requires / @Ensures on the class or the construction spec as data. The class actually constructed must establish every required field contract by the end of construction, under useDefineForClassFields too; a field a plain subclass sets after super() is accepted and still checked on assignment. The constructor appears in the snapshot, the tool schema, the JSON Schema and the docs.
  • shipped
    Declared parameter names@Name, or a slot's name, keys the tool schema, the snapshot and the OpenTelemetry attribute, and survives minification. A name read from the source only labels. contractDiff reports a rename as breaking for named callers.
  • shipped
    InheritanceField and method-parameter contracts are inherited. A subclass can strengthen a contract but never weaken it.
  • shipped
    Pre- and postconditions@Requires, @EnabledWhen, @Ensures (with old pre-state capture), and the reified, projectable @Returns. A @Requires or @Ensures clause can be a relation written as data (RelationContracts, TimeContracts), with a normal form to compare reworded clauses.
  • shipped
    Refusals as datacontract.checked returns each call's verdict instead of throwing; rejectedBy names the inner rule that refused, and numericBoundOf reads a bound refusal.
  • shipped
    Five in-core projectionsDocs, JSON Schema, LLM tool schema (for a method, a constructor or a contract() function, including OpenAI strict mode), observability, and privacy review.
  • shipped
    Safe-by-default redaction@Sensitive / @Telemetry, plus a build-time sensitive-flow detector (adorn check).
  • shipped
    Tests from the contractfuzzMethod, fuzzFunction, fuzzClass and the stateful fuzzSequence, with boundary candidates from a clause's literals, implication premise counts and an opt-in determinism check. Named formats, literal text and time values generate, and receivers are built from the constructor contract.
  • shipped
    Contract diffcontractDiff and contractSnapshot answer whether a change is breaking, position by position, with a checked witness for every breaking answer. fragmentImplies compares two descriptors.
  • shipped
    Verdict vectorsBand and relation semantics as language-neutral data, run through the decorator weave, contract() and contract.checked, which must agree.
  • shipped
    Build-time contract lintadorn/eslint: typed rules that move runtime refusals and unenforced contracts to the editor, with recommended, strict and boundary(globs) presets, adorn-allow reasons for opt-outs, and ADN ids shared with the runtime's diagnostic codes. The rules.
  • shipped
    Add-ons as subpath exportsadorn/test, adorn/otel and adorn/eslint, each behind optional peers.
  • rough
    0.5 is a breaking upgradeA tool schema needs @Name on every parameter, OpenTelemetry attributes key on declared names, @Telemetry takes no name, and @Contract() may return a validating subclass that refuses a construction leaving a required field unset. Each breaking entry in the changelog carries its migration line.
  • rough
    Names are declared by handA name read from the source still labels messages and docs, and a minifier renames it. Anything that keys on a name needs @Name, written beside the parameter it names.
  • rough
    Closures can't be projectedClosures in @Requires, @Ensures and @EnabledWhen are enforced but invisible to docs and schema. A relation clause shows in docs and round-trips through JSON, though not JSON Schema.
  • rough
    Field contracts without @Contract()Under useDefineForClassFields, a field declaration shadows adorn's accessor, and only the construction wrapper @Contract() adds can restore it. A class with field contracts and no @Contract() is reported (ADN0509), not fixed.
  • rough
    Legacy decorators onlyThe decorator path needs experimentalDecorators (legacy TypeScript decorators, not the TC39 standard). No runtime metadata required; the descriptor-first path needs no flags.
  • next
    TC39 standard decorators adapteradorn/standard, recording into the same core model, so the paradigm survives the language's decorator transition.
  • next
    Receiver pre-state and cross-field invariantsPostconditions that compare against the receiver's pre-call state, and an invariant relating several fields, checked at construction and after every public method. Argument pre-state already ships (capture). Both wait on evidence from real use.
  • next
    More of the lintA descriptor checked against the parameter's TypeScript type, unsatisfiable stacks and self-refuting defaults reported at build time, and adorn check running the rules without ESLint.
  • next
    Add-on ecosystemResilience, rate-limit, idempotency, cache and policy decorators, deliberately kept out of core.

Reach for adorn when

  • you validate untrusted input at an HTTP or queue boundary
  • you want docs and privacy reviews that can't go stale
  • you want property-based tests derived from contracts you already wrote
  • you want CI to tell you when a contract change breaks callers
  • you want contract mistakes reported in the editor, before the code runs
  • you expose methods as LLM tools and need the schema and validation to agree

Don't assume yet

  • coercion or defaults injection, since adorn rejects and never transforms
  • per-request policy: configuration is process-level and set once at startup
  • proofs, because the fuzzer samples rather than proves
  • a check that a descriptor matches the TypeScript type: the lint compares optionality and defaults, not types

Write the contract once.

The validator, the docs, the tests and the tool schema all follow from it.