@orkestrel/scaffold 0.0.134 → 0.0.136

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +777 -83
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +327 -21
  3. package/dist/bin/main.js +254 -36
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/AGENTS.md +2 -2
  6. package/dist/host/agents/orchestration.md +2 -2
  7. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -1
  8. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +983 -123
  9. package/dist/host/agents/skills/orkestrel-publish/references/release.md +1 -0
  10. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +22 -5
  11. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +403 -32
  12. package/dist/host/claude/agents/orkestrel.md +17 -17
  13. package/dist/host/claude/agents/reviewer.md +1 -1
  14. package/dist/host/claude/rules/architecture.md +1 -1
  15. package/dist/host/claude/rules/documentation.md +1 -1
  16. package/dist/host/claude/rules/patterns.md +4 -2
  17. package/dist/host/claude/rules/workspace.md +73 -67
  18. package/dist/host/configs/helpers.ts +109 -73
  19. package/dist/host/dotfiles/oxlintrc.json +1 -57
  20. package/dist/host/guides/agent.md +989 -395
  21. package/dist/host/guides/contract.md +198 -163
  22. package/dist/host/guides/database.md +978 -503
  23. package/dist/host/guides/indexeddb.md +80 -66
  24. package/dist/host/guides/middleware.md +5 -5
  25. package/dist/host/guides/ollama.md +41 -42
  26. package/dist/host/guides/relation.md +56 -32
  27. package/dist/host/guides/scaffold.md +185 -107
  28. package/dist/host/guides/sqlite.md +44 -23
  29. package/dist/host/guides/study.md +12 -12
  30. package/dist/host/guides/test.md +163 -47
  31. package/dist/host/guides/toolbox.md +127 -81
  32. package/dist/host/guides/workspace.md +21 -14
  33. package/dist/host/manifest.json +30 -30
  34. package/dist/host/scripts/browsers.sh +0 -0
  35. package/dist/host/scripts/codex.sh +0 -0
  36. package/dist/host/scripts/cursor.sh +0 -0
  37. package/dist/host/scripts/deps.sh +0 -0
  38. package/dist/host/scripts/npm.sh +0 -0
  39. package/dist/host/scripts/ollama.sh +0 -0
  40. package/dist/host/tests/config.test.ts +237 -115
  41. package/dist/src/core/index.cjs +591 -218
  42. package/dist/src/core/index.cjs.map +1 -1
  43. package/dist/src/core/index.d.cts +248 -29
  44. package/dist/src/core/index.d.ts +248 -29
  45. package/dist/src/core/index.js +581 -216
  46. package/dist/src/core/index.js.map +1 -1
  47. package/dist/src/server/index.cjs +18 -8
  48. package/dist/src/server/index.cjs.map +1 -1
  49. package/dist/src/server/index.d.cts +4 -3
  50. package/dist/src/server/index.d.ts +4 -3
  51. package/dist/src/server/index.js +19 -9
  52. package/dist/src/server/index.js.map +1 -1
  53. package/package.json +3 -3
@@ -13,36 +13,45 @@ Validation is where untrusted data — an HTTP body, a parsed JSON blob, a tool
13
13
 
14
14
  These exports compose an already compiled contract and format its faults.
15
15
 
16
- | Name | Kind | Signature | Summary |
17
- | ----------------------- | --------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
18
- | `ContractAdmission` | interface | `{ value, repairs }` | Carries an admitted value and the lossless repairs made while parsing it. |
19
- | `ContractRefusal` | interface | `{ faults, cause? }` | Carries bounded admission faults and the cause of an unreadable value when present. |
20
- | `FaultTextOptions` | interface | `{ limit? }` | Reserves a caller's text budget for a bounded fault report. |
21
- | `AuditFaultShape` | type | `ReturnType<FaultShaper['build']>` | Describes the closed shape built for audit faults, including paired discriminator hints. |
22
- | `admitValue` | function | `<T>(contract: ContractInterface<T>, value: unknown) => Result<ContractAdmission<T>, ContractRefusal>` | Admits a stable readable value with only lossless repairs and returns the parser's value. |
23
- | `describeFaults` | function | `(faults: readonly AuditFault[], schema?: JSONSchema, options?: FaultTextOptions) => string` | Describes bounded faults with encoded values and a schema-derived correction summary. |
24
- | `matchesUndefinedField` | function | `(fault: AuditFault, value: unknown, parsed: unknown) => boolean` | Checks whether a type fault describes an own undefined field omitted or defaulted by a successful parse. |
25
- | `truncateFaultText` | function | `(text: string, limit: number) => string` | Truncates text to a UTF-16 budget without splitting a surrogate pair. |
26
- | `auditFaultShape` | function | `() => AuditFaultShape` | Returns the shared closed audit-fault shape, building it on the first call. |
27
- | `extractPath` | function | `(fault: AuditFault) => readonly string[]` | Extracts a fault's path as its segments, reading a string path as one segment. |
28
- | `extractForms` | function | `(schema: JSONSchema \| undefined) => readonly JSONSchema[]` | Extracts a schema's forms: the schema itself, then its union arms, so a read looks through a nullable the same way everywhere. |
29
- | `extractSchema` | function | `(schema: JSONSchema, path: readonly string[]) => JSONSchema \| undefined` | Extracts the part of a schema a path reaches, through properties, array items, record values, and the arms of a union. |
30
- | `renderPath` | function | `(path: readonly string[]) => string` | Renders a path as text, encoding what a caller could have sent and eliding the middle of a long one. |
31
- | `renderList` | function | `(entries: readonly string[]) => string` | Renders a list as text, naming at most `FAULT_LIST_LIMIT` of its entries and counting the rest. |
32
- | `renderForm` | function | `(schema: JSONSchema, room?: number) => string` | Renders a schema as a short summary of what to send, such as `{"city": string, "note"?: string}`. |
33
- | `describeFaultLine` | function | `(fault: AuditFault, schema: JSONSchema) => string` | Describes one fault as the line a caller corrects from, naming what to send where the schema says. |
34
- | `FAULT_TEXT_LIMIT` | const | `2048` | Caps a fault message at 2048 UTF-16 code units. |
35
- | `FAULT_LIST_LIMIT` | const | `12` | Caps the keys or literal candidates named in a fault line. |
36
- | `FAULT_SCHEMA_LIMIT` | const | `160` | Caps a schema summary's UTF-16 code units. |
37
-
38
- The admission helper requires stable reads across its guard, reports, and parser. It parses once,
39
- refuses lossy repairs and capped audits, and returns the parser's ownership unchanged. An own
40
- undefined optional field can be omitted or filled by its declared default; neither counts as a repair.
41
- A guard-valid
42
- union can retain input identity. A successful undefined result is distinct from a refusal through
43
- the result discriminant; the root shape builders do not expose that undefined-only domain.
44
-
45
- Snapshot a foreign object before admission, as Tool.execute does. A getter changing between
16
+ | Name | Kind | Signature | Summary |
17
+ | ----------------------- | --------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
18
+ | `ContractRepair` | interface | `{ value, repairs }` | Carries a repaired value and the lossless repairs made while parsing it. |
19
+ | `ContractRefusal` | interface | `{ faults, cause? }` | Carries bounded admission faults and the cause of an unreadable value when present. |
20
+ | `FaultTextOptions` | interface | `{ limit? }` | Reserves a caller's text budget for a bounded fault report. |
21
+ | `AuditFaultShape` | type | `ReturnType<FaultShaper['build']>` | Describes the closed shape built for audit faults, including paired discriminator hints. |
22
+ | `admitValue` | function | `<T>(contract: ContractInterface<T>, value: unknown) => Result<T, ContractRefusal>` | Admits a readable value exactly where `is` holds and returns the parser's value. |
23
+ | `repairValue` | function | `<T>(contract: ContractInterface<T>, value: unknown) => Result<ContractRepair<T>, ContractRefusal>` | Repairs a stable readable value with only lossless repairs and returns the parser's value. |
24
+ | `filterUncoveredFaults` | function | `(faults: readonly AuditFault[]) => readonly AuditFault[]` | Filters out the faults a union fault covers, keeping every fault that states a fact no form shows. |
25
+ | `buildPathKey` | function | `(path: readonly string[], length?: number) => string` | Builds a map key from the leading segments of a path, without dispatching through array serialization. |
26
+ | `describeFaults` | function | `(faults: readonly AuditFault[], schema?: JSONSchema, options?: FaultTextOptions) => string` | Describes bounded faults with encoded values and a schema-derived correction summary. |
27
+ | `matchesUndefinedField` | function | `(fault: AuditFault, value: unknown, parsed: unknown) => boolean` | Checks whether a type fault describes an own undefined field omitted or defaulted by a successful parse. |
28
+ | `truncateFaultText` | function | `(text: string, limit: number) => string` | Truncates text to a UTF-16 budget without splitting a surrogate pair. |
29
+ | `auditFaultShape` | function | `() => AuditFaultShape` | Returns the shared closed audit-fault shape, building it on the first call. |
30
+ | `extractPath` | function | `(fault: AuditFault) => readonly string[]` | Extracts a fault's path as its segments, reading a string path as one segment. |
31
+ | `extractForms` | function | `(schema: JSONSchema \| undefined) => readonly JSONSchema[]` | Extracts a schema's forms: the schema itself, then its union arms, so a read looks through a nullable the same way everywhere. |
32
+ | `extractSchema` | function | `(schema: JSONSchema, path: readonly string[]) => JSONSchema \| undefined` | Extracts the part of a schema a path reaches, through properties, array items, record values, and the arms of a union. |
33
+ | `renderPath` | function | `(path: readonly string[]) => string` | Renders a path as text, encoding what a caller could have sent and eliding the middle of a long one. |
34
+ | `renderList` | function | `(entries: readonly string[]) => string` | Renders a list as text, naming at most `FAULT_LIST_LIMIT` of its entries and counting the rest. |
35
+ | `renderForm` | function | `(schema: JSONSchema, room?: number) => string` | Renders a schema as a short summary of what to send, such as `{"city": string, "note"?: string}`. |
36
+ | `describeFaultLine` | function | `(fault: AuditFault, schema: JSONSchema) => string` | Describes one fault as the line a caller corrects from, naming what to send where the schema says. |
37
+ | `FAULT_TEXT_LIMIT` | const | `2048` | Caps a fault message at 2048 UTF-16 code units. |
38
+ | `FAULT_LIST_LIMIT` | const | `12` | Caps the keys or literal candidates named in a fault line. |
39
+ | `FAULT_SCHEMA_LIMIT` | const | `160` | Caps a schema summary's UTF-16 code units. |
40
+
41
+ `admitValue` is strict: it succeeds exactly where `is` holds, returns the parser's value, and otherwise
42
+ refuses with every fault `audit` reports after `filterUncoveredFaults` prunes the faults a `variant` or
43
+ `oneOf` fault covers, bounded at `FAULT_LIMIT`. A `hidden` fault and an `extra` fault carrying `symbol`
44
+ stay whatever covers them. It repairs nothing: a numeric string for a number refuses.
45
+
46
+ `repairValue` is the repairing door. It requires stable reads across its guard, reports, and parser,
47
+ parses once, refuses lossy repairs and capped audits, and returns the parser's ownership unchanged.
48
+ Its result carries the lossless repairs made. An own undefined optional field can be omitted or filled
49
+ by its declared default; neither counts as a repair. A guard-valid union can retain input identity.
50
+ A successful undefined result is distinct from a refusal through the result discriminant; the root shape
51
+ builders do not expose that undefined-only domain. Its merge keeps every `extra` fault carrying `symbol`,
52
+ so two symbol keys of one description stay two faults. A finite number repairs to a string except `-0`.
53
+
54
+ Snapshot a foreign object before repair, as Tool.execute does. A getter changing between
46
55
  is and parse can publish a value that no recorded repair describes. A shallow snapshot stabilizes
47
56
  only its own level; nested foreign values must also provide stable reads.
48
57
 
@@ -57,9 +66,15 @@ send summary when a schema is supplied. Pass a smaller limit to reserve a headin
57
66
  Across union arms, a fault line names literal candidates only when the declarations at that path
58
67
  agree, and lists declared keys only when the declaring arms have the same keys. Lists are deduplicated;
59
68
  the final send summary still shows the arms. The root subject reads `value`. A `received` preview
60
- of at most `PREVIEW_LIMIT` characters without controls or line separators stays as written;
61
- other received text and foreign type words pass through `preview`. Received, constraint, and limit
62
- details use own fields.
69
+ of at most `PREVIEW_LIMIT` UTF-16 code units without controls or line separators stays as written;
70
+ other received text and foreign type words pass through `preview`. A `preview` result, its quotes,
71
+ its `…`, and a bigint's `n` included, is at most `PREVIEW_LIMIT` UTF-16 code units for every input.
72
+ The `preview` function encodes DEL (U+007F), the C1 controls (U+0080 to U+009F), U+2028, and U+2029
73
+ as `\u` sequences, so a fault line prints a received preview with one layer of quotes and no line
74
+ terminator. The `preview` function returns the `'object'` tag for a plain or null-prototype record
75
+ and the `'instance'` tag for every other object that is neither an array nor a function, such as a
76
+ class instance, a `Map`, or a `Date`. It reads the object's prototype to decide, so a `Proxy`
77
+ object's `getPrototypeOf` trap runs. Received, constraint, and limit details use own fields.
63
78
  Schema conversion refusal messages append a rendered path bounded by `FAULT_SCHEMA_LIMIT`, while
64
79
  their structured context retains the complete path.
65
80
  The generated-law regression covers stable values; it does not prove accessor read discipline,
@@ -252,22 +267,23 @@ the constant's own literal:
252
267
 
253
268
  The safe JSON surface keeps text parsing lazy: `parseJSON` returns `unknown`, while `parseJSONAs` walks only the guard shape supplied by its caller. `isJSONValue` and `parseJSONValue` are shipped explicit deep whole-tree gates; `isBoundedJSONValue` adds the fixed resource boundary, and `isBoundedJSONRecord` adds the record-root invariant. `JSONRecord` and `cloneJSONRecord` provide the record-root ownership contract required by metadata and persistence consumers, while `cloneJSONValue` owns any JSON root. A dedicated `JSONArray` alias, broad deep `isJSONObject` / `isJSONSchema` validators, and the ~50-field `JSONSchemaDefinition` remain deliberately omitted. Compose narrower shapes from the combinators and read a parsed blob field-by-field with the `parse*Field` readers when whole-tree work is unnecessary.
254
269
 
