dissent 0.0.0-stage → 0.1.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,3793 @@
1
+ import { AISDKError, APICallError, LoadAPIKeyError, NoObjectGeneratedError, NoOutputGeneratedError, Output, RetryError, asSchema, generateText } from "ai";
2
+ // src/errors.ts
3
+ const ROOT_MARKER = Symbol.for("dissent.error.DissentError");
4
+ const ARGUMENT_MARKER = Symbol.for("dissent.error.DissentArgumentError");
5
+ const NON_JSON_MARKER = Symbol.for("dissent.error.NonJsonValueError");
6
+ function hasMarker(error, marker) {
7
+ return typeof error === "object" && error !== null && error[marker] === true;
8
+ }
9
+ var DissentError = class extends Error {
10
+ [ROOT_MARKER] = true;
11
+ constructor(message, options) {
12
+ super(message, options);
13
+ this.name = "DissentError";
14
+ }
15
+ static isInstance(error) {
16
+ return hasMarker(error, ROOT_MARKER);
17
+ }
18
+ };
19
+ var DissentArgumentError = class extends DissentError {
20
+ [ARGUMENT_MARKER] = true;
21
+ code;
22
+ /** The option or path at fault, e.g. 'witnesses.__proto__' or 'compare./risk'. */
23
+ argument;
24
+ constructor(code, argument, message) {
25
+ super(message ?? `Invalid argument "${argument}": ${code}`);
26
+ this.name = "DissentArgumentError";
27
+ this.code = code;
28
+ this.argument = argument;
29
+ }
30
+ static isInstance(error) {
31
+ return hasMarker(error, ARGUMENT_MARKER);
32
+ }
33
+ };
34
+ /** Thrown by the internal canonicalizer; caught in Layer A and recorded as invalid-output. */
35
+ var NonJsonValueError = class extends DissentError {
36
+ [NON_JSON_MARKER] = true;
37
+ /** JSON Pointer of the offending value. */
38
+ path;
39
+ /** e.g. 'Date', 'Map', 'NaN', 'Infinity', 'bigint', 'function', 'symbol', 'undefined-in-array', 'cycle', 'depth'. */
40
+ found;
41
+ constructor(path, found) {
42
+ super(`Value at "${path === "" ? "(root)" : path}" is not JSON-compatible: ${found}`);
43
+ this.name = "NonJsonValueError";
44
+ this.path = path;
45
+ this.found = found;
46
+ }
47
+ static isInstance(error) {
48
+ return hasMarker(error, NON_JSON_MARKER);
49
+ }
50
+ };
51
+ // src/paths.ts
52
+ /** RFC 6901 JSON Pointer helpers (§5.1). Pure, no imports. */
53
+ function escapePointerToken(token) {
54
+ return token.replaceAll("~", "~0").replaceAll("/", "~1");
55
+ }
56
+ /** Throws `SyntaxError` for a `~` not followed by `0` or `1`. */
57
+ function unescapePointerToken(token) {
58
+ if (/~(?![01])/.test(token)) throw new SyntaxError(`Invalid JSON Pointer token: ${token}`);
59
+ return token.replaceAll("~1", "/").replaceAll("~0", "~");
60
+ }
61
+ /** Appends one escaped token to a pointer. `appendPointer('', 'a/b')` is `/a~1b`. */
62
+ function appendPointer(pointer, token) {
63
+ return `${pointer}/${escapePointerToken(token)}`;
64
+ }
65
+ /** Splits a pointer into unescaped tokens. `''` is the root (no tokens). */
66
+ function parsePointer(pointer) {
67
+ if (pointer === "") return [];
68
+ if (!pointer.startsWith("/")) throw new SyntaxError(`JSON Pointer must be empty or start with "/": ${pointer}`);
69
+ return pointer.slice(1).split("/").map(unescapePointerToken);
70
+ }
71
+ /**
72
+ * Normalizes a `compare` key or `claim.path`: a string starting with `/` is already a
73
+ * pointer; any other string is a top-level property name (§5.1).
74
+ */
75
+ function normalizePath(pathOrName) {
76
+ return pathOrName.startsWith("/") ? pathOrName : `/${escapePointerToken(pathOrName)}`;
77
+ }
78
+ /**
79
+ * RFC 8785 (JCS) serializer with a JSON-value guard (§4.1, §4.4).
80
+ *
81
+ * Keys sort by UTF-16 code units. `toJSON` is never called. Object properties whose value
82
+ * is `undefined` are omitted. Anything that is not plain JSON throws `NonJsonValueError`.
83
+ */
84
+ function canonicalJson(value) {
85
+ return serialize(value, "", 0, /* @__PURE__ */ new WeakSet());
86
+ }
87
+ function serialize(value, path, depth, stack) {
88
+ switch (typeof value) {
89
+ case "string": return JSON.stringify(value);
90
+ case "boolean": return value ? "true" : "false";
91
+ case "number":
92
+ if (Number.isNaN(value)) throw new NonJsonValueError(path, "NaN");
93
+ if (!Number.isFinite(value)) throw new NonJsonValueError(path, "Infinity");
94
+ return JSON.stringify(value);
95
+ case "bigint": throw new NonJsonValueError(path, "bigint");
96
+ case "function": throw new NonJsonValueError(path, "function");
97
+ case "symbol": throw new NonJsonValueError(path, "symbol");
98
+ case "undefined": throw new NonJsonValueError(path, "undefined");
99
+ }
100
+ if (value === null) return "null";
101
+ const object = value;
102
+ if (depth >= 64) throw new NonJsonValueError(path, "depth");
103
+ if (stack.has(object)) throw new NonJsonValueError(path, "cycle");
104
+ const isArray = Array.isArray(object);
105
+ if (!isArray) {
106
+ const proto = Object.getPrototypeOf(object);
107
+ if (proto !== Object.prototype && proto !== null) throw new NonJsonValueError(path, describe(object));
108
+ }
109
+ stack.add(object);
110
+ try {
111
+ if (isArray) {
112
+ const items = [];
113
+ for (let i = 0; i < object.length; i++) {
114
+ const itemPath = `${path}/${i}`;
115
+ if (!Object.hasOwn(object, i) || object[i] === void 0) throw new NonJsonValueError(itemPath, "undefined-in-array");
116
+ items.push(serialize(object[i], itemPath, depth + 1, stack));
117
+ }
118
+ return `[${items.join(",")}]`;
119
+ }
120
+ const record = object;
121
+ const keys = Object.keys(record).sort(compareUtf16);
122
+ const members = [];
123
+ for (const key of keys) {
124
+ const descriptor = Object.getOwnPropertyDescriptor(record, key);
125
+ if (descriptor !== void 0 && !("value" in descriptor)) throw new NonJsonValueError(appendPointer(path, key), "accessor");
126
+ const member = descriptor?.value;
127
+ if (member === void 0) continue;
128
+ members.push(`${JSON.stringify(key)}:${serialize(member, appendPointer(path, key), depth + 1, stack)}`);
129
+ }
130
+ return `{${members.join(",")}}`;
131
+ } finally {
132
+ stack.delete(object);
133
+ }
134
+ }
135
+ /** UTF-16 code-unit order (RFC 8785 §3.2.3). Never `localeCompare`. */
136
+ function compareUtf16(a, b) {
137
+ return a < b ? -1 : a > b ? 1 : 0;
138
+ }
139
+ function describe(object) {
140
+ if (object instanceof Date) return "Date";
141
+ if (object instanceof Map) return "Map";
142
+ if (object instanceof Set) return "Set";
143
+ if (object instanceof RegExp) return "RegExp";
144
+ const name = object.constructor?.name;
145
+ return typeof name === "string" && name !== "" ? `class-instance:${name}` : "class-instance";
146
+ }
147
+ // src/canonical/sha256.ts
148
+ /** SHA-256 of UTF-8 text as lowercase hex, via Web Crypto only. */
149
+ async function sha256Hex(text) {
150
+ return bytesToHex(await digest(new TextEncoder().encode(text)));
151
+ }
152
+ /** SHA-256 of raw bytes as lowercase hex. */
153
+ async function sha256HexBytes(bytes) {
154
+ return bytesToHex(await digest(bytes));
155
+ }
156
+ async function digest(bytes) {
157
+ return new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", bytes));
158
+ }
159
+ function bytesToHex(bytes) {
160
+ let out = "";
161
+ for (const byte of bytes) out += byte.toString(16).padStart(2, "0");
162
+ return out;
163
+ }
164
+ // src/canonical/hash-input.ts
165
+ /**
166
+ * Maps the caller's `instructions`, `prompt` or `messages` to a JSON value (§4.2).
167
+ * Strings get CRLF/CR → LF when `normalize` is true; bytes become `{ $bytes }`;
168
+ * `URL` becomes `{ $url }`. Anything else that is not plain JSON throws
169
+ * `DissentArgumentError('invalid-option', argument)`.
170
+ */
171
+ async function hashForm(value, normalize, argument) {
172
+ return map(value, normalize, argument, 0, /* @__PURE__ */ new WeakSet());
173
+ }
174
+ async function map(value, normalize, argument, depth, stack) {
175
+ if (typeof value === "string") return normalize ? value.replaceAll("\r\n", "\n").replaceAll("\r", "\n") : value;
176
+ if (value === null || typeof value === "boolean") return value;
177
+ if (typeof value === "number") {
178
+ if (Number.isFinite(value)) return value;
179
+ throw invalid(argument, "non-finite number");
180
+ }
181
+ if (typeof value !== "object") throw invalid(argument, typeof value);
182
+ if (value instanceof ArrayBuffer) return bytesForm(new Uint8Array(value));
183
+ if (ArrayBuffer.isView(value)) return bytesForm(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
184
+ if (value instanceof URL) return { $url: value.href };
185
+ if (depth >= 64) throw invalid(argument, "nesting too deep");
186
+ if (stack.has(value)) throw invalid(argument, "cycle");
187
+ stack.add(value);
188
+ try {
189
+ if (Array.isArray(value)) {
190
+ const out = [];
191
+ for (const item of value) out.push(await map(item, normalize, argument, depth + 1, stack));
192
+ return out;
193
+ }
194
+ const proto = Object.getPrototypeOf(value);
195
+ if (proto !== Object.prototype && proto !== null) throw invalid(argument, "non-plain object");
196
+ const out = {};
197
+ for (const key of Object.keys(value)) {
198
+ const member = value[key];
199
+ if (member === void 0) continue;
200
+ Object.defineProperty(out, key, {
201
+ value: await map(member, normalize, argument, depth + 1, stack),
202
+ enumerable: true,
203
+ writable: true,
204
+ configurable: true
205
+ });
206
+ }
207
+ return out;
208
+ } finally {
209
+ stack.delete(value);
210
+ }
211
+ }
212
+ async function bytesForm(bytes) {
213
+ return { $bytes: {
214
+ sha256: await sha256HexBytes(bytes),
215
+ length: bytes.byteLength
216
+ } };
217
+ }
218
+ function invalid(argument, what) {
219
+ return new DissentArgumentError("invalid-option", argument, `"${argument}" contains a value that cannot be hashed (${what}).`);
220
+ }
221
+ // src/compare/util.ts
222
+ function normalizeJsonZeros(value) {
223
+ if (typeof value === "number") return value === 0 ? 0 : value;
224
+ if (Array.isArray(value)) {
225
+ let changed = false;
226
+ const copy = [];
227
+ for (const orig of value) {
228
+ const norm = normalizeJsonZeros(orig);
229
+ if (!Object.is(orig, norm)) changed = true;
230
+ copy.push(norm);
231
+ }
232
+ return changed ? copy : value;
233
+ }
234
+ if (isPlainObject(value)) {
235
+ const keys = Object.keys(value);
236
+ const out = Object.create(null);
237
+ let changed = false;
238
+ for (const k of keys) {
239
+ const orig = ownValue(value, k);
240
+ if (orig === void 0) {
241
+ changed = true;
242
+ continue;
243
+ }
244
+ const norm = normalizeJsonZeros(orig);
245
+ if (!Object.is(orig, norm)) changed = true;
246
+ Object.defineProperty(out, k, {
247
+ value: norm,
248
+ enumerable: true,
249
+ writable: true,
250
+ configurable: true
251
+ });
252
+ }
253
+ return changed ? out : value;
254
+ }
255
+ return value;
256
+ }
257
+ function isPlainObject(value) {
258
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
259
+ const proto = Object.getPrototypeOf(value);
260
+ return proto === Object.prototype || proto === null;
261
+ }
262
+ function sortWith(items, cmp) {
263
+ return items.slice().sort(cmp);
264
+ }
265
+ function sortLabels(labels) {
266
+ return sortWith(labels, compareUtf16);
267
+ }
268
+ function ownValue(obj, key) {
269
+ return Object.getOwnPropertyDescriptor(obj, key)?.value;
270
+ }
271
+ function toSortedNullProtoRecord(entries) {
272
+ const sorted = sortWith(entries, (a, b) => compareUtf16(a[0], b[0]));
273
+ const out = Object.create(null);
274
+ for (const [key, value] of sorted) Object.defineProperty(out, key, {
275
+ value,
276
+ enumerable: true,
277
+ writable: true,
278
+ configurable: true
279
+ });
280
+ return out;
281
+ }
282
+ // src/compare/tolerance.ts
283
+ /**
284
+ * Checks whether two finite numbers lie within the combined tolerance bound:
285
+ * `|a - b| <= (absolute ?? 0) + (relative ?? 0) * max(|a|, |b|)`.
286
+ */
287
+ function withinTolerance(a, b, tolerance) {
288
+ const abs = tolerance.absolute ?? 0;
289
+ const rel = tolerance.relative ?? 0;
290
+ return Math.abs(a - b) <= abs + rel * Math.max(Math.abs(a), Math.abs(b));
291
+ }
292
+ function normalizeNumber(n) {
293
+ return n === 0 ? 0 : n;
294
+ }
295
+ /**
296
+ * Evaluates a `tolerance` field comparison over already-extracted presenters.
297
+ */
298
+ function compareTolerance(params) {
299
+ const { answered, presented, missing, nulls, presentValues, tolerance } = params;
300
+ const byNumber = /* @__PURE__ */ new Map();
301
+ const nullWitnesses = [];
302
+ for (const entry of presentValues) if (entry.value === null) nullWitnesses.push(entry.witness);
303
+ else if (typeof entry.value === "number" && Number.isFinite(entry.value)) {
304
+ const val = normalizeNumber(entry.value);
305
+ const list = byNumber.get(val);
306
+ if (list === void 0) byNumber.set(val, [entry.witness]);
307
+ else list.push(entry.witness);
308
+ }
309
+ const distinctNumbers = sortWith(Array.from(byNumber.keys()), (a, b) => a - b);
310
+ const groups = [];
311
+ if (distinctNumbers.length > 0) {
312
+ let currentValues = [];
313
+ let currentMin = distinctNumbers[0];
314
+ let currentMax = distinctNumbers[0];
315
+ let currentSupport = 0;
316
+ for (let i = 0; i < distinctNumbers.length; i++) {
317
+ const val = distinctNumbers[i];
318
+ const witnesses = sortLabels(byNumber.get(val));
319
+ const valueGroup = {
320
+ value: val,
321
+ witnesses,
322
+ support: witnesses.length
323
+ };
324
+ if (i === 0) {
325
+ currentValues = [valueGroup];
326
+ currentMin = val;
327
+ currentMax = val;
328
+ currentSupport = witnesses.length;
329
+ } else if (withinTolerance(distinctNumbers[i - 1], val, tolerance)) {
330
+ currentValues.push(valueGroup);
331
+ currentMax = val;
332
+ currentSupport += witnesses.length;
333
+ } else {
334
+ groups.push({
335
+ min: currentMin,
336
+ max: currentMax,
337
+ values: currentValues,
338
+ support: currentSupport
339
+ });
340
+ currentValues = [valueGroup];
341
+ currentMin = val;
342
+ currentMax = val;
343
+ currentSupport = witnesses.length;
344
+ }
345
+ }
346
+ groups.push({
347
+ min: currentMin,
348
+ max: currentMax,
349
+ values: currentValues,
350
+ support: currentSupport
351
+ });
352
+ }
353
+ let allPairsWithin = true;
354
+ for (let i = 0; i < distinctNumbers.length && allPairsWithin; i++) for (let j = i + 1; j < distinctNumbers.length; j++) if (!withinTolerance(distinctNumbers[i], distinctNumbers[j], tolerance)) {
355
+ allPairsWithin = false;
356
+ break;
357
+ }
358
+ let status;
359
+ if (presented.length < 2) status = "insufficient";
360
+ else if (nullWitnesses.length === 0) status = allPairsWithin ? "agree" : "split";
361
+ else if (distinctNumbers.length === 0) status = "agree";
362
+ else status = "split";
363
+ const out = {
364
+ comparator: "tolerance",
365
+ status,
366
+ answered,
367
+ presented,
368
+ missing,
369
+ nulls,
370
+ tolerance,
371
+ groups
372
+ };
373
+ if (distinctNumbers.length > 0) {
374
+ const min = distinctNumbers[0];
375
+ const max = distinctNumbers[distinctNumbers.length - 1];
376
+ out.min = min;
377
+ out.max = max;
378
+ out.spread = normalizeNumber(max - min);
379
+ }
380
+ if (nullWitnesses.length > 0) {
381
+ const sortedNullWitnesses = sortLabels(nullWitnesses);
382
+ out.nullGroup = {
383
+ witnesses: sortedNullWitnesses,
384
+ support: sortedNullWitnesses.length
385
+ };
386
+ }
387
+ return out;
388
+ }
389
+ // src/compare/compare-fields.ts
390
+ /**
391
+ * Reads a value at an RFC 6901 JSON Pointer using `Object.hasOwn` at every
392
+ * step. Intermediate non-objects (including `null` or arrays) make descendants
393
+ * missing rather than throwing or reading prototype keys.
394
+ */
395
+ function readByPointer(root, pointer) {
396
+ if (pointer === "") return {
397
+ present: true,
398
+ value: root
399
+ };
400
+ let cur = root;
401
+ for (const seg of parsePointer(pointer)) {
402
+ if (!isPlainObject(cur) || !Object.hasOwn(cur, seg)) return { present: false };
403
+ const next = ownValue(cur, seg);
404
+ if (next === void 0) return { present: false };
405
+ cur = next;
406
+ }
407
+ return {
408
+ present: true,
409
+ value: cur
410
+ };
411
+ }
412
+ function extractPresence(outputs, pointer) {
413
+ const presented = [];
414
+ const missing = [];
415
+ const nulls = [];
416
+ const presentValues = [];
417
+ for (const entry of outputs) {
418
+ const read = readByPointer(entry.output, pointer);
419
+ if (!read.present) {
420
+ missing.push(entry.witness);
421
+ continue;
422
+ }
423
+ const value = normalizeJsonZeros(read.value);
424
+ presented.push(entry.witness);
425
+ if (value === null) nulls.push(entry.witness);
426
+ presentValues.push({
427
+ witness: entry.witness,
428
+ value
429
+ });
430
+ }
431
+ return {
432
+ presented: sortLabels(presented),
433
+ missing: sortLabels(missing),
434
+ nulls: sortLabels(nulls),
435
+ presentValues: sortWith(presentValues, (a, b) => compareUtf16(a.witness, b.witness))
436
+ };
437
+ }
438
+ function buildExactGroups(presentValues) {
439
+ const byCanon = /* @__PURE__ */ new Map();
440
+ for (const entry of presentValues) {
441
+ const key = canonicalJson(entry.value);
442
+ const existing = byCanon.get(key);
443
+ if (existing === void 0) byCanon.set(key, {
444
+ value: entry.value,
445
+ witnesses: [entry.witness]
446
+ });
447
+ else existing.witnesses.push(entry.witness);
448
+ }
449
+ return sortLabels(Array.from(byCanon.keys())).map((k) => {
450
+ const entry = byCanon.get(k);
451
+ const witnesses = sortLabels(entry.witnesses);
452
+ return {
453
+ value: entry.value,
454
+ witnesses,
455
+ support: witnesses.length
456
+ };
457
+ });
458
+ }
459
+ function compareExact(answered, presence) {
460
+ const groups = buildExactGroups(presence.presentValues);
461
+ return {
462
+ comparator: "exact",
463
+ status: presence.presented.length < 2 ? "insufficient" : groups.length === 1 ? "agree" : "split",
464
+ answered,
465
+ presented: presence.presented,
466
+ missing: presence.missing,
467
+ nulls: presence.nulls,
468
+ groups
469
+ };
470
+ }
471
+ function computeSetCore(nonNullArrays, nonArrayCount = 0) {
472
+ const itemMap = /* @__PURE__ */ new Map();
473
+ const duplicates = [];
474
+ for (const entry of nonNullArrays) {
475
+ const seen = /* @__PURE__ */ new Set();
476
+ let hadDup = false;
477
+ for (const rawItem of entry.values) {
478
+ const item = normalizeJsonZeros(rawItem);
479
+ const key = canonicalJson(item);
480
+ if (seen.has(key)) {
481
+ hadDup = true;
482
+ continue;
483
+ }
484
+ seen.add(key);
485
+ const existing = itemMap.get(key);
486
+ if (existing === void 0) itemMap.set(key, {
487
+ item,
488
+ witnesses: [entry.witness]
489
+ });
490
+ else existing.witnesses.push(entry.witness);
491
+ }
492
+ if (hadDup) duplicates.push(entry.witness);
493
+ }
494
+ const nonNullCount = nonNullArrays.length + nonArrayCount;
495
+ const sortedKeys = sortLabels(Array.from(itemMap.keys()));
496
+ const union = [];
497
+ const intersection = [];
498
+ const items = [];
499
+ for (const key of sortedKeys) {
500
+ const entry = itemMap.get(key);
501
+ const witnesses = sortLabels(entry.witnesses);
502
+ union.push(entry.item);
503
+ if (nonNullCount > 0 && witnesses.length === nonNullCount) intersection.push(entry.item);
504
+ items.push({
505
+ item: entry.item,
506
+ witnesses,
507
+ support: witnesses.length
508
+ });
509
+ }
510
+ const out = {
511
+ union,
512
+ intersection,
513
+ items,
514
+ duplicates: sortLabels(duplicates)
515
+ };
516
+ if (nonNullCount >= 2) out.jaccard = nonArrayCount > 0 ? 0 : union.length === 0 ? 1 : intersection.length / union.length;
517
+ return out;
518
+ }
519
+ function compareSet(answered, presence) {
520
+ const nonNullArrays = [];
521
+ let nonArrayCount = 0;
522
+ for (const entry of presence.presentValues) {
523
+ if (entry.value === null) continue;
524
+ if (Array.isArray(entry.value)) nonNullArrays.push({
525
+ witness: entry.witness,
526
+ values: entry.value
527
+ });
528
+ else nonArrayCount += 1;
529
+ }
530
+ const core = computeSetCore(nonNullArrays, nonArrayCount);
531
+ const nullCount = presence.nulls.length;
532
+ let status;
533
+ if (presence.presented.length < 2) status = "insufficient";
534
+ else if (nonArrayCount > 0) status = "split";
535
+ else if (nullCount === presence.presented.length) status = "agree";
536
+ else if (nullCount > 0) status = "split";
537
+ else if (core.intersection.length === core.union.length) status = "agree";
538
+ else status = "split";
539
+ const out = {
540
+ comparator: "set",
541
+ status,
542
+ answered,
543
+ presented: presence.presented,
544
+ missing: presence.missing,
545
+ nulls: presence.nulls,
546
+ union: core.union,
547
+ intersection: core.intersection,
548
+ items: core.items,
549
+ duplicates: core.duplicates
550
+ };
551
+ if (core.jaccard !== void 0) out.jaccard = core.jaccard;
552
+ return out;
553
+ }
554
+ function compareNotCompared(plan, answered, presence) {
555
+ return {
556
+ comparator: "none",
557
+ status: "not-compared",
558
+ reason: plan.reason,
559
+ detail: plan.detail,
560
+ answered,
561
+ presented: presence.presented,
562
+ missing: presence.missing,
563
+ nulls: presence.nulls,
564
+ values: presence.presentValues.map((entry) => ({
565
+ witness: entry.witness,
566
+ value: entry.value
567
+ }))
568
+ };
569
+ }
570
+ function compareLeaf(plan, pointer, outputs) {
571
+ const answered = outputs.length;
572
+ const presence = extractPresence(outputs, pointer);
573
+ switch (plan.comparator) {
574
+ case "exact": return compareExact(answered, presence);
575
+ case "tolerance": return compareTolerance({
576
+ answered,
577
+ presented: presence.presented,
578
+ missing: presence.missing,
579
+ nulls: presence.nulls,
580
+ presentValues: presence.presentValues,
581
+ tolerance: plan.tolerance
582
+ });
583
+ case "set": return compareSet(answered, presence);
584
+ case "none": return compareNotCompared(plan, answered, presence);
585
+ }
586
+ }
587
+ function compareKeyedSet(plan, pointer, outputs) {
588
+ const answered = outputs.length;
589
+ const presence = extractPresence(outputs, pointer);
590
+ const duplicateKeyWitnesses = [];
591
+ let nonArrayCount = 0;
592
+ const witnessMaps = /* @__PURE__ */ new Map();
593
+ const keyRegistry = /* @__PURE__ */ new Map();
594
+ const keySetArrays = [];
595
+ for (const entry of presence.presentValues) {
596
+ if (entry.value === null) continue;
597
+ if (!Array.isArray(entry.value)) {
598
+ nonArrayCount += 1;
599
+ continue;
600
+ }
601
+ const wMap = /* @__PURE__ */ new Map();
602
+ const wKeys = [];
603
+ let failed = false;
604
+ for (const rawItem of entry.value) {
605
+ if (!isPlainObject(rawItem) || !Object.hasOwn(rawItem, plan.key)) {
606
+ failed = true;
607
+ break;
608
+ }
609
+ const rawKeyVal = ownValue(rawItem, plan.key);
610
+ if (rawKeyVal === void 0) {
611
+ failed = true;
612
+ break;
613
+ }
614
+ const keyVal = normalizeJsonZeros(rawKeyVal);
615
+ const canonKey = canonicalJson(keyVal);
616
+ if (wMap.has(canonKey)) {
617
+ failed = true;
618
+ break;
619
+ }
620
+ const normItem = normalizeJsonZeros(rawItem);
621
+ wMap.set(canonKey, {
622
+ keyValue: keyVal,
623
+ item: normItem
624
+ });
625
+ wKeys.push(keyVal);
626
+ }
627
+ if (failed) duplicateKeyWitnesses.push(entry.witness);
628
+ else {
629
+ witnessMaps.set(entry.witness, wMap);
630
+ keySetArrays.push({
631
+ witness: entry.witness,
632
+ values: wKeys
633
+ });
634
+ }
635
+ }
636
+ if (duplicateKeyWitnesses.length > 0) return {
637
+ comparator: "none",
638
+ status: "not-compared",
639
+ reason: "duplicate-key",
640
+ detail: "duplicate-key",
641
+ answered,
642
+ presented: presence.presented,
643
+ missing: presence.missing,
644
+ nulls: presence.nulls,
645
+ values: presence.presentValues.map((entry) => ({
646
+ witness: entry.witness,
647
+ value: entry.value
648
+ })),
649
+ duplicateKeyWitnesses: sortLabels(duplicateKeyWitnesses)
650
+ };
651
+ for (const [witness, wMap] of witnessMaps) for (const [canonKey, info] of wMap) {
652
+ const existing = keyRegistry.get(canonKey);
653
+ if (existing === void 0) keyRegistry.set(canonKey, {
654
+ keyValue: info.keyValue,
655
+ entries: [{
656
+ witness,
657
+ output: info.item
658
+ }]
659
+ });
660
+ else existing.entries.push({
661
+ witness,
662
+ output: info.item
663
+ });
664
+ }
665
+ const keysCore = computeSetCore(keySetArrays, nonArrayCount);
666
+ const keysResult = {
667
+ union: keysCore.union,
668
+ intersection: keysCore.intersection,
669
+ items: keysCore.items
670
+ };
671
+ if (keysCore.jaccard !== void 0) keysResult.jaccard = keysCore.jaccard;
672
+ const sortedItemFieldKeys = sortLabels(Object.keys(plan.itemFields));
673
+ const sortedKeyCanon = sortLabels(Array.from(keyRegistry.keys()));
674
+ let anyItemFieldSplit = false;
675
+ const items = [];
676
+ for (const canonKey of sortedKeyCanon) {
677
+ const reg = keyRegistry.get(canonKey);
678
+ const sortedEntries = sortWith(reg.entries, (a, b) => compareUtf16(a.witness, b.witness));
679
+ const witnesses = sortedEntries.map((e) => e.witness);
680
+ const fieldEntries = [];
681
+ for (const subpath of sortedItemFieldKeys) {
682
+ const leafRes = compareLeaf(ownValue(plan.itemFields, subpath), subpath, sortedEntries);
683
+ if (leafRes.status === "split") anyItemFieldSplit = true;
684
+ fieldEntries.push([subpath, leafRes]);
685
+ }
686
+ items.push({
687
+ key: reg.keyValue,
688
+ witnesses,
689
+ fields: toSortedNullProtoRecord(fieldEntries)
690
+ });
691
+ }
692
+ let status;
693
+ if (presence.presented.length < 2) status = "insufficient";
694
+ else if (nonArrayCount > 0) status = "split";
695
+ else if (presence.nulls.length === presence.presented.length) status = "agree";
696
+ else if (presence.nulls.length > 0) status = "split";
697
+ else if (keysCore.intersection.length === keysCore.union.length && !anyItemFieldSplit) status = "agree";
698
+ else status = "split";
699
+ return {
700
+ comparator: "keyed-set",
701
+ status,
702
+ answered,
703
+ presented: presence.presented,
704
+ missing: presence.missing,
705
+ nulls: presence.nulls,
706
+ key: plan.key,
707
+ keys: keysResult,
708
+ items
709
+ };
710
+ }
711
+ function compareDiscriminatedUnion(plan, pointer, outputs) {
712
+ const answered = outputs.length;
713
+ const presence = extractPresence(outputs, pointer);
714
+ const choicePresented = [];
715
+ const choiceMissing = [];
716
+ const choiceNulls = [];
717
+ const choicePresentValues = [];
718
+ const branchBuckets = /* @__PURE__ */ new Map();
719
+ for (const entry of presence.presentValues) {
720
+ if (entry.value === null) {
721
+ choicePresented.push(entry.witness);
722
+ choiceNulls.push(entry.witness);
723
+ choicePresentValues.push({
724
+ witness: entry.witness,
725
+ value: null
726
+ });
727
+ continue;
728
+ }
729
+ if (!isPlainObject(entry.value) || !Object.hasOwn(entry.value, plan.discriminator)) {
730
+ choiceMissing.push(entry.witness);
731
+ continue;
732
+ }
733
+ const rawDisc = ownValue(entry.value, plan.discriminator);
734
+ if (rawDisc === void 0) {
735
+ choiceMissing.push(entry.witness);
736
+ continue;
737
+ }
738
+ const discVal = normalizeJsonZeros(rawDisc);
739
+ choicePresented.push(entry.witness);
740
+ if (discVal === null) choiceNulls.push(entry.witness);
741
+ choicePresentValues.push({
742
+ witness: entry.witness,
743
+ value: discVal
744
+ });
745
+ const canonDisc = canonicalJson(discVal);
746
+ if (Object.hasOwn(plan.branches, canonDisc)) {
747
+ const bucket = branchBuckets.get(canonDisc);
748
+ if (bucket === void 0) branchBuckets.set(canonDisc, {
749
+ discValue: discVal,
750
+ entries: [{
751
+ witness: entry.witness,
752
+ output: entry.value
753
+ }]
754
+ });
755
+ else bucket.entries.push({
756
+ witness: entry.witness,
757
+ output: entry.value
758
+ });
759
+ }
760
+ }
761
+ const choice = compareExact(presence.presented.length, {
762
+ presented: sortLabels(choicePresented),
763
+ missing: sortLabels(choiceMissing),
764
+ nulls: sortLabels(choiceNulls),
765
+ presentValues: sortWith(choicePresentValues, (a, b) => compareUtf16(a.witness, b.witness))
766
+ });
767
+ const branches = [];
768
+ let anyBranchFieldSplit = false;
769
+ for (const canonKey of sortLabels(Array.from(branchBuckets.keys()))) {
770
+ const bucket = branchBuckets.get(canonKey);
771
+ const sortedEntries = sortWith(bucket.entries, (a, b) => compareUtf16(a.witness, b.witness));
772
+ const branchPlan = ownValue(plan.branches, canonKey);
773
+ const fieldEntries = [];
774
+ for (const subpath of sortLabels(Object.keys(branchPlan))) {
775
+ const leafRes = compareLeaf(ownValue(branchPlan, subpath), subpath, sortedEntries);
776
+ if (leafRes.status === "split") anyBranchFieldSplit = true;
777
+ fieldEntries.push([subpath, leafRes]);
778
+ }
779
+ branches.push({
780
+ value: bucket.discValue,
781
+ witnesses: sortedEntries.map((e) => e.witness),
782
+ fields: toSortedNullProtoRecord(fieldEntries)
783
+ });
784
+ }
785
+ let status;
786
+ if (presence.presented.length < 2 || choice.status === "insufficient") status = "insufficient";
787
+ else if (choice.status === "agree" && !anyBranchFieldSplit) status = "agree";
788
+ else status = "split";
789
+ return {
790
+ comparator: "discriminated-union",
791
+ status,
792
+ answered,
793
+ presented: presence.presented,
794
+ missing: presence.missing,
795
+ nulls: presence.nulls,
796
+ discriminator: plan.discriminator,
797
+ choice,
798
+ branches
799
+ };
800
+ }
801
+ function normalizeOutputs(answeredOutputs) {
802
+ return sortWith(Array.isArray(answeredOutputs) ? [...answeredOutputs] : Object.keys(answeredOutputs).map((witness) => ({
803
+ witness,
804
+ output: ownValue(answeredOutputs, witness)
805
+ })), (a, b) => compareUtf16(a.witness, b.witness));
806
+ }
807
+ /**
808
+ * Pure Layer B field comparison over answered witness outputs.
809
+ * Every answering witness participates (I2) and insertion order never affects output (I3).
810
+ */
811
+ function compareFields(planFields, answeredOutputs) {
812
+ const outputs = normalizeOutputs(answeredOutputs);
813
+ const resultEntries = [];
814
+ for (const path of sortLabels(Object.keys(planFields))) {
815
+ const plan = ownValue(planFields, path);
816
+ let res;
817
+ switch (plan.comparator) {
818
+ case "exact":
819
+ case "tolerance":
820
+ case "set":
821
+ case "none":
822
+ res = compareLeaf(plan, path, outputs);
823
+ break;
824
+ case "keyed-set":
825
+ res = compareKeyedSet(plan, path, outputs);
826
+ break;
827
+ case "discriminated-union": res = compareDiscriminatedUnion(plan, path, outputs);
828
+ }
829
+ resultEntries.push([path, res]);
830
+ }
831
+ return toSortedNullProtoRecord(resultEntries);
832
+ }
833
+ // src/compare/coverage.ts
834
+ function bumpReason(counts, key) {
835
+ counts.set(key, (counts.get(key) ?? 0) + 1);
836
+ }
837
+ /**
838
+ * Computes schema coverage over every plan entry at all depths (§9.3).
839
+ */
840
+ function computeCoverage(planFields, fieldResults) {
841
+ let compared = 0;
842
+ let notComparedByPolicy = 0;
843
+ let unsupported = 0;
844
+ let failedAtRuntime = 0;
845
+ const reasonCounts = /* @__PURE__ */ new Map();
846
+ function countLeaf(plan, underFailedKeyedSet = false) {
847
+ if (plan.comparator === "none") {
848
+ if (plan.reason === "policy") notComparedByPolicy += 1;
849
+ else unsupported += 1;
850
+ bumpReason(reasonCounts, plan.detail);
851
+ } else if (underFailedKeyedSet) {
852
+ failedAtRuntime += 1;
853
+ bumpReason(reasonCounts, "duplicate-key");
854
+ } else compared += 1;
855
+ }
856
+ for (const path of Object.keys(planFields)) {
857
+ const plan = ownValue(planFields, path);
858
+ if (plan.comparator === "keyed-set") {
859
+ const result = ownValue(fieldResults, path);
860
+ const isDupKey = result !== void 0 && result.comparator === "none" && result.reason === "duplicate-key";
861
+ if (isDupKey) {
862
+ failedAtRuntime += 1;
863
+ bumpReason(reasonCounts, "duplicate-key");
864
+ } else compared += 1;
865
+ for (const subpath of Object.keys(plan.itemFields)) countLeaf(ownValue(plan.itemFields, subpath), isDupKey);
866
+ } else if (plan.comparator === "discriminated-union") {
867
+ compared += 1;
868
+ for (const branchKey of Object.keys(plan.branches)) {
869
+ const branchLeaves = ownValue(plan.branches, branchKey);
870
+ for (const subpath of Object.keys(branchLeaves)) countLeaf(ownValue(branchLeaves, subpath), false);
871
+ }
872
+ } else countLeaf(plan, false);
873
+ }
874
+ const fields = compared + notComparedByPolicy + unsupported + failedAtRuntime;
875
+ const denom = fields - notComparedByPolicy;
876
+ const ratio = denom === 0 ? 1 : compared / denom;
877
+ return {
878
+ fields,
879
+ compared,
880
+ notComparedByPolicy,
881
+ unsupported,
882
+ failedAtRuntime,
883
+ ratio,
884
+ byReason: toSortedNullProtoRecord(Array.from(reasonCounts.entries()))
885
+ };
886
+ }
887
+ const IGNORED_KEYWORDS = /* @__PURE__ */ new Set([
888
+ "title",
889
+ "description",
890
+ "default",
891
+ "examples",
892
+ "format",
893
+ "pattern",
894
+ "minLength",
895
+ "maxLength",
896
+ "minimum",
897
+ "maximum",
898
+ "exclusiveMinimum",
899
+ "exclusiveMaximum",
900
+ "multipleOf",
901
+ "minItems",
902
+ "maxItems",
903
+ "uniqueItems",
904
+ "$schema",
905
+ "$id",
906
+ "$comment",
907
+ "readOnly",
908
+ "writeOnly",
909
+ "deprecated",
910
+ "propertyNames",
911
+ "additionalProperties"
912
+ ]);
913
+ function addReason(reasons, reason) {
914
+ return reasons.includes(reason) ? reasons : [...reasons, reason];
915
+ }
916
+ function withReason(ctx, reason) {
917
+ return {
918
+ ...ctx,
919
+ reasons: addReason(ctx.reasons, reason)
920
+ };
921
+ }
922
+ function withNullable(ctx) {
923
+ return {
924
+ ...ctx,
925
+ reasons: addReason(ctx.reasons, "nullable-unwrap"),
926
+ nullable: true
927
+ };
928
+ }
929
+ function buildLeaf(plan, primitiveType, isBooleanEnumConst, resolvedSchema) {
930
+ const leaf = {
931
+ kind: "leaf",
932
+ plan,
933
+ primitiveType,
934
+ isBooleanEnumConst
935
+ };
936
+ if (resolvedSchema !== void 0) leaf.resolvedSchema = resolvedSchema;
937
+ return leaf;
938
+ }
939
+ function makeUnsupported(ctx, detail, resolvedSchema) {
940
+ return buildLeaf({
941
+ comparator: "none",
942
+ reason: "unsupported",
943
+ detail,
944
+ reasons: addReason(ctx.reasons, "unsupported"),
945
+ nullable: ctx.nullable
946
+ }, "other", false, resolvedSchema);
947
+ }
948
+ function makePolicy(ctx, detail, primitiveType, resolvedSchema) {
949
+ return buildLeaf({
950
+ comparator: "none",
951
+ reason: "policy",
952
+ detail,
953
+ reasons: addReason(ctx.reasons, "policy"),
954
+ nullable: ctx.nullable
955
+ }, primitiveType, false, resolvedSchema);
956
+ }
957
+ function makeExact(ctx, opts) {
958
+ return buildLeaf({
959
+ comparator: "exact",
960
+ onSplit: opts.onSplit,
961
+ reasons: addReason(ctx.reasons, "default-by-type"),
962
+ nullable: ctx.nullable
963
+ }, opts.primitiveType, opts.isBooleanEnumConst ?? false, opts.resolvedSchema);
964
+ }
965
+ function resolvePointerInRoot(root, ref) {
966
+ if (!ref.startsWith("#")) return {
967
+ ok: false,
968
+ detail: "external-ref"
969
+ };
970
+ if (ref === "#") return {
971
+ ok: true,
972
+ target: root
973
+ };
974
+ if (!ref.startsWith("#/")) return {
975
+ ok: false,
976
+ detail: "invalid-ref"
977
+ };
978
+ let tokens;
979
+ try {
980
+ tokens = parsePointer(ref.slice(1));
981
+ } catch {
982
+ return {
983
+ ok: false,
984
+ detail: "invalid-ref"
985
+ };
986
+ }
987
+ let curr = root;
988
+ for (const token of tokens) {
989
+ if (curr === null || typeof curr !== "object") return {
990
+ ok: false,
991
+ detail: "invalid-ref"
992
+ };
993
+ if (Array.isArray(curr)) {
994
+ const idx = Number(token);
995
+ if (!Number.isInteger(idx) || idx < 0 || idx >= curr.length || !Object.hasOwn(curr, idx)) return {
996
+ ok: false,
997
+ detail: "invalid-ref"
998
+ };
999
+ curr = curr[idx];
1000
+ } else {
1001
+ if (!Object.hasOwn(curr, token)) return {
1002
+ ok: false,
1003
+ detail: "invalid-ref"
1004
+ };
1005
+ curr = ownValue(curr, token);
1006
+ }
1007
+ }
1008
+ if (typeof curr !== "boolean" && !isPlainObject(curr)) return {
1009
+ ok: false,
1010
+ detail: "invalid-ref"
1011
+ };
1012
+ return {
1013
+ ok: true,
1014
+ target: curr
1015
+ };
1016
+ }
1017
+ function resolveSimpleRef(node, ctx) {
1018
+ let curr = node;
1019
+ let depth = ctx.depth;
1020
+ const refStack = new Set(ctx.refStack);
1021
+ while (isPlainObject(curr) && typeof curr.$ref === "string") {
1022
+ if (refStack.has(curr.$ref)) return {
1023
+ ok: false,
1024
+ detail: "ref-cycle"
1025
+ };
1026
+ const res = resolvePointerInRoot(ctx.root, curr.$ref);
1027
+ if (!res.ok) return res;
1028
+ depth++;
1029
+ if (depth > 16) return {
1030
+ ok: false,
1031
+ detail: "depth-exceeded"
1032
+ };
1033
+ refStack.add(curr.$ref);
1034
+ curr = res.target;
1035
+ }
1036
+ return {
1037
+ ok: true,
1038
+ schema: curr,
1039
+ depth,
1040
+ refStack
1041
+ };
1042
+ }
1043
+ function isNullSchema(node, ctx) {
1044
+ const res = resolveSimpleRef(node, ctx);
1045
+ if (!res.ok || !isPlainObject(res.schema)) return false;
1046
+ const s = res.schema;
1047
+ if (s.type !== "null") return false;
1048
+ for (const key of [
1049
+ "properties",
1050
+ "items",
1051
+ "prefixItems",
1052
+ "anyOf",
1053
+ "oneOf",
1054
+ "allOf",
1055
+ "not",
1056
+ "if",
1057
+ "enum",
1058
+ "const"
1059
+ ]) if (Object.hasOwn(s, key)) return false;
1060
+ return true;
1061
+ }
1062
+ function extractLiteral(propSchema, ctx) {
1063
+ const resolved = resolveSimpleRef(propSchema, ctx);
1064
+ if (!resolved.ok || !isPlainObject(resolved.schema)) return { ok: false };
1065
+ const s = resolved.schema;
1066
+ for (const key of Object.keys(s)) {
1067
+ if (key === "type" || key === "const" || key === "enum" || IGNORED_KEYWORDS.has(key)) continue;
1068
+ return { ok: false };
1069
+ }
1070
+ let candidate;
1071
+ if (Object.hasOwn(s, "const") && s.const !== void 0) {
1072
+ if (Array.isArray(s.enum)) {
1073
+ if (s.enum.length !== 1) return { ok: false };
1074
+ try {
1075
+ if (canonicalJson(s.enum[0]) !== canonicalJson(s.const)) return { ok: false };
1076
+ } catch {
1077
+ return { ok: false };
1078
+ }
1079
+ }
1080
+ candidate = s.const;
1081
+ } else if (Array.isArray(s.enum) && s.enum.length === 1) candidate = s.enum[0];
1082
+ else return { ok: false };
1083
+ try {
1084
+ canonicalJson(candidate);
1085
+ return {
1086
+ ok: true,
1087
+ value: candidate
1088
+ };
1089
+ } catch {
1090
+ return { ok: false };
1091
+ }
1092
+ }
1093
+ function walkSchema(rootSchema) {
1094
+ let rootNode = rootSchema;
1095
+ let depth = 0;
1096
+ const refStack = /* @__PURE__ */ new Set();
1097
+ let reasons = [];
1098
+ while (isPlainObject(rootNode) && typeof rootNode.$ref === "string") {
1099
+ if (refStack.has(rootNode.$ref)) throw new DissentArgumentError("schema-root-not-object", "schema");
1100
+ const res = resolvePointerInRoot(rootSchema, rootNode.$ref);
1101
+ if (!res.ok || ++depth > 16) throw new DissentArgumentError("schema-root-not-object", "schema");
1102
+ refStack.add(rootNode.$ref);
1103
+ reasons = addReason(reasons, "ref-resolved");
1104
+ rootNode = res.target;
1105
+ }
1106
+ if (!isPlainObject(rootNode) || rootNode.type !== "object" || !isPlainObject(rootNode.properties)) throw new DissentArgumentError("schema-root-not-object", "schema");
1107
+ return walkObject(rootNode, {
1108
+ root: rootSchema,
1109
+ depth,
1110
+ refStack,
1111
+ reasons,
1112
+ nullable: false
1113
+ });
1114
+ }
1115
+ function walkUnionNode(unionBranchesRaw, node, ctx) {
1116
+ const nonNullBranches = unionBranchesRaw.filter((b) => !isNullSchema(b, ctx));
1117
+ const nextCtx = nonNullBranches.length < unionBranchesRaw.length ? withNullable(ctx) : ctx;
1118
+ if (nonNullBranches.length === 0) return makeExact({
1119
+ ...nextCtx,
1120
+ nullable: true
1121
+ }, {
1122
+ onSplit: "warn",
1123
+ primitiveType: "null",
1124
+ resolvedSchema: node
1125
+ });
1126
+ if (nonNullBranches.length === 1) return walkNode(nonNullBranches[0], nextCtx);
1127
+ return walkUnion(nonNullBranches, node, nextCtx);
1128
+ }
1129
+ function walkNode(node, ctx) {
1130
+ if (isPlainObject(node) && typeof node.$ref === "string") {
1131
+ const ref = node.$ref;
1132
+ if (ctx.refStack.has(ref)) return makeUnsupported(ctx, "ref-cycle", node);
1133
+ const resolved = resolvePointerInRoot(ctx.root, ref);
1134
+ if (!resolved.ok) return makeUnsupported(ctx, resolved.detail, node);
1135
+ const nextDepth = ctx.depth + 1;
1136
+ if (nextDepth > 16) return makeUnsupported(ctx, "depth-exceeded", node);
1137
+ const nextRefs = new Set(ctx.refStack);
1138
+ nextRefs.add(ref);
1139
+ return walkNode(resolved.target, {
1140
+ ...withReason(ctx, "ref-resolved"),
1141
+ depth: nextDepth,
1142
+ refStack: nextRefs
1143
+ });
1144
+ }
1145
+ if (ctx.depth > 16) return makeUnsupported(ctx, "depth-exceeded", isPlainObject(node) ? node : void 0);
1146
+ if (typeof node === "boolean" || !isPlainObject(node)) return makeUnsupported(ctx, "untyped");
1147
+ if (Array.isArray(node.type)) {
1148
+ const types = node.type;
1149
+ if (types.includes("null")) {
1150
+ const nonNull = types.filter((t) => t !== "null");
1151
+ const unwrappedCtx = withNullable(ctx);
1152
+ if (nonNull.length === 0) return walkNode({
1153
+ ...node,
1154
+ type: "null"
1155
+ }, unwrappedCtx);
1156
+ if (nonNull.length === 1) return walkNode({
1157
+ ...node,
1158
+ type: nonNull[0]
1159
+ }, unwrappedCtx);
1160
+ return makeUnsupported(unwrappedCtx, "multi-type", node);
1161
+ }
1162
+ if (types.length === 1) return walkNode({
1163
+ ...node,
1164
+ type: types[0]
1165
+ }, ctx);
1166
+ return makeUnsupported(ctx, types.length > 1 ? "multi-type" : "untyped", node);
1167
+ }
1168
+ const hasAnyOf = Array.isArray(node.anyOf);
1169
+ const hasOneOf = Array.isArray(node.oneOf);
1170
+ if (hasAnyOf && hasOneOf) return makeUnsupported(ctx, "union", node);
1171
+ const unionBranchesRaw = hasAnyOf ? node.anyOf : hasOneOf ? node.oneOf : null;
1172
+ if (unionBranchesRaw !== null) return walkUnionNode(unionBranchesRaw, node, ctx);
1173
+ if (Array.isArray(node.allOf)) return makeUnsupported(ctx, "all-of", node);
1174
+ if (Object.hasOwn(node, "if") || Object.hasOwn(node, "then") || Object.hasOwn(node, "else")) return makeUnsupported(ctx, "conditional", node);
1175
+ if (Object.hasOwn(node, "not")) return makeUnsupported(ctx, "not", node);
1176
+ if (Object.hasOwn(node, "const") && node.const !== void 0 || Array.isArray(node.enum)) return makeExact(ctx, {
1177
+ onSplit: "critical",
1178
+ primitiveType: node.type === "integer" || node.type === "number" || node.type === "string" || node.type === "boolean" || node.type === "null" ? node.type : "other",
1179
+ isBooleanEnumConst: true,
1180
+ resolvedSchema: node
1181
+ });
1182
+ if (typeof node.type === "string") switch (node.type) {
1183
+ case "boolean": return makeExact(ctx, {
1184
+ onSplit: "critical",
1185
+ primitiveType: "boolean",
1186
+ isBooleanEnumConst: true,
1187
+ resolvedSchema: node
1188
+ });
1189
+ case "integer": return makeExact(ctx, {
1190
+ onSplit: "warn",
1191
+ primitiveType: "integer",
1192
+ resolvedSchema: node
1193
+ });
1194
+ case "null": return makeExact(ctx, {
1195
+ onSplit: "warn",
1196
+ primitiveType: "null",
1197
+ resolvedSchema: node
1198
+ });
1199
+ case "number": return makePolicy(ctx, "number-without-tolerance", "number", node);
1200
+ case "string": return makePolicy(ctx, "free-text", "string", node);
1201
+ case "object": return walkObjectOrRecord(node, ctx);
1202
+ case "array": return walkArray(node, ctx);
1203
+ default: return makeUnsupported(ctx, "untyped", node);
1204
+ }
1205
+ return makeUnsupported(ctx, "untyped", node);
1206
+ }
1207
+ function walkUnion(nonNullBranches, rawUnion, ctx) {
1208
+ const branchEntries = [];
1209
+ for (const branch of nonNullBranches) {
1210
+ const res = resolveSimpleRef(branch, {
1211
+ root: ctx.root,
1212
+ depth: ctx.depth + 1,
1213
+ refStack: ctx.refStack
1214
+ });
1215
+ if (!res.ok) return makeUnsupported(ctx, res.detail === "depth-exceeded" ? "depth-exceeded" : "union", rawUnion);
1216
+ if (!isPlainObject(res.schema) || res.schema.type !== "object" || !isPlainObject(res.schema.properties)) return makeUnsupported(ctx, "union", rawUnion);
1217
+ if (Array.isArray(res.schema.allOf) || Array.isArray(res.schema.anyOf) || Array.isArray(res.schema.oneOf) || Object.hasOwn(res.schema, "if") || Object.hasOwn(res.schema, "not")) return makeUnsupported(ctx, "union", rawUnion);
1218
+ branchEntries.push({
1219
+ schema: res.schema,
1220
+ ctx: {
1221
+ root: ctx.root,
1222
+ depth: res.depth,
1223
+ refStack: res.refStack
1224
+ }
1225
+ });
1226
+ }
1227
+ const firstBranch = branchEntries[0].schema;
1228
+ const firstProps = firstBranch.properties;
1229
+ const firstRequired = Array.isArray(firstBranch.required) ? new Set(firstBranch.required.filter((x) => typeof x === "string")) : /* @__PURE__ */ new Set();
1230
+ const candidates = sortLabels(Object.keys(firstProps).filter((name) => firstRequired.has(name)));
1231
+ let chosenDiscriminator = null;
1232
+ let chosenValues = [];
1233
+ for (const propName of candidates) {
1234
+ const seenKeys = /* @__PURE__ */ new Set();
1235
+ const values = [];
1236
+ let valid = true;
1237
+ for (const branch of branchEntries) {
1238
+ const bProps = branch.schema.properties;
1239
+ const bReq = Array.isArray(branch.schema.required) ? branch.schema.required : [];
1240
+ if (!Object.hasOwn(bProps, propName) || !bReq.includes(propName)) {
1241
+ valid = false;
1242
+ break;
1243
+ }
1244
+ const lit = extractLiteral(bProps[propName], branch.ctx);
1245
+ if (!lit.ok) {
1246
+ valid = false;
1247
+ break;
1248
+ }
1249
+ const canonical = canonicalJson(lit.value);
1250
+ if (seenKeys.has(canonical)) {
1251
+ valid = false;
1252
+ break;
1253
+ }
1254
+ seenKeys.add(canonical);
1255
+ values.push({
1256
+ key: canonical,
1257
+ value: lit.value
1258
+ });
1259
+ }
1260
+ if (valid) {
1261
+ chosenDiscriminator = propName;
1262
+ chosenValues = values;
1263
+ break;
1264
+ }
1265
+ }
1266
+ if (chosenDiscriminator === null) return makeUnsupported(ctx, "union", rawUnion);
1267
+ const indexed = sortWith(chosenValues.map((cv, idx) => ({
1268
+ ...cv,
1269
+ idx
1270
+ })), (a, b) => compareUtf16(a.key, b.key));
1271
+ const branches = /* @__PURE__ */ new Map();
1272
+ for (const entry of indexed) {
1273
+ const branch = branchEntries[entry.idx];
1274
+ const walkedObj = walkObject(branch.schema, {
1275
+ ...branch.ctx,
1276
+ reasons: [],
1277
+ nullable: false
1278
+ }, chosenDiscriminator);
1279
+ branches.set(entry.key, {
1280
+ value: entry.value,
1281
+ object: walkedObj
1282
+ });
1283
+ }
1284
+ return {
1285
+ kind: "discriminated-union",
1286
+ reasons: addReason(ctx.reasons, "discriminated-union"),
1287
+ nullable: ctx.nullable,
1288
+ discriminator: chosenDiscriminator,
1289
+ branches
1290
+ };
1291
+ }
1292
+ function walkObjectOrRecord(node, ctx) {
1293
+ if (!isPlainObject(node.properties) || Object.keys(node.properties).length === 0) return makeUnsupported(ctx, "record", node);
1294
+ return walkObject(node, ctx);
1295
+ }
1296
+ function walkObject(node, ctx, excludeProperty) {
1297
+ const propsObj = node.properties;
1298
+ const propNames = sortLabels(Object.keys(propsObj).filter((name) => name !== excludeProperty));
1299
+ const childReasons = ctx.reasons.includes("ref-resolved") ? ["ref-resolved"] : [];
1300
+ const childCtx = {
1301
+ root: ctx.root,
1302
+ depth: ctx.depth + 1,
1303
+ refStack: ctx.refStack,
1304
+ reasons: childReasons,
1305
+ nullable: false
1306
+ };
1307
+ const properties = /* @__PURE__ */ new Map();
1308
+ for (const propName of propNames) properties.set(propName, walkNode(ownValue(propsObj, propName), childCtx));
1309
+ const required = /* @__PURE__ */ new Set();
1310
+ if (Array.isArray(node.required)) {
1311
+ for (const r of node.required) if (typeof r === "string") required.add(r);
1312
+ }
1313
+ const hasExtraProps = Object.hasOwn(node, "additionalProperties") && node.additionalProperties !== void 0 && node.additionalProperties !== false;
1314
+ return {
1315
+ kind: "object",
1316
+ reasons: ctx.reasons,
1317
+ nullable: ctx.nullable,
1318
+ properties,
1319
+ required,
1320
+ additionalProperties: hasExtraProps
1321
+ };
1322
+ }
1323
+ function walkArray(node, ctx) {
1324
+ if (Array.isArray(node.prefixItems) || Array.isArray(node.items)) return {
1325
+ kind: "array",
1326
+ reasons: ctx.reasons,
1327
+ nullable: ctx.nullable,
1328
+ items: null,
1329
+ tuple: true
1330
+ };
1331
+ if (!Object.hasOwn(node, "items") || node.items === void 0) return {
1332
+ kind: "array",
1333
+ reasons: ctx.reasons,
1334
+ nullable: ctx.nullable,
1335
+ items: makeUnsupported({
1336
+ reasons: [],
1337
+ nullable: false
1338
+ }, "untyped"),
1339
+ tuple: false
1340
+ };
1341
+ const walkedItem = walkNode(node.items, {
1342
+ root: ctx.root,
1343
+ depth: ctx.depth + 1,
1344
+ refStack: ctx.refStack,
1345
+ reasons: [],
1346
+ nullable: false
1347
+ });
1348
+ return {
1349
+ kind: "array",
1350
+ reasons: ctx.reasons,
1351
+ nullable: ctx.nullable,
1352
+ items: walkedItem,
1353
+ tuple: false
1354
+ };
1355
+ }
1356
+ /** Resolves a walkable node's raw schema for `{ key }` primitive validation in `derivePlan`. */
1357
+ function isValidKeySchema(node) {
1358
+ if (node.kind !== "leaf") return false;
1359
+ if (node.plan.nullable) return false;
1360
+ if (node.primitiveType === "string" || node.primitiveType === "integer") return true;
1361
+ if (node.resolvedSchema !== void 0) return Array.isArray(node.resolvedSchema.enum) || Object.hasOwn(node.resolvedSchema, "const") && node.resolvedSchema.const !== void 0;
1362
+ return false;
1363
+ }
1364
+ /** Collects flattened pointer paths under an object (used for validation and debugging). */
1365
+ function collectWalkedPaths(obj, prefix = "", out = /* @__PURE__ */ new Map()) {
1366
+ for (const [name, child] of obj.properties) {
1367
+ const path = appendPointer(prefix, name);
1368
+ out.set(path, child);
1369
+ if (child.kind === "object") collectWalkedPaths(child, path, out);
1370
+ }
1371
+ return out;
1372
+ }
1373
+ // src/compare/derive-plan.ts
1374
+ const VALID_SEVERITIES = /* @__PURE__ */ new Set([
1375
+ "info",
1376
+ "warn",
1377
+ "critical"
1378
+ ]);
1379
+ function mergeReasons(base, extra) {
1380
+ const result = [];
1381
+ for (const r of base) if (!result.includes(r)) result.push(r);
1382
+ for (const r of extra) if (!result.includes(r)) result.push(r);
1383
+ return result;
1384
+ }
1385
+ function contextReasons(reasons) {
1386
+ return reasons.filter((r) => r === "nullable-unwrap" || r === "ref-resolved");
1387
+ }
1388
+ function nonePlan(opts) {
1389
+ return {
1390
+ comparator: "none",
1391
+ reason: opts.reason,
1392
+ detail: opts.detail,
1393
+ reasons: mergeReasons(opts.reasons, [opts.reason]),
1394
+ nullable: opts.nullable
1395
+ };
1396
+ }
1397
+ function callerNonePlan(baseReasons, nullable) {
1398
+ return {
1399
+ comparator: "none",
1400
+ reason: "policy",
1401
+ detail: "caller-none",
1402
+ reasons: mergeReasons(baseReasons, ["caller-override", "policy"]),
1403
+ nullable
1404
+ };
1405
+ }
1406
+ function validateSeverity(value, path) {
1407
+ if (typeof value !== "string" || !VALID_SEVERITIES.has(value)) throw new DissentArgumentError("invalid-option", `compare.${path}`, `Invalid severity in override for "${path}"`);
1408
+ return value;
1409
+ }
1410
+ function checkToleranceBound(spec, field, path) {
1411
+ if (!Object.hasOwn(spec, field) || spec[field] === void 0) return;
1412
+ const val = ownValue(spec, field);
1413
+ if (typeof val !== "number" || !Number.isFinite(val) || val < 0) throw new DissentArgumentError("invalid-tolerance", path, `Tolerance ${field} at "${path}" must be a finite number >= 0`);
1414
+ return val === 0 ? 0 : val;
1415
+ }
1416
+ function validateTolerance(spec, path) {
1417
+ if (!isPlainObject(spec)) throw new DissentArgumentError("invalid-tolerance", path, `Tolerance for "${path}" must be a plain object`);
1418
+ for (const k of Object.keys(spec)) if (k !== "absolute" && k !== "relative") throw new DissentArgumentError("invalid-tolerance", path, `Unknown tolerance key "${k}" at "${path}"`);
1419
+ const abs = checkToleranceBound(spec, "absolute", path);
1420
+ const rel = checkToleranceBound(spec, "relative", path);
1421
+ if (abs === void 0 && rel === void 0) throw new DissentArgumentError("invalid-tolerance", path, `Tolerance at "${path}" requires at least one of absolute or relative`);
1422
+ const out = {};
1423
+ if (abs !== void 0) out.absolute = abs;
1424
+ if (rel !== void 0) out.relative = rel;
1425
+ return out;
1426
+ }
1427
+ function assertAllowedKeys(keys, allowed, label, path) {
1428
+ for (const k of keys) if (!allowed.has(k)) throw new DissentArgumentError("incompatible-override", path, `Unexpected key "${k}" in ${label} override at "${path}"`);
1429
+ }
1430
+ function optionalOnSplit(raw, path) {
1431
+ if (!Object.hasOwn(raw, "onSplit") || raw.onSplit === void 0) return;
1432
+ return validateSeverity(ownValue(raw, "onSplit"), path);
1433
+ }
1434
+ function parseOverride(raw, path) {
1435
+ if (raw === "exact" || raw === "set" || raw === "none") return { kind: raw };
1436
+ if (!isPlainObject(raw)) throw new DissentArgumentError("invalid-option", `compare.${path}`, `Invalid override value at "${path}"`);
1437
+ const keys = Object.keys(raw);
1438
+ if (Object.hasOwn(raw, "comparator")) {
1439
+ assertAllowedKeys(keys, /* @__PURE__ */ new Set(["comparator", "onSplit"]), "comparator", path);
1440
+ const comp = ownValue(raw, "comparator");
1441
+ if (comp === "none") {
1442
+ if (Object.hasOwn(raw, "onSplit") && raw.onSplit !== void 0) throw new DissentArgumentError("incompatible-override", path, `Override "none" at "${path}" cannot specify onSplit`);
1443
+ return { kind: "none" };
1444
+ }
1445
+ if (comp === "exact" || comp === "set") {
1446
+ const onSplit = optionalOnSplit(raw, path);
1447
+ return onSplit !== void 0 ? {
1448
+ kind: comp,
1449
+ onSplit
1450
+ } : { kind: comp };
1451
+ }
1452
+ throw new DissentArgumentError("incompatible-override", path, `Unsupported comparator override "${String(comp)}" at "${path}"`);
1453
+ }
1454
+ if (Object.hasOwn(raw, "tolerance")) {
1455
+ assertAllowedKeys(keys, /* @__PURE__ */ new Set(["tolerance", "onSplit"]), "tolerance", path);
1456
+ const onSplit = optionalOnSplit(raw, path);
1457
+ const tolerance = ownValue(raw, "tolerance");
1458
+ return onSplit !== void 0 ? {
1459
+ kind: "tolerance",
1460
+ tolerance,
1461
+ onSplit
1462
+ } : {
1463
+ kind: "tolerance",
1464
+ tolerance
1465
+ };
1466
+ }
1467
+ if (Object.hasOwn(raw, "key")) {
1468
+ assertAllowedKeys(keys, /* @__PURE__ */ new Set(["key", "onSplit"]), "keyed-set", path);
1469
+ const onSplit = optionalOnSplit(raw, path);
1470
+ const key = ownValue(raw, "key");
1471
+ return onSplit !== void 0 ? {
1472
+ kind: "keyed-set",
1473
+ key,
1474
+ onSplit
1475
+ } : {
1476
+ kind: "keyed-set",
1477
+ key
1478
+ };
1479
+ }
1480
+ if (Object.hasOwn(raw, "onSplit") && keys.length === 1) return {
1481
+ kind: "onSplit-only",
1482
+ onSplit: validateSeverity(ownValue(raw, "onSplit"), path)
1483
+ };
1484
+ throw new DissentArgumentError("invalid-option", `compare.${path}`, `Unrecognized override shape at "${path}"`);
1485
+ }
1486
+ function getArrayPolicyOrUnsupportedDetail(items) {
1487
+ if (items === null) return {
1488
+ reason: "unsupported",
1489
+ detail: "tuple"
1490
+ };
1491
+ if (items.kind === "array") return {
1492
+ reason: "unsupported",
1493
+ detail: "nested-array"
1494
+ };
1495
+ if (items.kind === "object") return {
1496
+ reason: "unsupported",
1497
+ detail: "object-array-requires-key"
1498
+ };
1499
+ if (items.kind === "discriminated-union") return {
1500
+ reason: "unsupported",
1501
+ detail: "union"
1502
+ };
1503
+ if (items.primitiveType === "number") return {
1504
+ reason: "policy",
1505
+ detail: "number-array"
1506
+ };
1507
+ if (items.primitiveType === "integer" || items.primitiveType === "boolean" || items.primitiveType === "string" || items.isBooleanEnumConst) return null;
1508
+ if (items.plan.comparator === "none" && items.plan.reason === "unsupported") return {
1509
+ reason: "unsupported",
1510
+ detail: items.plan.detail
1511
+ };
1512
+ return {
1513
+ reason: "unsupported",
1514
+ detail: "untyped"
1515
+ };
1516
+ }
1517
+ function planDefaultArray(node) {
1518
+ if (node.tuple) return nonePlan({
1519
+ reason: "unsupported",
1520
+ detail: "tuple",
1521
+ reasons: node.reasons,
1522
+ nullable: node.nullable
1523
+ });
1524
+ const itemReasons = node.items?.kind === "leaf" ? contextReasons(node.items.plan.reasons) : node.items !== null ? contextReasons(node.items.reasons) : [];
1525
+ const baseReasons = mergeReasons(node.reasons, itemReasons);
1526
+ const nonSet = getArrayPolicyOrUnsupportedDetail(node.items);
1527
+ if (nonSet !== null) return nonePlan({
1528
+ reason: nonSet.reason,
1529
+ detail: nonSet.detail,
1530
+ reasons: baseReasons,
1531
+ nullable: node.nullable
1532
+ });
1533
+ return {
1534
+ comparator: "set",
1535
+ onSplit: "warn",
1536
+ reasons: mergeReasons(baseReasons, ["default-by-type"]),
1537
+ nullable: node.nullable
1538
+ };
1539
+ }
1540
+ function planNestedObjectLeaves(obj, prefix, out, excludeTopKey) {
1541
+ if (obj.additionalProperties) out.push([prefix, nonePlan({
1542
+ reason: "unsupported",
1543
+ detail: "additional-properties",
1544
+ reasons: obj.reasons,
1545
+ nullable: obj.nullable
1546
+ })]);
1547
+ for (const [propName, child] of obj.properties) {
1548
+ if (prefix === "" && propName === excludeTopKey) continue;
1549
+ const childPath = appendPointer(prefix, propName);
1550
+ if (child.kind === "leaf") out.push([childPath, child.plan]);
1551
+ else if (child.kind === "object") planNestedObjectLeaves(child, childPath, out);
1552
+ else if (child.kind === "array") out.push([childPath, planDefaultArray(child)]);
1553
+ else out.push([childPath, nonePlan({
1554
+ reason: "unsupported",
1555
+ detail: "nested-composite",
1556
+ reasons: contextReasons(child.reasons),
1557
+ nullable: child.nullable
1558
+ })]);
1559
+ }
1560
+ }
1561
+ function planLeafWithOverride(leaf, override, path) {
1562
+ if (override === void 0) return leaf.plan;
1563
+ const baseCtx = contextReasons(leaf.plan.reasons);
1564
+ switch (override.kind) {
1565
+ case "exact": return {
1566
+ comparator: "exact",
1567
+ onSplit: override.onSplit ?? (leaf.isBooleanEnumConst ? "critical" : "warn"),
1568
+ reasons: mergeReasons(baseCtx, ["caller-override"]),
1569
+ nullable: leaf.plan.nullable
1570
+ };
1571
+ case "none": return callerNonePlan(baseCtx, leaf.plan.nullable);
1572
+ case "tolerance":
1573
+ if (leaf.primitiveType !== "number" && leaf.primitiveType !== "integer") throw new DissentArgumentError("incompatible-override", path, `Tolerance override at "${path}" requires a number or integer schema`);
1574
+ return {
1575
+ comparator: "tolerance",
1576
+ tolerance: validateTolerance(override.tolerance, path),
1577
+ onSplit: override.onSplit ?? "warn",
1578
+ reasons: mergeReasons(baseCtx, ["caller-override"]),
1579
+ nullable: leaf.plan.nullable
1580
+ };
1581
+ case "onSplit-only":
1582
+ if (leaf.plan.comparator === "none") throw new DissentArgumentError("incompatible-override", path, `Override { onSplit } at "${path}" requires a non-none default comparator`);
1583
+ return {
1584
+ ...leaf.plan,
1585
+ onSplit: override.onSplit,
1586
+ reasons: mergeReasons(leaf.plan.reasons, ["caller-override"])
1587
+ };
1588
+ case "set":
1589
+ case "keyed-set": throw new DissentArgumentError("incompatible-override", path, `Override "${override.kind}" at "${path}" requires an array schema`);
1590
+ }
1591
+ }
1592
+ function planArrayWithOverride(arr, override, path) {
1593
+ if (override === void 0) return planDefaultArray(arr);
1594
+ const baseCtx = contextReasons(arr.reasons);
1595
+ switch (override.kind) {
1596
+ case "exact":
1597
+ case "set": return {
1598
+ comparator: override.kind,
1599
+ onSplit: override.onSplit ?? "warn",
1600
+ reasons: mergeReasons(baseCtx, ["caller-override"]),
1601
+ nullable: arr.nullable
1602
+ };
1603
+ case "none": return callerNonePlan(baseCtx, arr.nullable);
1604
+ case "onSplit-only": {
1605
+ const def = planDefaultArray(arr);
1606
+ if (def.comparator === "none") throw new DissentArgumentError("incompatible-override", path, `Override { onSplit } at "${path}" requires a non-none default comparator`);
1607
+ return {
1608
+ ...def,
1609
+ onSplit: override.onSplit,
1610
+ reasons: mergeReasons(def.reasons, ["caller-override"])
1611
+ };
1612
+ }
1613
+ case "keyed-set": {
1614
+ if (arr.tuple || arr.items === null || arr.items.kind !== "object") throw new DissentArgumentError("incompatible-override", path, `Keyed-set override at "${path}" requires an array of objects`);
1615
+ const key = override.key;
1616
+ if (typeof key !== "string" || key.length === 0) throw new DissentArgumentError("invalid-key", path, `Keyed-set override at "${path}" requires a non-empty string key`);
1617
+ const keyNode = arr.items.properties.get(key);
1618
+ if (keyNode === void 0 || !arr.items.required.has(key) || !isValidKeySchema(keyNode)) throw new DissentArgumentError("invalid-key", path, `Key "${key}" at "${path}" must be a required non-nullable string, integer, enum, or const property`);
1619
+ const itemEntries = [];
1620
+ planNestedObjectLeaves(arr.items, "", itemEntries, key);
1621
+ return {
1622
+ comparator: "keyed-set",
1623
+ key,
1624
+ onSplit: override.onSplit ?? "warn",
1625
+ itemFields: toSortedNullProtoRecord(itemEntries),
1626
+ reasons: mergeReasons(mergeReasons(baseCtx, contextReasons(arr.items.reasons)), ["caller-override"]),
1627
+ nullable: arr.nullable
1628
+ };
1629
+ }
1630
+ case "tolerance": throw new DissentArgumentError("incompatible-override", path, `Tolerance override at "${path}" requires a number or integer schema`);
1631
+ }
1632
+ }
1633
+ function planUnionWithOverride(union, override, path) {
1634
+ const baseCtx = contextReasons(union.reasons);
1635
+ if (override !== void 0) {
1636
+ if (override.kind === "exact") return {
1637
+ comparator: "exact",
1638
+ onSplit: override.onSplit ?? "warn",
1639
+ reasons: mergeReasons(baseCtx, ["caller-override"]),
1640
+ nullable: union.nullable
1641
+ };
1642
+ if (override.kind === "none") return callerNonePlan(baseCtx, union.nullable);
1643
+ if (override.kind !== "onSplit-only") throw new DissentArgumentError("incompatible-override", path, `Override "${override.kind}" is incompatible with discriminated union at "${path}"`);
1644
+ }
1645
+ const branchEntries = [];
1646
+ for (const [canonKey, branch] of union.branches) {
1647
+ const leafEntries = [];
1648
+ planNestedObjectLeaves(branch.object, "", leafEntries);
1649
+ branchEntries.push([canonKey, toSortedNullProtoRecord(leafEntries)]);
1650
+ }
1651
+ return {
1652
+ comparator: "discriminated-union",
1653
+ discriminator: union.discriminator,
1654
+ onSplit: override?.kind === "onSplit-only" ? override.onSplit : "critical",
1655
+ branches: toSortedNullProtoRecord(branchEntries),
1656
+ reasons: override?.kind === "onSplit-only" ? mergeReasons(union.reasons, ["caller-override"]) : [...union.reasons],
1657
+ nullable: union.nullable
1658
+ };
1659
+ }
1660
+ function assertNoNestedOverridesUnder(prefix, overrides) {
1661
+ const slashPrefix = prefix === "" ? "/" : `${prefix}/`;
1662
+ for (const candidatePath of overrides.keys()) if (candidatePath.startsWith(slashPrefix)) throw new DissentArgumentError("incompatible-override", candidatePath, `Override at "${candidatePath}" conflicts with parent override at "${prefix}"`);
1663
+ }
1664
+ function walkPlanEntries(obj, prefix, ctx) {
1665
+ if (obj.additionalProperties) ctx.out.push([prefix, nonePlan({
1666
+ reason: "unsupported",
1667
+ detail: "additional-properties",
1668
+ reasons: obj.reasons,
1669
+ nullable: obj.nullable
1670
+ })]);
1671
+ for (const [propName, child] of obj.properties) {
1672
+ const childPath = appendPointer(prefix, propName);
1673
+ const override = ctx.overrides.get(childPath);
1674
+ if (child.kind === "leaf") ctx.out.push([childPath, planLeafWithOverride(child, override, childPath)]);
1675
+ else if (child.kind === "array") ctx.out.push([childPath, planArrayWithOverride(child, override, childPath)]);
1676
+ else if (child.kind === "discriminated-union") ctx.out.push([childPath, planUnionWithOverride(child, override, childPath)]);
1677
+ else if (override === void 0) walkPlanEntries(child, childPath, ctx);
1678
+ else {
1679
+ const baseCtx = contextReasons(child.reasons);
1680
+ if (override.kind === "exact") {
1681
+ assertNoNestedOverridesUnder(childPath, ctx.overrides);
1682
+ ctx.out.push([childPath, {
1683
+ comparator: "exact",
1684
+ onSplit: override.onSplit ?? "warn",
1685
+ reasons: mergeReasons(baseCtx, ["caller-override"]),
1686
+ nullable: child.nullable
1687
+ }]);
1688
+ } else if (override.kind === "none") {
1689
+ assertNoNestedOverridesUnder(childPath, ctx.overrides);
1690
+ ctx.out.push([childPath, callerNonePlan(baseCtx, child.nullable)]);
1691
+ } else throw new DissentArgumentError("incompatible-override", childPath, `Override "${override.kind}" cannot apply to plain object at "${childPath}"`);
1692
+ }
1693
+ }
1694
+ }
1695
+ /**
1696
+ * Synchronous pure plan derivation returning sorted, null-prototype `fields`
1697
+ * keyed by RFC 6901 JSON Pointer.
1698
+ */
1699
+ function buildPlanFields(rootSchema, compare) {
1700
+ const root = walkSchema(rootSchema);
1701
+ const walkedPaths = collectWalkedPaths(root);
1702
+ const overrides = /* @__PURE__ */ new Map();
1703
+ if (compare !== void 0) {
1704
+ if (!isPlainObject(compare)) throw new DissentArgumentError("invalid-option", "compare", "compare must be a plain object");
1705
+ for (const rawKey of Object.keys(compare)) {
1706
+ const pointer = normalizePath(rawKey);
1707
+ if (overrides.has(pointer)) throw new DissentArgumentError("invalid-option", `compare.${rawKey}`, `Duplicate compare path "${pointer}" from key "${rawKey}"`);
1708
+ if (!walkedPaths.has(pointer)) throw new DissentArgumentError("unknown-compare-path", pointer, `Compare path "${rawKey}" (normalized "${pointer}") does not exist in schema`);
1709
+ const rawOverride = ownValue(compare, rawKey);
1710
+ if (rawOverride !== void 0) overrides.set(pointer, parseOverride(rawOverride, pointer));
1711
+ }
1712
+ }
1713
+ const out = [];
1714
+ walkPlanEntries(root, "", {
1715
+ overrides,
1716
+ out
1717
+ });
1718
+ return toSortedNullProtoRecord(out);
1719
+ }
1720
+ /**
1721
+ * Derives the deterministic comparison plan and its `dissent-plan/1` fingerprint
1722
+ * from a resolved JSON Schema and optional caller comparator overrides.
1723
+ */
1724
+ async function derivePlan(rootSchema, compare) {
1725
+ const fields = buildPlanFields(rootSchema, compare);
1726
+ return {
1727
+ fingerprint: await sha256Hex(canonicalJson({
1728
+ protocol: "dissent-plan/1",
1729
+ fields
1730
+ })),
1731
+ fields
1732
+ };
1733
+ }
1734
+ // src/findings.ts
1735
+ const SEVERITY_RANK = {
1736
+ critical: 0,
1737
+ warn: 1,
1738
+ info: 2
1739
+ };
1740
+ function compareOptionalString(a, b) {
1741
+ if (a === void 0 && b === void 0) return 0;
1742
+ if (a === void 0) return -1;
1743
+ if (b === void 0) return 1;
1744
+ return compareUtf16(a, b);
1745
+ }
1746
+ /**
1747
+ * Compares two findings according to §9.1 canonical order:
1748
+ * severity (critical < warn < info), code, path (absent first),
1749
+ * canonicalJson(within ?? null), subpath (absent first), witnesses[0] (absent first).
1750
+ */
1751
+ function compareFindings(a, b) {
1752
+ const sevDiff = SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity];
1753
+ if (sevDiff !== 0) return sevDiff;
1754
+ const codeDiff = compareUtf16(a.code, b.code);
1755
+ if (codeDiff !== 0) return codeDiff;
1756
+ const pathDiff = compareOptionalString(a.path, b.path);
1757
+ if (pathDiff !== 0) return pathDiff;
1758
+ const withinDiff = compareUtf16(canonicalJson(a.within ?? null), canonicalJson(b.within ?? null));
1759
+ if (withinDiff !== 0) return withinDiff;
1760
+ const subpathDiff = compareOptionalString(a.subpath, b.subpath);
1761
+ if (subpathDiff !== 0) return subpathDiff;
1762
+ return compareOptionalString(a.witnesses?.[0], b.witnesses?.[0]);
1763
+ }
1764
+ /**
1765
+ * Returns a fresh array of findings sorted in canonical order (§9.1).
1766
+ */
1767
+ function sortFindings(findings) {
1768
+ return sortWith(findings, compareFindings);
1769
+ }
1770
+ /**
1771
+ * Derives the three-state advisory rollup from findings (§9.2).
1772
+ */
1773
+ function computeAdvisory(findings) {
1774
+ let hasWarn = false;
1775
+ for (const f of findings) {
1776
+ if (f.severity === "critical") return "review-required";
1777
+ if (f.severity === "warn") hasWarn = true;
1778
+ }
1779
+ return hasWarn ? "warnings" : "clear";
1780
+ }
1781
+ function pushNestedLeafFindings(findings, opts) {
1782
+ let anySplit = false;
1783
+ for (const subpath of Object.keys(opts.planMap)) {
1784
+ const subplan = ownValue(opts.planMap, subpath);
1785
+ const subres = ownValue(opts.fieldMap, subpath);
1786
+ if (subres === void 0) continue;
1787
+ if (subres.missing.length > 0 && subres.presented.length >= 1) findings.push({
1788
+ code: "field-partial",
1789
+ severity: "warn",
1790
+ path: opts.path,
1791
+ within: opts.within,
1792
+ subpath,
1793
+ witnesses: [...subres.missing]
1794
+ });
1795
+ if (subres.status === "split" && subplan.comparator !== "none") {
1796
+ anySplit = true;
1797
+ findings.push({
1798
+ code: "field-split",
1799
+ severity: subplan.onSplit,
1800
+ path: opts.path,
1801
+ within: opts.within,
1802
+ subpath,
1803
+ witnesses: [...subres.presented]
1804
+ });
1805
+ }
1806
+ }
1807
+ return anySplit;
1808
+ }
1809
+ /**
1810
+ * Collects pure Layer B, schema, and coverage findings from comparison outputs.
1811
+ * When `answered < 2`, `insufficient-quorum` is emitted and field-level findings
1812
+ * (`field-split`, `field-partial`, `duplicate-key`) are suppressed while
1813
+ * `unsupported-schema` and `coverage-low` continue to be emitted (§9.1).
1814
+ */
1815
+ function collectComparisonFindings(params) {
1816
+ const { answered, planFields, fieldResults, coverage, strictCoverage = false } = params;
1817
+ const findings = [];
1818
+ if (answered < 2) findings.push({
1819
+ code: "insufficient-quorum",
1820
+ severity: "critical",
1821
+ data: { answered }
1822
+ });
1823
+ for (const path of Object.keys(planFields)) {
1824
+ const plan = ownValue(planFields, path);
1825
+ const res = ownValue(fieldResults, path);
1826
+ if (plan.comparator === "none" && plan.reason === "unsupported") findings.push({
1827
+ code: "unsupported-schema",
1828
+ severity: "warn",
1829
+ path,
1830
+ data: { detail: plan.detail }
1831
+ });
1832
+ else if (plan.comparator === "keyed-set") for (const subpath of Object.keys(plan.itemFields)) {
1833
+ const subplan = ownValue(plan.itemFields, subpath);
1834
+ if (subplan.comparator === "none" && subplan.reason === "unsupported") findings.push({
1835
+ code: "unsupported-schema",
1836
+ severity: "warn",
1837
+ path,
1838
+ subpath,
1839
+ data: { detail: subplan.detail }
1840
+ });
1841
+ }
1842
+ else if (plan.comparator === "discriminated-union") for (const branchKey of Object.keys(plan.branches)) {
1843
+ const branchValue = JSON.parse(branchKey);
1844
+ const branchLeaves = ownValue(plan.branches, branchKey);
1845
+ for (const subpath of Object.keys(branchLeaves)) {
1846
+ const subplan = ownValue(branchLeaves, subpath);
1847
+ if (subplan.comparator === "none" && subplan.reason === "unsupported") findings.push({
1848
+ code: "unsupported-schema",
1849
+ severity: "warn",
1850
+ path,
1851
+ within: { branch: branchValue },
1852
+ subpath,
1853
+ data: { detail: subplan.detail }
1854
+ });
1855
+ }
1856
+ }
1857
+ if (answered < 2 || res === void 0) continue;
1858
+ if (res.missing.length > 0 && res.presented.length >= 1) findings.push({
1859
+ code: "field-partial",
1860
+ severity: "warn",
1861
+ path,
1862
+ witnesses: [...res.missing]
1863
+ });
1864
+ if (plan.comparator === "keyed-set" && res.comparator === "none" && res.reason === "duplicate-key") {
1865
+ findings.push({
1866
+ code: "duplicate-key",
1867
+ severity: "warn",
1868
+ path,
1869
+ witnesses: [...res.duplicateKeyWitnesses ?? []]
1870
+ });
1871
+ continue;
1872
+ }
1873
+ if (plan.comparator === "keyed-set" && res.comparator === "keyed-set") {
1874
+ let anyItemSplit = false;
1875
+ for (const item of res.items) if (pushNestedLeafFindings(findings, {
1876
+ path,
1877
+ within: { key: item.key },
1878
+ planMap: plan.itemFields,
1879
+ fieldMap: item.fields
1880
+ })) anyItemSplit = true;
1881
+ const hasNullVsArraySplit = res.nulls.length > 0 && res.nulls.length < res.presented.length;
1882
+ const hasKeySetDiff = res.keys.intersection.length !== res.keys.union.length;
1883
+ if (res.presented.length >= 2 && res.status === "split" && (hasNullVsArraySplit || hasKeySetDiff || !anyItemSplit)) findings.push({
1884
+ code: "field-split",
1885
+ severity: plan.onSplit,
1886
+ path,
1887
+ witnesses: [...res.presented]
1888
+ });
1889
+ continue;
1890
+ }
1891
+ if (plan.comparator === "discriminated-union" && res.comparator === "discriminated-union") {
1892
+ if (res.choice.status === "split") findings.push({
1893
+ code: "field-split",
1894
+ severity: plan.onSplit,
1895
+ path,
1896
+ witnesses: [...res.choice.presented]
1897
+ });
1898
+ for (const branch of res.branches) {
1899
+ const branchPlan = ownValue(plan.branches, canonicalJson(branch.value));
1900
+ if (branchPlan === void 0) continue;
1901
+ pushNestedLeafFindings(findings, {
1902
+ path,
1903
+ within: { branch: branch.value },
1904
+ planMap: branchPlan,
1905
+ fieldMap: branch.fields
1906
+ });
1907
+ }
1908
+ continue;
1909
+ }
1910
+ if (res.status === "split" && plan.comparator !== "none") findings.push({
1911
+ code: "field-split",
1912
+ severity: plan.onSplit,
1913
+ path,
1914
+ witnesses: [...res.presented]
1915
+ });
1916
+ }
1917
+ if (coverage.unsupported + coverage.failedAtRuntime > 0) findings.push({
1918
+ code: "coverage-low",
1919
+ severity: strictCoverage ? "critical" : "warn",
1920
+ data: {
1921
+ compared: coverage.compared,
1922
+ fields: coverage.fields,
1923
+ ratio: coverage.ratio
1924
+ }
1925
+ });
1926
+ return sortFindings(findings);
1927
+ }
1928
+ // src/sanitize.ts
1929
+ const ANSI_CSI_RE = /\u001b\[[0-?]*[ -/]*[@-~]/g;
1930
+ const ANSI_OSC_RE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g;
1931
+ const ANSI_OTHER_RE = /\u001b[\s\S]?/g;
1932
+ const UNSAFE_CONTROLS_RE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200b-\u200f\u202a-\u202e\u2060\u2066-\u2069\ufeff]/g;
1933
+ const REDACT_BEARER_RE = /Bearer\s+[A-Za-z0-9._~+/=-]+/gi;
1934
+ const REDACT_PREFIX_KEY_RE = /\b(?:sk|pk|rk|sess)-[A-Za-z0-9_-]{16,}/gi;
1935
+ const REDACT_GOOGLE_KEY_RE = /\bAIza[0-9A-Za-z_-]{35}\b/gi;
1936
+ const REDACT_KV_RE = /\b(api[_-]?key|x-api-key|authorization|token|secret|password)\b(["']?\s*[:=]\s*["']?)[^\s"',;&]+/gi;
1937
+ const REDACT_QUERY_RE = /([?&](?:key|api_key|apikey|token|access_token)=)[^&\s"']+/gi;
1938
+ /** Strips ANSI CSI/OSC/ESC sequences and unsafe control/BiDi characters (§11.3 step 1). */
1939
+ function sanitizeControlChars(text) {
1940
+ return text.replace(ANSI_CSI_RE, "").replace(ANSI_OSC_RE, "").replace(ANSI_OTHER_RE, "").replace(UNSAFE_CONTROLS_RE, "");
1941
+ }
1942
+ /** Strips unsafe controls and collapses newlines/tabs into single spaces for inline slots (§11.3 steps 1–2). */
1943
+ function sanitizeInline(text) {
1944
+ return sanitizeControlChars(text).replaceAll(/\r?\n|\r|\t/g, " ");
1945
+ }
1946
+ /** Applies the §12.3 best-effort secret redaction patterns in order. */
1947
+ function redactSecrets(text) {
1948
+ return text.replace(REDACT_BEARER_RE, "Bearer [REDACTED]").replace(REDACT_PREFIX_KEY_RE, "[REDACTED]").replace(REDACT_GOOGLE_KEY_RE, "[REDACTED]").replace(REDACT_KV_RE, (_m, k, sep) => `${k}${sep}[REDACTED]`).replace(REDACT_QUERY_RE, (_m, prefix) => `${prefix}[REDACTED]`);
1949
+ }
1950
+ // src/witness/redact.ts
1951
+ const encoder = new TextEncoder();
1952
+ const MAX_WARNINGS_PER_WITNESS = 16;
1953
+ /** Returns UTF-8 byte length of a string. */
1954
+ function utf8ByteLength(text) {
1955
+ return encoder.encode(text).byteLength;
1956
+ }
1957
+ /**
1958
+ * Truncates `text` to at most `maxBytes` UTF-8 bytes without splitting code points
1959
+ * and without appending an ellipsis (§12.4).
1960
+ */
1961
+ function truncateUtf8Bytes(text, maxBytes) {
1962
+ if (utf8ByteLength(text) <= maxBytes) return {
1963
+ text,
1964
+ truncated: false
1965
+ };
1966
+ let used = 0;
1967
+ let end = 0;
1968
+ for (const cp of text) {
1969
+ const len = encoder.encode(cp).byteLength;
1970
+ if (used + len > maxBytes) break;
1971
+ used += len;
1972
+ end += cp.length;
1973
+ }
1974
+ return {
1975
+ text: text.slice(0, end),
1976
+ truncated: true
1977
+ };
1978
+ }
1979
+ /** Sanitizes, redacts, and caps error text (`message` or `rawText`) per §12.3–§12.4. */
1980
+ function sanitizeErrorText(text, maxBytes) {
1981
+ return truncateUtf8Bytes(redactSecrets(sanitizeControlChars(text)), maxBytes);
1982
+ }
1983
+ function toSanitizedJson(value, depth, stack) {
1984
+ if (value === null || typeof value === "boolean") return value;
1985
+ if (typeof value === "string") return redactSecrets(sanitizeControlChars(value));
1986
+ if (typeof value === "number") return Number.isFinite(value) ? value : String(value);
1987
+ if (typeof value !== "object") return redactSecrets(sanitizeControlChars(String(value)));
1988
+ if (depth >= 16 || stack.has(value)) return "[truncated]";
1989
+ stack.add(value);
1990
+ try {
1991
+ if (Array.isArray(value)) {
1992
+ const arr = [];
1993
+ for (const item of value) arr.push(toSanitizedJson(item, depth + 1, stack));
1994
+ return arr;
1995
+ }
1996
+ if (!isPlainObject(value)) return redactSecrets(sanitizeControlChars(String(value)));
1997
+ const keys = Object.keys(value).slice();
1998
+ keys.sort(compareUtf16);
1999
+ const out = Object.create(null);
2000
+ for (const key of keys) {
2001
+ const member = ownValue(value, key);
2002
+ if (member === void 0) continue;
2003
+ const cleanKey = redactSecrets(sanitizeControlChars(key));
2004
+ Object.defineProperty(out, cleanKey, {
2005
+ value: toSanitizedJson(member, depth + 1, stack),
2006
+ enumerable: true,
2007
+ writable: true,
2008
+ configurable: true
2009
+ });
2010
+ }
2011
+ return out;
2012
+ } finally {
2013
+ stack.delete(value);
2014
+ }
2015
+ }
2016
+ /**
2017
+ * Normalizes SDK warnings to at most 16 canonical-JSON-safe, sanitized entries,
2018
+ * each capped at `maxErrorTextBytes` when serialized (§2.4, §12.4).
2019
+ */
2020
+ function sanitizeWarnings(warnings, maxErrorTextBytes) {
2021
+ if (!Array.isArray(warnings) || warnings.length === 0) return [];
2022
+ const capped = warnings.slice(0, MAX_WARNINGS_PER_WITNESS);
2023
+ const out = [];
2024
+ for (const entry of capped) {
2025
+ const clean = toSanitizedJson(entry, 0, /* @__PURE__ */ new WeakSet());
2026
+ const serialized = canonicalJson(clean);
2027
+ if (utf8ByteLength(serialized) <= maxErrorTextBytes) {
2028
+ out.push(clean);
2029
+ continue;
2030
+ }
2031
+ const wrapperOverhead = utf8ByteLength("{\"truncated\":\"\"}");
2032
+ let { text } = truncateUtf8Bytes(serialized, Math.max(0, maxErrorTextBytes - wrapperOverhead));
2033
+ while (utf8ByteLength(canonicalJson({ truncated: text })) > maxErrorTextBytes && text.length > 0) text = text.slice(0, Math.floor(text.length * .8));
2034
+ out.push({ truncated: text });
2035
+ }
2036
+ return out;
2037
+ }
2038
+ // src/witness/classify-error.ts
2039
+ const TIMEOUT_NAMES = /* @__PURE__ */ new Set(["TimeoutError"]);
2040
+ const ABORT_NAMES = /* @__PURE__ */ new Set(["AbortError", "ResponseAborted"]);
2041
+ const GATEWAY_ERROR_MARKER = Symbol.for("vercel.ai.gateway.error");
2042
+ const MAX_CAUSE_DEPTH = 4;
2043
+ function isGatewayError(error) {
2044
+ return typeof error === "object" && error !== null && error[GATEWAY_ERROR_MARKER] === true;
2045
+ }
2046
+ function isWrappedGatewayAuthError(error) {
2047
+ if (typeof error !== "object" || error === null) return false;
2048
+ if (GATEWAY_ERROR_MARKER in error) return false;
2049
+ if (AISDKError.isInstance(error) && error.name === "GatewayError") return true;
2050
+ return error instanceof Error && error.name === "GatewayAuthenticationError";
2051
+ }
2052
+ function asApiLikeError(error) {
2053
+ if (APICallError.isInstance(error) || isGatewayError(error)) return error;
2054
+ }
2055
+ /** Internal guard error when canonical witness output exceeds `maxOutputBytes`. */
2056
+ var OutputTooLargeError = class extends Error {
2057
+ bytes;
2058
+ maxBytes;
2059
+ constructor(bytes, maxBytes) {
2060
+ super(`Witness output is ${bytes} UTF-8 bytes, exceeding maxOutputBytes (${maxBytes})`);
2061
+ this.name = "OutputTooLarge";
2062
+ this.bytes = bytes;
2063
+ this.maxBytes = maxBytes;
2064
+ }
2065
+ };
2066
+ function readErrorName(error) {
2067
+ if (typeof error !== "object" || error === null) return void 0;
2068
+ const candidate = error.name;
2069
+ return typeof candidate === "string" && candidate.length > 0 ? candidate : void 0;
2070
+ }
2071
+ function readErrorMessage(error) {
2072
+ if (typeof error === "string") return error;
2073
+ if (typeof error === "object" && error !== null) {
2074
+ const candidate = error.message;
2075
+ if (typeof candidate === "string") return candidate;
2076
+ }
2077
+ try {
2078
+ return String(error);
2079
+ } catch {
2080
+ return "Unprintable error";
2081
+ }
2082
+ }
2083
+ function matchesCauseChain(start, names, visited) {
2084
+ let current = start;
2085
+ for (let depth = 0; depth <= MAX_CAUSE_DEPTH; depth++) {
2086
+ if (typeof current !== "object" || current === null) return false;
2087
+ if (visited.has(current)) return false;
2088
+ visited.add(current);
2089
+ const errName = readErrorName(current);
2090
+ if (errName !== void 0 && names.has(errName)) return true;
2091
+ current = current.cause;
2092
+ }
2093
+ return false;
2094
+ }
2095
+ function matchesErrorNames(error, names) {
2096
+ const visited = /* @__PURE__ */ new WeakSet();
2097
+ if (matchesCauseChain(error, names, visited)) return true;
2098
+ if (RetryError.isInstance(error) && error.lastError !== void 0) return matchesCauseChain(error.lastError, names, visited);
2099
+ return false;
2100
+ }
2101
+ function formatName(error, maxBytes) {
2102
+ return sanitizeErrorText(readErrorName(error) ?? typeof error, maxBytes).text || typeof error;
2103
+ }
2104
+ function numOrNull(value) {
2105
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2106
+ }
2107
+ /** Maps AI SDK `LanguageModelUsage` into JSON-safe `WitnessUsage`. */
2108
+ function mapUsage(usage) {
2109
+ if (usage === void 0 || usage === null) return null;
2110
+ return {
2111
+ inputTokens: numOrNull(usage.inputTokens),
2112
+ outputTokens: numOrNull(usage.outputTokens),
2113
+ totalTokens: numOrNull(usage.totalTokens),
2114
+ cacheReadTokens: numOrNull(usage.inputTokenDetails?.cacheReadTokens),
2115
+ cacheWriteTokens: numOrNull(usage.inputTokenDetails?.cacheWriteTokens),
2116
+ reasoningTokens: numOrNull(usage.outputTokenDetails?.reasoningTokens)
2117
+ };
2118
+ }
2119
+ /**
2120
+ * Classifies a thrown witness error per §7 rows 1–9 (row 0 caller abort is handled before calling).
2121
+ */
2122
+ function classifyWitnessError(error, context, maxErrorTextBytes) {
2123
+ const msg = sanitizeErrorText(readErrorMessage(error), maxErrorTextBytes);
2124
+ if (matchesErrorNames(error, TIMEOUT_NAMES)) return {
2125
+ kind: "timeout",
2126
+ name: formatName(error, maxErrorTextBytes),
2127
+ message: msg.text,
2128
+ messageTruncated: msg.truncated
2129
+ };
2130
+ if (matchesErrorNames(error, ABORT_NAMES)) return {
2131
+ kind: "aborted",
2132
+ name: formatName(error, maxErrorTextBytes),
2133
+ message: msg.text,
2134
+ messageTruncated: msg.truncated
2135
+ };
2136
+ if (NoObjectGeneratedError.isInstance(error) || NoOutputGeneratedError.isInstance(error)) {
2137
+ const fr = NoObjectGeneratedError.isInstance(error) ? error.finishReason ?? context?.finishReason : context?.finishReason;
2138
+ const out = {
2139
+ kind: fr === "length" ? "truncated" : fr === "content-filter" ? "refused" : "invalid-output",
2140
+ name: formatName(error, maxErrorTextBytes),
2141
+ message: msg.text,
2142
+ messageTruncated: msg.truncated
2143
+ };
2144
+ if (fr !== void 0) out.finishReason = fr;
2145
+ if (NoObjectGeneratedError.isInstance(error) && typeof error.text === "string" && error.text.length > 0) {
2146
+ const raw = sanitizeErrorText(error.text, maxErrorTextBytes);
2147
+ out.rawText = raw.text;
2148
+ out.rawTextTruncated = raw.truncated;
2149
+ }
2150
+ return out;
2151
+ }
2152
+ if (NonJsonValueError.isInstance(error)) return {
2153
+ kind: "invalid-output",
2154
+ name: "NonJsonValue",
2155
+ message: msg.text,
2156
+ messageTruncated: msg.truncated,
2157
+ path: sanitizeControlChars(error.path)
2158
+ };
2159
+ if (error instanceof OutputTooLargeError) return {
2160
+ kind: "invalid-output",
2161
+ name: "OutputTooLarge",
2162
+ message: msg.text,
2163
+ messageTruncated: msg.truncated
2164
+ };
2165
+ if (APICallError.isInstance(error) || LoadAPIKeyError.isInstance(error) || RetryError.isInstance(error) || isGatewayError(error) || isWrappedGatewayAuthError(error)) {
2166
+ const apiErr = asApiLikeError(error) ?? (RetryError.isInstance(error) ? asApiLikeError(error.lastError) : void 0);
2167
+ const out = {
2168
+ kind: "api-error",
2169
+ name: formatName(error, maxErrorTextBytes),
2170
+ message: msg.text,
2171
+ messageTruncated: msg.truncated
2172
+ };
2173
+ if (apiErr !== void 0) {
2174
+ if (typeof apiErr.statusCode === "number" && Number.isFinite(apiErr.statusCode)) out.statusCode = apiErr.statusCode;
2175
+ out.isRetryable = Boolean(apiErr.isRetryable);
2176
+ }
2177
+ return out;
2178
+ }
2179
+ return {
2180
+ kind: "unknown",
2181
+ name: formatName(error, maxErrorTextBytes),
2182
+ message: msg.text,
2183
+ messageTruncated: msg.truncated
2184
+ };
2185
+ }
2186
+ // src/witness/normalize-witnesses.ts
2187
+ const LABEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
2188
+ const RESERVED_LABELS = /* @__PURE__ */ new Set([
2189
+ "__proto__",
2190
+ "constructor",
2191
+ "prototype",
2192
+ "hasownproperty",
2193
+ "tostring",
2194
+ "valueof"
2195
+ ]);
2196
+ const DEFAULT_MAX_OUTPUT_BYTES = 1048576;
2197
+ const DEFAULT_MAX_ERROR_TEXT_BYTES = 2048;
2198
+ function isWitnessWrapper(entry) {
2199
+ return typeof entry === "object" && entry !== null && !Array.isArray(entry) && Object.hasOwn(entry, "model") && !Object.hasOwn(entry, "specificationVersion");
2200
+ }
2201
+ function isValidLanguageModel(model) {
2202
+ if (typeof model === "string") return model.trim().length > 0;
2203
+ if (typeof model !== "object" || model === null || Array.isArray(model)) return false;
2204
+ const m = model;
2205
+ return typeof m.specificationVersion === "string" && typeof m.provider === "string" && typeof m.modelId === "string" && m.modelId.length > 0;
2206
+ }
2207
+ function isGatewayProvider(provider) {
2208
+ return provider === "gateway" || provider === "gateway-string" || provider.startsWith("gateway.");
2209
+ }
2210
+ function hasNonEmptySlashParts(id) {
2211
+ const slash = id.indexOf("/");
2212
+ return slash > 0 && slash < id.length - 1;
2213
+ }
2214
+ /**
2215
+ * Computes the requested `ModelIdentity` for a model string or instance (§8.1–§8.2).
2216
+ */
2217
+ function toRequestedIdentity(model) {
2218
+ const provider = typeof model === "string" ? "gateway-string" : model.provider;
2219
+ const modelId = typeof model === "string" ? model : model.modelId;
2220
+ if (isGatewayProvider(provider) && hasNonEmptySlashParts(modelId)) {
2221
+ const canonicalId = modelId.toLowerCase();
2222
+ const slash = canonicalId.indexOf("/");
2223
+ return {
2224
+ provider,
2225
+ modelId,
2226
+ canonicalId,
2227
+ providerKey: canonicalId.slice(0, slash)
2228
+ };
2229
+ }
2230
+ if (provider === "gateway-string") return {
2231
+ provider,
2232
+ modelId,
2233
+ canonicalId: modelId.toLowerCase(),
2234
+ providerKey: "(default)"
2235
+ };
2236
+ const canonicalId = `${provider.split(".")[0] || "(default)"}/${modelId}`.toLowerCase();
2237
+ const slash = canonicalId.indexOf("/");
2238
+ return {
2239
+ provider,
2240
+ modelId,
2241
+ canonicalId,
2242
+ providerKey: canonicalId.slice(0, slash)
2243
+ };
2244
+ }
2245
+ /**
2246
+ * Computes the served `ModelIdentity` from `finalStep.response.modelId` (§8.2).
2247
+ */
2248
+ function toServedIdentity(requested, servedModelId) {
2249
+ if (typeof servedModelId !== "string" || servedModelId.length === 0) return null;
2250
+ if (isGatewayProvider(requested.provider) && hasNonEmptySlashParts(servedModelId)) {
2251
+ const canonicalId = servedModelId.toLowerCase();
2252
+ const providerKey = canonicalId.slice(0, canonicalId.indexOf("/"));
2253
+ return {
2254
+ provider: providerKey,
2255
+ modelId: servedModelId,
2256
+ canonicalId,
2257
+ providerKey
2258
+ };
2259
+ }
2260
+ const canonicalId = `${requested.providerKey}/${servedModelId}`.toLowerCase();
2261
+ return {
2262
+ provider: requested.providerKey,
2263
+ modelId: servedModelId,
2264
+ canonicalId,
2265
+ providerKey: requested.providerKey
2266
+ };
2267
+ }
2268
+ function normalizeAuthorModels(raw) {
2269
+ const normalized = [];
2270
+ for (let i = 0; i < raw.length; i++) {
2271
+ const entry = raw[i];
2272
+ if (typeof entry !== "string") throw new DissentArgumentError("invalid-author-model", `provenance.authorModels[${i}]`);
2273
+ const trimmed = entry.trim().toLowerCase();
2274
+ const parts = trimmed.split("/");
2275
+ if (parts.length !== 2 || parts[0].length === 0 || parts[1].length === 0) throw new DissentArgumentError("invalid-author-model", `provenance.authorModels[${i}]`, `Invalid authorModel "${entry}": expected "provider/modelId".`);
2276
+ normalized.push(trimmed);
2277
+ }
2278
+ return sortWith(normalized, compareUtf16);
2279
+ }
2280
+ function isAbortSignalLike(signal) {
2281
+ if (typeof signal !== "object" || signal === null) return false;
2282
+ const s = signal;
2283
+ return typeof s.aborted === "boolean" && typeof s.addEventListener === "function" && typeof s.removeEventListener === "function";
2284
+ }
2285
+ function validateIntegerRange(value, defaultValue, min, max, argument) {
2286
+ if (value === void 0) return defaultValue;
2287
+ if (!Number.isInteger(value) || value < min || value > max) throw new DissentArgumentError("invalid-option", argument, `${argument} must be an integer between ${min} and ${max}.`);
2288
+ return value;
2289
+ }
2290
+ /**
2291
+ * Validates and normalizes `corroborate` options synchronously before any model call (§2.2.1 step 1).
2292
+ */
2293
+ function normalizeAndValidateOptions(options) {
2294
+ if (typeof options !== "object" || options === null || Array.isArray(options)) throw new DissentArgumentError("invalid-option", "options");
2295
+ const rawWitnesses = options.witnesses;
2296
+ if (typeof rawWitnesses !== "object" || rawWitnesses === null || Array.isArray(rawWitnesses)) throw new DissentArgumentError("invalid-option", "witnesses");
2297
+ const rawKeys = Object.keys(rawWitnesses);
2298
+ for (const label of rawKeys) {
2299
+ if (RESERVED_LABELS.has(label.toLowerCase())) throw new DissentArgumentError("reserved-label", `witnesses.${label}`);
2300
+ if (!LABEL_RE.test(label)) throw new DissentArgumentError("invalid-label", `witnesses.${label}`);
2301
+ }
2302
+ if (rawKeys.length < 2) throw new DissentArgumentError("too-few-witnesses", "witnesses");
2303
+ if (rawKeys.length > 16) throw new DissentArgumentError("too-many-witnesses", "witnesses");
2304
+ const sortedLabels = sortLabels(rawKeys);
2305
+ const witnesses = [];
2306
+ for (const label of sortedLabels) {
2307
+ const entry = ownValue(rawWitnesses, label);
2308
+ let model;
2309
+ let settings;
2310
+ if (isWitnessWrapper(entry)) {
2311
+ model = entry.model;
2312
+ const rawSettings = ownValue(entry, "settings");
2313
+ if (rawSettings !== void 0) {
2314
+ if (!isPlainObject(rawSettings)) throw new DissentArgumentError("invalid-witness-entry", `witnesses.${label}.settings`);
2315
+ settings = rawSettings;
2316
+ }
2317
+ } else model = entry;
2318
+ if (!isValidLanguageModel(model)) throw new DissentArgumentError("invalid-witness-entry", `witnesses.${label}`);
2319
+ witnesses.push({
2320
+ label,
2321
+ model,
2322
+ settings,
2323
+ requested: toRequestedIdentity(model)
2324
+ });
2325
+ }
2326
+ const hasPrompt = options.prompt !== void 0;
2327
+ const hasMessages = options.messages !== void 0;
2328
+ if (hasPrompt && hasMessages) throw new DissentArgumentError("prompt-and-messages", "prompt");
2329
+ if (!hasPrompt && !hasMessages) throw new DissentArgumentError("no-input", "prompt");
2330
+ const rawSchema = options.schema;
2331
+ if (rawSchema === null || rawSchema === void 0 || typeof rawSchema !== "object" && typeof rawSchema !== "function") throw new DissentArgumentError("invalid-option", "schema");
2332
+ let authorModels = [];
2333
+ let excludeAuthor = false;
2334
+ if (options.provenance !== void 0) {
2335
+ const prov = options.provenance;
2336
+ if (!isPlainObject(prov) || !Array.isArray(prov.authorModels)) throw new DissentArgumentError("invalid-option", "provenance");
2337
+ authorModels = normalizeAuthorModels(prov.authorModels);
2338
+ if (prov.excludeAuthor !== void 0 && typeof prov.excludeAuthor !== "boolean") throw new DissentArgumentError("invalid-option", "provenance.excludeAuthor");
2339
+ excludeAuthor = prov.excludeAuthor === true;
2340
+ if (excludeAuthor && authorModels.length === 0) throw new DissentArgumentError("exclude-without-authors", "provenance.excludeAuthor");
2341
+ }
2342
+ const lineEndings = options.lineEndings ?? "normalize-for-hash";
2343
+ if (lineEndings !== "normalize-for-hash" && lineEndings !== "preserve") throw new DissentArgumentError("invalid-option", "lineEndings");
2344
+ const includeInput = options.includeInput ?? "hash";
2345
+ if (includeInput !== "hash" && includeInput !== "full") throw new DissentArgumentError("invalid-option", "includeInput");
2346
+ if (options.strictCoverage !== void 0 && typeof options.strictCoverage !== "boolean") throw new DissentArgumentError("invalid-option", "strictCoverage");
2347
+ if (options.onWitness !== void 0 && typeof options.onWitness !== "function") throw new DissentArgumentError("invalid-option", "onWitness");
2348
+ if (options.abortSignal !== void 0 && !isAbortSignalLike(options.abortSignal)) throw new DissentArgumentError("invalid-option", "abortSignal");
2349
+ const maxConcurrency = validateIntegerRange(options.maxConcurrency, 8, 1, 16, "maxConcurrency");
2350
+ const maxOutputBytes = validateIntegerRange(options.maxOutputBytes, DEFAULT_MAX_OUTPUT_BYTES, 1024, 67108864, "maxOutputBytes");
2351
+ const maxErrorTextBytes = validateIntegerRange(options.maxErrorTextBytes, DEFAULT_MAX_ERROR_TEXT_BYTES, 256, 65536, "maxErrorTextBytes");
2352
+ return {
2353
+ witnesses,
2354
+ authorModels,
2355
+ excludeAuthor,
2356
+ lineEndings,
2357
+ includeInput,
2358
+ strictCoverage: options.strictCoverage === true,
2359
+ maxConcurrency,
2360
+ maxOutputBytes,
2361
+ maxErrorTextBytes
2362
+ };
2363
+ }
2364
+ // src/witness/independence.ts
2365
+ function identityMatchesAuthor(identity, authorModel) {
2366
+ if (identity.canonicalId === authorModel) return true;
2367
+ return hasNonEmptySlashParts(identity.modelId) && identity.modelId.toLowerCase() === authorModel;
2368
+ }
2369
+ /**
2370
+ * Matches a witness against sorted normalized `authorModels` (§8.2).
2371
+ * `requested` takes priority over `served`; earliest UTF-16 author model wins ties.
2372
+ */
2373
+ function matchAuthorModel(requested, served, sortedAuthorModels) {
2374
+ for (const authorModel of sortedAuthorModels) if (identityMatchesAuthor(requested, authorModel)) return {
2375
+ authorModel,
2376
+ on: "requested"
2377
+ };
2378
+ if (served !== null) {
2379
+ for (const authorModel of sortedAuthorModels) if (identityMatchesAuthor(served, authorModel)) return {
2380
+ authorModel,
2381
+ on: "served"
2382
+ };
2383
+ }
2384
+ return null;
2385
+ }
2386
+ /**
2387
+ * Computes the §8.4 `Independence` block and the Layer A witness/independence findings (§9.1).
2388
+ * Expects `entries` ordered by UTF-16 sorted label.
2389
+ */
2390
+ function analyzeIndependence(entries, sortedAuthorModels) {
2391
+ const providerGroups = /* @__PURE__ */ new Map();
2392
+ const servedGroups = /* @__PURE__ */ new Map();
2393
+ const selfGradingWitnesses = [];
2394
+ const excludedWitnesses = [];
2395
+ const witnessFindings = [];
2396
+ let asked = 0;
2397
+ for (const { label, record } of entries) {
2398
+ if (!(record.status === "excluded" && record.stage === "before-dispatch")) {
2399
+ asked++;
2400
+ const pk = record.requested.providerKey;
2401
+ const group = providerGroups.get(pk);
2402
+ if (group === void 0) providerGroups.set(pk, [label]);
2403
+ else group.push(label);
2404
+ }
2405
+ if (record.status === "answered" && record.served !== null) {
2406
+ const cid = record.served.canonicalId;
2407
+ const group = servedGroups.get(cid);
2408
+ if (group === void 0) servedGroups.set(cid, [label]);
2409
+ else group.push(label);
2410
+ }
2411
+ const servedForMatch = record.status === "excluded" && record.stage === "before-dispatch" ? null : record.served;
2412
+ const match = matchAuthorModel(record.requested, servedForMatch, sortedAuthorModels);
2413
+ if (match !== null) {
2414
+ selfGradingWitnesses.push({
2415
+ witness: label,
2416
+ authorModel: match.authorModel,
2417
+ on: match.on
2418
+ });
2419
+ if (record.status === "answered") witnessFindings.push({
2420
+ code: "self-grading",
2421
+ severity: "warn",
2422
+ witnesses: [label],
2423
+ data: {
2424
+ authorModel: match.authorModel,
2425
+ on: match.on
2426
+ }
2427
+ });
2428
+ }
2429
+ if (record.status === "excluded") {
2430
+ excludedWitnesses.push({
2431
+ witness: label,
2432
+ stage: record.stage,
2433
+ authorModel: record.match.authorModel,
2434
+ on: record.match.on
2435
+ });
2436
+ witnessFindings.push({
2437
+ code: "witness-excluded",
2438
+ severity: "info",
2439
+ witnesses: [label],
2440
+ data: {
2441
+ stage: record.stage,
2442
+ authorModel: record.match.authorModel,
2443
+ on: record.match.on
2444
+ }
2445
+ });
2446
+ } else if (record.status === "failed") witnessFindings.push({
2447
+ code: "witness-failed",
2448
+ severity: "warn",
2449
+ witnesses: [label],
2450
+ data: { kind: record.error.kind }
2451
+ });
2452
+ else if (record.finishReason === "length") witnessFindings.push({
2453
+ code: "truncated-output",
2454
+ severity: "info",
2455
+ witnesses: [label]
2456
+ });
2457
+ }
2458
+ const duplicateServedModels = sortWith(Array.from(servedGroups.entries()).filter(([, labels]) => labels.length >= 2).map(([canonicalId, witnesses]) => ({
2459
+ canonicalId,
2460
+ witnesses
2461
+ })), (a, b) => compareUtf16(a.canonicalId, b.canonicalId));
2462
+ for (const group of duplicateServedModels) witnessFindings.push({
2463
+ code: "duplicate-served-model",
2464
+ severity: "warn",
2465
+ witnesses: [...group.witnesses],
2466
+ data: { canonicalId: group.canonicalId }
2467
+ });
2468
+ const sameProviderGroups = sortWith(Array.from(providerGroups.entries()).filter(([, labels]) => labels.length >= 2).map(([providerKey, witnesses]) => ({
2469
+ providerKey,
2470
+ witnesses
2471
+ })), (a, b) => compareUtf16(a.providerKey, b.providerKey));
2472
+ const uniqueRequestedProviders = providerGroups.size;
2473
+ if (asked >= 2 && uniqueRequestedProviders === 1) {
2474
+ const onlyProviderKey = providerGroups.keys().next().value;
2475
+ if (onlyProviderKey !== void 0 && onlyProviderKey !== "(default)") witnessFindings.push({
2476
+ code: "single-provider",
2477
+ severity: "warn",
2478
+ data: { providerKey: onlyProviderKey }
2479
+ });
2480
+ }
2481
+ return {
2482
+ independence: {
2483
+ uniqueRequestedProviders,
2484
+ duplicateServedModels,
2485
+ sameProviderGroups,
2486
+ selfGradingWitnesses,
2487
+ excludedWitnesses
2488
+ },
2489
+ witnessFindings
2490
+ };
2491
+ }
2492
+ // src/corroborate.ts
2493
+ const USAGE_KEYS = [
2494
+ "inputTokens",
2495
+ "outputTokens",
2496
+ "totalTokens",
2497
+ "cacheReadTokens",
2498
+ "cacheWriteTokens",
2499
+ "reasoningTokens"
2500
+ ];
2501
+ async function buildQuestion(options, normalized, resolvedSchema) {
2502
+ const normalize = normalized.lineEndings === "normalize-for-hash";
2503
+ const lineEndingsRecord = normalize ? "normalized-for-hash" : "preserved";
2504
+ const inputKind = options.prompt !== void 0 ? "prompt" : "messages";
2505
+ const rawInput = inputKind === "prompt" ? options.prompt : options.messages;
2506
+ const hashedInput = await hashForm(rawInput, normalize, inputKind);
2507
+ const inputCanon = canonicalJson(hashedInput);
2508
+ const inputBytes = utf8ByteLength(inputCanon);
2509
+ const inputHash = await sha256Hex(inputCanon);
2510
+ const instructionsHash = options.instructions !== void 0 ? await sha256Hex(canonicalJson(await hashForm(options.instructions, normalize, "instructions"))) : null;
2511
+ const schemaObj = { jsonSchema: resolvedSchema };
2512
+ if (options.schemaName !== void 0) schemaObj.name = options.schemaName;
2513
+ if (options.schemaDescription !== void 0) schemaObj.description = options.schemaDescription;
2514
+ const schemaHash = await sha256Hex(canonicalJson(schemaObj));
2515
+ const question = {
2516
+ fingerprint: await sha256Hex(canonicalJson({
2517
+ protocol: "dissent-question/1",
2518
+ inputKind,
2519
+ inputHash,
2520
+ instructionsHash,
2521
+ schemaHash,
2522
+ lineEndings: lineEndingsRecord
2523
+ })),
2524
+ inputKind,
2525
+ inputHash,
2526
+ instructionsHash,
2527
+ schemaHash,
2528
+ inputBytes,
2529
+ lineEndings: lineEndingsRecord
2530
+ };
2531
+ if (normalized.includeInput === "full") {
2532
+ const raw = {};
2533
+ if (options.instructions !== void 0) raw.instructions = await hashForm(options.instructions, false, "instructions");
2534
+ const rawPreserved = normalize ? await hashForm(rawInput, false, inputKind) : hashedInput;
2535
+ if (inputKind === "prompt") raw.prompt = rawPreserved;
2536
+ else raw.messages = rawPreserved;
2537
+ question.raw = raw;
2538
+ }
2539
+ return { question };
2540
+ }
2541
+ function buildGenerateTextParams(witness, options, outputSpec, abortSignal) {
2542
+ const params = {};
2543
+ const settings = witness.settings;
2544
+ if (settings !== void 0) for (const key of Object.keys(settings)) {
2545
+ if (key === "timeout" || key === "maxRetries" || key === "headers" || key === "providerOptions" || key === "abortSignal" || key === "model" || key === "prompt" || key === "messages" || key === "instructions" || key === "output" || key === "telemetry") continue;
2546
+ const val = settings[key];
2547
+ if (val !== void 0) params[key] = val;
2548
+ }
2549
+ const timeout = settings?.timeout ?? options.timeout;
2550
+ if (timeout !== void 0) params.timeout = timeout;
2551
+ const maxRetries = settings?.maxRetries ?? options.maxRetries;
2552
+ if (maxRetries !== void 0) params.maxRetries = maxRetries;
2553
+ const headers = settings?.headers ?? options.headers;
2554
+ if (headers !== void 0) params.headers = headers;
2555
+ const providerOptions = settings?.providerOptions ?? options.providerOptions;
2556
+ if (providerOptions !== void 0) params.providerOptions = providerOptions;
2557
+ if (options.telemetry !== void 0) params.telemetry = options.telemetry;
2558
+ if (options.instructions !== void 0) params.instructions = options.instructions;
2559
+ if (options.prompt !== void 0) params.prompt = options.prompt;
2560
+ else if (options.messages !== void 0) params.messages = options.messages;
2561
+ params.model = witness.model;
2562
+ params.output = outputSpec;
2563
+ params.abortSignal = abortSignal;
2564
+ return params;
2565
+ }
2566
+ function sumUsage(labels, records) {
2567
+ const total = {
2568
+ inputTokens: null,
2569
+ outputTokens: null,
2570
+ totalTokens: null,
2571
+ cacheReadTokens: null,
2572
+ cacheWriteTokens: null,
2573
+ reasoningTokens: null
2574
+ };
2575
+ for (const key of USAGE_KEYS) {
2576
+ let sum = 0;
2577
+ let count = 0;
2578
+ for (const label of labels) {
2579
+ const val = records.get(label)?.usage?.[key];
2580
+ if (typeof val === "number") {
2581
+ sum += val;
2582
+ count++;
2583
+ }
2584
+ }
2585
+ if (count > 0) total[key] = sum;
2586
+ }
2587
+ return total;
2588
+ }
2589
+ function witnessFingerprintPart(record) {
2590
+ if (record.status === "answered") return {
2591
+ status: "answered",
2592
+ requested: record.requested.canonicalId,
2593
+ served: record.served?.canonicalId ?? null,
2594
+ output: record.output
2595
+ };
2596
+ if (record.status === "failed") return {
2597
+ status: "failed",
2598
+ requested: record.requested.canonicalId,
2599
+ served: record.served?.canonicalId ?? null,
2600
+ kind: record.error.kind
2601
+ };
2602
+ return {
2603
+ status: "excluded",
2604
+ requested: record.requested.canonicalId,
2605
+ stage: record.stage
2606
+ };
2607
+ }
2608
+ /**
2609
+ * Runs one multi-model corroboration session over AI SDK v7 models (§2.2).
2610
+ */
2611
+ async function corroborate(options) {
2612
+ return corroborateWithHooks(options);
2613
+ }
2614
+ /**
2615
+ * Internal entry point supporting comparator injection for fingerprint-scope tests (I3c).
2616
+ * Never exported from the package root.
2617
+ */
2618
+ async function corroborateWithHooks(options, hooks) {
2619
+ const normalized = normalizeAndValidateOptions(options);
2620
+ if (options.abortSignal?.aborted) throw options.abortSignal.reason;
2621
+ let resolvedSchema;
2622
+ try {
2623
+ resolvedSchema = await asSchema(options.schema).jsonSchema;
2624
+ } catch (err) {
2625
+ if (options.abortSignal?.aborted) throw options.abortSignal.reason;
2626
+ throw new DissentArgumentError("invalid-option", "schema", err instanceof Error ? err.message : void 0);
2627
+ }
2628
+ if (options.abortSignal?.aborted) throw options.abortSignal.reason;
2629
+ const plan = await derivePlan(resolvedSchema, options.compare);
2630
+ if (options.abortSignal?.aborted) throw options.abortSignal.reason;
2631
+ const { question } = await buildQuestion(options, normalized, resolvedSchema);
2632
+ if (options.abortSignal?.aborted) throw options.abortSignal.reason;
2633
+ const recordMap = /* @__PURE__ */ new Map();
2634
+ const askedWitnesses = [];
2635
+ const preExcludedWitnesses = [];
2636
+ for (const witness of normalized.witnesses) {
2637
+ if (normalized.excludeAuthor) {
2638
+ const match = matchAuthorModel(witness.requested, null, normalized.authorModels);
2639
+ if (match !== null) {
2640
+ const record = {
2641
+ status: "excluded",
2642
+ stage: "before-dispatch",
2643
+ match,
2644
+ requested: witness.requested,
2645
+ served: null,
2646
+ durationMs: 0,
2647
+ usage: null
2648
+ };
2649
+ recordMap.set(witness.label, record);
2650
+ preExcludedWitnesses.push({
2651
+ label: witness.label,
2652
+ record
2653
+ });
2654
+ continue;
2655
+ }
2656
+ }
2657
+ askedWitnesses.push(witness);
2658
+ }
2659
+ if (askedWitnesses.length < 2) throw new DissentArgumentError("too-few-witnesses-after-exclusion", "witnesses", `Only ${askedWitnesses.length} witness(es) remain after author exclusion; at least 2 are required.`);
2660
+ const outputSpec = Output.object({
2661
+ schema: options.schema,
2662
+ ...options.schemaName !== void 0 ? { name: options.schemaName } : {},
2663
+ ...options.schemaDescription !== void 0 ? { description: options.schemaDescription } : {}
2664
+ });
2665
+ const internalController = new AbortController();
2666
+ const callerSignal = options.abortSignal;
2667
+ const callSignal = callerSignal !== void 0 ? AbortSignal.any([callerSignal, internalController.signal]) : internalController.signal;
2668
+ let terminated = false;
2669
+ let rejectControl;
2670
+ const controlPromise = new Promise((_resolve, reject) => {
2671
+ rejectControl = reject;
2672
+ });
2673
+ controlPromise.catch(() => {});
2674
+ const onCallerAbort = () => {
2675
+ if (terminated) return;
2676
+ terminated = true;
2677
+ const reason = callerSignal?.reason;
2678
+ internalController.abort(reason);
2679
+ rejectControl(reason);
2680
+ };
2681
+ if (callerSignal !== void 0) {
2682
+ if (callerSignal.aborted) throw callerSignal.reason;
2683
+ callerSignal.addEventListener("abort", onCallerAbort, { once: true });
2684
+ }
2685
+ const notifyWitness = (label, record) => {
2686
+ if (terminated || callerSignal?.aborted || options.onWitness === void 0) return;
2687
+ try {
2688
+ options.onWitness(label, record);
2689
+ } catch (callbackErr) {
2690
+ if (!terminated) {
2691
+ terminated = true;
2692
+ internalController.abort(callbackErr);
2693
+ rejectControl(callbackErr);
2694
+ }
2695
+ }
2696
+ };
2697
+ for (const pre of preExcludedWitnesses) {
2698
+ if (terminated) break;
2699
+ notifyWitness(pre.label, pre.record);
2700
+ }
2701
+ const runWitness = async (witness) => {
2702
+ if (terminated || callerSignal?.aborted) return;
2703
+ const startMs = performance.now();
2704
+ let result;
2705
+ let record;
2706
+ try {
2707
+ const params = buildGenerateTextParams(witness, options, outputSpec, callSignal);
2708
+ hooks?.onGenerateTextParams?.(params);
2709
+ result = await generateText(params);
2710
+ const obtained = result;
2711
+ const rawOutput = obtained.output;
2712
+ const finishReason = obtained.finishReason;
2713
+ const usage = mapUsage(obtained.usage) ?? {
2714
+ inputTokens: null,
2715
+ outputTokens: null,
2716
+ totalTokens: null,
2717
+ cacheReadTokens: null,
2718
+ cacheWriteTokens: null,
2719
+ reasoningTokens: null
2720
+ };
2721
+ const warnings = sanitizeWarnings(obtained.warnings, normalized.maxErrorTextBytes);
2722
+ const served = toServedIdentity(witness.requested, obtained.finalStep?.response?.modelId);
2723
+ const canon = canonicalJson(rawOutput);
2724
+ const byteLen = utf8ByteLength(canon);
2725
+ if (byteLen > normalized.maxOutputBytes) throw new OutputTooLargeError(byteLen, normalized.maxOutputBytes);
2726
+ const cleanOutput = JSON.parse(canon);
2727
+ if (!isPlainObject(cleanOutput)) throw new NoObjectGeneratedError({
2728
+ message: "Generated output must be a JSON object.",
2729
+ text: canon,
2730
+ response: {
2731
+ id: "",
2732
+ timestamp: /* @__PURE__ */ new Date(0),
2733
+ modelId: obtained.finalStep?.response?.modelId ?? witness.requested.modelId
2734
+ },
2735
+ usage: obtained.usage,
2736
+ finishReason
2737
+ });
2738
+ const durationMs = Math.max(0, Math.round(performance.now() - startMs));
2739
+ if (normalized.excludeAuthor && served !== null) {
2740
+ const postMatch = matchAuthorModel(witness.requested, served, normalized.authorModels);
2741
+ if (postMatch !== null) {
2742
+ record = {
2743
+ status: "excluded",
2744
+ stage: "after-response",
2745
+ match: postMatch,
2746
+ requested: witness.requested,
2747
+ served,
2748
+ durationMs,
2749
+ output: cleanOutput,
2750
+ usage
2751
+ };
2752
+ recordMap.set(witness.label, record);
2753
+ notifyWitness(witness.label, record);
2754
+ return;
2755
+ }
2756
+ }
2757
+ record = {
2758
+ status: "answered",
2759
+ requested: witness.requested,
2760
+ served,
2761
+ durationMs,
2762
+ output: cleanOutput,
2763
+ finishReason,
2764
+ usage,
2765
+ warnings
2766
+ };
2767
+ } catch (caught) {
2768
+ if (terminated || callerSignal?.aborted) return;
2769
+ const durationMs = Math.max(0, Math.round(performance.now() - startMs));
2770
+ const partialResult = result;
2771
+ const errorObj = classifyWitnessError(caught, partialResult !== void 0 ? {
2772
+ finishReason: partialResult.finishReason,
2773
+ usage: partialResult.usage
2774
+ } : void 0, normalized.maxErrorTextBytes);
2775
+ const served = partialResult !== void 0 ? toServedIdentity(witness.requested, partialResult.finalStep?.response?.modelId) : null;
2776
+ let usage = null;
2777
+ if (partialResult !== void 0) usage = mapUsage(partialResult.usage);
2778
+ else if (typeof caught === "object" && caught !== null && "usage" in caught) usage = mapUsage(caught.usage);
2779
+ record = {
2780
+ status: "failed",
2781
+ requested: witness.requested,
2782
+ served,
2783
+ durationMs,
2784
+ error: errorObj,
2785
+ usage
2786
+ };
2787
+ }
2788
+ if (terminated || callerSignal?.aborted) return;
2789
+ recordMap.set(witness.label, record);
2790
+ notifyWitness(witness.label, record);
2791
+ };
2792
+ let nextIdx = 0;
2793
+ const workerCount = Math.min(normalized.maxConcurrency, askedWitnesses.length);
2794
+ const workers = Array.from({ length: workerCount }, async () => {
2795
+ while (nextIdx < askedWitnesses.length) {
2796
+ if (terminated || callerSignal?.aborted) return;
2797
+ const idx = nextIdx;
2798
+ nextIdx++;
2799
+ await runWitness(askedWitnesses[idx]);
2800
+ }
2801
+ });
2802
+ const allWorkers = Promise.all(workers);
2803
+ allWorkers.catch(() => {});
2804
+ try {
2805
+ await Promise.race([allWorkers, controlPromise]);
2806
+ } finally {
2807
+ if (callerSignal !== void 0) callerSignal.removeEventListener("abort", onCallerAbort);
2808
+ }
2809
+ if (callerSignal?.aborted) throw callerSignal.reason;
2810
+ const sortedLabels = normalized.witnesses.map((w) => w.label);
2811
+ const witnessEntries = [];
2812
+ const witnessList = [];
2813
+ const answeredOutputs = [];
2814
+ const usageEntries = [];
2815
+ const witnessFpEntries = [];
2816
+ let answered = 0;
2817
+ let failed = 0;
2818
+ let excluded = 0;
2819
+ for (const label of sortedLabels) {
2820
+ const rec = recordMap.get(label);
2821
+ witnessEntries.push([label, rec]);
2822
+ witnessList.push({
2823
+ label,
2824
+ record: rec
2825
+ });
2826
+ usageEntries.push([label, rec.usage]);
2827
+ witnessFpEntries.push([label, witnessFingerprintPart(rec)]);
2828
+ if (rec.status === "answered") {
2829
+ answered++;
2830
+ answeredOutputs.push({
2831
+ witness: label,
2832
+ output: rec.output
2833
+ });
2834
+ } else if (rec.status === "failed") failed++;
2835
+ else excluded++;
2836
+ }
2837
+ const quorum = {
2838
+ listed: sortedLabels.length,
2839
+ asked: askedWitnesses.length,
2840
+ answered,
2841
+ failed,
2842
+ excluded
2843
+ };
2844
+ const fields = (hooks?.compareFields ?? compareFields)(plan.fields, answeredOutputs);
2845
+ const coverage = computeCoverage(plan.fields, fields);
2846
+ const { independence, witnessFindings } = analyzeIndependence(witnessList, normalized.authorModels);
2847
+ const comparisonFindings = collectComparisonFindings({
2848
+ answered: quorum.answered,
2849
+ planFields: plan.fields,
2850
+ fieldResults: fields,
2851
+ coverage,
2852
+ strictCoverage: normalized.strictCoverage
2853
+ });
2854
+ const findings = sortFindings([...witnessFindings, ...comparisonFindings]);
2855
+ const advisory = computeAdvisory(findings);
2856
+ return {
2857
+ protocol: "dissent-ledger/1",
2858
+ fingerprint: await sha256Hex(canonicalJson({
2859
+ protocol: "dissent-ledger/1",
2860
+ question: question.fingerprint,
2861
+ plan: plan.fingerprint,
2862
+ witnesses: toSortedNullProtoRecord(witnessFpEntries)
2863
+ })),
2864
+ question,
2865
+ plan,
2866
+ witnesses: toSortedNullProtoRecord(witnessEntries),
2867
+ quorum,
2868
+ independence,
2869
+ fields,
2870
+ coverage,
2871
+ findings,
2872
+ advisory,
2873
+ usage: {
2874
+ perWitness: toSortedNullProtoRecord(usageEntries),
2875
+ total: sumUsage(sortedLabels, recordMap)
2876
+ },
2877
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
2878
+ };
2879
+ }
2880
+ // src/receipt.ts
2881
+ const REQUIRED_STRING_FIELDS = [
2882
+ "provider",
2883
+ "profile",
2884
+ "runtimeImageDigest",
2885
+ "networkPolicySha256",
2886
+ "receiptId",
2887
+ "region"
2888
+ ];
2889
+ /**
2890
+ * Validates an experimental offline execution environment receipt (§10.5).
2891
+ * Pure, never throws.
2892
+ *
2893
+ * @experimental Can change in a minor release until the v0.3 sandbox producer exists.
2894
+ */
2895
+ function validateOfflineReceipt(receipt, expected) {
2896
+ if (!isPlainObject(receipt)) return {
2897
+ valid: false,
2898
+ reason: "malformed"
2899
+ };
2900
+ for (const field of REQUIRED_STRING_FIELDS) {
2901
+ if (!Object.hasOwn(receipt, field)) return {
2902
+ valid: false,
2903
+ reason: "malformed"
2904
+ };
2905
+ const val = ownValue(receipt, field);
2906
+ if (typeof val !== "string" || val === "") return {
2907
+ valid: false,
2908
+ reason: "malformed"
2909
+ };
2910
+ }
2911
+ if (!Object.hasOwn(receipt, "networkPolicyEnforced")) return {
2912
+ valid: false,
2913
+ reason: "malformed"
2914
+ };
2915
+ const networkPolicyEnforced = ownValue(receipt, "networkPolicyEnforced");
2916
+ if (typeof networkPolicyEnforced !== "boolean") return {
2917
+ valid: false,
2918
+ reason: "malformed"
2919
+ };
2920
+ if (ownValue(receipt, "profile") !== "offline-verification-v1") return {
2921
+ valid: false,
2922
+ reason: "wrong-profile"
2923
+ };
2924
+ if (networkPolicyEnforced !== true) return {
2925
+ valid: false,
2926
+ reason: "network-not-enforced"
2927
+ };
2928
+ if (isPlainObject(expected)) {
2929
+ const expectedPolicy = ownValue(expected, "networkPolicySha256");
2930
+ if (typeof expectedPolicy === "string" && ownValue(receipt, "networkPolicySha256") !== expectedPolicy) return {
2931
+ valid: false,
2932
+ reason: "policy-mismatch"
2933
+ };
2934
+ const expectedImage = ownValue(expected, "runtimeImageDigest");
2935
+ if (typeof expectedImage === "string" && ownValue(receipt, "runtimeImageDigest") !== expectedImage) return {
2936
+ valid: false,
2937
+ reason: "image-mismatch"
2938
+ };
2939
+ }
2940
+ return { valid: true };
2941
+ }
2942
+ /** Extracts a sanitized receipt ID string or null from an unchecked receipt candidate. */
2943
+ function readReceiptId(receipt) {
2944
+ if (!isPlainObject(receipt) || !Object.hasOwn(receipt, "receiptId")) return null;
2945
+ const raw = ownValue(receipt, "receiptId");
2946
+ if (typeof raw !== "string") return null;
2947
+ const clean = sanitizeInline(raw);
2948
+ return clean === "" ? null : clean;
2949
+ }
2950
+ // src/adjudicate.ts
2951
+ const OUTCOMES = /* @__PURE__ */ new Set([
2952
+ "pass",
2953
+ "fail",
2954
+ "error",
2955
+ "unknown"
2956
+ ]);
2957
+ const MAX_SOURCE_CHARS = 128;
2958
+ function assertJsonValue(value, argumentPath) {
2959
+ try {
2960
+ canonicalJson(value);
2961
+ } catch {
2962
+ throw new DissentArgumentError("invalid-evidence", argumentPath);
2963
+ }
2964
+ return normalizeJsonZeros(value);
2965
+ }
2966
+ const ALLOWED_ADJUDICATE_OPTIONS = /* @__PURE__ */ new Set(["escalateOnReview", "requireOfflineReceipt"]);
2967
+ const ALLOWED_RECEIPT_EXPECTED_KEYS = /* @__PURE__ */ new Set(["networkPolicySha256", "runtimeImageDigest"]);
2968
+ function validateAdjudicateOptions(options) {
2969
+ if (options === void 0) return {
2970
+ escalateOnReview: false,
2971
+ requireOfflineReceipt: false
2972
+ };
2973
+ if (!isPlainObject(options)) throw new DissentArgumentError("invalid-option", "options");
2974
+ for (const key of Object.keys(options)) if (!ALLOWED_ADJUDICATE_OPTIONS.has(key)) throw new DissentArgumentError("invalid-option", `options.${key}`);
2975
+ const escalate = ownValue(options, "escalateOnReview");
2976
+ if (escalate !== void 0 && typeof escalate !== "boolean") throw new DissentArgumentError("invalid-option", "escalateOnReview");
2977
+ const rawReq = ownValue(options, "requireOfflineReceipt");
2978
+ let requireOfflineReceipt = false;
2979
+ if (rawReq === true || rawReq === false || rawReq === void 0) requireOfflineReceipt = rawReq === true;
2980
+ else if (isPlainObject(rawReq)) {
2981
+ for (const key of Object.keys(rawReq)) if (!ALLOWED_RECEIPT_EXPECTED_KEYS.has(key)) throw new DissentArgumentError("invalid-option", `requireOfflineReceipt.${key}`);
2982
+ const normalized = {};
2983
+ const sha = ownValue(rawReq, "networkPolicySha256");
2984
+ if (sha !== void 0) {
2985
+ if (typeof sha !== "string") throw new DissentArgumentError("invalid-option", "requireOfflineReceipt.networkPolicySha256");
2986
+ normalized.networkPolicySha256 = sha;
2987
+ }
2988
+ const digest = ownValue(rawReq, "runtimeImageDigest");
2989
+ if (digest !== void 0) {
2990
+ if (typeof digest !== "string") throw new DissentArgumentError("invalid-option", "requireOfflineReceipt.runtimeImageDigest");
2991
+ normalized.runtimeImageDigest = digest;
2992
+ }
2993
+ requireOfflineReceipt = Object.keys(normalized).length === 0 ? true : normalized;
2994
+ } else throw new DissentArgumentError("invalid-option", "requireOfflineReceipt");
2995
+ return {
2996
+ escalateOnReview: escalate === true,
2997
+ requireOfflineReceipt
2998
+ };
2999
+ }
3000
+ function validateEvidenceItem(raw, index) {
3001
+ if (!isPlainObject(raw)) throw new DissentArgumentError("invalid-evidence", `evidence[${index}]`);
3002
+ const rawSource = ownValue(raw, "source");
3003
+ if (typeof rawSource !== "string") throw new DissentArgumentError("invalid-evidence", `evidence[${index}].source`);
3004
+ const source = redactSecrets(sanitizeInline(rawSource));
3005
+ if (source.trim().length === 0 || source.length > MAX_SOURCE_CHARS) throw new DissentArgumentError("invalid-evidence", `evidence[${index}].source`);
3006
+ const rawOutcome = ownValue(raw, "outcome");
3007
+ if (typeof rawOutcome !== "string" || !OUTCOMES.has(rawOutcome)) throw new DissentArgumentError("invalid-evidence", `evidence[${index}].outcome`);
3008
+ const outcome = rawOutcome;
3009
+ const forHash = {
3010
+ source,
3011
+ outcome
3012
+ };
3013
+ let claim;
3014
+ const rawClaim = ownValue(raw, "claim");
3015
+ if (rawClaim !== void 0) {
3016
+ if (!isPlainObject(rawClaim)) throw new DissentArgumentError("invalid-evidence", `evidence[${index}].claim`);
3017
+ const hasScope = Object.hasOwn(rawClaim, "scope");
3018
+ const hasPath = Object.hasOwn(rawClaim, "path");
3019
+ if (hasScope && !hasPath) {
3020
+ if (ownValue(rawClaim, "scope") !== "artifact") throw new DissentArgumentError("invalid-evidence", `evidence[${index}].claim.scope`);
3021
+ claim = { scope: "artifact" };
3022
+ forHash.claim = { scope: "artifact" };
3023
+ } else if (hasPath && !hasScope) {
3024
+ const rawPath = ownValue(rawClaim, "path");
3025
+ if (typeof rawPath !== "string") throw new DissentArgumentError("invalid-evidence", `evidence[${index}].claim.path`);
3026
+ let normalizedPath;
3027
+ try {
3028
+ normalizedPath = normalizePath(rawPath);
3029
+ parsePointer(normalizedPath);
3030
+ } catch {
3031
+ throw new DissentArgumentError("invalid-evidence", `evidence[${index}].claim.path`);
3032
+ }
3033
+ if (!Object.hasOwn(rawClaim, "value") || ownValue(rawClaim, "value") === void 0) throw new DissentArgumentError("invalid-evidence", `evidence[${index}].claim.value`);
3034
+ const value = assertJsonValue(ownValue(rawClaim, "value"), `evidence[${index}].claim.value`);
3035
+ claim = {
3036
+ path: normalizedPath,
3037
+ value
3038
+ };
3039
+ forHash.claim = {
3040
+ path: normalizedPath,
3041
+ value
3042
+ };
3043
+ } else throw new DissentArgumentError("invalid-evidence", `evidence[${index}].claim`);
3044
+ }
3045
+ const details = ownValue(raw, "details");
3046
+ if (details !== void 0) {
3047
+ if (!isPlainObject(details)) throw new DissentArgumentError("invalid-evidence", `evidence[${index}].details`);
3048
+ forHash.details = assertJsonValue(details, `evidence[${index}].details`);
3049
+ }
3050
+ const claims = ownValue(raw, "claims");
3051
+ if (claims !== void 0) {
3052
+ if (!isPlainObject(claims)) throw new DissentArgumentError("invalid-evidence", `evidence[${index}].claims`);
3053
+ forHash.claims = assertJsonValue(claims, `evidence[${index}].claims`);
3054
+ }
3055
+ const receipt = ownValue(raw, "receipt");
3056
+ if (receipt !== void 0) forHash.receipt = assertJsonValue(receipt, `evidence[${index}].receipt`);
3057
+ const out = {
3058
+ source,
3059
+ outcome,
3060
+ normalizedForHash: forHash
3061
+ };
3062
+ if (claim !== void 0) out.claim = claim;
3063
+ if (receipt !== void 0) out.receipt = receipt;
3064
+ return out;
3065
+ }
3066
+ function toCanonicalSet(values) {
3067
+ const out = /* @__PURE__ */ new Set();
3068
+ for (const v of values) out.add(canonicalJson(v));
3069
+ return out;
3070
+ }
3071
+ function buildKeyedMap(values, keyName) {
3072
+ if (!Array.isArray(values)) return null;
3073
+ const map = /* @__PURE__ */ new Map();
3074
+ for (const item of values) {
3075
+ if (!isPlainObject(item) || !Object.hasOwn(item, keyName)) return null;
3076
+ const keyVal = ownValue(item, keyName);
3077
+ if (keyVal === void 0) return null;
3078
+ const canonKey = canonicalJson(keyVal);
3079
+ if (map.has(canonKey)) return null;
3080
+ map.set(canonKey, canonicalJson(item));
3081
+ }
3082
+ return map;
3083
+ }
3084
+ function valuesMatchByPlan(plan, a, b) {
3085
+ switch (plan.comparator) {
3086
+ case "none": return false;
3087
+ case "exact":
3088
+ case "discriminated-union": return canonicalJson(a) === canonicalJson(b);
3089
+ case "tolerance":
3090
+ if (a === null && b === null) return true;
3091
+ if (typeof a === "number" && Number.isFinite(a) && typeof b === "number" && Number.isFinite(b)) return withinTolerance(a, b, plan.tolerance);
3092
+ return false;
3093
+ case "set": {
3094
+ if (a === null && b === null) return true;
3095
+ if (!Array.isArray(a) || !Array.isArray(b)) return false;
3096
+ const setA = toCanonicalSet(a);
3097
+ const setB = toCanonicalSet(b);
3098
+ if (setA.size !== setB.size) return false;
3099
+ for (const k of setA) if (!setB.has(k)) return false;
3100
+ return true;
3101
+ }
3102
+ case "keyed-set": {
3103
+ if (a === null && b === null) return true;
3104
+ const mapA = buildKeyedMap(a, plan.key);
3105
+ const mapB = buildKeyedMap(b, plan.key);
3106
+ if (mapA === null || mapB === null || mapA.size !== mapB.size) return false;
3107
+ for (const [k, v] of mapA) if (mapB.get(k) !== v) return false;
3108
+ return true;
3109
+ }
3110
+ }
3111
+ }
3112
+ function computeVerdict(counts, totalArtifact, escalateOnReview, advisory) {
3113
+ if (totalArtifact === 0) return {
3114
+ verdict: "uncertain",
3115
+ verdictReason: "no-artifact-evidence"
3116
+ };
3117
+ if (counts.fail > 0) return {
3118
+ verdict: "rejected",
3119
+ verdictReason: "artifact-evidence-failed"
3120
+ };
3121
+ if (counts.error > 0 || counts.unknown > 0) return {
3122
+ verdict: "uncertain",
3123
+ verdictReason: "artifact-evidence-inconclusive"
3124
+ };
3125
+ if (escalateOnReview && advisory === "review-required") return {
3126
+ verdict: "uncertain",
3127
+ verdictReason: "escalated-on-review"
3128
+ };
3129
+ return {
3130
+ verdict: "confirmed",
3131
+ verdictReason: "artifact-evidence-passed"
3132
+ };
3133
+ }
3134
+ /**
3135
+ * Pure Layer C adjudication: binds caller evidence to ledger fields (settlements, conflicts)
3136
+ * and computes the artifact verdict without calling any model (§10).
3137
+ */
3138
+ async function adjudicate(ledger, evidence, options) {
3139
+ if (!isPlainObject(ledger) || typeof ledger.fingerprint !== "string" || !isPlainObject(ledger.plan) || !isPlainObject(ledger.plan.fields) || !isPlainObject(ledger.witnesses)) throw new DissentArgumentError("invalid-option", "ledger");
3140
+ if (!Array.isArray(evidence)) throw new DissentArgumentError("invalid-evidence", "evidence");
3141
+ const resolvedOpts = validateAdjudicateOptions(options);
3142
+ const validated = evidence.map((item, i) => validateEvidenceItem(item, i));
3143
+ const allWitnesses = sortLabels(Object.keys(ledger.witnesses));
3144
+ const answeredPresenters = /* @__PURE__ */ new Map();
3145
+ for (const w of allWitnesses) {
3146
+ const rec = ownValue(ledger.witnesses, w);
3147
+ if (rec?.status === "answered") answeredPresenters.set(w, rec.output);
3148
+ }
3149
+ const settlements = [];
3150
+ const boundByPath = /* @__PURE__ */ new Map();
3151
+ const unbound = [];
3152
+ const receiptChecks = [];
3153
+ const artifactCounts = {
3154
+ pass: 0,
3155
+ fail: 0,
3156
+ error: 0,
3157
+ unknown: 0
3158
+ };
3159
+ let totalArtifact = 0;
3160
+ for (const item of validated) {
3161
+ if (item.claim === void 0) {
3162
+ unbound.push({
3163
+ source: item.source,
3164
+ outcome: item.outcome,
3165
+ reason: "no-claim"
3166
+ });
3167
+ continue;
3168
+ }
3169
+ if ("scope" in item.claim) {
3170
+ totalArtifact += 1;
3171
+ let effectiveOutcome = item.outcome;
3172
+ if (resolvedOpts.requireOfflineReceipt !== false) {
3173
+ const expected = resolvedOpts.requireOfflineReceipt === true ? void 0 : resolvedOpts.requireOfflineReceipt;
3174
+ const check = validateOfflineReceipt(item.receipt, expected);
3175
+ receiptChecks.push({
3176
+ source: item.source,
3177
+ receiptId: readReceiptId(item.receipt),
3178
+ check
3179
+ });
3180
+ if (!check.valid) effectiveOutcome = "unknown";
3181
+ }
3182
+ artifactCounts[effectiveOutcome] += 1;
3183
+ continue;
3184
+ }
3185
+ const { path, value } = item.claim;
3186
+ if (!Object.hasOwn(ledger.plan.fields, path)) {
3187
+ unbound.push({
3188
+ source: item.source,
3189
+ outcome: item.outcome,
3190
+ reason: "unknown-path"
3191
+ });
3192
+ continue;
3193
+ }
3194
+ const plan = ownValue(ledger.plan.fields, path);
3195
+ let pathBucket = boundByPath.get(path);
3196
+ if (pathBucket === void 0) {
3197
+ pathBucket = {
3198
+ plan,
3199
+ entries: []
3200
+ };
3201
+ boundByPath.set(path, pathBucket);
3202
+ }
3203
+ pathBucket.entries.push({
3204
+ source: item.source,
3205
+ outcome: item.outcome,
3206
+ value
3207
+ });
3208
+ if (plan.comparator === "none") {
3209
+ settlements.push({
3210
+ path,
3211
+ value,
3212
+ source: item.source,
3213
+ outcome: item.outcome,
3214
+ comparator: "not-comparable",
3215
+ witnessesAgreeing: [],
3216
+ witnessesDissenting: [],
3217
+ witnessesSilent: [...allWitnesses]
3218
+ });
3219
+ continue;
3220
+ }
3221
+ const witnessesAgreeing = [];
3222
+ const witnessesDissenting = [];
3223
+ const witnessesSilent = [];
3224
+ for (const w of allWitnesses) {
3225
+ const output = answeredPresenters.get(w);
3226
+ if (output === void 0) {
3227
+ witnessesSilent.push(w);
3228
+ continue;
3229
+ }
3230
+ const read = readByPointer(output, path);
3231
+ if (!read.present) {
3232
+ witnessesSilent.push(w);
3233
+ continue;
3234
+ }
3235
+ if (valuesMatchByPlan(plan, normalizeJsonZeros(read.value), value)) witnessesAgreeing.push(w);
3236
+ else witnessesDissenting.push(w);
3237
+ }
3238
+ settlements.push({
3239
+ path,
3240
+ value,
3241
+ source: item.source,
3242
+ outcome: item.outcome,
3243
+ comparator: plan.comparator,
3244
+ witnessesAgreeing,
3245
+ witnessesDissenting,
3246
+ witnessesSilent
3247
+ });
3248
+ }
3249
+ const conflicts = [];
3250
+ for (const path of sortLabels(Array.from(boundByPath.keys()))) {
3251
+ const { plan, entries } = boundByPath.get(path);
3252
+ if (plan.comparator === "none") continue;
3253
+ const involved = /* @__PURE__ */ new Set();
3254
+ for (let i = 0; i < entries.length; i++) {
3255
+ const a = entries[i];
3256
+ for (let j = i + 1; j < entries.length; j++) {
3257
+ const b = entries[j];
3258
+ const bothPass = a.outcome === "pass" && b.outcome === "pass";
3259
+ const passFail = a.outcome === "pass" && b.outcome === "fail" || a.outcome === "fail" && b.outcome === "pass";
3260
+ if (!bothPass && !passFail) continue;
3261
+ const match = valuesMatchByPlan(plan, a.value, b.value);
3262
+ if (bothPass && !match || passFail && match) {
3263
+ involved.add(a.source);
3264
+ involved.add(b.source);
3265
+ }
3266
+ }
3267
+ }
3268
+ if (involved.size > 0) conflicts.push({
3269
+ path,
3270
+ sources: sortLabels(Array.from(involved))
3271
+ });
3272
+ }
3273
+ const sortedSettlements = sortWith(settlements, (a, b) => {
3274
+ const pathCmp = compareUtf16(a.path, b.path);
3275
+ if (pathCmp !== 0) return pathCmp;
3276
+ const valCmp = compareUtf16(canonicalJson(a.value), canonicalJson(b.value));
3277
+ if (valCmp !== 0) return valCmp;
3278
+ const srcCmp = compareUtf16(a.source, b.source);
3279
+ if (srcCmp !== 0) return srcCmp;
3280
+ return compareUtf16(a.outcome, b.outcome);
3281
+ });
3282
+ const sortedUnbound = sortWith(unbound, (a, b) => {
3283
+ const srcCmp = compareUtf16(a.source, b.source);
3284
+ if (srcCmp !== 0) return srcCmp;
3285
+ const outCmp = compareUtf16(a.outcome, b.outcome);
3286
+ if (outCmp !== 0) return outCmp;
3287
+ return compareUtf16(a.reason, b.reason);
3288
+ });
3289
+ const sortedReceiptChecks = sortWith(receiptChecks, (a, b) => {
3290
+ const srcCmp = compareUtf16(a.source, b.source);
3291
+ if (srcCmp !== 0) return srcCmp;
3292
+ const idCmp = compareUtf16(a.receiptId ?? "", b.receiptId ?? "");
3293
+ if (idCmp !== 0) return idCmp;
3294
+ return compareUtf16(canonicalJson(a.check), canonicalJson(b.check));
3295
+ });
3296
+ const sortedEvidenceForHash = sortWith(validated.map((v) => ({
3297
+ canon: canonicalJson(v.normalizedForHash),
3298
+ item: v.normalizedForHash
3299
+ })), (a, b) => compareUtf16(a.canon, b.canon)).map((e) => e.item);
3300
+ const fingerprint = await sha256Hex(canonicalJson({
3301
+ protocol: "dissent-adjudication/1",
3302
+ ledgerFingerprint: ledger.fingerprint,
3303
+ evidence: sortedEvidenceForHash,
3304
+ options: resolvedOpts
3305
+ }));
3306
+ const { verdict, verdictReason } = computeVerdict(artifactCounts, totalArtifact, resolvedOpts.escalateOnReview, ledger.advisory);
3307
+ return {
3308
+ protocol: "dissent-adjudication/1",
3309
+ ledgerFingerprint: ledger.fingerprint,
3310
+ fingerprint,
3311
+ settlements: sortedSettlements,
3312
+ conflicts,
3313
+ verdict,
3314
+ verdictReason,
3315
+ artifactEvidence: artifactCounts,
3316
+ receiptChecks: sortedReceiptChecks,
3317
+ unbound: sortedUnbound
3318
+ };
3319
+ }
3320
+ // src/render/escape.ts
3321
+ const MARKDOWN_INLINE_SPECIAL_RE = /[\\`*_[\](){}#+\-.!|<>~]/g;
3322
+ /** Counts the longest consecutive run of backticks in `text`. */
3323
+ function longestBacktickRun(text) {
3324
+ let max = 0;
3325
+ for (const match of text.matchAll(/`+/g)) if (match[0].length > max) max = match[0].length;
3326
+ return max;
3327
+ }
3328
+ function collapseInline(text, maxInlineChars) {
3329
+ const clean = sanitizeInline(text);
3330
+ const cps = Array.from(clean);
3331
+ if (cps.length <= maxInlineChars) return clean;
3332
+ if (maxInlineChars <= 1) return maxInlineChars === 1 ? "…" : "";
3333
+ return `${cps.slice(0, maxInlineChars - 1).join("")}…`;
3334
+ }
3335
+ /**
3336
+ * Escapes untrusted text for Markdown inline contexts (§11.3 steps 1–3, Q2):
3337
+ * sanitize → inline collapse/truncate → if `@` is present, wrap in an inline
3338
+ * code span (since GitHub GFM links `&#64;user` as `@mentions`); otherwise
3339
+ * backslash-escape Markdown punctuation and replace `&` with `&amp;`.
3340
+ */
3341
+ function escapeMarkdownInline(text, maxInlineChars) {
3342
+ const collapsed = collapseInline(text, maxInlineChars);
3343
+ if (collapsed.includes("@")) return wrapMarkdownCodeSpan(collapsed);
3344
+ return collapsed.replace(MARKDOWN_INLINE_SPECIAL_RE, "\\$&").replaceAll("&", "&amp;");
3345
+ }
3346
+ /** Sanitizes and truncates untrusted text for ASCII inline lines (§11.3 steps 1–2). */
3347
+ function escapeAsciiInline(text, maxInlineChars) {
3348
+ return collapseInline(text, maxInlineChars);
3349
+ }
3350
+ function wrapMarkdownCodeSpan(body) {
3351
+ const fence = "`".repeat(longestBacktickRun(body) + 1);
3352
+ return `${fence}${(body.startsWith("`") || body.endsWith("`") ? ` ${body} ` : body).replaceAll("|", "\\|")}${fence}`;
3353
+ }
3354
+ /** Renders a JSON value as an inline Markdown code span safe inside GFM tables (§11.3 step 4). */
3355
+ function formatMarkdownValue(value, maxInlineChars) {
3356
+ return wrapMarkdownCodeSpan(collapseInline(canonicalJson(value), maxInlineChars));
3357
+ }
3358
+ /** Renders a JSON value for inline ASCII lines (§11.3 step 6). */
3359
+ function formatAsciiValue(value, maxInlineChars) {
3360
+ return collapseInline(canonicalJson(value), maxInlineChars);
3361
+ }
3362
+ function truncateBlock(text, maxBlockChars) {
3363
+ const clean = sanitizeControlChars(text);
3364
+ const cps = Array.from(clean);
3365
+ if (cps.length <= maxBlockChars) return clean;
3366
+ const remaining = cps.length - maxBlockChars;
3367
+ return `${cps.slice(0, maxBlockChars).join("")}\n… (truncated, ${remaining} more characters)`;
3368
+ }
3369
+ /** Renders an untrusted block inside a safe Markdown code fence with no info string (§11.3 step 5). */
3370
+ function formatMarkdownBlock(text, maxBlockChars) {
3371
+ const body = truncateBlock(text, maxBlockChars);
3372
+ const fence = "`".repeat(Math.max(3, longestBacktickRun(body) + 1));
3373
+ return `${fence}\n${body}\n${fence}`;
3374
+ }
3375
+ /** Renders an untrusted block indented by four spaces per line for ASCII (§11.3 step 6). */
3376
+ function formatAsciiBlock(text, maxBlockChars) {
3377
+ return truncateBlock(text, maxBlockChars).split("\n").map((line) => ` ${line}`).join("\n");
3378
+ }
3379
+ /** Formats the mandatory summary line (§11.1 item 2). */
3380
+ function formatSummaryLine(ledger) {
3381
+ const { quorum: q, coverage: c } = ledger;
3382
+ const pct = Math.round(c.ratio * 100);
3383
+ return `Advisory: ${sanitizeInline(ledger.advisory)} · Quorum: ${q.answered}/${q.listed} answered (${q.failed} failed, ${q.excluded} excluded) · Coverage: compared ${c.compared} of ${c.fields} fields (${pct}%)`;
3384
+ }
3385
+ /** Formats the detail/error/stage column for a witness record (§11.1 item 3). */
3386
+ function formatWitnessDetail(rec, escInline) {
3387
+ if (rec.status === "failed") return `${sanitizeInline(rec.error.kind)}: ${escInline(rec.error.message)}`;
3388
+ if (rec.status === "excluded") return `${sanitizeInline(rec.stage)} (${sanitizeInline(rec.match.on)}=${escInline(rec.match.authorModel)})`;
3389
+ return rec.finishReason === "length" ? "finish: length" : "—";
3390
+ }
3391
+ /**
3392
+ * Recovers raw non-array, non-null present values from answering witnesses when a `set`
3393
+ * or `keyed-set` field splits due to a scalar/object value (Handoff §0 P3-6).
3394
+ */
3395
+ function findNonArrayRawValues(ledger, path, res) {
3396
+ const nullSet = new Set(res.nulls);
3397
+ const extras = [];
3398
+ for (const w of res.presented) {
3399
+ if (nullSet.has(w)) continue;
3400
+ const rec = ownValue(ledger.witnesses, w);
3401
+ if (rec?.status !== "answered") continue;
3402
+ const read = readByPointer(rec.output, path);
3403
+ if (read.present && !Array.isArray(read.value) && read.value !== null) extras.push({
3404
+ witness: w,
3405
+ value: read.value
3406
+ });
3407
+ }
3408
+ return extras;
3409
+ }
3410
+ function summarizeExact(res, r) {
3411
+ const parts = res.groups.map((g) => `${r.value(g.value)} (${g.support}/${res.answered})`);
3412
+ const body = parts.length > 0 ? parts.join(", ") : "—";
3413
+ if (res.missing.length > 0) return `${body} · missing: ${res.missing.map(r.inline).join(", ")}`;
3414
+ return body;
3415
+ }
3416
+ function summarizeTolerance(res, r) {
3417
+ const parts = [];
3418
+ if (res.min !== void 0 && res.max !== void 0 && res.spread !== void 0) {
3419
+ const cleanSpread = Number(res.spread.toPrecision(12));
3420
+ parts.push(`${res.min}–${res.max} (spread ${cleanSpread})`);
3421
+ }
3422
+ const groupText = res.groups.map((g) => {
3423
+ return `${g.min === g.max ? String(g.min) : `${g.min}–${g.max}`} (${g.support}/${res.answered})`;
3424
+ });
3425
+ if (res.nullGroup !== void 0) groupText.push(`null (${res.nullGroup.support}/${res.answered})`);
3426
+ if (groupText.length > 0) parts.push(groupText.join(", "));
3427
+ if (res.missing.length > 0) parts.push(`missing: ${res.missing.map(r.inline).join(", ")}`);
3428
+ return parts.length > 0 ? parts.join(" · ") : "—";
3429
+ }
3430
+ function summarizeSet(ledger, path, res, r) {
3431
+ const head = [
3432
+ `∩ ${res.intersection.length}`,
3433
+ `∪ ${res.union.length}`,
3434
+ ...res.jaccard !== void 0 ? [`J=${res.jaccard.toFixed(2)}`] : []
3435
+ ].join(" · ");
3436
+ const interKeys = new Set(res.intersection.map((v) => canonicalJson(v)));
3437
+ const nonInter = res.items.filter((item) => !interKeys.has(canonicalJson(item.item))).map((item) => `${r.value(item.item)} (${item.support}/${res.answered})`);
3438
+ let text = nonInter.length > 0 ? `${head}: ${nonInter.join(", ")}` : head;
3439
+ if (res.nulls.length > 0) text += ` · nulls: ${res.nulls.map(r.inline).join(", ")}`;
3440
+ const nonArrays = path !== null ? findNonArrayRawValues(ledger, path, res) : [];
3441
+ if (nonArrays.length > 0) text += ` · non-array: ${nonArrays.map((e) => `${r.inline(e.witness)}=${r.value(e.value)}`).join(", ")}`;
3442
+ if (res.missing.length > 0) text += ` · missing: ${res.missing.map(r.inline).join(", ")}`;
3443
+ return text;
3444
+ }
3445
+ /** Formats a leaf field result concisely (§11.1 item 4). */
3446
+ function summarizeLeafResult(ledger, path, res, r) {
3447
+ switch (res.comparator) {
3448
+ case "exact": return summarizeExact(res, r);
3449
+ case "tolerance": return summarizeTolerance(res, r);
3450
+ case "set": return summarizeSet(ledger, path, res, r);
3451
+ case "none": {
3452
+ let text = `${r.inline(res.reason)}/${r.inline(res.detail)}`;
3453
+ if (res.duplicateKeyWitnesses !== void 0 && res.duplicateKeyWitnesses.length > 0) text += ` (${res.duplicateKeyWitnesses.map(r.inline).join(", ")})`;
3454
+ else if (!(res.reason === "policy" && res.detail === "free-text") && res.values.length > 0) text += `: ${res.values.map((v) => `${r.inline(v.witness)}=${r.value(v.value)}`).join(", ")}`;
3455
+ return text;
3456
+ }
3457
+ }
3458
+ }
3459
+ /** Formats any top-level `FieldResult` summary line (§11.1 item 4). */
3460
+ function summarizeFieldResult(ledger, path, res, r) {
3461
+ if (res.comparator === "keyed-set") {
3462
+ const head = [
3463
+ `key=${r.inline(res.key)}`,
3464
+ `∩ ${res.keys.intersection.length}`,
3465
+ `∪ ${res.keys.union.length}`,
3466
+ ...res.keys.jaccard !== void 0 ? [`J=${res.keys.jaccard.toFixed(2)}`] : []
3467
+ ].join(" · ");
3468
+ const nonArrays = findNonArrayRawValues(ledger, path, res);
3469
+ if (nonArrays.length > 0) return `${head} · non-array: ${nonArrays.map((e) => `${r.inline(e.witness)}=${r.value(e.value)}`).join(", ")}`;
3470
+ return head;
3471
+ }
3472
+ if (res.comparator === "discriminated-union") return `by ${r.inline(res.discriminator)}: ${summarizeExact(res.choice, r)}`;
3473
+ return summarizeLeafResult(ledger, path, res, r);
3474
+ }
3475
+ /** Builds structured sub-rows for `keyed-set` and `discriminated-union` fields (§11.1 item 4). */
3476
+ function buildCompositeSubRows(ledger, path, res, r) {
3477
+ return (res.comparator === "keyed-set" ? res.items.map((item) => ({
3478
+ heading: `key=${r.value(item.key)} (${item.witnesses.map(r.inline).join(", ")})`,
3479
+ fields: item.fields
3480
+ })) : res.branches.map((branch) => ({
3481
+ heading: `branch=${r.value(branch.value)} (${branch.witnesses.map(r.inline).join(", ")})`,
3482
+ fields: branch.fields
3483
+ }))).map((entry) => ({
3484
+ heading: entry.heading,
3485
+ leaves: sortLabels(Object.keys(entry.fields)).map((subpath) => ({
3486
+ subpath: r.inline(subpath),
3487
+ summary: summarizeLeafResult(ledger, res.comparator === "discriminated-union" ? `${path}${subpath}` : null, ownValue(entry.fields, subpath), r)
3488
+ }))
3489
+ }));
3490
+ }
3491
+ /** Extracts non-empty Independence display rows (§11.1 item 6). */
3492
+ function buildIndependenceEntries(ind, escInline) {
3493
+ const entries = [];
3494
+ if (ind.uniqueRequestedProviders > 0) entries.push({
3495
+ label: "Unique requested providers",
3496
+ value: String(ind.uniqueRequestedProviders)
3497
+ });
3498
+ if (ind.duplicateServedModels.length > 0) entries.push({
3499
+ label: "Duplicate served models",
3500
+ value: ind.duplicateServedModels.map((d) => `${escInline(d.canonicalId)} (${d.witnesses.map(escInline).join(", ")})`).join("; ")
3501
+ });
3502
+ if (ind.sameProviderGroups.length > 0) entries.push({
3503
+ label: "Same-provider groups",
3504
+ value: ind.sameProviderGroups.map((g) => `${escInline(g.providerKey)} (${g.witnesses.map(escInline).join(", ")})`).join("; ")
3505
+ });
3506
+ if (ind.selfGradingWitnesses.length > 0) entries.push({
3507
+ label: "Self-grading witnesses",
3508
+ value: ind.selfGradingWitnesses.map((s) => `${escInline(s.witness)} (${sanitizeInline(s.on)}=${escInline(s.authorModel)})`).join("; ")
3509
+ });
3510
+ if (ind.excludedWitnesses.length > 0) entries.push({
3511
+ label: "Excluded witnesses",
3512
+ value: ind.excludedWitnesses.map((e) => `${escInline(e.witness)} (${sanitizeInline(e.stage)}, ${sanitizeInline(e.on)}=${escInline(e.authorModel)})`).join("; ")
3513
+ });
3514
+ return entries;
3515
+ }
3516
+ /** Formats a finding's target (`path` / `within` / `subpath`) safely (§11.1 item 5). */
3517
+ function formatFindingTarget(finding, r) {
3518
+ if (finding.path === void 0) return "—";
3519
+ let target = r.inline(finding.path);
3520
+ if (finding.within !== void 0) target += "key" in finding.within ? ` [key=${r.value(finding.within.key)}]` : ` [branch=${r.value(finding.within.branch)}]`;
3521
+ if (finding.subpath !== void 0) target += ` ${r.inline(finding.subpath)}`;
3522
+ return target;
3523
+ }
3524
+ // src/render/format-ascii.ts
3525
+ const RULE_MAJOR = "=".repeat(78);
3526
+ const RULE_MINOR = "-".repeat(78);
3527
+ /** Renders a Ledger (and optional Adjudication) as an ASCII cockpit report (§11.1–§11.3). */
3528
+ function formatAscii(ledger, options) {
3529
+ const { maxInlineChars, maxBlockChars, adjudication, showOutputs } = options;
3530
+ const esc = (text) => escapeAsciiInline(text, maxInlineChars);
3531
+ const fmtVal = (val) => formatAsciiValue(val, maxInlineChars);
3532
+ const renderers = {
3533
+ inline: esc,
3534
+ value: fmtVal
3535
+ };
3536
+ const cleanFp = sanitizeInline(ledger.fingerprint);
3537
+ const shortFp = cleanFp.length > 12 ? `${cleanFp.slice(0, 12)}…` : cleanFp;
3538
+ const lines = [];
3539
+ lines.push(RULE_MAJOR);
3540
+ lines.push("Dissent Ledger");
3541
+ lines.push(RULE_MAJOR);
3542
+ lines.push(`Protocol : ${sanitizeInline(ledger.protocol)}`);
3543
+ lines.push(`Fingerprint : ${shortFp}`);
3544
+ lines.push(`Created : ${sanitizeInline(ledger.createdAt)}`);
3545
+ lines.push("");
3546
+ lines.push(formatSummaryLine(ledger), "");
3547
+ lines.push("Witnesses", RULE_MINOR);
3548
+ const witnessLabels = sortLabels(Object.keys(ledger.witnesses));
3549
+ for (const label of witnessLabels) {
3550
+ const rec = ownValue(ledger.witnesses, label);
3551
+ const req = esc(rec.requested.canonicalId);
3552
+ const served = rec.served !== null ? esc(rec.served.canonicalId) : "—";
3553
+ const detail = formatWitnessDetail(rec, esc);
3554
+ const tokens = rec.usage?.totalTokens !== null && rec.usage?.totalTokens !== void 0 ? String(rec.usage.totalTokens) : "—";
3555
+ lines.push(`${esc(label)} : status=${sanitizeInline(rec.status)}, req=${req}, served=${served}, detail=${detail}, duration=${rec.durationMs}ms, tokens=${tokens}`);
3556
+ }
3557
+ lines.push("");
3558
+ lines.push("Fields", RULE_MINOR);
3559
+ const fieldPaths = sortLabels(Object.keys(ledger.fields));
3560
+ const freeTextFields = [];
3561
+ if (fieldPaths.length === 0) lines.push("No fields.");
3562
+ else for (const path of fieldPaths) {
3563
+ const res = ownValue(ledger.fields, path);
3564
+ const summary = summarizeFieldResult(ledger, path, res, renderers);
3565
+ lines.push(`${esc(path)} : ${sanitizeInline(res.comparator)} [${sanitizeInline(res.status)}] -- ${summary}`);
3566
+ if (res.comparator === "keyed-set" || res.comparator === "discriminated-union") for (const sub of buildCompositeSubRows(ledger, path, res, renderers)) {
3567
+ lines.push(` ${sub.heading}`);
3568
+ for (const leaf of sub.leaves) lines.push(` ${leaf.subpath} : ${leaf.summary}`);
3569
+ }
3570
+ else if (res.comparator === "none" && res.reason === "policy" && res.detail === "free-text" && res.values.length > 0) freeTextFields.push({
3571
+ path,
3572
+ result: res
3573
+ });
3574
+ }
3575
+ lines.push("");
3576
+ if (freeTextFields.length > 0) {
3577
+ lines.push("Read side by side", RULE_MINOR);
3578
+ for (const entry of freeTextFields) for (const item of entry.result.values) {
3579
+ lines.push(`${esc(entry.path)} (${esc(item.witness)}) :`);
3580
+ const text = typeof item.value === "string" ? item.value : canonicalJson(item.value);
3581
+ lines.push(formatAsciiBlock(text, maxBlockChars));
3582
+ }
3583
+ lines.push("");
3584
+ }
3585
+ lines.push("Findings", RULE_MINOR);
3586
+ if (ledger.findings.length === 0) lines.push("None.");
3587
+ else for (const finding of ledger.findings) {
3588
+ const target = formatFindingTarget(finding, renderers);
3589
+ const witnesses = finding.witnesses !== void 0 && finding.witnesses.length > 0 ? finding.witnesses.map(esc).join(", ") : "—";
3590
+ lines.push(`${sanitizeInline(finding.severity)} : ${sanitizeInline(finding.code)}, target=${target}, witnesses=${witnesses}`);
3591
+ }
3592
+ lines.push("");
3593
+ const indEntries = buildIndependenceEntries(ledger.independence, esc);
3594
+ if (indEntries.length > 0) {
3595
+ lines.push("Independence", RULE_MINOR);
3596
+ for (const entry of indEntries) lines.push(`${entry.label} : ${entry.value}`);
3597
+ lines.push("");
3598
+ }
3599
+ if (adjudication !== void 0) {
3600
+ const ae = adjudication.artifactEvidence;
3601
+ lines.push("Adjudication", RULE_MINOR);
3602
+ lines.push(`Verdict : ${sanitizeInline(adjudication.verdict)} (${sanitizeInline(adjudication.verdictReason)})`);
3603
+ lines.push(`Artifact evidence : pass=${ae.pass}, fail=${ae.fail}, error=${ae.error}, unknown=${ae.unknown}`);
3604
+ lines.push(`Unbound : ${adjudication.unbound.length}`);
3605
+ lines.push(`Conflicts : ${adjudication.conflicts.length}`);
3606
+ for (const s of adjudication.settlements) {
3607
+ const agree = s.witnessesAgreeing.length > 0 ? s.witnessesAgreeing.map(esc).join(", ") : "—";
3608
+ const dissent = s.witnessesDissenting.length > 0 ? s.witnessesDissenting.map(esc).join(", ") : "—";
3609
+ const silent = s.witnessesSilent.length > 0 ? s.witnessesSilent.map(esc).join(", ") : "—";
3610
+ lines.push(` ${esc(s.path)} : value=${fmtVal(s.value)}, source=${esc(s.source)}, outcome=${sanitizeInline(s.outcome)}, agree=[${agree}], dissent=[${dissent}], silent=[${silent}]`);
3611
+ }
3612
+ for (const c of adjudication.conflicts) lines.push(` conflict ${esc(c.path)} : ${c.sources.map(esc).join(", ")}`);
3613
+ for (const rc of adjudication.receiptChecks) {
3614
+ const status = rc.check.valid ? "valid" : `invalid (${sanitizeInline(rc.check.reason)})`;
3615
+ const rid = rc.receiptId !== null ? esc(rc.receiptId) : "—";
3616
+ lines.push(` receipt ${esc(rc.source)} : id=${rid}, ${status}`);
3617
+ }
3618
+ lines.push("");
3619
+ }
3620
+ if (showOutputs) {
3621
+ lines.push("Outputs", RULE_MINOR);
3622
+ for (const label of witnessLabels) {
3623
+ const rec = ownValue(ledger.witnesses, label);
3624
+ if (rec.status !== "answered") continue;
3625
+ lines.push(`${esc(label)} :`);
3626
+ const jsonText = JSON.stringify(rec.output, null, 2) ?? "null";
3627
+ lines.push(formatAsciiBlock(jsonText, maxBlockChars));
3628
+ }
3629
+ lines.push("");
3630
+ }
3631
+ return `${lines.join("\n").replace(/\n+$/, "")}\n`;
3632
+ }
3633
+ // src/render/format-markdown.ts
3634
+ /** Renders a Ledger (and optional Adjudication) as GitHub-Flavored Markdown (§11.1–§11.3). */
3635
+ function formatMarkdown(ledger, options) {
3636
+ const { maxInlineChars, maxBlockChars, adjudication, showOutputs } = options;
3637
+ const esc = (text) => escapeMarkdownInline(text, maxInlineChars);
3638
+ const fmtVal = (val) => formatMarkdownValue(val, maxInlineChars);
3639
+ const renderers = {
3640
+ inline: esc,
3641
+ value: fmtVal
3642
+ };
3643
+ const lines = [];
3644
+ lines.push("## Dissent Ledger", "");
3645
+ lines.push(`- **Protocol:** ${sanitizeInline(ledger.protocol)}`);
3646
+ lines.push(`- **Fingerprint:** ${sanitizeInline(ledger.fingerprint)}`);
3647
+ lines.push(`- **Created:** ${sanitizeInline(ledger.createdAt)}`);
3648
+ lines.push("");
3649
+ lines.push(formatSummaryLine(ledger), "");
3650
+ lines.push("### Witnesses", "");
3651
+ lines.push("| Label | Requested | Served | Status | Detail | Duration | Tokens |");
3652
+ lines.push("|---|---|---|---|---|---:|---:|");
3653
+ const witnessLabels = sortLabels(Object.keys(ledger.witnesses));
3654
+ for (const label of witnessLabels) {
3655
+ const rec = ownValue(ledger.witnesses, label);
3656
+ const req = esc(rec.requested.canonicalId);
3657
+ const served = rec.served !== null ? esc(rec.served.canonicalId) : "—";
3658
+ const detail = formatWitnessDetail(rec, esc);
3659
+ const tokens = rec.usage?.totalTokens !== null && rec.usage?.totalTokens !== void 0 ? String(rec.usage.totalTokens) : "—";
3660
+ lines.push(`| ${esc(label)} | ${req} | ${served} | ${sanitizeInline(rec.status)} | ${detail} | ${rec.durationMs}ms | ${tokens} |`);
3661
+ }
3662
+ lines.push("");
3663
+ lines.push("### Fields", "");
3664
+ const fieldPaths = sortLabels(Object.keys(ledger.fields));
3665
+ const compositeDetails = [];
3666
+ const freeTextFields = [];
3667
+ if (fieldPaths.length === 0) lines.push("No fields.", "");
3668
+ else {
3669
+ lines.push("| Path | Comparator | Status | Summary |");
3670
+ lines.push("|---|---|---|---|");
3671
+ for (const path of fieldPaths) {
3672
+ const res = ownValue(ledger.fields, path);
3673
+ const summary = summarizeFieldResult(ledger, path, res, renderers);
3674
+ lines.push(`| ${esc(path)} | ${sanitizeInline(res.comparator)} | ${sanitizeInline(res.status)} | ${summary} |`);
3675
+ if (res.comparator === "keyed-set" || res.comparator === "discriminated-union") compositeDetails.push({
3676
+ path,
3677
+ subRows: buildCompositeSubRows(ledger, path, res, renderers)
3678
+ });
3679
+ else if (res.comparator === "none" && res.reason === "policy" && res.detail === "free-text" && res.values.length > 0) freeTextFields.push({
3680
+ path,
3681
+ result: res
3682
+ });
3683
+ }
3684
+ lines.push("");
3685
+ }
3686
+ for (const detail of compositeDetails) {
3687
+ if (detail.subRows.length === 0) continue;
3688
+ lines.push(`#### ${esc(detail.path)}`, "");
3689
+ for (const sub of detail.subRows) {
3690
+ lines.push(`- ${sub.heading}`);
3691
+ for (const leaf of sub.leaves) lines.push(` - ${leaf.subpath}: ${leaf.summary}`);
3692
+ }
3693
+ lines.push("");
3694
+ }
3695
+ if (freeTextFields.length > 0) {
3696
+ lines.push("### Read side by side", "");
3697
+ for (const entry of freeTextFields) for (const item of entry.result.values) {
3698
+ lines.push(`- **${esc(entry.path)} — ${esc(item.witness)}:**`, "");
3699
+ const text = typeof item.value === "string" ? item.value : canonicalJson(item.value);
3700
+ lines.push(formatMarkdownBlock(text, maxBlockChars), "");
3701
+ }
3702
+ }
3703
+ lines.push("### Findings", "");
3704
+ if (ledger.findings.length === 0) lines.push("None.", "");
3705
+ else {
3706
+ lines.push("| Severity | Code | Target | Witnesses |");
3707
+ lines.push("|---|---|---|---|");
3708
+ for (const finding of ledger.findings) {
3709
+ const target = formatFindingTarget(finding, renderers);
3710
+ const witnesses = finding.witnesses !== void 0 && finding.witnesses.length > 0 ? finding.witnesses.map(esc).join(", ") : "—";
3711
+ lines.push(`| ${sanitizeInline(finding.severity)} | ${sanitizeInline(finding.code)} | ${target} | ${witnesses} |`);
3712
+ }
3713
+ lines.push("");
3714
+ }
3715
+ const indEntries = buildIndependenceEntries(ledger.independence, esc);
3716
+ if (indEntries.length > 0) {
3717
+ lines.push("### Independence", "");
3718
+ for (const entry of indEntries) lines.push(`- **${entry.label}:** ${entry.value}`);
3719
+ lines.push("");
3720
+ }
3721
+ if (adjudication !== void 0) {
3722
+ const ae = adjudication.artifactEvidence;
3723
+ lines.push("### Adjudication", "");
3724
+ lines.push(`- **Verdict:** ${sanitizeInline(adjudication.verdict)} (${sanitizeInline(adjudication.verdictReason)})`);
3725
+ lines.push(`- **Artifact evidence:** pass=${ae.pass}, fail=${ae.fail}, error=${ae.error}, unknown=${ae.unknown}`);
3726
+ lines.push(`- **Unbound:** ${adjudication.unbound.length}`);
3727
+ lines.push(`- **Conflicts:** ${adjudication.conflicts.length}`);
3728
+ lines.push("");
3729
+ if (adjudication.settlements.length > 0) {
3730
+ lines.push("| Path | Value | Source | Outcome | Agreeing | Dissenting | Silent |");
3731
+ lines.push("|---|---|---|---|---|---|---|");
3732
+ for (const s of adjudication.settlements) {
3733
+ const agree = s.witnessesAgreeing.length > 0 ? s.witnessesAgreeing.map(esc).join(", ") : "—";
3734
+ const dissent = s.witnessesDissenting.length > 0 ? s.witnessesDissenting.map(esc).join(", ") : "—";
3735
+ const silent = s.witnessesSilent.length > 0 ? s.witnessesSilent.map(esc).join(", ") : "—";
3736
+ lines.push(`| ${esc(s.path)} | ${fmtVal(s.value)} | ${esc(s.source)} | ${sanitizeInline(s.outcome)} | ${agree} | ${dissent} | ${silent} |`);
3737
+ }
3738
+ lines.push("");
3739
+ }
3740
+ if (adjudication.conflicts.length > 0) {
3741
+ for (const c of adjudication.conflicts) lines.push(`- **Conflict** ${esc(c.path)}: ${c.sources.map(esc).join(", ")}`);
3742
+ lines.push("");
3743
+ }
3744
+ if (adjudication.receiptChecks.length > 0) {
3745
+ lines.push("| Source | Receipt ID | Check |");
3746
+ lines.push("|---|---|---|");
3747
+ for (const rc of adjudication.receiptChecks) {
3748
+ const status = rc.check.valid ? "valid" : `invalid (${sanitizeInline(rc.check.reason)})`;
3749
+ const rid = rc.receiptId !== null ? esc(rc.receiptId) : "—";
3750
+ lines.push(`| ${esc(rc.source)} | ${rid} | ${status} |`);
3751
+ }
3752
+ lines.push("");
3753
+ }
3754
+ }
3755
+ if (showOutputs) {
3756
+ lines.push("### Outputs", "");
3757
+ for (const label of witnessLabels) {
3758
+ const rec = ownValue(ledger.witnesses, label);
3759
+ if (rec.status !== "answered") continue;
3760
+ lines.push(`- **${esc(label)}:**`, "");
3761
+ const jsonText = JSON.stringify(rec.output, null, 2) ?? "null";
3762
+ lines.push(formatMarkdownBlock(jsonText, maxBlockChars), "");
3763
+ }
3764
+ }
3765
+ return `${lines.join("\n").replace(/\n+$/, "")}\n`;
3766
+ }
3767
+ // src/render/format-ledger.ts
3768
+ const DEFAULT_MAX_INLINE_CHARS = 120;
3769
+ const DEFAULT_MAX_BLOCK_CHARS = 4e3;
3770
+ function readPositiveIntOption(value, fallback, name) {
3771
+ if (value === void 0) return fallback;
3772
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) throw new DissentArgumentError("invalid-option", name);
3773
+ return value;
3774
+ }
3775
+ /**
3776
+ * Renders a `Ledger` as Markdown or ASCII without reading the clock, environment, or network (§11).
3777
+ */
3778
+ function formatLedger(ledger, options) {
3779
+ if (options !== void 0 && !isPlainObject(options)) throw new DissentArgumentError("invalid-option", "options");
3780
+ const format = options?.format ?? "markdown";
3781
+ if (format !== "markdown" && format !== "ascii") throw new DissentArgumentError("invalid-option", "format");
3782
+ if (options?.showOutputs !== void 0 && typeof options.showOutputs !== "boolean") throw new DissentArgumentError("invalid-option", "showOutputs");
3783
+ const resolved = {
3784
+ maxInlineChars: readPositiveIntOption(options?.maxInlineChars, DEFAULT_MAX_INLINE_CHARS, "maxInlineChars"),
3785
+ maxBlockChars: readPositiveIntOption(options?.maxBlockChars, DEFAULT_MAX_BLOCK_CHARS, "maxBlockChars"),
3786
+ showOutputs: options?.showOutputs === true
3787
+ };
3788
+ if (options?.adjudication !== void 0) resolved.adjudication = options.adjudication;
3789
+ return format === "markdown" ? formatMarkdown(ledger, resolved) : formatAscii(ledger, resolved);
3790
+ }
3791
+ export { DissentArgumentError, DissentError, NonJsonValueError, adjudicate, corroborate, formatLedger, validateOfflineReceipt };
3792
+
3793
+ //# sourceMappingURL=index.js.map