Architecture

The decorator is the adapter.
The descriptor is the foundation.

Every artifact adorn produces is read from one registry of reified contract descriptors. This page covers how they're recorded, how enforcement is installed, and the rules every projection follows, so that "can't drift" holds by construction rather than by discipline.

Design rules

These rules constrain every implementation choice. Most of the decision log is these rules being applied to a specific case.

One descriptor, many readers

Enforcement, docs, schemas, telemetry and fuzzers read the same recorded data. No projection is allowed its own copy of a constraint.

Degrade toward the weaker truth

When a projection can't express something exactly, it says less, never more. An over-claiming schema is worse than none.

Validate, never coerce

adorn rejects an invalid value. It never silently converts, defaults or transforms it, so a malformed argument is always a violation.

Safe by default

Every path adorn emits through redacts values without reading any annotation. Disclosure is opt-in, and @Sensitive vetoes it.

Frozen reads, private writes

The registry's read surface (getContracts, getEffective…) is semver-frozen public API. Its writers are deliberately not exported, because they would bypass the adapter that owns ordering and installation.

The core trick

A legacy TypeScript parameter decorator runs once, at class-definition time, and receives only (target, propertyKey, parameterIndex). It never sees an argument. adorn bridges that gap in two phases.

@Contract() is required

Parameter constraints do nothing on their own. A class that declares them without @Contract() isn't enforced and is invisible to every projection. Because that failure is silent, adorn emits a development-mode warning naming the class and methods. @Validate() is the per-method alternative, but class-level @Contract() installs outermost, so guard-before-flow holds by construction.

Constraints evaluate in declaration order: parameters left to right, stacked decorators top to bottom. When several arguments are invalid, the first one in the signature is the one reported.

Descriptors as data

The load-bearing move is that a constraint isn't an opaque closure that throws. It's a reified descriptor: an identity plus JSON-serializable params, with the predicate derived from those params. @GreaterThanEqual(1) is a thin @-syntax adapter over NumberContracts.GreaterThanEqual(1).

a custom constraint is first-class
import { defineConstraint, Verify, type JsonObject } from 'adorn';
import { toolSchemaFrom } from 'adorn/schema';

const even = defineConstraint<JsonObject, number>({
    kind: 'number',
    constraint: 'custom.even.v1',              // unique identity: the rehydration key
    derive: () => (v: unknown) =>              // the predicate is DERIVED from params
        typeof v === 'number' && Number.isInteger(v) && v % 2 === 0,
    describe: () => 'an even integer',
    schema: () => ({ type: 'integer', multipleOf: 2 }),
});

Verify.check(even({}), 'seats', 3);              // { ok: false, … 'an even integer' }
toolSchemaFrom({ params: { seats: even({}) } }); // seats: { type: 'integer', multipleOf: 2 }

Because the descriptor is data, the same object can be turned into a schema keyword, a docs row, a fast-check generator and the runtime predicate. It also round-trips through JSON, which is what lets compositional constraints such as ArrayOf, Dictionary, Shape and Nullable nest.

Total predicates

Every built-in predicate is total: a null, NaN or wrong-type argument reports a contract violation, never a bare TypeError. That matters twice over. A fuzzer feeds those values first, and a schema claims a type on the strength of it. It's also why required can be derived soundly: a missing argument already fails at runtime.

Bands & blame

A contracted call passes through ordered bands. Each band names who is at fault when it fails, and whether it can be projected.

BandReadsRunsBlamesProjectable
@EnabledWhenreceiver + argsbeforecaller ("not enabled in this state")no, closure
Parameter constraints and the signatureone argument; the argument countbeforecalleryes
@Requiresall argsbeforecallerclosure: no; relation: docs
@Returnssettled resultaftercalleeyes
@Ensuresresult + args (+ old)aftercalleeclosure: no; relation: docs
Field @Enforceassigned valueon setassigneryes
Invariantthe new instance's fieldsend of constructioncalleeyes, as the field contracts

@EnabledWhen is deliberately a separate band from @Requires. For enforcement alone they behave the same, but they mean opposite things downstream. A failed @Requires means "these arguments are never valid", which is a generation signal that shapes an input schema. A failed @EnabledWhen means "correctly not enabled in this state", an expected skip that no choice of arguments could satisfy.