255
- | Name | Kind | Signature | Summary |
256
- | ------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
257
- | `isJSONPrimitive` | function | `(value: unknown) => value is JSONPrimitive` | Determines whether a value is a primitive JSON value. |
258
- | `isJSONValue` | function | `(value: unknown) => value is JSONValue` | Determines whether a value is a cycle-safe JSON value. |
259
- | `isBoundedJSONValue` | function | `(value: unknown) => value is JSONValue` | Determines whether a value is JSON-valid within the fixed container-depth limit. |
260
- | `isBoundedJSONRecord` | function | `(value: unknown) => value is JSONRecord` | Determines whether a value is a depth-bounded JSON record. |
261
- | `parseJSON` | function | `(value: string) => unknown` | Parses a JSON string, returning `undefined` instead of throwing. |
262
- | `parseJSONAs` | function | `<T>(value: string, guard: Guard<T>) => T \| undefined` | Parses a JSON string and validates the result against a guard. |
263
- | `JSON_SCHEMA_TYPES` | const | `readonly JSONSchemaType[]` | Lists the seven standard JSON Schema `type` names, frozen. |
264
- | `STRICT_SCHEMA_KEYWORDS` | const | `readonly string[]` | Lists the JSON Schema keywords a strict `schemaToShape` conversion reads, frozen. |
265
- | `JSONPrimitive` | type | `string \| number \| boolean \| null` | Represents a primitive JSON value — the flat leaf of any JSON document. |
266
- | `JSONRecord` | type | `{ readonly [key: string]: JSONValue; }` | Represents a readonly string-keyed JSON object record. |
267
- | `JSONValue` | type | `JSONPrimitive \| readonly JSONValue[] \| JSONRecord` | Represents a recursive JSON value — primitives, arrays, and object records. |
268
- | `JSONSchemaType` | type | `'null' \| 'boolean' \| 'object' \| 'array' \| 'number' \| 'integer' \| 'string'` | Lists the seven standard JSON Schema `type` names. |
269
- | `JSONSchema` | interface | `{ type?, description?, default?, enum?, minLength?, maxLength?, pattern?, format?, minimum?, maximum?, minItems?, maxItems?, items?, properties?, required?, additionalProperties?, anyOf?, oneOf? }` | Represents a JSON Schema fragment — the supported keyword vocabulary the contract compiler emits and `RawShape` validates before embedding. |
270
- | `SchemaFormat` | type | `'date-time' \| 'date' \| 'time' \| 'uuid' \| 'email' \| 'uri'` | Lists the closed set of string formats `stringToFormat` recognizes. |
270
+ | Name | Kind | Signature | Summary |
271
+ | ------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
272
+ | `isJSONPrimitive` | function | `(value: unknown) => value is JSONPrimitive` | Determines whether a value is a primitive JSON value. |
273
+ | `isJSONValue` | function | `(value: unknown) => value is JSONValue` | Determines whether a value is a cycle-safe JSON value. |
274
+ | `isBoundedJSONValue` | function | `(value: unknown) => value is JSONValue` | Determines whether a value is JSON-valid within the fixed container-depth limit. |
275
+ | `isBoundedJSONRecord` | function | `(value: unknown) => value is JSONRecord` | Determines whether a value is a depth-bounded JSON record. |
276
+ | `parseJSON` | function | `(value: string) => unknown` | Parses a JSON string, returning `undefined` instead of throwing. |
277
+ | `parseJSONAs` | function | `<T>(value: string, guard: Guard<T>) => T \| undefined` | Parses a JSON string and validates the result against a guard. |
278
+ | `JSON_SCHEMA_TYPES` | const | `readonly JSONSchemaType[]` | Lists the seven standard JSON Schema `type` names, frozen. |
279
+ | `SCHEMA_ANNOTATIONS` | const | `readonly ["title", "description", "$schema", "$id", "$comment", "deprecated", "readOnly", "writeOnly", "examples"]` | Lists the JSON Schema annotations a strict `schemaToShape` conversion admits on any node, frozen. |
280
+ | `STRICT_SCHEMA_KEYWORDS` | const | `readonly string[]` | Lists the JSON Schema keywords a strict `schemaToShape` conversion reads, frozen. |
281
+ | `JSONPrimitive` | type | `string \| number \| boolean \| null` | Represents a primitive JSON value — the flat leaf of any JSON document. |
282
+ | `JSONRecord` | type | `{ readonly [key: string]: JSONValue; }` | Represents a readonly string-keyed JSON object record. |
283
+ | `JSONValue` | type | `JSONPrimitive \| readonly JSONValue[] \| JSONRecord` | Represents a recursive JSON value — primitives, arrays, and object records. |
284
+ | `JSONSchemaType` | type | `'null' \| 'boolean' \| 'object' \| 'array' \| 'number' \| 'integer' \| 'string'` | Lists the seven standard JSON Schema `type` names. |
285
+ | `JSONSchema` | interface | `{ type?, description?, default?, enum?, minLength?, maxLength?, pattern?, format?, minimum?, maximum?, minItems?, maxItems?, items?, properties?, required?, additionalProperties?, anyOf?, oneOf?, not? }` | Represents a JSON Schema fragment — the supported keyword vocabulary the contract compiler emits and `RawShape` validates before embedding. |
286
+ | `SchemaFormat` | type | `'date-time' \| 'date' \| 'time' \| 'uuid' \| 'email' \| 'uri'` | Lists the closed set of string formats `stringToFormat` recognizes. |
271
287
 
272
288
  ### Helper
273
289
 
@@ -275,57 +291,59 @@ The safe JSON surface keeps text parsing lazy: `parseJSON` returns `unknown`, wh
275
291
  | ---------------------- | ----- | --------------- | --------------------------------------------------------------------------------------------- |
276
292
  | `CONTRACT_ERROR_BRAND` | const | `unique symbol` | Holds the registry-global key used to recognize `ContractError` values across package copies. |
277
293
 
