@orkestrel/contract 0.0.9 → 0.0.11

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.
@@ -1,3 +1,31 @@
1
+ /**
2
+ * Collect one more member into a vocabulary that grows as a walk proceeds.
3
+ *
4
+ * @param members - The vocabulary to extend
5
+ * @param value - The value to admit
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const seen = collectMembers([])
10
+ * admitMember(seen, 'a')
11
+ * matchesMember(seen, 'a') // true
12
+ * ```
13
+ */
14
+ export declare function admitMember(members: Set<unknown>, value: unknown): void;
15
+
16
+ /**
17
+ * Record an object as entered on a traversal's active path.
18
+ *
19
+ * @param visited - The active-path set this traversal owns
20
+ * @param value - The object being entered
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * admitVisited(active, node)
25
+ * ```
26
+ */
27
+ export declare function admitVisited(visited: WeakSet<object>, value: object): void;
28
+
1
29
  /**
2
30
  * Combine two guards with logical AND — passes only when both pass.
3
31
  *
@@ -34,19 +62,67 @@ export declare type AnyConstructor<T = unknown> = new (...args: unknown[]) => T;
34
62
  export declare type AnyFunction = (...args: unknown[]) => unknown;
35
63
 
36
64
  /**
37
- * Build a guard that accepts arrays whose every element satisfies `elementGuard`.
65
+ * Append every element of one array onto another, by index.
66
+ *
67
+ * @remarks
68
+ * The sibling of {@link pathOf}, for the other shape the same defect takes.
69
+ * `target[target.length] = ...source` and `[summary, ...rest]` both dispatch through
70
+ * `Array.prototype[Symbol.iterator]`, and a caller-installed iterator that
71
+ * yields one extra value writes the caller's text into a diagnostic this
72
+ * package publishes as its own. Both operands here are arrays this package
73
+ * built, and an indexed read of an own index property dispatches through
74
+ * nothing.
75
+ *
76
+ * @param target - The array to extend in place
77
+ * @param source - The elements to append, read by index
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * appendEntries(faults, compileReporter(inner, raw, pathOf(path, key)))
82
+ * ```
83
+ */
84
+ export declare function appendEntries<T>(target: T[], source: readonly T[]): void;
85
+
86
+ /**
87
+ * Build a guard that accepts DENSE arrays whose every element satisfies
88
+ * `elementGuard`.
89
+ *
90
+ * @remarks
91
+ * Density is part of the contract, not an accident: the guard reads the array
92
+ * through the shared reflected own-index lens {@link readArrayEntries}, which is
93
+ * what makes it immune to caller-defined iteration and what `parseArray` reads
94
+ * too. A SPARSE array is therefore refused outright — `[1, , 3]` fails even when
95
+ * the element guard accepts `undefined` — because a hole is an absent own
96
+ * property rather than a present `undefined`, and the two are different facts.
97
+ * Pass `[1, undefined, 3]` when the middle slot is meant to exist.
38
98
  *
39
99
  * @example
40
100
  * ```ts
41
101
  * const isStringArray = arrayOf(isString)
42
102
  * isStringArray(['a', 'b']) // true
43
103
  * isStringArray(['a', 1]) // false
104
+ * isStringArray(['a', , 'b']) // false — sparse
44
105
  * ```
45
106
  */
46
107
  export declare function arrayOf<T>(elementGuard: Guard<T>): Guard<readonly T[]>;
47
108
 
48
109
  export declare function arrayOf(elementGuard: (value: unknown) => boolean): Guard<readonly unknown[]>;
49
110
 
111
+ /**
112
+ * Owned result of reading one array through its reflected own-index lens.
113
+ *
114
+ * @remarks
115
+ * {@link entries} is a frozen native array with actual holes: reading a hole
116
+ * yields `undefined`, while own membership remains absent. A length-driven
117
+ * consumer must first require {@link dense} or carry an independent work bound.
118
+ */
119
+ export declare interface ArrayRead<T = unknown> {
120
+ /** Frozen native entries in index order, retaining sparse positions as holes. */
121
+ readonly entries: readonly (T | undefined)[];
122
+ /** Whether every index from zero through length minus one was reflected. */
123
+ readonly dense: boolean;
124
+ }
125
+
50
126
  /** An array shape with an element shape and optional length bounds. */
