@tangle-network/agent-eval 0.133.0 → 0.133.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +1 -1
  3. package/dist/agent-profile-cell-OhuTee9n.js +335 -0
  4. package/dist/agent-profile-cell-OhuTee9n.js.map +1 -0
  5. package/dist/{analyze-runs-BjPn_fOS.js → analyze-runs-B-afTpCv.js} +6 -19
  6. package/dist/analyze-runs-B-afTpCv.js.map +1 -0
  7. package/dist/{analyze-runs-DZr7JW-m.d.ts → analyze-runs-BmX-h_yn.d.ts} +3 -3
  8. package/dist/{analyze-runs-DZr7JW-m.d.ts.map → analyze-runs-BmX-h_yn.d.ts.map} +1 -1
  9. package/dist/{baseline-HsBvw_dk.js → baseline-DcX5hQDv.js} +2 -70
  10. package/dist/{baseline-HsBvw_dk.js.map → baseline-DcX5hQDv.js.map} +1 -1
  11. package/dist/baseline-hG3K85h4.d.ts.map +1 -1
  12. package/dist/benchmarks/index.d.ts +1 -1
  13. package/dist/benchmarks/index.js +1 -1
  14. package/dist/{benchmarks-DncrVrSr.js → benchmarks-CJr1H1_a.js} +3 -3
  15. package/dist/{benchmarks-DncrVrSr.js.map → benchmarks-CJr1H1_a.js.map} +1 -1
  16. package/dist/builder-eval/index.js +1 -1
  17. package/dist/campaign/index.d.ts +3 -3
  18. package/dist/campaign/index.js +2 -2
  19. package/dist/{campaign-CyQMCCEU.js → campaign-BJjn1rhw.js} +19 -13
  20. package/dist/{campaign-CyQMCCEU.js.map → campaign-BJjn1rhw.js.map} +1 -1
  21. package/dist/{client-D4F9hdzR.d.ts → client-COvaLoQG.d.ts} +2 -2
  22. package/dist/{client-D4F9hdzR.d.ts.map → client-COvaLoQG.d.ts.map} +1 -1
  23. package/dist/contract/index.d.ts +3 -3
  24. package/dist/contract/index.js +5 -5
  25. package/dist/control.js +1 -1
  26. package/dist/{eval-campaign-CYkUME2T.js → eval-campaign-DXhpZghy.js} +4 -5
  27. package/dist/{eval-campaign-CYkUME2T.js.map → eval-campaign-DXhpZghy.js.map} +1 -1
  28. package/dist/hosted/index.d.ts +1 -1
  29. package/dist/index-3cdlURSk.d.ts.map +1 -1
  30. package/dist/{index-CiP2DRCj.d.ts → index-BREtv3ZZ.d.ts} +3 -3
  31. package/dist/{index-CiP2DRCj.d.ts.map → index-BREtv3ZZ.d.ts.map} +1 -1
  32. package/dist/{index-B_eUhU9K.d.ts → index-C7Wue8R6.d.ts} +28 -5
  33. package/dist/{index-B_eUhU9K.d.ts.map → index-C7Wue8R6.d.ts.map} +1 -1
  34. package/dist/{index-BAvgST_9.d.ts → index-nhIYz9hn.d.ts} +67 -9
  35. package/dist/index-nhIYz9hn.d.ts.map +1 -0
  36. package/dist/index.d.ts +7 -7
  37. package/dist/index.js +25 -18
  38. package/dist/index.js.map +1 -1
  39. package/dist/ledger-core/index.d.ts +2 -2
  40. package/dist/ledger-core/index.js +2 -2
  41. package/dist/ledger-core-CPZfcrC2.js +620 -0
  42. package/dist/ledger-core-CPZfcrC2.js.map +1 -0
  43. package/dist/meta-eval/index.js +2 -2
  44. package/dist/{mint-D5_87M5L.js → mint-BvkwcYZU.js} +2 -2
  45. package/dist/{mint-D5_87M5L.js.map → mint-BvkwcYZU.js.map} +1 -1
  46. package/dist/openapi.json +1 -1
  47. package/dist/{opencode-sqlite-BGrHeDu3.js → opencode-sqlite-8r6WUfHc.js} +2 -3
  48. package/dist/opencode-sqlite-8r6WUfHc.js.map +1 -0
  49. package/dist/{paired-arms-D9D0wXj2.js → paired-arms-6XItKzd1.js} +2 -2
  50. package/dist/{paired-arms-D9D0wXj2.js.map → paired-arms-6XItKzd1.js.map} +1 -1
  51. package/dist/pipelines/index.js +2 -2
  52. package/dist/profile-cell.js +1 -242
  53. package/dist/{propose-review-control-Bqb7daEJ.js → propose-review-control-SQ-n9-We.js} +2 -2
  54. package/dist/{propose-review-control-Bqb7daEJ.js.map → propose-review-control-SQ-n9-We.js.map} +1 -1
  55. package/dist/{release-report-DfmKSIEE.d.ts → release-report-CjHWa8Ia.d.ts} +2 -2
  56. package/dist/{release-report-DfmKSIEE.d.ts.map → release-report-CjHWa8Ia.d.ts.map} +1 -1
  57. package/dist/{release-report-oWt9f2k-.js → release-report-wuilQkvK.js} +3 -3
  58. package/dist/{release-report-oWt9f2k-.js.map → release-report-wuilQkvK.js.map} +1 -1
  59. package/dist/{replay-BMR4TEYY.js → replay-CJfGLdx4.js} +3 -3
  60. package/dist/{replay-BMR4TEYY.js.map → replay-CJfGLdx4.js.map} +1 -1
  61. package/dist/reporting.d.ts +2 -2
  62. package/dist/reporting.js +4 -4
  63. package/dist/{researcher-DMimgHtN.d.ts → researcher-CbSKhK8z.d.ts} +2 -2
  64. package/dist/{researcher-DMimgHtN.d.ts.map → researcher-CbSKhK8z.d.ts.map} +1 -1
  65. package/dist/{reward-hacking-BEvjdUtD.js → reward-hacking-Dl2UBzej.js} +3 -3
  66. package/dist/{reward-hacking-BEvjdUtD.js.map → reward-hacking-Dl2UBzej.js.map} +1 -1
  67. package/dist/rl.d.ts +1 -1
  68. package/dist/rl.js +6 -6
  69. package/dist/rollout/index.js +3 -3
  70. package/dist/{rollout-VEo41J0N.js → rollout-CreDz__7.js} +3 -3
  71. package/dist/{rollout-VEo41J0N.js.map → rollout-CreDz__7.js.map} +1 -1
  72. package/dist/{rubric-predictive-validity-B3xmbmS1.js → rubric-predictive-validity-QG7ydk0s.js} +2 -2
  73. package/dist/{rubric-predictive-validity-B3xmbmS1.js.map → rubric-predictive-validity-QG7ydk0s.js.map} +1 -1
  74. package/dist/{run-record-CN8Zd21B.js → run-record-BIwU2wdV.js} +2 -2
  75. package/dist/{run-record-CN8Zd21B.js.map → run-record-BIwU2wdV.js.map} +1 -1
  76. package/dist/{skillopt-optimization-method-DgN7U9iR.js → skillopt-optimization-method-CF6a327Q.js} +8 -4
  77. package/dist/{skillopt-optimization-method-DgN7U9iR.js.map → skillopt-optimization-method-CF6a327Q.js.map} +1 -1
  78. package/dist/{skillopt-optimization-method-CAASpcS3.d.ts → skillopt-optimization-method-wHF5xsUv.d.ts} +2 -2
  79. package/dist/{skillopt-optimization-method-CAASpcS3.d.ts.map → skillopt-optimization-method-wHF5xsUv.d.ts.map} +1 -1
  80. package/dist/{statistics-CnnxdpOg.js → statistics-DWM_AyLe.js} +90 -76
  81. package/dist/statistics-DWM_AyLe.js.map +1 -0
  82. package/dist/statistics-DbvkkDPa.d.ts.map +1 -1
  83. package/dist/{summary-report-DnUcjVpV.d.ts → summary-report-CFnQgNfg.d.ts} +2 -2
  84. package/dist/{summary-report-DnUcjVpV.d.ts.map → summary-report-CFnQgNfg.d.ts.map} +1 -1
  85. package/dist/{summary-report-BNs5nmXI.js → summary-report-Ci17nIdU.js} +4 -4
  86. package/dist/{summary-report-BNs5nmXI.js.map → summary-report-Ci17nIdU.js.map} +1 -1
  87. package/dist/supervisor-run/index.js +1 -1
  88. package/dist/{supervisor-run-_lnTLM3z.js → supervisor-run-B7lUGoyZ.js} +2 -2
  89. package/dist/{supervisor-run-_lnTLM3z.js.map → supervisor-run-B7lUGoyZ.js.map} +1 -1
  90. package/dist/traces.js +1 -1
  91. package/package.json +1 -1
  92. package/dist/analyze-runs-BjPn_fOS.js.map +0 -1
  93. package/dist/index-BAvgST_9.d.ts.map +0 -1
  94. package/dist/ledger-core-eqaI3PCD.js +0 -388
  95. package/dist/ledger-core-eqaI3PCD.js.map +0 -1
  96. package/dist/opencode-sqlite-BGrHeDu3.js.map +0 -1
  97. package/dist/pre-registration-DakwTRXk.js +0 -96
  98. package/dist/pre-registration-DakwTRXk.js.map +0 -1
  99. package/dist/profile-cell.js.map +0 -1
  100. package/dist/statistics-CnnxdpOg.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"ledger-core-eqaI3PCD.js","names":[],"sources":["../src/ledger-core/atomic-file-lock.ts","../src/ledger-core/journal-file.ts","../src/ledger-core/journal.ts"],"sourcesContent":["/** Crash-safe filesystem lock shared by campaign persistence and run exclusion. */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n constants,\n existsSync,\n fsyncSync,\n linkSync,\n openSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { hostname } from 'node:os'\n\nexport interface AtomicFileLockOwner {\n readonly pid: number\n readonly host: string\n readonly nonce: string\n}\n\nexport interface AtomicFileLock {\n readonly owner: AtomicFileLockOwner\n release(): void\n}\n\nexport type AtomicFileLockUnavailable =\n | { readonly acquired: false; readonly reason: 'held'; readonly holder: AtomicFileLockOwner }\n | { readonly acquired: false; readonly reason: 'recovery' }\n\nexport type AtomicFileLockAcquisition =\n | { readonly acquired: true; readonly lock: AtomicFileLock }\n | AtomicFileLockUnavailable\n\nexport interface AtomicFileLockOptions {\n readonly lockPath: string\n readonly pid?: number\n}\n\nexport class AtomicFileLockError extends Error {\n override readonly name = 'AtomicFileLockError'\n}\n\ntype OwnerState =\n | { readonly state: 'missing' }\n | { readonly state: 'stale'; readonly owner: AtomicFileLockOwner }\n | { readonly state: 'held'; readonly owner: AtomicFileLockOwner }\n\n/** Report whether another lock path prevents acquisition without modifying it. */\nexport function probeAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockUnavailable | null {\n if (existsSync(recoveryPath(options.lockPath))) return { acquired: false, reason: 'recovery' }\n const state = ownerState(options.lockPath)\n if (state.state === 'held') {\n return { acquired: false, reason: 'held', holder: state.owner }\n }\n return null\n}\n\n/**\n * Try to acquire a complete, uniquely-owned lock inode.\n *\n * A hard link publishes fully-written owner metadata atomically. Stale-owner\n * removal is serialized so one reclaimer cannot delete a new owner's lock.\n */\nexport function tryAcquireAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockAcquisition {\n const pid = options.pid ?? process.pid\n if (!Number.isSafeInteger(pid) || pid <= 0) {\n throw new AtomicFileLockError('atomic file lock pid must be a positive integer')\n }\n const owner: AtomicFileLockOwner = { pid, host: hostname(), nonce: randomUUID() }\n for (let attempt = 0; attempt < 8; attempt += 1) {\n if (existsSync(recoveryPath(options.lockPath))) {\n return { acquired: false, reason: 'recovery' }\n }\n if (tryLinkOwner(options.lockPath, owner, `acquire.${attempt}`)) {\n return acquired(options.lockPath, owner)\n }\n\n const holder = ownerState(options.lockPath)\n if (holder.state === 'missing') continue\n if (holder.state === 'held') {\n return { acquired: false, reason: 'held', holder: holder.owner }\n }\n\n const reclaimPath = recoveryPath(options.lockPath)\n if (!tryLinkOwner(reclaimPath, owner, `reclaim.${attempt}`)) {\n return { acquired: false, reason: 'recovery' }\n }\n try {\n const current = ownerState(options.lockPath)\n if (current.state === 'held') {\n return { acquired: false, reason: 'held', holder: current.owner }\n }\n if (current.state === 'stale') {\n const tombstone = `${options.lockPath}.stale.${owner.nonce}.${attempt}`\n try {\n renameSync(options.lockPath, tombstone)\n unlinkSync(tombstone)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n }\n if (tryLinkOwner(options.lockPath, owner, `recovered.${attempt}`)) {\n return acquired(options.lockPath, owner)\n }\n } finally {\n releaseOwnedPath(reclaimPath, owner)\n }\n }\n\n throw new AtomicFileLockError(`could not acquire atomic file lock ${options.lockPath}`)\n}\n\nfunction acquired(lockPath: string, owner: AtomicFileLockOwner): AtomicFileLockAcquisition {\n return {\n acquired: true,\n lock: {\n owner,\n release: () => releaseOwnedPath(lockPath, owner),\n },\n }\n}\n\nfunction tryLinkOwner(lockPath: string, owner: AtomicFileLockOwner, suffix: string): boolean {\n const ownerPath = `${lockPath}.${owner.pid}.${owner.nonce}.${suffix}.owner`\n const descriptor = openSync(\n ownerPath,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o600,\n )\n try {\n writeFileSync(descriptor, `${canonicalOwner(owner)}\\n`, 'utf8')\n fsyncSync(descriptor)\n } catch (error) {\n closeSync(descriptor)\n unlinkIfExists(ownerPath)\n throw error\n }\n closeSync(descriptor)\n\n try {\n linkSync(ownerPath, lockPath)\n return true\n } catch (error) {\n if (!isAlreadyExists(error)) throw error\n return false\n } finally {\n unlinkIfExists(ownerPath)\n }\n}\n\nfunction ownerState(lockPath: string): OwnerState {\n const owner = readOwner(lockPath)\n if (!owner) return { state: 'missing' }\n if (owner.host !== hostname()) return { state: 'held', owner }\n try {\n process.kill(owner.pid, 0)\n return { state: 'held', owner }\n } catch (error) {\n if (isNoSuchProcess(error)) return { state: 'stale', owner }\n return { state: 'held', owner }\n }\n}\n\nfunction readOwner(lockPath: string): AtomicFileLockOwner | undefined {\n let contents: string\n try {\n contents = readFileSync(lockPath, 'utf8').trim()\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n\n let value: unknown\n try {\n value = JSON.parse(contents)\n } catch (error) {\n throw invalidOwner(lockPath, error)\n }\n if (!isOwner(value)) throw invalidOwner(lockPath)\n return value\n}\n\nfunction isOwner(value: unknown): value is AtomicFileLockOwner {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record<string, unknown>\n return (\n Object.keys(record).length === 3 &&\n Number.isSafeInteger(record.pid) &&\n Number(record.pid) > 0 &&\n typeof record.host === 'string' &&\n record.host.trim().length > 0 &&\n typeof record.nonce === 'string' &&\n record.nonce.trim().length > 0\n )\n}\n\nfunction invalidOwner(lockPath: string, cause?: unknown): AtomicFileLockError {\n const error = new AtomicFileLockError(\n `atomic file lock has an invalid owner (${lockPath}); refusing unsafe recovery`,\n )\n if (cause !== undefined) Object.defineProperty(error, 'cause', { value: cause })\n return error\n}\n\nfunction releaseOwnedPath(lockPath: string, owner: AtomicFileLockOwner): void {\n const current = readOwner(lockPath)\n if (!current) return\n if (canonicalOwner(current) !== canonicalOwner(owner)) {\n throw new AtomicFileLockError(`atomic file lock owner changed before release (${lockPath})`)\n }\n try {\n unlinkSync(lockPath)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n\nfunction canonicalOwner(owner: AtomicFileLockOwner): string {\n return JSON.stringify({ host: owner.host, nonce: owner.nonce, pid: owner.pid })\n}\n\nfunction recoveryPath(lockPath: string): string {\n return `${lockPath}.reclaim`\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'EEXIST'\n}\n\nfunction isMissing(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ENOENT'\n}\n\nfunction isNoSuchProcess(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ESRCH'\n}\n\nfunction unlinkIfExists(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n","/** Filesystem durability and cross-process exclusion for append-only journal files. */\n\nimport { closeSync, constants, fsyncSync, mkdirSync, openSync, writeSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { AtomicFileLockError, tryAcquireAtomicFileLock } from './atomic-file-lock'\n\n/** How a journal binding reports file-layer faults in its own error taxonomy. */\nexport interface LedgerFileContext {\n /** Noun used in error messages, e.g. 'search ledger'. */\n subject: string\n integrityError(message: string, options?: { cause?: unknown }): Error\n}\n\n/** Append one already-serialized line; the write is fsynced (file and directory)\n * before returning so an acknowledged append survives a crash. */\nexport function appendLedgerLine(path: string, line: string, context: LedgerFileContext): void {\n mkdirSync(dirname(path), { recursive: true })\n const fd = openSync(path, constants.O_CREAT | constants.O_WRONLY | constants.O_APPEND, 0o600)\n try {\n writeAll(fd, Buffer.from(line, 'utf8'), context)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n fsyncDirectory(dirname(path))\n}\n\nexport function withLedgerFileLock<T>(path: string, context: LedgerFileContext, run: () => T): T {\n const result = tryWithLedgerFileLock(path, context, run)\n if (!result.acquired) {\n throw context.integrityError(`${context.subject} lock is held (${path})`)\n }\n return result.value\n}\n\nexport type FileLockResult<T> = { acquired: true; value: T } | { acquired: false }\n\nexport function tryWithLedgerFileLock<T>(\n path: string,\n context: LedgerFileContext,\n run: () => T,\n): FileLockResult<T> {\n mkdirSync(dirname(path), { recursive: true })\n const lockPath = `${path}.lock`\n try {\n const acquisition = tryAcquireAtomicFileLock({ lockPath })\n if (!acquisition.acquired) return { acquired: false }\n try {\n return { acquired: true, value: run() }\n } finally {\n acquisition.lock.release()\n }\n } catch (error) {\n if (error instanceof AtomicFileLockError) {\n throw context.integrityError(error.message, { cause: error })\n }\n throw error\n }\n}\n\nfunction writeAll(fd: number, bytes: Buffer, context: LedgerFileContext): void {\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset)\n if (written <= 0) throw context.integrityError('filesystem wrote zero bytes')\n offset += written\n }\n}\n\nfunction fsyncDirectory(path: string): void {\n const fd = openSync(path, constants.O_RDONLY)\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n","/**\n * Generic durable append-only journal with a SHA-256 hash chain.\n *\n * The file format is canonical JSONL: every row is the canonical JSON encoding\n * (object keys sorted recursively) of one entry, and every entry hashes the\n * previous entry's hash so the log is tamper-evident. Appends are serialized\n * in-process per path and across processes via a lock file, fsynced before\n * acknowledgement, and idempotent by `eventId`. A malformed, non-canonical,\n * truncated, reordered, or conflicting log fails loudly; a bad row is never\n * skipped.\n *\n * Domain vocabulary lives entirely in the consumer's codec: entry schema\n * validation, the constant header fields stamped into every entry, the error\n * taxonomy, and the state machine replayed over verified entries.\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { Mutex } from '../concurrency'\nimport { canonicalize } from '../pre-registration'\nimport { appendLedgerLine, type LedgerFileContext, withLedgerFileLock } from './journal-file'\n\nexport type LedgerHash = `sha256:${string}`\n\n/** Canonical JSON encoding: object keys sorted recursively. This is the byte\n * form that is hashed and stored, so identical values always encode identically. */\nexport function canonicalString(value: unknown): string {\n return JSON.stringify(canonicalize(value))\n}\n\nexport function hashCanonical(value: unknown): LedgerHash {\n return `sha256:${createHash('sha256').update(canonicalString(value)).digest('hex')}`\n}\n\n/** Minimum shape of a journal event: the idempotency key. */\nexport interface LedgerEventBase {\n eventId: string\n}\n\n/** Chain envelope every entry carries in addition to the journal's constant\n * header fields. `entryHash` covers the header, sequence, previous hash, and\n * event, so any rewrite of history invalidates every later entry. */\nexport interface LedgerChainFields<Event extends LedgerEventBase> {\n sequence: number\n previousHash: LedgerHash | null\n event: Event\n entryHash: LedgerHash\n}\n\nexport type LedgerEntryOf<Header extends object, Event extends LedgerEventBase> = Header &\n LedgerChainFields<Event>\n\nexport interface LedgerLineContext {\n path: string\n line: number\n}\n\n/** Domain state machine replayed over chain-verified entries in order.\n * `apply` throws (via the codec's error taxonomy) on an invalid transition;\n * `finish` builds the consumer's projection once every entry was applied. */\nexport interface LedgerProjector<Entry, Projection> {\n apply(entry: Entry, index: number): void\n finish(entries: Entry[]): Projection\n}\n\nexport interface LedgerJournalCodec<\n Header extends object,\n Event extends LedgerEventBase,\n Projection,\n> extends LedgerFileContext {\n /** Constant fields stamped into every entry and covered by its hash. */\n header: Header\n conflictError(message: string): Error\n /** Validate one parsed JSON row into a typed entry. Must reject malformed\n * rows and non-canonical event encodings with the binding's own errors;\n * the journal itself verifies the stored bytes and the hash chain. */\n parseEntry(raw: unknown, context: LedgerLineContext): LedgerEntryOf<Header, Event>\n /** Reject an entry whose constant header fields do not match this journal. */\n checkEntryHeader(entry: LedgerEntryOf<Header, Event>, index: number): void\n createProjector(): LedgerProjector<LedgerEntryOf<Header, Event>, Projection>\n}\n\nexport interface LedgerReplayResult<Entry, Projection> {\n entries: Entry[]\n projection: Projection\n}\n\nexport interface LedgerAppendResult<Entry, Projection> {\n entry: Entry\n /** False when the exact event was already durably present. */\n appended: boolean\n projection: Projection\n}\n\n// One async mutex per resolved journal path so concurrent appends from a single\n// process queue up instead of failing on the held cross-process lock file.\nconst journalMutexes = new Map<string, Mutex>()\n\nfunction mutexFor(path: string): Mutex {\n const existing = journalMutexes.get(path)\n if (existing) return existing\n const mutex = new Mutex()\n journalMutexes.set(path, mutex)\n return mutex\n}\n\n/** Durable filesystem journal. Construction performs no I/O; `append` and\n * `replay` validate the complete existing file under the locks. */\nexport class FileLedgerJournal<Header extends object, Event extends LedgerEventBase, Projection> {\n readonly path: string\n private readonly codec: LedgerJournalCodec<Header, Event, Projection>\n private readonly mutex: Mutex\n\n constructor(path: string, codec: LedgerJournalCodec<Header, Event, Projection>) {\n this.path = resolve(path)\n this.codec = codec\n this.mutex = mutexFor(this.path)\n }\n\n async replay(): Promise<LedgerReplayResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => this.replayLocked()),\n )\n }\n\n async append(\n event: Event,\n ): Promise<LedgerAppendResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n const before = this.replayLocked()\n const existing = before.entries.find((entry) => entry.event.eventId === event.eventId)\n if (existing) {\n if (canonicalString(existing.event) !== canonicalString(event)) {\n throw this.codec.conflictError(\n `eventId ${event.eventId} already exists with different content`,\n )\n }\n return { entry: existing, appended: false, projection: before.projection }\n }\n\n const material = {\n ...this.codec.header,\n sequence: before.entries.length,\n previousHash: before.entries.at(-1)?.entryHash ?? null,\n event,\n }\n const entry = { ...material, entryHash: hashCanonical(material) }\n\n // Apply the state transition before spending an append: an entry the\n // projector rejects must never reach the durable file.\n const projection = this.project([...before.entries, entry])\n appendLedgerLine(this.path, `${canonicalString(entry)}\\n`, this.codec)\n return { entry, appended: true, projection }\n }),\n )\n }\n\n private replayLocked(): LedgerReplayResult<LedgerEntryOf<Header, Event>, Projection> {\n const entries = this.readEntries()\n return { entries, projection: this.project(entries) }\n }\n\n private readEntries(): LedgerEntryOf<Header, Event>[] {\n if (!existsSync(this.path)) return []\n const text = readFileSync(this.path, 'utf8')\n if (text.length === 0) return []\n if (!text.endsWith('\\n')) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a truncated final record (missing newline)`,\n )\n }\n\n const lines = text.slice(0, -1).split('\\n')\n const entries: LedgerEntryOf<Header, Event>[] = []\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index]!\n if (line.length === 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a blank row at line ${index + 1}`,\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(line)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has invalid JSON at line ${index + 1}`,\n { cause: error },\n )\n }\n const entry = this.codec.parseEntry(raw, { path: this.path, line: index + 1 })\n if (line !== canonicalString(entry)) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has non-canonical bytes at line ${index + 1}`,\n )\n }\n entries.push(entry)\n }\n return entries\n }\n\n private project(entries: LedgerEntryOf<Header, Event>[]): Projection {\n const projector = this.codec.createProjector()\n const eventIds = new Set<string>()\n let expectedPrevious: LedgerHash | null = null\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index]!\n this.codec.checkEntryHeader(entry, index)\n if (entry.sequence !== index) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} has sequence ${entry.sequence}, expected ${index}`,\n )\n }\n if (entry.previousHash !== expectedPrevious) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} does not extend the previous hash`,\n )\n }\n const { entryHash: _entryHash, ...material } = entry\n const expectedHash = hashCanonical(material)\n if (entry.entryHash !== expectedHash) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} hash mismatch: expected ${expectedHash}, got ${entry.entryHash}`,\n )\n }\n expectedPrevious = entry.entryHash\n if (eventIds.has(entry.event.eventId)) {\n throw this.codec.integrityError(\n `duplicate eventId ${entry.event.eventId} in durable ledger`,\n )\n }\n eventIds.add(entry.event.eventId)\n projector.apply(entry, index)\n }\n return projector.finish(entries)\n }\n}\n"],"mappings":";;;;;;;;AAyCA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,OAAyB;AAC3B;;AAQA,SAAgB,oBACd,SACkC;CAClC,IAAI,WAAW,aAAa,QAAQ,QAAQ,C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iBAAiB,kBACzB,MAAM,KAAK,MAAM,eACf,SAAS,MAAM,MAAM,QAAQ,mCAC/B;GAEF,MAAM,EAAE,WAAW,YAAY,GAAG,aAAa;GAC/C,MAAM,eAAe,cAAc,QAAQ;GAC3C,IAAI,MAAM,cAAc,cACtB,MAAM,KAAK,MAAM,eACf,SAAS,MAAM,MAAM,QAAQ,2BAA2B,aAAa,QAAQ,MAAM,WACrF;GAEF,mBAAmB,MAAM;GACzB,IAAI,SAAS,IAAI,MAAM,MAAM,OAAO,GAClC,MAAM,KAAK,MAAM,eACf,qBAAqB,MAAM,MAAM,QAAQ,mBAC3C;GAEF,SAAS,IAAI,MAAM,MAAM,OAAO;GAChC,UAAU,MAAM,OAAO,KAAK;EAC9B;EACA,OAAO,UAAU,OAAO,OAAO;CACjC;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"opencode-sqlite-BGrHeDu3.js","names":["isRecord"],"sources":["../src/rollout/readers/claude-jsonl.ts","../src/rollout/readers/opencode-sqlite.ts"],"sourcesContent":["/**\n * Backfill reader over Claude Code project transcripts\n * (~/.claude/projects/<cwd-slug>/<sessionId>.jsonl) → canonical\n * chat-with-tools messages plus per-session token usage.\n *\n * Transcript lines consumed: type:\"user\" (string content or content blocks —\n * text + tool_result) and type:\"assistant\" (content blocks — thinking, text,\n * tool_use; message.usage carries tokens). Sidechain lines (isSidechain=true,\n * subagent threads) are separate invocations and are excluded from the main\n * transcript. Everything else (queue-operation, attachment, last-prompt…) is\n * transport metadata, not conversation.\n */\n\nimport { readdir, readFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { ChatMessage, ChatToolCall } from '../schema'\n\nexport const DEFAULT_CLAUDE_PROJECTS_DIR = join(homedir(), '.claude', 'projects')\n\n/** Claude Code's project-directory slug for a working directory. */\nexport function claudeProjectSlug(cwd: string): string {\n return cwd.replace(/[^a-zA-Z0-9-]/g, '-')\n}\n\nexport interface ClaudeTranscriptRef {\n sessionId: string\n path: string\n}\n\n/** Transcript files recorded for sessions launched from `cwd`. */\nexport async function findClaudeTranscripts(\n cwd: string,\n projectsDir: string = DEFAULT_CLAUDE_PROJECTS_DIR,\n): Promise<ClaudeTranscriptRef[]> {\n const dir = join(projectsDir, claudeProjectSlug(cwd))\n const names = await readdir(dir).catch(() => [])\n return names\n .filter((n) => n.endsWith('.jsonl'))\n .sort()\n .map((n) => ({ sessionId: n.replace(/\\.jsonl$/, ''), path: join(dir, n) }))\n}\n\nexport interface ClaudeUsageTotals {\n tokensIn: number\n tokensOut: number\n cacheRead: number\n cacheWrite: number\n}\n\nexport interface ClaudeTranscript {\n messages: ChatMessage[]\n usage: ClaudeUsageTotals\n /** Timestamp of the first conversation line; null = empty transcript. */\n startedAt: string | null\n endedAt: string | null\n model: string | null\n}\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\n/**\n * One conversation line of a transcript, still in Claude Code's own shape.\n *\n * This is the single line-level parse of the format. `readClaudeTranscript`\n * projects it to canonical messages + usage; the supervision-tree reader\n * (`src/supervisor-run/claude-code-reader.ts`) projects the SAME entries to\n * spawn/settle/steer instants. Two projections, one parser — a second\n * transcript parser is how the two views silently disagree.\n */\nexport interface ClaudeEntry {\n readonly type: 'user' | 'assistant'\n /** ISO instant of the line; null when the line carried none. */\n readonly timestamp: string | null\n /** The Anthropic message body (`role`, `content`, `model`, `usage`). */\n readonly message: Record<string, unknown>\n /** Claude Code's structured tool result, when the line carries one. */\n readonly toolUseResult: unknown\n /** True on subagent threads — a separate invocation, not this transcript's turn. */\n readonly isSidechain: boolean\n /** Subagent id Claude Code stamps on sidechain lines; null on main-thread lines. */\n readonly agentId: string | null\n}\n\n/** Parse transcript jsonl text into conversation lines. Non-conversation lines are dropped. */\nexport function parseClaudeEntries(raw: string): ClaudeEntry[] {\n const out: ClaudeEntry[] = []\n for (const line of raw.split('\\n')) {\n if (!line.trim()) continue\n let entry: Record<string, unknown>\n try {\n const parsed: unknown = JSON.parse(line)\n if (!isRecord(parsed)) continue\n entry = parsed\n } catch {\n continue\n }\n if (entry.type !== 'user' && entry.type !== 'assistant') continue\n const message = entry.message\n if (!isRecord(message)) continue\n out.push({\n type: entry.type,\n timestamp: typeof entry.timestamp === 'string' ? entry.timestamp : null,\n message,\n toolUseResult: entry.toolUseResult,\n isSidechain: entry.isSidechain === true,\n agentId: typeof entry.agentId === 'string' ? entry.agentId : null,\n })\n }\n return out\n}\n\nexport interface ReadClaudeTranscriptOptions {\n /**\n * Read the sidechain (subagent) thread instead of skipping it. Subagent\n * transcripts under `<session>/subagents/agent-<id>.jsonl` are sidechain\n * lines end to end, so their usage is invisible without this.\n */\n readonly includeSidechain?: boolean\n}\n\nfunction blockText(content: unknown): string {\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n return content\n .filter(\n (b): b is Record<string, unknown> =>\n isRecord(b) && b.type === 'text' && typeof b.text === 'string',\n )\n .map((b) => b.text as string)\n .join('\\n')\n}\n\n/** Parse one transcript jsonl into canonical messages + usage totals. */\nexport async function readClaudeTranscript(\n path: string,\n options: ReadClaudeTranscriptOptions = {},\n): Promise<ClaudeTranscript> {\n return transcriptFromEntries(parseClaudeEntries(await readFile(path, 'utf8')), options)\n}\n\n/** The messages+usage projection of already-parsed entries. */\nexport function transcriptFromEntries(\n entries: readonly ClaudeEntry[],\n options: ReadClaudeTranscriptOptions = {},\n): ClaudeTranscript {\n const wantSidechain = options.includeSidechain === true\n const messages: ChatMessage[] = []\n const usage: ClaudeUsageTotals = { tokensIn: 0, tokensOut: 0, cacheRead: 0, cacheWrite: 0 }\n let startedAt: string | null = null\n let endedAt: string | null = null\n let model: string | null = null\n // Claude Code writes one jsonl line PER CONTENT BLOCK of an API message,\n // repeating message.id and usage on each — merge blocks into one canonical\n // assistant turn and count usage once per API message id.\n let lastAssistantApiId: string | null = null\n let lastAssistantIndex = -1\n\n for (const entry of entries) {\n if (entry.isSidechain !== wantSidechain) continue\n const message = entry.message\n if (entry.timestamp !== null) {\n if (startedAt === null) startedAt = entry.timestamp\n endedAt = entry.timestamp\n }\n\n if (entry.type === 'user') {\n lastAssistantApiId = null\n lastAssistantIndex = -1\n const content = message.content\n if (typeof content === 'string') {\n messages.push({ role: 'user', content })\n continue\n }\n if (!Array.isArray(content)) continue\n // A user line may interleave tool_result blocks (answers to the prior\n // assistant tool_use) with plain text; preserve order.\n let userText = ''\n for (const block of content) {\n if (!isRecord(block)) continue\n if (block.type === 'tool_result' && typeof block.tool_use_id === 'string') {\n messages.push({\n role: 'tool',\n tool_call_id: block.tool_use_id,\n content:\n blockText(block.content) || (typeof block.content === 'string' ? block.content : ''),\n })\n } else if (block.type === 'text' && typeof block.text === 'string') {\n userText += (userText.length > 0 ? '\\n' : '') + block.text\n }\n }\n if (userText.length > 0) messages.push({ role: 'user', content: userText })\n continue\n }\n\n // assistant\n if (typeof message.model === 'string') model = message.model\n const apiId = typeof message.id === 'string' ? message.id : null\n const continuesTurn = apiId !== null && apiId === lastAssistantApiId && lastAssistantIndex >= 0\n const msgUsage = message.usage\n if (isRecord(msgUsage) && !continuesTurn) {\n usage.tokensIn += typeof msgUsage.input_tokens === 'number' ? msgUsage.input_tokens : 0\n usage.tokensOut += typeof msgUsage.output_tokens === 'number' ? msgUsage.output_tokens : 0\n usage.cacheRead +=\n typeof msgUsage.cache_read_input_tokens === 'number' ? msgUsage.cache_read_input_tokens : 0\n usage.cacheWrite +=\n typeof msgUsage.cache_creation_input_tokens === 'number'\n ? msgUsage.cache_creation_input_tokens\n : 0\n }\n const content = message.content\n if (!Array.isArray(content)) continue\n let reasoning = ''\n let text = ''\n const toolCalls: ChatToolCall[] = []\n for (const block of content) {\n if (!isRecord(block)) continue\n if (\n block.type === 'thinking' &&\n typeof block.thinking === 'string' &&\n block.thinking.length > 0\n ) {\n reasoning += (reasoning.length > 0 ? '\\n' : '') + block.thinking\n } else if (block.type === 'text' && typeof block.text === 'string') {\n text += (text.length > 0 ? '\\n' : '') + block.text\n } else if (block.type === 'tool_use' && typeof block.id === 'string') {\n toolCalls.push({\n id: block.id,\n type: 'function',\n function: {\n name: typeof block.name === 'string' ? block.name : 'unknown',\n arguments: JSON.stringify(block.input ?? {}),\n },\n })\n }\n }\n if (reasoning.length === 0 && text.length === 0 && toolCalls.length === 0) continue\n if (continuesTurn) {\n const prev = messages[lastAssistantIndex]!\n if (text.length > 0) prev.content = prev.content === null ? text : `${prev.content}\\n${text}`\n if (reasoning.length > 0) {\n prev.reasoning_content =\n prev.reasoning_content === undefined\n ? reasoning\n : `${prev.reasoning_content}\\n${reasoning}`\n }\n if (toolCalls.length > 0) prev.tool_calls = [...(prev.tool_calls ?? []), ...toolCalls]\n continue\n }\n messages.push({\n role: 'assistant',\n content: text.length > 0 ? text : null,\n ...(reasoning.length > 0 ? { reasoning_content: reasoning } : {}),\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n })\n lastAssistantApiId = apiId\n lastAssistantIndex = messages.length - 1\n }\n\n return { messages, usage, startedAt, endedAt, model }\n}\n","/**\n * Read-only backfill reader over the opencode sqlite store\n * (~/.local/share/opencode/opencode.db) → canonical chat-with-tools messages.\n *\n * Schema consumed (observed, 2026-07): `session` rows carry directory /\n * parent_id / agent / model / cost / tokens_*; `message` rows carry a JSON\n * `data` blob ({role, modelID, providerID, tokens, cost, finish}); `part`\n * rows carry the actual content ({type: text|reasoning|tool|step-start|\n * step-finish|snapshot…}). Tool parts hold {callID, state:{input, output,\n * status}} — both the call and its result, which we split into an assistant\n * tool_call plus a role:\"tool\" result message.\n *\n * The store is mutable and can be corrupt (a `.corrupt-bak` sibling ships\n * next to it in the wild), so `openOpencodeDb` returns null instead of\n * throwing — callers record a gap line, never crash the backfill.\n */\n\nimport { createRequire } from 'node:module'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { DatabaseSync } from 'node:sqlite'\nimport type { ChatMessage, ChatToolCall } from '../schema'\n\nexport const DEFAULT_OPENCODE_DB = join(homedir(), '.local', 'share', 'opencode', 'opencode.db')\n\nexport interface OpencodeSessionRow {\n id: string\n parentId: string | null\n directory: string\n agent: string | null\n /** Raw session.model JSON: {id, providerID, variant} where present. */\n model: { id?: string; providerID?: string } | null\n costUsd: number\n tokensInput: number\n tokensOutput: number\n tokensReasoning: number\n tokensCacheRead: number\n tokensCacheWrite: number\n timeCreated: number\n timeUpdated: number\n}\n\n// `node:sqlite` is loaded through CommonJS `require`, not `import()`. esbuild\n// (bundling) and Vite (tests) both rewrite a dynamic import and strip the\n// `node:` prefix under an es20xx target, turning this builtin into a bogus\n// \"sqlite\" package lookup; composing the specifier at runtime does not reliably\n// defeat that (it still resolved through Vite's transform in some workers, so\n// the failure moved around as test files were added). A require obtained from\n// `createRequire` is not an analyzable module reference in either tool, so\n// neither can rewrite it.\nconst nodeRequire = createRequire(import.meta.url)\n\n/** Open the store read-only; null = unavailable/corrupt (caller records a gap). */\nexport async function openOpencodeDb(\n path: string = DEFAULT_OPENCODE_DB,\n): Promise<DatabaseSync | null> {\n try {\n const { DatabaseSync } = nodeRequire('node:sqlite') as typeof import('node:sqlite')\n const db = new DatabaseSync(path, { readOnly: true })\n // Probe: a corrupt store can open() fine and fail on first page read.\n db.prepare('SELECT id FROM session LIMIT 1').get()\n return db\n } catch {\n return null\n }\n}\n\nconst isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\nfunction parseSessionRow(row: Record<string, unknown>): OpencodeSessionRow {\n let model: OpencodeSessionRow['model'] = null\n if (typeof row.model === 'string' && row.model.length > 0) {\n try {\n const parsed: unknown = JSON.parse(row.model)\n if (isRecord(parsed)) model = parsed as { id?: string; providerID?: string }\n } catch {\n model = null\n }\n }\n return {\n id: String(row.id),\n parentId: row.parent_id === null || row.parent_id === undefined ? null : String(row.parent_id),\n directory: String(row.directory),\n agent: row.agent === null || row.agent === undefined ? null : String(row.agent),\n model,\n costUsd: Number(row.cost ?? 0),\n tokensInput: Number(row.tokens_input ?? 0),\n tokensOutput: Number(row.tokens_output ?? 0),\n tokensReasoning: Number(row.tokens_reasoning ?? 0),\n tokensCacheRead: Number(row.tokens_cache_read ?? 0),\n tokensCacheWrite: Number(row.tokens_cache_write ?? 0),\n timeCreated: Number(row.time_created ?? 0),\n timeUpdated: Number(row.time_updated ?? 0),\n }\n}\n\nconst SESSION_COLUMNS =\n 'id, parent_id, directory, agent, model, cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write, time_created, time_updated'\n\n/** Sessions whose cwd is `directory` (the worker-clone join key). */\nexport function findOpencodeSessionsByDirectory(\n db: DatabaseSync,\n directory: string,\n): OpencodeSessionRow[] {\n const rows = db\n .prepare(`SELECT ${SESSION_COLUMNS} FROM session WHERE directory = ? ORDER BY time_created`)\n .all(directory) as Array<Record<string, unknown>>\n return rows.map(parseSessionRow)\n}\n\nexport function findOpencodeSessionById(\n db: DatabaseSync,\n sessionId: string,\n): OpencodeSessionRow | null {\n const row = db.prepare(`SELECT ${SESSION_COLUMNS} FROM session WHERE id = ?`).get(sessionId) as\n | Record<string, unknown>\n | undefined\n return row === undefined ? null : parseSessionRow(row)\n}\n\ninterface OpencodePart {\n type?: string\n text?: string\n tool?: string\n callID?: string\n state?: { status?: string; input?: unknown; output?: unknown }\n}\n\nfunction toolResultContent(output: unknown): string {\n if (typeof output === 'string') return output\n if (output === null || output === undefined) return ''\n return JSON.stringify(output)\n}\n\n/**\n * Convert one session's message+part rows into canonical messages.\n * An opencode assistant message row spans several model steps; each step's\n * parts (reasoning → text → tool …) become one assistant message followed by\n * the role:\"tool\" results of its calls, preserving order.\n */\nexport function readOpencodeSessionMessages(db: DatabaseSync, sessionId: string): ChatMessage[] {\n const messageRows = db\n .prepare('SELECT id, data FROM message WHERE session_id = ? ORDER BY time_created, id')\n .all(sessionId) as Array<{ id: string; data: string }>\n const partsStmt = db.prepare('SELECT data FROM part WHERE message_id = ? ORDER BY id')\n\n const messages: ChatMessage[] = []\n for (const messageRow of messageRows) {\n let data: Record<string, unknown>\n try {\n const parsed: unknown = JSON.parse(messageRow.data)\n if (!isRecord(parsed)) continue\n data = parsed\n } catch {\n continue\n }\n const parts: OpencodePart[] = []\n for (const row of partsStmt.all(messageRow.id) as Array<{ data: string }>) {\n try {\n const parsed: unknown = JSON.parse(row.data)\n if (isRecord(parsed)) parts.push(parsed as OpencodePart)\n } catch {\n // Malformed part payload: skip the part, keep the message.\n }\n }\n\n if (data.role === 'user') {\n const text = parts\n .filter((p) => p.type === 'text' && typeof p.text === 'string')\n .map((p) => p.text as string)\n .join('\\n')\n messages.push({ role: 'user', content: text })\n continue\n }\n if (data.role !== 'assistant') continue\n\n // Split the row into steps at step-start boundaries; parts before the\n // first step-start (none observed, but tolerated) form an implicit step.\n const steps: OpencodePart[][] = []\n let current: OpencodePart[] = []\n for (const part of parts) {\n if (part.type === 'step-start') {\n if (current.length > 0) steps.push(current)\n current = []\n continue\n }\n if (part.type === 'step-finish' || part.type === 'snapshot' || part.type === 'patch') continue\n current.push(part)\n }\n if (current.length > 0) steps.push(current)\n\n for (const step of steps) {\n const reasoning = step\n .filter((p) => p.type === 'reasoning' && typeof p.text === 'string' && p.text.length > 0)\n .map((p) => p.text as string)\n .join('\\n')\n const text = step\n .filter((p) => p.type === 'text' && typeof p.text === 'string')\n .map((p) => p.text as string)\n .join('\\n')\n const toolParts = step.filter((p) => p.type === 'tool' && typeof p.callID === 'string')\n const toolCalls: ChatToolCall[] = toolParts.map((p) => ({\n id: p.callID as string,\n type: 'function',\n function: {\n name: p.tool ?? 'unknown',\n arguments: JSON.stringify(p.state?.input ?? {}),\n },\n }))\n if (reasoning.length === 0 && text.length === 0 && toolCalls.length === 0) continue\n messages.push({\n role: 'assistant',\n content: text.length > 0 ? text : null,\n ...(reasoning.length > 0 ? { reasoning_content: reasoning } : {}),\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n })\n for (const p of toolParts) {\n messages.push({\n role: 'tool',\n tool_call_id: p.callID as string,\n name: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ACnB;EACA,IAAI,QAAQ,SAAS,GAAG,MAAM,KAAK,OAAO;EAE1C,KAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,YAAY,KACf,QAAQ,MAAM,EAAE,SAAS,eAAe,OAAO,EAAE,SAAS,YAAY,EAAE,KAAK,SAAS,CAAC,CAAC,CACxF,KAAK,MAAM,EAAE,IAAc,CAAC,CAC5B,KAAK,IAAI;GACZ,MAAM,OAAO,KACV,QAAQ,MAAM,EAAE,SAAS,UAAU,OAAO,EAAE,SAAS,QAAQ,CAAC,CAC9D,KAAK,MAAM,EAAE,IAAc,CAAC,CAC5B,KAAK,IAAI;GACZ,MAAM,YAAY,KAAK,QAAQ,MAAM,EAAE,SAAS,UAAU,OAAO,EAAE,WAAW,QAAQ;GACtF,MAAM,YAA4B,UAAU,KAAK,OAAO;IACtD,IAAI,EAAE;IACN,MAAM;IACN,UAAU;KACR,MAAM,EAAE,QAAQ;KAChB,WAAW,KAAK,UAAU,EAAE,OAAO,SAAS,CAAC,CAAC;IAChD;GACF,EAAE;GACF,IAAI,UAAU,WAAW,KAAK,KAAK,WAAW,KAAK,UAAU,WAAW,GAAG;GAC3E,SAAS,KAAK;IACZ,MAAM;IACN,SAAS,KAAK,SAAS,IAAI,OAAO;IAClC,GAAI,UAAU,SAAS,IAAI,EAAE,mBAAmB,UAAU,IAAI,CAAC;IAC/D,GAAI,UAAU,SAAS,IAAI,EAAE,YAAY,UAAU,IAAI,CAAC;GAC1D,CAAC;GACD,KAAK,MAAM,KAAK,WACd,SAAS,KAAK;IACZ,MAAM;IACN,cAAc,EAAE;IAChB,MAAM,EAAE,QAAQ;IAChB,SAAS,kBAAkB,EAAE,OAAO,MAAM;GAC5C,CAAC;EAEL;CACF;CACA,OAAO;AACT"}
@@ -1,96 +0,0 @@
1
- //#region src/pre-registration.ts
2
- /**
3
- * Deterministic JSON canonicalization — sort object keys recursively.
4
- *
5
- * Two semantically-equal objects produce byte-identical canonicalized output;
6
- * this is what makes a content-hash stable across encoders, key insertion
7
- * orders, and runtime versions. Exported for any consumer that needs the same
8
- * canonicalization guarantee outside the manifest-signing path (e.g., signing
9
- * an artifact bundle, hashing a dataset version, etc.).
10
- */
11
- function canonicalize(v) {
12
- if (v === null || typeof v !== "object") return v;
13
- if (Array.isArray(v)) return v.map(canonicalize);
14
- const keys = Object.keys(v).sort();
15
- const out = {};
16
- for (const k of keys) out[k] = canonicalize(v[k]);
17
- return out;
18
- }
19
- /**
20
- * SHA-256 hex (full 64 chars) over the canonicalized JSON encoding of `obj`.
21
- *
22
- * The same primitive `signManifest` and `verifyManifest` are built on, exposed
23
- * directly so consumers signing arbitrary structured content (artifact bundles,
24
- * production packets, dataset manifests, etc.) don't have to re-derive
25
- * canonicalize+sha256 from scratch.
26
- *
27
- * Stable across:
28
- * - object key insertion order (canonicalization sorts keys recursively)
29
- * - encoder choice (UTF-8 via TextEncoder, fixed)
30
- * - runtime (uses the Web Crypto subtle digest, present in Node ≥18 and browsers)
31
- *
32
- * Named `hashJson` to disambiguate from `prompt-registry.ts`'s `hashContent`,
33
- * which takes a string input and returns a truncated 12-char prompt id.
34
- * Use `hashJson` when you mean "canonicalize then hash."
35
- *
36
- * @example
37
- * const hash = await hashJson({ id: '1', kind: 'spec' })
38
- * // 'a3f1...' (64 hex chars)
39
- */
40
- async function hashJson(obj) {
41
- const canonical = canonicalize(obj);
42
- const bytes = new TextEncoder().encode(JSON.stringify(canonical));
43
- const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
44
- return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
45
- }
46
- /**
47
- * Sign a manifest with a SHA-256 content hash.
48
- *
49
- * The hash covers the canonicalized manifest with the `contentHash`
50
- * and `algo` fields stripped; this lets verifiers re-sign the rest and
51
- * compare. Returned manifest always carries `algo: 'sha256-content'`
52
- * so downstream consumers can identify the scheme; manifests without
53
- * `algo` still verify because it is stripped before hashing on both sides.
54
- */
55
- async function signManifest(m) {
56
- const hash = await hashJson(m);
57
- return {
58
- ...m,
59
- contentHash: hash,
60
- algo: "sha256-content"
61
- };
62
- }
63
- /**
64
- * Verify that a signed manifest has not been tampered with.
65
- *
66
- * Strips `contentHash` and `algo` before re-signing so manifests without
67
- * `algo` verify identically to ones that carry it.
68
- */
69
- async function verifyManifest(m) {
70
- const { contentHash, algo: _algo, ...rest } = m;
71
- return (await signManifest(rest)).contentHash === contentHash;
72
- }
73
- /**
74
- * Evaluate a pre-registered hypothesis against observed results.
75
- * Mechanical — no re-interpretation permitted.
76
- */
77
- async function evaluateHypothesis(manifest, observed) {
78
- if (!await verifyManifest(manifest)) throw new Error("evaluateHypothesis: manifest content hash mismatch (tampered)");
79
- const reasons = [];
80
- if (!(manifest.direction === "increase" ? observed.effect > 0 : observed.effect < 0)) reasons.push("wrong_direction");
81
- if (Math.abs(observed.effect) < manifest.minEffect) reasons.push("effect_too_small");
82
- if (observed.pValue >= manifest.alpha) reasons.push("not_significant");
83
- if (observed.n < manifest.preRegisteredN) reasons.push("undersampled");
84
- return {
85
- manifest,
86
- observedN: observed.n,
87
- observedEffect: observed.effect,
88
- observedPValue: observed.pValue,
89
- confirmed: reasons.length === 0,
90
- rejectionReasons: reasons
91
- };
92
- }
93
- //#endregion
94
- export { verifyManifest as a, signManifest as i, evaluateHypothesis as n, hashJson as r, canonicalize as t };
95
-
96
- //# sourceMappingURL=pre-registration-DakwTRXk.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"pre-registration-DakwTRXk.js","names":[],"sources":["../src/pre-registration.ts"],"sourcesContent":["/**\n * Pre-registered hypotheses — declare what you're testing BEFORE the\n * run, check it AFTER. Prevents p-hacking, optional stopping, and the\n * \"we ran until it looked good\" failure mode.\n *\n * Manifest is a plain JSON-friendly object. Sign it with a content hash\n * + timestamp; the registered record becomes immutable. Post-run,\n * evaluate the manifest against observed results — the library refuses\n * to let you re-interpret a different metric as the declared one.\n */\n\nexport interface HypothesisManifest {\n id: string\n /** Human prose — goes into the audit trail. */\n hypothesis: string\n /** Metric the hypothesis claims to move. */\n metric: string\n /** 'increase' = candidate should score higher than baseline; 'decrease' = lower. */\n direction: 'increase' | 'decrease'\n /** Minimum effect size to count (same units as the metric). */\n minEffect: number\n /** Alpha threshold. */\n alpha: number\n /** Target statistical power at which sample size was pre-computed. */\n power: number\n /** Declared N per arm before running. */\n preRegisteredN: number\n /** ISO8601 timestamp the manifest was registered. */\n registeredAt: string\n /** Optional identifiers to tie into the trace corpus. */\n baselineLabel?: string\n candidateLabel?: string\n}\n\n/**\n * Identifier for the hashing scheme used to produce `contentHash`.\n *\n * `'sha256-content'` — sha256 hex over the canonicalized manifest with\n * the `contentHash` and `algo` fields stripped. Held as a string union\n * so future schemes can be added without breaking parsers; SignedManifest\n * values without `algo` deserialize cleanly because the field is optional.\n */\nexport type SignedManifestAlgo = 'sha256-content'\n\nexport interface SignedManifest extends HypothesisManifest {\n /** sha256 hex of canonicalized manifest (everything except contentHash and algo). */\n contentHash: string\n /**\n * Algorithm string describing how `contentHash` was produced.\n *\n * Optional on the type so serialized manifests without it still parse,\n * but ALWAYS populated by {@link signManifest}. Consumers that want to\n * enforce a known algorithm should reject manifests where this field\n * is missing or unrecognized.\n */\n algo?: SignedManifestAlgo\n}\n\nexport interface HypothesisResult {\n manifest: SignedManifest\n observedN: number\n observedEffect: number\n observedPValue: number\n /** True iff the observed effect hits the pre-declared direction with\n * magnitude ≥ minEffect AND p < alpha. */\n confirmed: boolean\n /** Enumerated reasons the hypothesis was rejected (each a machine-tag). */\n rejectionReasons: Array<\n 'wrong_direction' | 'effect_too_small' | 'not_significant' | 'undersampled'\n >\n notes?: string\n}\n\n/**\n * Deterministic JSON canonicalization — sort object keys recursively.\n *\n * Two semantically-equal objects produce byte-identical canonicalized output;\n * this is what makes a content-hash stable across encoders, key insertion\n * orders, and runtime versions. Exported for any consumer that needs the same\n * canonicalization guarantee outside the manifest-signing path (e.g., signing\n * an artifact bundle, hashing a dataset version, etc.).\n */\nexport function canonicalize(v: unknown): unknown {\n if (v === null || typeof v !== 'object') return v\n if (Array.isArray(v)) return v.map(canonicalize)\n const keys = Object.keys(v as Record<string, unknown>).sort()\n const out: Record<string, unknown> = {}\n for (const k of keys) out[k] = canonicalize((v as Record<string, unknown>)[k])\n return out\n}\n\n/**\n * SHA-256 hex (full 64 chars) over the canonicalized JSON encoding of `obj`.\n *\n * The same primitive `signManifest` and `verifyManifest` are built on, exposed\n * directly so consumers signing arbitrary structured content (artifact bundles,\n * production packets, dataset manifests, etc.) don't have to re-derive\n * canonicalize+sha256 from scratch.\n *\n * Stable across:\n * - object key insertion order (canonicalization sorts keys recursively)\n * - encoder choice (UTF-8 via TextEncoder, fixed)\n * - runtime (uses the Web Crypto subtle digest, present in Node ≥18 and browsers)\n *\n * Named `hashJson` to disambiguate from `prompt-registry.ts`'s `hashContent`,\n * which takes a string input and returns a truncated 12-char prompt id.\n * Use `hashJson` when you mean \"canonicalize then hash.\"\n *\n * @example\n * const hash = await hashJson({ id: '1', kind: 'spec' })\n * // 'a3f1...' (64 hex chars)\n */\nexport async function hashJson<T>(obj: T): Promise<string> {\n const canonical = canonicalize(obj)\n const bytes = new TextEncoder().encode(JSON.stringify(canonical))\n const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes)\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n/**\n * Sign a manifest with a SHA-256 content hash.\n *\n * The hash covers the canonicalized manifest with the `contentHash`\n * and `algo` fields stripped; this lets verifiers re-sign the rest and\n * compare. Returned manifest always carries `algo: 'sha256-content'`\n * so downstream consumers can identify the scheme; manifests without\n * `algo` still verify because it is stripped before hashing on both sides.\n */\nexport async function signManifest(m: HypothesisManifest): Promise<SignedManifest> {\n const hash = await hashJson(m)\n return { ...m, contentHash: hash, algo: 'sha256-content' }\n}\n\n/**\n * Verify that a signed manifest has not been tampered with.\n *\n * Strips `contentHash` and `algo` before re-signing so manifests without\n * `algo` verify identically to ones that carry it.\n */\nexport async function verifyManifest(m: SignedManifest): Promise<boolean> {\n const { contentHash, algo: _algo, ...rest } = m\n void _algo\n const resigned = await signManifest(rest)\n return resigned.contentHash === contentHash\n}\n\n/**\n * Evaluate a pre-registered hypothesis against observed results.\n * Mechanical — no re-interpretation permitted.\n */\nexport async function evaluateHypothesis(\n manifest: SignedManifest,\n observed: { n: number; effect: number; pValue: number },\n): Promise<HypothesisResult> {\n if (!(await verifyManifest(manifest))) {\n throw new Error('evaluateHypothesis: manifest content hash mismatch (tampered)')\n }\n const reasons: HypothesisResult['rejectionReasons'] = []\n const directionOk = manifest.direction === 'increase' ? observed.effect > 0 : observed.effect < 0\n if (!directionOk) reasons.push('wrong_direction')\n if (Math.abs(observed.effect) < manifest.minEffect) reasons.push('effect_too_small')\n if (observed.pValue >= manifest.alpha) reasons.push('not_significant')\n if (observed.n < manifest.preRegisteredN) reasons.push('undersampled')\n return {\n manifest,\n observedN: observed.n,\n observedEffect: observed.effect,\n observedPValue: observed.pValue,\n confirmed: reasons.length === 0,\n rejectionReasons: reasons,\n }\n}\n"],"mappings":";;;;;;;;;;AAkFA,SAAgB,aAAa,GAAqB;CAChD,IAAI,MAAM,QAAQ,OAAO,MAAM,UAAU,OAAO;CAChD,IAAI,MAAM,QAAQ,CAAC,GAAG,OAAO,EAAE,IAAI,YAAY;CAC/C,MAAM,OAAO,OAAO,KAAK,CAA4B,CAAC,CAAC,KAAK;CAC5D,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,KAAK,MAAM,IAAI,KAAK,aAAc,EAA8B,EAAE;CAC7E,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;AAuBA,eAAsB,SAAY,KAAyB;CACzD,MAAM,YAAY,aAAa,GAAG;CAClC,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,SAAS,CAAC;CAChE,MAAM,SAAS,MAAM,WAAW,OAAO,OAAO,OAAO,WAAW,KAAK;CACrE,OAAO,MAAM,KAAK,IAAI,WAAW,MAAM,CAAC,CAAC,CACtC,KAAK,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAC3C,KAAK,EAAE;AACZ;;;;;;;;;;AAWA,eAAsB,aAAa,GAAgD;CACjF,MAAM,OAAO,MAAM,SAAS,CAAC;CAC7B,OAAO;EAAE,GAAG;EAAG,aAAa;EAAM,MAAM;CAAiB;AAC3D;;;;;;;AAQA,eAAsB,eAAe,GAAqC;CACxE,MAAM,EAAE,aAAa,MAAM,OAAO,GAAG,SAAS;CAG9C,QAAO,MADgB,aAAa,IAAI,EAAA,CACxB,gBAAgB;AAClC;;;;;AAMA,eAAsB,mBACpB,UACA,UAC2B;CAC3B,IAAI,CAAE,MAAM,eAAe,QAAQ,GACjC,MAAM,IAAI,MAAM,+DAA+D;CAEjF,MAAM,UAAgD,CAAC;CAEvD,IAAI,EADgB,SAAS,cAAc,aAAa,SAAS,SAAS,IAAI,SAAS,SAAS,IAC9E,QAAQ,KAAK,iBAAiB;CAChD,IAAI,KAAK,IAAI,SAAS,MAAM,IAAI,SAAS,WAAW,QAAQ,KAAK,kBAAkB;CACnF,IAAI,SAAS,UAAU,SAAS,OAAO,QAAQ,KAAK,iBAAiB;CACrE,IAAI,SAAS,IAAI,SAAS,gBAAgB,QAAQ,KAAK,cAAc;CACrE,OAAO;EACL;EACA,WAAW,SAAS;EACpB,gBAAgB,SAAS;EACzB,gBAAgB,SAAS;EACzB,WAAW,QAAQ,WAAW;EAC9B,kBAAkB;CACpB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"profile-cell.js","names":[],"sources":["../src/agent-profile-cell.ts"],"sourcesContent":["import type { AgentProfile } from '@tangle-network/agent-interface'\nimport { ValidationError } from './errors'\nimport { hashJson } from './pre-registration'\n\nexport type AgentProfileCellSchemaVersion = 'agent-profile-cell/v1'\n\nexport type AgentProfileJsonObject = { [key: string]: AgentProfileJson }\n\nexport type AgentProfileJson =\n | string\n | number\n | boolean\n | null\n | AgentProfileJson[]\n | AgentProfileJsonObject\n\nexport type AgentProfileDimensionValue = string | number | boolean | null\n\nexport interface AgentProfileSource {\n /** Runtime/profile contract being fingerprinted, e.g. `agent-interface-profile`. */\n kind: string\n /** sha256 over the canonical source profile object. */\n hash: string\n}\n\nexport interface AgentProfileSourceInput {\n kind: string\n /** Precomputed sha256 for callers that already sign their profile artifact. */\n hash?: string\n /** Full canonical runtime profile; hashed and then discarded from the cell. */\n profile?: AgentProfileJson\n}\n\nexport interface AgentProfileHarness {\n id: string\n version?: string\n hash?: string\n}\n\nexport interface AgentProfileCellInput {\n profileId: string\n sourceProfile: AgentProfileSourceInput\n harness?: AgentProfileHarness\n model?: string\n promptHash?: string\n dimensions?: Record<string, AgentProfileDimensionValue>\n}\n\nexport interface AgentProfileCell {\n schemaVersion: AgentProfileCellSchemaVersion\n cellId: string\n profileId: string\n sourceProfile: AgentProfileSource\n harness?: AgentProfileHarness\n model?: string\n promptHash?: string\n dimensions?: Record<string, AgentProfileDimensionValue>\n}\n\nexport class AgentProfileCellValidationError extends ValidationError {\n readonly path: string\n constructor(message: string, path = '') {\n super(path ? `${message} (at ${path})` : message)\n this.path = path\n }\n}\n\nconst SHA256_HEX = /^[0-9a-f]{64}$/\nconst CELL_ID = /^agent-profile-cell:sha256:[0-9a-f]{64}$/\n\nexport async function buildAgentProfileCell(\n input: AgentProfileCellInput,\n): Promise<AgentProfileCell> {\n const material = await normalizeAgentProfileCellInput(input)\n const cellId = `agent-profile-cell:sha256:${await hashJson(material)}`\n return { ...material, cellId }\n}\n\nexport function agentProfileCellHashMaterial(\n cell: AgentProfileCell,\n): Omit<AgentProfileCell, 'cellId'> {\n const { cellId: _cellId, ...material } = cell\n void _cellId\n return normalizeAgentProfileCell(material)\n}\n\n/**\n * Verify an `AgentProfileCell`'s `cellId` matches the sha256 of its hash-material fields, confirming the record has not been tampered with.\n */\nexport async function verifyAgentProfileCell(cell: AgentProfileCell): Promise<boolean> {\n validateAgentProfileCell(cell)\n return (\n cell.cellId ===\n `agent-profile-cell:sha256:${await hashJson(agentProfileCellHashMaterial(cell))}`\n )\n}\n\nexport function validateAgentProfileCell(input: unknown): AgentProfileCell {\n if (input === null || typeof input !== 'object') {\n throw new AgentProfileCellValidationError('expected object')\n }\n const obj = input as Record<string, unknown>\n expectLiteral(obj.schemaVersion, 'agent-profile-cell/v1', 'schemaVersion')\n if (typeof obj.cellId !== 'string' || !CELL_ID.test(obj.cellId)) {\n throw new AgentProfileCellValidationError(\n 'cellId must match agent-profile-cell:sha256:<64 lowercase hex chars>',\n 'cellId',\n )\n }\n expectString(obj.profileId, 'profileId')\n validateSource(obj.sourceProfile, 'sourceProfile')\n if (obj.harness !== undefined) validateHarness(obj.harness, 'harness')\n if (obj.model !== undefined) expectString(obj.model, 'model')\n if (obj.promptHash !== undefined) expectString(obj.promptHash, 'promptHash')\n if (obj.dimensions !== undefined) validateDimensions(obj.dimensions, 'dimensions')\n return input as AgentProfileCell\n}\n\nexport function requireAgentProfileCell(record: {\n runId: string\n agentProfile?: AgentProfileCell\n}): AgentProfileCell {\n if (!record.agentProfile) {\n throw new AgentProfileCellValidationError(\n `run \"${record.runId}\" is missing agentProfile; profile-cell grouping requires explicit profile identity`,\n 'agentProfile',\n )\n }\n return validateAgentProfileCell(record.agentProfile)\n}\n\nexport function agentProfileCellKey(record: {\n runId: string\n agentProfile?: AgentProfileCell\n}): string {\n return requireAgentProfileCell(record).cellId\n}\n\nexport async function assertRunAgentProfileCell(record: {\n runId: string\n model: string\n promptHash: string\n agentProfile?: AgentProfileCell\n}): Promise<AgentProfileCell> {\n const profile = requireAgentProfileCell(record)\n if (!(await verifyAgentProfileCell(profile))) {\n throw new AgentProfileCellValidationError(\n `run \"${record.runId}\" has an agentProfile.cellId that does not match its content`,\n 'agentProfile.cellId',\n )\n }\n if (profile.model !== undefined && profile.model !== record.model) {\n throw new AgentProfileCellValidationError(\n `run \"${record.runId}\" agentProfile.model \"${profile.model}\" does not match model \"${record.model}\"`,\n 'agentProfile.model',\n )\n }\n if (profile.promptHash !== undefined && profile.promptHash !== record.promptHash) {\n throw new AgentProfileCellValidationError(\n `run \"${record.runId}\" agentProfile.promptHash \"${profile.promptHash}\" does not match promptHash \"${record.promptHash}\"`,\n 'agentProfile.promptHash',\n )\n }\n return profile\n}\n\nexport function groupRunsByAgentProfileCell<\n T extends { runId: string; agentProfile?: AgentProfileCell },\n>(records: readonly T[]): Map<string, T[]> {\n const groups = new Map<string, T[]>()\n for (const record of records) {\n const key = agentProfileCellKey(record)\n const bucket = groups.get(key)\n if (bucket) bucket.push(record)\n else groups.set(key, [record])\n }\n return groups\n}\n\nasync function normalizeAgentProfileCellInput(\n input: AgentProfileCellInput,\n): Promise<Omit<AgentProfileCell, 'cellId'>> {\n return normalizeAgentProfileCell({\n schemaVersion: 'agent-profile-cell/v1',\n profileId: input.profileId,\n sourceProfile: await normalizeSourceInput(input.sourceProfile),\n harness: input.harness,\n model: input.model,\n promptHash: input.promptHash,\n dimensions: input.dimensions,\n })\n}\n\nfunction normalizeAgentProfileCell(\n input: Omit<AgentProfileCell, 'cellId'>,\n): Omit<AgentProfileCell, 'cellId'> {\n return compactObject({\n schemaVersion: 'agent-profile-cell/v1' as const,\n profileId: requireNonEmpty(input.profileId, 'profileId'),\n sourceProfile: normalizeSource(input.sourceProfile),\n harness: input.harness ? normalizeHarness(input.harness, 'harness') : undefined,\n model: optionalNonEmpty(input.model, 'model'),\n promptHash: optionalNonEmpty(input.promptHash, 'promptHash'),\n dimensions: input.dimensions\n ? nonEmptyRecord(normalizeDimensions(input.dimensions))\n : undefined,\n })\n}\n\nasync function normalizeSourceInput(input: AgentProfileSourceInput): Promise<AgentProfileSource> {\n const kind = requireNonEmpty(input.kind, 'sourceProfile.kind')\n if (input.hash !== undefined && input.profile !== undefined) {\n throw new AgentProfileCellValidationError(\n 'sourceProfile must provide either hash or profile, not both',\n 'sourceProfile',\n )\n }\n if (input.hash !== undefined) {\n return { kind, hash: requireSha256Hex(input.hash, 'sourceProfile.hash') }\n }\n if (input.profile === undefined) {\n throw new AgentProfileCellValidationError(\n 'sourceProfile must provide hash or profile',\n 'sourceProfile',\n )\n }\n assertJson(input.profile, 'sourceProfile.profile')\n return { kind, hash: await hashJson(input.profile) }\n}\n\nfunction normalizeSource(input: AgentProfileSource): AgentProfileSource {\n return {\n kind: requireNonEmpty(input.kind, 'sourceProfile.kind'),\n hash: requireSha256Hex(input.hash, 'sourceProfile.hash'),\n }\n}\n\nfunction normalizeHarness(input: AgentProfileHarness, path: string): AgentProfileHarness {\n return compactObject({\n id: requireNonEmpty(input.id, `${path}.id`),\n version: optionalNonEmpty(input.version, `${path}.version`),\n hash: optionalNonEmpty(input.hash, `${path}.hash`),\n })\n}\n\nfunction normalizeDimensions(\n input: Record<string, AgentProfileDimensionValue>,\n): Record<string, AgentProfileDimensionValue> {\n const out: Record<string, AgentProfileDimensionValue> = {}\n for (const key of Object.keys(input).sort()) {\n const value = input[key]\n requireNonEmpty(key, 'dimensions.<key>')\n if (\n value !== null &&\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n throw new AgentProfileCellValidationError(\n 'expected primitive dimension value',\n `dimensions.${key}`,\n )\n }\n if (typeof value === 'number' && !Number.isFinite(value)) {\n throw new AgentProfileCellValidationError('expected finite number', `dimensions.${key}`)\n }\n out[key] = value\n }\n return out\n}\n\nfunction compactObject<T extends Record<string, unknown>>(input: T): T {\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(input)) {\n if (value !== undefined) out[key] = value\n }\n return out as T\n}\n\nfunction nonEmptyRecord<T extends Record<string, unknown>>(input: T): T | undefined {\n return Object.keys(input).length > 0 ? input : undefined\n}\n\nfunction validateSource(value: unknown, path: string): void {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new AgentProfileCellValidationError('expected object', path)\n }\n const rec = value as Record<string, unknown>\n expectString(rec.kind, `${path}.kind`)\n requireSha256Hex(rec.hash, `${path}.hash`)\n}\n\nfunction validateHarness(value: unknown, path: string): void {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new AgentProfileCellValidationError('expected object', path)\n }\n const rec = value as Record<string, unknown>\n expectString(rec.id, `${path}.id`)\n if (rec.version !== undefined) expectString(rec.version, `${path}.version`)\n if (rec.hash !== undefined) expectString(rec.hash, `${path}.hash`)\n}\n\nfunction validateDimensions(value: unknown, path: string): void {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new AgentProfileCellValidationError('expected object', path)\n }\n normalizeDimensions(value as Record<string, AgentProfileDimensionValue>)\n}\n\nfunction assertJson(value: AgentProfileJson, path: string): void {\n if (value === null) return\n const type = typeof value\n if (type === 'string' || type === 'boolean') return\n if (type === 'number') {\n if (!Number.isFinite(value)) {\n throw new AgentProfileCellValidationError('expected finite number', path)\n }\n return\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n assertJson(item, `${path}[${index}]`)\n })\n return\n }\n if (type === 'object') {\n for (const [key, nested] of Object.entries(value)) {\n requireNonEmpty(key, `${path}.<key>`)\n assertJson(nested, `${path}.${key}`)\n }\n return\n }\n throw new AgentProfileCellValidationError('expected JSON-compatible value', path)\n}\n\nfunction expectLiteral(value: unknown, expected: string, path: string): void {\n if (value !== expected) {\n throw new AgentProfileCellValidationError(`expected ${expected}`, path)\n }\n}\n\nfunction expectString(value: unknown, path: string): void {\n if (typeof value !== 'string' || value.length === 0) {\n throw new AgentProfileCellValidationError('expected non-empty string', path)\n }\n}\n\nfunction requireNonEmpty(value: string, path: string): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new AgentProfileCellValidationError('expected non-empty string', path)\n }\n return value\n}\n\nfunction optionalNonEmpty(value: string | undefined, path: string): string | undefined {\n if (value === undefined) return undefined\n return requireNonEmpty(value, path)\n}\n\nfunction requireSha256Hex(value: unknown, path: string): string {\n if (typeof value !== 'string' || !SHA256_HEX.test(value)) {\n throw new AgentProfileCellValidationError('expected 64 lowercase sha256 hex chars', path)\n }\n return value\n}\n\n// ── Consumer helpers ─────────────────────────────────────────────────\n//\n// Boilerplate every product consuming `buildAgentProfileCell` used to duplicate:\n//\n// 1. A `JSON.parse(JSON.stringify(value))` helper that canonicalizes an\n// arbitrary `@tangle-network/agent-interface` `AgentProfile` into the recursive\n// `AgentProfileJson` shape, with a fail-loud error when the profile\n// is not JSON-serializable.\n//\n// 2. The magic string `'agent-interface-profile'` for `sourceProfile.kind`.\n//\n// Both belong here so the cross-product cell join (same canonical profile\n// hashes to the same `sourceProfile.hash` across products) is enforced by\n// the type system, not by every consumer remembering to do it right.\n// See blueprint-agent issue tangle-network/agent-eval#82.\n\n/** Canonical `sourceProfile.kind` values. Two products fingerprinting the\n * same canonical profile MUST use the same kind for their cells to share\n * `sourceProfile.hash`. Extend rather than create new strings — adding a\n * new kind is a deliberate cross-product schema change. */\nexport const AGENT_PROFILE_KINDS = {\n /** A profile declared via `defineAgentProfile(...)` from\n * `@tangle-network/agent-interface`. The default kind for router-backed\n * and sandbox-backed products. */\n AGENT_INTERFACE_PROFILE: 'agent-interface-profile',\n} as const\n\nexport type AgentProfileKind = (typeof AGENT_PROFILE_KINDS)[keyof typeof AGENT_PROFILE_KINDS]\n\n/** Canonicalize an arbitrary value into `AgentProfileJson` by JSON\n * round-trip. Throws when the value contains anything not representable\n * as JSON (functions, BigInt, cycles) — non-portable profiles fail loud\n * rather than silently dropping fields. */\nexport function toAgentProfileJson(value: unknown): AgentProfileJson {\n let serialized: string | undefined\n try {\n serialized = JSON.stringify(value)\n } catch (err) {\n throw new AgentProfileCellValidationError(\n `agent profile must be JSON-serializable: ${err instanceof Error ? err.message : String(err)}`,\n 'sourceProfile.profile',\n )\n }\n if (serialized === undefined) {\n throw new AgentProfileCellValidationError(\n 'agent profile must be JSON-serializable (got undefined after JSON.stringify)',\n 'sourceProfile.profile',\n )\n }\n return JSON.parse(serialized) as AgentProfileJson\n}\n\n/** Canonical AgentProfile shape required when deriving a stable cell id. */\nexport type AgentInterfaceProfileLike = AgentProfile & { name: string; version: string }\n\n/** Higher-level helper that hard-codes the canonical\n * `agent-interface-profile` kind plus the JSON canonicalization. Equivalent\n * to calling `buildAgentProfileCell` with `profileId = \\`${name}@${version}\\``\n * and `sourceProfile = { kind: AGENT_INTERFACE_PROFILE, profile: <round-tripped> }`.\n *\n * Use this from any product consuming an agent-interface `AgentProfile`; the\n * manual `buildAgentProfileCell` call is reserved for advanced cases\n * (custom kinds, pre-computed source hashes, alternate profileId\n * conventions). */\nexport async function buildAgentInterfaceProfileCell(\n profile: AgentInterfaceProfileLike,\n input: Omit<AgentProfileCellInput, 'profileId' | 'sourceProfile'>,\n): Promise<AgentProfileCell> {\n if (!profile || typeof profile !== 'object') {\n throw new AgentProfileCellValidationError('AgentProfile must be an object', 'profile')\n }\n if (typeof profile.name !== 'string' || profile.name.length === 0) {\n throw new AgentProfileCellValidationError(\n 'AgentProfile must have a non-empty `name`',\n 'profile.name',\n )\n }\n if (typeof profile.version !== 'string' || profile.version.length === 0) {\n throw new AgentProfileCellValidationError(\n 'AgentProfile must have a non-empty `version`',\n 'profile.version',\n )\n }\n return buildAgentProfileCell({\n ...input,\n profileId: `${profile.name}@${profile.version}`,\n sourceProfile: {\n kind: AGENT_PROFILE_KINDS.AGENT_INTERFACE_PROFILE,\n profile: toAgentProfileJson(profile),\n },\n })\n}\n"],"mappings":";;;AA2DA,IAAa,kCAAb,cAAqD,gBAAgB;CACnE;CACA,YAAY,SAAiB,OAAO,IAAI;EACtC,MAAM,OAAO,GAAG,QAAQ,OAAO,KAAK,KAAK,OAAO;EAChD,KAAK,OAAO;CACd;AACF;AAEA,MAAM,aAAa;AACnB,MAAM,UAAU;AAEhB,eAAsB,sBACpB,OAC2B;CAC3B,MAAM,WAAW,MAAM,+BAA+B,KAAK;CAC3D,MAAM,SAAS,6BAA6B,MAAM,SAAS,QAAQ;CACnE,OAAO;EAAE,GAAG;EAAU;CAAO;AAC/B;AAEA,SAAgB,6BACd,MACkC;CAClC,MAAM,EAAE,QAAQ,SAAS,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AAW,OAAO,YAAY,UACjC,MAAM,IAAI,gCAAgC,kCAAkC,SAAS;CAEvF,IAAI,OAAO,QAAQ,SAAS,YAAY,QAAQ,KAAK,WAAW,GAC9D,MAAM,IAAI,gCACR,6CACA,cACF;CAEF,IAAI,OAAO,QAAQ,YAAY,YAAY,QAAQ,QAAQ,WAAW,GACpE,MAAM,IAAI,gCACR,gDACA,iBACF;CAEF,OAAO,sBAAsB;EAC3B,GAAG;EACH,WAAW,GAAG,QAAQ,KAAK,GAAG,QAAQ;EACtC,eAAe;GACb,MAAM,oBAAoB;GAC1B,SAAS,mBAAmB,OAAO;EACrC;CACF,CAAC;AACH"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"statistics-CnnxdpOg.js","names":["mulberry32","prev"],"sources":["../src/judge-calibration.ts","../src/statistics.ts"],"sourcesContent":["/**\n * Judge calibration — measure judge quality against human gold + bias.\n *\n * Workflow:\n * 1. Build a golden set: {itemId, humanScore}[].\n * 2. Run candidate judges; each produces {itemId, score}.\n * 3. `calibrateJudge(golden, candidate)` reports κ + Pearson + MAE.\n * 4. `calibrateJudgeContinuous(golden, candidate)` adds quadratic-weighted\n * κ over the un-rounded [0,1] scores plus ICC(2,1), Pearson, Spearman,\n * and bootstrap CIs — use this for fine-grained judges where rounding\n * to int discards information (e.g. 0.78 vs 0.81 both round to 1 and\n * look \"perfectly agreed\" to integer κ).\n * 5. Run bias probes (positional, verbosity, self-preference) to\n * detect systematic score inflation.\n * 6. For N≥2 judges on the same items, `continuousAgreement(scores)`\n * reports ICC(2,1) + κ_w + Pearson + Spearman with bootstrap CIs.\n *\n * Returns actionable diagnostics, not a single number. Consumers then\n * decide whether to trust the judge, retrain it, or add a tie-breaker.\n */\n\nimport { pearsonR, spearmanR } from './statistics'\n\nexport interface GoldenItem {\n itemId: string\n humanScore: number\n /** Optional group used for per-group bias audits (e.g. model-of-output family). */\n group?: string\n}\n\nexport interface CandidateScore {\n itemId: string\n score: number\n /** Optional — enables positional-bias analysis (did order matter?). */\n positionOfAInput?: 'first' | 'second'\n}\n\nexport interface CalibrationResult {\n n: number\n pearson: number\n /** Cohen's κ with quadratic weights over integer-rounded scores. */\n kappa: number\n /** Mean absolute error vs human. */\n mae: number\n /** Worst-5 miscalibrations (largest |judge - human|). */\n worstItems: Array<{ itemId: string; judge: number; human: number; delta: number }>\n}\n\n/**\n * Measure judge quality against human gold labels: computes Cohen's κ, Pearson correlation, and MAE over matched item ids.\n */\nexport function calibrateJudge(\n golden: GoldenItem[],\n candidate: CandidateScore[],\n): CalibrationResult {\n const map = new Map<string, { h: number; j: number }>()\n for (const g of golden) map.set(g.itemId, { h: g.humanScore, j: NaN })\n for (const c of candidate) {\n const entry = map.get(c.itemId)\n if (entry) entry.j = c.score\n }\n const common = [...map.values()].filter((v) => Number.isFinite(v.j))\n const n = common.length\n if (n < 2) {\n return { n, pearson: NaN, kappa: NaN, mae: NaN, worstItems: [] }\n }\n const humans = common.map((c) => c.h)\n const judges = common.map((c) => c.j)\n const pearson = pearsonR(humans, judges)\n const kappa = weightedKappa(humans.map(Math.round), judges.map(Math.round))\n const absDiffs = common.map((c) => Math.abs(c.j - c.h))\n const mae = absDiffs.reduce((a, b) => a + b, 0) / n\n const worst = [...map.entries()]\n .filter(([, v]) => Number.isFinite(v.j))\n .map(([itemId, v]) => ({ itemId, judge: v.j, human: v.h, delta: Math.abs(v.j - v.h) }))\n .sort((a, b) => b.delta - a.delta)\n .slice(0, 5)\n return { n, pearson, kappa, mae, worstItems: worst }\n}\n\nexport interface PositionalBiasResult {\n /**\n * Score delta (first-position - second-position) averaged across items\n * presented in both positions. Non-zero = positional bias.\n */\n avgDelta: number\n n: number\n}\n\n/**\n * Feed the same items to the judge twice with A/B swapped and pass all\n * results here. Items that don't appear in both positions are ignored.\n */\nexport function positionalBias(scores: CandidateScore[]): PositionalBiasResult {\n const pairs = new Map<string, { first?: number; second?: number }>()\n for (const s of scores) {\n const slot = pairs.get(s.itemId) ?? {}\n if (s.positionOfAInput === 'first') slot.first = s.score\n else if (s.positionOfAInput === 'second') slot.second = s.score\n pairs.set(s.itemId, slot)\n }\n const deltas: number[] = []\n for (const { first, second } of pairs.values()) {\n if (first !== undefined && second !== undefined) deltas.push(first - second)\n }\n if (deltas.length === 0) return { avgDelta: 0, n: 0 }\n return { avgDelta: deltas.reduce((a, b) => a + b, 0) / deltas.length, n: deltas.length }\n}\n\nexport interface VerbosityBiasResult {\n /** Pearson correlation between output length and score. Strong positive = verbosity bias. */\n pearson: number\n n: number\n}\n\nexport function verbosityBias(\n samples: Array<{ outputLen: number; score: number }>,\n): VerbosityBiasResult {\n const n = samples.length\n if (n < 3) return { pearson: NaN, n }\n return {\n pearson: pearsonR(\n samples.map((s) => s.outputLen),\n samples.map((s) => s.score),\n ),\n n,\n }\n}\n\nexport interface SelfPreferenceResult {\n /** Mean judge score when judge's family matches output's family. */\n inFamilyMean: number\n outOfFamilyMean: number\n deltaMean: number\n n: number\n}\n\n/**\n * Pass the same scenarios scored with judge-model X grading outputs from\n * model X (in-family) and model Y (out-of-family). Non-zero delta\n * indicates self-preference.\n */\nexport function selfPreference(\n samples: Array<{ score: number; inFamily: boolean }>,\n): SelfPreferenceResult {\n const inF = samples.filter((s) => s.inFamily).map((s) => s.score)\n const outF = samples.filter((s) => !s.inFamily).map((s) => s.score)\n if (inF.length === 0 || outF.length === 0)\n return { inFamilyMean: 0, outOfFamilyMean: 0, deltaMean: 0, n: 0 }\n const inMean = inF.reduce((a, b) => a + b, 0) / inF.length\n const outMean = outF.reduce((a, b) => a + b, 0) / outF.length\n return {\n inFamilyMean: inMean,\n outOfFamilyMean: outMean,\n deltaMean: inMean - outMean,\n n: samples.length,\n }\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────\n\n/** Quadratic weighted Cohen's κ over bounded integer scores. */\nfunction weightedKappa(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length === 0) return NaN\n const min = Math.min(...a, ...b)\n const max = Math.max(...a, ...b)\n const K = max - min + 1\n if (K < 2) return 1\n const observed: number[][] = Array.from({ length: K }, () => new Array(K).fill(0))\n const rowMarg = new Array(K).fill(0)\n const colMarg = new Array(K).fill(0)\n for (let i = 0; i < a.length; i++) {\n const ai = a[i]! - min\n const bi = b[i]! - min\n const row = observed[ai]!\n row[bi] = (row[bi] ?? 0) + 1\n rowMarg[ai]++\n colMarg[bi]++\n }\n let num = 0\n let den = 0\n for (let i = 0; i < K; i++) {\n for (let j = 0; j < K; j++) {\n const w = (i - j) ** 2 / (K - 1) ** 2\n const expected = (rowMarg[i] * colMarg[j]) / a.length\n num += w * observed[i]![j]!\n den += w * expected\n }\n }\n if (den === 0) return 1\n return 1 - num / den\n}\n\n// ── Continuous-value inter-rater agreement ──────────────────────────\n//\n// `weightedKappa` above quantises to integers. For [0,1] judges that is\n// lossy: 0.78 and 0.81 both round to 1 and look identical to integer κ.\n// `continuousAgreement` keeps the original magnitudes:\n//\n// - κ_w : Cohen's weighted κ generalised to continuous scores. For two\n// raters, weighted κ = 1 − Σ w_ij·o_ij / Σ w_ij·e_ij collapses\n// into the closed form below when each \"category\" is the score\n// itself (Janson & Olsson 2001; Cohen 1968 quadratic weights).\n// - ICC : Intraclass Correlation Coefficient, ICC(2,1) per Shrout &\n// Fleiss (1979) — two-way random effects, absolute agreement,\n// single rater. The right reliability coefficient when judges\n// are a random sample of the judge population.\n// - r, ρ : Pearson + Spearman for sanity-check. Pearson catches linear\n// association regardless of scale; Spearman catches monotone\n// association regardless of distribution.\n// - CIs : Bootstrap percentile CIs over items (rows). Bias is preserved\n// because we resample the full row, i.e. a judge's vector\n// stays internally consistent within each bootstrap replicate.\n//\n// References:\n// - Shrout, P. E. & Fleiss, J. L. (1979). Intraclass correlations: uses\n// in assessing rater reliability. Psychological Bulletin, 86(2), 420.\n// - McGraw, K. O. & Wong, S. P. (1996). Forming inferences about some\n// intraclass correlation coefficients. Psychological Methods, 1, 30.\n// - Janson, H. & Olsson, U. (2001). A measure of agreement for interval\n// or nominal multivariate observations. Educ. Psychol. Meas., 61, 277.\n\nexport interface ContinuousAgreement {\n /** Cohen's κ_w with quadratic weights, computed on raw [0,1] scores. */\n weightedKappa: number\n /** ICC(2,1): two-way random effects, absolute agreement, single rater. */\n icc: number\n /** Pearson product-moment correlation (averaged over rater pairs if N>2). */\n pearson: number\n /** Spearman rank correlation (averaged over rater pairs if N>2). */\n spearman: number\n /** 95% bootstrap percentile CIs over items. */\n ci: {\n icc: [number, number]\n weightedKappa: [number, number]\n }\n /** Number of complete items (no NaN across raters). */\n n: number\n /** Number of raters. */\n raters: number\n}\n\nexport interface ContinuousAgreementOptions {\n /** Bootstrap iterations. Default 1000. Set to 0 to skip CIs (CI = [NaN, NaN]). */\n bootstrap?: number\n /** κ weighting scheme. Default 'quadratic'. */\n weights?: 'linear' | 'quadratic'\n /** PRNG seed for reproducible bootstrap. Default 0xC0FFEE. */\n seed?: number\n /** Confidence level for percentile CI. Default 0.95. */\n ciLevel?: number\n}\n\n/**\n * Inter-rater agreement on continuous (typically [0,1]) scores.\n *\n * `scores` has shape [n_items][n_raters]. Rows with any non-finite entry\n * are dropped. Returns NaN metrics if fewer than 2 raters or 2 complete\n * items remain.\n */\nexport function continuousAgreement(\n scores: number[][],\n opts: ContinuousAgreementOptions = {},\n): ContinuousAgreement {\n const bootstrap = opts.bootstrap ?? 1000\n const weights = opts.weights ?? 'quadratic'\n const seed = opts.seed ?? 0xc0ffee\n const ciLevel = opts.ciLevel ?? 0.95\n\n const matrix = scores.filter((row) => row.length >= 2 && row.every((v) => Number.isFinite(v)))\n const raters = matrix[0]?.length ?? 0\n // All rows must have the same rater count, else drop the offenders.\n const clean = matrix.filter((row) => row.length === raters)\n const nClean = clean.length\n\n if (nClean < 2 || raters < 2) {\n return {\n weightedKappa: NaN,\n icc: NaN,\n pearson: NaN,\n spearman: NaN,\n ci: { icc: [NaN, NaN], weightedKappa: [NaN, NaN] },\n n: nClean,\n raters,\n }\n }\n\n const kappa = continuousWeightedKappa(clean, weights)\n const icc = icc21(clean)\n const pearson = avgPairwise(clean, pearsonR)\n const spearman = avgPairwise(clean, spearmanR)\n\n const ciIcc: [number, number] = [NaN, NaN]\n const ciKappa: [number, number] = [NaN, NaN]\n if (bootstrap > 0) {\n const rng = mulberry32(seed)\n const iccs: number[] = []\n const kappas: number[] = []\n for (let b = 0; b < bootstrap; b++) {\n const sample: number[][] = new Array(nClean)\n for (let i = 0; i < nClean; i++) {\n sample[i] = clean[Math.floor(rng() * nClean)]!\n }\n const iccB = icc21(sample)\n const kB = continuousWeightedKappa(sample, weights)\n if (Number.isFinite(iccB)) iccs.push(iccB)\n if (Number.isFinite(kB)) kappas.push(kB)\n }\n const [lo, hi] = percentileBounds(ciLevel)\n if (iccs.length > 0) {\n iccs.sort((a, b) => a - b)\n ciIcc[0] = quantile(iccs, lo)\n ciIcc[1] = quantile(iccs, hi)\n }\n if (kappas.length > 0) {\n kappas.sort((a, b) => a - b)\n ciKappa[0] = quantile(kappas, lo)\n ciKappa[1] = quantile(kappas, hi)\n }\n }\n\n return {\n weightedKappa: kappa,\n icc,\n pearson,\n spearman,\n ci: { icc: ciIcc, weightedKappa: ciKappa },\n n: nClean,\n raters,\n }\n}\n\nexport interface ContinuousCalibrationResult extends CalibrationResult {\n /** Cohen's κ_w computed on raw (un-rounded) scores. */\n weightedKappaContinuous: number\n /** ICC(2,1) treating golden + candidate as two raters. */\n icc: number\n spearman: number\n ci: {\n icc: [number, number]\n weightedKappa: [number, number]\n }\n}\n\n/**\n * Extends `calibrateJudge` with continuous-value agreement metrics while\n * retaining its base calibration summary.\n */\nexport function calibrateJudgeContinuous(\n golden: GoldenItem[],\n candidate: CandidateScore[],\n opts: ContinuousAgreementOptions = {},\n): ContinuousCalibrationResult {\n const base = calibrateJudge(golden, candidate)\n const map = new Map<string, { h: number; j: number }>()\n for (const g of golden) map.set(g.itemId, { h: g.humanScore, j: NaN })\n for (const c of candidate) {\n const entry = map.get(c.itemId)\n if (entry) entry.j = c.score\n }\n const rows: number[][] = []\n for (const v of map.values()) {\n if (Number.isFinite(v.j)) rows.push([v.h, v.j])\n }\n const agreement = continuousAgreement(rows, opts)\n return {\n ...base,\n weightedKappaContinuous: agreement.weightedKappa,\n icc: agreement.icc,\n spearman: agreement.spearman,\n ci: agreement.ci,\n }\n}\n\n// ── Continuous-agreement internals ──────────────────────────────────\n\n/**\n * Quadratic-weighted κ on continuous scores. With weights w(x,y) = (x-y)^2\n * (or |x-y| for linear) the formula collapses to:\n *\n * κ_w = 1 − E_obs[w] / E_exp[w]\n *\n * where E_obs averages w over paired (a_i, b_i) and E_exp averages w over\n * the independent product distribution (sum_{i,j} w(a_i, b_j) / n^2).\n * The normalisation by (max-min)^2 in the integer version cancels in the\n * ratio, so we don't need it here. Generalises to N raters by averaging κ_w\n * over all rater pairs (mean pairwise weighted agreement).\n */\nfunction continuousWeightedKappa(rows: number[][], scheme: 'linear' | 'quadratic'): number {\n if (rows.length === 0) return NaN\n const raters = rows[0]!.length\n if (raters < 2) return NaN\n const wFn =\n scheme === 'linear'\n ? (x: number, y: number) => Math.abs(x - y)\n : (x: number, y: number) => (x - y) ** 2\n let sum = 0\n let pairs = 0\n for (let r1 = 0; r1 < raters; r1++) {\n for (let r2 = r1 + 1; r2 < raters; r2++) {\n const a = rows.map((row) => row[r1]!)\n const b = rows.map((row) => row[r2]!)\n const n = a.length\n let obs = 0\n for (let i = 0; i < n; i++) obs += wFn(a[i]!, b[i]!)\n obs /= n\n // Expected under independence: average of w over all i,j cross pairs.\n let exp = 0\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) exp += wFn(a[i]!, b[j]!)\n }\n exp /= n * n\n if (exp === 0) {\n // Degenerate: at least one rater is constant. Convention: perfect\n // agreement iff observed disagreement is also zero, else 0.\n sum += obs === 0 ? 1 : 0\n } else {\n sum += 1 - obs / exp\n }\n pairs++\n }\n }\n return pairs === 0 ? NaN : sum / pairs\n}\n\n/**\n * ICC(2,1) — two-way random effects, absolute agreement, single rater.\n *\n * ICC(2,1) = (MSR − MSE) / (MSR + (k−1)·MSE + k·(MSC − MSE)/n)\n *\n * where MSR = between-rows MS, MSC = between-columns MS, MSE = residual MS,\n * n = rows (items), k = columns (raters).\n */\nfunction icc21(rows: number[][]): number {\n const n = rows.length\n if (n < 2) return NaN\n const k = rows[0]!.length\n if (k < 2) return NaN\n\n // Row means.\n const rowMeans = rows.map((row) => row.reduce((s, v) => s + v, 0) / k)\n // Column means.\n const colMeans = new Array(k).fill(0)\n for (let j = 0; j < k; j++) {\n let s = 0\n for (let i = 0; i < n; i++) s += rows[i]![j]!\n colMeans[j] = s / n\n }\n // Grand mean.\n let grand = 0\n for (let i = 0; i < n; i++) grand += rowMeans[i]!\n grand /= n\n\n let ssR = 0\n for (let i = 0; i < n; i++) ssR += (rowMeans[i]! - grand) ** 2\n ssR *= k\n let ssC = 0\n for (let j = 0; j < k; j++) ssC += (colMeans[j]! - grand) ** 2\n ssC *= n\n let ssT = 0\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < k; j++) ssT += (rows[i]![j]! - grand) ** 2\n }\n const ssE = ssT - ssR - ssC\n\n const dfR = n - 1\n const dfC = k - 1\n const dfE = (n - 1) * (k - 1)\n const msR = ssR / dfR\n const msC = ssC / dfC\n const msE = dfE > 0 ? ssE / dfE : 0\n\n const denom = msR + (k - 1) * msE + (k * (msC - msE)) / n\n if (denom === 0) {\n // Degenerate (all values equal): convention = 1 if rows identical,\n // else 0. Identical rows ⇒ msR = 0 too, so msR − msE near 0.\n return msR === 0 && msE === 0 ? 1 : 0\n }\n return (msR - msE) / denom\n}\n\n/** Average pairwise statistic over all rater pairs. */\nfunction avgPairwise(rows: number[][], fn: (a: number[], b: number[]) => number): number {\n const k = rows[0]?.length ?? 0\n if (k < 2) return NaN\n let sum = 0\n let pairs = 0\n for (let i = 0; i < k; i++) {\n for (let j = i + 1; j < k; j++) {\n const a = rows.map((row) => row[i]!)\n const b = rows.map((row) => row[j]!)\n const r = fn(a, b)\n if (Number.isFinite(r)) {\n sum += r\n pairs++\n }\n }\n }\n return pairs === 0 ? NaN : sum / pairs\n}\n\n/** Seeded PRNG — Mulberry32. Deterministic across platforms. */\nfunction mulberry32(seed: number): () => number {\n let a = seed >>> 0\n return () => {\n a = (a + 0x6d2b79f5) >>> 0\n let t = a\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n\nfunction percentileBounds(ciLevel: number): [number, number] {\n const tail = (1 - ciLevel) / 2\n return [tail, 1 - tail]\n}\n\n/** Linear-interpolated quantile of a pre-sorted ascending array. */\nfunction quantile(sorted: number[], q: number): number {\n if (sorted.length === 0) return NaN\n if (sorted.length === 1) return sorted[0]!\n const pos = q * (sorted.length - 1)\n const lo = Math.floor(pos)\n const hi = Math.ceil(pos)\n if (lo === hi) return sorted[lo]!\n const frac = pos - lo\n return sorted[lo]! * (1 - frac) + sorted[hi]! * frac\n}\n","import { ValidationError } from './errors'\nimport {\n type ContinuousAgreement,\n type ContinuousAgreementOptions,\n continuousAgreement,\n} from './judge-calibration'\nimport type { JudgeScore } from './types'\n\n/** Identity: dimensions already follow \"higher = better\" by prompt convention\n * (inverted dims like hallucination are scored 10 = best at the source). */\nexport const normalizeScores = (scores: JudgeScore[]): JudgeScore[] => scores\n\n/** Weighted mean — falls back to uniform weights when omitted */\nexport function weightedMean(scores: { score: number; weight?: number }[]): number {\n if (scores.length === 0) return 0\n let totalWeight = 0\n let weightedSum = 0\n for (const { score, weight } of scores) {\n const w = weight ?? 1\n weightedSum += score * w\n totalWeight += w\n }\n return totalWeight > 0 ? weightedSum / totalWeight : 0\n}\n\n/** Bootstrap confidence interval */\nexport function confidenceInterval(\n scores: number[],\n confidence = 0.95,\n opts: { seed?: number; resamples?: number } = {},\n): { mean: number; lower: number; upper: number } {\n if (scores.length === 0) return { mean: 0, lower: 0, upper: 0 }\n if (scores.length === 1) return { mean: scores[0]!, lower: scores[0]!, upper: scores[0]! }\n\n const n = scores.length\n const mean = scores.reduce((a, b) => a + b, 0) / n\n\n const B = opts.resamples ?? 1000\n const rng = makeRng(opts.seed)\n const bootstrapMeans: number[] = []\n\n for (let i = 0; i < B; i++) {\n let sum = 0\n for (let j = 0; j < n; j++) {\n sum += scores[Math.floor(rng() * n)]!\n }\n bootstrapMeans.push(sum / n)\n }\n\n bootstrapMeans.sort((a, b) => a - b)\n\n const alpha = 1 - confidence\n const lowerIdx = Math.floor((alpha / 2) * B)\n const upperIdx = Math.floor((1 - alpha / 2) * B) - 1\n\n return {\n mean,\n lower: bootstrapMeans[lowerIdx]!,\n upper: bootstrapMeans[Math.min(upperIdx, B - 1)]!,\n }\n}\n\n/**\n * Inter-rater reliability — simplified Krippendorff's alpha.\n *\n * Each inner array is one judge's scores for all items.\n * All arrays must have the same length (same items scored).\n */\nexport function interRaterReliability(judgeScores: JudgeScore[][]): number {\n if (judgeScores.length < 2) return 1\n\n // Group scores by dimension across judges\n const dimensionMap = new Map<string, number[][]>()\n for (const judgeSet of judgeScores) {\n for (const s of judgeSet) {\n if (!dimensionMap.has(s.dimension)) dimensionMap.set(s.dimension, [])\n const arr = dimensionMap.get(s.dimension)!\n if (arr.length === 0 || arr[arr.length - 1]!.length >= judgeScores.length) {\n arr.push([s.score])\n } else {\n arr[arr.length - 1]!.push(s.score)\n }\n }\n }\n\n // Collect all paired ratings\n const allValues: number[] = []\n const pairDiffs: number[] = []\n\n for (const items of dimensionMap.values()) {\n for (const ratings of items) {\n if (ratings.length < 2) continue\n for (const v of ratings) allValues.push(v)\n for (let i = 0; i < ratings.length; i++) {\n for (let j = i + 1; j < ratings.length; j++) {\n pairDiffs.push((ratings[i]! - ratings[j]!) ** 2)\n }\n }\n }\n }\n\n if (pairDiffs.length === 0 || allValues.length < 2) return 1\n\n const observedDisagreement = pairDiffs.reduce((a, b) => a + b, 0) / pairDiffs.length\n\n // Expected disagreement from all possible pairings of values\n let expectedDisagreement = 0\n let expectedCount = 0\n for (let i = 0; i < allValues.length; i++) {\n for (let j = i + 1; j < allValues.length; j++) {\n expectedDisagreement += (allValues[i]! - allValues[j]!) ** 2\n expectedCount++\n }\n }\n expectedDisagreement = expectedCount > 0 ? expectedDisagreement / expectedCount : 0\n\n if (expectedDisagreement === 0) return 1\n return 1 - observedDisagreement / expectedDisagreement\n}\n\n/**\n * Mann-Whitney U test for comparing two independent groups.\n * Returns U statistic and approximate p-value (normal approximation).\n */\nexport function mannWhitneyU(a: number[], b: number[]): { u: number; p: number } {\n if (a.length === 0 || b.length === 0) return { u: 0, p: 1 }\n\n const n1 = a.length\n const n2 = b.length\n\n // Rank all values together\n const combined = [\n ...a.map((v) => ({ v, group: 'a' as const })),\n ...b.map((v) => ({ v, group: 'b' as const })),\n ].sort((x, y) => x.v - y.v)\n\n // Assign ranks with tie handling\n const ranks: number[] = new Array(combined.length)\n let i = 0\n while (i < combined.length) {\n let j = i\n while (j < combined.length && combined[j]!.v === combined[i]!.v) j++\n const avgRank = (i + 1 + j) / 2\n for (let k = i; k < j; k++) ranks[k] = avgRank\n i = j\n }\n\n // Sum ranks for group a\n let r1 = 0\n for (let k = 0; k < combined.length; k++) {\n if (combined[k]!.group === 'a') r1 += ranks[k]!\n }\n\n const u1 = r1 - (n1 * (n1 + 1)) / 2\n const u2 = n1 * n2 - u1\n const u = Math.min(u1, u2)\n\n // Normal approximation for p-value\n const mu = (n1 * n2) / 2\n const sigma = Math.sqrt((n1 * n2 * (n1 + n2 + 1)) / 12)\n\n if (sigma === 0) return { u, p: 1 }\n\n const z = Math.abs(u - mu) / sigma\n // Two-tailed p-value from z-score (approximation)\n const p = 2 * (1 - normalCdf(z))\n\n return { u, p }\n}\n\n/** Partial credit: returns 0-1 ratio of current toward target */\nexport function partialCredit(current: number, target: number): number {\n if (target <= 0) return 1\n return Math.min(1, Math.max(0, current / target))\n}\n\n/**\n * Paired t-test — before/after measurements on the SAME items.\n * Pairing removes inter-item variance, giving tighter significance than\n * an unpaired test when comparing prompt v1 vs prompt v2 on identical\n * scenarios.\n */\nexport function pairedTTest(\n before: number[],\n after: number[],\n): { t: number; df: number; p: number } {\n if (before.length !== after.length) {\n throw new ValidationError(\n `pairedTTest: unequal sample sizes (${before.length} vs ${after.length})`,\n )\n }\n const n = before.length\n if (n < 2) return { t: 0, df: 0, p: 1 }\n\n const diffs = before.map((b, i) => after[i]! - b)\n const mean = diffs.reduce((a, b) => a + b, 0) / n\n const variance = diffs.reduce((acc, d) => acc + (d - mean) ** 2, 0) / (n - 1)\n const se = Math.sqrt(variance / n)\n if (se === 0) return { t: mean === 0 ? 0 : Infinity, df: n - 1, p: mean === 0 ? 1 : 0 }\n\n const t = mean / se\n const df = n - 1\n const p = 2 * (1 - studentTCdf(Math.abs(t), df))\n return { t, df, p }\n}\n\n/**\n * Wilcoxon signed-rank test — paired non-parametric alternative.\n * Use when the differences aren't normally distributed.\n */\nexport function wilcoxonSignedRank(before: number[], after: number[]): { w: number; p: number } {\n if (before.length !== after.length) {\n throw new ValidationError(\n `wilcoxonSignedRank: unequal sample sizes (${before.length} vs ${after.length})`,\n )\n }\n const diffs = before.map((b, i) => after[i]! - b).filter((d) => d !== 0)\n const n = diffs.length\n if (n < 6) return { w: 0, p: 1 }\n\n const absRanks = diffs\n .map((d, i) => ({ abs: Math.abs(d), sign: Math.sign(d), i }))\n .sort((a, b) => a.abs - b.abs)\n const ranks: number[] = new Array(n)\n let i = 0\n while (i < n) {\n let j = i\n while (j < n && absRanks[j]!.abs === absRanks[i]!.abs) j++\n const avg = (i + 1 + j) / 2\n for (let k = i; k < j; k++) ranks[absRanks[k]!.i] = avg\n i = j\n }\n let wPlus = 0\n for (let k = 0; k < n; k++) if (diffs[k]! > 0) wPlus += ranks[k]!\n\n const mean = (n * (n + 1)) / 4\n const variance = (n * (n + 1) * (2 * n + 1)) / 24\n const z = (wPlus - mean) / Math.sqrt(variance)\n const p = 2 * (1 - normalCdf(Math.abs(z)))\n return { w: wPlus, p }\n}\n\n/**\n * Cohen's d — standardized effect size for two independent groups.\n * Positive d means group b has higher mean than group a.\n * Rule of thumb: |d| < 0.2 negligible, 0.2–0.5 small, 0.5–0.8 medium, > 0.8 large.\n */\nexport function cohensD(a: number[], b: number[]): number {\n if (a.length < 2 || b.length < 2) return 0\n const meanA = a.reduce((x, y) => x + y, 0) / a.length\n const meanB = b.reduce((x, y) => x + y, 0) / b.length\n const varA = a.reduce((acc, x) => acc + (x - meanA) ** 2, 0) / (a.length - 1)\n const varB = b.reduce((acc, x) => acc + (x - meanB) ** 2, 0) / (b.length - 1)\n const pooled = Math.sqrt(\n ((a.length - 1) * varA + (b.length - 1) * varB) / (a.length + b.length - 2),\n )\n if (pooled === 0) return 0\n return (meanB - meanA) / pooled\n}\n\n/**\n * Cohen's dz for paired observations: mean(after - before) divided by the\n * sample standard deviation of those within-pair deltas.\n *\n * Returns null when fewer than two pairs exist or a non-zero constant delta\n * has zero observed variance. In that case the standardized effect is\n * undefined, not an arbitrarily large finite number.\n */\nexport function pairedCohensDz(before: number[], after: number[]): number | null {\n if (before.length !== after.length) {\n throw new ValidationError(\n `pairedCohensDz: unequal sample sizes (${before.length} vs ${after.length})`,\n )\n }\n if (before.length < 2) return null\n const deltas = before.map((value, index) => after[index]! - value)\n if (deltas.some((value) => !Number.isFinite(value))) {\n throw new ValidationError('pairedCohensDz: all paired values must be finite')\n }\n const meanDelta = deltas.reduce((sum, value) => sum + value, 0) / deltas.length\n const variance =\n deltas.reduce((sum, value) => sum + (value - meanDelta) ** 2, 0) / (deltas.length - 1)\n const standardDeviation = Math.sqrt(variance)\n const scale = Math.max(1, Math.abs(meanDelta), ...deltas.map(Math.abs))\n if (standardDeviation <= Number.EPSILON * scale) return meanDelta === 0 ? 0 : null\n return meanDelta / standardDeviation\n}\n\nexport type CliffsMagnitude = 'negligible' | 'small' | 'medium' | 'large'\n\n/**\n * Cliff's delta — a non-parametric effect size for two independent samples.\n * `δ = (#(after > before) − #(after < before)) / (n_before · n_after)`,\n * ranging [-1, 1]. Positive ⇒ `after` tends to exceed `before` (improvement).\n *\n * Distribution-free counterpart to Cohen's d: no normality assumption, robust\n * to the bounded/skewed score distributions judges produce. Pairs with\n * `pairedBootstrap` / `wilcoxonSignedRank` for the non-parametric reporting\n * path. Returns 0 when either sample is empty.\n */\nexport function cliffsDelta(before: number[], after: number[]): number {\n const n = before.length * after.length\n if (n === 0) return 0\n let dominance = 0\n for (const a of after) {\n for (const b of before) {\n if (a > b) dominance += 1\n else if (a < b) dominance -= 1\n }\n }\n return dominance / n\n}\n\n/**\n * Map a Cliff's delta to a qualitative magnitude using the standard\n * Romano et al. thresholds (|δ|): <0.147 negligible, <0.33 small,\n * <0.474 medium, else large.\n */\nexport function interpretCliffs(delta: number): CliffsMagnitude {\n const d = Math.abs(delta)\n if (d < 0.147) return 'negligible'\n if (d < 0.33) return 'small'\n if (d < 0.474) return 'medium'\n return 'large'\n}\n\n// ── Correlation (Pearson / Spearman) ─────────────────────────────────\n//\n// The single source for linear (Pearson) and rank (Spearman) correlation.\n// Edge-case contract is explicit so every caller agrees on what a\n// degenerate input means:\n// - length mismatch or n < 2 → NaN (correlation is undefined; not 0)\n// - both series constant → 1 (degenerate perfect agreement)\n// - exactly one series constant → 0 (no covariation to detect)\n// Returning NaN for n < 2 (rather than 0) keeps \"not enough data\" distinct\n// from \"measured zero correlation\", which a 0 would silently conflate.\n\n/**\n * Average-rank-with-ties transform (1-indexed). Tied values receive the mean\n * of the ranks they span, the standard correction for Spearman's ρ.\n */\nexport function ranks(xs: number[]): number[] {\n const indexed = xs.map((v, i) => ({ v, i })).sort((a, b) => a.v - b.v)\n const r = new Array<number>(xs.length)\n let i = 0\n while (i < indexed.length) {\n let j = i\n while (j + 1 < indexed.length && indexed[j + 1]!.v === indexed[i]!.v) j++\n const avg = (i + j) / 2 + 1\n for (let k = i; k <= j; k++) r[indexed[k]!.i] = avg\n i = j + 1\n }\n return r\n}\n\n/**\n * Pearson product-moment correlation coefficient r ∈ [-1, 1] between two\n * equal-length series. See the edge-case contract above: NaN for n < 2 or\n * unequal lengths, 1 when both series are constant, 0 when exactly one is.\n */\nexport function pearsonR(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length < 2) return Number.NaN\n const n = a.length\n const meanA = a.reduce((s, v) => s + v, 0) / n\n const meanB = b.reduce((s, v) => s + v, 0) / n\n let num = 0\n let varA = 0\n let varB = 0\n for (let i = 0; i < n; i++) {\n const da = a[i]! - meanA\n const db = b[i]! - meanB\n num += da * db\n varA += da * da\n varB += db * db\n }\n if (varA === 0 || varB === 0) return varA === 0 && varB === 0 ? 1 : 0\n return num / Math.sqrt(varA * varB)\n}\n\n/**\n * Spearman's rank correlation ρ — Pearson over the average-rank-with-ties\n * transform of each series. Same edge-case contract as {@link pearsonR}.\n */\nexport function spearmanR(a: number[], b: number[]): number {\n if (a.length !== b.length || a.length < 2) return Number.NaN\n return pearsonR(ranks(a), ranks(b))\n}\n\nexport interface WeightedCompositeInput {\n /** Per-dimension scores (typically 0..1). */\n dims: Record<string, number>\n /** Weight per dimension. Every weighted dimension MUST be present in\n * `dims` — a weight for an absent dimension is a config error and throws,\n * because silently dropping it would renormalise the composite onto a\n * different denominator than intended. */\n weights: Record<string, number>\n /** Optional pass threshold; when set, the result reports `pass`. */\n threshold?: number\n}\n\nexport interface WeightedCompositeResult {\n composite: number\n pass?: boolean\n}\n\n/**\n * Weighted composite over judge dimensions: `Σ(score_d · w_d) / Σ(w_d)` across\n * the weighted dimensions. The canonical replacement for the per-consumer\n * hand-rolled composite math (tax/legal/creative/gtm each ship a copy).\n *\n * Fail-loud: throws if a weighted dimension is missing from `dims`, if any\n * weight is negative, or if the weights sum to 0 — none of which can produce\n * a meaningful composite.\n */\nexport function weightedComposite(input: WeightedCompositeInput): WeightedCompositeResult {\n const entries = Object.entries(input.weights)\n if (entries.length === 0) {\n throw new Error('weightedComposite: `weights` is empty — nothing to combine')\n }\n let weightedSum = 0\n let weightTotal = 0\n for (const [dim, weight] of entries) {\n if (weight < 0) {\n throw new Error(`weightedComposite: weight for '${dim}' is negative (${weight})`)\n }\n if (!(dim in input.dims)) {\n throw new Error(\n `weightedComposite: weighted dimension '${dim}' is absent from \\`dims\\` — ` +\n 'refusing to renormalise onto a different denominator',\n )\n }\n weightedSum += input.dims[dim]! * weight\n weightTotal += weight\n }\n if (weightTotal === 0) {\n throw new Error('weightedComposite: weights sum to 0 — composite is undefined')\n }\n const composite = weightedSum / weightTotal\n return input.threshold === undefined\n ? { composite }\n : { composite, pass: composite >= input.threshold }\n}\n\n// ── Corpus-wide inter-rater agreement ──────────────────────────────\n//\n// `interRaterReliability(judgeScores)` computes a within-item\n// Krippendorff α — multiple judges score *the same item* and we ask\n// \"how much do their scores agree on that item?\" Useful for a single\n// scenario, but it cannot answer \"how reliable are these judges across\n// the whole evaluation corpus?\"\n//\n// `corpusInterRaterAgreement` does the corpus-wide question properly.\n// Inputs are flat per-(item, judge, dimension) score records. For each\n// dimension we pivot to a complete [n_items × n_judges] matrix and feed\n// it to the ICC(2,1) + κ_w machinery already validated in\n// `judge-calibration.ts`. An overall pooled metric averages the\n// per-dimension ICC/κ across dimensions.\n\nexport interface CorpusScoreRecord {\n /** Stable identifier for the rated item (scenario, span, turn, …). */\n itemId: string\n /** Identifier for the judge that produced this score. */\n judgeName: string\n /** Dimension name (matches `JudgeScore.dimension`). */\n dimension: string\n /** Numeric score; must be finite. */\n score: number\n}\n\nexport interface CorpusAgreementPerDimension extends ContinuousAgreement {\n dimension: string\n /** Item IDs that contributed to this dimension's matrix (every judge scored them). */\n itemIds: string[]\n /** Judge IDs that contributed to this dimension's matrix. */\n judgeIds: string[]\n}\n\nexport interface CorpusAgreementReport {\n /** Per-dimension ICC(2,1) + κ_w + Pearson + Spearman + bootstrap CIs. */\n perDimension: CorpusAgreementPerDimension[]\n /** Mean ICC across dimensions (NaN if no dimension yielded a finite ICC). */\n overallIcc: number\n /** Mean weighted κ across dimensions (NaN if none finite). */\n overallWeightedKappa: number\n /** Dimensions evaluated (sorted). */\n dimensions: string[]\n /** Judges seen across the corpus (sorted). */\n judgeIds: string[]\n}\n\nexport interface CorpusAgreementOptions extends ContinuousAgreementOptions {\n /**\n * Restrict the audit to these dimensions. Default = every dimension\n * that appears in the input. A dimension named here but absent from\n * the input throws — silent omission would corrupt the overall metric.\n */\n dimensions?: string[]\n /**\n * Restrict the audit to these judges. Default = every judge that\n * appears in the input. A judge named here but absent from a\n * dimension throws (see \"fail loud\" below).\n */\n judges?: string[]\n}\n\n/**\n * Corpus-wide inter-rater agreement across N items × M judges × D dimensions.\n *\n * For each dimension, builds the [n_items][n_judges] matrix of scores\n * (keeping only items every judge rated on that dimension), then runs\n * `continuousAgreement` to get ICC(2,1), κ_w, Pearson, Spearman, and\n * bootstrap CIs. Reports a pooled mean across dimensions as a single\n * \"is this judge panel reliable on this corpus?\" number.\n *\n * Fail-loud contract:\n * - Empty input throws.\n * - Fewer than 2 judges or fewer than 2 items per dimension throws.\n * - A judge present in some dimensions but with zero scored items on\n * another dimension throws (would silently shrink the matrix).\n * - Duplicate (itemId, judgeName, dimension) records throw.\n */\nexport function corpusInterRaterAgreement(\n records: CorpusScoreRecord[],\n opts: CorpusAgreementOptions = {},\n): CorpusAgreementReport {\n if (records.length === 0) {\n throw new ValidationError('corpusInterRaterAgreement: no score records supplied')\n }\n\n const judgesSeen = new Set<string>()\n const dimsSeen = new Set<string>()\n // dimension → judge → itemId → score\n const grid = new Map<string, Map<string, Map<string, number>>>()\n\n for (const r of records) {\n if (!Number.isFinite(r.score)) {\n throw new ValidationError(\n `corpusInterRaterAgreement: non-finite score for (item=${r.itemId}, judge=${r.judgeName}, dim=${r.dimension})`,\n )\n }\n judgesSeen.add(r.judgeName)\n dimsSeen.add(r.dimension)\n const byJudge = grid.get(r.dimension) ?? new Map<string, Map<string, number>>()\n const byItem = byJudge.get(r.judgeName) ?? new Map<string, number>()\n if (byItem.has(r.itemId)) {\n throw new ValidationError(\n `corpusInterRaterAgreement: duplicate record for (item=${r.itemId}, judge=${r.judgeName}, dim=${r.dimension})`,\n )\n }\n byItem.set(r.itemId, r.score)\n byJudge.set(r.judgeName, byItem)\n grid.set(r.dimension, byJudge)\n }\n\n const targetDims = opts.dimensions ?? [...dimsSeen].sort()\n for (const d of targetDims) {\n if (!dimsSeen.has(d)) {\n throw new ValidationError(\n `corpusInterRaterAgreement: dimension '${d}' was requested but no records carry it`,\n )\n }\n }\n const targetJudges = opts.judges ? [...opts.judges] : [...judgesSeen].sort()\n for (const j of targetJudges) {\n if (!judgesSeen.has(j)) {\n throw new ValidationError(\n `corpusInterRaterAgreement: judge '${j}' was requested but produced no records`,\n )\n }\n }\n if (targetJudges.length < 2) {\n throw new ValidationError(\n `corpusInterRaterAgreement: need ≥2 judges, got ${targetJudges.length}`,\n )\n }\n\n const perDimension: CorpusAgreementPerDimension[] = []\n const iccs: number[] = []\n const kappas: number[] = []\n\n for (const dim of targetDims) {\n const byJudge = grid.get(dim)!\n // Fail loud: every requested judge must have scored ≥1 item on this dim.\n const judgeItemCounts: Record<string, number> = {}\n for (const j of targetJudges) {\n const m = byJudge.get(j)\n judgeItemCounts[j] = m?.size ?? 0\n }\n const emptyJudges = targetJudges.filter((j) => judgeItemCounts[j] === 0)\n if (emptyJudges.length > 0) {\n throw new ValidationError(\n `corpusInterRaterAgreement: dimension '${dim}' has no scores from judge(s) ${emptyJudges.join(', ')} (counts: ${JSON.stringify(judgeItemCounts)})`,\n )\n }\n\n // Items rated by *every* requested judge on this dim.\n let commonItems: Set<string> | null = null\n for (const j of targetJudges) {\n const ids = new Set(byJudge.get(j)!.keys())\n if (commonItems === null) {\n commonItems = ids\n } else {\n const prev: Set<string> = commonItems\n commonItems = new Set([...prev].filter((x) => ids.has(x)))\n }\n }\n const sortedItems = [...(commonItems ?? new Set<string>())].sort()\n if (sortedItems.length < 2) {\n throw new ValidationError(\n `corpusInterRaterAgreement: dimension '${dim}' has ${sortedItems.length} item(s) rated by all ${targetJudges.length} judges (need ≥2)`,\n )\n }\n\n const matrix: number[][] = sortedItems.map((itemId) =>\n targetJudges.map((j) => byJudge.get(j)!.get(itemId)!),\n )\n const agreement = continuousAgreement(matrix, opts)\n perDimension.push({\n ...agreement,\n dimension: dim,\n itemIds: sortedItems,\n judgeIds: [...targetJudges],\n })\n if (Number.isFinite(agreement.icc)) iccs.push(agreement.icc)\n if (Number.isFinite(agreement.weightedKappa)) kappas.push(agreement.weightedKappa)\n }\n\n const mean = (xs: number[]) =>\n xs.length === 0 ? Number.NaN : xs.reduce((a, b) => a + b, 0) / xs.length\n return {\n perDimension,\n overallIcc: mean(iccs),\n overallWeightedKappa: mean(kappas),\n dimensions: targetDims,\n judgeIds: targetJudges,\n }\n}\n\n/**\n * Convenience adapter for `JudgeScore[]` data keyed externally by item.\n *\n * Use when you have per-item arrays of `JudgeScore[]` (e.g. one\n * `ScenarioResult.judgeScores` per scenario) and want corpus-wide\n * agreement without manually flattening. `itemId` must be unique per\n * row of `itemsScores`.\n */\nexport function corpusInterRaterAgreementFromJudgeScores(\n itemsScores: Array<{ itemId: string; scores: JudgeScore[] }>,\n opts: CorpusAgreementOptions = {},\n): CorpusAgreementReport {\n const records: CorpusScoreRecord[] = []\n const seen = new Set<string>()\n for (const { itemId, scores } of itemsScores) {\n if (seen.has(itemId)) {\n throw new ValidationError(\n `corpusInterRaterAgreementFromJudgeScores: duplicate itemId '${itemId}'`,\n )\n }\n seen.add(itemId)\n for (const s of scores) {\n records.push({\n itemId,\n judgeName: s.judgeName,\n dimension: s.dimension,\n score: s.score,\n })\n }\n }\n return corpusInterRaterAgreement(records, opts)\n}\n\n/** Student-t CDF approximation via Abramowitz-Stegun series. */\nfunction studentTCdf(t: number, df: number): number {\n if (df <= 0) return 0.5\n if (df > 100) return normalCdf(t)\n const x = df / (df + t * t)\n const a = df / 2\n const b = 0.5\n const ib = incompleteBeta(x, a, b)\n return t >= 0 ? 1 - 0.5 * ib : 0.5 * ib\n}\n\n/** Regularized incomplete beta function via continued fraction (Lentz). */\nfunction incompleteBeta(x: number, a: number, b: number): number {\n if (x <= 0) return 0\n if (x >= 1) return 1\n const lnBeta = lnGamma(a) + lnGamma(b) - lnGamma(a + b)\n const front = Math.exp(Math.log(x) * a + Math.log(1 - x) * b - lnBeta) / a\n const maxIter = 200\n const eps = 3e-7\n let c = 1\n let d = 1 - ((a + b) * x) / (a + 1)\n if (Math.abs(d) < 1e-30) d = 1e-30\n d = 1 / d\n let f = d\n for (let m = 1; m <= maxIter; m++) {\n const m2 = 2 * m\n let num = (m * (b - m) * x) / ((a + m2 - 1) * (a + m2))\n d = 1 + num * d\n if (Math.abs(d) < 1e-30) d = 1e-30\n c = 1 + num / c\n if (Math.abs(c) < 1e-30) c = 1e-30\n d = 1 / d\n f *= d * c\n num = -((a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1))\n d = 1 + num * d\n if (Math.abs(d) < 1e-30) d = 1e-30\n c = 1 + num / c\n if (Math.abs(c) < 1e-30) c = 1e-30\n d = 1 / d\n const delta = d * c\n f *= delta\n if (Math.abs(delta - 1) < eps) break\n }\n return front * f\n}\n\n/** Lanczos approximation to ln Γ(z). */\nfunction lnGamma(z: number): number {\n const g = 7\n const coefs = [\n 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313,\n -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6,\n 1.5056327351493116e-7,\n ]\n if (z < 0.5) {\n return Math.log(Math.PI / Math.sin(Math.PI * z)) - lnGamma(1 - z)\n }\n z -= 1\n let x = coefs[0]!\n for (let i = 1; i < g + 2; i++) x += coefs[i]! / (z + i)\n const t = z + g + 0.5\n return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(x)\n}\n\n// Standard normal CDF approximation (Abramowitz and Stegun)\nfunction normalCdf(x: number): number {\n const a1 = 0.254829592\n const a2 = -0.284496736\n const a3 = 1.421413741\n const a4 = -1.453152027\n const a5 = 1.061405429\n const p = 0.3275911\n\n const sign = x < 0 ? -1 : 1\n const absX = Math.abs(x)\n const t = 1 / (1 + p * absX)\n const y = 1 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp((-absX * absX) / 2)\n\n return 0.5 * (1 + sign * y)\n}\n\n// ── Power analysis + multiple-comparison correction ──────────────────\n\n/**\n * Required N per arm for a two-sample comparison at target effect size,\n * alpha, and power. Normal-approximation formula:\n * n = 2 * ( (z_{1-α/2} + z_{1-β}) / d )^2\n * where d is Cohen's d. Returns Infinity for effect ≤ 0.\n */\nexport function requiredSampleSize(opts: {\n effect: number\n alpha?: number\n power?: number\n twoSided?: boolean\n}): number {\n const effect = opts.effect\n if (!Number.isFinite(effect) || effect <= 0) return Infinity\n const alpha = opts.alpha ?? 0.05\n const power = opts.power ?? 0.8\n const twoSided = opts.twoSided ?? true\n const zAlpha = zQuantile(twoSided ? 1 - alpha / 2 : 1 - alpha)\n const zBeta = zQuantile(power)\n const n = 2 * ((zAlpha + zBeta) / effect) ** 2\n return Math.ceil(n)\n}\n\n/**\n * Required number of paired observations for a target Cohen's dz.\n * Unlike the independent-groups formula, this has no two-arm factor of two.\n */\nexport function requiredPairedSampleSize(opts: {\n effect: number\n alpha?: number\n power?: number\n twoSided?: boolean\n}): number {\n const effect = opts.effect\n if (!Number.isFinite(effect) || effect <= 0) return Infinity\n const alpha = opts.alpha ?? 0.05\n const power = opts.power ?? 0.8\n const twoSided = opts.twoSided ?? true\n const zAlpha = zQuantile(twoSided ? 1 - alpha / 2 : 1 - alpha)\n const zBeta = zQuantile(power)\n return Math.ceil(((zAlpha + zBeta) / effect) ** 2)\n}\n\n/**\n * Minimum detectable paired effect (standardised units) for a target paired\n * sample size: d_min = (z_{1-α/2} + z_β) / sqrt(n_paired). Multiply by\n * sd(deltas) for score units; treat as a lower bound — Wilcoxon and bootstrap\n * have asymptotic relative efficiency below 1 vs the t-test on heavy tails.\n */\nexport function pairedMde(opts: {\n nPaired: number\n alpha?: number\n power?: number\n twoSided?: boolean\n}): number {\n if (!Number.isFinite(opts.nPaired) || opts.nPaired <= 0) return Infinity\n const alpha = opts.alpha ?? 0.05\n const power = opts.power ?? 0.8\n const twoSided = opts.twoSided ?? true\n const zAlpha = zQuantile(twoSided ? 1 - alpha / 2 : 1 - alpha)\n const zBeta = zQuantile(power)\n return (zAlpha + zBeta) / Math.sqrt(opts.nPaired)\n}\n\n/**\n * Number of paired observations needed for a McNemar test to reach a target\n * power — the pre-registration companion to {@link mcnemar}. Parametrised by the\n * expected discordant-cell probabilities `p10` (P[treatment wins on a pair]) and\n * `p01` (P[control wins]); concordant pairs carry no information, so the count\n * is driven entirely by the discordant rate. Lachin's (1992) asymptotic normal\n * approximation: with discordant rate `pDisc = p10 + p01` and marginal effect\n * `δ = p10 − p01`,\n * n = ( z_{1-α/2}·√pDisc + z_{1-β}·√(pDisc − δ²) )² / δ².\n * Returns Infinity when there is no effect (p10 === p01). Asymptotic — at the\n * tiny discordant counts where the exact {@link mcnemar} differs from the normal\n * approximation, treat the result as a lower bound and prefer the discordant-pair\n * floor.\n */\nexport function mcnemarRequiredN(opts: {\n p10: number\n p01: number\n alpha?: number\n power?: number\n twoSided?: boolean\n}): number {\n const { p10, p01 } = opts\n if (p10 < 0 || p01 < 0 || p10 + p01 > 1) {\n throw new Error(`mcnemarRequiredN: require p10,p01 ≥ 0 and p10+p01 ≤ 1 (got ${p10}, ${p01})`)\n }\n const delta = p10 - p01\n if (delta === 0) return Infinity\n const alpha = opts.alpha ?? 0.05\n const power = opts.power ?? 0.8\n const twoSided = opts.twoSided ?? true\n const pDisc = p10 + p01\n const zAlpha = zQuantile(twoSided ? 1 - alpha / 2 : 1 - alpha)\n const zBeta = zQuantile(power)\n const n =\n (zAlpha * Math.sqrt(pDisc) + zBeta * Math.sqrt(Math.max(0, pDisc - delta * delta))) ** 2 /\n (delta * delta)\n return Math.ceil(n)\n}\n\n/**\n * Power of a McNemar test at a given number of paired observations, the inverse\n * of {@link mcnemarRequiredN} (same Lachin asymptotic model, same parameters).\n * Returns a value in [0, 1]; equals `alpha` when there is no effect.\n */\nexport function mcnemarPower(opts: {\n p10: number\n p01: number\n nPairs: number\n alpha?: number\n twoSided?: boolean\n}): number {\n const { p10, p01, nPairs } = opts\n if (p10 < 0 || p01 < 0 || p10 + p01 > 1) {\n throw new Error(`mcnemarPower: require p10,p01 ≥ 0 and p10+p01 ≤ 1 (got ${p10}, ${p01})`)\n }\n const alpha = opts.alpha ?? 0.05\n const twoSided = opts.twoSided ?? true\n const delta = p10 - p01\n if (delta === 0 || nPairs <= 0) return alpha\n const pDisc = p10 + p01\n const zAlpha = zQuantile(twoSided ? 1 - alpha / 2 : 1 - alpha)\n const denom = Math.sqrt(Math.max(1e-12, pDisc - delta * delta))\n const zBeta = (Math.sqrt(nPairs) * Math.abs(delta) - zAlpha * Math.sqrt(pDisc)) / denom\n return Math.min(1, Math.max(0, normalCdf(zBeta)))\n}\n\n/** Bonferroni adjustment: multiply every p-value by the test count, clamp at 1. */\nexport function bonferroni(\n pValues: number[],\n alpha = 0.05,\n): { adjusted: number[]; significant: boolean[] } {\n const k = pValues.length\n const adjusted = pValues.map((p) => Math.min(1, p * k))\n const significant = adjusted.map((p) => p < alpha)\n return { adjusted, significant }\n}\n\n/**\n * Holm step-down family-wise error adjustment.\n *\n * P-values are sorted from smallest to largest, multiplied by their remaining\n * hypothesis count, and made monotonically non-decreasing before being mapped\n * back to input order. This uniformly dominates plain Bonferroni while keeping\n * strong family-wise error control under arbitrary dependence.\n */\nexport function holm(\n pValues: readonly number[],\n alpha = 0.05,\n): { adjusted: number[]; significant: boolean[] } {\n if (!Number.isFinite(alpha) || alpha <= 0 || alpha >= 1) {\n throw new ValidationError(`holm: alpha must be in (0,1), got ${alpha}`)\n }\n for (const [index, pValue] of pValues.entries()) {\n if (!Number.isFinite(pValue) || pValue < 0 || pValue > 1) {\n throw new ValidationError(`holm: pValues[${index}] must be in [0,1], got ${pValue}`)\n }\n }\n const count = pValues.length\n if (count === 0) return { adjusted: [], significant: [] }\n\n const ordered = pValues\n .map((pValue, index) => ({ pValue, index }))\n .sort((a, b) => a.pValue - b.pValue || a.index - b.index)\n const adjusted = new Array<number>(count)\n let previous = 0\n for (let rank = 0; rank < count; rank++) {\n const entry = ordered[rank]!\n const stepAdjusted = Math.min(1, entry.pValue * (count - rank))\n previous = Math.max(previous, stepAdjusted)\n adjusted[entry.index] = previous\n }\n // Holm's rejection rule is inclusive at the adjusted alpha boundary.\n return { adjusted, significant: adjusted.map((pValue) => pValue <= alpha) }\n}\n\n/**\n * Benjamini–Hochberg false discovery rate. Returns adjusted q-values and\n * significance at the target FDR; handles ties and preserves q monotonicity.\n */\nexport function benjaminiHochberg(\n pValues: number[],\n fdr = 0.05,\n): { qValues: number[]; significant: boolean[] } {\n const n = pValues.length\n if (n === 0) return { qValues: [], significant: [] }\n const indexed = pValues.map((p, i) => ({ p, i })).sort((a, b) => a.p - b.p)\n const q = new Array<number>(n)\n let minRight = 1\n for (let k = n - 1; k >= 0; k--) {\n const rank = k + 1\n const entry = indexed[k]!\n const raw = (entry.p * n) / rank\n const bounded = Math.min(minRight, raw)\n minRight = bounded\n q[entry.i] = Math.min(1, bounded)\n }\n const significant = q.map((v) => v < fdr)\n return { qValues: q, significant }\n}\n\n// ── Paired bootstrap (promotion-gate effect size) ────────────────────\n\nexport interface PairedBootstrapResult {\n /** Number of paired observations. */\n n: number\n /** Median of paired deltas (after − before). */\n median: number\n /** Mean of paired deltas. */\n mean: number\n /** Lower bound of the bootstrap CI on the chosen statistic. */\n low: number\n /** Upper bound of the bootstrap CI on the chosen statistic. */\n high: number\n /** Confidence level used (e.g. 0.95). */\n confidence: number\n /** Number of bootstrap resamples used. */\n resamples: number\n}\n\nexport interface PairedBootstrapOptions {\n /** Confidence level. Default 0.95. */\n confidence?: number\n /** Bootstrap resample count. Default 2000. */\n resamples?: number\n /** Statistic to bootstrap. Default 'median'. */\n statistic?: 'median' | 'mean'\n /** Deterministic seed. If omitted, uses Math.random(). */\n seed?: number\n}\n\n/**\n * Paired bootstrap on (after − before) deltas. Returns a CI on the chosen\n * statistic (median by default); pairs are resampled with replacement. The\n * lower bound is what the promotion gate checks — `low > threshold` means the\n * gain is real at the confidence level. Throws on unequal sample sizes.\n */\nexport function pairedBootstrap(\n before: number[],\n after: number[],\n opts: PairedBootstrapOptions = {},\n): PairedBootstrapResult {\n if (before.length !== after.length) {\n throw new Error(`pairedBootstrap: unequal sample sizes (${before.length} vs ${after.length})`)\n }\n const confidence = opts.confidence ?? 0.95\n const resamples = opts.resamples ?? 2000\n const statistic = opts.statistic ?? 'median'\n if (confidence <= 0 || confidence >= 1) {\n throw new Error(`pairedBootstrap: confidence must be in (0,1), got ${confidence}`)\n }\n\n const n = before.length\n const deltas = before.map((b, i) => after[i]! - b)\n if (n === 0) {\n return { n: 0, median: 0, mean: 0, low: 0, high: 0, confidence, resamples }\n }\n if (n === 1) {\n const d = deltas[0]!\n return { n: 1, median: d, mean: d, low: d, high: d, confidence, resamples }\n }\n\n const rng = makeRng(opts.seed)\n const samples = new Array<number>(resamples)\n for (let b = 0; b < resamples; b++) {\n if (statistic === 'mean') {\n let sum = 0\n for (let k = 0; k < n; k++) {\n sum += deltas[Math.floor(rng() * n)]!\n }\n samples[b] = sum / n\n } else {\n const acc = new Array<number>(n)\n for (let k = 0; k < n; k++) {\n acc[k] = deltas[Math.floor(rng() * n)]!\n }\n samples[b] = medianInPlace(acc)\n }\n }\n samples.sort((a, b) => a - b)\n\n const alpha = 1 - confidence\n const lowIdx = Math.floor((alpha / 2) * resamples)\n const highIdx = Math.min(resamples - 1, Math.ceil((1 - alpha / 2) * resamples) - 1)\n\n return {\n n,\n median: medianInPlace([...deltas]),\n mean: deltas.reduce((s, x) => s + x, 0) / n,\n low: samples[lowIdx]!,\n high: samples[Math.max(highIdx, lowIdx)]!,\n confidence,\n resamples,\n }\n}\n\n/** Pre-registered direction for a one-sided paired sign test. */\nexport type SignTestAlternative = 'greater' | 'less'\n\n/** Exact one-sided sign-test result for paired numeric differences. */\nexport interface PairedSignTestResult {\n /** Total supplied differences, including zero ties. */\n n: number\n /** Strictly positive differences. */\n positive: number\n /** Strictly negative differences. */\n negative: number\n /** Zero differences excluded from the binomial test. */\n ties: number\n /** Non-zero differences used by the binomial test. */\n nNonTies: number\n /** Direction of the pre-registered alternative hypothesis. */\n alternative: SignTestAlternative\n /** Exact one-sided p-value under P(positive) = P(negative) = 0.5. */\n pValue: number\n}\n\n/**\n * Exact one-sided sign test over paired differences.\n *\n * Pass `after[i] - before[i]` for each matched item. `alternative = 'greater'`\n * tests whether positive signs are more likely than negative signs and returns\n * `P(Binomial(nNonTies, 0.5) >= positive)`. `alternative = 'less'` treats\n * negative signs as successes instead. With a continuous difference\n * distribution this is the usual directional median test. Exact zero\n * differences are ties and do not enter the binomial denominator. All-tie and\n * empty inputs return p = 1. Every input difference must be finite, and the\n * direction must be chosen explicitly so a caller cannot select it after\n * seeing the signs.\n */\nexport function pairedSignTest(\n differences: readonly number[],\n alternative: SignTestAlternative,\n): PairedSignTestResult {\n if (alternative !== 'greater' && alternative !== 'less') {\n throw new ValidationError(\n `pairedSignTest: alternative must be 'greater' or 'less', got ${alternative}`,\n )\n }\n\n let positive = 0\n let negative = 0\n let ties = 0\n for (let i = 0; i < differences.length; i++) {\n const difference = differences[i]!\n if (!Number.isFinite(difference)) {\n throw new ValidationError(\n `pairedSignTest: difference at index ${i} must be finite, got ${difference}`,\n )\n }\n if (difference > 0) positive++\n else if (difference < 0) negative++\n else ties++\n }\n\n const nNonTies = positive + negative\n const successes = alternative === 'greater' ? positive : negative\n return {\n n: differences.length,\n positive,\n negative,\n ties,\n nNonTies,\n alternative,\n pValue: binomialHalfUpperTail(successes, nNonTies),\n }\n}\n\n// ── Binomial proportion + paired-binary + coding-eval estimators ─────\n//\n// The paired family above (pairedBootstrap/pairedTTest/wilcoxonSignedRank)\n// operates on continuous scores. Pass/fail A/B comparisons — \"does treatment\n// X raise the success RATE vs control\" — are binary and paired, so they need\n// their own correct estimators: McNemar for significance (only the discordant\n// pairs carry signal), the paired risk difference for effect size, Wilson for\n// a single-arm proportion CI, and pass@k for the standard k-sample coding-eval\n// metric. The normal approximation is wrong for proportions near 0/1 and for\n// the small discordant counts typical of eval runs, so these are exact /\n// Wilson-based, not Wald.\n\n/** A binomial proportion estimate with a confidence interval. */\nexport interface ProportionInterval {\n /** Point estimate successes / n (0 when n = 0). */\n estimate: number\n /** Lower bound, clamped to [0, 1]. */\n lower: number\n /** Upper bound, clamped to [0, 1]. */\n upper: number\n}\n\n/**\n * Wilson score interval for a binomial proportion. Correct at small n and near\n * 0/1, where the normal (Wald) approximation produces bounds outside [0, 1] and\n * understates coverage. Use this for any pass-rate / hit-rate / realness-rate\n * CI — the continuous `confidenceInterval` assumes the wrong distribution for a\n * proportion. `n = 0 ⇒ {0, 0, 0}`.\n */\nexport function wilson(successes: number, n: number, confidence = 0.95): ProportionInterval {\n if (n <= 0) return { estimate: 0, lower: 0, upper: 0 }\n if (successes < 0 || successes > n) {\n throw new Error(`wilson: successes (${successes}) must be in [0, ${n}]`)\n }\n const z = zQuantile(1 - (1 - confidence) / 2)\n const p = successes / n\n const z2 = z * z\n const denom = 1 + z2 / n\n const center = (p + z2 / (2 * n)) / denom\n const half = (z * Math.sqrt((p * (1 - p) + z2 / (4 * n)) / n)) / denom\n return {\n estimate: p,\n lower: Math.max(0, center - half),\n upper: Math.min(1, center + half),\n }\n}\n\n/** Result of a McNemar paired-binary significance test. */\nexport interface McNemarResult {\n /** Total paired observations. */\n n: number\n /** Discordant pairs (b + c) — the only ones that carry signal. */\n nDiscordant: number\n /** Pairs where treatment succeeded and control failed (\"newly correct\"). */\n b: number\n /** Pairs where control succeeded and treatment failed (\"newly wrong\"). */\n c: number\n /** Continuity-corrected chi-square statistic (reference; exact p drives the call). */\n statistic: number\n /** Two-sided p-value. Exact (binomial sign test on discordant pairs). */\n pValue: number\n}\n\n/**\n * McNemar's test for paired binary outcomes — the correct significance test for\n * \"does treatment change the success rate vs control on the SAME items\". Only\n * discordant pairs (one arm right, the other wrong) carry information; concordant\n * pairs are uninformative, so a paired t-test / two-proportion z-test on the raw\n * rates is wrong here. The p-value is exact: under H0 the b \"treatment-wins\" are\n * Binomial(b + c, 0.5), so the two-sided p is the doubled binomial tail — correct\n * at the small discordant counts typical of eval runs (no continuity-corrected\n * chi-square approximation needed, though it is returned as `statistic` for\n * reference). Inputs are paired 0/1 (or boolean) arrays, control first to match\n * the module's (before, after) convention. Throws on unequal lengths.\n */\nexport function mcnemar(\n control: ArrayLike<number | boolean>,\n treatment: ArrayLike<number | boolean>,\n): McNemarResult {\n if (control.length !== treatment.length) {\n throw new Error(`mcnemar: unequal sample sizes (${control.length} vs ${treatment.length})`)\n }\n const n = control.length\n let b = 0 // treatment 1, control 0\n let c = 0 // treatment 0, control 1\n for (let i = 0; i < n; i++) {\n const ctrl = control[i] ? 1 : 0\n const treat = treatment[i] ? 1 : 0\n if (treat === 1 && ctrl === 0) b++\n else if (treat === 0 && ctrl === 1) c++\n }\n const nDiscordant = b + c\n const statistic = nDiscordant === 0 ? 0 : (Math.abs(b - c) - 1) ** 2 / nDiscordant\n return { n, nDiscordant, b, c, statistic, pValue: binomialSignTwoSided(b, c) }\n}\n\n/** A paired binary effect size (treatment rate − control rate) with a CI. */\nexport interface RiskDifferenceResult {\n /** Total paired observations. */\n n: number\n /** Discordant pairs: treatment-win count. */\n b: number\n /** Discordant pairs: control-win count. */\n c: number\n /** Paired risk difference p(treatment) − p(control) = (b − c) / n. */\n riskDifference: number\n /** Lower bound of the CI, clamped to [-1, 1]. */\n lower: number\n /** Upper bound of the CI, clamped to [-1, 1]. */\n upper: number\n /** Confidence level used. */\n confidence: number\n}\n\n/**\n * Paired risk difference (the effect-size companion to {@link mcnemar}): the\n * change in success rate p(treatment) − p(control) on matched items, which for\n * paired binary data equals (b − c) / n. The CI uses the paired variance from\n * the discordant counts, not the independent-samples formula (which overstates\n * the interval by ignoring the pairing). Inputs are paired 0/1 (or boolean)\n * arrays, control first. Throws on unequal lengths.\n */\nexport function pairedRiskDifference(\n control: ArrayLike<number | boolean>,\n treatment: ArrayLike<number | boolean>,\n confidence = 0.95,\n): RiskDifferenceResult {\n if (control.length !== treatment.length) {\n throw new Error(\n `pairedRiskDifference: unequal sample sizes (${control.length} vs ${treatment.length})`,\n )\n }\n const n = control.length\n if (n === 0) return { n: 0, b: 0, c: 0, riskDifference: 0, lower: 0, upper: 0, confidence }\n let b = 0\n let c = 0\n for (let i = 0; i < n; i++) {\n const ctrl = control[i] ? 1 : 0\n const treat = treatment[i] ? 1 : 0\n if (treat === 1 && ctrl === 0) b++\n else if (treat === 0 && ctrl === 1) c++\n }\n const rd = (b - c) / n\n const variance = (b + c - (b - c) ** 2 / n) / (n * n)\n const z = zQuantile(1 - (1 - confidence) / 2)\n const half = z * Math.sqrt(Math.max(0, variance))\n return {\n n,\n b,\n c,\n riskDifference: rd,\n lower: Math.max(-1, rd - half),\n upper: Math.min(1, rd + half),\n confidence,\n }\n}\n\n/**\n * Unbiased pass@k for code generation (Chen et al. 2021, \"Evaluating Large\n * Language Models Trained on Code\"). Given `n` independent samples for one\n * problem of which `c` pass, the probability that at least one of a random k of\n * them passes is 1 − C(n−c, k) / C(n, k). Estimating pass@k as \"did any of the\n * first k pass\" is biased high at small n; this is the variance-reduced estimator\n * averaged implicitly over all k-subsets. Average the per-problem values across\n * the suite for the corpus pass@k. Computed in the numerically stable product\n * form. Requires 1 ≤ k ≤ n and 0 ≤ c ≤ n.\n */\nexport function passAtK(n: number, c: number, k: number): number {\n if (!Number.isInteger(n) || !Number.isInteger(c) || !Number.isInteger(k)) {\n throw new Error(`passAtK: n, c, k must be integers (got n=${n}, c=${c}, k=${k})`)\n }\n if (k < 1 || k > n || c < 0 || c > n) {\n throw new Error(`passAtK: require 1 ≤ k ≤ n and 0 ≤ c ≤ n (got n=${n}, c=${c}, k=${k})`)\n }\n if (n - c < k) return 1\n let prob = 1\n for (let i = n - c + 1; i <= n; i++) prob *= 1 - k / i\n return 1 - prob\n}\n\n/**\n * Two-sided exact p-value for b successes out of (b + c) Bernoulli(0.5) trials —\n * the exact-binomial core of {@link mcnemar}. `min(1, 2·P(X ≤ min(b,c)))`. No\n * discordant pairs ⇒ no evidence ⇒ p = 1. Summed in log space (lnGamma) so it\n * stays exact at large discordant counts without overflow.\n */\nfunction binomialSignTwoSided(b: number, c: number): number {\n const nd = b + c\n if (nd === 0) return 1\n return Math.min(1, 2 * binomialHalfLowerTail(Math.min(b, c), nd))\n}\n\n/** P(X >= successes) for X ~ Binomial(n, 0.5). */\nfunction binomialHalfUpperTail(successes: number, n: number): number {\n if (successes <= 0) return 1\n if (successes > n) return 0\n\n // Use the smaller side of the distribution. For lower thresholds the\n // complement sums at most half the mass; for upper thresholds symmetry\n // maps the upper tail to a lower tail without subtraction.\n if (successes <= n / 2) {\n return Math.max(0, 1 - binomialHalfLowerTail(successes - 1, n))\n }\n return binomialHalfLowerTail(n - successes, n)\n}\n\n/** P(X <= maxSuccesses) for X ~ Binomial(n, 0.5), accumulated in log space. */\nfunction binomialHalfLowerTail(maxSuccesses: number, n: number): number {\n if (maxSuccesses < 0) return 0\n if (maxSuccesses >= n) return 1\n if (maxSuccesses === 0) return 2 ** -n\n\n const logHalfN = n * Math.log(0.5)\n let logTail = Number.NEGATIVE_INFINITY\n for (let i = 0; i <= maxSuccesses; i++) {\n const logChoose = lnGamma(n + 1) - lnGamma(i + 1) - lnGamma(n - i + 1)\n logTail = logAddExp(logTail, logChoose + logHalfN)\n }\n return Math.min(1, Math.exp(logTail))\n}\n\nfunction logAddExp(a: number, b: number): number {\n if (a === Number.NEGATIVE_INFINITY) return b\n if (b === Number.NEGATIVE_INFINITY) return a\n const max = Math.max(a, b)\n const min = Math.min(a, b)\n return max + Math.log1p(Math.exp(min - max))\n}\n\n// ── Anytime-valid e-process (betting test-martingale) ────────────────\n\nexport interface EProcessOptions {\n /** Type-I error budget. The process decides when wealth ≥ 1/alpha\n * (Ville's inequality). Default 0.05. */\n alpha?: number\n /** Truncation bound on the predictable bet λ ∈ [0, maxBet]. Must satisfy\n * maxBet < 1/nullMean so every wealth factor stays strictly positive.\n * Default 0.5. */\n maxBet?: number\n /** The null boundary m₀ for H0: E[x] ≤ m₀ on x ∈ [0,1]. Default 0.5\n * (the paired-delta encoding x = (d+1)/2 maps \"no effect\" to 1/2).\n * A pre-registered minEffect shifts this — see `sequentialPairedGate`. */\n nullMean?: number\n}\n\nexport interface EProcessStep {\n /** Current wealth W_n — the e-value against H0 after n observations. */\n wealth: number\n /** Observations consumed so far. */\n n: number\n /** True from the first n where W_n ≥ 1/alpha onward (sticky). */\n decided: boolean\n}\n\nexport interface EProcessState extends EProcessStep {\n alpha: number\n maxBet: number\n nullMean: number\n /** The decision boundary 1/alpha. */\n threshold: number\n /** Observation count at the first threshold crossing; undefined until decided. */\n decidedAtN?: number\n}\n\nexport interface EProcess {\n /** Consume one observation x ∈ [0,1]. Throws on non-finite / out-of-range\n * input — a silent clamp would corrupt the type-I guarantee. */\n update(x: number): EProcessStep\n state(): EProcessState\n}\n\n/**\n * Betting test-martingale for bounded observations — the e-process core of\n * anytime-valid sequential testing (Waudby-Smith & Ramdas, \"Estimating means\n * of bounded random variables by betting\", JRSS-B 2024).\n *\n * Observations x_i ∈ [0,1]; H0: E[x] ≤ m₀ (`nullMean`, default 1/2). Wealth\n *\n * W_t = Π_{i≤t} (1 + λ_i (x_i − m₀)), W_0 = 1\n *\n * with the truncated GROW-style plug-in bet computed from PRIOR observations:\n *\n * λ_i = clamp((μ̂_{i−1} − m₀) / (σ̂²_{i−1} + (μ̂_{i−1} − m₀)²), 0, maxBet)\n *\n * where μ̂/σ̂² are the shrunk running estimates μ̂_t = (1/2 + Σx_i)/(t+1),\n * σ̂²_t = (1/4 + Σ(x_i − μ̂_i)²)/(t+1).\n *\n * PREDICTABILITY INVARIANT (load-bearing): λ_i is a function of x_1..x_{i−1}\n * ONLY — it may never see x_i. With λ_i ≥ 0 predictable, each factor has\n * E[1 + λ_i(x_i − m₀) | past] ≤ 1 under H0, so W is a nonnegative\n * supermartingale and Ville's inequality gives P(∃t: W_t ≥ 1/α) ≤ α — the\n * type-I guarantee holds at ANY data-dependent stopping time. λ_1 is always 0\n * (no prior evidence), so the first observation never moves wealth.\n *\n * `decided` latches at the first crossing W_t ≥ 1/α and never un-latches;\n * wealth keeps updating after the crossing (the e-process remains valid), but\n * the decision time is the first crossing.\n */\nexport function eProcess(opts: EProcessOptions = {}): EProcess {\n const alpha = opts.alpha ?? 0.05\n const maxBet = opts.maxBet ?? 0.5\n const nullMean = opts.nullMean ?? 0.5\n if (!Number.isFinite(alpha) || alpha <= 0 || alpha >= 1) {\n throw new ValidationError(`eProcess: alpha must be in (0,1), got ${alpha}`)\n }\n if (!Number.isFinite(nullMean) || nullMean <= 0 || nullMean >= 1) {\n throw new ValidationError(`eProcess: nullMean must be in (0,1), got ${nullMean}`)\n }\n if (!Number.isFinite(maxBet) || maxBet <= 0 || maxBet >= 1 / nullMean) {\n throw new ValidationError(\n `eProcess: maxBet must be in (0, 1/nullMean=${(1 / nullMean).toFixed(4)}) so wealth ` +\n `factors stay positive, got ${maxBet}`,\n )\n }\n const threshold = 1 / alpha\n let wealth = 1\n let n = 0\n let decided = false\n let decidedAtN: number | undefined\n // Running sums over observations consumed so far — read BEFORE folding in\n // the next x, so every bet is predictable.\n let sumX = 0\n let varSum = 0\n return {\n update(x: number): EProcessStep {\n if (typeof x !== 'number' || !Number.isFinite(x) || x < 0 || x > 1) {\n throw new ValidationError(\n `eProcess: observation must be a finite number in [0,1], got ${x}`,\n )\n }\n // λ from prior observations ONLY — x has not touched sumX/varSum yet.\n const muPrev = (0.5 + sumX) / (n + 1)\n const varPrev = (0.25 + varSum) / (n + 1)\n const edge = muPrev - nullMean\n const lambda = Math.min(maxBet, Math.max(0, edge / (varPrev + edge * edge)))\n wealth *= 1 + lambda * (x - nullMean)\n n += 1\n sumX += x\n const muNow = (0.5 + sumX) / (n + 1)\n varSum += (x - muNow) ** 2\n if (!decided && wealth >= threshold) {\n decided = true\n decidedAtN = n\n }\n return { wealth, n, decided }\n },\n state(): EProcessState {\n return { wealth, n, decided, alpha, maxBet, nullMean, threshold, decidedAtN }\n },\n }\n}\n\n// ── private stats helpers ────────────────────────────────────────────\n\n/** Standard-normal inverse CDF (Acklam approximation). */\nfunction zQuantile(p: number): number {\n if (p <= 0 || p >= 1) {\n if (p === 0) return -Infinity\n if (p === 1) return Infinity\n return NaN\n }\n const a = [\n -3.969683028665376e1, 2.209460984245205e2, -2.759285104469687e2, 1.38357751867269e2,\n -3.066479806614716e1, 2.506628277459239,\n ]\n const b = [\n -5.447609879822406e1, 1.615858368580409e2, -1.556989798598866e2, 6.680131188771972e1,\n -1.328068155288572e1,\n ]\n const c = [\n -7.784894002430293e-3, -3.223964580411365e-1, -2.400758277161838, -2.549732539343734,\n 4.374664141464968, 2.938163982698783,\n ]\n const d = [7.784695709041462e-3, 3.224671290700398e-1, 2.445134137142996, 3.754408661907416]\n const pLow = 0.02425\n const pHigh = 1 - pLow\n let q: number\n let r: number\n if (p < pLow) {\n q = Math.sqrt(-2 * Math.log(p))\n return (\n (((((c[0]! * q + c[1]!) * q + c[2]!) * q + c[3]!) * q + c[4]!) * q + c[5]!) /\n ((((d[0]! * q + d[1]!) * q + d[2]!) * q + d[3]!) * q + 1)\n )\n }\n if (p <= pHigh) {\n q = p - 0.5\n r = q * q\n return (\n ((((((a[0]! * r + a[1]!) * r + a[2]!) * r + a[3]!) * r + a[4]!) * r + a[5]!) * q) /\n (((((b[0]! * r + b[1]!) * r + b[2]!) * r + b[3]!) * r + b[4]!) * r + 1)\n )\n }\n q = Math.sqrt(-2 * Math.log(1 - p))\n return (\n -(((((c[0]! * q + c[1]!) * q + c[2]!) * q + c[3]!) * q + c[4]!) * q + c[5]!) /\n ((((d[0]! * q + d[1]!) * q + d[2]!) * q + d[3]!) * q + 1)\n )\n}\n\nfunction medianInPlace(xs: number[]): number {\n if (xs.length === 0) return 0\n xs.sort((a, b) => a - b)\n const mid = Math.floor(xs.length / 2)\n return xs.length % 2 === 0 ? (xs[mid - 1]! + xs[mid]!) / 2 : xs[mid]!\n}\n\nfunction makeRng(seed: number | undefined): () => number {\n if (seed === undefined) return Math.random\n return mulberry32(seed)\n}\n\n/** Tiny seedable PRNG (mulberry32) — deterministic resampling/shuffling, not\n * cryptographic. Exported so e-process shuffles and bootstrap resampling\n * share ONE PRNG implementation; a seed is REQUIRED (unseeded randomness in\n * gate verdicts is non-reproducible by construction). */\nexport function mulberry32(seed: number): () => number {\n let s = seed | 0 || 0x9e3779b9\n return () => {\n s = (s + 0x6d2b79f5) | 0\n let t = s\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,eACd,QACA,WACmB;CACnB,MAAM,sBAAM,IAAI,IAAsC;CACtD,KAAK,MAAM,KAAK,QAAQ,IAAI,IAAI,EAAE,QAAQ;EAAE,GAAG,EAAE;EAAY,GAAG;CAAI,CAAC;CACrE,KAAK,MAAM,KAAK,WAAW;EACzB,MAAM,QAAQ,IAAI,IAAI,EAAE,MAAM;EAC9B,IAAI,OAAO,MAAM,IAAI,EAAE;CACzB;CACA,MAAM,SAAS,CAAC,GAAG,IAAI,OAAO,CAAC,CAAC,CAAC,QAAQ,MAAM,OAAO,SAAS,EAAE,CAAC,CAAC;CACnE,MAAM,IAAI,OAAO;CACjB,IAAI,IAAI,GACN,OAAO;EAAE;EAAG,SAAS;EAAK,OAAO;EAAK,KAAK;EAAK,YAAY,CAAC;CAAE;CAEjE,MAAM,SAAS,OAAO,KAAK,MAAM,EAAE,CAAC;CACpC,MAAM,SAAS,OAAO,KAAK,MAAM,EAAE,CAAC;CAUpC,OAAO;EAAE;EAAG,SATI,SAAS,QAAQ,MASf;EAAG,OARP,cAAc,OAAO,IAAI,KAAK,KAAK,GAAG,OAAO,IAAI,KAAK,KAAK,CAQhD;EAAG,KA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