278
- | Name | Kind | Signature | Summary |
279
- | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
280
- | `success` | function | `<T>(value: T) => Success<T>` | Boxes a value as the `Success` branch of a `Result`. |
281
- | `failure` | function | `<E>(error: E) => Failure<E>` | Boxes an error as the `Failure` branch of a `Result`. |
282
- | `isSuccess` | function | `<T, E>(result: Result<T, E>) => result is Success<T>` | Narrows a `Result` to its `Success` branch. |
283
- | `isFailure` | function | `<T, E>(result: Result<T, E>) => result is Failure<E>` | Narrows a `Result` to its `Failure` branch. |
284
- | `attempt` | function | `<T>(callback: () => T) => Result<T>` | Invokes a callback once and synchronously captures its exact outcome as a `Result`. |
285
- | `errorToMessage` | function | `(error: unknown) => string` | Renders a thrown value as a non-empty message. |
286
- | `INTRINSICS` | const | `Readonly<{ freeze: { <T extends Function>(f: T): T; <T extends { [idx: string]: U \| null \| undefined \| object; }, U extends string \| bigint \| number \| boolean \| symbol>(o: T): Readonly<T>; <T>(o: T): Readonly<T>; }; frozen: (o: any) => boolean; keys: { (o: object): string[]; (o: {}): string[]; }; values: { <T>(o: { [s: string]: T; } \| ArrayLike<T>): T[]; (o: {}): any[]; }; own: (o: object, v: PropertyKey) => boolean; same: (value1: any, value2: any) => boolean; create: { (o: object \| null): any; (o: object \| null, properties: PropertyDescriptorMap & ThisType<any>): any; }; proxy: ProxyConstructor; describe: (o: any, p: PropertyKey) => PropertyDescriptor \| undefined; define: <T>(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType<any>) => T; definitions: <T>(o: T, properties: PropertyDescriptorMap & ThisType<any>) => T; prototype: (o: any) => any; symbols: (o: any) => symbol[]; base: Object; reflect: Readonly<{ read: typeof Reflect.get; write: typeof Reflect.set; members: typeof Reflect.ownKeys; present: typeof Reflect.has; describe: typeof Reflect.getOwnPropertyDescriptor; define: typeof Reflect.defineProperty; prototype: typeof Reflect.getPrototypeOf; apply: typeof Reflect.apply; construct: typeof Reflect.construct; }>; finite: (number: unknown) => boolean; integer: (number: unknown) => boolean; safe: (number: unknown) => boolean; nan: (number: unknown) => boolean; array: (arg: any) => arg is any[]; stringify: { (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string \| number): string; (value: any, replacer?: (number \| string)[] \| null, space?: string \| number): string; }; decode: (text: string, reviver?: (this: any, key: string, value: any) => any) => any; floor: (x: number) => number; ceil: (x: number) => number; max: (...values: number[]) => number; min: (...values: number[]) => number; imul: (x: number, y: number) => number; text: StringConstructor; numeric: NumberConstructor; pattern: RegExpConstructor; captures: (string: string) => RegExpExecArray \| null; expression: (() => any) \| undefined; modifiers: (() => any) \| undefined; list: ArrayConstructor; order: (compareFn?: ((a: any, b: any) => number) \| undefined) => any[]; some: (predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any) => boolean; find: (predicate: (value: any, index: number, obj: any[]) => unknown, thisArg?: any) => number; each: (callbackfn: (value: any, index: number, array: any[]) => void, thisArg?: any) => void; from: { <T>(arrayLike: ArrayLike<T>): T[]; <T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; <T>(iterable: Iterable<T> \| ArrayLike<T>): T[]; <T, U>(iterable: Iterable<T> \| ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; }; fold: { (callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any): any; (callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any, initialValue: any): any; <U>(callbackfn: (previousValue: U, currentValue: any, currentIndex: number, array: any[]) => U, initialValue: U): U; }; reduce: { (callbackfn: (previousValue: any, currentValue: any, currentIndex: number) => any): any; (callbackfn: (previousValue: any, currentValue: any, currentIndex: number) => any, initialValue: any): any; <U>(callbackfn: (previousValue: U, currentValue: any, currentIndex: number) => U, initialValue: U): U; }; select: { <S extends any>(predicate: (value: any, index: number, array: any[]) => value is S, thisArg?: any): S[]; (predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any[]; }; project: <U>(callbackfn: (value: any, index: number, array: any[]) => U, thisArg?: any) => U[]; expand: <U, This = undefined>(callback: (this: This, value: any, index: number, array: any[]) => U \| readonly U[], thisArg?: This \| undefined) => U[]; flip: () => any[]; iterator: () => ArrayIterator<any>; indices: () => ArrayIterator<number>; advance: any; join: (separator?: string) => string; bind: (this: Function, thisArg: any, ...argArray: any[]) => any; record: { <T = any>(entries: Iterable<readonly [PropertyKey, T]>): { [k: string]: T; }; (entries: Iterable<readonly any[]>): any; }; rebase: (o: any, proto: object \| null) => any; map: MapConstructor; fetch: (key: any) => any; store: (key: any, value: any) => Map<any, any>; keyed: (key: any) => boolean; pairs: (callbackfn: (value: any, key: any, map: Map<any, any>) => void, thisArg?: any) => void; set: SetConstructor; union: <U>(other: ReadonlySetLike<U>) => Set<any>; member: (value: any) => boolean; admit: (value: any) => Set<any>; sweep: (callbackfn: (value: any, value2: any, set: Set<any>) => void, thisArg?: any) => void; remove: (value: any) => boolean; weakMap: WeakMapConstructor; recall: (key: WeakKey) => any; retain: (key: WeakKey, value: any) => WeakMap<WeakKey, any>; weakSet: WeakSetConstructor; tracked: (value: WeakKey) => boolean; track: (value: WeakKey) => WeakSet<WeakKey>; untrack: (value: WeakKey) => boolean; error: ErrorConstructor; date: DateConstructor; instant: () => number; now: () => number; }>` | Captures every host operation this package dispatches through, while this module evaluates. |
287
- | `contain` | function | `<T>(callback: () => T, door: string, options?: ContainOptions) => T` | Runs a public door's whole body and publishes only this package's error class. |
288
- | `appendEntries` | function | `<T>(target: T[], source: readonly T[]) => void` | Appends every element of one array onto another, by index. |
289
- | `limitEntries` | function | `<T>(entries: readonly T[], limit: number) => readonly T[]` | Takes at most `limit` leading elements of an array, by index. |
290
- | `comparePrimitives` | function | `<T extends string \| number>(left: T, right: T) => number` | Orders two primitive keys or indices ascending. |
291
- | `sortValues` | function | `<T extends string \| number>(values: readonly T[]) => readonly T[]` | Orders primitive keys or indices deterministically, on an owned copy, through the captured sort. |
292
- | `pathOf` | function | `(path: readonly string[], ...segments: ReadonlyArray<string \| undefined>) => readonly string[]` | Builds a diagnostic path from an existing path and further segments, without dispatching through array iteration. |
293
- | `readValue` | function | `<T>(callback: () => T, reader: string, options?: ReadValueOptions) => T` | Reads a value through the shared containment boundary or refuses it with the contract module's uniform read diagnostic. |
294
- | `readArrayEntries` | function | `<T>(value: readonly T[]) => Result<ArrayRead<T>>` | Snapshots an array through its reflected own-index population. |
295
- | `readGuardShape` | function | `(shape: GuardsShape, optional: readonly string[] \| true \| undefined, reader: string) => GuardShapeRead` | Snapshots a guard shape and its optional-key mode for a shape combinator. |
296
- | `holds` | function | `(callback: () => boolean) => boolean` | Invokes a predicate through the sanctioned never-throw boundary. |
297
- | `enumerableKeys` | function | `(value: object) => readonly string[] \| undefined` | Snapshots an object's own enumerable string keys through a total boundary. |
298
- | `readOptions` | function | `<T extends object>(source: T \| undefined, keys: ReadonlyArray<keyof T & string>, builder: string, shape: string) => T \| undefined` | Validates and snapshots a shape-builder options record through every reflective operation the builder relies on. |
299
- | `refuseOptionKeys` | function | `(source: object \| undefined, keys: readonly string[], builder: string, shape: string) => void` | Refuses an options record that holds a key its builder does not read. |
300
- | `drawRandom` | function | `(random: RandomFunction, shape: string) => number` | Draws and validates one generator random sample. |
301
- | `enumerableSymbolCount` | function | `(value: object) => number` | Counts the enumerable own-symbol keys on a value. |
302
- | `matchesJSONValue` | function | `(entry: unknown, ancestors: WeakSet<object>, budget?: { left: number; }) => entry is JSONValue` | Matches an unknown value against the recursive JSON value structure. |
303
- | `matchesRecordBrand` | function | `(value: unknown) => boolean` | Determines whether a value carries the plain-record brand, raising a hostile prototype observation instead of answering it. |
304
- | `matchesJSONDepth` | function | `(value: unknown) => boolean` | Determines whether a readable value stays within the fixed JSON container-depth limit. |
305
- | `resolveField` | function | `(record: Readonly<Record<string, unknown>>, path: FieldPath) => unknown` | Resolves a (possibly nested) field value from a record by a key or key path. |
306
- | `seededRandom` | function | `(seed: number) => RandomFunction` | Builds a deterministic pseudo-random source seeded from a single number. |
307
- | `schemaToParameters` | function | `(schema: JSONSchema) => Readonly<Record<string, unknown>> \| undefined` | Narrows a compiled `JSONSchema` down to the open `Readonly<Record<string, unknown>>` shape tool definitions advertise as `parameters` — through the `isRecord` boundary guard, never an assertion, as `.claude/rules/patterns.md` § Validation and contracts requires. |
308
- | `schemaToObject` | function | `(schema: JSONSchema) => JSONSchema` | Wraps a non-object `JSONSchema` root in a single-property object schema, so an inferred primitive/array/union schema can flow into `schemaToParameters` as an MCP-compatible `inputSchema`. |
309
- | `collectMembers` | function | `(values: readonly unknown[]) => Set<unknown>` | Collects an array's entries into a membership collection this package owns. |
310
- | `matchesMember` | function | `(members: ReadonlySet<unknown>, value: unknown) => boolean` | Determines whether a value is a member of a collected vocabulary, by SameValueZero. |
311
- | `admitMember` | function | `(members: Set<unknown>, value: unknown) => void` | Collects one more member into a vocabulary that grows as a walk proceeds. |
312
- | `matchesVisited` | function | `(visited: WeakSet<object>, value: object) => boolean` | Determines whether an object is already on a traversal's active path. |
313
- | `admitVisited` | function | `(visited: WeakSet<object>, value: object) => void` | Records an object as entered on a traversal's active path. |
314
- | `omitVisited` | function | `(visited: WeakSet<object>, value: object) => void` | Records an object as exited from a traversal's active path. |
315
- | `retainDepth` | function | `<T>(memo: WeakMap<object, Map<number, T>>, node: object, depth: number, answer: T) => void` | Records one node's answer at one remaining-depth allowance in a shared memo. |
316
- | `collectEntries` | function | `(target: unknown[][]) => EntryCollectorFunction` | Builds the collector a captured `forEach` sweep appends through. |
317
- | `readSetEntries` | function | `(value: ReadonlySet<unknown>) => Result<readonly unknown[]>` | Snapshots the genuine contents of a caller's `Set` without running an iterator. |
318
- | `readMapEntries` | function | `(value: ReadonlyMap<unknown, unknown>) => Result<ReadonlyArray<readonly unknown[]>>` | Snapshots the genuine entries of a caller's `Map` without running an iterator. |
319
- | `matchesPattern` | function | `(pattern: RegExp, value: string) => boolean` | Determines whether a string is in the language of a pattern this package owns. |
320
- | `matchesStringLength` | function | `(value: string, min: number \| undefined, max: number \| undefined) => boolean` | Checks whether a string's length in code points falls within optional bounds. |
321
- | `computeSurrogatePairs` | function | `(value: string, limit: number) => number` | Counts the surrogate pairs in a string, stopping at a limit. |
322
- | `escapeRegExp` | function | `(value: string) => string` | Escapes every regular-expression metacharacter in a text, so the text matches literally inside a larger `RegExp` source. |
323
- | `readPatternSource` | function | `(pattern: unknown) => string \| undefined` | Reads a regular expression's source text through the captured accessor. |
324
- | `readPatternFlags` | function | `(pattern: unknown) => string \| undefined` | Reads a regular expression's flag text through the captured accessor. |
325
- | `readPattern` | function | `(pattern: RegExp) => RegExp` | Rebuilds a caller's regular expression as a stateless pattern this package owns. |
326
- | `ownPattern` | function | `(pattern: RegExp, reader: string) => RegExp` | Rebuilds a declaration's regular expression as a stateless pattern this package owns, and refuses an unreadable one under the reader's own name. |
327
- | `pinMembers` | function | `(prototype: object, owner: string) => void` | Pins every own member of a class prototype as a non-configurable member — non-writable too when it is a data property — and verify the pin took. |
328
- | `refuseExpansion` | function | `(expansion: number \| undefined) => void` | Refuses a validated declaration whose compiled expansion exceeds `COMPILE_NODE_LIMIT`. |
294
+ | Name | Kind | Signature | Summary |
295
+ | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
296
+ | `success` | function | `<T>(value: T) => Success<T>` | Boxes a value as the `Success` branch of a `Result`. |
297
+ | `failure` | function | `<E>(error: E) => Failure<E>` | Boxes an error as the `Failure` branch of a `Result`. |
298
+ | `isSuccess` | function | `<T, E>(result: Result<T, E>) => result is Success<T>` | Narrows a `Result` to its `Success` branch. |
299
+ | `isFailure` | function | `<T, E>(result: Result<T, E>) => result is Failure<E>` | Narrows a `Result` to its `Failure` branch. |
300
+ | `attempt` | function | `<T>(callback: () => T) => Result<T>` | Invokes a callback once and synchronously captures its exact outcome as a `Result`. |
301
+ | `errorToMessage` | function | `(error: unknown) => string` | Renders a thrown value as a non-empty message. |
302
+ | `INTRINSICS` | const | `Readonly<{ freeze: { <T extends Function>(f: T): T; <T extends { [idx: string]: U \| null \| undefined \| object; }, U extends string \| bigint \| number \| boolean \| symbol>(o: T): Readonly<T>; <T>(o: T): Readonly<T>; }; frozen: (o: any) => boolean; keys: { (o: object): string[]; (o: {}): string[]; }; values: { <T>(o: { [s: string]: T; } \| ArrayLike<T>): T[]; (o: {}): any[]; }; own: (o: object, v: PropertyKey) => boolean; same: (value1: any, value2: any) => boolean; create: { (o: object \| null): any; (o: object \| null, properties: PropertyDescriptorMap & ThisType<any>): any; }; proxy: ProxyConstructor; describe: (o: any, p: PropertyKey) => PropertyDescriptor \| undefined; define: <T>(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType<any>) => T; definitions: <T>(o: T, properties: PropertyDescriptorMap & ThisType<any>) => T; prototype: (o: any) => any; symbols: (o: any) => symbol[]; names: (o: any) => string[]; base: Object; reflect: Readonly<{ read: typeof Reflect.get; write: typeof Reflect.set; members: typeof Reflect.ownKeys; present: typeof Reflect.has; describe: typeof Reflect.getOwnPropertyDescriptor; define: typeof Reflect.defineProperty; prototype: typeof Reflect.getPrototypeOf; apply: typeof Reflect.apply; construct: typeof Reflect.construct; }>; finite: (number: unknown) => boolean; integer: (number: unknown) => boolean; safe: (number: unknown) => boolean; nan: (number: unknown) => boolean; array: (arg: any) => arg is any[]; stringify: { (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string \| number): string; (value: any, replacer?: (number \| string)[] \| null, space?: string \| number): string; }; decode: (text: string, reviver?: (this: any, key: string, value: any) => any) => any; floor: (x: number) => number; ceil: (x: number) => number; max: (...values: number[]) => number; min: (...values: number[]) => number; imul: (x: number, y: number) => number; text: StringConstructor; numeric: NumberConstructor; pattern: RegExpConstructor; captures: (string: string) => RegExpExecArray \| null; expression: (() => any) \| undefined; modifiers: (() => any) \| undefined; list: ArrayConstructor; order: (compareFn?: ((a: any, b: any) => number) \| undefined) => any[]; some: (predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any) => boolean; every: { <S extends any>(predicate: (value: any, index: number, array: any[]) => value is S, thisArg?: any): this is S[]; (predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): boolean; }; find: (predicate: (value: any, index: number, obj: any[]) => unknown, thisArg?: any) => number; each: (callbackfn: (value: any, index: number, array: any[]) => void, thisArg?: any) => void; from: { <T>(arrayLike: ArrayLike<T>): T[]; <T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; <T>(iterable: Iterable<T> \| ArrayLike<T>): T[]; <T, U>(iterable: Iterable<T> \| ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; }; fold: { (callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any): any; (callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any, initialValue: any): any; <U>(callbackfn: (previousValue: U, currentValue: any, currentIndex: number, array: any[]) => U, initialValue: U): U; }; reduce: { (callbackfn: (previousValue: any, currentValue: any, currentIndex: number) => any): any; (callbackfn: (previousValue: any, currentValue: any, currentIndex: number) => any, initialValue: any): any; <U>(callbackfn: (previousValue: U, currentValue: any, currentIndex: number) => U, initialValue: U): U; }; select: { <S extends any>(predicate: (value: any, index: number, array: any[]) => value is S, thisArg?: any): S[]; (predicate: (value: any, index: number, array: any[]) => unknown, thisArg?: any): any[]; }; project: <U>(callbackfn: (value: any, index: number, array: any[]) => U, thisArg?: any) => U[]; expand: <U, This = undefined>(callback: (this: This, value: any, index: number, array: any[]) => U \| readonly U[], thisArg?: This \| undefined) => U[]; flip: () => any[]; iterator: () => ArrayIterator<any>; indices: () => ArrayIterator<number>; advance: any; join: (separator?: string) => string; bind: (this: Function, thisArg: any, ...argArray: any[]) => any; record: { <T = any>(entries: Iterable<readonly [PropertyKey, T]>): { [k: string]: T; }; (entries: Iterable<readonly any[]>): any; }; rebase: (o: any, proto: object \| null) => any; map: MapConstructor; fetch: (key: any) => any; store: (key: any, value: any) => Map<any, any>; keyed: (key: any) => boolean; pairs: (callbackfn: (value: any, key: any, map: Map<any, any>) => void, thisArg?: any) => void; set: SetConstructor; union: <U>(other: ReadonlySetLike<U>) => Set<any>; member: (value: any) => boolean; admit: (value: any) => Set<any>; sweep: (callbackfn: (value: any, value2: any, set: Set<any>) => void, thisArg?: any) => void; remove: (value: any) => boolean; weakMap: WeakMapConstructor; recall: (key: WeakKey) => any; retain: (key: WeakKey, value: any) => WeakMap<WeakKey, any>; weakSet: WeakSetConstructor; tracked: (value: WeakKey) => boolean; track: (value: WeakKey) => WeakSet<WeakKey>; untrack: (value: WeakKey) => boolean; error: ErrorConstructor; date: DateConstructor; instant: () => number; now: () => number; }>` | Captures every host operation this package dispatches through, while this module evaluates. |
303
+ | `contain` | function | `<T>(callback: () => T, door: string, options?: ContainOptions) => T` | Runs a public door's whole body and publishes only this package's error class. |
304
+ | `appendEntries` | function | `<T>(target: T[], source: readonly T[]) => void` | Appends every element of one array onto another, by index. |
305
+ | `limitEntries` | function | `<T>(entries: readonly T[], limit: number) => readonly T[]` | Takes at most `limit` leading elements of an array, by index. |
306
+ | `comparePrimitives` | function | `<T extends string \| number>(left: T, right: T) => number` | Orders two primitive keys or indices ascending. |
307
+ | `sortValues` | function | `<T extends string \| number>(values: readonly T[]) => readonly T[]` | Orders primitive keys or indices deterministically, on an owned copy, through the captured sort. |
308
+ | `pathOf` | function | `(path: readonly string[], ...segments: ReadonlyArray<string \| undefined>) => readonly string[]` | Builds a diagnostic path from an existing path and further segments, without dispatching through array iteration. |
309
+ | `readValue` | function | `<T>(callback: () => T, reader: string, options?: ReadValueOptions) => T` | Reads a value through the shared containment boundary or refuses it with the contract module's uniform read diagnostic. |
310
+ | `collectArrayEntries` | function | `<T>(value: readonly T[]) => ArrayRead<T>` | Collects an array's entries through its reflected own-index population. |
311
+ | `readArrayEntries` | function | `<T>(value: readonly T[]) => Result<ArrayRead<T>>` | Snapshots an array through its reflected own-index population. |
312
+ | `readGuardShape` | function | `(shape: GuardsShape, optional: readonly string[] \| true \| undefined, reader: string) => GuardShapeRead` | Snapshots a guard shape and its optional-key mode for a shape combinator. |
313
+ | `holds` | function | `(callback: () => boolean) => boolean` | Invokes a predicate through the sanctioned never-throw boundary. |
314
+ | `enumerableKeys` | function | `(value: object) => readonly string[] \| undefined` | Snapshots an object's own enumerable string keys through a total boundary. |
315
+ | `matchesEnumerableKeys` | function | `(value: object, keys: readonly string[]) => boolean` | Checks whether an object owns no key outside the enumerable string keys already read from it. |
316
+ | `readOptions` | function | `<T extends object>(source: T \| undefined, keys: ReadonlyArray<keyof T & string>, builder: string, shape: string) => T \| undefined` | Validates and snapshots a shape-builder options record through every reflective operation the builder relies on. |
317
+ | `refuseOptionKeys` | function | `(source: object \| undefined, keys: readonly string[], builder: string, shape: string) => void` | Refuses an options record that holds a key its builder does not read. |
318
+ | `drawRandom` | function | `(random: RandomFunction, shape: string) => number` | Draws and validates one generator random sample. |
319
+ | `enumerableSymbolCount` | function | `(value: object) => number` | Counts the enumerable own-symbol keys on a value. |
320
+ | `matchesJSONValue` | function | `(entry: unknown, ancestors: WeakSet<object>, budget?: { left: number; }) => entry is JSONValue` | Matches an unknown value against the recursive JSON value structure. |
321
+ | `matchesRecordBrand` | function | `(value: unknown) => boolean` | Determines whether a value carries the plain-record brand, raising a hostile prototype observation instead of answering it. |
322
+ | `matchesJSONDepth` | function | `(value: unknown) => boolean` | Determines whether a readable value stays within the fixed JSON container-depth limit. |
323
+ | `resolveField` | function | `(record: Readonly<Record<string, unknown>>, path: FieldPath) => unknown` | Resolves a (possibly nested) field value from a record by a key or key path. |
324
+ | `seededRandom` | function | `(seed: number) => RandomFunction` | Builds a deterministic pseudo-random source seeded from a single number. |
325
+ | `schemaToParameters` | function | `(schema: JSONSchema) => Readonly<Record<string, unknown>> \| undefined` | Narrows a compiled `JSONSchema` down to the open `Readonly<Record<string, unknown>>` shape tool definitions advertise as `parameters` — through the `isRecord` boundary guard, never an assertion, as `.claude/rules/patterns.md` § Validation and contracts requires. |
326
+ | `schemaToObject` | function | `(schema: JSONSchema) => JSONSchema` | Wraps a non-object `JSONSchema` root in a single-property object schema, so an inferred primitive/array/union schema can flow into `schemaToParameters` as an MCP-compatible `inputSchema`. |
327
+ | `collectMembers` | function | `(values: readonly unknown[]) => Set<unknown>` | Collects an array's entries into a membership collection this package owns. |
328
+ | `matchesMember` | function | `(members: ReadonlySet<unknown>, value: unknown) => boolean` | Determines whether a value is a member of a collected vocabulary, by SameValueZero. |
329
+ | `admitMember` | function | `(members: Set<unknown>, value: unknown) => void` | Collects one more member into a vocabulary that grows as a walk proceeds. |
330
+ | `matchesVisited` | function | `(visited: WeakSet<object>, value: object) => boolean` | Determines whether an object is already on a traversal's active path. |
331
+ | `admitVisited` | function | `(visited: WeakSet<object>, value: object) => void` | Records an object as entered on a traversal's active path. |
332
+ | `omitVisited` | function | `(visited: WeakSet<object>, value: object) => void` | Records an object as exited from a traversal's active path. |
333
+ | `retainDepth` | function | `<T>(memo: WeakMap<object, Map<number, T>>, node: object, depth: number, answer: T) => void` | Records one node's answer at one remaining-depth allowance in a shared memo. |
334
+ | `collectEntries` | function | `(target: unknown[][]) => EntryCollectorFunction` | Builds the collector a captured `forEach` sweep appends through. |
335
+ | `readSetEntries` | function | `(value: ReadonlySet<unknown>) => Result<readonly unknown[]>` | Snapshots the genuine contents of a caller's `Set` without running an iterator. |
336
+ | `readMapEntries` | function | `(value: ReadonlyMap<unknown, unknown>) => Result<ReadonlyArray<readonly unknown[]>>` | Snapshots the genuine entries of a caller's `Map` without running an iterator. |
337
+ | `matchesPattern` | function | `(pattern: RegExp, value: string) => boolean` | Determines whether a string is in the language of a pattern this package owns. |
338
+ | `matchesStringLength` | function | `(value: string, min: number \| undefined, max: number \| undefined) => boolean` | Checks whether a string's length in code points falls within optional bounds. |
339
+ | `computeSurrogatePairs` | function | `(value: string, limit: number) => number` | Counts the surrogate pairs in a string, stopping at a limit. |
340
+ | `escapeRegExp` | function | `(value: string) => string` | Escapes every regular-expression metacharacter in a text, so the text matches literally inside a larger `RegExp` source. |
341
+ | `readPatternSource` | function | `(pattern: unknown) => string \| undefined` | Reads a regular expression's source text through the captured accessor. |
342
+ | `readPatternFlags` | function | `(pattern: unknown) => string \| undefined` | Reads a regular expression's flag text through the captured accessor. |
343
+ | `readPattern` | function | `(pattern: RegExp) => RegExp` | Rebuilds a caller's regular expression as a stateless pattern this package owns. |
344
+ | `ownPattern` | function | `(pattern: RegExp, reader: string) => RegExp` | Rebuilds a declaration's regular expression as a stateless pattern this package owns, and refuses an unreadable one under the reader's own name. |
345
+ | `pinMembers` | function | `(prototype: object, owner: string) => void` | Pins every own member of a class prototype as a non-configurable member — non-writable too when it is a data property — and verify the pin took. |
346
+ | `refuseExpansion` | function | `(expansion: number \| undefined) => void` | Refuses a validated declaration whose compiled expansion exceeds `COMPILE_NODE_LIMIT`. |
329
347
 