@Requires and @Ensures also take a relation: the same clause written as a descriptor over the call's bindings ({args} before, {result, args, old?} after), built from RelationContracts or TimeContracts. It runs in the same band with the same blame, and because it is data it names itself in messages and violation facts, renders in generated docs, and round-trips through JSON. JSON Schema has no keyword for a relation between properties, so it stays out of schemas.

The postcondition bands run on the settled value. adorn's shared settle classifier handles sync returns, thenables and observable-like values, so an async method's contract is checked against what it resolves to.

Written in its options form, @Ensures({ predicate, capture }) also sees pre-state: capture(...args) runs at call entry and its deep-cloned, frozen result reaches the predicate as old, so a body that mutates one of its arguments can't mask its own violation.

Trust & enforcement

Each contract is classified by trust:

  • guard (the default) validates untrusted input and stays on in production. Only disableGuardEnforcement({confirm, reason}) strips it.
  • assert is an internal self-check that's stripped in production.

setViolationPolicy('throw' | 'warn' | handler) controls what happens on a violation. 'warn' proceeds into the method, which is what makes it possible to stage a new contract over live traffic before it starts rejecting.

Process-level configuration

The configuration family is set once at startup, not per request. Set at boot it's safe under concurrency. The data-first core (constraint decorators, *Contracts descriptors, Verify.check) is pure and carries no ambient state at all.

Inheritance: strengthen, never weaken

A subclass's field is checked against the union of every declaration on its prototype chain, and an overridden method inherits its parent's preconditions. A subclass can add constraints but can't remove one. @Optional follows required-wins: if any level requires a parameter, it's required.

The getEffective… read family answers "what is in force here?", which is exactly what enforcement applies and what a projection should render.

A constructor is the exception: its contract is own-scoped. A subclass constructor is a new signature and inherits nothing from the base constructor's contract, though the base wrapper still checks the arguments super(...) passes it.

Construction

No decorator runs when an instance is built, so the class decorator is the only place adorn can act. When there is something to check at construction, a constructor contract or an instance field contract, @Contract() returns a validating subclass: its constructor runs the parameter, signature and @Requires checks, calls super(...args), then checks the field invariant and @Ensures. A subclass, rather than a Proxy, keeps instanceof, new.target, instance #private members, a.constructor === Class and design:paramtypes, and a new a.constructor() can't escape the check.

The constructor's contract is recorded on a host of its own, under the key 'constructor', and every projection reads it there like a method: snapshot, tool schema, JSON Schema annotation and docs. The fuzzers read it as a generator for their start state, so an instance method is tested on receivers built from arguments the constructor accepts.

The invariant, and useDefineForClassFields

A field contract is enforced by an accessor on the prototype. Under [[Define]] semantics (useDefineForClassFields, the TypeScript default from target: ES2022, and native class fields), a field declaration defines an own data property on each instance that shadows the accessor, so every assignment would skip the contract, silently. At the end of the most-derived wrapper, adorn validates each such own property, puts its accessor back, and checks that every required field contract holds. Under a plain (uncontracted) subclass that check runs as super(...) returns, before the subclass's constructor body, so it refuses an established field holding an invalid value but passes over one still undefined: the subclass may set it after super(), and the field's accessor checks that assignment. Only the class actually constructed must establish its required fields; a plain subclass's own fields, and a base field it never assigns, are checked at construction only with @Contract() on the subclass. A class no wrapper covers can't be reached, so it is reported in development as ADN0509 rather than silently unenforced.

Names: a label is not a key

A parameter's name can come from two places: a declaration (@Name, a slot's name), or the function's source text. The source text is renamed by a minifier, to different letters in two builds of the same code, so it may label but never key. One resolver, parameterNameOf, answers for every reader, and says which source it used.

Keys: declared names onlyLabels: declared, else parsed, else arg{i}
Tool-schema properties and requiredViolation messages and facts
The snapshot's name and the diff's name bandGenerated docs and the privacy report
The OpenTelemetry attribute adorn.param.<name>The observation event's name

Because the privacy report and the observation event read the one resolver, they name every position alike. A parameter list the scanner can't vouch for (a destructured parameter) names nothing, rather than quoting a fragment of source.

Projection rules

Descriptive vs. prescriptive

schemaForClass and toolSchemaForMethod are siblings, not one function with a flag. A descriptive schema under-claims: it describes values enforcement will accept. A tool schema is tight: it specifies the object a producer must send.