51
127
  export declare interface ArrayShape<S extends ContractShape = ContractShape> {
52
128
  readonly type: 'array';
@@ -79,8 +155,8 @@ export declare interface ArrayShapeOptions {
79
155
  }
80
156
 
81
157
  /**
82
- * Invoke a callback and capture its outcome as a {@link Result}, never letting
83
- * a throw escape.
158
+ * Invoke a callback once and synchronously capture its exact outcome as a
159
+ * {@link Result}.
84
160
  *
85
161
  * @remarks
86
162
  * The sanctioned never-throw boundary for the guards (AGENTS §14). The
@@ -89,12 +165,20 @@ export declare interface ArrayShapeOptions {
89
165
  * `boolean`. This converts a throwing callback into a `Failure` so the
90
166
  * surrounding guard can treat it as a non-match instead of propagating the
91
167
  * exception, written once and shared rather than copy-pasted as ad-hoc
92
- * `try`/`catch`. The sole hand-written exception is {@link isContractError},
93
- * whose local boundary avoids an `errors` → `helpers` dependency inversion.
168
+ * `try`/`catch`. The return or thrown value is retained exactly and is never
169
+ * inspected, coerced, cloned, frozen, or mutated. A returned Promise or
170
+ * thenable is an ordinary successful value; later settlement is outside this
171
+ * synchronous boundary. {@link isContractError} does not use this boundary and
172
+ * is not an exception to it: it carries its own `try`/`catch` inside the class
173
+ * body, because `errors.ts` cannot import this module without inverting the
174
+ * dependency. The earlier claim here — that it was total BY CONSTRUCTION and had
175
+ * nothing to contain — was false, and it is what justified deleting the
176
+ * containment the committed baseline had. A guard whose totality rests on an
177
+ * argument that nothing inside it can throw is one refactor away from throwing.
94
178
  *
95
179
  * @param callback - The callback to invoke with no arguments
96
- * @returns A `Success` carrying the return value, or a `Failure` carrying the
97
- * thrown reason normalised to an `Error`
180
+ * @returns A `Success` carrying the exact return value, or a `Failure` carrying
181
+ * the exact thrown value as `unknown`
98
182
  *
99
183
  * @example
100
184
  * ```ts
@@ -104,6 +188,22 @@ export declare interface ArrayShapeOptions {
104
188
  */
105
189
  export declare function attempt<T>(callback: () => T): Result<T>;
106
190
 
191
+ /** Every fault an audit reports — the parse faults plus undeclared keys. */
192
+ export declare type AuditFault = Fault | ExtraFault;
193
+
194
+ /**
195
+ * A compiled strict-domain diagnostic — the shape of `compileAuditor` bound to
196
+ * one shape.
197
+ *
198
+ * @remarks
199
+ * The optional `path` is the prefix every fault this call reports is rooted at,
200
+ * so a nested walk can name where it started. A contract's
201
+ * {@link ContractInterface.audit} takes only the value, because no contract
202
+ * consumer injects a root path; a function of this type is assignable to that
203
+ * property, so one compiled function can serve both surfaces.
204
+ */
205
+ export declare type AuditorFunction = (value: unknown, path?: readonly string[]) => readonly AuditFault[];
206
+
107
207
  /** A boolean shape — accepts only `true` or `false`. */
108
208
  export declare interface BooleanShape {
109
209
  readonly type: 'boolean';
@@ -204,6 +304,26 @@ export declare function boundsOf(min?: number, max?: number): Guard<number>;
204
304
  */
205
305
  export declare function buildObjectShape(schema: JSONSchema, depth: number, visited: WeakSet<object>, memo: WeakMap<object, Map<number, ContractShape>>, description: string | undefined): ContractShape;
206
306
 
307
+ /**
308
+ * Build one empty {@link SampleMemo} node.
309
+ *
310
+ * @remarks
311
+ * The root a multi-sample walk starts from and the node every further row
312
+ * prefix is grown into, built from the CAPTURED `WeakMap` and `Map` so a
313
+ * replaced global cannot decide what a published schema is served from. One
314
+ * memo belongs to one walk: {@link samplesToSchema} builds it at the door, and
315
+ * a direct caller of {@link inferSamples} / {@link inferRecordSamples} builds a
316
+ * fresh one per call.
317
+ *
318
+ * @returns An empty memo node with no recorded rows and no recorded schemas
319
+ *
320
+ * @example
321
+ * ```ts
322
+ * inferRecordSamples([{ id: 1 }], 32, 256, true, false, false, buildSampleMemo())
323
+ * ```
324
+ */
325
+ export declare function buildSampleMemo(): SampleMemo;
326
+
207
327
  /**
208
328
  * Build a {@link ContractShape} for one JSON Schema node — the recursive
209
329
  * spine of {@link schemaToShape}, shared with per-child recursion via
@@ -231,15 +351,15 @@ export declare function buildObjectShape(schema: JSONSchema, depth: number, visi
231
351
  * the matching primitive shape, with length/range bounds derived via
232
352
  * {@link deriveLengthBounds} / {@link deriveRangeBounds}. An integer node
233
353
  * additionally drops its bounds when they describe an EMPTY integer range
234
- * (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShape`
354
+ * (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShapeDepth`
235
355
  * rejects — so the result is always a valid shape.
236
356
  * 5. `type: 'array'` — an {@link arrayShape} whose element shape recurses into
237
357
  * a record-valued `items` (widening to {@link rawShape} otherwise), with
238
358
  * bounds from `minItems` / `maxItems`.
239
359
  * 6. `type: 'object'`, OR no `type` / `enum` / `oneOf` / `anyOf` but a
240
360
  * record-valued `properties` — delegates to {@link buildObjectShape}.
241
- * 7. Everything else — an empty schema, an unrecognized/absent `type`,
242
- * exhausted depth/breadth, or an attempt failure — widens to
361
+ * 7. Everything else — an empty schema, an unrecognized/absent `type`, or
362
+ * exhausted depth/breadth — widens to
243
363
  * {@link rawShape}, whose guard accepts every defined value and whose
244
364
  * emitted schema is the same `{}` (plus `description`) the node carried.
245
365
  * This is the exact inverse of `{}`, JSON Schema's accept-anything schema,
@@ -273,12 +393,13 @@ export declare function buildObjectShape(schema: JSONSchema, depth: number, visi
273
393
  export declare function buildShapeFromNode(schema: JSONSchema, depth: number, visited: WeakSet<object>, memo: WeakMap<object, Map<number, ContractShape>>): ContractShape;
274
394
 
275
395
  /**
276
- * Encode one value as a deterministic, key-sorted JSON string — the recursive
396
+ * Encode one value as a deterministic, key-sorted JSON string — the traversal
277
397
  * spine of {@link canonicalStringify}.
278
398
  *
279
399
  * @remarks
280
- * Arrays keep their element order; records sort their own keys before encoding,
281
- * recursively at every nesting level. Every other value is encoded by
400
+ * Arrays keep their element order through the shared dense own-index lens;
401
+ * records sort their own keys before encoding, at every nesting level. Every
402
+ * other value is encoded by
282
403
  * `JSON.stringify`, so `NaN` / `±Infinity` collapse to `'null'` and `-0`
283
404
  * encodes as `'0'` — the same lossy-but-deterministic mapping real JSON makes.
284
405
  *
@@ -286,10 +407,20 @@ export declare function buildShapeFromNode(schema: JSONSchema, depth: number, vi
286
407
  * function, a symbol, an array hole, or a cyclic back-edge to an ancestor. A
287
408
  * container carrying such a member is itself un-encodable and returns
288
409
  * `undefined` too, so the result is either a faithful encoding of the WHOLE
289
- * value or nothing — a partially-encoded key is never emitted. Traversal is NOT
290
- * contained here: a hostile getter or `Proxy` trap throws through to
291
- * {@link canonicalStringify}, which owns the single {@link attempt} boundary
292
- * for the walk.
410
+ * value or nothing — a partially-encoded key is never emitted. A hostile
411
+ * getter or `Proxy` trap is refused through this function's own required-read
412
+ * boundary, including when this spine is called directly.
413
+ *
414
+ * The walk is ITERATIVE over an explicit enter/exit stack and keeps a
415
+ * walk-local encoding memo, so a container reached through several paths is
416
+ * encoded ONCE. That memo is sound precisely because a partial answer does not
417
+ * exist here: any cycle or JSON-inexpressible member abandons the whole call,
418
+ * so a recorded encoding is the container's complete encoding on every path.
419
+ * The earlier recursion re-encoded per path, which made thirty ordinary shared
420
+ * aliases cost `2^30` encodings through the public {@link canonicalStringify}
421
+ * and {@link unifySchemas} doors. Each container's members are read ONCE, at
422
+ * the moment it is entered, and the ancestor set is restored on every exit
423
+ * including the abandoning ones.
293
424
  *
294
425
  * @param value - The value to encode
295
426
  * @param ancestors - Objects on the active traversal path, guarding cycles
@@ -315,8 +446,8 @@ export declare function canonicalizeValue(value: unknown, ancestors: WeakSet<obj
315
446
  * `JSONSchema` fragments built independently always canonicalize to the same
316
447
  * string. Pure host-independent ECMAScript with no environment-specific imports.
317
448
  *
318
- * TOTAL: it NEVER throws, for any input. It returns `undefined` — never a
319
- * partial or invalid encoding — for every value JSON cannot faithfully encode:
449
+ * For READABLE input it returns `undefined` — never a partial or invalid
450
+ * encoding — for every value JSON cannot faithfully encode:
320
451
  *
321
452
  * - `undefined` itself, a function, a symbol, or an array hole (JSON encodes
322
453
  * none of them), at the top level or anywhere inside a container;
@@ -324,8 +455,10 @@ export declare function canonicalizeValue(value: unknown, ancestors: WeakSet<obj
324
455
  * - cyclic input, tracked with the same ancestor-{@link WeakSet} discipline
325
456
  * {@link inferArray} / {@link inferObject} use, so a shared (non-cyclic)
326
457
  * reference reached twice through different paths still encodes;
327
- * - hostile traversal — a throwing own-getter, a hostile `ownKeys` trap, or a
328
- * revoked `Proxy` anywhere in the value — contained via {@link attempt}.
458
+ * A hostile traversal is categorically different: a throwing own-getter,
459
+ * hostile `ownKeys` trap, or revoked `Proxy` throws a `structure`
460
+ * {@link ContractError} through {@link readValue}. A caller can therefore
461
+ * distinguish "not JSON-encodable" from "could not be read".
329
462
  *
330
463
  * A caller therefore treats `undefined` as "this value has no canonical key",
331
464
  * never as an encoding: see {@link unifySchemas} (an un-keyed member cannot
@@ -336,6 +469,7 @@ export declare function canonicalizeValue(value: unknown, ancestors: WeakSet<obj
336
469
  * nested piece of one)
337
470
  * @returns A deterministic string encoding of `value`, or `undefined` when JSON
338
471
  * cannot encode it
472
+ * @throws {ContractError} When the value cannot be read
339
473
  *
340
474
  * @example
341
475
  * ```ts
@@ -348,6 +482,55 @@ export declare function canonicalizeValue(value: unknown, ancestors: WeakSet<obj
348
482
  */
349
483
  export declare function canonicalStringify(value: unknown): string | undefined;
350
484
 
485
+ /**
486
+ * Classify an already-bounded string against the pattern-only and
487
+ * calendar-checked {@link SchemaFormat} vocabulary.
488
+ *
489
+ * @remarks
490
+ * The pure leaf behind {@link stringToFormat}'s total boundary: it performs the
491
+ * pattern dispatch, and the door decides what a failed dispatch answers. Order
492
+ * is significant — `date-time` is tried before `date`, and both require the
493
+ * calendar check, so `2020-13-45` matches the pattern and is still refused.
494
+ *
495
+ * @param value - The candidate string, already length-bounded
496
+ * @returns The matched {@link SchemaFormat}, or `undefined`
497
+ * @throws The exact value thrown by a redirected pattern dispatch
498
+ *
499
+ * @example
500
+ * ```ts
501
+ * classifyFormat('ada@example.com') // 'email'
502
+ * ```
503
+ */
504
+ export declare function classifyFormat(value: string): SchemaFormat | undefined;
505
+
506
+ /**
507
+ * The maximum number of nodes one JSON snapshot may produce, frozen.
508
+ *
509
+ * @remarks
510
+ * JSON persistence is a TREE, so `cloneJSONValue` / `cloneJSONRecord`
511
+ * deliberately duplicate a repeated noncyclic alias into distinct equal
512
+ * branches — `clone.primary !== clone.fallback` is a documented guarantee, not
513
+ * an accident, and a memo would silently take it away. The price of that
514
+ * guarantee is that output size is exponential in the number of shared aliases:
515
+ * an ordinary in-memory graph of twenty-one objects, a few hundred bytes,
516
+ * produced two million nodes and took seconds, and thirty aliases took hours.
517
+ * No attacker is needed — shared references are normal data.
518
+ *
519
+ * So the cost is BOUNDED rather than paid: the walk counts the nodes it
520
+ * produces and refuses past this cap with the ordinary cause-free `clone`
521
+ * refusal, which makes the door's worst case a function of this constant
522
+ * instead of the caller's input. Size a snapshot against it: a document with
523
+ * more than this many nodes — counting every array, record, and leaf the
524
+ * snapshot would contain AFTER alias duplication — is refused rather than
525
+ * cloned.
526
+ *
527
+ * @example
528
+ * ```ts
529
+ * CLONE_NODE_LIMIT // 262144
530
+ * ```
531
+ */
532
+ export declare const CLONE_NODE_LIMIT = 262144;
533
+
351
534
  /**
352
535
  * Deep-clone an exact JSON object record into an owned frozen snapshot.
353
536
  *
@@ -381,6 +564,8 @@ export declare function cloneJSONRecord(value: unknown): JSONRecord;
381
564
  * JSON data, so frozen arrays remain valid. Property descriptors are inspected
382
565
  * without reading values through accessors, and every hostile reflective
383
566
  * operation is contained before a new clone-coded error is exposed.
567
+ * Each call creates a fresh {@link JSONCloner}; use the class directly when
568
+ * terminal success or failure identity must be replayed without another read.
384
569
  *
385
570
  * @param value - The unknown value to validate and snapshot
386
571
  * @returns The primitive unchanged, or a deeply cloned and frozen JSON graph
@@ -406,6 +591,8 @@ export declare function cloneJSONValue(value: unknown): JSONValue;
406
591
  * null prototypes, arrays retain only their intrinsic array prototype, and
407
592
  * every produced object is frozen after its edges are wired. Hostile traversal
408
593
  * throws a clone-coded {@link ContractError}, never a caller-owned raw error.
594
+ * Each call creates a fresh {@link SchemaCloner}; use the class directly when
595
+ * terminal success or failure identity must be replayed without another read.
409
596
  *
410
597
  * @param schema - The JSON Schema graph to snapshot
411
598
  * @returns A deeply cloned and frozen JSON Schema graph
@@ -424,18 +611,30 @@ export declare function cloneSchema(schema: JSONSchema): JSONSchema;
424
611
  * Deep-clone a contract shape graph into an owned frozen snapshot.
425
612
  *
426
613
  * @remarks
427
- * Uses an explicit memo to preserve shared-child identity and close cyclic
428
- * edges onto their cloned nodes. Shape-node shells are created iteratively,
429
- * then their structural edges are wired and their copied collections frozen.
430
- * String patterns are captured by source and flags behind an enumerable
431
- * accessor that returns a fresh frozen zero-state `RegExp` on every read.
432
- * A raw schema delegates to {@link cloneSchema}; every shape-graph read is
433
- * contained, so hostile traversal throws only a clone-coded
434
- * {@link ContractError}.
614
+ * A fresh public {@link ShapeCloner} preserves shared-child identity while
615
+ * building the candidate snapshot, owns raw schemas, validates the exact
616
+ * completed root, applies deferred fidelity, and translates unexpected hostile
617
+ * failures. Inside the engine, each node's own data discriminant and every
618
+ * declared field are captured descriptor-first from two agreeing reads, and the
619
+ * carried population alone supplies its shallow shell, semantic checks, child
620
+ * scheduling, and later edge wiring. An inherited field is refused through a
621
+ * non-invoking presence check, and a revealed accessor is refused without
622
+ * invocation except for the builder's `pattern` contract: two fresh frozen
623
+ * genuine `RegExp` values with equal source and flags are captured as owned
624
+ * source/flags semantics.
625
+ *
626
+ * Literal and union members retain their own-index descriptor/repeated-read
627
+ * checks; property entries retain descriptor/first/second agreement plus two
628
+ * exactly equal ordered key populations; raw schemas delegate to
629
+ * {@link cloneSchema}. Before return, a fresh {@link ShapeValidator} independently
630
+ * validates the exact cloned root. Ownership never erases a structural edge or
631
+ * normalizes an invalid scalar/bound into a plausible declaration: those
632
+ * inputs throw their coded structure/bound error. Hostile traversal remains
633
+ * distinct and throws a clone-coded {@link ContractError}.
435
634
  *
436
635
  * @param shape - The contract shape graph to snapshot
437
636
  * @returns A deeply cloned and frozen shape graph
438
- * @throws {ContractError} When hostile shape or raw-schema traversal prevents ownership
637
+ * @throws {ContractError} When the declaration cannot be copied faithfully or hostile shape or raw-schema traversal prevents ownership
439
638
  *
440
639
  * @example
441
640
  * ```ts
@@ -448,14 +647,94 @@ export declare function cloneShape(shape: StringShape): StringShape;
448
647
 
449
648
  export declare function cloneShape(shape: ContractShape): ContractShape;
450
649
 
650
+ /**
651
+ * Build the collector a captured `forEach` sweep appends through.
652
+ *
653
+ * @remarks
654
+ * Extracted rather than written inline for the same reason
655
+ * {@link compareValues} is: `Reflect.apply` takes its arguments as a LIST, so an
656
+ * inline collector is a function expression inside an array literal rather than
657
+ * one passed directly as an argument — a hidden function assignment this
658
+ * repository forbids wherever it appears. Returned directly from a factory it is
659
+ * both named and testable. Both sweeps hand the callback `(value, key)`; a `Set`
660
+ * passes its entry in both positions, so one collector serves both.
661
+ *
662
+ * @param target - The pair list to append each swept entry onto
663
+ * @returns The collector a captured `forEach` invokes per entry
664
+ *
665
+ * @example
666
+ * ```ts
667
+ * const collected: unknown[][] = []
668
+ * new Set(['a']).forEach(collectEntries(collected)) // [['a', 'a']]
669
+ * ```
670
+ */
671
+ export declare function collectEntries(target: unknown[][]): (value: unknown, key: unknown) => void;
672
+
673
+ /**
674
+ * Collect an array's entries into a membership collection this package owns.
675
+ *
676
+ * @remarks
677
+ * THE builder behind every declared vocabulary, and the first half of the answer
678
+ * to a defect that survived three rounds by moving rather than closing. A guard
679
+ * deciding membership with `set.has(value)` answers whatever the caller most
680
+ * recently installed on `Set.prototype`, and answering it instead through the
681
+ * `has` method of an exported class only moved the writable member one prototype
682
+ * up: `Vocabulary.prototype.has = () => true` reproduced the whole defect at
683
+ * nineteen door groups. There is no property lookup here to redirect —
684
+ * membership is asked of a MODULE BINDING, which the specification makes
685
+ * immutable to every importer, over operations {@link INTRINSICS} captured while
686
+ * it evaluated.
687
+ *
688
+ * Collection is by INDEX rather than from an iterable on purpose:
689
+ * `new Set(values)` reads `Symbol.iterator` off the argument and `add` off the
690
+ * instance, so building from an iterable would reintroduce two replaceable
691
+ * dispatches to remove one.
692
+ *
693
+ * @param values - The members to collect, read by index
694
+ * @returns A collection no caller holds a reference to
695
+ *
696
+ * @example
697
+ * ```ts
698
+ * const allowed = collectMembers(['admin', 'guest'])
699
+ * matchesMember(allowed, 'admin') // true
700
+ * ```
701
+ */
702
+ export declare function collectMembers(values: readonly unknown[]): Set<unknown>;
703
+
704
+ /**
705
+ * Order two primitive keys or indices ascending.
706
+ *
707
+ * @remarks
708
+ * The comparison {@link sortValues} hands to the captured sort, extracted rather
709
+ * than written inline. `Reflect.apply` takes its arguments as a LIST, so an
710
+ * inline comparator is a function expression inside an array literal rather than
711
+ * one passed directly as an argument — a hidden function assignment, which this
712
+ * repository forbids wherever it appears because a function that is not a named
713
+ * declaration is a function no caller can reach and no test can exercise. As a
714
+ * declaration it is both. The comparison is `<` / `>` on primitives, which
715
+ * dispatches through nothing: no `valueOf`, no `toString`, and no member a
716
+ * caller can replace, so the order a published schema is emitted in is decided
717
+ * by the values and not by the environment.
718
+ *
719
+ * @param left - The value ordered first when it compares lower
720
+ * @param right - The value compared against
721
+ * @returns `-1`, `1`, or `0` as `left` sorts before, after, or with `right`
722
+ *
723
+ * @example
724
+ * ```ts
725
+ * compareValues('a', 'b') // -1
726
+ * ```
727
+ */
728
+ export declare function compareValues<T extends string | number>(left: T, right: T): number;
729
+
451
730
  /**
452
731
  * The maximum supported nesting depth of a compiled contract shape, frozen.
453
732
  *
454
733
  * @remarks
455
- * {@link validateShape} rejects the next level with a depth-coded
456
- * {@link ContractError} before recursive artifact compilation begins, so a
457
- * finite but pathologically deep developer-authored shape fails predictably
458
- * instead of reaching the JavaScript call-stack limit.
734
+ * {@link validateShapeDepth} rejects the next level
735
+ * with a depth-coded {@link ContractError} before recursive artifact
736
+ * compilation begins, so a finite but pathologically deep developer-authored
737
+ * shape fails predictably instead of reaching the JavaScript call-stack limit.
459
738
  *
460
739
  * @example
461
740
  * ```ts
@@ -464,6 +743,81 @@ export declare function cloneShape(shape: ContractShape): ContractShape;
464
743
  */
465
744
  export declare const COMPILE_DEPTH_LIMIT = 512;
466
745
 
746
+ /**
747
+ * The maximum number of nodes a compiled artifact may expand a shape into,
748
+ * frozen.
749
+ *
750
+ * @remarks
751
+ * A shape graph is a DAG; every compiled artifact is a TREE. A declaration may
752
+ * therefore be tiny and its schema, guard, parser, reporter, auditor and
753
+ * generated value enormous: `objectShape({ left: node, right: node })` nested
754
+ * thirty times is thirty-one authored nodes that expand into more than a
755
+ * billion emitted ones. Sharing one child is ordinary authoring, not an attack,
756
+ * and the compilers cannot fold the expansion away without publishing a schema
757
+ * whose members alias each other.
758
+ *
759
+ * So the cost is BOUNDED rather than paid. {@link validateShapeDepth} and
760
+ * {@link ContractCompiler} preparation both count the nodes the declaration
761
+ * expands into (one per node, summed over every incoming edge) and refuse past
762
+ * this cap through {@link refuseExpansion}, with an `expansion`-coded
763
+ * {@link ContractError}. Ownership is deliberately NOT bounded by it:
764
+ * {@link cloneShape} and {@link ownShape} preserve shared-child identity, so
765
+ * they answer a shared-child graph in time proportional to its authored nodes
766
+ * and keep working above this cap.
767
+ *
768
+ * What this cap bounds MOVED when the compilers stopped expanding a DAG. Every
769
+ * artifact family is now one entry per unique node, so the boundary declaration
770
+ * above compiles fourteen nodes in about a millisecond rather than sixteen
771
+ * thousand in 1,342 ms, and the cap is no longer what keeps compilation finite.
772
+ * What still expands is what a CONSUMER materializes from the artifacts: the
773
+ * value `generate` builds, and the document a compiled schema serializes to,
774
+ * are trees of exactly this size. The cap survives as a bound on what a caller
775
+ * can be handed, not on what the compiler pays.
776
+ *
777
+ * @example
778
+ * ```ts
779
+ * COMPILE_NODE_LIMIT // 16384
780
+ * ```
781
+ */
782
+ export declare const COMPILE_NODE_LIMIT = 16384;
783
+
784
+ /**
785
+ * Audit a value against the strict acceptance domain of a {@link ContractShape}.
786
+ *
787
+ * @remarks
788
+ * The diagnostic for the domain {@link compileGuard} and {@link compileSchema}
789
+ * describe, where {@link compileReporter} diagnoses the wider preimage
790
+ * {@link compileParser} maps into it. This walk therefore mirrors the guard:
791
+ * leaf coercions are faults, closed-object extras are faults, and union
792
+ * acceptance is decided from each variant's strict audit emptiness, so the
793
+ * soundness invariant
794
+ * `compileAuditor(shape, v).length === 0 ⟺ compileGuard(shape)(v)` holds
795
+ * structurally. The shared declaration gate rejects structural and bound-domain
796
+ * malformations before either artifact is built, so the invariant is only
797
+ * evaluated for a valid declaration. The invariant relates two
798
+ * separate calls, so it holds for a value whose reads are stable across calls;
799
+ * see the read-stability precondition on {@link ContractInterface}. Every
800
+ * recursive call returns at most {@link FAULT_LIMIT} entries. Hostile property
801
+ * access raises the shared coded read refusal with the current container path
802
+ * and shape, so unreadability never masquerades as a type mismatch.
803
+ * It requests exactly the `auditor` root of a fresh {@link ContractCompiler}
804
+ * and applies it once; reuse the compiler (or a contract's `audit`) when many
805
+ * values are audited against one shape.
806
+ *
807
+ * @param shape - The shape to audit against
808
+ * @param value - The value to check
809
+ * @param path - The path prefix for faults produced at this call
810
+ * @returns The strict faults found, empty exactly when the compiled guard accepts a stably-read value
811
+ *
812
+ * @example
813
+ * ```ts
814
+ * const user = objectShape({ name: stringShape() })
815
+ * compileAuditor(user, { name: 'Ada', extra: true })
816
+ * // [{ reason: 'extra', path: ['extra'] }]
817
+ * ```
818
+ */
819
+ export declare function compileAuditor(shape: ContractShape, value: unknown, path?: readonly string[]): readonly AuditFault[];
820
+
467
821
  /**
468
822
  * Compile a {@link ContractShape} into a deterministic seed value.
469
823
  *
@@ -473,20 +827,19 @@ export declare const COMPILE_DEPTH_LIMIT = 512;
473
827
  * from the wall clock when none is supplied. Shape-generation failures throw a
474
828
  * {@link ContractError} with code `'generate'`; {@link drawRandom} failures use
475
829
  * code `'random'` and retain the consuming shape category in context.
476
- * Failures include a degenerate empty `literalShape` / `unionShape`, a
477
- * pattern-constrained `stringShape` whose generated sample cannot satisfy the
478
- * pattern, an invalid random sample, and a `rawShape` whose arbitrary embedded
479
- * schema cannot be auto-generated. {@link validateShapeDepth} iteratively
480
- * rejects excessive nesting or cycles before recursive generation begins.
481
- * `createContract` runs
482
- * {@link validateShape} first, so a degenerate `literalShape` / `unionShape` /
483
- * bounded shape is normally caught there; these throws remain here as defense
484
- * for standalone `compileGenerator` use. Union candidates are bounded by
830
+ * Failures include a pattern-constrained `stringShape` whose generated sample
831
+ * cannot satisfy the pattern, an invalid random sample, and a `rawShape` whose
832
+ * arbitrary embedded schema cannot be auto-generated. Degenerate empty
833
+ * literal/union vocabularies fail earlier with the shared gate's `empty` code.
834
+ * It requests exactly the `generator` root of a fresh
835
+ * {@link ContractCompiler} and invokes it once, so the declaration is owned and
836
+ * validated once before any draw. Union candidates are bounded by
485
837
  * {@link GENERATION_ATTEMPT_LIMIT} and accepted only when they satisfy the
486
- * union's compiled guard.
838
+ * union's compiled guard, which is why a declaration containing a union also
839
+ * builds the compiler's guard plan.
487
840
  *
488
841
  * @param shape - The shape to generate from
489
- * @param random - A seeded random source (defaults to `seededRandom(Date.now())`)
842
+ * @param random - A seeded random source (defaults to a wall-clock seed drawn inside the door's boundary)
490
843
  * @returns A value matching the shape
491
844
  * @throws {ContractError} When the shape or random source cannot produce a valid value
492
845
  *
@@ -505,12 +858,16 @@ export declare function compileGenerator(shape: ContractShape, random?: RandomFu
505
858
  * @remarks
506
859
  * Reuses the combinators for structural and refined shapes, including
507
860
  * {@link literalOf} for SameValueZero literal matching. Compiled object shapes
508
- * observe own enumerable string keys through {@link enumerableKeys}, matching
509
- * their parser, reporter, and inference view for both open and closed objects.
510
- * Like every guard it is total — it never throws (AGENTS §14). The shape is
511
- * taken through {@link ownShape} first, so an unfrozen caller-owned graph
512
- * compiles from a snapshot. {@link validateShapeDepth} iteratively rejects
513
- * excessive nesting or cycles before recursive guard compilation begins.
861
+ * observe own enumerable string keys through {@link enumerableKeys}, the same
862
+ * key view their parser, reporter, auditor, and inference use for both open and
863
+ * closed objects — the view is shared, the verdict on an undeclared key is not
864
+ * (this guard rejects the object; the parser drops the key).
865
+ * Like every guard it is total — it never throws (AGENTS §14). It requests
866
+ * exactly the `guard` root of a fresh {@link ContractCompiler}, which owns the
867
+ * declaration once through {@link ownShape} and validates that snapshot once,
868
+ * so an unfrozen caller-owned graph compiles from a snapshot and excessive
869
+ * nesting, cycles, and excessive expansion are rejected before any guard is
870
+ * built.
514
871
  *
515
872
  * @param shape - The shape to compile
516
873
  * @returns A guard narrowing to the shape's inferred type
@@ -530,21 +887,26 @@ export declare function compileGuard(shape: ContractShape): Guard<unknown>;
530
887
  *
531
888
  * @remarks
532
889
  * Reuses the leaf parsers (`parseString` / `parseInteger` / `parseNumber` /
533
- * `parseBoolean` / `parseRecord`) and coerces structurally. An object fails as a
890
+ * `parseBoolean`) and coerces structurally. An object fails as a
534
891
  * whole on any required-field failure; a union returns a guard-valid value
535
892
  * unchanged, otherwise the first variant that both parses and guards wins.
536
893
  *
537
894
  * After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same
538
- * combinators `compileGuard` uses — `stringOf` for a string's length/pattern,
539
- * `boundsOf` for a number's value and an array's length, and {@link literalOf}
540
- * for literal membership — so a value that coerces but violates a bound parses
541
- * to `undefined`. The result is full parse↔guard soundness (AGENTS §14): a
895
+ * combinators {@link compileGuard} uses — `stringOf` for a string's
896
+ * length/pattern, `boundsOf` for a number's value and an array's length, and
897
+ * {@link literalOf} for literal membership — so a value that coerces but
898
+ * violates a bound parses to `undefined`. The result is full parse↔guard
899
+ * soundness (AGENTS §14): a
542
900
  * non-`undefined` parse always satisfies the contract's `is`, refinements
543
- * included. Object presence and extra-key processing use the same
544
- * own-enumerable-string snapshot as the guard, reporter, and inference. The
545
- * shape is taken through {@link ownShape} first, so an unfrozen caller-owned
546
- * graph compiles from a snapshot. {@link validateShapeDepth} iteratively
547
- * rejects excessive nesting or cycles before recursive parser compilation.
901
+ * included — a statement about the OUTPUT, never about the input, which may be
902
+ * a value `is` rejects. Object presence and extra-key processing read the same
903
+ * own-enumerable-string key view as the guard, reporter, auditor, and inference
904
+ * — one key set, deliberately different verdicts: this parser drops an
905
+ * undeclared key that {@link compileGuard} rejects and {@link compileAuditor}
906
+ * faults. It requests exactly the `parser` root of a fresh
907
+ * {@link ContractCompiler}, which owns and validates the declaration once; a
908
+ * union's variant selection is a guard question, so a declaration containing one
909
+ * also builds the compiler's guard plan.
548
910
  *
549
911
  * @param shape - The shape to compile
550
912
  * @returns A parser yielding the shape's inferred type or `undefined`
@@ -571,6 +933,11 @@ export declare function compileParser(shape: ContractShape): Parser<unknown>;
571
933
  * holds structurally — `explain` mirrors `parse`, not the stricter `is` (a
572
934
  * coercible value like `'42'` against a `numberShape` reports no fault, the
573
935
  * same leniency `parse` grants, even though the strict guard would reject it).
936
+ * The invariant relates two separate calls, so it holds for a value whose reads
937
+ * are stable across calls; see the read-stability precondition on
938
+ * {@link ContractInterface}. {@link compileAuditor} is the counterpart report
939
+ * for the strict domain, mirroring {@link compileGuard} the way this one
940
+ * mirrors {@link compileParser}.
574
941
  *
575
942
  * Faults are collected in stable pre-order (declared key/index order); every
576
943
  * call — object, array, and union alike, including a union's `oneOf` "no
@@ -579,12 +946,15 @@ export declare function compileParser(shape: ContractShape): Parser<unknown>;
579
946
  * bound holds at every level of nesting, not just the outermost container, on
580
947
  * adversarial input (a huge array, a wide record, a wide union of wide
581
948
  * records). A closed object's extra keys never
582
- * fault — `parse` silently drops them, so `explain` mirrors that leniency; an
583
- * open object with a constraining `additionalProperties` shape recurses extras
584
- * against it instead. A hostile getter or throwing `Proxy` trap is contained
585
- * via {@link attempt} and surfaces as a single top-level type fault, never a
586
- * throw (AGENTS §14). {@link validateShapeDepth} iteratively rejects excessive
587
- * shape nesting or cycles before recursive reporting begins.
949
+ * fault — `parse` silently drops them, so `explain` mirrors that leniency, and
950
+ * {@link compileAuditor} is where they do fault; an open object with a
951
+ * constraining `additionalProperties` shape recurses extras against it instead.
952
+ * A hostile getter or throwing `Proxy` trap is contained via {@link attempt}
953
+ * and surfaces as a single top-level type fault, never a throw (AGENTS §14).
954
+ * It requests exactly the `reporter` root of a fresh {@link ContractCompiler}
955
+ * and applies it once, so one call owns and validates the declaration once
956
+ * rather than re-gating every node it descends into. Reuse the compiler (or a
957
+ * contract's `explain`) when many values are reported against one shape.
588
958
  *
589
959
  * @param shape - The shape to report against
590
960
  * @param value - The value to check
@@ -599,7 +969,7 @@ export declare function compileParser(shape: ContractShape): Parser<unknown>;
599
969
  * compileReporter(user, { name: 'Ada' }) // []
600
970
  * ```
601
971
  */
602
- export declare function compileReporter(shape: ContractShape, value: unknown, path?: string[]): readonly Fault[];
972
+ export declare function compileReporter(shape: ContractShape, value: unknown, path?: readonly string[]): readonly Fault[];
603
973
 
604
974
  /**
605
975
  * Compile a {@link ContractShape} into a JSON Schema document.
@@ -609,8 +979,11 @@ export declare function compileReporter(shape: ContractShape, value: unknown, pa
609
979
  * required keys in `required`; nullable shapes emit an `anyOf` with `{ type:
610
980
  * 'null' }`. The result is an owned deeply frozen graph; raw schemas are cloned
611
981
  * rather than retained by reference. Emission only — it never inspects a
612
- * runtime value. {@link validateShapeDepth} iteratively rejects excessive
613
- * nesting or cycles before recursive emission begins.
982
+ * runtime value. It requests exactly the `schema` root of a fresh
983
+ * {@link ContractCompiler}, so the declaration is owned once and validated once
984
+ * and no other artifact family is built. Shared declaration identity survives
985
+ * into the emitted document: two slots holding one authored node hold one
986
+ * emitted subschema, while structurally equal distinct nodes stay distinct.
614
987
  *
615
988
  * @param shape - The shape to compile
616
989
  * @returns The emitted JSON Schema
@@ -635,6 +1008,68 @@ export declare function compileSchema(shape: ContractShape): JSONSchema;
635
1008
  */
636
1009
  export declare function complementOf<TBase, TExcluded extends TBase>(base: Guard<TBase>, excluded: Guard<TExcluded> | ((value: TBase) => value is TExcluded)): Guard<Exclude<TBase, TExcluded>>;
637
1010
 
1011
+ /**
1012
+ * Run a public door's whole body and publish only this package's error class.
1013
+ *
1014
+ * @remarks
1015
+ * The other half of the answer {@link INTRINSICS} gives, and the half that does
1016
+ * not depend on anyone enumerating anything. Capture removes a named dispatch;
1017
+ * this removes the CONSEQUENCE of every dispatch a door's path still makes,
1018
+ * named or not. Four consecutive rounds fixed the statements they were shown
1019
+ * and were defeated by a statement one line later, because a boundary placed
1020
+ * per statement is only ever as complete as the last sweep. A boundary at the
1021
+ * door composes: whatever the body reaches, and whatever a caller installs
1022
+ * under it, the door publishes a {@link ContractError} or the value it
1023
+ * promised.
1024
+ *
1025
+ * A {@link ContractError} reaching this boundary passes through by identity —
1026
+ * the diagnosis a door spent its whole body computing is the point of the door,
1027
+ * and rewrapping it would demote it to a cause. The mechanism is
1028
+ * {@link isContractError}, which establishes CLASS MEMBERSHIP; it does not and
1029
+ * cannot establish that this package authored the error, and the passthrough is
1030
+ * described by what it tests rather than by what it intends. Anything else is a
1031
+ * host failure the caller arranged, so it is republished under the door's own
1032
+ * name with the exact thrown value retained as `cause`.
1033
+ *
1034
+ * Its population is exactly the public doors that can refuse — every door whose
1035
+ * TSDoc carries `@throws {ContractError}`, and no door whose body cannot throw
1036
+ * at all. A wrapper around a body that only allocates a closure buys nothing
1037
+ * and misreports where the refusals are.
1038
+ *
1039
+ * Use {@link readValue} instead where a single read has its own subject and
1040
+ * deserves its own diagnostic; use this where the subject is the door.
1041
+ *
1042
+ * @param callback - The door body to run
1043
+ * @param door - The public door name used in the diagnostic
1044
+ * @param options - Optional code and structured context for the published refusal
1045
+ * @returns The body's exact return value
1046
+ * @throws {ContractError} The body's own refusal, or a coded translation of a host failure
1047
+ *
1048
+ * @example
1049
+ * ```ts
1050
+ * export function nullShape(options?: NullShapeOptions): NullShape {
1051
+ * return contain(() => buildNullShape(options), 'nullShape')
1052
+ * }
1053
+ * ```
1054
+ */
1055
+ export declare function contain<T>(callback: () => T, door: string, options?: ContainOptions): T;
1056
+
1057
+ /**
1058
+ * Optional diagnostic metadata for a public door's containment boundary.
1059
+ *
1060
+ * @remarks
1061
+ * Deliberately narrower than {@link ReadValueOptions}: a contained door's
1062
+ * subject IS the door, so there is no `subject` to name. The two options types
1063
+ * are separate because a signature that accepts a key it silently ignores tells
1064
+ * the caller a lie the type checker will not catch.
1065
+ */
1066
+ export declare interface ContainOptions {
1067
+ /** Machine-readable refusal category. */
1068
+ readonly code?: ContractCode;
1069
+ /** Structured location and domain details retained by the refusal. */
1070
+ readonly context?: ContractErrorContext;
1071
+ }
1072
+
638
1073
  /** Machine-readable category carried by a {@link ContractError}. */
639
1074
  export declare type ContractCode =
640
1075
  /** Identifies a bound contract error. */
@@ -643,8 +1078,10 @@ export declare type ContractCode =
643
1078
  | 'range'
644
1079
  /** Identifies an empty-value contract error. */
645
1080
  | 'empty'
646
- /** Identifies a placement contract error. */
1081
+ /** Identifies a valid optional shape used in a forbidden position. */
647
1082
  | 'placement'
1083
+ /** Identifies a corrupt shape node or structural slot. */
1084
+ | 'structure'
648
1085
  /** Identifies a literal contract error. */
649
1086
  | 'literal'
650
1087
  /** Identifies a cycle contract error. */
@@ -658,10 +1095,142 @@ export declare type ContractCode =
658
1095
  /** Identifies an owned-clone contract error. */
659
1096
  | 'clone'
660
1097
  /** Identifies a compilation-depth contract error. */
661
- | 'depth';
1098
+ | 'depth'
1099
+ /** Identifies a shape whose compiled expansion exceeds the emitted-node limit. */
1100
+ | 'expansion';
1101
+
1102
+ /**
1103
+ * Lazy compiler owning one contract shape's six artifacts and their bundle.
1104
+ *
1105
+ * @remarks
1106
+ * The engine every standalone `compile*` function and `createContract` now runs
1107
+ * on. Its reason for existing is that the recursive compilers used to re-own and
1108
+ * re-validate the SUBGRAPH at every node they descended into, so a depth-100
1109
+ * chain paid a hundred clones of shrinking graphs and a hundred validations —
1110
+ * quadratic work for a linear declaration, measured at 640 ms for one guard and
1111
+ * 1.87 s for one contract. Here ownership runs once, validation runs once over
1112
+ * that owned result, and each unique node and structural edge is indexed once
1113
+ * into children-before-parent order. Every artifact family is then a single
1114
+ * postorder pass whose entries are keyed by node identity, so a shared child is
1115
+ * compiled once however many parents point at it. The same asymmetry exists on
1116
+ * the VALUE side and is answered the same way: `guard`, `auditor` and `reporter`
1117
+ * carry a call-scoped ledger, so a shared object costs one visit per compiled
1118
+ * node rather than one per path through the graph.
1119
+ *
1120
+ * Construction observes nothing at all: no read, no validation, no clone, no
1121
+ * graph-sized allocation, no clock, no draw. The first getter read prepares; the
1122
+ * getters after it replay. A getter builds its own family and no other, except
1123
+ * that `parser`, `reporter` and `generator` build the guard plan when the graph
1124
+ * holds a union, because a union's membership question IS a guard question in
1125
+ * all three.
1126
+ *
1127
+ * One terminal lifecycle covers preparation and every family. A failure settles
1128
+ * the compiler: later getters rethrow that exact error, while an artifact
1129
+ * already handed out keeps working, because each compiled artifact is
1130
+ * self-contained. Reentry — reachable only through a caller accessor the
1131
+ * declaration itself exposes, since a `pattern` getter is the one accessor
1132
+ * ownership invokes — poisons the nested read, the interrupted outer read, and
1133
+ * every later read with one shared cause-free error.
1134
+ *
1135
+ * @typeParam S - The declaration's shape type, which types the published artifacts
1136
+ *
1137
+ * @example
1138
+ * ```ts
1139
+ * const compiler = new ContractCompiler({ type: 'string', min: 1 })
1140
+ * compiler.guard('Ada') // true
1141
+ * compiler.guard === compiler.guard // true — every getter replays its exact root
1142
+ * ```
1143
+ */
1144
+ export declare class ContractCompiler<S extends ContractShape = ContractShape> implements ContractCompilerInterface<S> {
1145
+ #private;
1146
+ /**
1147
+ * Retain a shape declaration without observing it.
1148
+ *
1149
+ * @param shape - The live declaration the first getter read will own
1150
+ */
1151
+ constructor(shape: S);
1152
+ /**
1153
+ * The emitted JSON Schema for the owned declaration.
1154
+ *
1155
+ * @remarks
1156
+ * A deeply frozen graph that preserves shared declaration identity: two
1157
+ * property slots holding the same authored node hold the same emitted
1158
+ * subschema, while structurally equal distinct nodes stay distinct objects.
1159
+ */
1160
+ get schema(): JSONSchema;
1161
+ /** The compiled strict guard for the owned declaration. */
1162
+ get guard(): Guard<Infer<S>>;
1163
+ /** The compiled coercive parser for the owned declaration. */
1164
+ get parser(): Parser<Infer<S>>;
1165
+ /** The compiled strict-domain diagnostic for the owned declaration. */
1166
+ get auditor(): AuditorFunction;
1167
+ /** The compiled coercive-domain diagnostic for the owned declaration. */
1168
+ get reporter(): ReporterFunction;
1169
+ /** The compiled seed-data source for the owned declaration. */
1170
+ get generator(): SeederFunction<Infer<S>>;
1171
+ /**
1172
+ * The frozen six-member bundle of this compiler's artifacts.
1173
+ *
1174
+ * @remarks
1175
+ * Own enumerable keys `schema`, `is`, `parse`, `audit`, `explain`,
1176
+ * `generate`, in that order, each holding the exact value the corresponding
1177
+ * getter publishes.
1178
+ */
1179
+ get contract(): ContractInterface<Infer<S>>;
1180
+ }
1181
+
1182
+ /**
1183
+ * Lazy owner of one contract shape's six compiled artifacts plus their bundle.
1184
+ *
1185
+ * @remarks
1186
+ * Construction observes nothing. The FIRST getter read owns the declaration
1187
+ * once, validates that owned graph once, and indexes each unique node and
1188
+ * structural edge once into children-before-parent order; every artifact family
1189
+ * is then one postorder pass over that index, so a shared child costs its
1190
+ * authored nodes rather than its paths. A getter builds its own family and no
1191
+ * other, except where an artifact genuinely consumes the compiled guard —
1192
+ * `parser`, `reporter` and `generator` resolve union membership through it, so
1193
+ * they build it too. `contract` requests all six roots in getter order.
1194
+ *
1195
+ * Every getter REPLAYS its exact artifact: reading one twice returns the same
1196
+ * function or graph by identity, and {@link contract}'s six members are those
1197
+ * exact values. One terminal lifecycle covers preparation and every family, so
1198
+ * a failure anywhere settles the compiler permanently — later getters rethrow
1199
+ * that exact error while an artifact already handed out stays usable, because
1200
+ * each one is self-contained. Cross-getter reentry (only reachable through a
1201
+ * caller accessor the declaration exposes) poisons the nested read, the
1202
+ * interrupted outer read, and every later read with one shared cause-free
1203
+ * error.
1204
+ *
1205
+ * @example
1206
+ * ```ts
1207
+ * const compiler = new ContractCompiler(stringShape({ min: 1 }))
1208
+ * compiler.guard('Ada') // true
1209
+ * ```
1210
+ */
1211
+ export declare interface ContractCompilerInterface<S extends ContractShape> {
1212
+ /** The emitted JSON Schema, deeply frozen and shared-identity preserving. */
1213
+ readonly schema: JSONSchema;
1214
+ /** The compiled strict guard. */
1215
+ readonly guard: Guard<Infer<S>>;
1216
+ /** The compiled coercive parser. */
1217
+ readonly parser: Parser<Infer<S>>;
1218
+ /** The compiled strict-domain diagnostic. */
1219
+ readonly auditor: AuditorFunction;
1220
+ /** The compiled coercive-domain diagnostic. */
1221
+ readonly reporter: ReporterFunction;
1222
+ /** The compiled seed-data source. */
1223
+ readonly generator: SeederFunction<Infer<S>>;
1224
+ /** The frozen six-member bundle whose values are the six artifacts above. */
1225
+ readonly contract: ContractInterface<Infer<S>>;
1226
+ }
662
1227
 
663
1228
  /**
664
- * Error carrying a machine-readable contract category and optional context.
1229
+ * Error carrying a machine-readable contract category, optional context, and
1230
+ * an exact optional cause. Omitting `cause` omits the own property; explicitly
1231
+ * supplying `cause: undefined` retains an own property with that value. Both
1232
+ * optional options are read as OWN properties, so a construction never consults
1233
+ * the caller-writable prototype chain of the container it was handed.
665
1234
  *
666
1235
  * @example
667
1236
  * ```ts
@@ -672,6 +1241,7 @@ export declare type ContractCode =
672
1241
  * ```
673
1242
  */
674
1243
  export declare class ContractError extends Error {
1244
+ #private;
675
1245
  readonly name = "ContractError";
676
1246
  readonly code: ContractCode;
677
1247
  readonly context: ContractErrorContext | undefined;
@@ -682,6 +1252,52 @@ export declare class ContractError extends Error {
682
1252
  * @param options - Machine-readable category, optional context, and optional cause
683
1253
  */
684
1254
  constructor(message: string, options: ContractErrorOptions);
1255
+ /**
1256
+ * Hand the module the branded recognition test.
1257
+ *
1258
+ * @remarks
1259
+ * The bootstrap seam, and deliberately NOT a spelling of the recognition
1260
+ * question. Private-name membership is legal only inside this class body, so
1261
+ * something must bridge the class to the module — and the previous bridge was
1262
+ * a static that ANSWERED the question, `ContractError.owns(value)`. That
1263
+ * reintroduced, verbatim, the poisonable surface the private brand was chosen
1264
+ * to remove: one assignment made the package fail to recognize its own errors,
1265
+ * so an engine rewrapped an error it had authored as an unreadable failure,
1266
+ * and a throwing assignment put the caller's raw value through fifteen public
1267
+ * doors.
1268
+ *
1269
+ * This hands over the CLOSURE instead: {@link isContractError} calls it and
1270
+ * applies the result, so the only member on the recognition path hands the
1271
+ * test over rather than answering with it. That per-call read is not a seam,
1272
+ * because the static block below pins this member as a non-writable,
1273
+ * non-configurable own data property.
1274
+ *
1275
+ * An earlier round argued the pin needed no further defence, because a static
1276
+ * block runs during class definition and no order — this module's, an
1277
+ * importer's, or a module that evaluated first — reaches `ContractError.guard`
1278
+ * before the block runs. That is true and it answers the wrong question.
1279
+ * INSTALLING IS NOT READING. The concern was never that something reads the
1280
+ * member unpinned; it was whether the pin installs at all, and the pin is one
1281
+ * live dispatch through `Object.defineProperty`. A module that evaluated
1282
+ * first can replace it with a selective no-op, after which the block runs,
1283
+ * returns, installs nothing, and every later read finds a writable member
1284
+ * again — the whole `owns` defect restored, invisibly, in a realm where every
1285
+ * shipped test still passes.
1286
+ *
1287
+ * So the block VERIFIES its own work and refuses to define the class when the
1288
+ * pin did not take. A silent failure becomes a loud one at import. The
1289
+ * residual is named rather than denied: an adversary who also answers the
1290
+ * verifying descriptor read defeats it, and that adversary already chose what
1291
+ * every capture in this package holds.
1292
+ *
1293
+ * @returns The total recognition guard `isContractError` publishes
1294
+ *
1295
+ * @example
1296
+ * ```ts
1297
+ * ContractError.guard()(new ContractError('x', { code: 'clone' })) // true
1298
+ * ```
1299
+ */
1300
+ static guard(): Guard<ContractError>;
685
1301
  }
686
1302
 
687
1303
  /** Optional structured details carried by a {@link ContractError}. */
@@ -707,27 +1323,64 @@ export declare interface ContractErrorOptions {
707
1323
  }
708
1324
 
709
1325
  /**
710
- * A compiled contract — the five lockstep outputs derived from one shape.
1326
+ * A compiled contract — the six lockstep outputs derived from one shape.
711
1327
  *
712
1328
  * @remarks
713
- * Built by `createContract`: `is` narrows, `parse` coerces (returning the typed
714
- * value or `undefined`), `schema` is an owned deeply frozen emitted JSON
715
- * Schema, `explain` reports the structured faults behind a failed `parse`, and
716
- * `generate` produces deterministic seed data from a {@link RandomFunction}
717
- * (defaulting to a wall-clock-seeded source when none is supplied).
1329
+ * Built by `createContract`: `is` narrows, `audit` diagnoses strict rejection,
1330
+ * `parse` coerces (returning the typed value or `undefined`), `schema` is an
1331
+ * owned deeply frozen emitted JSON Schema, `explain` reports the structured
1332
+ * faults behind a failed `parse`, and `generate` produces deterministic seed
1333
+ * data from a {@link RandomFunction} (defaulting to a wall-clock-seeded source
1334
+ * when none is supplied).
1335
+ *
1336
+ * LOCKSTEP means derived from one owned snapshot of the shape, not agreeing on
1337
+ * which values to accept: `is` and `schema` describe the contract's canonical
1338
+ * domain, while `parse` is a map into that domain whose preimage is
1339
+ * deliberately larger (it coerces leaves and drops a closed object's undeclared
1340
+ * keys). `audit` diagnoses the domain; `explain` diagnoses the map.
1341
+ *
1342
+ * READ STABILITY is the precondition on both soundness laws — `audit` against
1343
+ * `is`, `explain` against `parse`. Each law relates two separate calls, and
1344
+ * every call reads the value it is handed, so both hold for a STABLE value: one
1345
+ * whose observable reads do not change between calls. A getter that answers a
1346
+ * declared string on its first read and a number on its second, or a `Proxy`
1347
+ * whose traps change behavior mid-flight, can leave `audit` empty and still
1348
+ * fail `is`; no law spanning two calls can promise otherwise, and no artifact
1349
+ * re-reads a value to close the gap. This is a statement of scope, not a hedge:
1350
+ * for primitives and data-only structures whose entire observable read surface
1351
+ * stays stable across both calls, both laws hold exactly as written.
1352
+ * `Object.freeze` alone does not establish that condition because it is shallow
1353
+ * and does not stabilize accessors.
718
1354
  */
719
1355
  export declare interface ContractInterface<T> {
720
1356
  readonly schema: JSONSchema;
721
1357
  readonly is: Guard<T>;
722
1358
  parse(value: unknown): T | undefined;
1359
+ /**
1360
+ * Report every strict fault a value has against this contract.
1361
+ *
1362
+ * @remarks
1363
+ * An empty report means the value is strictly valid. Soundness invariant:
1364
+ * `audit(v).length === 0` if and only if `is(v)`, for a value whose reads are
1365
+ * stable across calls (see the read-stability precondition on
1366
+ * {@link ContractInterface}). It is the report for the stricter of the two
1367
+ * domains, so a coercible leaf and a closed object's undeclared key both
1368
+ * fault here and neither faults in `explain`.
1369
+ *
1370
+ * @param value - The value to check
1371
+ * @returns The faults found, empty when the value is strictly valid
1372
+ */
1373
+ audit(value: unknown): readonly AuditFault[];
723
1374
  /**
724
1375
  * Report every structured parse fault a value has against this contract.
725
1376
  *
726
1377
  * @remarks
727
1378
  * An empty report means the value is valid. Soundness invariant:
728
- * `explain(v).length === 0` if and only if `parse(v) !== undefined` — explain
729
- * mirrors `parse`'s coercion, not the stricter `is`. Faults are listed in
730
- * stable pre-order (declared key/index order).
1379
+ * `explain(v).length === 0` if and only if `parse(v) !== undefined`, for a
1380
+ * value whose reads are stable across calls (see the read-stability
1381
+ * precondition on {@link ContractInterface}) — explain mirrors `parse`'s
1382
+ * coercion, not the stricter `is`, and `audit` is the report that mirrors
1383
+ * `is`. Faults are listed in stable pre-order (declared key/index order).
731
1384
  *
732
1385
  * @param value - The value to check
733
1386
  * @returns The faults found, empty when the value parses successfully
@@ -742,28 +1395,59 @@ export declare interface ContractInterface<T> {
742
1395
  *
743
1396
  * @remarks
744
1397
  * A discriminated union keyed on `type`. Shapes nest (an `ArrayShape` holds an
745
- * element shape, an `ObjectShape` a map of them). {@link validateShape}
1398
+ * element shape, an `ObjectShape` a map of them). {@link validateShapeDepth}
746
1399
  * enforces an acyclic graph within {@link COMPILE_DEPTH_LIMIT}.
747
1400
  */
748
1401
  export declare type ContractShape = StringShape | NumberShape | BooleanShape | NullShape | LiteralShape | ArrayShape | ObjectShape | UnionShape | OptionalShape | NullableShape | JSONShape | RawShape;
749
1402
 
750
1403
  /**
751
- * Compile a {@link ContractShape} into a {@link ContractInterface} — the five
752
- * lockstep outputs from one declaration.
1404
+ * Build the length faults an array has against an {@link ArrayShape}.
1405
+ *
1406
+ * @remarks
1407
+ * Takes the LENGTH rather than the array, because both doors have already read
1408
+ * their entries through {@link readArrayEntries} and must report the length that
1409
+ * read observed rather than re-asking the caller's value for it. `received` is
1410
+ * that count rendered through the captured `String`, matching the other length
1411
+ * diagnostics in the package. Order is `min`, then `max`. It refuses an
1412
+ * unreadable shape through the same boundary and for the same reason
1413
+ * {@link createStringFaults} does.
1414
+ *
1415
+ * @param shape - The array shape whose bounds are checked
1416
+ * @param length - The entry count the door already observed
1417
+ * @param path - The path every produced fault is rooted at
1418
+ * @returns A fresh array of faults, empty when the length satisfies both bounds
1419
+ * @throws {ContractError} When the shape's bound fields cannot be read
1420
+ *
1421
+ * @example
1422
+ * ```ts
1423
+ * createArrayFaults({ type: 'array', items: { type: 'string' }, min: 2 }, 1, [])
1424
+ * // [{ reason: 'constraint', path: [], expected: 'array', constraint: 'min', limit: 2, received: '1' }]
1425
+ * ```
1426
+ */
1427
+ export declare function createArrayFaults(shape: ArrayShape, length: number, path: readonly string[]): readonly Fault[];
1428
+
1429
+ /**
1430
+ * Compile a {@link ContractShape} into a {@link ContractInterface} — the six
1431
+ * lockstep outputs from one declaration, lockstep meaning derived from one
1432
+ * owned snapshot rather than accepting the same values.
753
1433
  *
754
1434
  * @remarks
755
- * Runs {@link validateShape} first — a malformed shape throws immediately
756
- * rather than compiling into a silently-wrong contract (AGENTS §12). It always
757
- * takes its own {@link cloneShape} snapshot — never merely a frozen node's word
758
- * — and hands that same graph to every artifact compiler.
759
- * Then it precompiles the deeply frozen owned schema, guard, and parser once;
760
- * `generate` walks the
761
- * snapshot per call with the supplied random source, and `explain` compiles the
762
- * diagnostic report via {@link compileReporter} at zero added compile-time cost
763
- * (it re-walks the snapshot per call, exactly like `generate`).
1435
+ * Creates ONE {@link ContractCompiler} and returns that compiler's exact
1436
+ * `contract` bundle. One ownership population governs the whole contract: the
1437
+ * declaration is owned once through {@link ownShape}, that owned graph is
1438
+ * validated once, and the six artifacts are compiled from it. There is no
1439
+ * discarded pre-ownership pass over the caller's declaration and no second
1440
+ * snapshot — ownership already refuses a malformed structural slot, scalar
1441
+ * field, or bound rather than normalizing it, so a second walk of the caller's
1442
+ * live source only added a population that could disagree with the one the
1443
+ * artifacts actually use.
1444
+ * All six artifacts are precompiled, so `audit`, `explain` and `generate` no
1445
+ * longer re-walk and re-gate the declaration on every call the way they used
1446
+ * to; `contract.audit` and `compileAuditor` are the same compiled function
1447
+ * reached two ways.
764
1448
  *
765
1449
  * @param shape - The shape to compile
766
- * @returns A contract bundling `schema` / `is` / `parse` / `explain` / `generate`
1450
+ * @returns A contract bundling `schema` / `is` / `parse` / `audit` / `explain` / `generate`
767
1451
  *
768
1452
  * @example
769
1453
  * ```ts
@@ -777,6 +1461,72 @@ export declare function createContract<S extends ContractShape>(shape: S): Contr
777
1461
 
778
1462
  export declare function createContract(shape: ContractShape): ContractInterface<unknown>;
779
1463
 
1464
+ /**
1465
+ * Build the refinement faults a number value has against a {@link NumberShape}.
1466
+ *
1467
+ * @remarks
1468
+ * The numeric sibling of {@link createStringFaults}, shared by the same two
1469
+ * doors for the same reason. `expected` is the shape's own kind — `'integer'`
1470
+ * when `integer: true`, otherwise `'number'` — so a caller reading the report
1471
+ * sees the declaration's vocabulary rather than the value's. Order is
1472
+ * `integer`, then `min`, then `max`. It refuses an unreadable shape through the
1473
+ * same boundary and for the same reason {@link createStringFaults} does.
1474
+ *
1475
+ * @param shape - The number shape whose refinements are checked
1476
+ * @param value - The already-obtained number to check
1477
+ * @param path - The path every produced fault is rooted at
1478
+ * @returns A fresh array of faults, empty when the value satisfies every refinement
1479
+ * @throws {ContractError} When the shape's refinement fields cannot be read
1480
+ *
1481
+ * @example
1482
+ * ```ts
1483
+ * createNumberFaults({ type: 'number', integer: true }, 1.5, [])
1484
+ * // [{ reason: 'constraint', path: [], expected: 'integer', constraint: 'integer', received: '1.5' }]
1485
+ * ```
1486
+ */
1487
+ export declare function createNumberFaults(shape: NumberShape, value: number, path: readonly string[]): readonly Fault[];
1488
+
1489
+ /**
1490
+ * Build the refinement faults a string value has against a {@link StringShape}.
1491
+ *
1492
+ * @remarks
1493
+ * The single source of the string refinement report, shared by
1494
+ * `compileReporter` and `compileAuditor`. The two doors differ only in how they
1495
+ * OBTAIN the string — the reporter coerces through `parseString`, the auditor
1496
+ * demands a primitive string — and agreed on every constraint afterwards by
1497
+ * carrying two copies of the same twenty-one lines, which is one edit away from
1498
+ * two contracts. Faults come out in declaration order — `min`, then `max`, then
1499
+ * `pattern` — because a report is read top to bottom and its order is public.
1500
+ *
1501
+ * The pattern is applied through an OWNED stateless rebuild
1502
+ * ({@link readPattern}) and asked through {@link matchesPattern}, so a caller's
1503
+ * `lastIndex` never moves and no caller-writable member decides whether the
1504
+ * value matched.
1505
+ *
1506
+ * The whole body reads the caller's SHAPE, so it runs through the same
1507
+ * {@link readValue} boundary {@link shapeToKind} uses and refuses an
1508
+ * out-of-domain declaration with the same diagnostic. The compiled doors gate a
1509
+ * non-`RegExp` `pattern` and a non-finite bound long before this helper sees
1510
+ * them, so the package's own path never arrives here off-domain — but the door
1511
+ * is PUBLISHED, and a shape a `StringShape` annotation merely vouched for
1512
+ * (parsed out of a document, say) reaches it unchecked. Publishing the host's
1513
+ * own `TypeError` from such a shape would falsify the promise this module makes
1514
+ * for every one of its doors.
1515
+ *
1516
+ * @param shape - The string shape whose refinements are checked
1517
+ * @param value - The already-obtained string to check
1518
+ * @param path - The path every produced fault is rooted at
1519
+ * @returns A fresh array of faults, empty when the value satisfies every refinement
1520
+ * @throws {ContractError} When the shape's refinement fields cannot be read
1521
+ *
1522
+ * @example
1523
+ * ```ts
1524
+ * createStringFaults({ type: 'string', min: 3 }, 'ab', [])
1525
+ * // [{ reason: 'constraint', path: [], expected: 'string', constraint: 'min', limit: 3, received: '"ab"' }]
1526
+ * ```
1527
+ */
1528
+ export declare function createStringFaults(shape: StringShape, value: string, path: readonly string[]): readonly Fault[];
1529
+
780
1530
  /**
781
1531
  * Derive `min`/`max` shape bounds from a pair of non-negative-integer JSON
782
1532
  * Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`).
@@ -836,7 +1586,8 @@ export declare function deriveRangeBounds(min: unknown, max: unknown): {
836
1586
  * @param random - The caller-supplied random source
837
1587
  * @param shape - The shape category consuming the sample
838
1588
  * @returns A finite sample in `[0, 1)`
839
- * @throws {ContractError} When the source throws or returns outside `[0, 1)`
1589
+ * @throws {ContractError} When the source throws or returns outside `[0, 1)`;
1590
+ * a thrown value is retained exactly as the cause
840
1591
  *
841
1592
  * @example
842
1593
  * ```ts
@@ -845,6 +1596,29 @@ export declare function deriveRangeBounds(min: unknown, max: unknown): {
845
1596
  */
846
1597
  export declare function drawRandom(random: RandomFunction, shape: string): number;
847
1598
 
1599
+ /**
1600
+ * Encode one non-container value the way JSON encodes it, or `undefined` when
1601
+ * JSON cannot encode it at all.
1602
+ *
1603
+ * @remarks
1604
+ * The leaf half of {@link canonicalizeValue}: `JSON.stringify` returns
1605
+ * `undefined` (never a string) for `undefined`, a function, and a symbol —
1606
+ * exactly the values with no JSON encoding — and THROWS on a bigint, which is
1607
+ * refused before the call rather than through it. A `Date` and any other
1608
+ * non-record object encode through the same captured `JSON.stringify`, so a
1609
+ * `toJSON` member keeps its ordinary meaning.
1610
+ *
1611
+ * @param value - The non-container value to encode
1612
+ * @returns The JSON encoding, or `undefined` when JSON cannot encode `value`
1613
+ *
1614
+ * @example
1615
+ * ```ts
1616
+ * encodeLeaf(Number.NaN) // 'null'
1617
+ * encodeLeaf(undefined) // undefined
1618
+ * ```
1619
+ */
1620
+ export declare function encodeLeaf(value: unknown): string | undefined;
1621
+
848
1622
  /**
849
1623
  * Snapshot an object's own enumerable string keys through a total boundary.
850
1624
  *
@@ -870,9 +1644,13 @@ export declare function enumerableKeys(value: object): readonly string[] | undef
870
1644
  *
871
1645
  * @remarks
872
1646
  * String keys are ignored — only `Object.getOwnPropertySymbols` entries whose
873
- * descriptor is `enumerable` are counted. Backs the object-emptiness guards
874
- * (`isEmptyObject` / `isNonEmptyObject`) so a record keyed only by an
875
- * enumerable symbol is not mistaken for empty.
1647
+ * descriptor is `enumerable` are counted, and each descriptor is read through
1648
+ * the captured observation so no accessor runs. It answers exactly the
1649
+ * `JSON.stringify`-invisible half of a record's own-symbol population, for a
1650
+ * consumer that needs that count directly. It does NOT back `isEmptyObject` /
1651
+ * `isNonEmptyObject` — those ask the complete own-key question `recordOf` asks,
1652
+ * because an enumerable-only count made their `never` narrowing unsound for an
1653
+ * own non-enumerable key.
876
1654
  *
877
1655
  * @param value - The object to inspect
878
1656
  * @returns The number of enumerable own-symbol keys
@@ -889,6 +1667,10 @@ export declare function enumerableSymbolCount(value: object): number;
889
1667
  /**
890
1668
  * Build a guard from a native `enum` or any object whose values are strings or
891
1669
  * numbers.
1670
+
1671
+ * @param enumeration - The readable enumeration whose values the guard accepts
1672
+ * @returns A guard accepting one enumeration value
1673
+ * @throws {ContractError} When the enumeration cannot be read
892
1674
  *
893
1675
  * @example
894
1676
  * ```ts
@@ -900,6 +1682,12 @@ export declare function enumerableSymbolCount(value: object): number;
900
1682
  */
901
1683
  export declare function enumOf<const E extends Record<string, string | number>>(enumeration: E): Guard<E[keyof E]>;
902
1684
 
1685
+ /** A key present on a value that its closed object shape does not declare. */
1686
+ export declare interface ExtraFault {
1687
+ readonly reason: 'extra';
1688
+ readonly path: FieldPath;
1689
+ }
1690
+
903
1691
  /**
904
1692
  * Discriminated failure branch of a {@link Result}.
905
1693
  *
@@ -954,14 +1742,17 @@ export declare type Fault = {
954
1742
  };
955
1743
 
956
1744
  /**
957
- * The maximum number of {@link Fault} entries a single `explain` report ever
958
- * returns, frozen.
1745
+ * The maximum number of {@link Fault} / {@link AuditFault} entries a single
1746
+ * `explain` or `audit` report ever returns, frozen.
959
1747
  *
960
1748
  * @remarks
961
- * Bounds the report against adversarial input (a giant array, a wide record) —
962
- * `compileReporter` collects faults in stable pre-order and stops once this cap
963
- * is reached, so the report size (and the work to build it) stays finite and
964
- * deterministic regardless of the input's size.
1749
+ * Bounds BOTH reports against adversarial input (a giant array, a wide record)
1750
+ * — `compileReporter` and `compileAuditor` each collect faults in stable
1751
+ * pre-order and stop once this cap is reached, and every recursive call slices
1752
+ * to it, so the report size (and the work to build it) stays finite and
1753
+ * deterministic at every nesting level regardless of the input's size. Size a
1754
+ * diagnostic surface off this constant and it bounds `audit` exactly as it
1755
+ * bounds `explain`.
965
1756
  */
966
1757
  export declare const FAULT_LIMIT = 64;
967
1758
 
@@ -1030,13 +1821,15 @@ export declare const GENERATION_ATTEMPT_LIMIT = 32;
1030
1821
  export declare type Guard<T> = (value: unknown) => value is T;
1031
1822
 
1032
1823
  /**
1033
- * The maximum number of active {@link lazyOf} invocations for one lazy guard,
1824
+ * The maximum active recursion or JSON container depth for runtime guards,
1034
1825
  * frozen.
1035
1826
  *
1036
1827
  * @remarks
1037
1828
  * Bounds explicitly recursive guards before the JavaScript call stack becomes
1038
- * the limiting mechanism. An invocation beyond this depth returns `false`, and
1039
- * the counter unwinds after every contained guard call.
1829
+ * the limiting mechanism. It also caps array/plain-record containers on each
1830
+ * active path inspected by {@link matchesJSONDepth}: noncontainers are depth
1831
+ * zero, an empty container is depth one, 512 containers pass, and the 513th
1832
+ * fails. Active cycle edges do not add a level.
1040
1833
  *
1041
1834
  * @example
1042
1835
  * ```ts
@@ -1123,14 +1916,21 @@ export declare type Infer<S extends ContractShape> = [ContractShape] extends [S]
1123
1916
  export declare const INFER_BREADTH_LIMIT = 256;
1124
1917
 
1125
1918
  /**
1126
- * The default maximum object/array nesting depth {@link valueToSchema} walks,
1127
- * frozen.
1919
+ * The maximum object/array nesting depth {@link valueToSchema} walks, frozen.
1128
1920
  *
1129
1921
  * @remarks
1130
1922
  * Bounds inference against adversarial or cyclic runtime input — once the
1131
1923
  * remaining depth budget reaches zero, inference stops descending and emits
1132
1924
  * the empty accept-anything schema `{}` for that branch instead of recursing
1133
- * further. Overridable per call via {@link ValueToSchemaOptions.maxDepth}.
1925
+ * further. LOWERABLE per call via {@link ValueToSchemaOptions.maxDepth}; a
1926
+ * higher value is held here.
1927
+ *
1928
+ * A ceiling rather than a default, because the walk recurses: what a deeper
1929
+ * walk spends is the JavaScript call stack rather than this budget, and that
1930
+ * stack is not a fixed quantity. The survivable depth measured on one host rose
1931
+ * across repeated calls within a single process as the engine optimized, and
1932
+ * fell to roughly this number under a reduced stack size. Any larger constant
1933
+ * therefore has a host where it fails, which is why none is published.
1134
1934
  */
1135
1935
  export declare const INFER_DEPTH_LIMIT = 32;
1136
1936
 
@@ -1156,31 +1956,34 @@ export declare const INFER_ENUM_LIMIT = 12;
1156
1956
  * depth) and unified with {@link unifySchemas}: a single distinct element
1157
1957
  * schema becomes `items` directly; multiple distinct schemas become
1158
1958
  * `items: { anyOf: [...] }`. Depth exhaustion or a cyclic re-encounter of
1159
- * `value` both yield the empty schema `{}` instead of descending. A sparse
1160
- * array (holes, e.g. `[1, , 3]`) is densified via `Array.from` before
1161
- * sampling so every slot — including a hole — is visited as an explicit
1162
- * `undefined` leaf (which {@link inferValue} maps to `{}`), rather than left
1163
- * as a hole that would otherwise reach {@link unifySchemas} as `undefined`.
1959
+ * `value` both yield the empty schema `{}` instead of descending. A SPARSE
1960
+ * array (holes, e.g. `[1, , 3]`) has no JSON expression and widens to the
1961
+ * accept-anything `{}`, the same treatment `NaN`, a function, a symbol, a
1962
+ * `Map` and a `Set` receive — it is not read as a list of present `undefined`
1963
+ * leaves, because the array schema that reading produced was rejected by its
1964
+ * own compiled guard, which is the one direction the round-trip law forbids.
1965
+ * Invalid direct depth and breadth budgets use {@link sanitizeBudget} with the
1966
+ * package defaults, matching the higher-level inference boundaries.
1164
1967
  *
1165
1968
  * ALL reads of `value` — including its `length` — happen inside
1166
- * {@link attempt}: a hostile `length` getter (e.g. a Proxy-over-array whose
1167
- * `get` trap throws) is exactly as contained as a throwing own-getter element
1168
- * or a Proxy-over-array element access, and cannot escape as a thrown error.
1169
- * On failure — or when the sampled/classified list ends up empty — this
1170
- * returns `{ type: 'array' }` (no `items`), since `value` is still known to
1171
- * be an array, mirroring the empty-array emission. A same-object
1172
- * re-inference at the same remaining `depth` is served from `memo` instead
1173
- * of recomputing (guards a shared-reference DAG against exponential blowup).
1969
+ * {@link attempt}, then cross {@link readValue}: a hostile `length` getter,
1970
+ * throwing own-getter element, or hostile element access raises the shared
1971
+ * coded refusal instead of returning the empty-array schema. A genuinely
1972
+ * empty sampled/classified list still returns `{ type: 'array' }` with no
1973
+ * `items`. A same-object re-inference at the same remaining `depth` is served
1974
+ * from `memo` instead of recomputing (guards a shared-reference DAG against
1975
+ * exponential blowup).
1174
1976
  *
1175
1977
  * @param value - The array to infer from
1176
- * @param depth - Remaining descent budget
1177
- * @param breadth - The maximum number of elements sampled
1978
+ * @param depth - Remaining descent budget; invalid values use the package default
1979
+ * @param breadth - Maximum elements sampled; invalid values use the package default
1178
1980
  * @param closed - Threaded through to nested object elements
1179
1981
  * @param format - Threaded through to nested string/`Date` elements
1180
1982
  * @param visited - The ancestor set guarding against cycles
1181
1983
  * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
1182
1984
  * against exponential re-inference of a shared-reference DAG
1183
1985
  * @returns The inferred array schema
1986
+ * @throws {ContractError} When the array cannot be read
1184
1987
  *
1185
1988
  * @example
1186
1989
  * ```ts
@@ -1256,8 +2059,9 @@ export declare type InferObject<P extends Readonly<Record<string, ContractShape>
1256
2059
  * Own enumerable string keys via {@link enumerableKeys}, sorted
1257
2060
  * lexicographically for deterministic output, capped at `breadth`. This is the
1258
2061
  * same property view compiled object guards, parsers, and reporters use. Each
1259
- * property value is read through {@link attempt} so a hostile getter cannot
1260
- * escape as a thrown error; a property whose value is `undefined` is DROPPED
2062
+ * property value is read through {@link attempt} and {@link readValue}; a
2063
+ * hostile getter raises the shared coded refusal. A readable property whose
2064
+ * value is `undefined` is DROPPED
1261
2065
  * — JSON encodes no such property (`JSON.stringify({ a: undefined })` is
1262
2066
  * `'{}'`), so it contributes neither a `properties` entry nor a `required`
1263
2067
  * entry. Every other present key is required (single-value mode).
@@ -1285,6 +2089,7 @@ export declare type InferObject<P extends Readonly<Record<string, ContractShape>
1285
2089
  * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
1286
2090
  * against exponential re-inference of a shared-reference DAG
1287
2091
  * @returns The inferred object schema
2092
+ * @throws {ContractError} When the record cannot be read
1288
2093
  *
1289
2094
  * @example
1290
2095
  * ```ts
@@ -1374,20 +2179,19 @@ export declare function inferPrimitiveEnum(values: readonly unknown[], limit: nu
1374
2179
  * {@link inferArray}, this path carries no `visited` `WeakSet` — a value
1375
2180
  * shared by reference across multiple sample rows is legitimate (not a
1376
2181
  * cycle back to an ancestor), so termination on cyclic row data relies on
1377
- * the decrementing `depth` budget alone.
1378
- *
1379
- * `additionalProperties` is forced to `true` regardless of `closed` whenever
1380
- * the declared key list stops describing every key the rows carry — the same
1381
- * incomplete-sample-opens-the-schema rule {@link inferObject} applies, so a
1382
- * closed schema never rejects the very rows it was inferred from. That happens
1383
- * three ways: the union of sample keys exceeds `breadth` (truncation); a
1384
- * hostile getter defeats a key's value walk (which drops that key for ALL
1385
- * rows — a deliberate all-or-nothing scope, not a per-row partial failure);
1386
- * or some row carries the key as an own property holding `undefined`, which
1387
- * JSON encodes as no property at all, so the key is dropped rather than
1388
- * declared with a shape that row would fail. When the KEY walk itself fails
1389
- * (a hostile `ownKeys` trap on any row), nothing is known and the whole slot
1390
- * widens to `{}`.
2182
+ * the decrementing `depth` budget and the shared {@link SampleMemo}.
2183
+ *
2184
+ * `additionalProperties` is forced to `true` regardless of `closed` when the
2185
+ * key union exceeds `breadth`, or a readable row carries a key as an own
2186
+ * property holding `undefined`. A hostile getter or failed KEY walk throws the
2187
+ * shared coded refusal instead of dropping a key or widening the whole slot.
2188
+ *
2189
+ * The memo is keyed by the slot's ORDERED row identities, not by a single row.
2190
+ * Keying only the one-row slot left every MULTI-row slot — the shape this door
2191
+ * exists for — re-inferring a shared child once per path: two rows sharing one
2192
+ * `{ a: child, b: child }` detail cost `2^depth` inferences, the identical
2193
+ * denial of service the one-row memo was added to remove, through the same
2194
+ * public door.
1391
2195
  *
1392
2196
  * @param samples - The plain-record samples
1393
2197
  * @param depth - Remaining descent budget
@@ -1395,16 +2199,19 @@ export declare function inferPrimitiveEnum(values: readonly unknown[], limit: nu
1395
2199
  * @param closed - Whether the emitted schema closes to unknown keys
1396
2200
  * @param format - Whether a unanimous string column gains a `format` keyword
1397
2201
  * @param enumOn - Whether a low-cardinality column may emit `enum`
2202
+ * @param memo - The walk's {@link SampleMemo}, shared with
2203
+ * {@link inferSamples}; build one with {@link buildSampleMemo}
1398
2204
  * @returns The inferred object schema
2205
+ * @throws {ContractError} When a sample row or the memo cannot be read
1399
2206
  *
1400
2207
  * @example
1401
2208
  * ```ts
1402
- * inferRecordSamples([{ id: 1 }, { id: 2, name: 'Ada' }], 32, 256, true, false, false)
2209
+ * inferRecordSamples([{ id: 1 }, { id: 2, name: 'Ada' }], 32, 256, true, false, false, buildSampleMemo())
1403
2210
  * // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },
1404
2211
  * // required: ['id'], additionalProperties: false }
1405
2212
  * ```
1406
2213
  */
1407
- export declare function inferRecordSamples(samples: readonly Record<string, unknown>[], depth: number, breadth: number, closed: boolean, format: boolean, enumOn: boolean): JSONSchema;
2214
+ export declare function inferRecordSamples(samples: readonly Record<string, unknown>[], depth: number, breadth: number, closed: boolean, format: boolean, enumOn: boolean, memo: SampleMemo): JSONSchema;
1408
2215
 
1409
2216
  /**
1410
2217
  * Infer a `JSONSchema` for a collected slot of sample values — the shared
@@ -1429,15 +2236,20 @@ export declare function inferRecordSamples(samples: readonly Record<string, unkn
1429
2236
  * @param closed - Whether nested objects close to unknown keys
1430
2237
  * @param format - Whether a unanimous string slot gains a `format` keyword
1431
2238
  * @param enumOn - Whether low-cardinality primitive slots may emit `enum`
2239
+ * @param memo - The walk's {@link SampleMemo}, shared with
2240
+ * {@link inferRecordSamples} so a row list reached through
2241
+ * several slots is inferred once; build one with
2242
+ * {@link buildSampleMemo}
1432
2243
  * @returns The inferred schema for the slot
2244
+ * @throws {ContractError} When the samples or the memo cannot be read
1433
2245
  *
1434
2246
  * @example
1435
2247
  * ```ts
1436
- * inferSamples(['2024-01-01', '2024-02-02'], 32, 256, true, true, false)
2248
+ * inferSamples(['2024-01-01', '2024-02-02'], 32, 256, true, true, false, buildSampleMemo())
1437
2249
  * // { type: 'string', format: 'date' }
1438
2250
  * ```
1439
2251
  */
1440
- export declare function inferSamples(samples: readonly unknown[], depth: number, breadth: number, closed: boolean, format: boolean, enumOn: boolean): JSONSchema;
2252
+ export declare function inferSamples(samples: readonly unknown[], depth: number, breadth: number, closed: boolean, format: boolean, enumOn: boolean, memo: SampleMemo): JSONSchema;
1441
2253
 
1442
2254
  /** {@link Infer} of a union shape's `variants` — the union of each variant's inferred type. */
1443
2255
  export declare type InferUnion<V extends readonly ContractShape[]> = V extends readonly (infer U)[] ? U extends ContractShape ? Infer<U> : never : never;
@@ -1448,7 +2260,8 @@ export declare type InferUnion<V extends readonly ContractShape[]> = V extends r
1448
2260
  * {@link inferArray} / {@link inferObject}.
1449
2261
  *
1450
2262
  * @remarks
1451
- * Total: never throws, and terminates on cyclic input via `visited`. Leaf
2263
+ * Terminates on cyclic readable input via `visited`; failed traversal is
2264
+ * refused by the containing public reader. Leaf
1452
2265
  * classification order: `null`, boolean, integer (`Number.isInteger`
1453
2266
  * semantics — `-0` counts), finite non-integer number, string (gaining a
1454
2267
  * `format` keyword when `format` is on and {@link stringToFormat} matches),
@@ -1475,6 +2288,7 @@ export declare type InferUnion<V extends readonly ContractShape[]> = V extends r
1475
2288
  * @param memo - A per-call `(object, remaining depth) → schema` cache guarding
1476
2289
  * against exponential re-inference of a shared-reference DAG
1477
2290
  * @returns The inferred schema fragment for `value`
2291
+ * @throws {ContractError} When a traversed container cannot be read
1478
2292
  *
1479
2293
  * @example
1480
2294
  * ```ts
@@ -1528,6 +2342,229 @@ export declare function intersectionOf<const Gs extends ReadonlyArray<Guard<unkn
1528
2342
 
1529
2343
  export declare function intersectionOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown>;
1530
2344
 
2345
+ /**
2346
+ * Every host operation this package dispatches through, captured while this
2347
+ * module evaluates.
2348
+ *
2349
+ * @remarks
2350
+ * THE answer to a defect class that mutated four times before anyone stated it
2351
+ * as a class. A caller can replace a global constructor, a static, a prototype
2352
+ * member, or a symbol-keyed hook, and each replacement can fail in two ways: it
2353
+ * can THROW, which a boundary contains, or it can LIE, which no boundary can
2354
+ * see. `Object.freeze = (value) => value` is the second kind and it is the
2355
+ * worse one: every cloner succeeds, publishes a mutable graph, and the caller
2356
+ * cannot tell that the package's central guarantee evaporated.
2357
+ *
2358
+ * Containment cannot close that, because there is nothing to contain — only
2359
+ * capture can, and only capture taken while this module evaluates. A module's
2360
+ * initializers run at import, so a reference read here is whatever was
2361
+ * installed at the moment THIS module evaluated, and reading it later, at the
2362
+ * call site, is reading whatever the caller most recently installed. "Before any
2363
+ * caller code runs" is the tempting phrasing and it is false in exactly the case
2364
+ * the limit below names, so it is not used.
2365
+ *
2366
+ * The limit that follows, stated as a limit rather than as a guarantee: capture
2367
+ * is only as early as this package's own evaluation. A consumer module that
2368
+ * evaluates BEFORE `@orkestrel/contract` — ESM evaluates imports in source
2369
+ * order — chooses what this table captures, and no mechanism inside the package
2370
+ * can reach code that ran before the package existed. That precondition is
2371
+ * outside this package's control, and an adversary who holds it can replace the
2372
+ * package wholesale rather than bother with the table, so it is named here
2373
+ * instead of defended.
2374
+ *
2375
+ * Membership rule, stated so a reviewer can apply it and a new call site knows
2376
+ * where to go: **every host operation this package dispatches by name whose
2377
+ * result a published answer depends on.** That admits statics, constructors and
2378
+ * namespaces, and — this is the part the earlier wording got wrong by writing
2379
+ * the rule from the rows instead of the rows from the rule — it admits a
2380
+ * PROTOTYPE member on the same terms, including an ACCESSOR's getter,
2381
+ * dispatched onto the package's own receiver through {@link INTRINSICS.apply}.
2382
+ * A round that read `Object.getOwnPropertyDescriptor(RegExp.prototype, 'source')`
2383
+ * per call had captured nothing: capture is decided by WHEN the reference is
2384
+ * taken, not by which reflective spelling takes it.
2385
+ *
2386
+ * Collection membership was previously excluded on the grounds that it needs a
2387
+ * data structure rather than one operation, and the exclusion was answered with
2388
+ * an exported class whose `has` method every consumer could rewrite — which
2389
+ * reproduced the whole defect one prototype higher. The rule has no exception
2390
+ * for it: `Set.prototype.has` / `.add` / `.forEach`,
2391
+ * `Map.prototype.has` / `.forEach`, and
2392
+ * `WeakSet.prototype.has` / `.add` / `.delete` are ordinary rows here, dispatched
2393
+ * onto collections this package built and no caller holds, and every membership
2394
+ * and visitation answer in the package is asked through the module-scope
2395
+ * functions {@link matchesMember} / {@link admitMember} /
2396
+ * {@link matchesVisited} / {@link admitVisited} / {@link omitVisited}. A module
2397
+ * binding is not a property, so there is no member on that path to replace.
2398
+ *
2399
+ * The walk-collection exclusion the earlier wording carried — "a redirect
2400
+ * corrupts it inside a boundary and the door refuses, which is loud" — was
2401
+ * false in the direction the corpus itself installs. `WeakSet.prototype.has`
2402
+ * answering `false` does not make a cyclic clone refuse; it removes the
2403
+ * termination bound, and a door that never returns is the one failure no
2404
+ * boundary can report. Visitation state is captured here for that reason.
2405
+ *
2406
+ * @example
2407
+ * ```ts
2408
+ * INTRINSICS.freeze(snapshot) // the genuine Object.freeze, whatever the caller installed
2409
+ * ```
2410
+ */
2411
+ export declare const INTRINSICS: Readonly<{
2412
+ /** `Object.freeze` — the operation the ownership guarantee is made of. */
2413
+ freeze: {
2414
+ <T extends Function>(f: T): T;
2415
+ <T extends {
2416
+ [idx: string]: U | null | undefined | object;
2417
+ }, U extends string | bigint | number | boolean | symbol>(o: T): Readonly<T>;
2418
+ <T>(o: T): Readonly<T>;
2419
+ };
2420
+ /** `Object.isFrozen` — the independent check that the guarantee actually held. */
2421
+ frozen: (o: any) => boolean;
2422
+ /** `Object.keys` — the own enumerable string-key population of a snapshot. */
2423
+ keys: {
2424
+ (o: object): string[];
2425
+ (o: {}): string[];
2426
+ };
2427
+ /** `Object.values` — the own enumerable value population of a snapshot. */
2428
+ values: {
2429
+ <T>(o: {
2430
+ [s: string]: T;
2431
+ } | ArrayLike<T>): T[];
2432
+ (o: {}): any[];
2433
+ };
2434
+ /** `Object.hasOwn` — own presence, so no read leaves a container for its prototype. */
2435
+ own: (o: object, v: PropertyKey) => boolean;
2436
+ /** `Object.is` — `SameValue`, so a `NaN` or signed-zero comparison stays exact. */
2437
+ same: (value1: any, value2: any) => boolean;
2438
+ /** `Object.create` — the null-prototype and prototype-pinned accumulators. */
2439
+ create: {
2440
+ (o: object | null): any;
2441
+ (o: object | null, properties: PropertyDescriptorMap & ThisType<any>): any;
2442
+ };
2443
+ /** `Object.getOwnPropertyDescriptor` — value observation that runs no accessor. */
2444
+ describe: (o: any, p: PropertyKey) => PropertyDescriptor | undefined;
2445
+ /** `Object.defineProperty` — exact placement of an own data property. */
2446
+ define: <T>(o: T, p: PropertyKey, attributes: PropertyDescriptor & ThisType<any>) => T;
2447
+ /** `Object.getPrototypeOf` — the record-brand observation. */
2448
+ prototype: (o: any) => any;
2449
+ /** `Object.getOwnPropertySymbols` — the own-symbol population. */
2450
+ symbols: (o: any) => symbol[];
2451
+ /** `Object.prototype` — the realm-local plain-record prototype identity. */
2452
+ base: Object;
2453
+ /** `Reflect.get` — a proxy-visible read that reports the trap's exact answer. */
2454
+ read: typeof Reflect.get;
2455
+ /** `Reflect.set` — a proxy-visible write. */
2456
+ write: typeof Reflect.set;
2457
+ /** `Reflect.ownKeys` — the complete own-key population, strings and symbols. */
2458
+ members: typeof Reflect.ownKeys;
2459
+ /** `Reflect.has` — a proxy-visible presence observation. */
2460
+ present: typeof Reflect.has;
2461
+ /** `Reflect.getOwnPropertyDescriptor` — the reflective descriptor observation. */
2462
+ reveal: typeof Reflect.getOwnPropertyDescriptor;
2463
+ /** `Reflect.defineProperty` — placement that answers instead of throwing. */
2464
+ declare: typeof Reflect.defineProperty;
2465
+ /** `Reflect.getPrototypeOf` — the reflective prototype observation. */
2466
+ parent: typeof Reflect.getPrototypeOf;
2467
+ /** `Reflect.apply` — dispatch of a captured method onto its receiver. */
2468
+ apply: typeof Reflect.apply;
2469
+ /** `Reflect.construct` — construction with an explicit new target. */
2470
+ construct: typeof Reflect.construct;
2471
+ /** `Number.isFinite` — the finite-bound test every numeric shape refuses on. */
2472
+ finite: (number: unknown) => boolean;
2473
+ /** `Number.isInteger` — the integer-budget test the inference caps refuse on. */
2474
+ integer: (number: unknown) => boolean;
2475
+ /** `Number.isSafeInteger` — the safe-integer test every length bound refuses on. */
2476
+ safe: (number: unknown) => boolean;
2477
+ /** `Number.isNaN` — the calendar-validity test for a parsed instant. */
2478
+ nan: (number: unknown) => boolean;
2479
+ /** `Array.isArray` — array identity across realms. */
2480
+ array: (arg: any) => arg is any[];
2481
+ /** `JSON.stringify` — the escaping used by previews and canonical text. */
2482
+ stringify: {
2483
+ (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
2484
+ (value: any, replacer?: (number | string)[] | null, space?: string | number): string;
2485
+ };
2486
+ /** `JSON.parse` — document decoding. */
2487
+ decode: (text: string, reviver?: (this: any, key: string, value: any) => any) => any;
2488
+ /** `Math.floor` — index and quantity flooring. */
2489
+ floor: (x: number) => number;
2490
+ /** `Math.ceil` — index and quantity ceiling. */
2491
+ ceil: (x: number) => number;
2492
+ /** `Math.max` — bound selection. */
2493
+ max: (...values: number[]) => number;
2494
+ /** `Math.min` — bound selection. */
2495
+ min: (...values: number[]) => number;
2496
+ /** `Math.imul` — the seeded generator's mixing step. */
2497
+ imul: (x: number, y: number) => number;
2498
+ /** `String` — primitive text coercion. */
2499
+ text: StringConstructor;
2500
+ /** `Number` — primitive numeric coercion. */
2501
+ numeric: NumberConstructor;
2502
+ /** `RegExp` — pattern construction from captured source and flags. */
2503
+ pattern: RegExpConstructor;
2504
+ /**
2505
+ * `RegExp.prototype.exec` — THE pattern membership answer, dispatched through
2506
+ * `apply`.
2507
+ *
2508
+ * @remarks
2509
+ * `test` is deliberately absent. `RegExp.prototype.test` is spec-defined in
2510
+ * terms of `RegExpExec`, which re-reads `exec` OFF THE RECEIVER and calls it
2511
+ * when it is callable, so capturing `test` and dispatching it still asks
2512
+ * whatever the caller installed on `RegExp.prototype.exec`. Only
2513
+ * `RegExp.prototype.exec` itself is `RegExpBuiltinExec`, which reads the
2514
+ * pattern's internal slots and no member at all. A capture that still routes
2515
+ * through the replaced member is not a capture.
2516
+ */
2517
+ captures: (string: string) => RegExpExecArray | null;
2518
+ /** The `RegExp.prototype.source` getter — the pattern text a published schema embeds, dispatched through `apply`. */
2519
+ expression: (() => any) | undefined;
2520
+ /** The `RegExp.prototype.flags` getter — the flag text an owned pattern is rebuilt from, dispatched through `apply`. */
2521
+ modifiers: (() => any) | undefined;
2522
+ /** `Array` — array construction. */
2523
+ list: ArrayConstructor;
2524
+ /** `Array.prototype.sort` — the deterministic ordering every published schema is emitted in, dispatched through `apply`. */
2525
+ order: (compareFn?: ((a: any, b: any) => number) | undefined) => any[];
2526
+ /** `Map` — keyed working state. */
2527
+ map: MapConstructor;
2528
+ /** `Map.prototype.get` — a memo read whose answer a published graph embeds, dispatched through `apply`. */
2529
+ fetch: (key: any) => any;
2530
+ /** `Map.prototype.set` — a memo write a published graph is later assembled from, dispatched through `apply`. */
2531
+ store: (key: any, value: any) => Map<any, any>;
2532
+ /** `Map.prototype.has` — a memo presence answer that decides whether a node is captured, dispatched through `apply`. */
2533
+ keyed: (key: any) => boolean;
2534
+ /** `Map.prototype.forEach` — the only full view of a caller's `Map` that runs no iterator, dispatched through `apply`. */
2535
+ pairs: (callbackfn: (value: any, key: any, map: Map<any, any>) => void, thisArg?: any) => void;
2536
+ /** `Set` — membership working state. */
2537
+ set: SetConstructor;
2538
+ /** `Set.prototype.has` — THE membership answer every published verdict rests on, dispatched through `apply`. */
2539
+ member: (value: any) => boolean;
2540
+ /** `Set.prototype.add` — collection of one more member, dispatched through `apply`. */
2541
+ admit: (value: any) => Set<any>;
2542
+ /** `Set.prototype.forEach` — the only full view of a caller's `Set` that runs no iterator, dispatched through `apply`. */
2543
+ sweep: (callbackfn: (value: any, value2: any, set: Set<any>) => void, thisArg?: any) => void;
2544
+ /** `WeakMap` — object-keyed working state. */
2545
+ weakMap: WeakMapConstructor;
2546
+ /** `WeakMap.prototype.get` — an object-keyed memo read a published graph embeds, dispatched through `apply`. */
2547
+ recall: (key: WeakKey) => any;
2548
+ /** `WeakMap.prototype.set` — an object-keyed memo write, dispatched through `apply`. */
2549
+ retain: (key: WeakKey, value: any) => WeakMap<WeakKey, any>;
2550
+ /** `WeakSet` — object-membership working state. */
2551
+ weakSet: WeakSetConstructor;
2552
+ /** `WeakSet.prototype.has` — the visitation answer every traversal's termination rests on, dispatched through `apply`. */
2553
+ tracked: (value: WeakKey) => boolean;
2554
+ /** `WeakSet.prototype.add` — entry onto the active path, dispatched through `apply`. */
2555
+ track: (value: WeakKey) => WeakSet<WeakKey>;
2556
+ /** `WeakSet.prototype.delete` — exit from the active path, dispatched through `apply`. */
2557
+ untrack: (value: WeakKey) => boolean;
2558
+ /** `Error` — the internal marker an engine throws into its own contained walk. */
2559
+ error: ErrorConstructor;
2560
+ /** `Date` — calendar validation of an ISO instant. */
2561
+ date: DateConstructor;
2562
+ /** `Date.prototype.getTime` — the calendar verdict a published `format` rests on, dispatched through `apply`. */
2563
+ instant: () => number;
2564
+ /** `Date.now` — the wall-clock reading a default generator seed is drawn from. */
2565
+ now: () => number;
2566
+ }>;
2567
+
1531
2568
  /** Determine whether a value is an array.
1532
2569
  *
1533
2570
  * @example
@@ -1645,26 +2682,89 @@ export declare function isBigUint64Array(value: unknown): value is BigUint64Arra
1645
2682
  export declare function isBoolean(value: unknown): value is boolean;
1646
2683
 
1647
2684
  /**
1648
- * Determine whether a value can be used as a `new`-target constructor.
2685
+ * Determine whether a value is a depth-bounded JSON record.
1649
2686
  *
1650
2687
  * @remarks
1651
- * Probes with `Reflect.construct(String, [], value)`: a real constructor
1652
- * succeeds, while arrow functions, plain functions, and non-functions throw
1653
- * and yield `false`. Never throws. Backs the `instanceOf` combinator.
2688
+ * Requires the existing plain-record root invariant before applying
2689
+ * {@link isBoundedJSONValue}. Arrays therefore remain valid bounded JSON
2690
+ * values but never bounded JSON records.
2691
+ *
2692
+ * @param value - The value to inspect
2693
+ * @returns `true` when the value is a plain-record-rooted bounded JSON value
1654
2694
  *
1655
2695
  * @example
1656
2696
  * ```ts
1657
- * isConstructor(class X {}) // true
1658
- * isConstructor(() => {}) // false
2697
+ * isBoundedJSONRecord({ value: 1 }) // true
2698
+ * isBoundedJSONRecord([1]) // false
1659
2699
  * ```
1660
2700
  */
1661
- export declare function isConstructor(value: unknown): value is AnyConstructor<object>;
2701
+ export declare function isBoundedJSONRecord(value: unknown): value is JSONRecord;
1662
2702
 
1663
2703
  /**
1664
- * Determine whether an unknown value is a {@link ContractError}.
2704
+ * Determine whether a value is JSON-valid within the fixed container-depth limit.
2705
+ *
2706
+ * @remarks
2707
+ * Runs the total depth predicate before the existing JSON guard. These are
2708
+ * sequential observations of caller-owned input, not an atomic snapshot.
2709
+ *
2710
+ * @param value - The value to inspect
2711
+ * @returns `true` when the value is both depth-bounded and a valid {@link JSONValue}
2712
+ *
2713
+ * @example
2714
+ * ```ts
2715
+ * isBoundedJSONValue({ nested: [1] }) // true
2716
+ * isBoundedJSONValue(new Date()) // false
2717
+ * ```
2718
+ */
2719
+ export declare function isBoundedJSONValue(value: unknown): value is JSONValue;
2720
+
2721
+ /**
2722
+ * Determine whether a value can be used as a `new`-target constructor.
2723
+ *
2724
+ * @remarks
2725
+ * Probes with `Reflect.construct(String, [], value)`: a real constructor
2726
+ * succeeds, while arrow functions, plain functions, and non-functions throw
2727
+ * and yield `false`. Never throws. Backs the `instanceOf` combinator.
2728
+ *
2729
+ * @example
2730
+ * ```ts
2731
+ * isConstructor(class X {}) // true
2732
+ * isConstructor(() => {}) // false
2733
+ * ```
2734
+ */
2735
+ export declare function isConstructor(value: unknown): value is AnyConstructor<object>;
2736
+
2737
+ /**
2738
+ * Determine whether an unknown value is a {@link ContractError}.
2739
+ *
2740
+ * @remarks
2741
+ * The ONLY spelling of the recognition question this package publishes. The test
2742
+ * itself is a private static of the class, because private-name membership is
2743
+ * legal only inside a class body; the one member on the path,
2744
+ * {@link ContractError.guard}, hands that test over and is pinned non-writable
2745
+ * and non-configurable while the class is defined. So there is no property a
2746
+ * caller can point somewhere else, and no member that ANSWERS the recognition
2747
+ * question — which is exactly what the static that preceded it did.
2748
+ *
2749
+ * A function declaration rather than a `const` holding the retrieved closure.
2750
+ * The retrieved form was tried and was wrong twice over: a module-scope binding
2751
+ * bound to a computed value is module DATA, which belongs in a data kind file
2752
+ * and not in the file that owns the error classes and their guards; and the
2753
+ * single read it bought guarded a window that does not exist, since the pin is
2754
+ * installed during class definition and no code can observe this member before
2755
+ * it. Reading a permanently pinned own data property per call buys the caller
2756
+ * nothing, so the guard is spelled as what it is.
2757
+ *
2758
+ * Recognition is realm-local and identity-based: a value from another copy of
2759
+ * this module is not this class's error, exactly as `instanceof` reported; a
2760
+ * `Proxy` over a genuine error is refused, because a proxy holds no private
2761
+ * field of its target; and `Reflect.construct(ContractError, args, Foreign)` IS
2762
+ * recognized, because that construction genuinely ran this constructor and only
2763
+ * the prototype was the caller's choice. That last consequence is a widening
2764
+ * rather than a narrowing, and it is named rather than left to be discovered.
1665
2765
  *
1666
2766
  * @param value - The value to inspect
1667
- * @returns `true` only when the value is a `ContractError`
2767
+ * @returns `true` only for a value this class's constructor branded
1668
2768
  *
1669
2769
  * @example
1670
2770
  * ```ts
@@ -1725,12 +2825,22 @@ export declare function isEmptyArray(value: unknown): value is readonly [];
1725
2825
  */
1726
2826
  export declare function isEmptyMap(value: unknown): value is ReadonlyMap<never, never>;
1727
2827
 
1728
- /** Determine whether a value is an empty plain object (no own string or enumerable symbol keys).
2828
+ /** Determine whether a value is an empty plain object — no OWN keys at all, of any
2829
+ * kind: string or symbol, enumerable or not.
2830
+ *
2831
+ * @remarks
2832
+ * The own-key population is the one `recordOf` inspects (`Reflect.ownKeys`), and
2833
+ * it has to be: this guard narrows to `Record<string | symbol, never>`, so
2834
+ * counting only ENUMERABLE keys made the narrowing unsound — a record carrying
2835
+ * an own non-enumerable `hidden: 1` answered `true` here while `recordOf({})`
2836
+ * saw the key and rejected the same value, and the enumerable-symbol and
2837
+ * non-enumerable-string cases were treated differently for no stated reason.
1729
2838
  *
1730
2839
  * @example
1731
2840
  * ```ts
1732
2841
  * isEmptyObject({}) // true
1733
2842
  * isEmptyObject({ a: 1 }) // false
2843
+ * isEmptyObject(Object.defineProperty({}, 'hidden', { value: 1 })) // false
1734
2844
  * ```
1735
2845
  */
1736
2846
  export declare function isEmptyObject(value: unknown): value is Record<string | symbol, never>;
@@ -1957,6 +3067,25 @@ export declare function isJSONPrimitive(value: unknown): value is JSONPrimitive;
1957
3067
  */
1958
3068
  export declare function isJSONValue(value: unknown): value is JSONValue;
1959
3069
 
3070
+ /**
3071
+ * Determine whether a value belongs to the string, number, or boolean literal domain.
3072
+ *
3073
+ * @remarks
3074
+ * Every JavaScript number belongs to this structural domain, including `NaN`,
3075
+ * `±Infinity`, and signed zero. Declaration and schema policies apply finiteness
3076
+ * separately where their contracts require it.
3077
+ *
3078
+ * @param value - The value to inspect
3079
+ * @returns `true` for a string, number, or boolean
3080
+ *
3081
+ * @example
3082
+ * ```ts
3083
+ * isLiteralValue(Number.NaN) // true
3084
+ * isLiteralValue(null) // false
3085
+ * ```
3086
+ */
3087
+ export declare function isLiteralValue(value: unknown): value is LiteralValue;
3088
+
1960
3089
  /** Determine whether a value is a `Map`.
1961
3090
  *
1962
3091
  * @example
@@ -1987,7 +3116,12 @@ export declare function isNonEmptyArray<T = unknown>(value: unknown): value is r
1987
3116
  */
1988
3117
  export declare function isNonEmptyMap<K = unknown, V = unknown>(value: unknown): value is ReadonlyMap<K, V>;
1989
3118
 
1990
- /** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key).
3119
+ /** Determine whether a value is a non-empty plain object — at least one own key of
3120
+ * any kind: string or symbol, enumerable or not.
3121
+ *
3122
+ * @remarks
3123
+ * The exact negation of {@link isEmptyObject} over the same own-key population;
3124
+ * see there for why enumerability is not part of the rule.
1991
3125
  *
1992
3126
  * @example
1993
3127
  * ```ts
@@ -2017,6 +3151,42 @@ export declare function isNonEmptySet<T = unknown>(value: unknown): value is Rea
2017
3151
  */
2018
3152
  export declare function isNonEmptyString(value: unknown): value is string;
2019
3153
 
3154
+ /**
3155
+ * Determine whether a value is a non-negative finite primitive integer.
3156
+ *
3157
+ * @remarks
3158
+ * Composes {@link isNonNegativeNumber} with {@link isInteger}. Representable
3159
+ * unsafe integers remain integers; safe-integer policy is a separate domain.
3160
+ *
3161
+ * @param value - The value to inspect
3162
+ * @returns `true` for non-negative integers other than `-0`
3163
+ *
3164
+ * @example
3165
+ * ```ts
3166
+ * isNonNegativeInteger(3) // true
3167
+ * isNonNegativeInteger(3.5) // false
3168
+ * ```
3169
+ */
3170
+ export declare function isNonNegativeInteger(value: unknown): value is number;
3171
+
3172
+ /**
3173
+ * Determine whether a value is a finite primitive number at or above positive zero.
3174
+ *
3175
+ * @remarks
3176
+ * Positive fractions pass. Negative zero is rejected explicitly, and no
3177
+ * coercion or property access is performed for non-number inputs.
3178
+ *
3179
+ * @param value - The value to inspect
3180
+ * @returns `true` for finite primitive numbers greater than or equal to zero, except `-0`
3181
+ *
3182
+ * @example
3183
+ * ```ts
3184
+ * isNonNegativeNumber(0.5) // true
3185
+ * isNonNegativeNumber(-0) // false
3186
+ * ```
3187
+ */
3188
+ export declare function isNonNegativeNumber(value: unknown): value is number;
3189
+
2020
3190
  /** Determine whether a value is `null`.
2021
3191
  *
2022
3192
  * @example
@@ -2126,18 +3296,14 @@ export declare function isPromiseLike<T = unknown>(value: unknown): value is Pro
2126
3296
  * not an array or class instance.
2127
3297
  *
2128
3298
  * @remarks
2129
- * Use instead of {@link isObject} to distinguish a plain `{}` /
2130
- * `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain
2131
- * test is realm-agnostic: rather than comparing against the current realm's
2132
- * `Object.prototype` (which a plain object from another `vm.Context`, iframe,
2133
- * or worker would fail), it accepts any value whose prototype is `null`, OR
2134
- * whose prototype's own prototype is `null` — the shape every plain object
2135
- * has in every realm, since `Object.prototype` itself always sits one step
2136
- * above `null`. Arrays and class instances are still rejected: an array's
2137
- * prototype chain runs through `Array.prototype` before `null`, and a class
2138
- * instance's runs through the class's own prototype. The whole body runs
2139
- * inside `holds` (AGENTS §14) so a revoked `Proxy` or a hostile
2140
- * `getPrototypeOf` trap cannot escape as a thrown error.
3299
+ * The total form of the shared {@link matchesRecordBrand} rule, and the only
3300
+ * one a guard may use: the whole brand runs inside `holds` (AGENTS §14) so a
3301
+ * revoked `Proxy` or a hostile `getPrototypeOf` trap answers `false` instead of
3302
+ * escaping as a thrown error. Use instead of {@link isObject} to distinguish a
3303
+ * plain `{}` / `Object.create(null)` — or a plain object from another realm,
3304
+ * whose prototype is that realm's `Object.prototype` — from arrays, `Date`,
3305
+ * `Map`, and class instances, including a class whose prototype a caller
3306
+ * reparented to `null`.
2141
3307
  *
2142
3308
  * @example
2143
3309
  * ```ts
@@ -2265,22 +3431,23 @@ export declare function isUint8ClampedArray(value: unknown): value is Uint8Clamp
2265
3431
  export declare function isUndefined(value: unknown): value is undefined;
2266
3432
 
2267
3433
  /**
2268
- * Determine whether an ISO-8601-shaped string parses to a valid instant.
3434
+ * Determine whether a supported ISO-8601 date or date-time is valid.
2269
3435
  *
2270
3436
  * @remarks
2271
- * A pure, attempt-guarded `Date` validity probe: `new Date(value)` never
2272
- * throws on a string input, but a value like `2020-13-45` parses to an
2273
- * `Invalid Date` whose `getTime()` is `NaN` — this is the real validation
2274
- * step behind {@link stringToFormat}'s `date` / `date-time` / `time`
2275
- * branches, which pattern-match the shape first and confirm validity here.
3437
+ * Accepts exactly `YYYY-MM-DD`, or `YYYY-MM-DDTHH:MM:SS` with optional
3438
+ * fractional seconds followed by `Z` or a numeric offset. Inside the
3439
+ * {@link attempt} boundary, captured components receive explicit Gregorian
3440
+ * month/leap/day and clock validation before `Date#getTime` performs the final
3441
+ * offset/instant refusal. Backs {@link stringToFormat}'s `date`, `date-time`,
3442
+ * and prefixed `time` validation.
2276
3443
  *
2277
3444
  * @param value - The candidate ISO-8601 string
2278
3445
  * @returns `true` when `value` parses to a real instant
2279
3446
  *
2280
3447
  * @example
2281
3448
  * ```ts
2282
- * isValidISOInstant('2020-01-01') // true
2283
- * isValidISOInstant('2020-13-45') // false
3449
+ * isValidISOInstant('2024-02-29') // true
3450
+ * isValidISOInstant('2024-01-01T24:00Z') // false — incomplete normalized clock
2284
3451
  * ```
2285
3452
  */
2286
3453
  export declare function isValidISOInstant(value: string): boolean;
@@ -2357,7 +3524,7 @@ export declare function isZeroArgGenerator(value: unknown): value is () => Gener
2357
3524
  *
2358
3525
  * @example
2359
3526
  * ```ts
2360
- * import { JSON_SCHEMA_TYPES, literalOf, parseEnumField } from '@src/core'
3527
+ * import { JSON_SCHEMA_TYPES, literalOf, parseEnumField } from '@orkestrel/contract'
2361
3528
  *
2362
3529
  * const isSchemaType = literalOf(...JSON_SCHEMA_TYPES) // Guard<JSONSchemaType>
2363
3530
  * parseEnumField(schema, 'type', JSON_SCHEMA_TYPES) // JSONSchemaType | undefined
@@ -2365,6 +3532,60 @@ export declare function isZeroArgGenerator(value: unknown): value is () => Gener
2365
3532
  */
2366
3533
  export declare const JSON_SCHEMA_TYPES: readonly JSONSchemaType[];
2367
3534
 
3535
+ /**
3536
+ * Stateful owner of one exact JSON snapshot operation.
3537
+ *
3538
+ * @remarks
3539
+ * Construction retains the source without observing it. The first
3540
+ * {@link clone} call performs one iterative descriptor walk and settles
3541
+ * permanently. Success replays the exact frozen root; failure rethrows the
3542
+ * exact class-owned error. Nonredirectable terminal failure releases partial
3543
+ * traversal working state while retaining the source and exact error. Reentry
3544
+ * poisons the active operation and every later call with one shared cause-free
3545
+ * error.
3546
+ *
3547
+ * @param value - The unknown value to retain for cloning
3548
+ *
3549
+ * @example
3550
+ * ```ts
3551
+ * const source = { settings: { enabled: true } }
3552
+ * const cloner = new JSONCloner(source)
3553
+ * const clone = cloner.clone()
3554
+ * source.settings.enabled = false
3555
+ * cloner.clone() === clone // true
3556
+ * ```
3557
+ */
3558
+ export declare class JSONCloner implements JSONClonerInterface {
3559
+ #private;
3560
+ constructor(value: unknown);
3561
+ /**
3562
+ * Clone the retained source into exact, deeply frozen JSON data.
3563
+ *
3564
+ * @returns The settled JSON snapshot
3565
+ * @throws {ContractError} When the source is inexact, cyclic, unreadable, or cloning is reentered
3566
+ */
3567
+ clone(): JSONValue;
3568
+ }
3569
+
3570
+ /**
3571
+ * Stateful owner of one exact JSON snapshot operation.
3572
+ *
3573
+ * @remarks
3574
+ * Construction retains the source without observing it. The first
3575
+ * {@link clone} call settles once; later calls replay the exact same frozen
3576
+ * value or exact same owned {@link ContractError}. Terminal failure releases
3577
+ * partial traversal working state while retaining the source and exact error.
3578
+ */
3579
+ export declare interface JSONClonerInterface {
3580
+ /**
3581
+ * Clone the retained source into exact, deeply frozen JSON data.
3582
+ *
3583
+ * @returns The settled JSON snapshot
3584
+ * @throws {ContractError} When the source is inexact, cyclic, unreadable, or cloning is reentered
3585
+ */
3586
+ clone(): JSONValue;
3587
+ }
3588
+
2368
3589
  /**
2369
3590
  * A primitive JSON value — the flat leaf of any JSON document.
2370
3591
  *
@@ -2395,8 +3616,8 @@ export declare type JSONRecord = {
2395
3616
  };
2396
3617
 
2397
3618
  /**
2398
- * A JSON Schema fragment — the subset of keywords the contract compiler emits
2399
- * and {@link RawShape} embeds.
3619
+ * A JSON Schema fragment — the supported keyword vocabulary the contract
3620
+ * compiler emits and {@link RawShape} validates before embedding.
2400
3621
  *
2401
3622
  * @remarks
2402
3623
  * Intentionally lean (not the full ~50-keyword vocabulary): it carries only the
@@ -2411,7 +3632,7 @@ export declare type JSONRecord = {
2411
3632
  export declare interface JSONSchema {
2412
3633
  readonly type?: JSONSchemaType;
2413
3634
  readonly description?: string;
2414
- readonly enum?: readonly (string | number | boolean)[];
3635
+ readonly enum?: readonly LiteralValue[];
2415
3636
  readonly minLength?: number;
2416
3637
  readonly maxLength?: number;
2417
3638
  readonly pattern?: string;
@@ -2452,7 +3673,10 @@ export declare interface JSONShape {
2452
3673
  * @remarks
2453
3674
  * The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary
2454
3675
  * schema fragment and accepts every defined value at runtime, while `jsonShape`
2455
- * validates that a value is real JSON (via {@link isJSONValue}).
3676
+ * validates that a value is real JSON (via {@link isJSONValue}). Its emitted
3677
+ * schema is the empty accept-anything `{}`, so here the schema claims MORE than
3678
+ * the compiled guard accepts — `NaN`, a `Map`, and a class instance all satisfy
3679
+ * `{}` and all fail `isJSONValue`.
2456
3680
  *
2457
3681
  * @param options - Optional `description`
2458
3682
  * @returns A JSON passthrough shape
@@ -2527,6 +3751,26 @@ export declare function keyOf<const O extends Readonly<Record<PropertyKey, unkno
2527
3751
  */
2528
3752
  export declare function lazyOf<T>(thunk: () => Guard<T>): Guard<T>;
2529
3753
 
3754
+ /**
3755
+ * Take at most `limit` leading elements of an array, by index.
3756
+ *
3757
+ * @remarks
3758
+ * `Array.prototype.slice` is a caller-writable member on every path that bounds
3759
+ * a published report, so a substitute decides how much of a diagnostic the
3760
+ * caller sees. Returns the input untouched when it already fits, so a bounded
3761
+ * report allocates nothing in the ordinary case.
3762
+ *
3763
+ * @param entries - The entries to bound
3764
+ * @param limit - The maximum number of leading entries to retain
3765
+ * @returns The input when it already fits, otherwise a fresh bounded copy
3766
+ *
3767
+ * @example
3768
+ * ```ts
3769
+ * limitEntries(faults, FAULT_LIMIT)
3770
+ * ```
3771
+ */
3772
+ export declare function limitEntries<T>(entries: readonly T[], limit: number): readonly T[];
3773
+
2530
3774
  /**
2531
3775
  * Build a guard that accepts a provided literal primitive using SameValueZero
2532
3776
  * comparison.
@@ -2552,12 +3796,12 @@ export declare function lazyOf<T>(thunk: () => Guard<T>): Guard<T>;
2552
3796
  * const isSameRole = literalOf(['admin', 'member', 'guest']) // the same guard, from an array
2553
3797
  * ```
2554
3798
  */
2555
- export declare function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(literals: Literals): Guard<Literals[number]>;
3799
+ export declare function literalOf<const Literals extends ReadonlyArray<LiteralValue>>(literals: Literals): Guard<Literals[number]>;
2556
3800
 
2557
- export declare function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(...literals: Literals): Guard<Literals[number]>;
3801
+ export declare function literalOf<const Literals extends ReadonlyArray<LiteralValue>>(...literals: Literals): Guard<Literals[number]>;
2558
3802
 
2559
3803
  /** A literal shape — accepts exactly one of a fixed set of primitive values. */
2560
- export declare interface LiteralShape<T extends readonly (string | number | boolean)[] = readonly (string | number | boolean)[]> {
3804
+ export declare interface LiteralShape<T extends readonly LiteralValue[] = readonly LiteralValue[]> {
2561
3805
  readonly type: 'literal';
2562
3806
  readonly values: T;
2563
3807
  readonly description?: string;
@@ -2578,13 +3822,16 @@ export declare interface LiteralShape<T extends readonly (string | number | bool
2578
3822
  * const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })
2579
3823
  * ```
2580
3824
  */
2581
- export declare function literalShape<const T extends readonly (string | number | boolean)[]>(values: T, options?: LiteralShapeOptions): LiteralShape<Readonly<T>>;
3825
+ export declare function literalShape<const T extends readonly LiteralValue[]>(values: T, options?: LiteralShapeOptions): LiteralShape<Readonly<T>>;
2582
3826
 
2583
3827
  /** Options for {@link LiteralShape} (via `literalShape`). */
2584
3828
  export declare interface LiteralShapeOptions {
2585
3829
  readonly description?: string;
2586
3830
  }
2587
3831
 
3832
+ /** A string, number, or boolean literal value. */
3833
+ export declare type LiteralValue = string | number | boolean;
3834
+
2588
3835
  /**
2589
3836
  * Build a guard that accepts `Map` instances where every key satisfies
2590
3837
  * `keyGuard` and every value satisfies `valueGuard`.
@@ -2600,6 +3847,35 @@ export declare function mapOf<K, V>(keyGuard: Guard<K>, valueGuard: Guard<V>): G
2600
3847
 
2601
3848
  export declare function mapOf(keyPredicate: (value: unknown) => boolean, valuePredicate: (value: unknown) => boolean): Guard<ReadonlyMap<unknown, unknown>>;
2602
3849
 
3850
+ /**
3851
+ * Determine whether a readable value stays within the fixed JSON container-depth limit.
3852
+ *
3853
+ * @remarks
3854
+ * Counts array and plain-record containers on each active root-to-value path.
3855
+ * Primitive and readable non-record objects are leaves, active cycles add no
3856
+ * level, and shared aliases are answered from the shallowest depth at which
3857
+ * the alias already fit. Arrays are traversed through their reflected
3858
+ * own-index population, so sparse work is proportional to populated entries
3859
+ * rather than advertised length. Every observable operation is contained;
3860
+ * hostile or contradictory reads return `false`.
3861
+ *
3862
+ * The walk carries a settled-depth memo beside its active-path set: a
3863
+ * container that fit at depth `d` also fits at any depth `<= d`, because every
3864
+ * path below it is then shallower than the one already measured. Without it a
3865
+ * node reachable by `k` distinct paths was re-walked `k` times, so an ORDINARY
3866
+ * record graph with thirty shared aliases — thirty-one nodes — cost `2^30`
3867
+ * visits through a public guard.
3868
+ *
3869
+ * @param value - The value whose readable container depth to inspect
3870
+ * @returns `true` when no active path exceeds {@link GUARD_DEPTH_LIMIT}
3871
+ *
3872
+ * @example
3873
+ * ```ts
3874
+ * matchesJSONDepth({ nested: [1] }) // true
3875
+ * ```
3876
+ */
3877
+ export declare function matchesJSONDepth(value: unknown): boolean;
3878
+
2603
3879
  /**
2604
3880
  * Match an unknown value against the recursive JSON value structure.
2605
3881
  *
@@ -2607,8 +3883,28 @@ export declare function mapOf(keyPredicate: (value: unknown) => boolean, valuePr
2607
3883
  * The caller-owned ancestor set tracks only the active traversal path, so
2608
3884
  * cycles fail while shared references across sibling branches remain valid.
2609
3885
  * The set belongs to one traversal from one entry point; passing a shared or
2610
- * pre-populated set is unsupported. Arrays and plain records recurse through
2611
- * this helper; class instances and non-finite numbers are rejected.
3886
+ * pre-populated set is unsupported. Arrays descend through the shared dense
3887
+ * own-index lens and plain records descend by values; class instances and
3888
+ * non-finite numbers are rejected.
3889
+ *
3890
+ * The walk is ITERATIVE, over an explicit enter/exit stack, exactly as
3891
+ * {@link matchesJSONDepth} already was. It used to recurse, and that made the
3892
+ * verdict a function of the REMAINING CALL STACK rather than of the value: the
3893
+ * same readable 4,000-deep document answered `true` at a root call site and
3894
+ * `false` a few frames down, and `parseJSONValue` republished the resulting
3895
+ * `RangeError` as `value could not be read` for a value every read of which
3896
+ * succeeded. A cap enforced by the JavaScript stack is not a cap. This walk
3897
+ * carries no depth cap of its own — `isJSONValue` is deliberately the unbounded
3898
+ * deep gate and {@link matchesJSONDepth} / `isBoundedJSONValue` are the bounded
3899
+ * pair beside it — so the answer now depends only on the value, at every depth
3900
+ * and from every call site.
3901
+ *
3902
+ * Beside the ancestor set the walk keeps a walk-local PROVED set, so a node
3903
+ * whose whole subtree already matched is not re-walked when a second path
3904
+ * reaches it. Removing the recursion alone left the work exponential in shared
3905
+ * aliases: thirty aliases — thirty-one ordinary records — cost `2^30` visits
3906
+ * through `isJSONValue`, `parseJSONValue`, `canonicalStringify` and every
3907
+ * `jsonShape` contract.
2612
3908
  *
2613
3909
  * @param entry - The value to inspect
2614
3910
  * @param ancestors - Objects on the active traversal path
@@ -2620,7 +3916,138 @@ export declare function mapOf(keyPredicate: (value: unknown) => boolean, valuePr
2620
3916
  * matchesJSONValue(Number.NaN, new WeakSet()) // false
2621
3917
  * ```
2622
3918
  */
2623
- export declare function matchesJSONValue(entry: unknown, ancestors: WeakSet<object>): boolean;
3919
+ export declare function matchesJSONValue(entry: unknown, ancestors: WeakSet<object>): entry is JSONValue;
3920
+
3921
+ /**
3922
+ * Determine whether a value is a member of a collected vocabulary, by
3923
+ * SameValueZero.
3924
+ *
3925
+ * @param members - The vocabulary to ask, built by {@link collectMembers}
3926
+ * @param value - The value to test for membership
3927
+ * @returns `true` only when the value was collected
3928
+ *
3929
+ * @example
3930
+ * ```ts
3931
+ * matchesMember(collectMembers([Number.NaN]), Number.NaN) // true — SameValueZero
3932
+ * ```
3933
+ */
3934
+ export declare function matchesMember(members: Set<unknown>, value: unknown): boolean;
3935
+
3936
+ /**
3937
+ * Determine whether a string is in the language of a pattern this package owns.
3938
+ *
3939
+ * @remarks
3940
+ * The pattern-membership answer, asked exactly as {@link matchesMember} asks the
3941
+ * literal one, and asked through `exec` rather than `test` on purpose:
3942
+ * `RegExp.prototype.test` is spec-defined in terms of `RegExpExec`, which
3943
+ * re-reads `exec` off the receiver, so even a CAPTURED `test` still answers
3944
+ * whatever the caller installed. Replacing either member decided what `matchOf`,
3945
+ * `stringOf`, `contract.is`, `contract.parse`, `audit`, `explain` and the format
3946
+ * inferers published — a wrong yes for a non-member and a wrong no for a member,
3947
+ * silently.
3948
+ *
3949
+ * @param pattern - The owned pattern to apply
3950
+ * @param value - The string to test
3951
+ * @returns `true` only when the pattern genuinely matches
3952
+ *
3953
+ * @example
3954
+ * ```ts
3955
+ * matchesPattern(/^[0-9a-f]+$/, '1a2f') // true
3956
+ * ```
3957
+ */
3958
+ export declare function matchesPattern(pattern: RegExp, value: string): boolean;
3959
+
3960
+ /**
3961
+ * Determine whether a value carries the plain-record brand, raising a hostile
3962
+ * prototype observation instead of answering it.
3963
+ *
3964
+ * @remarks
3965
+ * THE single record-brand rule: a plain record is a non-array object whose
3966
+ * prototype is `null`, or is a realm's `Object.prototype`. Realm-agnosticism is
3967
+ * why the second arm cannot simply compare against this realm's
3968
+ * `Object.prototype` — a plain object from another `vm.Context`, iframe, or
3969
+ * worker inherits from THAT realm's `Object.prototype`, which is a different
3970
+ * object. The earlier rule accepted any prototype that itself had a `null`
3971
+ * prototype, which every realm's `Object.prototype` satisfies — and so does a
3972
+ * class prototype a caller reparented to `null`, which is how a class instance
3973
+ * laundered through every ownership door. A foreign `Object.prototype` is
3974
+ * therefore identified by the own members ECMAScript requires every realm to
3975
+ * put on it (`constructor`, `hasOwnProperty`, `isPrototypeOf`,
3976
+ * `propertyIsEnumerable`, `toLocaleString`, `toString`, `valueOf`), each read
3977
+ * through its own DESCRIPTOR so no accessor on a hostile prototype ever runs.
3978
+ * Each must be an own DATA property whose value is a FUNCTION — true of every
3979
+ * conformant realm, so the requirement costs a genuine foreign record nothing,
3980
+ * and it refuses the cheapest forgery (stamping the seven names with
3981
+ * `undefined`) for free.
3982
+ *
3983
+ * That is a structural test, not a provenance one, and the residual is stated
3984
+ * as exactly what it is: a FUNCTION-VALUED forgery passes, and this realm's own
3985
+ * `Object.prototype` supplies the seven functions to stamp, so the price is a
3986
+ * few lines rather than nothing. Reparenting a class prototype to `null` and
3987
+ * stamping the seven names with real functions passes; so does leaving the
3988
+ * class untouched and putting a `Proxy` in prototype position that reports
3989
+ * `null` as its own prototype and answers those seven descriptor reads with
3990
+ * functions. In both cases the value is a live class instance whose methods are
3991
+ * still reachable on it. A further own-key SUBSET rule buys even less: it
3992
+ * refuses a forgery that left methods on its prototype and accepts the same
3993
+ * class with those methods moved onto the instance, where they are
3994
+ * indistinguishable from a plain record's function
3995
+ * properties — so it raises the forgery's price and narrows the realm-agnostic
3996
+ * arm this rule exists to keep open. What the pass buys is acceptance at
3997
+ * brand-governed doors and nothing after it: every ownership engine publishes a
3998
+ * frozen plain record built only from captured data, so no class instance,
3999
+ * class behavior, or forged prototype survives into a snapshot.
4000
+ *
4001
+ * `Object.create(<null-prototype object>)` is refused, and NOT because it is
4002
+ * structurally identical to a reparented class instance — it is not, since a
4003
+ * class prototype always owns `constructor` and a bare `Object.create(null)`
4004
+ * owns nothing. It is refused as policy: no realm produces that chain for a
4005
+ * plain object, no consumer of it has been named, and a caller erases the
4006
+ * difference by deleting `constructor`.
4007
+ *
4008
+ * This is the diagnosing form, deliberately NOT total: a revoked `Proxy` or a
4009
+ * hostile `getPrototypeOf` trap throws out of it, so an ownership engine can
4010
+ * report an unreadable value as a failed read with the exact cause rather than
4011
+ * as a well-formed structural refusal. {@link isRecord} is the total form for
4012
+ * every guard consumer and contains that throw as `false`.
4013
+ *
4014
+ * @param value - The value whose record brand to inspect
4015
+ * @returns `true` only when the value is a plain record
4016
+ * @throws The exact value thrown by a hostile brand observation
4017
+ *
4018
+ * @example
4019
+ * ```ts
4020
+ * matchesRecordBrand({}) // true
4021
+ * matchesRecordBrand(Object.create(null)) // true
4022
+ * matchesRecordBrand(new Date()) // false
4023
+ * ```
4024
+ */
4025
+ export declare function matchesRecordBrand(value: unknown): boolean;
4026
+
4027
+ /**
4028
+ * Determine whether an object is already on a traversal's active path.
4029
+ *
4030
+ * @remarks
4031
+ * The visitation half, and the one an earlier ruling wrongly excused as safe
4032
+ * because "a redirect corrupts it inside a boundary and the door refuses, which
4033
+ * is loud". It is not loud in the direction that matters:
4034
+ * `WeakSet.prototype.has` answering `false` does not make a cyclic clone refuse,
4035
+ * it removes the door's termination bound, and a door that never returns is the
4036
+ * one failure a containment boundary cannot report. Every walk's termination
4037
+ * therefore rests on a captured operation rather than on a caller-writable one.
4038
+ *
4039
+ * @param visited - The active-path set this traversal owns
4040
+ * @param value - The object to test
4041
+ * @returns `true` only when the object is already on the active path
4042
+ *
4043
+ * @example
4044
+ * ```ts
4045
+ * const active = new WeakSet<object>()
4046
+ * admitVisited(active, node)
4047
+ * matchesVisited(active, node) // true
4048
+ * ```
4049
+ */
4050
+ export declare function matchesVisited(visited: WeakSet<object>, value: object): boolean;
2624
4051
 
2625
4052
  /**
2626
4053
  * Build a guard that accepts strings matching a regular expression.
@@ -2748,9 +4175,13 @@ export declare interface NumberShapeOptions {
2748
4175
  *
2749
4176
  * @remarks
2750
4177
  * A property whose shape is an {@link OptionalShape} may be absent; all others
2751
- * are required. `additionalProperties` controls unknown keys: `undefined` /
2752
- * `false` rejects them (closed), `true` accepts them as-is, a `ContractShape`
2753
- * validates them.
4178
+ * are required. `additionalProperties` controls unknown keys, and each compiled
4179
+ * artifact acts on that setting in its own way. Closed (`undefined` / `false`):
4180
+ * the compiled guard rejects the object, the compiled auditor reports one
4181
+ * `'extra'` fault at the offending key, and the emitted schema sets
4182
+ * `additionalProperties: false` — while the compiled parser drops the key and
4183
+ * the compiled reporter stays silent, mirroring that parser. `true` accepts
4184
+ * unknown keys as-is, and a `ContractShape` validates them, in every artifact.
2754
4185
  */
2755
4186
  export declare interface ObjectShape<P extends Readonly<Record<string, ContractShape>> = Readonly<Record<string, ContractShape>>, A extends boolean | ContractShape = boolean | ContractShape> {
2756
4187
  readonly type: 'object';
@@ -2801,6 +4232,19 @@ export declare interface ObjectShapeOptions<A extends boolean | ContractShape =
2801
4232
  */
2802
4233
  export declare function omitOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(shape: S, keys: K): Omit<S, K[number]>;
2803
4234
 
4235
+ /**
4236
+ * Record an object as exited from a traversal's active path.
4237
+ *
4238
+ * @param visited - The active-path set this traversal owns
4239
+ * @param value - The object being exited
4240
+ *
4241
+ * @example
4242
+ * ```ts
4243
+ * omitVisited(active, node)
4244
+ * ```
4245
+ */
4246
+ export declare function omitVisited(visited: WeakSet<object>, value: object): void;
4247
+
2804
4248
  /**
2805
4249
  * Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.
2806
4250
  *
@@ -2899,33 +4343,27 @@ export declare function orOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A | B
2899
4343
  export declare function orOf(left: (value: unknown) => boolean, right: (value: unknown) => boolean): Guard<unknown>;
2900
4344
 
2901
4345
  /**
2902
- * Take ownership of a contract shape node — the node itself when it is already
2903
- * frozen, otherwise a {@link cloneShape} snapshot of its graph.
4346
+ * Take ownership of a contract shape node as an independent {@link cloneShape}
4347
+ * snapshot of its graph.
2904
4348
  *
2905
4349
  * @remarks
2906
- * Builder- and `cloneShape`-produced frozen means owned: those nodes have frozen
2907
- * `properties` / `variants` / `values` collections and pattern accessors that
2908
- * return fresh frozen snapshots, so they cannot drift under a caller who still
2909
- * holds an input reference or a previously read pattern. `Object.freeze` on a
2910
- * hand-authored pattern shape is not an ownership marker because it cannot
2911
- * protect `RegExp` internal slots; leave that shape unfrozen for this function
2912
- * to snapshot, or pass it through {@link cloneShape} first.
2913
- *
2914
- * Every compiler entry point (`compileSchema` / `compileGuard` /
2915
- * `compileParser` / `compileGenerator` / `compileReporter`) opens with this
2916
- * call, and the check applies per node as the recursion descends: a frozen
2917
- * parent is trusted for its own fields while each child is owned again at its
2918
- * own level, so a hand-assembled graph that froze only part of itself is still
2919
- * compiled from owned data.
4350
+ * Every successful return is a deeply frozen caller-independent graph, and
4351
+ * "frozen" here means frozen by the `Object.freeze` this package captured while
4352
+ * it loaded, not by whatever `Object.freeze` names when the call is made. The
4353
+ * distinction is the whole guarantee: under `Object.freeze = (value) => value`
4354
+ * this door used to SUCCEED and publish a mutable graph, with no throw and no
4355
+ * signal a caller could read. A frozen caller root receives no identity
4356
+ * exception: shallow freezing cannot establish ownership of nested collections,
4357
+ * child nodes, raw schemas, or `RegExp` internal state, and the fidelity clone
4358
+ * has already paid the traversal cost needed to prove and carry those values.
2920
4359
  *
2921
4360
  * @param shape - The contract shape to own
2922
- * @returns The shape itself when frozen, otherwise a deeply cloned frozen snapshot
4361
+ * @returns A deeply cloned frozen snapshot
2923
4362
  *
2924
4363
  * @example
2925
4364
  * ```ts
2926
- * const authored = stringShape() // builders freeze
2927
- * ownShape(authored) === authored // true
2928
- * ownShape({ type: 'string' }) // a frozen snapshot — the literal is caller-owned
4365
+ * const authored = stringShape()
4366
+ * ownShape(authored) === authored // false
2929
4367
  * ```
2930
4368
  */
2931
4369
  export declare function ownShape(shape: ContractShape): ContractShape;
@@ -3010,7 +4448,8 @@ export declare function parseBooleanField(record: Record<string, unknown>, path:
3010
4448
  * `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive
3011
4449
  * (string, number, or boolean), not only strings. Matching is identity, never
3012
4450
  * cross-type coercion: `parseEnum('1', [1])` stays `undefined`. The allowed
3013
- * values are copied into an owned frozen `Set`; hostile iteration returns
4451
+ * values are captured through their dense own-index view and copied into an
4452
+ * owned `Set`; caller-defined iteration is ignored and unreadability returns
3014
4453
  * `undefined` rather than escaping.
3015
4454
  *
3016
4455
  * @param value - The value to parse
@@ -3023,9 +4462,9 @@ export declare function parseBooleanField(record: Record<string, unknown>, path:
3023
4462
  * parseEnum('z', ['a', 'b', 'c']) // undefined
3024
4463
  * ```
3025
4464
  */
3026
- export declare function parseEnum<const T extends string | number | boolean>(value: unknown, allowed: readonly T[]): T | undefined;
4465
+ export declare function parseEnum<const T extends LiteralValue>(value: unknown, allowed: readonly T[]): T | undefined;
3027
4466
 
3028
- export declare function parseEnum(value: unknown, allowed: readonly (string | number | boolean)[]): string | number | boolean | undefined;
4467
+ export declare function parseEnum(value: unknown, allowed: readonly LiteralValue[]): LiteralValue | undefined;
3029
4468
 
3030
4469
  /**
3031
4470
  * Read and parse an enum field from a record by key or nested key path.
@@ -3035,7 +4474,7 @@ export declare function parseEnum(value: unknown, allowed: readonly (string | nu
3035
4474
  * @param allowed - The permitted literal values
3036
4475
  * @returns The matched literal, or `undefined`
3037
4476
  */
3038
- export declare function parseEnumField<const T extends string | number | boolean>(record: Record<string, unknown>, path: FieldPath, allowed: readonly T[]): T | undefined;
4477
+ export declare function parseEnumField<const T extends LiteralValue>(record: Record<string, unknown>, path: FieldPath, allowed: readonly T[]): T | undefined;
3039
4478
 
3040
4479
  /**
3041
4480
  * Parse an unknown value to a finite integer.
@@ -3109,13 +4548,14 @@ export declare function parseJSONAs<T>(value: string, guard: Guard<T>): T | unde
3109
4548
  * @remarks
3110
4549
  * Unlike {@link parseRecord} / {@link parseArray}, this is a DEEP gate: it
3111
4550
  * walks the entire tree via {@link isJSONValue} rather than checking only the
3112
- * top-level shape. That walk is cycle-safe and total (never throws) because
3113
- * `isJSONValue` runs its own probe inside a guard, so an adversarial
3114
- * structure (a cycle, a hostile getter) yields `undefined` instead of hanging
3115
- * or throwing.
4551
+ * top-level shape. That walk is cycle-safe. A readable non-JSON structure,
4552
+ * including a cycle, returns `undefined`; a failed property read throws a
4553
+ * `structure` {@link ContractError}, keeping unreadability distinct from an
4554
+ * honest invalid result.
3116
4555
  *
3117
4556
  * @param value - The value to parse
3118
4557
  * @returns The value, or `undefined` when it is not a valid JSON value
4558
+ * @throws {ContractError} When the JSON tree cannot be read
3119
4559
  *
3120
4560
  * @example
3121
4561
  * ```ts
@@ -3233,6 +4673,7 @@ export declare type Parser<T> = (value: unknown) => T | undefined;
3233
4673
  *
3234
4674
  * @param value - The value to parse
3235
4675
  * @returns The record, or `undefined`
4676
+ * @throws {ContractError} When an object value cannot be read
3236
4677
  */
3237
4678
  export declare function parseRecord(value: unknown): Record<string, unknown> | undefined;
3238
4679
 
@@ -3273,6 +4714,34 @@ export declare function parseString(value: unknown): string | undefined;
3273
4714
  */
3274
4715
  export declare function parseStringField(record: Record<string, unknown>, path: FieldPath): string | undefined;
3275
4716
 
4717
+ /**
4718
+ * Build a diagnostic path from an existing path and further segments, without
4719
+ * dispatching through array iteration.
4720
+ *
4721
+ * @remarks
4722
+ * `[...path, key]` reads well and dispatches through
4723
+ * `Array.prototype[Symbol.iterator]`, a member every caller can write — and the
4724
+ * damaging installation is not a thrower but a LIAR. An iterator yielding one
4725
+ * extra value before the array's real contents turns a refusal this package
4726
+ * authored into `path: ['INJECTED', 'properties', 'INJECTED']`, so the caller
4727
+ * writes their own text into a diagnostic this package published. An indexed
4728
+ * walk reads only own index properties of an array this package owns, and a
4729
+ * rest parameter collects its arguments without an iterator either, so nothing
4730
+ * on the path is caller-reachable.
4731
+ *
4732
+ * @param path - The path segments accumulated so far
4733
+ * @param segments - Further segments to append in order; an absent segment is
4734
+ * omitted, so an optional level needs no branch at the call site
4735
+ * @returns A fresh path carrying every existing segment and each new one
4736
+ *
4737
+ * @example
4738
+ * ```ts
4739
+ * pathOf(['properties'], 'age') // ['properties', 'age']
4740
+ * pathOf(path) // an owned copy
4741
+ * ```
4742
+ */
4743
+ export declare function pathOf(path: readonly string[], ...segments: readonly (string | undefined)[]): readonly string[];
4744
+
3276
4745
  /**
3277
4746
  * Build a new guard shape by keeping only the listed keys — the structural
3278
4747
  * equivalent of `Pick<T, K>`. Produces a shape for {@link recordOf}, not a guard.
@@ -3286,18 +4755,61 @@ export declare function parseStringField(record: Record<string, unknown>, path:
3286
4755
  */
3287
4756
  export declare function pickOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(shape: S, keys: K): Pick<S, K[number]>;
3288
4757
 
4758
+ /**
4759
+ * Pin every own member of a class prototype as a non-configurable member —
4760
+ * non-writable too when it is a data property — and verify the pin took.
4761
+ *
4762
+ * @remarks
4763
+ * The other half of the structural answer. Membership answers moved off class
4764
+ * methods entirely, but a class this package EXPORTS still has methods its own
4765
+ * modules dispatch through — `cloneShape` reaches `ShapeCloner.prototype.clone`,
4766
+ * and one assignment there made `compileSchema` publish whatever the caller
4767
+ * chose while `compileSchema` itself was never touched. That is the same defect
4768
+ * as a replaced host member with the package's own name on it, so every exported
4769
+ * class pins its prototype while it is DEFINED.
4770
+ *
4771
+ * The qualification that phrase used to carry — "before any importer's code can
4772
+ * run" — was FALSE, in exactly the case {@link INTRINSICS} already states and
4773
+ * does not defend: ESM evaluates imports in source order, so a module that
4774
+ * evaluates before this package has already run. What is true is narrower and is
4775
+ * what the pin buys: no code that runs AFTER this class is defined can replace a
4776
+ * member on its prototype.
4777
+ *
4778
+ * Placement goes through the captured `Reflect.defineProperty`, which ANSWERS
4779
+ * instead of throwing, and the answer is then corroborated by reading the
4780
+ * descriptor back. Installing is not reading: a pin that silently did not happen
4781
+ * is indistinguishable from one that did until something asks, so this asks. The
4782
+ * residual is named rather than denied: an adversary who also answers the
4783
+ * verifying descriptor read defeats this, and that adversary already chose what
4784
+ * {@link INTRINSICS} captured.
4785
+ *
4786
+ * @param prototype - The class prototype to pin
4787
+ * @param owner - The class name used in the refusal
4788
+ * @throws {ContractError} When a member cannot be pinned or the pin cannot be verified
4789
+ *
4790
+ * @example
4791
+ * ```ts
4792
+ * class Widget { static { pinMembers(Widget.prototype, 'Widget') } }
4793
+ * ```
4794
+ */
4795
+ export declare function pinMembers(prototype: object, owner: string): void;
4796
+
3289
4797
  /**
3290
4798
  * Render a short, safe, TOTAL preview of an unknown value for a {@link Fault}'s
3291
4799
  * `received` field.
3292
4800
  *
3293
4801
  * @remarks
3294
- * A primitive renders as its literal: a string is `JSON.stringify`-escaped and
3295
- * clipped to {@link PREVIEW_LIMIT} characters (with a trailing `…` when
3296
- * clipped); a number / boolean / bigint / symbol renders via `String`; `null`
3297
- * and `undefined` render as their own name. Everything else — a plain object,
3298
- * an array, a function, a class instance, a `Map` — is NEVER traversed or
3299
- * stringified; it renders as its bare `typeof` tag (`'object'` / `'function'`),
3300
- * so a hostile or enormous structure can never blow up the preview.
4802
+ * A primitive renders as printable text: a string retains its quoted JSON
4803
+ * representation, while a narrowed symbol renders through intrinsic `String`
4804
+ * and receives the same escaping without outer quotes. One bounded indexed
4805
+ * encoder appends only complete escaped code-point tokens within
4806
+ * {@link PREVIEW_LIMIT}; clipping therefore never retrieves the mutable string
4807
+ * iterator or splits an escape/surrogate pair before its trailing `…`, and
4808
+ * enormous primitive text is not fully traversed. A number / boolean / bigint
4809
+ * renders via `String`; `null` and `undefined` render as their own name. An
4810
+ * array renders as `'array'`. Every other host — a plain object, a function, a
4811
+ * class instance, a `Map` — is NEVER traversed or stringified; it renders as
4812
+ * its bare `typeof` tag (`'object'` / `'function'`).
3301
4813
  *
3302
4814
  * @param value - The value to preview
3303
4815
  * @returns A short descriptive string, always safe to embed in a diagnostic
@@ -3308,7 +4820,7 @@ export declare function pickOf<S extends GuardsShape, K extends ReadonlyArray<ke
3308
4820
  * preview(42) // '42'
3309
4821
  * preview(null) // 'null'
3310
4822
  * preview({ a: 1 }) // 'object'
3311
- * preview([1, 2, 3]) // 'object'
4823
+ * preview([1, 2, 3]) // 'array'
3312
4824
  * ```
3313
4825
  */
3314
4826
  export declare function preview(value: unknown): string;
@@ -3327,10 +4839,16 @@ export declare const PREVIEW_LIMIT = 64;
3327
4839
  export declare type RandomFunction = () => number;
3328
4840
 
3329
4841
  /**
3330
- * A raw JSON Schema passthrough — embeds a schema fragment directly.
4842
+ * A validated raw JSON Schema passthrough — embeds a supported schema fragment directly.
3331
4843
  *
3332
4844
  * @remarks
3333
- * For values the shape DSL can't express. The compiled guard accepts every
4845
+ * For values the shape DSL can't express. The fragment is checked recursively
4846
+ * against the lean {@link JSONSchema} vocabulary before it is accepted or
4847
+ * emitted; unsupported keywords and malformed keyword values throw a coded
4848
+ * {@link ContractError}. This is structural and keyword-domain validation,
4849
+ * not a full JSON Schema solver: it does not resolve cross-keyword
4850
+ * contradictions, `required`/`properties` membership, keyword/type coherence,
4851
+ * `enum`/`type` compatibility, or a closed `format` vocabulary. The compiled guard accepts every
3334
4852
  * top-level value except `undefined`, which is reserved as the parser failure
3335
4853
  * sentinel. Wrap the shape with {@link OptionalShape} to admit absence. Defined
3336
4854
  * values pass through unchanged, and the schema is emitted structurally
@@ -3342,18 +4860,24 @@ export declare interface RawShape {
3342
4860
  }
3343
4861
 
3344
4862
  /**
3345
- * Build a {@link RawShape} from a JSON Schema fragment.
4863
+ * Build a {@link RawShape} from a supported JSON Schema fragment.
3346
4864
  *
3347
4865
  * @remarks
3348
- * For values the shape DSL can't express. The compiled guard accepts every
4866
+ * For values the shape DSL can't express. The fragment is recursively checked
4867
+ * against the lean {@link JSONSchema} vocabulary before ownership is taken;
4868
+ * malformed or unsupported keywords throw a coded {@link ContractError}. The
4869
+ * compiled guard accepts every
3349
4870
  * DEFINED value — `undefined` alone fails, because it is the parser's failure
3350
4871
  * sentinel; wrap the shape in {@link optionalShape} to admit absence. The
3351
4872
  * parser passes a defined value through unchanged, and the fragment is
3352
4873
  * deep-cloned into an owned frozen snapshot ({@link cloneSchema}), so
3353
4874
  * `rawShape(fragment).schema !== fragment` and later edits to the caller's
3354
4875
  * fragment cannot reach the shape. `compileSchema` re-emits that snapshot
3355
- * structurally verbatim; `compileGenerator` throws, since an arbitrary embedded
3356
- * schema has no auto-generatable sample.
4876
+ * structurally verbatim, so here the schema claims LESS than the compiled guard
4877
+ * accepts — `rawShape({ type: 'string' })` emits `{ type: 'string' }` and its
4878
+ * guard still accepts `42`, the mirror of {@link jsonShape}'s looseness.
4879
+ * `compileGenerator` throws, since an arbitrary embedded schema has no
4880
+ * auto-generatable sample.
3357
4881
  *
3358
4882
  * @param schema - The JSON Schema fragment to embed
3359
4883
  * @returns A raw shape owning a frozen copy of the fragment
@@ -3365,6 +4889,224 @@ export declare interface RawShape {
3365
4889
  */
3366
4890
  export declare function rawShape(schema: JSONSchema): RawShape;
3367
4891
 
4892
+ /**
4893
+ * Snapshot an array through its reflected own-index population.
4894
+ *
4895
+ * @remarks
4896
+ * Reads `length` once and one reflected own-key population, then corroborates
4897
+ * and reads only those reflected canonical indices in ascending order. The
4898
+ * frozen native snapshot retains actual holes: reading one yields `undefined`,
4899
+ * while own membership remains absent. Its work is proportional to the
4900
+ * reflected population, so a length-driven consumer must require `dense` or
4901
+ * carry an independent bound. Caller-defined iteration is ignored. A
4902
+ * descriptor-only index omitted from reflection is deliberately outside this
4903
+ * lens and remains a hole. Failure retains the exact thrown value when length,
4904
+ * reflection, membership, or indexed value observation throws; a non-native
4905
+ * length or view disagreement is also failure. `4294967295` is metadata rather
4906
+ * than an array index.
4907
+ *
4908
+ * @param value - The array whose reflected indexed entries to read
4909
+ * @returns A successful frozen entry snapshot with its dense fact, or a
4910
+ * failure carrying the exact thrown value as `unknown`
4911
+ *
4912
+ * @example
4913
+ * ```ts
4914
+ * readArrayEntries([1, 2]) // { success: true, value: { entries: [1, 2], dense: true } }
4915
+ * ```
4916
+ */
4917
+ export declare function readArrayEntries<T>(value: readonly T[]): Result<ArrayRead<T>>;
4918
+
4919
+ /**
4920
+ * Snapshot the genuine entries of a caller's `Map` without running an iterator.
4921
+ *
4922
+ * @remarks
4923
+ * The `Map` half of {@link readSetEntries}, with one further replaceable
4924
+ * dispatch removed: destructuring `for (const [key, value] of map)` reads
4925
+ * `Map.prototype[Symbol.iterator]` AND `Array.prototype[Symbol.iterator]` for
4926
+ * every pair, so a substituting iterator could rename a key or replace a value
4927
+ * while every downstream structural check still passed. Each pair is read
4928
+ * positionally from a list this package built.
4929
+ *
4930
+ * @param value - The map whose genuine entries to snapshot
4931
+ * @returns A frozen `[key, value]` pair snapshot, or a failure carrying the exact thrown value
4932
+ *
4933
+ * @example
4934
+ * ```ts
4935
+ * readMapEntries(new Map([['a', 1]])) // { success: true, value: [['a', 1]] }
4936
+ * ```
4937
+ */
4938
+ export declare function readMapEntries(value: ReadonlyMap<unknown, unknown>): Result<readonly (readonly unknown[])[]>;
4939
+
4940
+ /**
4941
+ * Validate and snapshot a shape-builder options record through every reflective
4942
+ * operation the builder relies on.
4943
+ *
4944
+ * @remarks
4945
+ * Primitive inputs are rejected before reflection so ordinary caller mistakes
4946
+ * retain the reader's precise plain-record diagnostic. For an object, every
4947
+ * consumed key is read exactly once, checked for presence, and inspected for an
4948
+ * own descriptor while the container is enumerated once. Every successfully
4949
+ * read non-`undefined` consumed value enters the fresh own-enumerable snapshot,
4950
+ * including an inherited or non-enumerable option. A hostile host is reported
4951
+ * uniformly as an unreadable options record, while a readable array or class
4952
+ * instance retains the plain-record diagnostic.
4953
+ *
4954
+ * @param source - The optional builder options value
4955
+ * @param keys - Every option key consumed by that builder
4956
+ * @param builder - The builder name used in diagnostics
4957
+ * @param shape - The shape category used in structured error context
4958
+ * @returns An owned options snapshot, or `undefined` when options are absent
4959
+ * @throws {ContractError} When the value is not a plain record or reflection fails
4960
+ *
4961
+ * @example
4962
+ * ```ts
4963
+ * const options = readOptions(source, ['min', 'max'], 'numberShape', 'number')
4964
+ * ```
4965
+ */
4966
+ export declare function readOptions<T extends object>(source: T | undefined, keys: readonly (keyof T & string)[], builder: string, shape: string): T | undefined;
4967
+
4968
+ /**
4969
+ * Rebuild a caller's regular expression as a stateless pattern this package
4970
+ * owns.
4971
+ *
4972
+ * @remarks
4973
+ * Strips the stateful `g` / `y` flags so repeated checks are stable and the
4974
+ * caller's `lastIndex` never moves. The strip is an INDEXED character filter
4975
+ * rather than `String.prototype.replaceAll`, which is itself a caller-writable
4976
+ * member: a substitute answering `'i'` made `matchOf(/^abc$/)` accept `'ABC'` —
4977
+ * the package building a case-insensitive pattern the developer never wrote.
4978
+ *
4979
+ * @param pattern - The caller's regular expression
4980
+ * @returns An owned, stateless equivalent
4981
+ * @throws The exact value thrown when the pattern's source or flags cannot be read
4982
+ *
4983
+ * @example
4984
+ * ```ts
4985
+ * readPattern(/^a+$/gy) // /^a+$/
4986
+ * ```
4987
+ */
4988
+ export declare function readPattern(pattern: RegExp): RegExp;
4989
+
4990
+ /**
4991
+ * Read a regular expression's flag text through the captured accessor.
4992
+ *
4993
+ * @param pattern - The candidate regular expression to read
4994
+ * @returns The pattern's flag text, or `undefined` when it cannot be read as a string
4995
+ * @throws The exact value the captured accessor throws for a receiver that is not a pattern
4996
+ *
4997
+ * @example
4998
+ * ```ts
4999
+ * readPatternFlags(/^a+$/giu) // 'giu'
5000
+ * ```
5001
+ */
5002
+ export declare function readPatternFlags(pattern: unknown): string | undefined;
5003
+
5004
+ /**
5005
+ * Read a regular expression's source text through the captured accessor.
5006
+ *
5007
+ * @remarks
5008
+ * `RegExp.prototype.source` is an ACCESSOR on a shared prototype, so replacing
5009
+ * its getter changes what every pattern in the realm reports — not only the
5010
+ * caller's own. A getter answering `'.*'` made `compileSchema` publish
5011
+ * `pattern: ".*"` inside a frozen schema and made `isRegExp('x')` answer `true`.
5012
+ * Reading the descriptor per call, as an earlier round did, captures nothing:
5013
+ * capture is decided by WHEN the reference is taken.
5014
+ *
5015
+ * @param pattern - The candidate regular expression to read
5016
+ * @returns The pattern's source text, or `undefined` when it cannot be read as a string
5017
+ * @throws The exact value the captured accessor throws for a receiver that is not a pattern
5018
+ *
5019
+ * @example
5020
+ * ```ts
5021
+ * readPatternSource(/^a+$/) // '^a+$'
5022
+ * ```
5023
+ */
5024
+ export declare function readPatternSource(pattern: unknown): string | undefined;
5025
+
5026
+ /**
5027
+ * Check that a value really is a {@link SampleMemo} before a walk stores a
5028
+ * published schema in it.
5029
+ *
5030
+ * @remarks
5031
+ * The memo is the one argument position on `inferSamples` /
5032
+ * `inferRecordSamples` that reaches a `WeakMap` and a `Map` the caller
5033
+ * supplied, and both doors are reachable untyped from JavaScript. Without this
5034
+ * check a wrong value there failed inside the traversal and was published as
5035
+ * `samples could not be read` — a true refusal naming the wrong argument, the
5036
+ * defect class those doors were already corrected for twice. It refuses under
5037
+ * the memo's own name and its own path instead.
5038
+ *
5039
+ * @param memo - The candidate memo
5040
+ * @param reader - The door name the refusal is published under
5041
+ * @returns The same memo when it carries a real `rows` `WeakMap` and `schemas` `Map`
5042
+ * @throws {ContractError} When the memo is not a `SampleMemo`
5043
+ *
5044
+ * @example
5045
+ * ```ts
5046
+ * readSampleMemo(buildSampleMemo(), 'inferSamples') // the same memo
5047
+ * ```
5048
+ */
5049
+ export declare function readSampleMemo(memo: SampleMemo, reader: string): SampleMemo;
5050
+
5051
+ /**
5052
+ * Snapshot the genuine contents of a caller's `Set` without running an iterator.
5053
+ *
5054
+ * @remarks
5055
+ * `Set.prototype[Symbol.iterator]` is a caller-writable member, and every other
5056
+ * view of the same collection disagrees with a replaced one: an iterator that
5057
+ * silently skips the non-string in `new Set(['a', 42])` made `setOf(isString)`
5058
+ * answer `true` while `forEach` and `size` still reported the real contents. The
5059
+ * sibling `arrayOf` already read its caller's collection through captured
5060
+ * reflection, so the exclusion was not even self-consistent within one file.
5061
+ * `forEach` is the only complete view of `[[SetData]]` that runs no iterator, so
5062
+ * it is dispatched here from the captured table.
5063
+ *
5064
+ * @param value - The set whose genuine entries to snapshot
5065
+ * @returns A frozen entry snapshot, or a failure carrying the exact thrown value
5066
+ *
5067
+ * @example
5068
+ * ```ts
5069
+ * readSetEntries(new Set(['a', 42])) // { success: true, value: ['a', 42] }
5070
+ * ```
5071
+ */
5072
+ export declare function readSetEntries(value: ReadonlySet<unknown>): Result<readonly unknown[]>;
5073
+
5074
+ /**
5075
+ * Read a value through the shared containment boundary or refuse it with the
5076
+ * contract module's uniform read diagnostic.
5077
+ *
5078
+ * @remarks
5079
+ * Unlike {@link attempt}, this is not an optional-result boundary: a caller
5080
+ * has committed to reading the supplied value, so a failed read cannot be
5081
+ * represented as absence or another permissive answer. Every reader using
5082
+ * this helper throws with the same `<reader>: <subject> could not be read`
5083
+ * message shape and retains the exact thrown value as its cause. Required
5084
+ * structural readers use the defaults; pattern readers supply `pattern` for
5085
+ * both the subject and code.
5086
+ *
5087
+ * @param callback - The read operation to perform
5088
+ * @param reader - The public reader name used in the diagnostic
5089
+ * @param options - Optional subject, code, and structured context
5090
+ * @returns The successfully read value
5091
+ * @throws {ContractError} When the read operation fails
5092
+ *
5093
+ * @example
5094
+ * ```ts
5095
+ * readValue(() => source.value, 'parseRecord')
5096
+ * ```
5097
+ */
5098
+ export declare function readValue<T>(callback: () => T, reader: string, options?: ReadValueOptions): T;
5099
+
5100
+ /** Optional diagnostic metadata for a required read. */
5101
+ export declare interface ReadValueOptions {
5102
+ /** Argument/domain noun used in the refusal message. */
5103
+ readonly subject?: string;
5104
+ /** Machine-readable refusal category. */
5105
+ readonly code?: ContractCode;
5106
+ /** Structured location and domain details retained by the refusal. */
5107
+ readonly context?: ContractErrorContext;
5108
+ }
5109
+
3368
5110
  export declare function recordOf<S extends GuardsShape>(shape: S): Guard<FromGuards<S>>;
3369
5111
 
3370
5112
  export declare function recordOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(shape: S, optional: K): Guard<OptionalFromGuards<S, K>>;
@@ -3383,6 +5125,7 @@ export declare function recordOf<S extends GuardsShape>(shape: S, optional: true
3383
5125
  * @param values - The shape every value must match
3384
5126
  * @param options - Optional `description`
3385
5127
  * @returns An open object shape
5128
+ * @throws {ContractError} When `values` is absent at runtime
3386
5129
  *
3387
5130
  * @example
3388
5131
  * ```ts
@@ -3396,16 +5139,55 @@ export declare interface RecordShapeOptions {
3396
5139
  readonly description?: string;
3397
5140
  }
3398
5141
 
5142
+ /**
5143
+ * Refuse a validated declaration whose compiled expansion exceeds
5144
+ * {@link COMPILE_NODE_LIMIT}.
5145
+ *
5146
+ * @remarks
5147
+ * The compilers' emitted-node bound, written once because two boundaries apply
5148
+ * it over a {@link ShapeValidatorInterface.expansion} count: the eager
5149
+ * {@link validateShapeDepth} function and the lazy {@link ContractCompiler}
5150
+ * preparation. The refusal keeps `validateShapeDepth`'s name because that gate
5151
+ * OWNS the rule and its exact diagnostic is public API — the same reason
5152
+ * `ShapeCloner` publishes the gate's depth wording rather than inventing a
5153
+ * second vocabulary for one rule. Two constructions of one refusal are two
5154
+ * messages waiting to drift apart.
5155
+ *
5156
+ * @param expansion - The node count one successful validation measured
5157
+ * @returns Nothing when the count is within the limit
5158
+ * @throws {ContractError} When the count exceeds {@link COMPILE_NODE_LIMIT}
5159
+ *
5160
+ * @example
5161
+ * ```ts
5162
+ * const validator = new ShapeValidator(shape)
5163
+ * validator.validate()
5164
+ * refuseExpansion(validator.expansion)
5165
+ * ```
5166
+ */
5167
+ export declare function refuseExpansion(expansion: number): void;
5168
+
5169
+ /**
5170
+ * A compiled coercive-domain diagnostic — the shape of `compileReporter` bound
5171
+ * to one shape.
5172
+ *
5173
+ * @remarks
5174
+ * The counterpart of {@link AuditorFunction} for the wider preimage `parse`
5175
+ * maps into the domain, with the same optional root-path prefix and the same
5176
+ * assignability to {@link ContractInterface.explain}.
5177
+ */
5178
+ export declare type ReporterFunction = (value: unknown, path?: readonly string[]) => readonly Fault[];
5179
+
3399
5180
  /**
3400
5181
  * Resolve a (possibly nested) field value from a record by a key or key path.
3401
5182
  *
3402
5183
  * @remarks
3403
5184
  * A single `string` is ONE key (never split on `.`, so dotted keys are safe); a
3404
- * string array descends left-to-right through nested objects. Intermediates may
3405
- * be any object — records, class instances, or arrays indexed by string. Returns
3406
- * `undefined` the moment a segment is missing or lands on a non-object, so the
3407
- * lookup is total — even against a hostile getter or Proxy trap that throws on
3408
- * read, contained via {@link attempt} so the throw never escapes.
5185
+ * string array descends left-to-right through own properties of nested objects.
5186
+ * The root must satisfy {@link isRecord}; inherited properties are never fields.
5187
+ * Intermediates may be objects or arrays indexed by string. Returns `undefined`
5188
+ * the moment a segment is missing or lands on a non-object, so the lookup is
5189
+ * total — even against a hostile getter or Proxy trap that throws on read,
5190
+ * contained via {@link attempt} so the throw never escapes.
3409
5191
  *
3410
5192
  * @param record - The source record
3411
5193
  * @param path - A property key, or a key path descending into nested objects
@@ -3420,8 +5202,70 @@ export declare interface RecordShapeOptions {
3420
5202
  */
3421
5203
  export declare function resolveField(record: Readonly<Record<string, unknown>>, path: FieldPath): unknown;
3422
5204
 
3423
- /** Discriminated union for operations that can succeed or fail without throwing. */
3424
- export declare type Result<T, E = Error> = Success<T> | Failure<E>;
5205
+ /**
5206
+ * Discriminated union for operations that can succeed or fail without throwing.
5207
+ *
5208
+ * @remarks
5209
+ * The failure channel defaults to `unknown`. Operations with a guaranteed
5210
+ * domain error name that error type explicitly.
5211
+ */
5212
+ export declare type Result<T, E = unknown> = Success<T> | Failure<E>;
5213
+
5214
+ /**
5215
+ * Record one node's answer at one remaining-depth allowance in a shared memo.
5216
+ *
5217
+ * @remarks
5218
+ * A depth-bounded walk answers the same node differently depending on how much
5219
+ * allowance was left when it arrived, so each node keeps a `Map` of answers
5220
+ * inside one `WeakMap`. Written inline, the get-or-create ferried that map out
5221
+ * of the branch that built it through a `let`, three times over in
5222
+ * `inferArray`, `inferObject` and `schemaNodeToShape`. Written once it is one
5223
+ * statement per caller, and the captured `WeakMap`/`Map` members stay the only
5224
+ * ones all three dispatch through — a substituted `WeakMap.prototype.get` that
5225
+ * answered a decoy map would otherwise decide what a later call replays.
5226
+ *
5227
+ * @param memo - The per-node depth memo this walk owns
5228
+ * @param node - The source node the answer was computed for
5229
+ * @param depth - The remaining-depth allowance the answer was computed under
5230
+ * @param answer - The answer to record for that node at that allowance
5231
+ *
5232
+ * @example
5233
+ * ```ts
5234
+ * const memo = new WeakMap<object, Map<number, string>>()
5235
+ * retainDepth(memo, node, 8, 'answer')
5236
+ * memo.get(node)?.get(8) // 'answer'
5237
+ * ```
5238
+ */
5239
+ export declare function retainDepth<T>(memo: WeakMap<object, Map<number, T>>, node: object, depth: number, answer: T): void;
5240
+
5241
+ /**
5242
+ * The per-walk memo {@link inferSamples} and {@link inferRecordSamples} share,
5243
+ * keyed by the ORDERED identities of the rows a slot collected.
5244
+ *
5245
+ * @remarks
5246
+ * `rows` is one step of a prefix chain: following the slot's rows in order
5247
+ * lands on the node that owns that exact row list, so two slots collecting the
5248
+ * same rows in the same order share one entry and two slots collecting
5249
+ * different rows never do. `schemas` holds that row list's already-inferred
5250
+ * results, keyed by EVERY budget and flag the emitted schema depends on
5251
+ * (remaining depth, breadth, `closed`, `format`, `enum`) — so the memo can
5252
+ * only ever return the schema a fresh call would have produced, and two
5253
+ * ordinary calls that differ in one flag cannot be served each other's answer.
5254
+ *
5255
+ * Build one with {@link buildSampleMemo} and give it to ONE walk. It is
5256
+ * traversal state, not a cache to keep: nothing is invalidated when a sample
5257
+ * row is later mutated.
5258
+ *
5259
+ * @example
5260
+ * ```ts
5261
+ * const memo = buildSampleMemo()
5262
+ * inferSamples([{ id: 1 }], 32, 256, true, false, false, memo)
5263
+ * ```
5264
+ */
5265
+ export declare interface SampleMemo {
5266
+ readonly rows: WeakMap<object, SampleMemo>;
5267
+ readonly schemas: Map<string, JSONSchema>;
5268
+ }
3425
5269
 
3426
5270
  /**
3427
5271
  * Classify a list of sample values against the {@link SchemaFormat}
@@ -3464,12 +5308,14 @@ export declare function samplesToFormat(values: readonly unknown[]): SchemaForma
3464
5308
  * and `enum` (both default `false`) opt a low-cardinality/unanimous-format
3465
5309
  * slot into the corresponding keyword — see {@link inferSamples} for the
3466
5310
  * precedence and the multi-sample format-disabling seam. `maxDepth` /
3467
- * `maxProperties` are sanitized via {@link sanitizeBudget} the same way
3468
- * {@link valueToSchema} sanitizes them — see there for why.
5311
+ * `maxProperties` are resolved exactly as {@link valueToSchema} resolves them —
5312
+ * breadth through {@link sanitizeBudget}, depth through {@link sanitizeDepth},
5313
+ * which also caps at {@link INFER_DEPTH_LIMIT}; see there for why.
3469
5314
  *
3470
5315
  * @param samples - The example values to infer a schema from
3471
5316
  * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` / `enum` bounds
3472
5317
  * @returns The inferred `JSONSchema`
5318
+ * @throws {ContractError} When the samples or options cannot be read
3473
5319
  *
3474
5320
  * @example
3475
5321
  * ```ts
@@ -3483,7 +5329,7 @@ export declare function samplesToSchema(samples: readonly unknown[], options?: V
3483
5329
 
3484
5330
  /**
3485
5331
  * Sanitize a user-supplied inference budget (`maxDepth` / `maxProperties`) to
3486
- * a finite non-negative integer, falling back to a default for anything else.
5332
+ * a finite non-negative integer, selecting a valid fallback for anything else.
3487
5333
  *
3488
5334
  * @remarks
3489
5335
  * Guards {@link valueToSchema} / {@link samplesToSchema} against a hostile or
@@ -3493,13 +5339,17 @@ export declare function samplesToSchema(samples: readonly unknown[], options?: V
3493
5339
  * instead of capping the list (a fractional value has a similarly undefined
3494
5340
  * `slice` bound). `Infinity` is rejected too — `Number.isInteger(Infinity)`
3495
5341
  * is `false` — since an unbounded budget is exactly the adversarial case the
3496
- * caps exist to prevent. A valid finite non-negative integer passes through
3497
- * unchanged.
5342
+ * caps exist to prevent. A valid candidate passes through unchanged without
5343
+ * inspecting the fallback. When the candidate is invalid, the fallback must
5344
+ * satisfy the same finite non-negative-integer contract or this boundary
5345
+ * refuses it with a coded error instead of returning an invalid budget.
3498
5346
  *
3499
5347
  * @param value - The candidate budget value
3500
- * @param fallback - The default to use when `value` is not a finite
3501
- * non-negative integer
5348
+ * @param fallback - The default to select when `value` is not a finite
5349
+ * non-negative integer
3502
5350
  * @returns A finite non-negative integer budget
5351
+ * @throws {ContractError} When the selected fallback is not a finite
5352
+ * non-negative integer
3503
5353
  *
3504
5354
  * @example
3505
5355
  * ```ts
@@ -3510,6 +5360,89 @@ export declare function samplesToSchema(samples: readonly unknown[], options?: V
3510
5360
  */
3511
5361
  export declare function sanitizeBudget(value: number | undefined, fallback: number): number;
3512
5362
 
5363
+ /**
5364
+ * Resolve a caller's depth budget to one the traversal can actually survive.
5365
+ *
5366
+ * @remarks
5367
+ * {@link sanitizeBudget} decides the SHAPE of a budget and deliberately lets any
5368
+ * finite non-negative integer through, because it must never read a fallback a
5369
+ * hostile caller supplied. That left the depth axis unbounded from above, and
5370
+ * depth is the axis that recurses: `1e9` is a valid integer, so the walk descended
5371
+ * until the call STACK failed, at a depth that varied between runs, and the
5372
+ * refusal surfaced as an unreadable value rather than as the exhaustion the guard
5373
+ * promises. Breadth needs no such ceiling — its loop is already bounded by the
5374
+ * entries actually present.
5375
+ *
5376
+ * So {@link INFER_DEPTH_LIMIT} is the ceiling as well as the default, and
5377
+ * `maxDepth` narrows the walk rather than widening it. One bound, and the same
5378
+ * answer on every host.
5379
+ *
5380
+ * @param value - The candidate depth budget
5381
+ * @returns A finite non-negative integer no greater than `INFER_DEPTH_LIMIT`
5382
+ *
5383
+ * @example
5384
+ * ```ts
5385
+ * sanitizeDepth(4) // 4
5386
+ * sanitizeDepth(1e9) // 32
5387
+ * ```
5388
+ */
5389
+ export declare function sanitizeDepth(value: number | undefined): number;
5390
+
5391
+ /**
5392
+ * Stateful owner of one JSON Schema snapshot operation.
5393
+ *
5394
+ * @remarks
5395
+ * Construction retains the source without observing it. The first
5396
+ * {@link clone} call performs one iterative identity-memoized walk and settles
5397
+ * permanently. Success replays the exact frozen root; failure rethrows the
5398
+ * exact class-owned error. Nonredirectable terminal settlement releases
5399
+ * populated traversal state before publishing that result, while retaining
5400
+ * the source and exact result afterward. Reentry poisons the active operation
5401
+ * and every later call with one shared cause-free error.
5402
+ *
5403
+ * @param schema - The JSON Schema graph to retain for cloning
5404
+ *
5405
+ * @example
5406
+ * ```ts
5407
+ * const child = { type: 'string' }
5408
+ * const cloner = new SchemaCloner({ anyOf: [child, child] })
5409
+ * const clone = cloner.clone()
5410
+ * clone.anyOf?.[0] === clone.anyOf?.[1] // true
5411
+ * cloner.clone() === clone // true
5412
+ * ```
5413
+ */
5414
+ export declare class SchemaCloner implements SchemaClonerInterface {
5415
+ #private;
5416
+ constructor(schema: JSONSchema);
5417
+ /**
5418
+ * Clone the retained schema into an identity-preserving frozen graph.
5419
+ *
5420
+ * @returns The settled JSON Schema snapshot
5421
+ * @throws {ContractError} When traversal is unreadable or cloning is reentered
5422
+ */
5423
+ clone(): JSONSchema;
5424
+ }
5425
+
5426
+ /**
5427
+ * Stateful owner of one JSON Schema snapshot operation.
5428
+ *
5429
+ * @remarks
5430
+ * Construction retains the schema without observing it. The first
5431
+ * {@link clone} call settles once; later calls replay the exact same frozen
5432
+ * schema or exact same owned {@link ContractError}. Nonredirectable terminal
5433
+ * settlement releases populated traversal state before publishing that exact
5434
+ * result, while retaining the source and result afterward.
5435
+ */
5436
+ export declare interface SchemaClonerInterface {
5437
+ /**
5438
+ * Clone the retained schema into a deeply frozen identity-preserving graph.
5439
+ *
5440
+ * @returns The settled JSON Schema snapshot
5441
+ * @throws {ContractError} When traversal is unreadable or cloning is reentered
5442
+ */
5443
+ clone(): JSONSchema;
5444
+ }
5445
+
3513
5446
  /**
3514
5447
  * The closed set of string formats {@link stringToFormat} recognizes.
3515
5448
  *
@@ -3529,15 +5462,15 @@ export declare type SchemaFormat = 'date-time' | 'date' | 'time' | 'uuid' | 'ema
3529
5462
  * `oneOf` / `anyOf` variants).
3530
5463
  *
3531
5464
  * @remarks
3532
- * Total: never throws. Guards depth exhaustion, a non-record node (the
3533
- * node's static `JSONSchema` type is not trusted at runtime), and a cyclic
3534
- * re-encounter of `schema` — all three widen to {@link rawShape}. The
5465
+ * Guards depth exhaustion, a readable non-record node (the node's static
5466
+ * `JSONSchema` type is not trusted at runtime), and a cyclic re-encounter of
5467
+ * `schema` — all three widen to {@link rawShape}. The
3535
5468
  * ancestor set is added to and removed from around the WHOLE subtree
3536
5469
  * conversion (not permanently), so a DAG-shaped schema reached twice via two
3537
5470
  * different, non-cyclic paths does not false-positive as a cycle. The
3538
- * subtree conversion itself runs inside {@link attempt}, so a hostile
3539
- * throwing getter/Proxy anywhere in `schema` cannot escape as a thrown error
3540
- * — it degrades to {@link rawShape} instead. A same-node re-conversion at
5471
+ * subtree conversion itself runs through {@link readValue}, so a hostile
5472
+ * throwing getter/Proxy anywhere in `schema` raises a coded read refusal
5473
+ * instead of degrading to an accept-anything shape. A same-node re-conversion at
3541
5474
  * the same remaining `depth` is served from `memo` (guards a
3542
5475
  * shared-reference schema DAG against exponential blowup), mirroring
3543
5476
  * {@link inferObject} / {@link inferArray} (inferers.ts).
@@ -3552,7 +5485,8 @@ export declare type SchemaFormat = 'date-time' | 'date' | 'time' | 'uuid' | 'ema
3552
5485
  * recursion state owned by the {@link schemaToShape} entry point; passing
3553
5486
  * a shared or pre-populated `WeakMap` changes caching behavior and is not
3554
5487
  * supported usage
3555
- * @returns The built shape for `schema`, or {@link rawShape} on any failure
5488
+ * @returns The built shape for `schema`, or {@link rawShape} for readable widening cases
5489
+ * @throws {ContractError} When schema traversal fails
3556
5490
  *
3557
5491
  * @example
3558
5492
  * ```ts
@@ -3568,7 +5502,7 @@ export declare function schemaNodeToShape(schema: JSONSchema, depth: number, vis
3568
5502
  * as an MCP-compatible `inputSchema`.
3569
5503
  *
3570
5504
  * @remarks
3571
- * Total and deterministic. `schema.type === 'object'` passes through
5505
+ * Deterministic for readable input. `schema.type === 'object'` passes through
3572
5506
  * unchanged; every other root (a primitive/array `type`, an `anyOf`/`enum`-only
3573
5507
  * schema with no `type`, or the empty `{}`) is wrapped as a single required
3574
5508
  * `value` property: `{ type: 'object', properties: { value: schema },
@@ -3577,6 +5511,7 @@ export declare function schemaNodeToShape(schema: JSONSchema, depth: number, vis
3577
5511
  *
3578
5512
  * @param schema - The schema to wrap
3579
5513
  * @returns `schema` unchanged when object-rooted, otherwise the wrapped object schema
5514
+ * @throws {ContractError} When the schema root cannot be read
3580
5515
  *
3581
5516
  * @example
3582
5517
  * ```ts
@@ -3603,10 +5538,11 @@ export declare function schemaToObject(schema: JSONSchema): JSONSchema;
3603
5538
  *
3604
5539
  * @param schema - The compiled JSON Schema (a contract's `schema`)
3605
5540
  * @returns The schema as the open tool-parameters record, or `undefined` when it is not a record
5541
+ * @throws {ContractError} When the schema cannot be read
3606
5542
  *
3607
5543
  * @example
3608
5544
  * ```ts
3609
- * import { createContract, schemaToParameters } from '@src/core'
5545
+ * import { createContract, schemaToParameters } from '@orkestrel/contract'
3610
5546
  *
3611
5547
  * const contract = createContract(shape)
3612
5548
  * const parameters = schemaToParameters(contract.schema) // the open record a tool advertises
@@ -3616,14 +5552,15 @@ export declare function schemaToParameters(schema: JSONSchema): Readonly<Record<
3616
5552
 
3617
5553
  /**
3618
5554
  * Convert a runtime `JSONSchema` value into a validating {@link ContractShape}
3619
- * — the inverse of {@link compileSchema}, and the validating sibling of
3620
- * {@link rawShape} (which embeds a schema fragment WITHOUT validating it).
5555
+ * — the inverse of {@link compileSchema}. Unlike direct {@link rawShape}
5556
+ * construction, which rejects malformed supported-vocabulary keywords, this
5557
+ * conversion is total and widens an inexpressible input to a valid raw `{}`.
3621
5558
  *
3622
5559
  * @remarks
3623
- * Total: NEVER throws, for any input — a malformed, cyclic, deeply-nested, or
3624
- * outright hostile (throwing-getter Proxy) `schema` value all degrade to
3625
- * {@link rawShape} rather than escaping as an error, so
3626
- * `createContract(schemaToShape(x))` is safe to call for any `x`. See
5560
+ * Readable malformed, cyclic, or deeply nested schema nodes widen to
5561
+ * {@link rawShape}; a failed traversal raises the shared coded refusal because
5562
+ * an unreadable value is not a schema. `createContract(schemaToShape(x))`
5563
+ * therefore remains safe for every readable `x`. See
3627
5564
  * {@link buildShapeFromNode} for the exact per-keyword precedence.
3628
5565
  *
3629
5566
  * `format` and `pattern` are NEVER asserted by the compiled shape — `format`
@@ -3635,12 +5572,16 @@ export declare function schemaToParameters(schema: JSONSchema): Readonly<Record<
3635
5572
  * cyclic re-encounter — widens to {@link rawShape} (accept any defined
3636
5573
  * value), never narrows.
3637
5574
  *
3638
- * ROUND TRIP: `compileGuard(schemaToShape(valueToSchema(v)))(v)` is `true` for
3639
- * every `v` — including the values no JSON Schema keyword describes (`NaN`,
3640
- * `±Infinity`, a `Map`, a `Set`, a class instance, a function, a symbol, a
3641
- * bigint, a cyclic or hostile host), which infer `{}` and widen back to an
3642
- * accept-anything {@link rawShape}. Widening is the only source of looseness.
3643
- * The law has three explicit host limits:
5575
+ * ROUND TRIP: for every readable `v`,
5576
+ * `compileGuard(schemaToShape(valueToSchema(v)))(v)` is `true` — including
5577
+ * values no JSON Schema keyword describes (`NaN`, `±Infinity`, a `Map`, a
5578
+ * `Set`, a class instance, a function, a symbol, a bigint, and readable cyclic
5579
+ * hosts), which infer `{}` and widen back to an accept-anything
5580
+ * {@link rawShape}. An unreadable host is refused by {@link valueToSchema}
5581
+ * before this law produces a schema; direct hostile input to
5582
+ * {@link schemaToShape} receives the same coded refusal.
5583
+ * Widening is the only source of looseness. The law has three explicit host
5584
+ * limits:
3644
5585
  *
3645
5586
  * - **Absence.** `undefined` is not a value: no compiled guard accepts it
3646
5587
  * (`rawShape` reserves it as the parser failure sentinel). So `undefined`
@@ -3665,6 +5606,7 @@ export declare function schemaToParameters(schema: JSONSchema): Readonly<Record<
3665
5606
  *
3666
5607
  * @param schema - The JSON Schema value to convert
3667
5608
  * @returns The built {@link ContractShape}
5609
+ * @throws {ContractError} When schema traversal fails
3668
5610
  *
3669
5611
  * @example
3670
5612
  * ```ts
@@ -3696,6 +5638,55 @@ export declare function schemaToShape(schema: JSONSchema): ContractShape;
3696
5638
  */
3697
5639
  export declare function seededRandom(seed: number): RandomFunction;
3698
5640
 
5641
+ /**
5642
+ * A compiled seed-data source — the shape of `compileGenerator` bound to one
5643
+ * shape.
5644
+ *
5645
+ * @remarks
5646
+ * An absent `random` selects the invocation's own wall-clock-seeded source, so
5647
+ * a generator retains no randomness between calls.
5648
+ *
5649
+ * @remarks
5650
+ * Named for the SEED DATA it produces rather than for the `generator` getter it
5651
+ * serves, which is the one place this package's three compiled-diagnostic types
5652
+ * break their own symmetry with {@link AuditorFunction} and
5653
+ * {@link ReporterFunction}. `GeneratorFunction` is already taken twice over: it
5654
+ * is a realm global (the constructor every `function*` reports), and it is the
5655
+ * exact string {@link isGeneratorFunction} compares against. Publishing a type
5656
+ * of that name beside that guard would put two contradictory meanings of one
5657
+ * word in one barrel, where `isGeneratorFunction(contract.generate)` answers
5658
+ * `false` for a value the types call a `GeneratorFunction`.
5659
+ */
5660
+ export declare type SeederFunction<T> = (random?: RandomFunction) => T;
5661
+
5662
+ /**
5663
+ * Select the report of the variant that came closest to matching.
5664
+ *
5665
+ * @remarks
5666
+ * The union summary both diagnostic doors append their closest variant's faults
5667
+ * to. "Closest" is the SHORTEST report, and an earlier variant wins a tie, so a
5668
+ * union's diagnostic follows declaration order rather than whichever variant a
5669
+ * later comparison happened to visit. The winning report is returned BY
5670
+ * IDENTITY, never copied, so the summary carries the exact fault objects the
5671
+ * variant produced. No report at all — a union whose every variant slot was
5672
+ * unreadable — yields a frozen empty collection rather than `undefined`, so the
5673
+ * caller appends nothing instead of branching.
5674
+ *
5675
+ * The scan is an indexed read of arrays this package built, so neither the
5676
+ * choice of variant nor the length comparison dispatches through a member a
5677
+ * caller can replace.
5678
+ *
5679
+ * @param reports - One report per variant, in declaration order
5680
+ * @returns The first shortest report, or a frozen empty collection when there are none
5681
+ *
5682
+ * @example
5683
+ * ```ts
5684
+ * selectClosestFaults([[fault, fault], [fault]]) // the second report
5685
+ * selectClosestFaults([]) // []
5686
+ * ```
5687
+ */
5688
+ export declare function selectClosestFaults<T extends AuditFault>(reports: readonly (readonly T[])[]): readonly T[];
5689
+
3699
5690
  /**
3700
5691
  * Build a guard that accepts `Set` instances whose every element satisfies
3701
5692
  * `elementGuard`.
@@ -3711,18 +5702,99 @@ export declare function setOf<T>(elementGuard: Guard<T>): Guard<ReadonlySet<T>>;
3711
5702
 
3712
5703
  export declare function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>>;
3713
5704
 
5705
+ /**
5706
+ * Stateful owner of one contract-shape snapshot operation.
5707
+ *
5708
+ * @remarks
5709
+ * Construction retains the source without observing it. The first
5710
+ * {@link clone} call captures and validates one owned graph and settles
5711
+ * permanently. Success replays the exact frozen root; failure rethrows the
5712
+ * exact class-owned or directly adopted error. Nonredirectable settlement
5713
+ * releases populated traversal state before publishing that result. Reentry
5714
+ * poisons the active operation and every later call with one shared cause-free
5715
+ * error.
5716
+ *
5717
+ * @param shape - The contract-shape graph to retain for cloning
5718
+ *
5719
+ * @example
5720
+ * ```ts
5721
+ * const cloner = new ShapeCloner({ type: 'string', min: 1 })
5722
+ * const clone = cloner.clone()
5723
+ * cloner.clone() === clone // true
5724
+ * ```
5725
+ */
5726
+ export declare class ShapeCloner implements ShapeClonerInterface {
5727
+ #private;
5728
+ constructor(shape: ContractShape);
5729
+ /**
5730
+ * Clone the retained declaration into an owned, validated frozen graph.
5731
+ *
5732
+ * @returns The settled contract-shape snapshot
5733
+ * @throws {ContractError} When the declaration is malformed, unreadable, cyclic, too deep, or cloning is reentered
5734
+ */
5735
+ clone(): ContractShape;
5736
+ }
5737
+
5738
+ export declare interface ShapeClonerInterface {
5739
+ /**
5740
+ * Clone the retained shape into a deeply frozen identity-preserving graph.
5741
+ *
5742
+ * @returns The settled contract-shape snapshot
5743
+ * @throws {ContractError} When the declaration is malformed, unreadable, cyclic, too deep, or cloning is reentered
5744
+ */
5745
+ clone(): ContractShape;
5746
+ }
5747
+
5748
+ /**
5749
+ * Stateful owner of one contract-shape snapshot operation.
5750
+ *
5751
+ * @remarks
5752
+ * Construction retains the shape without observing it. The first
5753
+ * {@link clone} call settles once; later calls replay the exact same frozen
5754
+ * shape or exact same owned {@link ContractError}. Nonredirectable terminal
5755
+ * settlement releases populated traversal state before publishing that exact
5756
+ * result, while retaining the source and result afterward.
5757
+ * Reentry permanently poisons the active operation with one shared error.
5758
+ */
5759
+ /**
5760
+ * One captured property of an object shape, held as an ordered entry rather
5761
+ * than as a `Map` pair.
5762
+ *
5763
+ * @remarks
5764
+ * The published property population of a cloned object shape is decided by
5765
+ * walking these entries. A `Map` would be the natural carrier and the wrong
5766
+ * one: iterating it dispatches through `Map.prototype[Symbol.iterator]` and
5767
+ * destructuring each pair through `Array.prototype[Symbol.iterator]`, both
5768
+ * caller-writable, and an arity-preserving substitution there renames a
5769
+ * property inside a snapshot the package publishes as exact.
5770
+ */
5771
+ export declare interface ShapeProperty {
5772
+ /** The own enumerable key the property was captured under. */
5773
+ readonly key: string;
5774
+ /** The captured child shape, absent when the declaration held no shape. */
5775
+ readonly child: ContractShape | undefined;
5776
+ }
5777
+
3714
5778
  /**
3715
5779
  * Project a {@link ContractShape} to the {@link FaultKind} it describes.
3716
5780
  *
3717
5781
  * @remarks
3718
5782
  * A structural mapping used by {@link compileReporter} to fill a `Fault`'s
3719
- * `expected` field: most shapes map to their own `type` (`numberShape` maps to
5783
+ * `expected` field and by {@link compileAuditor} to fill an `AuditFault`'s:
5784
+ * most shapes map to their own `type` (`numberShape` maps to
3720
5785
  * `'integer'` when `integer: true`, else `'number'`); `optionalShape` /
3721
5786
  * `nullableShape` project through to their inner shape's kind, and `rawShape`
3722
5787
  * (an arbitrary embedded schema with no fixed kind) projects to `'json'`.
3723
5788
  *
5789
+ * A hand-authored node carrying an unrecognized discriminant is REFUSED rather
5790
+ * than answered out of type. The switch used to fall off its end and return
5791
+ * `undefined` for such a node, which made the declared non-optional
5792
+ * {@link FaultKind} return type a lie at a public export; every other door in
5793
+ * this module refuses out-of-domain input, so this one does too.
5794
+ *
3724
5795
  * @param shape - The shape to project
3725
5796
  * @returns The shape's {@link FaultKind}
5797
+ * @throws {ContractError} When the node carries no recognized shape discriminant
3726
5798
  *
3727
5799
  * @example
3728
5800
  * ```ts
@@ -3733,6 +5805,106 @@ export declare function setOf(elementGuard: (value: unknown) => boolean): Guard<
3733
5805
  */
3734
5806
  export declare function shapeToKind(shape: ContractShape): FaultKind;
3735
5807
 
5808
+ /**
5809
+ * A reusable live validator for one retained contract-shape source.
5810
+ *
5811
+ * @remarks
5812
+ * Construction performs no source observation. Every non-overlapping
5813
+ * {@link validate} call starts a fresh pass over the source's current state.
5814
+ * Reentry poisons the active pass with one shared cause-free structure error;
5815
+ * cleanup always restores an idle validator for the next independent call.
5816
+ *
5817
+ * @example
5818
+ * ```ts
5819
+ * const validator = new ShapeValidator({ type: 'string', min: 1 })
5820
+ * validator.validate()
5821
+ * ```
5822
+ */
5823
+ export declare class ShapeValidator implements ShapeValidatorInterface {
5824
+ #private;
5825
+ /**
5826
+ * Retain a shape source without observing it.
5827
+ *
5828
+ * @param shape - The live shape source validated by each call
5829
+ */
5830
+ constructor(shape: ContractShape);
5831
+ /**
5832
+ * The number of nodes the last successful {@link validate} found the source
5833
+ * expands into.
5834
+ *
5835
+ * @remarks
5836
+ * One per node per INCOMING EDGE, summed bottom-up — the size of the tree a
5837
+ * compiler would build from this DAG, which a node count of the declaration
5838
+ * itself does not describe. `0` before the first successful pass and after a
5839
+ * failed one, because a failed pass has no expansion to report.
5840
+ */
5841
+ get expansion(): number;
5842
+ /**
5843
+ * Validate the retained source's current declaration.
5844
+ *
5845
+ * @remarks
5846
+ * The whole traversal is contained, and a failure this class did not author
5847
+ * is translated into `validateShapeDepth: shape reflection failed` carrying
5848
+ * the exact thrown value. Containment is what makes that claim hold for
5849
+ * dispatch nobody enumerated — including the recognition of an authored error,
5850
+ * which is why that recognition is no longer answerable by any member a caller
5851
+ * can write. The sentence this replaces asserted the same conclusion from the
5852
+ * absence of reachable dispatch, and the absence was not established.
5853
+ *
5854
+ * @returns Nothing when the declaration is valid
5855
+ * @throws {ContractError} When the declaration is malformed, cyclic, too deep, unreadable, or reentered
5856
+ */
5857
+ validate(): void;
5858
+ }
5859
+
5860
+ /**
5861
+ * Validates one retained contract-shape source on demand.
5862
+ *
5863
+ * @remarks
5864
+ * Construction does not observe the source. Every {@link validate} call is an
5865
+ * independent live validation pass over its current state.
5866
+ */
5867
+ export declare interface ShapeValidatorInterface {
5868
+ /**
5869
+ * The number of nodes the last successful {@link validate} found the retained
5870
+ * declaration expands into, counting one per node per incoming edge — the
5871
+ * size of the TREE every compiled artifact would build from this DAG. `0`
5872
+ * before the first successful pass and after a failed one.
5873
+ */
5874
+ readonly expansion: number;
5875
+ /**
5876
+ * Validate the retained shape declaration.
5877
+ *
5878
+ * @returns Nothing when the declaration is valid
5879
+ * @throws {ContractError} When the declaration is malformed, cyclic, or too deep
5880
+ */
5881
+ validate(): void;
5882
+ }
5883
+
5884
+ /**
5885
+ * Order primitive keys or indices deterministically, on an owned copy, through
5886
+ * the captured sort.
5887
+ *
5888
+ * @remarks
5889
+ * Every schema this package emits is ordered so the same input produces the
5890
+ * same bytes, and `Array.prototype.sort` is a caller-writable member on every
5891
+ * one of those paths: a substitute that empties its receiver made
5892
+ * `valueToSchema({ b: 1, a: 2 })` publish `{"type":"object","additionalProperties":false}`
5893
+ * — a successful answer with the caller's properties silently gone. The copy is
5894
+ * taken first so a caller-owned array is never reordered in place, and the order
5895
+ * is decided by {@link compareValues}, whose `<` / `>` comparison dispatches
5896
+ * through nothing.
5897
+ *
5898
+ * @param values - The keys or indices to order
5899
+ * @returns A fresh array in ascending order
5900
+ *
5901
+ * @example
5902
+ * ```ts
5903
+ * sortValues(['b', 'a']) // ['a', 'b']
5904
+ * ```
5905
+ */
5906
+ export declare function sortValues<T extends string | number>(values: readonly T[]): readonly T[];
5907
+
3736
5908
  /**
3737
5909
  * Build a guard that accepts strings satisfying optional length and pattern
3738
5910
  * refinements — `min` / `max` length and a `pattern`.
@@ -3747,6 +5919,7 @@ export declare function shapeToKind(shape: ContractShape): FaultKind;
3747
5919
  *
3748
5920
  * @param options - Optional length bounds and regular expression refinement
3749
5921
  * @returns A string guard enforcing the requested refinements
5922
+ * @throws {ContractError} When the options cannot be read
3750
5923
  *
3751
5924
  * @example
3752
5925
  * ```ts
@@ -3769,7 +5942,10 @@ export declare interface StringShape {
3769
5942
  readonly type: 'string';
3770
5943
  readonly min?: number;
3771
5944
  readonly max?: number;
3772
- /** A pattern constraint; builders and cloners expose an owned fresh frozen zero-state copy per read. */
5945
+ /**
5946
+ * An unflagged pattern constraint; use inline pattern constructs for flag-like behavior.
5947
+ * Builders and cloners expose an owned fresh frozen zero-state copy per read.
5948
+ */
3773
5949
  readonly pattern?: RegExp;
3774
5950
  readonly description?: string;
3775
5951
  }
@@ -3784,7 +5960,7 @@ export declare interface StringShape {
3784
5960
  *
3785
5961
  * @param options - Optional length (`min` / `max`), `pattern`, and `description`
3786
5962
  * @returns A string shape
3787
- * @throws {ContractError} When a present bound is invalid or `pattern` has flags
5963
+ * @throws {ContractError} When a present bound is invalid, `pattern` is not a `RegExp`, or `pattern` has flags
3788
5964
  *
3789
5965
  * @example
3790
5966
  * ```ts
@@ -3871,14 +6047,15 @@ export declare type TupleFromGuards<Ts extends ReadonlyArray<Guard<unknown>>> =
3871
6047
  }>;
3872
6048
 
3873
6049
  /**
3874
- * Build a guard that accepts fixed-arity tuples, testing each index with the
3875
- * corresponding guard.
6050
+ * Build a guard that accepts fixed-arity DENSE tuples, testing each index with
6051
+ * the corresponding guard.
3876
6052
  *
3877
6053
  * @example
3878
6054
  * ```ts
3879
6055
  * const isPair = tupleOf(isString, isNumber)
3880
6056
  * isPair(['hello', 42]) // true
3881
6057
  * isPair(['hello']) // false — wrong arity
6058
+ * isPair([, 42]) // false — sparse; see arrayOf for the dense lens
3882
6059
  * ```
3883
6060
  */
3884
6061
  export declare function tupleOf<const Gs extends ReadonlyArray<Guard<unknown>>>(...guards: Gs): Guard<TupleFromGuards<Gs>>;
@@ -3897,13 +6074,18 @@ export declare function tupleOf(...predicates: ReadonlyArray<(value: unknown) =>
3897
6074
  * `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.
3898
6075
  * An empty input list returns the empty accept-anything schema `{}`.
3899
6076
  *
3900
- * A member {@link canonicalStringify} cannot key — a cyclic, hostile, or
6077
+ * Every captured member must first be a non-null object record. This runtime
6078
+ * requirement is realm-agnostic and admits ordinary and null-prototype schema
6079
+ * records while refusing primitives and callables before canonicalization.
6080
+ *
6081
+ * A readable member {@link canonicalStringify} cannot key — a cyclic or
3901
6082
  * otherwise JSON-inexpressible fragment, which only a direct caller can supply
3902
6083
  * since the inferers always build plain encodable fragments — has NO
3903
6084
  * de-duplication key, so it can participate in neither de-duplication nor the
3904
6085
  * canonical-key ordering. It is KEPT (dropping a variant would narrow the
3905
6086
  * union, and unification only ever widens), appended in input order after the
3906
- * sorted keyed members, so the result stays total and deterministic.
6087
+ * sorted keyed members. A failed member read propagates the canonicalizer's
6088
+ * coded refusal instead of participating in the union.
3907
6089
  *
3908
6090
  * @param schemas - The schemas to unify
3909
6091
  * @returns The unified schema
@@ -3963,64 +6145,53 @@ export declare function unionShape<V extends readonly ContractShape[]>(...varian
3963
6145
  export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
3964
6146
 
3965
6147
  /**
3966
- * Validate that a {@link ContractShape} graph is well-formed before
3967
- * compilation.
6148
+ * Gate recursive compiler work on shape structure, depth, and cycles.
3968
6149
  *
3969
6150
  * @remarks
3970
- * Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this
3971
- * throws a coded {@link ContractError} immediately rather than surfacing as a
3972
- * silently-wrong guard, parser, schema, or generator later. The iterative walk
3973
- * tracks active ancestors, so a structural cycle reports its precise path while
3974
- * a shared child reached through separate paths remains legal. Checks:
3975
- *
3976
- * - An {@link OptionalShape} is only legal as a direct object-property value —
3977
- * `optionalShape` wrapping an array item, a union variant, another
3978
- * optional/nullable's inner shape, `additionalProperties`, or the top-level
3979
- * shape all throw. An object property IS the one legal placement: its value
3980
- * is unwrapped to `.inner` before recursing, so `.inner` itself is validated
3981
- * as a normal (non-optional-wrapping) shape.
3982
- * - A {@link UnionShape} needs at least one variant; a {@link LiteralShape}
3983
- * needs at least one value and rejects non-finite (`NaN` / `Infinity` /
3984
- * `-Infinity`) number values.
3985
- * - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}
3986
- * needs `min <= max` when both are set.
3987
- * - Every present number bound is finite.
3988
- * - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer
3989
- * range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.
3990
- * - Shape nesting may not exceed {@link COMPILE_DEPTH_LIMIT}; excessive depth
3991
- * fails before recursive artifact compilation begins. Because the depth check
3992
- * runs before the active-ancestor check, a back-edge first reached beyond the
3993
- * limit reports `depth`; a cycle reached within the limit reports `cycle`.
3994
- * - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion
3995
- * continues into array items, object properties (and `additionalProperties`
3996
- * when it is a shape), union variants, and optional/nullable inner shapes.
6151
+ * Constructs a fresh {@link ShapeValidator} and eagerly validates the graph.
6152
+ * The validator walks iteratively with explicit stack space and observes each
6153
+ * unique node exactly ONCE per call, so a shared-child DAG costs its AUTHORED
6154
+ * nodes and edges rather than its paths. Every incoming edge is still inspected:
6155
+ * where an `optional` node is legal depends on the slot it arrived through, and
6156
+ * depth is measured over the captured graph afterwards rather than by walking
6157
+ * each path.
6158
+ *
6159
+ * This is also where the compilers' expansion bound lives. Every compiled
6160
+ * artifact is a tree, so a DAG's cost is the size of the tree it expands into —
6161
+ * `objectShape({ left: node, right: node })` nested thirty times is thirty-one
6162
+ * authored nodes and more than a billion emitted ones. The validator counts
6163
+ * that expansion and {@link refuseExpansion} refuses past
6164
+ * {@link COMPILE_NODE_LIMIT} with an `expansion`-coded {@link ContractError}, so
6165
+ * every standalone compiler and {@link createContract} answer a shared-child
6166
+ * declaration in bounded time instead of not answering. {@link cloneShape} /
6167
+ * {@link ownShape} are deliberately NOT bounded by it: they preserve
6168
+ * shared-child identity, so ownership of the same declaration stays
6169
+ * proportional to its authored nodes.
6170
+ * Every structural child slot must contain a shape node before it can enter the
6171
+ * walk; every scalar field must hold its declared runtime domain before a
6172
+ * compiler can use it; and a missing child, corrupt container, inherited
6173
+ * discriminant, or unrecognized node reports `structure`. This is the SOLE
6174
+ * eager well-formedness pass — there is no second prepass and no alias for it:
6175
+ * it enforces every bound domain and range used by the artifacts, including
6176
+ * non-empty literal/union vocabularies, finite literal numbers, integer-range
6177
+ * satisfiability, unflagged string patterns, optional-shape placement, and the
6178
+ * recursively supported raw-schema vocabulary where every present property or
6179
+ * dense union member is a record.
6180
+ * Active ancestors are tracked so shared children remain legal. Every
6181
+ * standalone compiler reaches this same validation once, over its owned
6182
+ * snapshot, through {@link ContractCompiler} preparation.
6183
+ * Failures have deterministic precedence independent of traversal order: depth,
6184
+ * then structure, then cycle, then field and vocabulary policy.
3997
6185
  *
3998
- * @param shape - The shape to validate
3999
- * @throws {ContractError} When the shape is malformed or cyclic
6186
+ * @param shape - The shape graph to gate
6187
+ * @returns Nothing; successful return means recursive compilation is structurally safe, depth-safe, and bounded in emitted nodes
6188
+ * @throws {ContractError} When a node or structural slot is corrupt, a bound or vocabulary is outside its declared domain, the graph is cyclic, it exceeds the compilation depth limit, or it expands past the compilation node limit
4000
6189
  *
4001
6190
  * @example
4002
6191
  * ```ts
4003
- * validateShape(stringShape({ min: 1, max: 10 })) // does not throw
4004
- * validateShape(stringShape({ min: 10, max: 1 })) // throws
6192
+ * validateShapeDepth(stringShape({ min: 1 })) // returns; the declaration is compilable
4005
6193
  * ```
4006
6194
  */
4007
- export declare function validateShape(shape: ContractShape): void;
4008
-
4009
- /**
4010
- * Gate recursive compiler work on shape depth and structural cycles.
4011
- *
4012
- * @remarks
4013
- * Walks the shape graph iteratively in linear time and stack space, tracking
4014
- * active ancestors so shared children remain legal. Every standalone compiler
4015
- * calls this gate before its recursive branch begins. The depth check runs
4016
- * before the active-ancestor check, so a back-edge first reached beyond
4017
- * {@link COMPILE_DEPTH_LIMIT} reports `depth`; a shallower cycle reports
4018
- * `cycle`.
4019
- *
4020
- * @param shape - The shape graph to gate
4021
- * @returns Nothing; successful return means recursive compilation is depth-safe
4022
- * @throws {ContractError} When the shape is cyclic or exceeds the compilation depth limit
4023
- */
4024
6195
  export declare function validateShapeDepth(shape: ContractShape): void;
4025
6196
 
4026
6197
  /**
@@ -4028,8 +6199,9 @@ export declare function validateShapeDepth(shape: ContractShape): void;
4028
6199
  * {@link compileSchema}.
4029
6200
  *
4030
6201
  * @remarks
4031
- * Total: never throws, and is cycle/depth/breadth-bounded (see
4032
- * {@link inferValue} / {@link inferArray} / {@link inferObject}). Nested
6202
+ * Cycle/depth/breadth-bounded (see {@link inferValue} / {@link inferArray} /
6203
+ * {@link inferObject}). A failed traversal throws a `structure`
6204
+ * {@link ContractError}; it never becomes `{}` or another permissive schema. Nested
4033
6205
  * objects close to unknown keys (`additionalProperties: false`) by default;
4034
6206
  * pass `closed: false` to open them. `format` (default `false`) opts a
4035
6207
  * string/`Date` leaf into the `format` keyword. Structurally-equal inputs
@@ -4040,15 +6212,21 @@ export declare function validateShapeDepth(shape: ContractShape): void;
4040
6212
  * expect an object-shaped `inputSchema`; wrap a non-object payload with
4041
6213
  * {@link schemaToObject} before advertising it as a tool's parameters.
4042
6214
  *
4043
- * `maxDepth` / `maxProperties` are sanitized via {@link sanitizeBudget} to a
4044
- * finite non-negative integer, falling back to {@link INFER_DEPTH_LIMIT} /
4045
- * {@link INFER_BREADTH_LIMIT} for anything else (`NaN`, `Infinity`, negative,
4046
- * fractional) — a hostile or malformed budget can never defeat the depth
4047
- * guard or corrupt the sampled key/element list.
6215
+ * `maxProperties` is sanitized via {@link sanitizeBudget} to a finite
6216
+ * non-negative integer, falling back to {@link INFER_BREADTH_LIMIT} for anything
6217
+ * else (`NaN`, `Infinity`, negative, fractional), so a malformed breadth cannot
6218
+ * corrupt the sampled key/element list.
6219
+ *
6220
+ * `maxDepth` goes through {@link sanitizeDepth}, which does the same and then caps
6221
+ * at {@link INFER_DEPTH_LIMIT}, so the option NARROWS the walk and cannot widen
6222
+ * it. The cap is what makes the depth guard unbreakable: depth is the recursing
6223
+ * axis, and a large-but-valid budget used to descend until the call STACK failed
6224
+ * rather than until the guard said stop.
4048
6225
  *
4049
6226
  * @param value - The value to infer a schema from
4050
6227
  * @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` bounds
4051
6228
  * @returns The inferred `JSONSchema`
6229
+ * @throws {ContractError} When the value or options cannot be read
4052
6230
  *
4053
6231
  * @example
4054
6232
  * ```ts