330
348
  | Name | Kind | Signature | Summary |
331
349
  | -------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
@@ -388,7 +406,7 @@ What is NOT guaranteed, beyond the realm assumption above: a value whose observa
388
406
  | Name | Kind | Signature | Summary |
389
407
  | ------------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
390
408
  | `Failure` | interface | `{ success, error }` | Represents the discriminated failure branch of a `Result`. |
391
- | `ArrayRead<T = unknown>` | interface | `{ entries, dense }` | Represents the owned result of reading one array through its reflected own-index lens. |
409
+ | `ArrayRead<T = unknown>` | interface | `{ entries, dense, exact }` | Represents the owned result of reading one array through its reflected own-index lens. |
392
410
  | `GuardShapeRead` | interface | `{ guards, names, optional, vocabulary }` | Represents the owned result of reading one guard shape and its optional-key mode. |
393
411
  | `BoundsRead` | interface | `{ min?, max? }` | Represents a derived numeric bounds pair, either member absent. |
394
412
  | `EntryCollectorFunction` | type | `(value: unknown, key: unknown) => void` | Represents the collector a captured `forEach` sweep invokes per entry. |
@@ -470,7 +488,7 @@ isContractError(error) // true
470
488
 
471
489
  `ownShape` returns a successful independent eager snapshot for both frozen and unfrozen sources. After failure it rethrows a non-`clone` `ContractError` or any failure for an unfrozen source. For a frozen source whose clone failure is `clone`-coded or foreign, it validates the source with a fresh `ShapeValidator`, prefers that validator's `ContractError` when present, and otherwise rethrows the original clone failure.
472
490
 
473
- The machinery behind owned snapshots (see Shape builders, below) — from [`JSONCloner.ts`](../src/core/JSONCloner.ts), [`SchemaCloner.ts`](../src/core/SchemaCloner.ts), [`ShapeCloner.ts`](../src/core/ShapeCloner.ts), and the eager boundaries in [`cloners.ts`](../src/core/cloners.ts). The JSON cloner accepts only exact acyclic JSON data, rejects sparse or decorated arrays and non-data record properties without invoking accessors, and builds deeply frozen standard arrays plus null-prototype records. “Decorated” means the array own-key set contains anything other than intrinsic `length` and every canonical index, including an extra, substituted, symbol, hidden, or accessor key. Index writability and configurability are normalized rather than treated as JSON data, so frozen arrays and nonwritable data indices remain valid. Because JSON persistence is a tree, repeated noncyclic source aliases are duplicated into distinct equal output branches; active-path back-edges fail as cycles. `cloneJSONRecord` adds record-root validation over the same engine. `cloneSchema` preserves shared-child identity and closes cyclic schema edges onto its clone; `cloneShape` preserves sharing, carries one accepted declaration population into its clone, and runs the complete declaration gate on that carried clone before returning, so a cyclic shape is refused with the same `cycle` diagnosis as every other shape entry. A key literally named `__proto__` stays own data. Every hostile reflective operation is contained through the sanctioned total boundary, and so is every caller-reachable dispatch on the declaration gate's own path: `ShapeValidator.validate` and `validateShape` translate a failure they did not author into a coded `ContractError` carrying the exact thrown value, rather than rethrowing it verbatim. JSON reflection failures and schema enumeration failures remain cause-free. A schema property-read failure instead retains the exact thrown value as its cause, including an explicit `undefined`; caller-owned errors never become terminal errors by identity. Only the exact errors owned or explicitly adopted by an engine can replay by terminal identity.
491
+ The machinery behind owned snapshots (see Shape builders, below) — from [`JSONCloner.ts`](../src/core/JSONCloner.ts), [`SchemaCloner.ts`](../src/core/SchemaCloner.ts), [`ShapeCloner.ts`](../src/core/ShapeCloner.ts), and the eager boundaries in [`cloners.ts`](../src/core/cloners.ts). The JSON cloner accepts only exact acyclic JSON data, rejects sparse or decorated arrays and non-data record properties without invoking accessors, and builds deeply frozen standard arrays plus null-prototype records. “Decorated” means the array own-key set contains anything other than intrinsic `length` and every canonical index, including an extra, substituted, symbol, hidden, or accessor key. Index writability and configurability are normalized rather than treated as JSON data, so frozen arrays and nonwritable data indices remain valid. Because JSON persistence is a tree, repeated noncyclic source aliases are duplicated into distinct equal output branches; active-path back-edges fail as cycles. A refusal that names a member or a container carries the complete `path` in its context beside `received`, which holds the value's preview, or the label `accessor` or the label `threw` where a member's descriptor holds no value or could not be read, and its message ends with `at` and the path `renderPath` renders, so a caller key reaches the text encoded and bounded. A symbol key adds no segment: the refusal sits at its record and names the symbol in its text, as `cloneJSONValue: record has a symbol property Symbol(s) at settings`. A refusal at the root carries the empty path and no suffix, and the node-limit refusal carries no path. A replaced array or `RegExp` member does not change a refusal's text, its path, or its replay. `cloneJSONRecord` adds record-root validation over the same engine, and a nested refusal keeps its `cloneJSONValue:` message through it. `cloneSchema` preserves shared-child identity and closes cyclic schema edges onto its clone; `cloneShape` preserves sharing, carries one accepted declaration population into its clone, and runs the complete declaration gate on that carried clone before returning, so a cyclic shape is refused with the same `cycle` diagnosis as every other shape entry. A key literally named `__proto__` stays own data. Every hostile reflective operation is contained through the sanctioned total boundary, and so is every caller-reachable dispatch on the declaration gate's own path: `ShapeValidator.validate` and `validateShape` translate a failure they did not author into a coded `ContractError` carrying the exact thrown value, rather than rethrowing it verbatim. JSON reflection failures and schema enumeration failures remain cause-free. A schema property-read failure instead retains the exact thrown value as its cause, including an explicit `undefined`; caller-owned errors never become terminal errors by identity. Only the exact errors owned or explicitly adopted by an engine can replay by terminal identity.
474
492
 
475
493
  | Name | Kind | Signature | Summary |
476
494
  | ------------------ | -------- | ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
@@ -533,12 +551,13 @@ Declarative constructors for the `ContractShape` union (`src/core/shapers.ts`).
533
551
  | `optionalShape` | function | `<S extends ContractShape>(inner: S, options?: OptionalShapeOptions) => OptionalShape<S>` | Wraps a shape so it may be absent (`undefined`). |
534
552
  | `nullableShape` | function | `<S extends ContractShape>(inner: S) => NullableShape<S>` | Wraps a shape so it may be `null`. |
535
553
  | `jsonShape` | function | `(options?: JSONShapeOptions) => JSONShape` | Builds a `JSONShape`. |
554
+ | `functionShape` | function | `(options?: FunctionShapeOptions) => FunctionShape` | Builds a `FunctionShape`. |
536
555
  | `rawShape` | function | `(schema: JSONSchema) => RawShape` | Builds a `RawShape` from a supported JSON Schema fragment. |
537
556
  | `schemaToShape` | function | `(schema: JSONSchema, options?: SchemaToShapeOptions) => ContractShape` | Converts a runtime `JSONSchema` value into a validating `ContractShape` — the inverse of `compileSchema`. Unlike direct `rawShape` construction, which rejects malformed supported-vocabulary keywords, the lenient conversion is total and widens an inexpressible input to a valid raw `{}`, and a strict conversion refuses that input. |
538
557
  | `deriveLengthBounds` | function | `(min: unknown, max: unknown) => BoundsRead` | Derives `min`/`max` shape bounds from a pair of non-negative-integer JSON Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`). |
539
558
  | `deriveRangeBounds` | function | `(min: unknown, max: unknown) => BoundsRead` | Derives `min`/`max` shape bounds from a pair of finite-number JSON Schema range keywords (`minimum`/`maximum`). |
540
559
 
541
- An ordinary `oneOfShape` parser returns the input itself when exactly one arm accepts it. It makes no defensive copy: mutating the result mutates the input. Object key order and prototype, frozen state, and hidden and symbol members are retained. Copy explicitly if you need an independent result. Primitive and JSON-valued arms, no-match and ambiguous refusals, and the prohibition on defaults under unions keep their existing behavior. A required literal discriminator can still select an arm for coercion.
560
+ An ordinary `oneOfShape` parser returns the input itself when exactly one arm accepts it. It makes no defensive copy: mutating the result mutates the input. Object key order, prototype, and frozen state are retained. Hidden and symbol members are retained only through an arm with `additionalProperties: true`, because every other object arm refuses them. Copy explicitly if you need an independent result. Primitive and JSON-valued arms, no-match and ambiguous refusals, and the prohibition on defaults under unions keep their existing behavior. A required literal discriminator can still select an arm for coercion.
542
561
 
543
562
  **String bounds count code points.** `min` and `max` on a string count what the `minLength` and `maxLength` the shape emits count, so one astral character has a length of one and a lone surrogate counts as one. `stringOf` and the two reports share `matchesStringLength`, which decides from `.length` where it can: a string holds at most `.length` code points and at least half that. Only where a bound sits between those two figures does it call `computeSurrogatePairs`, which stops as soon as the pairs it has found settle the bound.
544
563
 
@@ -559,6 +578,8 @@ booking.audit({ arrival: '2026-02-30' })
559
578
  booking.schema.properties?.arrival // { type: 'string', format: 'date' }
560
579
  ```
561
580
 
581
+ **Function members.** `functionShape` declares a member that holds a function, such as a callback in an options record. Its guard is `isFunction`, so every callable passes, a class constructor included, and no arity is checked; its parser returns the value by identity. A string sent there reports `upgrade: type; expected function; received "migrate"` through `describeFaults`, and the summary names the member `"upgrade"?: function`. JSON carries no function, so the emitted schema is `{ not: {}, format: 'function' }`, which no JSON instance satisfies: `not` holds the answer for a validator, `format` names the member for a reader, and `description` appears only when you author one. `generate` returns one frozen function, the same one under every seed. `Infer` resolves the member to `(...args: never[]) => unknown`: a `(name: string) => string` callback assigns to it and a call passing `42` does not compile, while a call with no argument still does. A strict `schemaToShape` reads that leaf back as `functionShape()` and refuses every other `not`; a lenient one widens it to `rawShape`.
582
+
562
583
  **Field defaults.** `optionalShape(inner, { default })` lets a declaration state what an absent field reads as. The compiled parser fills the default where the property is absent or `undefined`, through the inner parser, on a fresh copy when the default is a container, so nested defaults apply and two parses share no tree. A default on a `jsonShape`, a `rawShape`, or a union inner reaches you as a frozen copy, because those parsers return their input by identity. `is`, `audit`, `explain`, and `generate` do not read a default: an absent optional stays canonical, so `is({})` is `true`, and `generate` keeps omitting the key or drawing from `inner`. The emitted property schema carries the keyword. `null` is a value and fills; a present `undefined` is a `structure` refusal, because absence is not a value.
563
584
 
564
585
  The builder and `cloneShape` own a frozen copy of a value that passes `isJSONValue`, so a stored shape survives a JSON round trip. Every compiler refuses a default its `inner` guard refuses, refinements included, with code `structure` at `[…path, 'default']`: a restored declaration never met a builder, and `validateShape` judges structure only. A shape holding a default builds the guard family for that check whichever artifact you read first; a shape holding none builds what it always built.
@@ -580,7 +601,7 @@ retries.is({}) // true — an absent optional stays canonical
580
601
  retries.schema.properties?.limit?.default // 3