Tool-schema decisionWhy
No $schemaIt's a parameters sub-schema, not a standalone document.
Each property keyed by the declared nameA key has to be the same in every build. With no @Name, the projection throws, naming each position and the fix, rather than emit a key a minifier will change.
required = every typed position, minus the optional ones the installer recordedSound because predicates are total: a missing argument already fails at runtime. A position @Optional(), @Default() or a TypeScript default lets a caller omit is left out.
additionalProperties: falseA method's parameter set is closed: every parameter is typed, and enforcement refuses a call past the typed signature. A property name outside the schema maps to no position at all, so for the arguments object itself the keyword stays producer-steering.

Exact objects: a keyword earns its place

A value constraint emits additionalProperties only when enforcement backs it. A Fields and a @Shape are exact by default: they refuse an undeclared own key at runtime, so their fragment emits additionalProperties: false, in schemaForClass as well as the tool schema, and there it is a necessary condition rather than producer-steering. {extra: 'allow'} opens one object, and its fragment then says nothing about extra keys. Openness is per descriptor: the objects nested inside an open Fields stay exact unless they opt out too.

Formats never over-claim

@Uuid, @DateTime and @Ipv4 are validating descriptors whose predicate is at least as strict as the format keyword they emit. date-time uses strict RFC 3339 with real calendar validation, not Date.parse. Where no keyword says exactly what a check does, the fragment says less: a time bound has no keyword and is left to enforcement, and Format('url-http') emits only its pattern, because format: uri would accept less than the check does.

OpenAI strict mode

Strict function calling requires every property to appear in required and additionalProperties: false at every object level. {provider: 'openai', strict: true} applies that recursively, but strict mode forbids a truly absent property, so an optional field has to become nullable in the declaration.

nullability lives in the declaration
const parameters = toolSchemaFrom({
    name: 'scheduleReminder',
    params: {
        patientId: StringContracts.Uuid(),
        note: NullableContracts.Nullable(StringContracts.NotEmpty()), // ◆
    },
}, { provider: 'openai', strict: true });
// note → { type: ['string', 'null'], minLength: 1 }, and it is listed in `required`.
// The model sends null; the same Nullable validator accepts it. No drift.

A bare non-nullable optional parameter, or an open Dictionary map, can't be expressed under strict mode. adorn refuses to build those with an actionable message instead of letting the API return a silent 400.

Redaction & privacy

Every path adorn can emit a value through, including @Log, violation messages and observation events, renders [REDACTED] by default without reading any annotation. setValueDisclosure('all') turns raw values back on for local debugging, and a @Sensitive marking vetoes even that. The veto is surfaced, not silenced.

@Telemetry.value(), .redact(strategy) and .result() opt a value into disclosure on the observation path; the name they appear under is the parameter's @Name. telemetryForClass is the review projection: a pure registry read reporting what each position is configured to disclose, with its scanned denominator printed so a clean table is never mistaken for a clean bill of health.

The sensitive-flow detector

adorn check (also the no-sensitive-to-adorn-sink rule of adorn/eslint) statically follows a @Sensitive value through aliases, template interpolation and destructuring to adorn's own emitters. It is report-only, permanently, and it states its limits on every run: s.ssn.slice(-4) isn't caught, and a raw console.log of a sensitive value is yours to handle.

The observability seam

A neutral, zero-dependency seam. setObservationSink installs one around-shaped ObservationSink. The enforcement weave emits value-free violation facts and completions, and @Observe emits completions carrying pre-disclosed values, redacted by default ("seeing ≠ emitting").

  • record is the fire-and-forget point-event surface (completed, violation, message).
  • scope opens a span, and its correlated completed event closes it, matched by callId.
  • nextCallId() is the one shared id sequence, so your own emitter never collides with adorn's.
  • adorn/otel maps only the public sink onto OpenTelemetry, so an event you emit by hand becomes a span too.

The testing projection

adorn/test derives fast-check generators from descriptors. Its rule is sound generation: produce only inputs the contract accepts, or decline and say so. Its oracle consumes the same functions enforcement runs (evaluatePreconditions, evaluatePostconditions, evaluateEnabledness), so it flags an input exactly when the enforced wrapper would throw.

fuzzSequence extends this to stateful objects. A command is a method plus generated arguments, and a sequence is an array of commands that fast-check shrinks structurally. Enabledness is resolved at run time against the real instance, so fc.commands is deliberately not used. It would force a parallel abstract model, which is exactly the drift @EnabledWhen exists to prevent.