581
602
  ```
582
603
 
583
- Raw-schema validation is deliberately structural and vocabulary-domain validation, not a full JSON Schema solver. It checks that every keyword is supported, every keyword value has the declared runtime domain, arrays are dense and vocabularies unique where required, every member captured from a present `properties`, dense `anyOf`, or dense `oneOf` population is a plain record, patterns compile, and the graph stays acyclic and within the depth limit. A `default` keyword must hold a JSON value, so a present `undefined` is refused, and neither the node's guard nor its parser reads it. Population is determined by membership, so a present member valued `undefined` is refused rather than erased as absence; omitted optional keywords, plus explicitly `undefined` `items` and `additionalProperties`, retain their absence behavior. It does not resolve cross-keyword contradictions such as `minLength: 5` with `maxLength: 1`, require each `required` name to appear in `properties`, enforce keyword/type coherence, compare `enum` members with `type`, or restrict `format` to a known vocabulary; those semantic interactions remain the responsibility of a full JSON Schema implementation.
604
+ Raw-schema validation is deliberately structural and vocabulary-domain validation, not a full JSON Schema solver. It checks that every keyword is supported, every keyword value has the declared runtime domain, arrays are dense and vocabularies unique where required, every member captured from a present `properties`, dense `anyOf`, or dense `oneOf` population is a plain record, patterns compile, `not` holds the empty schema `{}` alone, and the graph stays acyclic and within the depth limit. A `default` keyword must hold a JSON value, so a present `undefined` is refused, and neither the node's guard nor its parser reads it. Population is determined by membership, so a present member valued `undefined` is refused rather than erased as absence; omitted optional keywords, plus explicitly `undefined` `items` and `additionalProperties`, retain their absence behavior. It does not resolve cross-keyword contradictions such as `minLength: 5` with `maxLength: 1`, require each `required` name to appear in `properties`, enforce keyword/type coherence, compare `enum` members with `type`, or restrict `format` to a known vocabulary; those semantic interactions remain the responsibility of a full JSON Schema implementation.
584
605
 
585
606
  `rawShape` first validates the caller-visible fragment, clones it exactly once, validates that exact owned clone, and returns that same frozen clone. A caller phase change that makes the captured population invalid is therefore refused; a valid captured population is the one published, and failures during the single clone retain the established `cloneSchema` diagnostic.
586
607
 
@@ -596,7 +617,7 @@ The precedence below assumes a readable node and a lenient conversion. A readabl
596
617
 
597
618
  A lenient conversion carries a property's `default` when the key is not in `required`, the object is closed with no union ancestor, and the value is one the property's primitive or literal guard accepts. It drops every other `default`, because a carried default that cannot compile would end the conversion's totality.
598
619
 
599
- **Strict conversion.** `schemaToShape(schema, { strict: true })` is the door for a foreign schema. It refuses, with code `structure` and the keyword's path, what the lenient walk would widen or read past: every node the walk would widen to `rawShape` (an empty schema, a `type` typo at any depth, a non-record child, an array with no `items`, exhausted depth, and a cycle), a keyword outside `STRICT_SCHEMA_KEYWORDS` (`$ref`, `$defs`, `definitions`, `const`, `allOf`, `$anchor`, `$dynamicAnchor`, the `content*` keywords, `nullable`, `discriminator`, `example`, `patternProperties`, `propertyNames`, and `prefixItems`), `pattern` and every `format` but `'date'` on a string node, which no compiled shape asserts, a `format: 'date'` whose length bounds exclude length 10, a malformed keyword value or annotation, a boolean schema, an `enum` entry that is neither a finite primitive nor `null`, a contradictory or malformed bound, a keyword the node's type never reads, a `type` beside a union, a pair of keywords only one of which the walk would keep, an enum member its `type` contradicts, a `required` name not in `properties`, breadth past `INFER_BREADTH_LIMIT`, and a `default` with no optional property to fill or one its schema refuses. `oneOf` keeps exactly-one here, because this walk reads every keyword that could keep two arms apart. An object with no `additionalProperties` closes, unlike JSON Schema's own default, because a misspelled key at a foreign door must reach `audit`; an explicit `true` or schema value stays open. Below a `oneOf` it refuses instead, at any depth, because closing it could change which arms match: two arms declaring optional `a` and `b` both match `{ a: 'x' }` as written, and only one does once closed. It accepts the annotations a schema generator emits, which assert nothing and which the shape drops: `title`, `$schema`, `$id`, and `$comment` when strings, `examples` when an array, and `deprecated`, `readOnly`, and `writeOnly` when booleans. A default under a union or on an open object refuses with `placement` at its path in the schema, ending `properties`, the key, and `default`.
620
+ **Strict conversion.** `schemaToShape(schema, { strict: true })` is the door for a foreign schema. It refuses, with code `structure` and the keyword's path, what the lenient walk would widen or read past: every node the walk would widen to `rawShape` (an empty schema, a `type` typo at any depth, a non-record child, an array with no `items`, exhausted depth, and a cycle), a keyword outside `STRICT_SCHEMA_KEYWORDS` (`$ref`, `$defs`, `definitions`, `const`, `allOf`, `$anchor`, `$dynamicAnchor`, the `content*` keywords, `nullable`, `discriminator`, `example`, `patternProperties`, `propertyNames`, and `prefixItems`), `pattern` and every `format` but `'date'` on a string node and `'function'` beside `not: {}`, which no compiled shape asserts, every `not` outside that function leaf, a keyword beside the leaf other than its annotations and a `default`, a `format: 'date'` whose length bounds exclude length 10, a malformed keyword value or annotation, a boolean schema, an `enum` entry that is neither a finite primitive nor `null`, a contradictory or malformed bound, a keyword the node's type never reads, a `type` beside a union, a pair of keywords only one of which the walk would keep, an enum member its `type` contradicts, a `required` name not in `properties`, breadth past `INFER_BREADTH_LIMIT`, and a `default` with no optional property to fill or one its schema refuses. `oneOf` keeps exactly-one here, because this walk reads every keyword that could keep two arms apart. An object with no `additionalProperties` closes, unlike JSON Schema's own default, because a misspelled key at a foreign door must reach `audit`; an explicit `true` or schema value stays open. Below a `oneOf` it refuses instead, at any depth, because closing it could change which arms match: two arms declaring optional `a` and `b` both match `{ a: 'x' }` as written, and only one does once closed. It accepts the annotations a schema generator emits, which assert nothing and which the shape drops: `title`, `$schema`, `$id`, and `$comment` when strings, `examples` when an array, and `deprecated`, `readOnly`, and `writeOnly` when booleans. A default under a union or on an open object refuses with `placement` at its path in the schema, ending `properties`, the key, and `default`.
600
621
 
601
622
  **Round-trip law:** for any READABLE value `v` — including `NaN`, `±Infinity`, a `Map`, a `Set`, a class instance, a function, a symbol, a bigint, and readable cyclic hosts — `compileGuard(schemaToShape(valueToSchema(v)))(v) === true`, with widening as the ONLY source of looseness, never narrowing. An unreadable host is refused before the law produces a schema. The law otherwise retains its three limits: JSON absence, `Date` serialization, and unstable reads between inference and validation. A widened node cannot be auto-generated: `createContract(schemaToShape(x)).generate()` throws when the conversion widened anywhere; its parser returns `undefined` for readable invalid input and propagates the shared coded refusal when a required read fails.
602
623
 
@@ -617,42 +638,44 @@ contract.parse({ id: 'nope', name: 'x' }) // undefined
617
638
  A resolver whose value is a multi-branch conditional carries none, and its `Summary` states
618
639
  what the resolution produces.
619
640
 
620
- | Name | Kind | Signature | Summary |
621
- | ---------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
622
- | `ContractShape` | type | `StringShape \| NumberShape \| BooleanShape \| NullShape \| LiteralShape \| ArrayShape \| ObjectShape \| UnionShape \| OptionalShape \| NullableShape \| JSONShape \| ShapeShape \| RawShape` | Describes a value declaratively — a declaration the shape builders build and the compilers turn into a guard, a parser, a JSON Schema, and a generator. |
623
- | `StringShape` | interface | `{ category, min?, max?, pattern?, date?, description? }` | Describes a string with optional length, pattern, and calendar-date constraints. |
624
- | `NumberShape` | interface | `{ category, min?, max?, integer?, description? }` | Describes a number with optional bounds; `integer` restricts to whole numbers. |
625
- | `BooleanShape` | interface | `{ category, description? }` | Describes a boolean — accepts only `true` or `false`. |
626
- | `NullShape` | interface | `{ category, description? }` | Describes a null value — accepts only `null`. |
627
- | `LiteralShape` | interface | `{ category, values, description? }` | Describes a literal — accepts exactly one of a fixed set of primitive values. |
628
- | `ArrayShape` | interface | `{ category, items, min?, max?, description? }` | Describes an array with an element shape and optional length bounds. |
629
- | `ObjectShape` | interface | `{ category, properties, additionalProperties?, description? }` | Describes an object — a map of property names to child shapes. |
630
- | `UnionShape` | interface | `{ category, variants, mode?, description? }` | Describes a union — accepts a value matching any one variant (first match wins). |
631
- | `OptionalShape` | interface | `{ category, inner, default? }` | Wraps an inner shape that may be absent (`undefined`). |
632
- | `NullableShape` | interface | `{ category, inner }` | Wraps an inner shape that may be `null`. |
633
- | `JSONShape` | interface | `{ category, description? }` | Describes a JSON passthrough — accepts any JSON value. |
634
- | `RawShape` | interface | `{ category, schema }` | Describes a validated raw JSON Schema passthrough — embeds a supported schema fragment directly. |
635
- | `Infer` | type | `[ContractShape] extends [S] ? unknown : S extends ShapeShape ? ContractShape : S extends StringShape ? string : S extends NumberShape ? number : S extends BooleanShape ? boolean : S extends NullShape ? null : S extends { readonly category: 'literal'; readonly values: infer V; } ? V extends ReadonlyArray<infer L> ? L : never : S extends { readonly category: 'array'; readonly items: infer I; } ? I extends ContractShape ? ReadonlyArray<Infer<I>> : never : S extends ObjectShape<infer P, infer A> ? P extends Readonly<Record<string, ContractShape>> ? [A] extends [boolean \| ContractShape] ? InferObject<P, A> : never : never : S extends { readonly category: 'union'; readonly variants: infer V; } ? V extends readonly ContractShape[] ? InferUnion<V> : never : S extends { readonly category: 'optional'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> \| undefined : never : S extends { readonly category: 'nullable'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> \| null : never : S extends JSONShape ? JSONValue : unknown` | Resolves the static TypeScript type a `ContractShape` describes. |
636
- | `InferObject` | type | `[keyof P] extends [never] ? [A] extends [false] ? Readonly<Record<never, never>> : InferIndex<A> : Readonly<{ [K in keyof P as P[K] extends { readonly category: 'optional'; } ? never : K]: Infer<P[K]>; } & { [K in keyof P as P[K] extends { readonly category: 'optional'; } ? K : never]?: P[K] extends { readonly category: 'optional'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> : never : never; }> & InferOpenIndex<A>` | Resolves `Infer` of an object shape's `properties` — the required keys, plus the `optional`-wrapped keys as optional members, plus the index-signature contribution of `additionalProperties` (see `InferIndex`). |
637
- | `InferIndex` | type | `[A] extends [false] ? unknown : [A] extends [true] ? { readonly [k: string]: unknown; } : [A] extends [ContractShape] ? { readonly [k: string]: Infer<A>; } : unknown` | Computes the index-signature contribution of a pure record shape's `additionalProperties` — the `recordShape` case, where `properties` is empty. |
638
- | `InferOpenIndex` | type | `[A] extends [false] ? unknown : [A] extends [true] ? { readonly [k: string]: unknown; } : [A] extends [ContractShape] ? { readonly [k: string]: unknown; } : unknown` | Computes the index-signature contribution of a MIXED object shape's `additionalProperties` — one with both fixed `properties` and an open tail. |
639
- | `InferMutable` | type | `{ -readonly [K in keyof Infer<S>]: Infer<S>[K]; }` | Strips the TOP-LEVEL `readonly` modifiers from `Infer` (a shallow strip — nested object/array properties stay readonly) — for consumers writing the parsed value's own fields. |
640
- | `InferUnion` | type | `V extends ReadonlyArray<infer U> ? (U extends ContractShape ? Infer<U> : never) : never` | Resolves `Infer` of a union shape's `variants` — the union of each variant's inferred type. |
641
- | `StringShapeOptions` | interface | `{ min?, max?, pattern?, date?, description? }` | Groups the options for `StringShape` (through `stringShape`). |
642
- | `NumberShapeOptions` | interface | `{ min?, max?, integer?, description? }` | Groups the options for `NumberShape` (through `numberShape` / `integerShape`). |
643
- | `BooleanShapeOptions` | interface | `{ description? }` | Groups the options for `BooleanShape` (through `booleanShape`). |
644
- | `NullShapeOptions` | interface | `{ description? }` | Groups the options for `NullShape` (through `nullShape`). |
645
- | `JSONShapeOptions` | interface | `{ description? }` | Groups the options for `JSONShape` (through `jsonShape`). |
646
- | `LiteralShapeOptions` | interface | `{ description? }` | Groups the options for `LiteralShape` (through `literalShape`). |
647
- | `ArrayShapeOptions` | interface | `{ min?, max?, description? }` | Groups the options for `ArrayShape` (through `arrayShape`). |
648
- | `ObjectShapeOptions` | interface | `{ additionalProperties?, description? }` | Groups the options for `ObjectShape` (through `objectShape`). |
649
- | `RecordShapeOptions` | interface | `{ description? }` | Groups the options for record shapes (through `recordShape`). |
650
- | `OptionalShapeOptions` | interface | `{ default? }` | Groups the options for `OptionalShape` (through `optionalShape`). |
651
- | `SchemaToShapeOptions` | interface | `{ strict? }` | Groups the options for converting a JSON Schema (through `schemaToShape`). |
641
+ | Name | Kind | Signature | Summary |
642
+ | ---------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
643
+ | `ContractShape` | type | `StringShape \| NumberShape \| BooleanShape \| NullShape \| LiteralShape \| ArrayShape \| ObjectShape \| UnionShape \| OptionalShape \| NullableShape \| JSONShape \| ShapeShape \| FunctionShape \| RawShape` | Describes a value declaratively — a declaration the shape builders build and the compilers turn into a guard, a parser, a JSON Schema, and a generator. |
644
+ | `StringShape` | interface | `{ category, min?, max?, pattern?, date?, description? }` | Describes a string with optional length, pattern, and calendar-date constraints. |
645
+ | `NumberShape` | interface | `{ category, min?, max?, integer?, description? }` | Describes a number with optional bounds; `integer` restricts to whole numbers. |
646
+ | `BooleanShape` | interface | `{ category, description? }` | Describes a boolean — accepts only `true` or `false`. |
647
+ | `NullShape` | interface | `{ category, description? }` | Describes a null value — accepts only `null`. |
648
+ | `LiteralShape` | interface | `{ category, values, description? }` | Describes a literal — accepts exactly one of a fixed set of primitive values. |
649
+ | `ArrayShape` | interface | `{ category, items, min?, max?, description? }` | Describes an array with an element shape and optional length bounds. |
650
+ | `ObjectShape` | interface | `{ category, properties, additionalProperties?, description? }` | Describes an object — a map of property names to child shapes. |
651
+ | `UnionShape` | interface | `{ category, variants, mode?, description? }` | Describes a union — accepts a value matching any one variant (first match wins). |
652
+ | `OptionalShape` | interface | `{ category, inner, default? }` | Wraps an inner shape that may be absent (`undefined`). |
653
+ | `NullableShape` | interface | `{ category, inner }` | Wraps an inner shape that may be `null`. |
654
+ | `JSONShape` | interface | `{ category, description? }` | Describes a JSON passthrough — accepts any JSON value. |
655
+ | `FunctionShape` | interface | `{ category, description? }` | Describes a callable value — accepts every function, a class constructor included. |
656
+ | `RawShape` | interface | `{ category, schema }` | Describes a validated raw JSON Schema passthrough — embeds a supported schema fragment directly. |
657
+ | `Infer` | type | `[ContractShape] extends [S] ? unknown : S extends ShapeShape ? ContractShape : S extends FunctionShape ? (...args: never[]) => unknown : S extends StringShape ? string : S extends NumberShape ? number : S extends BooleanShape ? boolean : S extends NullShape ? null : S extends { readonly category: 'literal'; readonly values: infer V; } ? V extends ReadonlyArray<infer L> ? L : never : S extends { readonly category: 'array'; readonly items: infer I; } ? I extends ContractShape ? ReadonlyArray<Infer<I>> : never : S extends ObjectShape<infer P, infer A> ? P extends Readonly<Record<string, ContractShape>> ? [A] extends [boolean \| ContractShape] ? InferObject<P, A> : never : never : S extends { readonly category: 'union'; readonly variants: infer V; } ? V extends readonly ContractShape[] ? InferUnion<V> : never : S extends { readonly category: 'optional'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> \| undefined : never : S extends { readonly category: 'nullable'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> \| null : never : S extends JSONShape ? JSONValue : unknown` | Resolves the static TypeScript type a `ContractShape` describes. |
658
+ | `InferObject` | type | `[keyof P] extends [never] ? [A] extends [false] ? Readonly<Record<never, never>> : InferIndex<A> : Readonly<{ [K in keyof P as P[K] extends { readonly category: 'optional'; } ? never : K]: Infer<P[K]>; } & { [K in keyof P as P[K] extends { readonly category: 'optional'; } ? K : never]?: P[K] extends { readonly category: 'optional'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> : never : never; }> & InferOpenIndex<A>` | Resolves `Infer` of an object shape's `properties` — the required keys, plus the `optional`-wrapped keys as optional members, plus the index-signature contribution of `additionalProperties` (see `InferIndex`). |
659
+ | `InferIndex` | type | `[A] extends [false] ? unknown : [A] extends [true] ? { readonly [k: string]: unknown; } : [A] extends [ContractShape] ? { readonly [k: string]: Infer<A>; } : unknown` | Computes the index-signature contribution of a pure record shape's `additionalProperties` — the `recordShape` case, where `properties` is empty. |
660
+ | `InferOpenIndex` | type | `[A] extends [false] ? unknown : [A] extends [true] ? { readonly [k: string]: unknown; } : [A] extends [ContractShape] ? { readonly [k: string]: unknown; } : unknown` | Computes the index-signature contribution of a MIXED object shape's `additionalProperties` — one with both fixed `properties` and an open tail. |
661
+ | `InferMutable` | type | `{ -readonly [K in keyof Infer<S>]: Infer<S>[K]; }` | Strips the TOP-LEVEL `readonly` modifiers from `Infer` (a shallow strip — nested object/array properties stay readonly) — for consumers writing the parsed value's own fields. |
662
+ | `InferUnion` | type | `V extends ReadonlyArray<infer U> ? (U extends ContractShape ? Infer<U> : never) : never` | Resolves `Infer` of a union shape's `variants` — the union of each variant's inferred type. |
663
+ | `StringShapeOptions` | interface | `{ min?, max?, pattern?, date?, description? }` | Groups the options for `StringShape` (through `stringShape`). |
664
+ | `NumberShapeOptions` | interface | `{ min?, max?, integer?, description? }` | Groups the options for `NumberShape` (through `numberShape` / `integerShape`). |
665
+ | `BooleanShapeOptions` | interface | `{ description? }` | Groups the options for `BooleanShape` (through `booleanShape`). |
666
+ | `NullShapeOptions` | interface | `{ description? }` | Groups the options for `NullShape` (through `nullShape`). |
667
+ | `JSONShapeOptions` | interface | `{ description? }` | Groups the options for `JSONShape` (through `jsonShape`). |
668
+ | `FunctionShapeOptions` | interface | `{ description? }` | Configures the description of a function-valued declaration. |
669
+ | `LiteralShapeOptions` | interface | `{ description? }` | Groups the options for `LiteralShape` (through `literalShape`). |
670
+ | `ArrayShapeOptions` | interface | `{ min?, max?, description? }` | Groups the options for `ArrayShape` (through `arrayShape`). |
671
+ | `ObjectShapeOptions` | interface | `{ additionalProperties?, description? }` | Groups the options for `ObjectShape` (through `objectShape`). |
672
+ | `RecordShapeOptions` | interface | `{ description? }` | Groups the options for record shapes (through `recordShape`). |
673
+ | `OptionalShapeOptions` | interface | `{ default? }` | Groups the options for `OptionalShape` (through `optionalShape`). |
674
+ | `SchemaToShapeOptions` | interface | `{ strict? }` | Groups the options for converting a JSON Schema (through `schemaToShape`). |
652
675
 
653
676
  ### Compilers
654
677
 
655
- Turn one `ContractShape` into the six lockstep outputs — `schema` / `is` / `parse` / `audit` / `explain` / `generate` (`src/core/compilers.ts`). `createContract` is the one door in this section that returns an entity rather than a compiled projection, so it lives in `src/core/factories.ts` over the same engine. Two engines sit under those functions. `ShapeValidator` owns the sole stateful declaration walk; `validateShape` constructs a fresh validator as its eager function boundary, while `cloners.ts`, `ShapeCloner`, and the shape builders use the class directly so lower validation no longer imports the compiler module. `ContractCompiler` owns ownership, preparation, and the six artifact families; every function in this section is a real typed door over it that requests exactly the root it is named for, so asking for a guard never compiles a generator. LOCKSTEP here means DERIVED FROM ONE SNAPSHOT, not equal in what they accept: `createContract` compiles all six from a single owned copy of the declaration, so no later edit to the shape you passed can move one of them without the others. It does not mean the six accept the same values — deliberately, they do not (see Domains, below). The individual compilers return untyped runtime functions; `createContract` is the typed entry point — its `is` / `parse` / `generate` carry `Infer<S>` by inferring once, at the boundary (so the recursion stays cheap). `compileGuard` / `compileParser` / `compileReporter` / `compileAuditor` reuse the existing combinators and parsers rather than re-implementing them: `literalOf` IS the literal match at all four (one SameValueZero implementation, taking its vocabulary as an array), and each leaf's refinements (`min` / `max` / `pattern`) are read off the one shape node rather than restated per artifact — `compileGuard` and `compileParser` compose them through the **same** combinators (`stringOf` for a string's length and pattern, `boundsOf` for a number's value and an array's length), while `compileReporter` and `compileAuditor` check those same three against that same node inline, so each violated refinement can carry its own fault; the pattern test is the same flag-stripped owned `RegExp` in every artifact (`matchOf` for the two reports, the identical construction inside `stringOf` for the guard and parser). No artifact — not `compileGuard`, not `compileParser`, not `compileReporter`, not `compileAuditor` — holds a bound of its own to drift from the other three. What the four do NOT share is the leaf TYPE test: `compileGuard` and `compileAuditor` demand a `string`, `compileParser` and `compileReporter` accept whatever `parseString` coerces — which is where the two domains part company. Every entry point reaches the same declaration-rule set through validation or ownership, and `cloneShape` asks that claim of the carried cloned root after its node fields have completed descriptor/two-read capture and its property map has completed its separate enumeration and child-capture checks. The validator mirrors the ownership boundary by rejecting ordinary declared-field accessors before `Reflect.get`, while preserving the documented `pattern` exception. No entry can therefore launder a malformed property/variant/value container, discriminant, scalar accessor, vocabulary, raw-schema child, or structural child into a plausible contract. Every compiled object artifact — guard, parser, reporter, auditor, and the inference direction too — reads an object through the one `enumerableKeys` property view (own enumerable string keys, the set `JSON.stringify` serializes), so all of them see the SAME key set. What each does with an undeclared key in that set differs by design: for a CLOSED object `is` rejects the object, `audit` reports an `'extra'` fault at the key, `parse` drops the key WITHOUT reading it, `explain` says nothing about it, and `schema` forbids it with `additionalProperties: false`. For an OPEN one they all READ it, including under `additionalProperties: true` where nothing constrains the value: open means unconstrained, not unobserved, and the parser copies every such key into its result. Skipping that read on three of the four doors is how `is`, `audit` and `explain` all certified a value clean that `parse` then refused as unreadable.
678
+ Turn one `ContractShape` into the six lockstep outputs — `schema` / `is` / `parse` / `audit` / `explain` / `generate` (`src/core/compilers.ts`). `createContract` is the one door in this section that returns an entity rather than a compiled projection, so it lives in `src/core/factories.ts` over the same engine. Two engines sit under those functions. `ShapeValidator` owns the sole stateful declaration walk; `validateShape` constructs a fresh validator as its eager function boundary, while `cloners.ts`, `ShapeCloner`, and the shape builders use the class directly so lower validation no longer imports the compiler module. `ContractCompiler` owns ownership, preparation, and the six artifact families; every function in this section is a real typed door over it that requests exactly the root it is named for, so asking for a guard never compiles a generator. LOCKSTEP here means DERIVED FROM ONE SNAPSHOT, not equal in what they accept: `createContract` compiles all six from a single owned copy of the declaration, so no later edit to the shape you passed can move one of them without the others. It does not mean the six accept the same values — deliberately, they do not (see Domains, below). The individual compilers return untyped runtime functions; `createContract` is the typed entry point — its `is` / `parse` / `generate` carry `Infer<S>` by inferring once, at the boundary (so the recursion stays cheap). `compileGuard` / `compileParser` / `compileReporter` / `compileAuditor` reuse the existing combinators and parsers rather than re-implementing them: `literalOf` IS the literal match at all four (one SameValueZero implementation, taking its vocabulary as an array), and each leaf's refinements (`min` / `max` / `pattern`) are read off the one shape node rather than restated per artifact — `compileGuard` and `compileParser` compose them through the **same** combinators (`stringOf` for a string's length and pattern, `boundsOf` for a number's value and an array's length), while `compileReporter` and `compileAuditor` check those same three against that same node inline, so each violated refinement can carry its own fault; the pattern test is the same flag-stripped owned `RegExp` in every artifact (`matchOf` for the two reports, the identical construction inside `stringOf` for the guard and parser). No artifact — not `compileGuard`, not `compileParser`, not `compileReporter`, not `compileAuditor` — holds a bound of its own to drift from the other three. What the four do NOT share is the leaf TYPE test: `compileGuard` and `compileAuditor` demand a `string`, `compileParser` and `compileReporter` accept whatever `parseString` coerces — which is where the two domains part company. Every entry point reaches the same declaration-rule set through validation or ownership, and `cloneShape` asks that claim of the carried cloned root after its node fields have completed descriptor/two-read capture and its property map has completed its separate enumeration and child-capture checks. The validator mirrors the ownership boundary by rejecting ordinary declared-field accessors before `Reflect.get`, while preserving the documented `pattern` exception. No entry can therefore launder a malformed property/variant/value container, discriminant, scalar accessor, vocabulary, raw-schema child, or structural child into a plausible contract. Every compiled object artifact — guard, parser, reporter, auditor, and the inference direction too — reads an object through the one `enumerableKeys` property view (own enumerable string keys, the set `JSON.stringify` serializes), so all of them see the SAME enumerable key set; the guard and the auditor of a closed or tail-shaped object also read its own names and symbols. Those two refuse and report an own member outside that view, a non-enumerable string key or a symbol key, while `parse` and `explain` keep the view: `is` answers `false`, `audit` reports a declared such member as `'hidden'` where `explain` reports `'missing'`, an undeclared one as `'extra'` when closed and `'hidden'` under a tail shape, and each symbol key as `'extra'` at the object with `symbol` naming it. An object with `additionalProperties: true` runs no own-key count: it admits an undeclared non-enumerable or symbol member, while a declared member outside the enumerable view still reads as absent, so `is` answers `false` for a required one and `audit` and `explain` report it `'missing'`. What each does with an undeclared key in that set differs by design: for a CLOSED object `is` rejects the object, `audit` reports an `'extra'` fault at the key, `parse` drops the key WITHOUT reading it, `explain` says nothing about it, and `schema` forbids it with `additionalProperties: false`. For an OPEN one they all READ it, including under `additionalProperties: true` where nothing constrains the value: open means unconstrained, not unobserved, and the parser copies every such key into its result. Skipping that read on three of the four doors is how `is`, `audit` and `explain` all certified a value clean that `parse` then refused as unreadable.
656
679
 
657
680
  | Name | Kind | Signature | Summary |
658
681
  | --------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
@@ -675,6 +698,14 @@ Turn one `ContractShape` into the six lockstep outputs — `schema` / `is` / `pa
675
698
  | `COMPILE_DEPTH_LIMIT` | const | `512` | Caps at `512` the supported nesting depth of a compiled contract shape, frozen. |
676
699
  | `COMPILE_NODE_LIMIT` | const | `16384` | Caps at `16384` the number of nodes a compiled artifact may expand a shape into, frozen. |
677
700
  | `PRESENCE_MASK_LIMIT` | const | `31` | Caps at `31` the number of object keys one compiled presence mask carries, frozen. |
701
+ | `KEY_PLAN_LIMIT` | const | `4` | Caps at `4` the number of key plans one compiled closed-object guard keeps, frozen. |
702
+ | `KeyStep` | interface | `{ key, guard }` | Represents one step of a key plan: a declared key and the compiled guard its member answers to. |
703
+ | `buildKeyPlan` | function | `(keys: readonly string[], guards: Readonly<Record<string, Guard<unknown> \| undefined>>) => readonly KeyStep[] \| undefined` | Builds the key plan that answers one key order from the declared member guards. |
704
+ | `matchesKeyPlan` | function | `(this: readonly string[], plan: readonly KeyStep[]) => boolean` | Checks whether a key plan answers the key list bound as `this`. |
705
+ | `matchesStepKey` | function | `(this: readonly string[], step: KeyStep, index: number) => boolean` | Checks whether a key-plan step names the key at its index in the list bound as `this`. |
706
+ | `matchesStepGuard` | function | `(this: Readonly<Record<string, unknown>>, step: KeyStep) => boolean` | Checks whether the member of the record bound as `this` passes a key-plan step's guard. |
707
+
708
+ A compiled closed-object guard keeps the plans of the key orders it accepts until it holds `KEY_PLAN_LIMIT` plans, and answers every other key order through the full walk. A plan is one `KeyStep` entry per key, in the order the value listed its own enumerable keys, and the `buildKeyPlan` helper builds it after a walk that accepted. Every call counts the value's own names and symbols first, on a hit as on a miss, because that check runs before the guard looks for a kept plan. A later value whose keys arrive in a kept order is answered by asking each step's guard in turn, through the captured `every` member with the `matchesStepGuard` predicate and the value as the `thisArg` argument; the `matchesKeyPlan` and `matchesStepKey` predicates find the kept plan the same way. The guard learns nothing from a refused call and never evicts a plan, so the kept plans are those of the earliest accepted key orders; both paths read the same members in the same order and answer alike, and only the cost differs. A tail-shaped object keeps no plans, because a dictionary's key list is data: it takes the full walk and the own-key count on every call.
678
709
 
679
710
  `ContractCompilerInterface` declares no call-signature member, so it has no Methods table: its
680
711
  whole surface is the readonly data properties — `schema` (a `JSONSchema`), `guard` (a
@@ -685,7 +716,7 @@ whole surface is the readonly data properties — `schema` (a `JSONSchema`), `gu
685
716
  value the corresponding getter publishes — `contract.is` is exactly `compiler.guard`, by
686
717
  identity rather than as a copy of it.
687
718
 
688
- Compilation costs ONE ownership and ONE validation per call, not one per node. Every `compile*` entry and `createContract` construct a `ContractCompiler`, which owns the declaration once, validates that owned graph once, and indexes each unique node and structural edge once; the artifact families are postorder passes over that index. A builder records what it validated, so wrapping a built child observes only the new node, and a declaration made entirely by builders is compiled as it stands, with no snapshot and no walk. A hand-written node anywhere in the graph, or a field a node may leave out appearing on `Object.prototype`, takes the whole walk instead, and that walk authors every refusal, so a refusal reads the same and fires at the same call either way. This is what replaced the arrangement where each recursive invocation re-ran `ownShape` AND `validateShape` over the subgraph it received — quadratic work for a linear declaration, and the reason a 129-node depth chain used to measure 6.3 ms of gate plus 7.9 ms of ownership and a 257-node chain 26.0 + 41.9 ms. A 30-alias depth-100 declaration now compiles a guard in 3 ms and a whole contract in 4 ms, against 640 ms and 1.87 s before. Every artifact compiles once, so `audit`, `explain` and `generate` re-walk and re-gate nothing on a later call either; `contract.audit` and `compileAuditor` run the same compiled plan reached by different names. A union whose arms are all objects declaring a required literal property answers through one arm when a value's own property exactly equals a literal only that arm holds: `explain` and `audit` report that arm's faults at their real paths in place of `variant`, and `parse` repairs through it alone, so `{ operation: 'find', limit: '5' }` parses to `limit: 5` however many arms precede it. No other arm's guard could accept that value, so the three laws hold and `is` does not change. A value that names no one arm, because its property is absent, matches no literal, or matches one two arms share, keeps `variant` or `oneOf`, with `key` and `expected` naming the property and what it may hold. `oneOfShape` behaves the same way: its parser refuses to coerce only because an ambiguous value has no target, and a named arm is one. An arm that is not an object, a discriminator that is optional or inside a nullable, and a nested union all change nothing at that union. `createContract` over a declaration made entirely by builders compiles its schema at that call and its function members together on the first call to any of them, so a module can declare contracts as data and pay only for the ones it uses; any other declaration, and a bare leaf, compiles every member at that call. Every refusal a declaration can earn still fires at `createContract` either way, because preparation and the schema ask them all, and each member is one plain function, so destructuring and spreading compile nothing. A member compiling after the call reads its declaration through own fields, so a field added to `Object.prototype` since cannot reach it. A host member replaced since is the one thing that can stop it: compiling there would outlive the replacement, so the member refuses to compile until the host is restored, with its guard answering `false`, its parser `undefined`, and its diagnostics and generator refusing, and the next call on a restored host compiles as usual. A first call near the stack limit recovers the same way. A compiled artifact is no longer a TREE either. Each family holds one entry per unique node and a parent points at its children, so a shared child is compiled once and the emitted schema preserves that sharing — which is why the cap boundary stopped being expensive: `createContract` over the two-edge-per-level DAG at the 16,383-node boundary now takes under a millisecond where it took 1,342 ms, because it compiles fourteen nodes rather than sixteen thousand. Cost tracks AUTHORED nodes and edges instead: measured here, a depth-100 chain and a 30-alias depth-100 staircase answer every door in 1–5 ms, and a flat 10,001-node object takes 52–68 ms per artifact and 110 ms for a whole contract. One level past the cap boundary — 32,767 emitted nodes over thirty-one authored ones — still refuses in about two milliseconds with code `expansion`, because the count is measured over the captured graph rather than by walking the expansion. What the cap now protects is the consumer's side of the artifacts rather than the compiler's: `generate` materializes the whole tree, and so does serializing the schema. The JSON cloner is capped for the opposite reason — it DUPLICATES a shared alias by contract rather than re-walking it: see `CLONE_NODE_LIMIT`. The `samplesToSchema` family is not on this list and was never meant to be reachable: its record path carried neither an ancestor set nor a memo, so an ordinary shared reference bought `k^depth` visits; it now memoizes a single-row slot on `(row, remaining depth)` exactly as the record branch of `valueToSchema` does. Everything above is the DECLARATION side, and for one release that was the only side measured. A compiled artifact applies each child artifact once per OCCURRENCE, which is right for a tree and wrong for a graph, so a value whose levels each held two references to one object was walked once per PATH: twenty-two shared arrays against a twenty-three-node chain of `arrayShape` — zero aliases in the declaration, every published limit satisfied — cost 524,286 node reads, 4.4 s for `is` and 8.4 s for `audit`, growing fourfold per two levels, while the same declaration over a TREE value answered instantly and `valueToSchema` answered the same graph in 4 ms because it already memoized. The verdict families now carry a per-CALL identity memo keyed by `(compiled node, value object)`, and the same value now costs thirty-six reads and under a millisecond. These details are exact rather than incidental. The guard reuses either answer while the auditor and reporter reuse only the CLEAN one, because a fault carries the path it was found at and emptiness carries nothing — a faulted node is re-walked and bounded by `FAULT_LIMIT` instead. The active synchronous call owns each node's memo and releases the scope on settlement, so an answer never survives into a later call where the caller may have changed the value. And a leaf is not tracked at all: it descends into no child, so tracking one would buy nothing and would replace the package's own guards and parsers in the artifacts a leaf-rooted declaration publishes. `parse` is deliberately absent from that list, because its result IS the expansion; the threat model names what that costs.
719
+ Compilation costs ONE ownership and ONE validation per call, not one per node. Every `compile*` entry and `createContract` construct a `ContractCompiler`, which owns the declaration once, validates that owned graph once, and indexes each unique node and structural edge once; the artifact families are postorder passes over that index. A builder records what it validated, so wrapping a built child observes only the new node, and a declaration made entirely by builders is compiled as it stands, with no snapshot and no walk. A hand-written node anywhere in the graph, or a field a node may leave out appearing on `Object.prototype`, takes the whole walk instead, and that walk authors every refusal, so a refusal reads the same and fires at the same call either way. This is what replaced the arrangement where each recursive invocation re-ran `ownShape` AND `validateShape` over the subgraph it received — quadratic work for a linear declaration, and the reason a 129-node depth chain used to measure 6.3 ms of gate plus 7.9 ms of ownership and a 257-node chain 26.0 + 41.9 ms. A 30-alias depth-100 declaration now compiles a guard in 3 ms and a whole contract in 4 ms, against 640 ms and 1.87 s before. Every artifact compiles once, so `audit`, `explain` and `generate` re-walk and re-gate nothing on a later call either; `contract.audit` and `compileAuditor` run the same compiled plan reached by different names. A union whose arms are all objects declaring a required literal property answers through one arm when a value's own property exactly equals a literal only that arm holds: `explain` and `audit` report that arm's faults at their real paths in place of `variant`, and `parse` repairs through it alone, so `{ operation: 'find', limit: '5' }` parses to `limit: 5` however many arms precede it. `is` answers from that arm alone as well, in both modes, so `is`, `parse`, `audit`, and `explain` agree on that value and the three laws hold. When the property reads as its own descriptor states, no other arm's guard could accept that value, so `is` answers as every arm would, and an accepted or refused value costs one arm rather than every arm. A value that names no one arm, because its property is absent, matches no literal, or matches one two arms share, keeps `variant` or `oneOf`, with `key` and `expected` naming the property and what it may hold. `oneOfShape` behaves the same way: its parser refuses to coerce only because an ambiguous value has no target, and a named arm is one. An arm that is not an object, a discriminator that is optional or inside a nullable, and a nested union all change nothing at that union. `createContract` over a declaration made entirely by builders compiles its schema at that call and its function members together on the first call to any of them, so a module can declare contracts as data and pay only for the ones it uses; any other declaration, and a bare leaf, compiles every member at that call. Every refusal a declaration can earn still fires at `createContract` either way, because preparation and the schema ask them all, and each member is one plain function, so destructuring and spreading compile nothing. A member compiling after the call reads its declaration through own fields, so a field added to `Object.prototype` since cannot reach it. A host member replaced since is the one thing that can stop it: compiling there would outlive the replacement, so the member refuses to compile until the host is restored, with its guard answering `false`, its parser `undefined`, and its diagnostics and generator refusing, and the next call on a restored host compiles as usual. A first call near the stack limit recovers the same way. A compiled artifact is no longer a TREE either. Each family holds one entry per unique node and a parent points at its children, so a shared child is compiled once and the emitted schema preserves that sharing — which is why the cap boundary stopped being expensive: `createContract` over the two-edge-per-level DAG at the 16,383-node boundary now takes under a millisecond where it took 1,342 ms, because it compiles fourteen nodes rather than sixteen thousand. Cost tracks AUTHORED nodes and edges instead: measured here, a depth-100 chain and a 30-alias depth-100 staircase answer every door in 1–5 ms, and a flat 10,001-node object takes 52–68 ms per artifact and 110 ms for a whole contract. One level past the cap boundary — 32,767 emitted nodes over thirty-one authored ones — still refuses in about two milliseconds with code `expansion`, because the count is measured over the captured graph rather than by walking the expansion. What the cap now protects is the consumer's side of the artifacts rather than the compiler's: `generate` materializes the whole tree, and so does serializing the schema. The JSON cloner is capped for the opposite reason — it DUPLICATES a shared alias by contract rather than re-walking it: see `CLONE_NODE_LIMIT`. The `samplesToSchema` family is not on this list and was never meant to be reachable: its record path carried neither an ancestor set nor a memo, so an ordinary shared reference bought `k^depth` visits; it now memoizes a single-row slot on `(row, remaining depth)` exactly as the record branch of `valueToSchema` does. Everything above is the DECLARATION side, and for one release that was the only side measured. A compiled artifact applies each child artifact once per OCCURRENCE, which is right for a tree and wrong for a graph, so a value whose levels each held two references to one object was walked once per PATH: twenty-two shared arrays against a twenty-three-node chain of `arrayShape` — zero aliases in the declaration, every published limit satisfied — cost 524,286 node reads, 4.4 s for `is` and 8.4 s for `audit`, growing fourfold per two levels, while the same declaration over a TREE value answered instantly and `valueToSchema` answered the same graph in 4 ms because it already memoized. The verdict families now carry a per-CALL identity memo keyed by `(compiled node, value object)`, and the same value now costs thirty-six reads and under a millisecond. These details are exact rather than incidental. The guard reuses either answer while the auditor and reporter reuse only the CLEAN one, because a fault carries the path it was found at and emptiness carries nothing — a faulted node is re-walked and bounded by `FAULT_LIMIT` instead. The active synchronous call owns each node's memo and releases the scope on settlement, so an answer never survives into a later call where the caller may have changed the value. And a leaf is not tracked at all: it descends into no child, so tracking one would buy nothing and would replace the package's own guards and parsers in the artifacts a leaf-rooted declaration publishes. `parse` is deliberately absent from that list, because its result IS the expansion; the threat model names what that costs.
689
720
 
690
721
  String and array length bounds deliberately use the builders' FULL rule — every present bound is a non-negative safe integer — rather than merely checking finiteness. A finiteness-only gate would close the `NaN` / infinity bypass but still admit hand-authored negative, fractional, and unsafe-integer length keywords that no builder can produce and that are not valid JSON Schema length bounds. Matching the builders costs compatibility only for those already-malformed hand-authored shapes; it preserves every legitimate builder output and keeps guard, parser, audit, and schema semantics on one domain.
691
722
 
@@ -716,7 +747,7 @@ objectShape({ child: source.child }) // throws ContractError { code: 'structure'
716
747
 
717
748
  ### Inferers
718
749
 
719
- The **reverse** direction of `compileSchema` (`src/core/inferers.ts`): instead of emitting a `JSONSchema` from a developer-authored `ContractShape`, these infer a `JSONSchema` at runtime from an unknown/opaque value — a database row, a parsed endpoint payload — so an inferred schema can flow through the same `schemaToParameters` → `createTool` → MCP `inputSchema` bridge a hand-declared shape does. Unlike a shape tree (finite, developer-authored, never cyclic), a runtime value may be arbitrarily deep, wide, or self-referential, so every inferer here is bounded on three axes: a `WeakSet` ancestor set (cycle safety), a decrementing depth budget (`INFER_DEPTH_LIMIT` default), and a per-container sampling cap (`INFER_BREADTH_LIMIT` default) — never a type parameter, conditional type, mapped type, or overload. Readable unsupported values may widen where documented; a failed read throws the shared coded refusal instead of producing a schema.
750
+ The **reverse** direction of `compileSchema` (`src/core/inferers.ts`): instead of emitting a `JSONSchema` from a developer-authored `ContractShape`, these infer a `JSONSchema` at runtime from an unknown/opaque value — a database row, a parsed endpoint payload — so an inferred schema can flow through the same `schemaToParameters` → `createTool` → MCP `inputSchema` bridge a hand-declared shape does. Unlike a shape tree (finite, developer-authored, never cyclic), a runtime value may be arbitrarily deep, wide, or self-referential, so every inferer here is bounded on three axes: a `WeakSet` ancestor set (cycle safety), a decrementing depth budget (`INFER_DEPTH_LIMIT` default), and a per-container sampling cap (`INFER_BREADTH_LIMIT` default) — never a type parameter, conditional type, mapped type, or overload. Readable unsupported values may widen where documented; a failed read throws the shared coded refusal instead of producing a schema. A record that holds a non-enumerable string key or a symbol key infers an open object (`additionalProperties: true`) whatever `closed` says, as a truncated record or one holding a member that is `undefined` does, because a closed schema would refuse the record it was inferred from.
720
751
 
721
752
  One deliberate asymmetry with the compiled direction: an inferred schema is a PLAIN, MUTABLE result, not an owned frozen snapshot. `compileSchema` and `contract.schema` are frozen because they must stay in lockstep with a guard and parser compiled beside them; `valueToSchema` / `samplesToSchema` answer a question about one value and hand you the answer to edit — annotate a `description`, drop a column, merge two fragments. When you need the ownership guarantee, take it explicitly: `cloneSchema(schema)` for a frozen copy, `rawShape(schema)` to embed one in a shape, or `createContract(schemaToShape(schema))` for the full compiled bundle.
722
753
 
@@ -776,30 +807,33 @@ schemaToParameters(valueToSchema(row)) // the open record a tool advertises as `
776
807
 
777
808
  One diagnostic for each artifact that answers yes-or-no. `compileReporter` is the counterpart of `compileParser`: instead of a coerced value it returns every structured `Fault` a value has against a shape — MIRROR-PARSE semantics, so it reuses the exact leaf parsers/guards `compileParser` uses and the soundness invariant `explain(v).length === 0 ⟺ parse(v) !== undefined` holds structurally for READABLE input (`explain` mirrors `parse`'s coercion leniency, not the stricter `is`). `compileAuditor` is the counterpart of `compileGuard`: instead of a `boolean` it returns every `AuditFault` a value has against the STRICT domain, reusing the leaf guards `compileGuard` uses, so `audit(v).length === 0 ⟺ is(v)`. Each report mirrors exactly one artifact, and neither mirrors both, because `is` and `parse` accept different values — which is the subject of the next section. Before either pair compiles, `validateShape` rejects structural and bound-domain malformations; the laws are evaluated only for a valid declaration. Both biconditionals span two separate calls, so both require STABLE reads; the parse biconditional additionally requires the read to succeed rather than raise its coded refusal (see Domains).
778
809
 
779
- | Name | Kind | Signature | Summary |
780
- | ----------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
781
- | `compileAuditor` | function | `(shape: ContractShape, value: unknown, path?: readonly string[]) => readonly AuditFault[]` | Audits a value against the strict acceptance domain of a `ContractShape`. |
782
- | `compileReporter` | function | `(shape: ContractShape, value: unknown, path?: readonly string[]) => readonly Fault[]` | Compiles a `ContractShape` into a structured fault report for a value — the diagnostic counterpart of `compileGuard` / `compileParser`. |
783
- | `buildStringFaults` | function | `(shape: StringShape, value: string, path: readonly string[], pattern?: RegExp) => readonly Fault[]` | Builds the refinement faults a string value has against a `StringShape`. |
784
- | `buildNumberFaults` | function | `(shape: NumberShape, value: number, path: readonly string[]) => readonly Fault[]` | Builds the refinement faults a number value has against a `NumberShape`. |
785
- | `buildArrayFaults` | function | `(shape: ArrayShape, length: number, path: readonly string[]) => readonly Fault[]` | Builds the length faults an array has against an `ArrayShape`. |
786
- | `matchesLosslessRepair` | function | `(fault: AuditFault, input: unknown, parsed: unknown) => boolean` | Determines whether a repair `parse` made kept everything the value said. |
787
- | `matchesExactKeys` | function | `(value: object, required: readonly string[], optional?: readonly string[]) => boolean` | Determines whether an object holds exactly the named own keys. |
788
- | `selectClosestFaults` | function | `<T extends AuditFault>(reports: ReadonlyArray<readonly T[]>) => readonly T[]` | Selects the report of the variant that came closest to matching. |
789
- | `shapeToKind` | function | `(shape: ContractShape) => FaultKind` | Projects a `ContractShape` to the `FaultKind` it describes. |
790
- | `preview` | function | `(value: unknown) => string` | Renders an unknown value as a short, safe, TOTAL string for a `Fault`'s `received` field. |
791
- | `FAULT_KINDS` | const | `readonly FaultKind[]` | Lists every `FaultKind`, frozen. |
792
- | `FAULT_CONSTRAINTS` | const | `readonly FaultConstraint[]` | Lists every `FaultConstraint`, frozen. |
793
- | `FAULT_LIMIT` | const | `64` | Caps at `64` the number of `Fault` / `AuditFault` entries a single `explain` or `audit` report ever returns, frozen. |
794
- | `PREVIEW_LIMIT` | const | `64` | Caps at `64` the character length of a `preview`-rendered string, frozen. |
795
- | `Fault` | type | `{ readonly reason: 'type'; readonly path: FieldPath; readonly expected: FaultKind; readonly received: string; } \| { readonly reason: 'missing'; readonly path: FieldPath; readonly expected: FaultKind; } \| { readonly reason: 'constraint'; readonly path: FieldPath; readonly expected: FaultKind; readonly constraint: FaultConstraint; readonly limit?: number \| string; readonly received: string; } \| { readonly reason: 'variant'; readonly path: FieldPath; readonly variants: number; readonly key?: string; readonly expected?: readonly LiteralValue[]; } \| { readonly reason: 'oneOf'; readonly path: FieldPath; readonly matched: number; readonly key?: string; readonly expected?: readonly LiteralValue[]; }` | Represents a single structured parse-failure diagnostic — one entry of an `ContractInterface.explain` report. |
796
- | `ExtraFault` | interface | `{ reason, path }` | Represents a key present on a value that its closed object shape does not declare. |
797
- | `AuditFault` | type | `Fault \| ExtraFault` | Covers every fault an audit reports — the parse faults plus undeclared keys. |
798
- | `FaultKind` | type | `'string' \| 'date' \| 'number' \| 'integer' \| 'boolean' \| 'null' \| 'literal' \| 'array' \| 'object' \| 'union' \| 'json' \| 'shape'` | Names the kind of value a `Fault` expected — the shape-projected counterpart of a `ContractShape`'s `category`. |
799
- | `FaultConstraint` | type | `'min' \| 'max' \| 'pattern' \| 'date' \| 'integer'` | Names the refinement a `Fault` of reason `'constraint'` violates. |
810
+ | Name | Kind | Signature | Summary |
811
+ | ----------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
812
+ | `compileAuditor` | function | `(shape: ContractShape, value: unknown, path?: readonly string[]) => readonly AuditFault[]` | Audits a value against the strict acceptance domain of a `ContractShape`. |
813
+ | `compileReporter` | function | `(shape: ContractShape, value: unknown, path?: readonly string[]) => readonly Fault[]` | Compiles a `ContractShape` into a structured fault report for a value — the diagnostic counterpart of `compileGuard` / `compileParser`. |
814
+ | `buildStringFaults` | function | `(shape: StringShape, value: string, path: readonly string[], pattern?: RegExp) => readonly Fault[]` | Builds the refinement faults a string value has against a `StringShape`. |
815
+ | `buildNumberFaults` | function | `(shape: NumberShape, value: number, path: readonly string[]) => readonly Fault[]` | Builds the refinement faults a number value has against a `NumberShape`. |
816
+ | `buildArrayFaults` | function | `(shape: ArrayShape, length: number, path: readonly string[]) => readonly Fault[]` | Builds the length faults an array has against an `ArrayShape`. |
817
+ | `matchesLosslessRepair` | function | `(fault: AuditFault, input: unknown, parsed: unknown) => boolean` | Determines whether a repair `parse` made kept everything the value said. |
818
+ | `matchesExactKeys` | function | `(value: object, required: readonly string[], optional?: readonly string[]) => boolean` | Determines whether an object holds exactly the named own keys. |
819
+ | `selectClosestFaults` | function | `<T extends AuditFault>(reports: ReadonlyArray<readonly T[]>) => readonly T[]` | Selects the report of the variant that came closest to matching. |
820
+ | `shapeToKind` | function | `(shape: ContractShape) => FaultKind` | Projects a `ContractShape` to the `FaultKind` it describes. |
821
+ | `preview` | function | `(value: unknown) => string` | Renders a value as a bounded single-line string for a `Fault`'s `received` field, running a `Proxy` object's `getPrototypeOf` trap. |
822
+ | `FAULT_KINDS` | const | `readonly FaultKind[]` | Lists every `FaultKind`, frozen. |
823
+ | `FAULT_CONSTRAINTS` | const | `readonly FaultConstraint[]` | Lists every `FaultConstraint`, frozen. |
824
+ | `FAULT_LIMIT` | const | `64` | Caps at `64` the number of `Fault` / `AuditFault` entries a single `explain` or `audit` report ever returns, frozen. |
825
+ | `PREVIEW_LIMIT` | const | `64` | Caps at `64` the length in UTF-16 code units of every `preview` result, frozen. |
826
+ | `Fault` | type | `{ readonly reason: 'type'; readonly path: FieldPath; readonly expected: FaultKind; readonly received: string; } \| { readonly reason: 'missing'; readonly path: FieldPath; readonly expected: FaultKind; } \| { readonly reason: 'constraint'; readonly path: FieldPath; readonly expected: FaultKind; readonly constraint: FaultConstraint; readonly limit?: number \| string; readonly received: string; } \| { readonly reason: 'variant'; readonly path: FieldPath; readonly variants: number; readonly key?: string; readonly expected?: readonly LiteralValue[]; } \| { readonly reason: 'oneOf'; readonly path: FieldPath; readonly matched: number; readonly key?: string; readonly expected?: readonly LiteralValue[]; }` | Represents a single structured parse-failure diagnostic — one entry of an `ContractInterface.explain` report. |
827
+ | `ExtraFault` | interface | `{ reason, path, symbol? }` | Represents a key present on a value that its closed object shape does not declare, or an own key other than an index or `length` on a value its array shape describes. |
828
+ | `HiddenFault` | interface | `{ reason, path }` | Represents an own member outside the enumerable view that a closed or tail-shaped object refuses. |
829
+ | `AuditFault` | type | `Fault \| ExtraFault \| HiddenFault` | Covers every fault an audit reports — the parse faults plus undeclared and hidden keys. |
830
+ | `FaultKind` | type | `'string' \| 'date' \| 'number' \| 'integer' \| 'boolean' \| 'null' \| 'literal' \| 'array' \| 'object' \| 'union' \| 'json' \| 'shape' \| 'function'` | Names the kind of value a `Fault` expected — the shape-projected counterpart of a `ContractShape`'s `category`. |
831
+ | `FaultConstraint` | type | `'min' \| 'max' \| 'pattern' \| 'date' \| 'integer'` | Names the refinement a `Fault` of reason `'constraint'` violates. |
800
832
 
801
833
  #### How a union is audited and reported
802
834
 
835
+ When a value's discriminator names one variant, that variant alone answers `is`, `parse`, `audit`, and `explain` in both modes, and its faults are the report. The following rules apply to a value that names no variant.
836
+
803
837
  An `anyOf` union stops at the FIRST variant that reports nothing, in declaration order, and runs no later variant plan. `is` and `parse` make the same stop at the first accepting variant, so `is`, `parse`, `audit` and `explain` agree on a value one variant accepts and a later one cannot read: a refusal a later variant would have raised, such as an object variant's prototype probe, is never reached.
804
838
 
805
839
  An `anyOf` union with no matching variant reports one `'variant'` summary plus the closest variant's own faults — fewest faults, ties favouring the lowest index. A `oneOf` union runs every variant plan, because its verdict is the match count rather than the first acceptance, and reports `'oneOf'` with the raw guard-match count; a count of `0` also appends the closest variant's faults, and a count of `2` or more stands alone. A value a later `oneOf` variant cannot read therefore still reaches the same coded refusal.
@@ -816,7 +850,7 @@ A leaf that declares no refinement has no refinement question, so its compiled p
816
850
 
817
851
  ### Domains
818
852
 
819
- A compiled contract describes TWO sets of values, not one. `is` and `schema` describe the canonical domain — the values the declaration literally admits. `parse` is a map INTO that domain whose preimage is deliberately larger: it coerces `'36'` into `36` and drops a closed object's undeclared keys, so it accepts inputs `is` rejects and answers with a value `is` accepts. `explain` diagnoses the map; `audit` diagnoses the domain.
853
+ A compiled contract describes TWO sets of values, not one. `is` decides the canonical domain — the values the declaration literally admits — and `schema` states it for JSON, so a `functionShape` member, whose values JSON cannot carry, emits a schema no instance satisfies. `parse` is a map INTO that domain whose preimage is deliberately larger: it coerces `'36'` into `36` and drops a closed object's undeclared keys, so it accepts inputs `is` rejects and answers with a value `is` accepts. `explain` diagnoses the map; `audit` diagnoses the domain.
820
854
 
821
855
  The laws that bind those domains:
822
856
 
@@ -1306,6 +1340,7 @@ contract.explain({ id: 'nope', name: 'x', role: 'y' })
1306
1340
  - [`tests/src/core/cloners.test.ts`](../tests/src/core/cloners.test.ts) — eager JSON and schema behavior plus the shape function boundaries: fresh `cloneShape` roots/failures/source observation, overload/runtime and compact class parity, and genuine `ownShape` frozen-failure precedence and independent-success behavior.
1307
1341
  - [`tests/src/core/combinators.test.ts`](../tests/src/core/combinators.test.ts) — guard-combinator semantics, refinement composition, exact records/tuples, open-object and member-carrying-callable controls including the prototype-accessor proof, lazy recursion, thrown-value containment, dense array membership, genuine foreign-pattern ownership/flag stripping, and the unreadable-brand versus proxy/forgery diagnostic split.
1308
1342
  - [`tests/src/core/ContractCompiler.test.ts`](../tests/src/core/ContractCompiler.test.ts) — the lazy engine's own contract: the pinned getters, construction that observes nothing, per-root replay identity and the frozen bundle, one entry per unique node, terminal adoption/reentry poison, release, the shared-edge staircase and the bounded expansion refusal, door-versus-getter agreement across every shape category, and field defaults: the fill at both absence sites, a distinct tree per parse for every inner category, nested defaults, the emitted keyword, the JSON round trip, the refusal at every door with its path, and what `generate` does with a default.
1343
+ - [`tests/src/core/KeyPlanCache.test.ts`](../tests/src/core/KeyPlanCache.test.ts) — the interned `KeyPlanCache` class reached by relative source path: a recall that misses on a reordered key list and on a prefix, the oldest plans kept and every key order past `KEY_PLAN_LIMIT` plans missed, one plan per held key order, no plan for a key list holding an undeclared key, and the `retain` method under polluted array construction.
1309
1344
  - [`tests/src/core/compilers.test.ts`](../tests/src/core/compilers.test.ts) — the `compile*` exports and `createContract`, including schema/guard/parser/generator behavior, the public depth boundary, strict auditor and coercive reporter fault semantics, hostile input containment, and contract wiring. It binds genuine foreign patterns through every compiler, exact captured property populations read twice (including refusal of an invalid captured population, and the absence of any further caller read), and the validator/cloner/compiler/contract forgery matrix. The explicit declaration matrix covers non-record roots and children, object-valued RegExp `source` / `flags`, present raw `undefined` populations, and flagged-pattern refusal, with plain/null-prototype/foreign records plus valid local/foreign/accessor patterns as controls; no generated message inventory or source pin participates.
1310
1345
  - [`tests/src/core/errors.test.ts`](../tests/src/core/errors.test.ts) — cross-copy `ContractError` recognition through distinct source-module instances, including transparent-wrapper, stripped-brand subclass, plain-error, complete self-branded forgery, and undeclared-code controls.
1311
1346
  - [`tests/src/core/factories.test.ts`](../tests/src/core/factories.test.ts) — the entity door `createContract` driven directly: an eager bundle whose roots are data properties carrying one artifact identity through destructuring and through a spread, the generic overload and the widened-`ContractShape` overload each answering at every root, a malformed declaration refused at the call itself with the authoring door's own diagnosis rather than a rewrap, and `is` agreeing with `compileGuard` over a corpus that exercises each verdict.
@@ -1328,7 +1363,7 @@ contract.explain({ id: 'nope', name: 'x', role: 'y' })
1328
1363
 
1329
1364
  ### Indexed derivation helpers
1330
1365
 
1331
- These leaves expose the indexed operations used by the compiler and inference engines. `readIndexView` forwards lazy length, membership, and element reads through the source receiver while giving captured array methods a non-array receiver, preventing constructor and species lookup. Its callbacks receive the view as their collection argument. Array construction consumes the pinned indexed cursors instead of synthetic objects that could inherit an iterator. `iterateIndices` rereads its bound before each step and yields the last index below a fractional bound. `encodeParts` stops before an unencodable member; `parseEnumValues` includes the first invalid member as `undefined` and then stops. Their iterator protocols are pinned when the module evaluates. These leaves propagate failed input observations to their consuming boundary.
1366
+ These leaves expose the indexed operations used by the compiler and inference engines. `readIndexView` forwards lazy length, membership, and element reads through the source receiver while giving captured array methods a non-array receiver, preventing constructor and species lookup. Its callbacks receive the view as their collection argument. Array construction consumes the pinned indexed cursors, or an array-like that carries no prototype, never an object that could inherit an iterator. `iterateIndices` rereads its bound before each step and yields the last index below a fractional bound. `encodeParts` stops before an unencodable member; `parseEnumValues` includes the first invalid member as `undefined` and then stops. Their iterator protocols are pinned when the module evaluates. These leaves propagate failed input observations to their consuming boundary. `collectArrayEntries` is the one array walk: it throws on an unreadable array and returns fresh unfrozen entries with the `dense` and `exact` facts, where `exact` is false for any own key other than a canonical index or `length`, a symbol key included. `readArrayEntries` runs that walk inside `attempt` and freezes the read. The compiled array guard calls `collectArrayEntries` and requires `dense` and `exact`, so it refuses `Object.assign(['a'], { note: 'n' })` and its auditor reports `extra` at `note`, or `extra` at the array with `symbol` for a symbol key; `arrayOf` keeps admitting such an array, and inference widens it, so the round-trip law holds for it.
1332
1367
 
1333
1368
  ```ts
1334
1369
  import {