A receiver is built the same way. With no hand-written subject, a class @Contract() wraps for construction is instantiated from generated constructor arguments, filtered by its construction @Requires. The arguments ride on the generated tuple, so they shrink with a counterexample, and the oracle checks the new instance with the same invariant checker the wrapper uses: a constructor that throws is a construction-crash, one that leaves a field invalid a construction-invariant-violation.

It samples. It doesn't prove.

A clean run means no generated sequence broke an invariant or postcondition. The report states that boundary every time, and it warns that the real methods run, side effects included.

Reading the relations it tests

Because a relational clause is data, the tester can read it as well as run it. A clause that compares an argument with a literal (LessThan(Arg(0), 500)) feeds the literal and its neighbours, 499, 500 and 501, into that argument's generator, still filtered by the parameter's descriptors and the precondition. For every Implies(p, q), the result counts on how many cases the evaluation reached it and on how many of those p held, and a premise that never held raises a warning: its consequent was never checked. Closures can't be read, so they're listed as not counted rather than guessed at.

An opt-in determinism oracle (determinism: true) runs each passing case a second time on a deep clone of its arguments and a fresh subject, and compares the results structurally. A difference is a nondeterministic-result finding, separate from contract findings; arguments or results that aren't plain data are counted as not comparable instead.

Three enforcement paths, one semantics

The decorator weave, contract() and contract.checked are three ways to enforce one contract. Their band semantics (order, the short circuit before the body, blame, value-free facts, capture/old, structural Equal, NaN, missing paths) are written down as language-neutral verdict and relation vectors that adorn owns and others may copy. Every case runs through all three paths, which must agree with the file and with each other.

Contract diff

A contract that is data can be compared with another version of itself. contractDiff reads each position of the new input contract and of the old output contract and answers compatible (proved), breaking (accepting less or promising less, with a witness call run through the real checks of both versions), or unknown (with the reason). It degrades toward the weaker truth like every projection: a closure, an Old(...) clause or a descriptor it can't read is never proved, only shown breaking by a checked witness or left unknown.

What an old caller could pass is read from the old version's enforcement, never from a function's source. A snapshot records the signature (arity, extraArgs), and a decorated method's snapshot is read from what its installer recorded when it built the wrapper, including its trust: a move from stripped assert input checks to enforced ones is breaking (with a witness call) or unknown.

A snapshot also records each declared name, and the diff reads them as a band of their own: a rename leaves every positional call as it was, but breaks a caller that sends arguments by name, so it is breaking unless the diff is told every caller is positional. A constructor snapshots like a method, so a new required constructor parameter is breaking and a new optional one compatible.

Build-time lint

The runtime holds a contract as data, but some facts exist only in the source: TypeScript's ?, a default initialiser, a rest parameter, the order decorators are written in, a parameter past Function.length. adorn/eslint reads them with the type checker, so it reports in the editor what the runtime refuses at install, warns about in development, or can't see at all.

The rules follow the same rule as the projections: no table of what a decorator means. A parameter decorator is type-bearing when its type is adorn's declared AdornParameterDecoratorFn, and a name is adorn's when the checker resolves it to a declaration in the adorn package. Each rule carries an ADN id shared with the runtime's diagnostic codes, so one id names one problem wherever it is found. An opt-out of a strict default carries its reason in a comment the lint checks, never in the contract, so a reason changes no snapshot or diff. The rules.

Deliberate boundaries

These are things adorn currently doesn't do, recorded as decisions rather than oversights.

No TypeScript type cross-check

@GreaterThan(0) x: string compiles and lints clean. adorn removes drift between projections, and the lint reconciles optionality and defaults with TypeScript, but not a descriptor with the parameter's type.

Legacy decorators

Parameter decorators exist only in legacy TypeScript. A standard-decorators adapter recording into the same core is on the roadmap.

Closures stay closures

A closure in @Requires, @Ensures or @EnabledWhen carries no identity, so it's enforced and fuzzed but never projected. Write a @Requires or @Ensures clause as a relation and it projects to docs.

Names are declared

A name recovered from source text only labels. Anything that keys on a name (a tool schema, a snapshot, an OpenTelemetry attribute) needs @Name, and refuses or falls back to the index without it.

No per-request policy

Divergent enforcement per concurrent context isn't expressible today. Configuration is process-level.

Add-ons stay out of core

Resilience, limits, caching and policy decorators belong in separate packages, so the root stays dependent on tslib only.