@arnilo/prism-hosts 0.0.0-stage → 0.13.1

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 (322) hide show
  1. package/CHANGELOG.md +394 -0
  2. package/LICENSE +21 -0
  3. package/README.md +34 -2
  4. package/acp/README.md +87 -0
  5. package/acp/src/capabilities.ts +184 -0
  6. package/acp/src/errors.ts +24 -0
  7. package/acp/src/host.ts +36 -0
  8. package/acp/src/index.ts +25 -0
  9. package/acp/src/limits.ts +49 -0
  10. package/acp/src/mapper.ts +419 -0
  11. package/acp/src/permission.ts +37 -0
  12. package/acp/src/projection.ts +39 -0
  13. package/acp/src/prompt.ts +170 -0
  14. package/acp/src/serve.ts +345 -0
  15. package/acp/src/session-map.ts +49 -0
  16. package/ag-ui/README.md +56 -0
  17. package/ag-ui/src/a2ui.ts +570 -0
  18. package/ag-ui/src/ag-ui-mapper.ts +507 -0
  19. package/ag-ui/src/encrypted-value.ts +40 -0
  20. package/ag-ui/src/errors.ts +29 -0
  21. package/ag-ui/src/handler.ts +642 -0
  22. package/ag-ui/src/index.ts +177 -0
  23. package/ag-ui/src/input.ts +190 -0
  24. package/ag-ui/src/limits.ts +279 -0
  25. package/ag-ui/src/mcp-apps.ts +256 -0
  26. package/ag-ui/src/mcp.ts +94 -0
  27. package/ag-ui/src/projection.ts +201 -0
  28. package/ag-ui/src/projectors.ts +272 -0
  29. package/ag-ui/src/renderer/bind.ts +152 -0
  30. package/ag-ui/src/renderer/core.ts +270 -0
  31. package/ag-ui/src/renderer/index.ts +165 -0
  32. package/ag-ui/src/replay.ts +189 -0
  33. package/ag-ui/src/types.ts +66 -0
  34. package/channels/README.md +139 -0
  35. package/channels/src/admission.ts +8 -0
  36. package/channels/src/approvals.ts +262 -0
  37. package/channels/src/checkpoint-contract.ts +97 -0
  38. package/channels/src/delivery.ts +116 -0
  39. package/channels/src/host-ui.ts +356 -0
  40. package/channels/src/identity.ts +46 -0
  41. package/channels/src/index.ts +82 -0
  42. package/channels/src/limits.ts +49 -0
  43. package/channels/src/memory-stores.ts +112 -0
  44. package/channels/src/pairing.ts +178 -0
  45. package/channels/src/runtime-admit.ts +389 -0
  46. package/channels/src/runtime-core.ts +621 -0
  47. package/channels/src/runtime-reconcile.ts +299 -0
  48. package/channels/src/runtime-turn.ts +664 -0
  49. package/channels/src/runtime-types.ts +95 -0
  50. package/channels/src/runtime.ts +86 -0
  51. package/channels/src/secret-ref.ts +42 -0
  52. package/channels/src/signal.ts +790 -0
  53. package/channels/src/state.ts +355 -0
  54. package/channels/src/telegram.ts +1317 -0
  55. package/channels/src/types.ts +442 -0
  56. package/devtools/README.md +92 -0
  57. package/devtools/bin/prism-devtools.ts +63 -0
  58. package/devtools/src/args.ts +71 -0
  59. package/devtools/src/bun.d.ts +27 -0
  60. package/devtools/src/compare.ts +190 -0
  61. package/devtools/src/errors.ts +15 -0
  62. package/devtools/src/index.ts +25 -0
  63. package/devtools/src/replay.ts +36 -0
  64. package/devtools/src/security.ts +80 -0
  65. package/devtools/src/serve.ts +259 -0
  66. package/devtools/src/ui/assets.ts +108 -0
  67. package/devtools/src/ui/inspector.ts +182 -0
  68. package/driver-process/README.md +197 -0
  69. package/driver-process/src/abort.ts +74 -0
  70. package/driver-process/src/adapter.ts +211 -0
  71. package/driver-process/src/driver.ts +303 -0
  72. package/driver-process/src/errors.ts +17 -0
  73. package/driver-process/src/extend.ts +72 -0
  74. package/driver-process/src/index.ts +5 -0
  75. package/driver-process/src/inspect.ts +33 -0
  76. package/driver-process/src/session.ts +72 -0
  77. package/driver-process/src/testing.ts +394 -0
  78. package/driver-process/src/transports/json-rpc.ts +147 -0
  79. package/driver-process/src/transports/jsonl-stream.ts +12 -0
  80. package/driver-process/src/transports/types.ts +11 -0
  81. package/driver-process/src/turn.ts +106 -0
  82. package/evals/README.md +843 -0
  83. package/evals/src/calibration.ts +179 -0
  84. package/evals/src/citation-integrity.ts +98 -0
  85. package/evals/src/citations.ts +45 -0
  86. package/evals/src/compare-experiments.ts +153 -0
  87. package/evals/src/comparison.ts +230 -0
  88. package/evals/src/curate.ts +257 -0
  89. package/evals/src/dataset.ts +81 -0
  90. package/evals/src/erp-invariants.ts +163 -0
  91. package/evals/src/errors.ts +23 -0
  92. package/evals/src/experiment.ts +537 -0
  93. package/evals/src/failure-injection.ts +77 -0
  94. package/evals/src/feedback.ts +53 -0
  95. package/evals/src/index.ts +198 -0
  96. package/evals/src/injection.ts +247 -0
  97. package/evals/src/judge-panel.ts +109 -0
  98. package/evals/src/judge.ts +89 -0
  99. package/evals/src/limits.ts +50 -0
  100. package/evals/src/report-record.ts +47 -0
  101. package/evals/src/rubric-judge.ts +334 -0
  102. package/evals/src/scenario-runner.ts +317 -0
  103. package/evals/src/scenarios.ts +81 -0
  104. package/evals/src/score.ts +328 -0
  105. package/evals/src/scorer.ts +21 -0
  106. package/evals/src/state-match.ts +130 -0
  107. package/evals/src/stats.ts +635 -0
  108. package/evals/src/threshold.ts +117 -0
  109. package/evals/src/timeline.ts +38 -0
  110. package/evals/src/toolless-session.ts +33 -0
  111. package/evals/src/trace.ts +80 -0
  112. package/evals/src/trajectory.ts +623 -0
  113. package/evals/src/types.ts +672 -0
  114. package/evals/src/user-simulator.ts +101 -0
  115. package/evals/src/util.ts +207 -0
  116. package/headless/README.md +172 -0
  117. package/headless/src/answers.ts +91 -0
  118. package/headless/src/authority.ts +32 -0
  119. package/headless/src/errors.ts +36 -0
  120. package/headless/src/index.ts +17 -0
  121. package/headless/src/limits.ts +11 -0
  122. package/headless/src/pending.ts +16 -0
  123. package/headless/src/policy.ts +36 -0
  124. package/headless/src/resume.ts +103 -0
  125. package/headless/src/route.ts +153 -0
  126. package/headless/src/scheduler/clock.ts +22 -0
  127. package/headless/src/scheduler/cron.ts +19 -0
  128. package/headless/src/scheduler/firing.ts +58 -0
  129. package/headless/src/scheduler/index.ts +399 -0
  130. package/headless/src/scheduler/lease.ts +38 -0
  131. package/headless/src/scheduler/missed.ts +12 -0
  132. package/headless/src/scheduler/state.ts +132 -0
  133. package/host-builder/README.md +251 -0
  134. package/host-builder/bin/prism-host-builder.ts +169 -0
  135. package/host-builder/data/api.json +6197 -0
  136. package/host-builder/data/errors.json +558 -0
  137. package/host-builder/data/examples/acp.ts +63 -0
  138. package/host-builder/data/examples/adapters/conformance.ts +34 -0
  139. package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
  140. package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
  141. package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
  142. package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
  143. package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
  144. package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
  145. package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
  146. package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
  147. package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
  148. package/host-builder/data/examples/advisor.ts +94 -0
  149. package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
  150. package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
  151. package/host-builder/data/examples/ag-ui-server.ts +118 -0
  152. package/host-builder/data/examples/agent-durable-approval.ts +43 -0
  153. package/host-builder/data/examples/api-key-auth.ts +23 -0
  154. package/host-builder/data/examples/approval.ts +92 -0
  155. package/host-builder/data/examples/attention-compiler.ts +81 -0
  156. package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
  157. package/host-builder/data/examples/behavior-evaluation.ts +303 -0
  158. package/host-builder/data/examples/build-workflow.ts +334 -0
  159. package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
  160. package/host-builder/data/examples/caveman-ponytail.ts +197 -0
  161. package/host-builder/data/examples/cli.ts +31 -0
  162. package/host-builder/data/examples/coding-approval.ts +115 -0
  163. package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
  164. package/host-builder/data/examples/coding-compaction.ts +30 -0
  165. package/host-builder/data/examples/coding-goal-verify.ts +121 -0
  166. package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
  167. package/host-builder/data/examples/compaction.ts +36 -0
  168. package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
  169. package/host-builder/data/examples/context.ts +29 -0
  170. package/host-builder/data/examples/custom-adapter.ts +256 -0
  171. package/host-builder/data/examples/custom-builders.ts +66 -0
  172. package/host-builder/data/examples/custom-loop.ts +89 -0
  173. package/host-builder/data/examples/custom-provider.ts +70 -0
  174. package/host-builder/data/examples/custom-session-store.ts +72 -0
  175. package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
  176. package/host-builder/data/examples/decision-models.ts +98 -0
  177. package/host-builder/data/examples/define-package.ts +188 -0
  178. package/host-builder/data/examples/delegate.ts +200 -0
  179. package/host-builder/data/examples/discover-skills.ts +65 -0
  180. package/host-builder/data/examples/drive-rag-sync.ts +44 -0
  181. package/host-builder/data/examples/durable-approval.ts +139 -0
  182. package/host-builder/data/examples/durable-investigation.ts +93 -0
  183. package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
  184. package/host-builder/data/examples/enterprise-identity.ts +21 -0
  185. package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
  186. package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
  187. package/host-builder/data/examples/eval-injection.ts +73 -0
  188. package/host-builder/data/examples/eval-judges.ts +145 -0
  189. package/host-builder/data/examples/evals.ts +86 -0
  190. package/host-builder/data/examples/evaluation-gate.ts +40 -0
  191. package/host-builder/data/examples/execution-timeline.ts +173 -0
  192. package/host-builder/data/examples/external-agent.ts +541 -0
  193. package/host-builder/data/examples/external-app-db-backed.ts +344 -0
  194. package/host-builder/data/examples/governance-deny.ts +122 -0
  195. package/host-builder/data/examples/guardrail-packs.ts +240 -0
  196. package/host-builder/data/examples/headless-host.ts +245 -0
  197. package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
  198. package/host-builder/data/examples/hooks-json.ts +87 -0
  199. package/host-builder/data/examples/host-builder-agent.ts +150 -0
  200. package/host-builder/data/examples/host-hooks.ts +71 -0
  201. package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
  202. package/host-builder/data/examples/hosted-sandbox.ts +48 -0
  203. package/host-builder/data/examples/instruction-injection.ts +127 -0
  204. package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
  205. package/host-builder/data/examples/long-term-memory.ts +158 -0
  206. package/host-builder/data/examples/manifest.ts +112 -0
  207. package/host-builder/data/examples/mcp-server.ts +48 -0
  208. package/host-builder/data/examples/mcp-trust.ts +173 -0
  209. package/host-builder/data/examples/memory-and-wiki.ts +315 -0
  210. package/host-builder/data/examples/memory-lifecycle.ts +302 -0
  211. package/host-builder/data/examples/memory-system.ts +255 -0
  212. package/host-builder/data/examples/messaging-agent.ts +70 -0
  213. package/host-builder/data/examples/minimal-host-app.ts +41 -0
  214. package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
  215. package/host-builder/data/examples/model-router.ts +106 -0
  216. package/host-builder/data/examples/obscura.ts +48 -0
  217. package/host-builder/data/examples/observability.ts +116 -0
  218. package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
  219. package/host-builder/data/examples/openai-compatible.ts +70 -0
  220. package/host-builder/data/examples/package-skills.ts +85 -0
  221. package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
  222. package/host-builder/data/examples/provider-registration.ts +29 -0
  223. package/host-builder/data/examples/provider-resolver.ts +39 -0
  224. package/host-builder/data/examples/rag.ts +40 -0
  225. package/host-builder/data/examples/remote-agent-server.ts +45 -0
  226. package/host-builder/data/examples/remote-agent.ts +124 -0
  227. package/host-builder/data/examples/research-ledger.ts +79 -0
  228. package/host-builder/data/examples/revocation-propagation.ts +287 -0
  229. package/host-builder/data/examples/run-feedback.ts +93 -0
  230. package/host-builder/data/examples/scanned-document-rag.ts +48 -0
  231. package/host-builder/data/examples/sdk-basics.ts +21 -0
  232. package/host-builder/data/examples/secure-agent.ts +55 -0
  233. package/host-builder/data/examples/semantic-memory.ts +52 -0
  234. package/host-builder/data/examples/serve-tools.ts +495 -0
  235. package/host-builder/data/examples/session-memory.ts +318 -0
  236. package/host-builder/data/examples/session-search.ts +131 -0
  237. package/host-builder/data/examples/session.ts +52 -0
  238. package/host-builder/data/examples/side-call.ts +68 -0
  239. package/host-builder/data/examples/signal-agent.ts +9 -0
  240. package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
  241. package/host-builder/data/examples/skills.ts +19 -0
  242. package/host-builder/data/examples/sqlite-resume.ts +147 -0
  243. package/host-builder/data/examples/system-project-prompts.ts +74 -0
  244. package/host-builder/data/examples/system-prompts.ts +19 -0
  245. package/host-builder/data/examples/telegram-agent.ts +30 -0
  246. package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
  247. package/host-builder/data/examples/tools.ts +29 -0
  248. package/host-builder/data/examples/validator.ts +67 -0
  249. package/host-builder/data/examples/web-no-key.ts +85 -0
  250. package/host-builder/data/examples/web-research.ts +35 -0
  251. package/host-builder/data/examples/workflow-event-sink.ts +114 -0
  252. package/host-builder/data/examples/workflow-loop.ts +93 -0
  253. package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
  254. package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
  255. package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
  256. package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
  257. package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
  258. package/host-builder/data/examples.json +130 -0
  259. package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
  260. package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
  261. package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
  262. package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
  263. package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
  264. package/host-builder/skills/prism-host-builder/references/security.md +52 -0
  265. package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
  266. package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
  267. package/host-builder/src/check/child.ts +108 -0
  268. package/host-builder/src/check/conformance.ts +13 -0
  269. package/host-builder/src/check/inspect.ts +20 -0
  270. package/host-builder/src/check/manifest.ts +23 -0
  271. package/host-builder/src/check/runner.ts +181 -0
  272. package/host-builder/src/check/targets.ts +65 -0
  273. package/host-builder/src/errors.ts +35 -0
  274. package/host-builder/src/index.ts +25 -0
  275. package/host-builder/src/indexes.ts +145 -0
  276. package/host-builder/src/install/install.ts +400 -0
  277. package/host-builder/src/install/targets.ts +50 -0
  278. package/host-builder/src/lookup/api.ts +127 -0
  279. package/host-builder/src/lookup/bound.ts +38 -0
  280. package/host-builder/src/lookup/docs.ts +238 -0
  281. package/host-builder/src/lookup/errors.ts +92 -0
  282. package/host-builder/src/lookup/examples.ts +117 -0
  283. package/host-builder/src/lookup/text.ts +60 -0
  284. package/host-builder/src/server.ts +300 -0
  285. package/host-builder/src/version.ts +38 -0
  286. package/mcp-server/README.md +219 -0
  287. package/mcp-server/src/bounds.ts +23 -0
  288. package/mcp-server/src/host.ts +31 -0
  289. package/mcp-server/src/index.ts +27 -0
  290. package/mcp-server/src/serve-tools.ts +408 -0
  291. package/mcp-server/src/serve.ts +329 -0
  292. package/mcp-server/src/server.ts +331 -0
  293. package/mcp-server/src/session-map.ts +47 -0
  294. package/mcp-server/src/skill-resources.ts +85 -0
  295. package/mcp-server/src/types.ts +215 -0
  296. package/package.json +130 -4
  297. package/remote/README.md +244 -0
  298. package/remote/src/attribution.ts +22 -0
  299. package/remote/src/auth.ts +30 -0
  300. package/remote/src/bun-module.d.ts +34 -0
  301. package/remote/src/channel.ts +86 -0
  302. package/remote/src/connect.ts +212 -0
  303. package/remote/src/dispatcher.ts +282 -0
  304. package/remote/src/errors.ts +59 -0
  305. package/remote/src/host-ui.ts +152 -0
  306. package/remote/src/http-gate.ts +43 -0
  307. package/remote/src/index.ts +53 -0
  308. package/remote/src/jsonl.ts +69 -0
  309. package/remote/src/limits.ts +43 -0
  310. package/remote/src/mirror.ts +90 -0
  311. package/remote/src/pending.ts +22 -0
  312. package/remote/src/protocol.ts +107 -0
  313. package/remote/src/serve.ts +560 -0
  314. package/remote/src/session-proxy.ts +219 -0
  315. package/remote/src/sse.ts +38 -0
  316. package/remote/src/stdio-client.ts +41 -0
  317. package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
  318. package/remote/src/testing.ts +230 -0
  319. package/remote/src/transport.ts +139 -0
  320. package/remote/src/transports/client.ts +126 -0
  321. package/remote/src/transports/network.ts +268 -0
  322. package/remote/src/wire.ts +244 -0
@@ -0,0 +1,843 @@
1
+ # @arnilo/prism-hosts/evals
2
+
3
+ Host library providing evaluation, datasets, scorers, judges, experiments, and multi-turn scenarios for Prism agents. It operates over public `Agent` and `Session` surfaces and does not construct an agent directly.
4
+
5
+ Imports into host libraries are strictly governed by [`scripts/host-surface-allowlist.json`](../../../scripts/host-surface-allowlist.json).
6
+
7
+ ## Evaluation and experiment storage
8
+
9
+ Import `EvaluationRecord`, `EvaluationStatus`, `EvaluationQuery`, `EvaluationStore`,
10
+ `ExperimentReportRecord`, `ExperimentReportQuery`, and `ExperimentReportStore` from `@arnilo/prism`.
11
+ The memory implementations live in `@arnilo/prism-extensions/store-codecs`; evals no longer exports the
12
+ moved types or `createMemoryEvaluationStore`.
13
+
14
+ ```ts
15
+ import { createMemoryEvaluationStore, createMemoryExperimentReportStore } from "@arnilo/prism-extensions/store-codecs";
16
+ import { runExperiment } from "@arnilo/prism-hosts/evals";
17
+
18
+ const ownership = { tenantId: "tenant", userId: "user" };
19
+ const store = createMemoryEvaluationStore();
20
+ const experimentStore = createMemoryExperimentReportStore();
21
+ const report = await runExperiment({ agent, dataset, scorers, ownership, store, experimentStore });
22
+ const baseline = await experimentStore.latest({ ...ownership, datasetId: dataset.id,
23
+ manifestMatch: { runtimeRevision: "release-1" } });
24
+ ```
25
+
26
+ `runExperiment` awaits **one summary write per completed experiment**, including failed or aborted
27
+ experiments that produce a report. Store failures reject the call. `toExperimentReportRecord(report,
28
+ ownership?)` builds the same immutable summary: dataset identity/hash, manifest, aggregate statistics,
29
+ and per-item scorer means over scored records. It excludes item input/output, reasons, trial content,
30
+ and record metadata. Summaries exceeding **1 MiB** throw `ERR_PRISM_EVAL_REPORT_BOUNDS`.
31
+ `metadata` on the summary is reserved for explicit store callers; the converter never copies it.
32
+
33
+ Queries match tenant, account, and user exactly, including absent fields. An unscoped query reads
34
+ only unowned records. Reuse the full ownership scope on writes and queries. Pagination defaults to
35
+ 100 records, caps at 1,000, and returns a cursor for the last returned record. `latest` selects the
36
+ newest dataset/owner match, breaking timestamp ties by id; `manifestMatch` matches each supplied
37
+ manifest field exactly. These optional capabilities are declared on `ProductionPersistenceStore`;
38
+ SQL adapter implementations follow in plan 201 Task 3. Stored item means do not retain trial labels
39
+ or tags: reconstructing a full report for `compareExperiments` needs host-supplied report context.
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ bun add @arnilo/prism-hosts
45
+ ```
46
+
47
+ `@arnilo/prism` is a required peer. `@arnilo/prism-extensions/observability` is an **optional** peer: it is needed only to project timelines (`timeline: "metadata" | "redacted_io"`). Text-only scoring and experiments never load it, and asking for a timeline without installing it throws `EvalError` `ERR_PRISM_EVAL_TIMELINE_UNAVAILABLE` naming the package.
48
+
49
+ ```jsonc
50
+ { "@arnilo/prism-hosts": "^0.13.0", "@arnilo/prism-extensions": "^0.13.0" }
51
+ ```
52
+
53
+ ## Evaluation telemetry
54
+
55
+ `scoreRun`, `scoreRunLive`, `runExperiment`, and `runScenario` accept an optional
56
+ `telemetry: EvaluationTelemetrySink`. It receives one call per stored/returned record after
57
+ redaction, including scored, failed, sampled-out, per-step, and simulator-failure skips.
58
+ No model calls are added. With a store, a failed append propagates before telemetry is called.
59
+
60
+ ```ts
61
+ import type { EvaluationTelemetry } from "@arnilo/prism-extensions/observability";
62
+
63
+ // instrumentation is a host-held createOpenTelemetryInstrumentation() instance.
64
+ const telemetry = { handleEvaluation: (e: EvaluationTelemetry) => instrumentation.handleEvaluation(e) };
65
+ await scoreRunLive(result, { scorers, telemetry, onError: (error) => console.error(error) });
66
+ ```
67
+
68
+ The payload contains only `runId`, scorer id as `name`, `status`, optional `score`, and
69
+ `hasReason`; it never includes reason/error text, input/output, metadata, or ownership.
70
+ A simulator failure before any run uses the evaluation record id as its standalone
71
+ correlation id. Sink exceptions leave records unchanged: live scoring reports each through
72
+ `onError`; direct scoring, experiments, and scenarios ignore them. The sink is synchronous;
73
+ async exporters must handle their own failures. Only the payload type references the optional
74
+ observability peer; supplying a structural sink does not load or require it at runtime.
75
+ The package definition does not expose its internal instrumentation instance.
76
+
77
+ ## Online evaluation
78
+
79
+ `scoreRunLive`, `scoreRun`, and `runExperiment` accept `sampling: EvaluationSampling` (replacing the retired `sampleRate` option) to stratify and weight online or sampled evaluations:
80
+
81
+ ```ts
82
+ import { estimateOnline, scoreRunLive } from "@arnilo/prism-hosts/evals";
83
+
84
+ const records = await scoreRunLive(result, {
85
+ scorers: [citationScorer],
86
+ sampling: {
87
+ rate: 0.1,
88
+ strata: (run) => run.status,
89
+ rates: { completed: 0.05 },
90
+ always: (run) => run.status !== "completed",
91
+ },
92
+ seed: 42,
93
+ store,
94
+ ownership: { tenantId: "acme" },
95
+ });
96
+
97
+ const estimate = estimateOnline(records, { scorerId: "contains-citation", seed: 42 });
98
+ // { scorerId, n, effectiveN, mean, ci95: { low, high }, byStratum: { ... } }
99
+ ```
100
+
101
+ - `rate` is the default per-run inclusion probability in `[0, 1]` (defaults to `1`).
102
+ - `strata(result) => string` classifies the run once per `scoreRun` call (`"default"` when omitted) and makes no extra model calls.
103
+ - `rates: Record<stratum, number>` overrides the inclusion probability for matching strata in `[0, 1]`.
104
+ - `always(result) => boolean` forces inclusion probability `1` when true (for example, failed runs or runs with denied tools), overriding `rate` and `rates[stratum]`.
105
+ - Probability `0` for a run or stratum records nothing (`[]` returned, no store append, no telemetry emitted).
106
+ - With a Positive probability, each emitted record stores `metadata.sampling = { stratum, probability }`. Scorer-returned `metadata.sampling` cannot overwrite this record metadata. When `sampling` is configured and a run is not selected by the random draw, `scoreRun` records a `skipped` record with `reason: "sampled out (`<probability>`)"` and the same `metadata.sampling`.
107
+ - When `seed` is provided without a custom `random`, `scoreRun` derives a deterministic per-run stream via `mulberry32(hash32(seed, experimentId, datasetId, itemId, runId, sessionId))`.
108
+ - `estimateOnline(records, { scorerId, seed = 0, resamples = 2000, confidence = 0.95 })` filters to `status === "scored"` records for `scorerId` and computes the Horvitz–Thompson / Hájek ratio weighted mean `(Σ y_i / π_i) / (Σ 1 / π_i)`, Kish's effective sample size `(Σ w_i)² / Σ w_i²` (`w_i = 1 / π_i`), per-stratum `{ n, mean, weightSum }`, and a percentile bootstrap confidence interval (`ci95`) via `bootstrapInterval` (`undefined` when `n < 2`). Every scored record for `scorerId` must carry valid `metadata.sampling` with a non-empty `stratum` and `probability` in `(0, 1]`; unweighted or malformed records fail closed with `EvalError` (`ERR_PRISM_EVAL_STATS`).
109
+
110
+ ## Statistics
111
+
112
+ The statistics helpers are standalone pure TypeScript utilities with no runtime dependency.
113
+
114
+ ```ts
115
+ import { bootstrapInterval, passAtK, wilsonInterval } from "@arnilo/prism-hosts/evals";
116
+
117
+ wilsonInterval(18, 20); // { low: 0.698966…, high: 0.972134… }
118
+ passAtK(10, 3, 5); // 0.916666…
119
+ bootstrapInterval([0, 0, 1, 1], {
120
+ statistic: (xs) => xs.reduce((sum, x) => sum + x / xs.length, 0),
121
+ clusterIds: ["item-a", "item-a", "item-b", "item-b"],
122
+ seed: 7,
123
+ }); // { low: 0, high: 1 }
124
+ ```
125
+
126
+ In the formulas below, `N` is the number of records, `G` the number of clusters,
127
+ `q` the discordant-pair rate, `d` the absolute paired effect, `Φ` the standard normal CDF,
128
+ and `z = Φ⁻¹(1−α/2)`.
129
+
130
+ | Function | Formula and use |
131
+ | --- | --- |
132
+ | `wilsonInterval(successes, n, confidence = .95)` | `(p + z²/(2n) ± z√(p(1−p)/n + z²/(4n²))) / (1 + z²/n)`. Use for independent binary outcomes, including zero or all successes. [Wilson (1927)](https://doi.org/10.1080/01621459.1927.10502953). |
133
+ | `clusteredStandardError(values, clusterIds)` | CR1: `√(G/(G−1) × Σ_g (Σ_i∈g (x_i−mean))² / N²)`. Use when trials share an item; requires at least two distinct clusters. Singleton clusters give the usual sample SE. [Miller (2024), §2.2 and Appendix A](https://arxiv.org/abs/2411.00640). |
134
+ | `bootstrapInterval(values, { statistic, seed, resamples = 2000, confidence = .95, clusterIds? })` | Percentile interval `[Q(α/2), Q(1−α/2)]` with linear quantile interpolation. Draws `N` records or `G` entire clusters with replacement. Unequal clusters keep their sizes, so record means remain record-weighted. [Efron & Tibshirani (1993)](https://doi.org/10.1201/9780429246593). |
135
+ | `mcnemarExact(aOnly, bOnly)` | `min(1, 2 P(Binomial(aOnly+bOnly, .5) ≤ min(aOnly,bOnly)))`. Two-sided exact test for discordant binary pairs; returns 1 with no discordance. [McNemar (1947)](https://doi.org/10.1007/BF02295996). |
136
+ | `pairedPermutationTest(differences, { seed, resamples = 10000 })` | `P(abs(Σ sign_i d_i) ≥ abs(Σ d_i))`. Two-sided paired sign-flips; enumerate all signs when `n ≤ 16`, otherwise use Monte Carlo `(extreme+1)/(resamples+1)`. Fisher (1935), *The Design of Experiments*. |
137
+ | `benjaminiHochberg(pValues)` | Sorted `q_(i) = min_{j≥i}(1, m p_(j)/j)` returned in input order. Adjust a family of p-values for false discovery rate under independence or appropriate positive dependence. [Benjamini & Hochberg (1995)](https://doi.org/10.1111/j.2517-6161.1995.tb02031.x). |
138
+ | `passAtK(n, c, k)` | `1 − C(n−c,k)/C(n,k)` via a stable product: probability at least one of `k` draws succeeds. [Chen et al. (2021), §2.1](https://arxiv.org/abs/2107.03374). |
139
+ | `passHatK(n, c, k)` | `C(c,k)/C(n,k)`: probability all `k` draws without replacement succeed. [Yao et al. (2024), τ-bench §3](https://arxiv.org/abs/2406.12045). |
140
+ | `pairedProportionPower({ discordantRate, effect, n, alpha = .05 })` | `Φ((−z√q−√n d)/√(q−d²)) + Φ((√n d−z√q)/√(q−d²))`. Two-sided normal approximation to McNemar, without continuity correction. [Connor (1987)](https://doi.org/10.2307/2531961). |
141
+ | `minimumDetectableEffect({ discordantRate, n, alpha = .05, power = .8 })` | Inverts the same power formula over `[0, q]`; throws if target power is unattainable. Use to size the smallest detectable paired effect. |
142
+
143
+ Both interval functions return `{ low, high }`. Samples must be nonempty and finite; counts must be
144
+ safe integers (`n ≥ 1`, `0 ≤ c ≤ n`, `1 ≤ k ≤ n`); confidence and alpha lie strictly in `(0, 1)`.
145
+ Power calculations require `0 < q ≤ 1`, `abs(effect) ≤ q`, and `alpha < power < 1` for inversion.
146
+ Cluster ids are nonempty strings or finite numbers, one per record. Seeds are required safe integers,
147
+ mapped to the existing `mulberry32` 32-bit stream; repeated calls with the same inputs reproduce results.
148
+ Invalid input, a throwing statistic, or a non-finite statistic result throws `EvalError` with
149
+ `code: "ERR_PRISM_EVAL_STATS"`.
150
+
151
+ Resamples must be integers in `[1, HARD_STATS_RESAMPLES]` (`100_000`), including when permutation
152
+ enumeration is exact. Bootstrap costs `O(resamples × N)` in expectation for a linear-time statistic,
153
+ plus sorting `resamples` statistics; unequal cluster sizes can produce longer individual resamples.
154
+ Monte Carlo permutation costs `O(resamples × N)`; exact permutation costs `O(2^N × N)` for `N ≤ 16`.
155
+ The test suite allows 1 second for the 1,000-item / 2,000-resample bootstrap (4× the 250 ms target).
156
+ Normal quantiles and the power CDF use rational approximations; CDF absolute error is below `7.5e-8`.
157
+
158
+ ## Datasets
159
+
160
+ `defineDataset` returns a deeply frozen JSON snapshot and computes one SHA-256 over its items (at most 10,000). `contentHash` is `sha256:` plus 64 lowercase hex digits. Object keys are sorted, array/item order is preserved, object properties with `undefined` are dropped, and undefined array entries become `null`, as in JSON. Functions, cycles, non-finite numbers, bigint, symbols, and non-JSON objects fail with `EvalDatasetError` (`not serializable`). Dataset id, version, metadata, and canary are outside the item hash; item metadata is included.
161
+
162
+ ```ts
163
+ const dataset = defineDataset({ id: "support", version: "3", canary: "prism-eval-canary-7f3c", items: [
164
+ { id: "q1", input: "Where is my order?", expected: "tracking", split: "heldout",
165
+ tags: ["tracking"], label: { source: "human", adjudicated: true, by: "reviewer-1" } },
166
+ ] });
167
+ const report = await runExperiment({ agent, dataset, scorers, split: "heldout", allowHeldout: true });
168
+ validateReleaseEvalManifest({ ...manifest, datasetContentHash: dataset.contentHash }, report);
169
+ ```
170
+
171
+ `split` is `dev`, `test`, or `heldout`; `runExperiment.split` accepts one or an array. Without a filter all items are selected, including unassigned items. An explicit filter omits unassigned items. Any selected heldout item requires `allowHeldout: true` before any agent runs; otherwise `EvalDatasetError` has code `ERR_PRISM_EVAL_HELDOUT`. Keep heldout results away from prompt tuning; the opt-in controls execution, not access to dataset content.
172
+
173
+ Items may have up to 16 tags of at most 64 characters each, and `label: { source, adjudicated?, by? }`, where source is `human`, `model`, `curated`, or `synthetic`. `aggregate.byTag[tag].scorers` repeats the full per-scorer statistics for that tag; duplicate tags count an item once and untagged items contribute only to the overall aggregate. `compareExperiments(a, b, { byTag: true })` returns per-tag comparisons and applies BH correction across all tag/scorer tests, separately from the overall scorer family. Tags with fewer than two paired items are omitted. Comparisons reject different dataset content hashes, including when only one report carries a hash; external score-only reports with neither hash retain their existing behavior.
174
+
175
+ Reports record `datasetContentHash` and the requested `split`. `validateEvalManifest` still accepts the two revision fields; `validateReleaseEvalManifest(manifest, report?)` additionally requires a valid `datasetContentHash` and, with a report, an exact hash match. Rubric hashes share the sorted-key canonical JSON helper; hashes created before this change must be regenerated.
176
+
177
+ An optional canary (at most 128 characters) appears in `dataset.canary`, `dataset.metadata.canary`, and the serialized report. Use a unique inert marker and search suspected training corpora, for example `rg --fixed-strings 'prism-eval-canary-7f3c' path/to/corpus`. A hit can reveal contamination; no hit does not prove its absence. Report serialization still applies configured secret redaction and byte limits.
178
+
179
+ ## Scorers
180
+
181
+ Custom scorers use `defineScorer`; the built-ins cover the common trajectory checks.
182
+
183
+ | Scorer | `requires` | `invariant` | Checks |
184
+ | --- | --- | --- | --- |
185
+ | `createToolCallMatchScorer` | `timeline` | with `deny` or `invariant: true` | expected tool calls present, in order or unordered |
186
+ | `createApprovalBeforeEffectScorer({ tools })` | `timeline` | yes | an effect passes only with an `approved` `hitl` step for the same `toolCallId` before it |
187
+ | `createGuardrailPackScorer({ forbidTools })` | `timeline` | yes | no guardrail-pack denial for the forbidden tools |
188
+ | `createSchemaScorer` | `timeline` | no | final output parses against a JSON schema |
189
+ | `createErrorClassScorer()` | `timeline` | with `deny` | denied error classes never appear (and scores `0` with no evidence) |
190
+ | `createNoLoopScorer` | `timeline` | yes | no repeated identical tool call |
191
+ | `createCitationIntegrityScorer` | `environment` | yes | citations resolve against a live source |
192
+ | `createStateMatchScorer` | `environment` | with `invariant: true` | final JSON state equals or contains a goal state |
193
+ | ERP invariant scorers | — | yes | amount/approval/effect invariants on the result text |
194
+ | `createModelJudge` | — | no | low-level host judge adapter; see `createRubricJudge` for rubric judging |
195
+ | `createRubricJudge` | timeline when `include: "answer+timeline"` | no | labeled rubric judging with a tool-less agent |
196
+
197
+ `requires` is checked once by `scoreRun`, `runExperiment`, and `runScenario` **before** any agent run: a scorer that needs a timeline and is handed `timeline: "off"` throws `ERR_PRISM_EVAL_TIMELINE_REQUIRED` (`_TRACE_REQUIRED`, `_ENVIRONMENT_REQUIRED` likewise) instead of scoring a silent zero.
198
+
199
+ `createStateMatchScorer({ expected, select?, mode: "exact" | "subset", ignore?, invariant? })` compares final JSON state supplied by `toEnvironment` (or `scoreRun.environment`). `expected` is a value or `(item) => item?.expected`; `select` projects the environment before comparison. Exact mode checks all keys; subset mode checks every expected key recursively and allows extra actual keys. Arrays compare by index, so a subset array matches a prefix, preserving order and duplicates. `ignore` contains JSON pointers relative to the selected state (including escaped `~0` and `~1`); ignored array slots do not shift other indices, and the empty pointer ignores the whole state. Neither input is mutated.
200
+
201
+ Both compared states pass through `ScorerInput.redactor` before comparison, so differences hidden by redaction are intentionally equivalent. Each selected actual/expected JSON snapshot is capped at 1 MiB before and after redaction; exceeding it produces a failed record with `ERR_PRISM_EVAL_STATE_BOUNDS`. Comparison is linear in state size. Mismatches score 0 with at most 32 `metadata.diff` entries `{ path, expected, actual }`; paths are JSON pointers, missing values are `undefined`, and values over 256 serialized UTF-8 bytes become truncated strings. The diff also passes through normal record redaction. Matches score 1; `invariant: true` makes this a hard gate.
202
+
203
+ `createApprovalBeforeEffectScorer({ tools })` treats approval as evidence, not intent. `tools` (normally `agent.tools`) selects the calls whose `effects` include `write`, `execute`, or `external`; a tool step it does not declare is assumed effectful. An effect passes only when an `approved` `hitl` step for the same tool call precedes it — a denied or still-suspended decision fails the call, and a `succeeded` guardrail step never stands in for a human decision.
204
+
205
+ ```ts
206
+ const records = await scoreRun({ result, scorers: [createToolCallMatchScorer({ mode: "unordered", expected: ["search"] })], timeline: "metadata", injectedTimeline: timeline });
207
+ ```
208
+
209
+ - `timeline: "metadata"` needs a `traceResolver` in `scoreRun`; `runExperiment` and `runScenario` project while running, so they only need the mode.
210
+ - `forEach: "tool" | "workflow_node"` scores each matching step separately and passes it as `ScorerInput.step`, recording `stepId`. With no matching step it records one `skipped` record per scorer with reason `no matching steps` — absence of steps never reads as absence of failures.
211
+
212
+ ## Hard invariants
213
+
214
+ A scorer declares itself a safety gate with `invariant: true`. `scoreRun` stamps `metadata.invariant` on every record of such a scorer — including a `failed` record from a scorer that threw — and `runExperiment` reports `aggregate.invariantsPassed: false` unless all of them scored `1`.
215
+
216
+ ```ts
217
+ const noForbiddenTool = defineScorer({
218
+ id: "no_drop_database",
219
+ invariant: true,
220
+ requires: ["timeline"],
221
+ score: ({ timeline }) => ({ score: timeline?.steps.some((step) => step.name === "drop_database") ? 0 : 1 }),
222
+ });
223
+
224
+ assertEvaluationThreshold(report, { requireInvariants: true }); // fails when no invariant scorer ran at all
225
+ ```
226
+
227
+ - Only the declaration counts. A `metadata.invariant` returned from `score` is stripped, so a scorer cannot promote itself at runtime.
228
+ - A non-invariant failure (a judge timeout, say) is a normal failure: `maximumFailures` governs it and it does not make `invariantsPassed` false.
229
+ - `requireInvariants: true` additionally fails when the report has no invariant records, so a threshold that expects a safety gate cannot pass because the gate was never configured.
230
+
231
+ ## Experiments
232
+
233
+ `runExperiment({ agent, dataset, scorers, trials })` runs a dataset over an agent with bounded concurrency and per-scorer statistics.
234
+
235
+ `aggregate.scorers[id]` contains `{ items, records, mean, passRate, passAtK?, passHatK?, passKCounts?, se?, ci95?, method }`. Only scored numeric records enter statistics; failed and skipped records retain their separate counts. Records are grouped by item: `mean` averages item means, so repeated trials and `forEach` steps cannot outweigh another item. `aggregate.macroMean` is the unweighted mean of scorer means and is absent when nothing scored.
236
+
237
+ `se` uses CR1 over records clustered by item. With unequal record counts this estimates uncertainty of the record-weighted mean; the reported `mean` and bootstrap interval remain item-weighted. A binary scorer with exactly one record per item uses a Wilson 95% interval (`{ low, high }`). Otherwise the report bootstraps item means (equivalent to drawing whole items with equal weight), once per scorer, with 2,000 resamples and `seed` (default `0`). This costs O(2,000 × items) per scorer plus sorting. With fewer than two scored items, `se` and `ci95` are absent and `method` is `"single_item"`; otherwise it is `"wilson"` or `"cluster_bootstrap"`. Trial metadata contains only `count`, optional `seed`, and `sampleCount`.
238
+
239
+ `minimumMacroMean` and `minimumByScorer` are point-estimate gates; they do not test statistical significance.
240
+
241
+ ```ts
242
+ const report = await runExperiment({ agent, dataset, scorers, trials: 3, seed: 7, concurrency: 4, timeline: "metadata" });
243
+ assertEvaluationThreshold(report, { minimumMacroMean: 0.8, requireInvariants: true });
244
+ ```
245
+
246
+ - A `seed` gives each `(itemId, trialIndex)` its own stream — `mulberry32(hash32(seed, itemId, trialIndex))` — so sampled trials are identical at any concurrency. An explicit `random` instead shares one stream and is order-dependent.
247
+ A scorer's `passThreshold` is a finite number in `[0, 1]`, defaulting to `1`. A scored record passes when `score >= passThreshold`. `passRate` averages each item's fraction of passing scored trials, giving each item equal weight. Failed/skipped records are excluded, and an item with no scored trials contributes no pass fraction.
248
+
249
+ With `trials > 1`, each scorer also reports numeric `passAtK[k]` (at least one success) and `passHatK[k]` (all succeed) for `k = 1..trials`, averaged over items with at least `k` scored trials. These use the without-replacement estimators in Statistics above, extended incrementally across k. `passKCounts[k]` gives `{ items, excludedItems }`, counting excluded items against the full dataset, including items with no scored trials. A k with no eligible items has counts but no estimate; a scorer with no scored records is absent entirely. Exclusions can bias the result if missing trials depend on outcome; inspect the counts and failure total. Reliability summaries add O(items × trials) work. Setting `trials: k` multiplies agent runs by k (and usually cost).
250
+
251
+ ```ts
252
+ const success = defineScorer({ id: "task_success", passThreshold: 1, score: checkTask });
253
+ // Run with scorers: [success], trials: 4, then require reliable repeated success:
254
+ assertEvaluationThreshold(report, { minimumPassHatK: { task_success: { k: 4, minimum: 0.8 } } });
255
+ ```
256
+
257
+ `minimumPassHatK` validates positive integer k and a minimum in `[0, 1]`; it fails when the scorer or k estimate is absent, including single-trial reports. With one item passing 2 of 4 trials, `passRate` is 0.5, `passAtK[4]` is 1, and `passHatK[4]` is 0. Hard invariants still require every record to score exactly 1, regardless of `passThreshold`.
258
+
259
+ - Aborting keeps the work that finished: finished items retain their results and evaluations, unstarted items carry the abort reason, `status` is `aborted`, and `aggregate` counts only the finished items.
260
+ - `hooks` and `slots` are passed to an agent factory exactly as `runScenario` does; combining them with an `Agent` instance throws `ERR_PRISM_EVAL_EXPERIMENT`.
261
+
262
+ ## Usage, cost, and latency
263
+
264
+ Every `runExperiment` item has `trials: [{ usage?, durationMs?, status, costComplete }]`, including single-trial experiments. `usage` preserves `RunResult.usage`; `result` still holds the last available run. Duration measures only `session.run` with a monotonic clock, including thrown/aborted runs, and excludes agent creation, input conversion, scoring, and timeline drain. Unstarted trials carry `status: "aborted"`, no duration/usage, and `costComplete: false`.
265
+
266
+ `aggregate.cost` sums observed `inputTokens`, `outputTokens`, `totalTokens`, `cacheReadTokens`, and `cacheWriteTokens`. Absent counts stay absent; available counts can be partial, and `estimated: true` propagates if any trial used estimates. `meanPerItem` divides these totals by the dataset item count, including all trials per item. `meanPerItem.durationMs` likewise divides summed measured run time by item count; it is work per item, not concurrent experiment wall time. `durationMs: { p50, p95 }` uses nearest-rank percentiles over measured trial times and is absent if no run was timed.
267
+
268
+ Billing is stricter: `cost` (and its per-item mean) is present only when **every** trial has finite, nonnegative, non-estimated cost, every provider attempt has complete pricing evidence, and all currencies match. Missing currency matches only another missing currency; no conversion or currency assumption is made. The collector observes turn and terminal run events even with timeline off, using constant accounting state and making no extra provider calls. Unpriced turns, missing/truncated evidence, mixed currencies, unstarted trials, and empty runs leave the total absent and `costComplete: false`. A trial's raw `usage.cost` can be partial; inspect its `costComplete` before treating it as a bill. Scorer/judge calls and agent setup costs are outside agent-run accounting.
269
+
270
+ ```ts
271
+ import { paretoFrontier } from "@arnilo/prism-hosts/evals";
272
+
273
+ const frontier = paretoFrontier(reports, {
274
+ quality: r => r.aggregate.macroMean ?? 0,
275
+ cost: r => r.aggregate.cost?.cost ?? Infinity,
276
+ });
277
+ ```
278
+
279
+ `paretoFrontier` maximizes quality and minimizes cost. A point is dominated when another is at least as good on both axes and strictly better on either. It returns the original report objects in ascending cost order, retaining identical points in input order and leaving the input untouched. Quality must be finite; cost must be finite or positive `Infinity` (for unknown billing), otherwise it throws `ERR_PRISM_EVAL_STATS`. Unknown cost is not a free run and can remain on the frontier if its quality is higher; filter incomplete reports first if you need only known bills. Compare the same quality metric and currency across reports; the callbacks do not convert currencies. Selection costs O(reports × log(reports)) and runs no agents.
280
+
281
+ ## Multi-turn scenarios
282
+
283
+ `runScenario(scenario, agentFactory, options)` runs conversational clarification, refusal, and multi-turn workflows over a host-built agent.
284
+
285
+ ```ts
286
+ const result = await runScenario(
287
+ { turns: ["Transfer 50 USD", { user: "Yes, confirm", assertReply: (text) => text.includes("denied") }], maxTurns: 4 },
288
+ (extra) => createAgent({ model: { provider: "mock", model: "demo" }, ...extra }),
289
+ { scorers, timeline: "metadata", scoreTurns: "each" },
290
+ );
291
+ ```
292
+
293
+ - `turns` is bounded, not truncated: more turns than `maxTurns` (default 8, hard cap 32) throws `ERR_PRISM_EVAL_SCENARIO_BOUNDS` before the agent is built, so a cut-off scenario cannot pass for the wrong reason.
294
+ - `status` is `succeeded`, `failed`, or `aborted` (a host signal, or a final run the agent aborted). A throwing `assertReply` stops the scenario with `failed` and `ERR_PRISM_EVAL_SCENARIO_ASSERTION` naming the turn.
295
+ - `scoreTurns: "each"` scores every turn on that turn's result and timeline slice, recording `metadata.turnIndex`; the default `"last"` scores only the final turn. `"each"` multiplies scorer calls (and judge cost) by the turn count.
296
+
297
+ Scenario inputs also work in ordinary datasets, including mixed single-turn and
298
+ multi-turn items:
299
+
300
+ ```ts
301
+ const dataset = defineDataset({ id: "refunds", items: [{
302
+ id: "r1", input: { kind: "scenario", turns: ["I want a refund", "Order 42"], scoreTurns: "each" },
303
+ }] });
304
+ const report = await runExperiment({ agent: factory, dataset, scorers, trials: 3, timeline: "metadata" });
305
+ ```
306
+
307
+ Each trial opens a fresh session, even when `agent` is an existing instance. The
308
+ factory receives the experiment's `hooks` and `slots`; ownership, cancellation,
309
+ redaction, and run options apply on every turn. `toEnvironment` runs after the
310
+ last turn by default, or after each turn with `scoreTurns: "each"`. Stored records
311
+ carry `itemId`, `metadata.trialIndex`, and, when scoring each turn,
312
+ `metadata.turnIndex`. Statistics and storage use the ordinary experiment pipeline;
313
+ trial usage and duration include all scenario runs. Cost equals running those
314
+ turns individually, with no extra model calls. A non-completed run ends the loop.
315
+
316
+ Dataset scenarios must be JSON: use strings or `{ user: message }` turns;
317
+ function-valued `assertReply` remains available only in standalone scenarios.
318
+ `ScenarioInput` accepts exactly one of `turns` or `user`. Invalid turn bounds,
319
+ scoring modes, or both/neither input sources fail before an agent is constructed.
320
+ The existing standalone `runScenario` signatures and exports remain available.
321
+
322
+ ## Simulated users
323
+
324
+ ```ts
325
+ const user = createUserSimulator({
326
+ agent: simulatorAgent, persona: "terse customer",
327
+ goal: "Get a refund for order 42 to the original card.",
328
+ });
329
+ const result = await runScenario({ agent, user, scorers, secrets: [customerSecret] });
330
+ // Or: defineDataset({ id: "refunds", items: [{ id: "r1", input: { kind: "scenario", user } }] })
331
+ console.log(result.simulation); // { turns: [{ user, assistant }], stopReason, simulatorModel }
332
+ ```
333
+
334
+ Simulation is opt-in: one extra simulator model call per proposed user turn,
335
+ including a call that returns the stop token. `maxTurns` defaults to **8** (hard
336
+ cap 32); `stop` defaults to `"###DONE###"` and must match the trimmed reply exactly.
337
+ An explicit scenario `maxTurns` can lower the simulator's limit. The loop stops
338
+ on the token (`goal_reached`), the limit (`max_turns`), or a non-completed agent
339
+ run (`agent_stopped`). Experiment trial entries also retain `simulation`.
340
+
341
+ Each proposal uses a fresh, closed, tool-less session, one provider attempt, and
342
+ no continuation. The versioned prompt contains only persona, hidden goal, stop
343
+ token, and text conversation: expected answers, environment state, timelines,
344
+ and tool I/O are excluded. The resolved scorer redactor (`redactor` plus
345
+ `secrets`) redacts this data before sending it to the simulator and redacts the
346
+ recorded simulation turns. `timeoutMs` defaults to 30,000 (hard cap 300,000);
347
+ prompts are capped at 1 MiB and replies at 16 KiB. Empty, oversized, failed, or
348
+ timed-out replies fail the scenario with `ERR_PRISM_EVAL_USER_SIMULATOR` and skip
349
+ its scorers with that reason. Per-turn scoring is deferred until simulation
350
+ finishes so simulator failures cannot count against the agent. Existing agent
351
+ failures still receive normal scoring. Simulator tokens/cost are additional to
352
+ the target-agent usage reported by experiment accounting.
353
+
354
+ The simulator specification and model identity are JSON; its host-owned agent
355
+ binding is held outside the hash in a weak map and preserved by `defineDataset`.
356
+ After loading serialized items, rebuild each `user` with
357
+ `createUserSimulator({ ...savedUser, agent: simulatorAgent })` before
358
+ `defineDataset`. Unbound specs fail closed. The host retains responsibility for
359
+ disposing both agents. No credentials or agent object enter dataset JSON.
360
+
361
+ ## Failure injection
362
+
363
+ `failureInjection(options)` builds an `AgentConfig.hooks` value that denies tools via `tool.call` and marks unknown effects via `tool.execute`; `failingStore(store)` wraps a `SessionStore` to fail on the first append. Both exist so a test can prove a host degrades safely without a real outage.
364
+
365
+ ## Curation
366
+
367
+ `datasetFromRuns({ dataset, runIds, sessionIds, store, ownership })` resolves recorded runs from the production store, redacts, maps each run through `toItem`, and appends the results as a new immutable dataset version.
368
+
369
+ ```ts
370
+ const { dataset: next, added, skipped } = await datasetFromRuns({ runIds: ["run_a"], dataset, store, ownership });
371
+ // skipped: [{ id: "run_a", reason: "already in dataset" }]
372
+ ```
373
+
374
+ - Idempotent by run id: every candidate is checked against the existing item ids before any trace is read, so a repeat sweep costs one `Set` lookup per run. A custom `toItem` id that collides with an existing item is caught after mapping and skipped the same way, so one pass cannot add a duplicate either.
375
+ - New items carry `label.source: "human"` when feedback metadata supplied `expected`, otherwise `"curated"`; existing labels, dataset metadata, and canary are preserved.
376
+ - Datasets are immutable versions; an existing item is never replaced — a changed label is a new item id or a new version, the host's choice.
377
+ - When every candidate skips, the input dataset object and its `version` come back unchanged (`added: 0`).
378
+ - Skip reasons: `missing run`, `ownership mismatch`, `empty output`, `host filter` (a `toItem` returning `undefined`), `redaction failed`, and `already in dataset`.
379
+ - Versioning: numeric versions increment (`1` → `2`); a non-numeric label keeps its prefix and counts in a trailing `.N` (`v1` → `v1.1` → `v1.2`, `v1.9` → `v1.10`).
380
+
381
+ ## Thresholds and reports
382
+
383
+ `assertEvaluationThreshold(report, thresholds)` throws `EvalError` `ERR_PRISM_EVAL_THRESHOLD` unless every requested gate holds: `minimumMacroMean`, `maximumFailures`, `minimumByScorer`, `minimumPassHatK`, `minimumLowerBound`, `maximumRegression`, `minimumCandidateWins`, and `requireInvariants` (which also fails when no invariant scorer ran at all). `serializeEvaluationReport` writes the stable JSON form for a CI artifact.
384
+
385
+ ## Errors
386
+
387
+ All failures are `EvalError` subclasses carrying a stable `code`:
388
+
389
+ | Code | Raised when |
390
+ | --- | --- |
391
+ | `ERR_PRISM_EVAL_SCORE` | a scorer returned a non-finite or out-of-range score |
392
+ | `ERR_PRISM_EVAL_HELDOUT` | heldout items selected without `allowHeldout: true` |
393
+ | `ERR_PRISM_EVAL_DATASET` | a dataset manifest, item, or revision pin is invalid |
394
+ | `ERR_PRISM_EVAL_TRACE_REQUIRED` / `_TIMELINE_REQUIRED` / `_ENVIRONMENT_REQUIRED` | a scorer's declared requirement is not available |
395
+ | `ERR_PRISM_EVAL_TIMELINE_UNAVAILABLE` | a timeline was requested but `@arnilo/prism-extensions/observability` is not installed |
396
+ | `ERR_PRISM_EVAL_SCENARIO_BOUNDS` | `maxTurns`/`turns` exceed the bounded scenario contract |
397
+ | `ERR_PRISM_EVAL_SCENARIO_ASSERTION` | a turn's `assertReply` threw |
398
+ | `ERR_PRISM_EVAL_EXPERIMENT` | experiment options cannot work (e.g. `hooks` with an `Agent` instance) |
399
+ | `ERR_PRISM_EVAL_CURATE` | a curated item exceeds the byte cap |
400
+ | `ERR_PRISM_EVAL_JUDGE_PANEL` | invalid panel/model diversity or fewer than half of panel judges succeeded |
401
+ | `ERR_PRISM_EVAL_JUDGE_SELF` | the candidate model identity is missing or equals the judge model without explicit opt-in |
402
+ | `ERR_PRISM_EVAL_JUDGE_OUTPUT` | a rubric judge reply is invalid after the configured attempts |
403
+ | `ERR_PRISM_EVAL_JUDGE_TIMEOUT` / `_JUDGE_BOUNDS` | a judge attempt timed out or a byte/option bound was exceeded |
404
+ | `ERR_PRISM_EVAL_SCORER` / `_JUDGE` / `_MANIFEST` / `_TRIALS` / `_COMPARISON` | an invalid scorer, judge, manifest, trials, or comparison input |
405
+ | `ERR_PRISM_EVAL_CALIBRATION` | invalid calibration options, unsettled runs, or exceeded item/matrix bounds |
406
+ | `ERR_PRISM_EVAL_THRESHOLD` | an evaluation threshold was not met |
407
+ | `ERR_PRISM_EVAL_STORE_FAILURE` | an evaluation store append or query failed |
408
+
409
+ ## Cost, security, and failure behavior
410
+
411
+ - **Judge cost.** Model judges (`createModelJudge`) invoke an LLM once per evaluation item, so cost scales as `O(items × trials)`, and `scoreTurns: "each"` multiplies it by the turn count. Prefer deterministic rule, schema, and trajectory scorers for continuous CI; reserve judges for semantic quality gates.
412
+ - **Redaction.** Curation redacts before an item is built; a redactor that throws skips the run (`redaction failed`) rather than storing raw data. Records are redacted on the way out (`reason`, `error`, `metadata`), but a scorer's *input* is raw: `result`, `item`, and an untimelined run carry the text as recorded. The entry point resolves `redactor`/`secrets` once and hands the result to every scorer as `ScorerInput.redactor`, so a scorer or judge that embeds text in a prompt redacts with `input.redactor?.redact(value)` first. `createModelJudge` already does this for the target and the item before the prompt; a host that configures neither option has declared no secrets, and the seam is `undefined`.
413
+ - **Fail closed.** A missing timeline is a requirement error, not a zero (except where a scorer explicitly reports `0` with `metadata.invariant`); a missing decision is never inferred from a guardrail pass; an unstarted item is never counted as a pass.
414
+ - **No timeline, no peer.** Timeline projection is the only reason this package needs `@arnilo/prism-extensions/observability`; text-only hosts do not install it.
415
+
416
+ ## Comparing two runs
417
+
418
+ ```ts
419
+ import { compareExperiments } from "@arnilo/prism-hosts/evals";
420
+ const comparison = compareExperiments(baseline, candidate, { seed: 1 });
421
+ const success = comparison.scorers.task_success;
422
+ // difference = candidateMean - baselineMean; negative means regression.
423
+ // ci95 = { low, high }; significant uses the BH-adjusted qValue.
424
+ ```
425
+
426
+ The function pairs shared item ids, averages scored observations within each item,
427
+ and gives every paired item equal weight. It uses exact McNemar for binary scores
428
+ with one scored observation per item on both sides, and paired sign-flip permutation
429
+ otherwise. The 95% percentile bootstrap resamples item differences together.
430
+ Benjamini–Hochberg adjusts p-values across the compared scorers; `significant`
431
+ means `qValue <= alpha` (default `.05`), for either improvement or regression.
432
+
433
+ Dataset ids must match. Report versions, and manifest dataset versions, must match
434
+ when present on both sides. Duplicate ids, fewer than two shared items, or a
435
+ missing scorer/valid numeric score on any paired item throw
436
+ `ERR_PRISM_EVAL_COMPARE_UNPAIRED`. Failed/skipped records are excluded; a paired
437
+ item with no scored observations for a compared scorer is rejected. Unshared
438
+ items are excluded, so inspect `pairedItems` before drawing conclusions.
439
+
440
+ `scorers` selects distinct scorer ids; by default all observed scorer ids from
441
+ both reports are compared and required on every paired item. `seed` defaults to
442
+ zero. `resamples` overrides both bootstrap (default 2,000) and Monte Carlo
443
+ permutation (default 10,000), capped at `HARD_STATS_RESAMPLES`. Invalid numerical
444
+ options throw `ERR_PRISM_EVAL_STATS`. `alpha` changes significance only; `ci95`
445
+ always has 95% coverage. Comparison is pure and makes no agent calls.
446
+
447
+ ## Gating a release
448
+
449
+ Point-estimate gates (`minimumMacroMean`, `minimumByScorer`, `minimumPassHatK`,
450
+ and `minimumCandidateWins`) are non-statistical. They suit deterministic mock
451
+ suites. For sampled datasets, opt into confidence-aware gates:
452
+
453
+ ```ts
454
+ assertEvaluationThreshold(candidate, {
455
+ minimumLowerBound: { task_success: .7 },
456
+ maximumRegression: { baseline, delta: .02, alpha: .05 },
457
+ });
458
+ ```
459
+
460
+ `minimumLowerBound` requires each scorer's `ci95.low >= minimum`. Missing or
461
+ invalid intervals fail closed, including reports with fewer than two scored
462
+ items. For example, 9/10 successes has mean .9 but a Wilson lower bound about
463
+ .596, so it fails a .8 lower-bound gate. Bounds must be finite in `[0, 1]`;
464
+ equality passes. Failures name the scorer, requested bound, and observed interval
465
+ (or unavailable evidence).
466
+
467
+ `maximumRegression` calls `compareExperiments` once, using `baseline`, optional
468
+ `scorers`, and `alpha` (default .05). It fails when a candidate-minus-baseline
469
+ difference is strictly below `-delta` (default 0) and its BH-adjusted
470
+ `qValue <= alpha`. Equality at `-delta` passes. Failures include the scorer,
471
+ difference, margin, 95% interval, p-value, q-value, and alpha. Significance tests
472
+ against zero; the margin filters the observed drop, rather than testing a null
473
+ at `-delta`. A passing gate does not establish equivalence or sufficient power.
474
+ `delta` must be finite in `[0, 1]`, and `alpha` in `(0, 1)`. Pairing and option
475
+ errors propagate from comparison; a pairwise preference report cannot use this
476
+ gate. The comparison adds resampling work, with no extra agent or judge calls.
477
+
478
+ Size the paired dataset before running it:
479
+
480
+ ```ts
481
+ import { powerAnalysis, minimumDetectableEffect } from "@arnilo/prism-hosts/evals";
482
+ powerAnalysis({ baselinePassRate: .85, minimumDetectableDrop: .05 }); // { items: 909 }
483
+ powerAnalysis({ baselinePassRate: .85, minimumDetectableDrop: .05,
484
+ expectedDiscordance: .1 }); // { items: 312 }
485
+ minimumDetectableEffect({ discordantRate: .1, n: 312 }); // approximately .05
486
+ ```
487
+
488
+ `powerAnalysis` returns the smallest integer `items` reaching the target power
489
+ under the same two-sided McNemar normal approximation as `pairedProportionPower`
490
+ (Connor 1987), without continuity correction. Defaults are `alpha: .05` and
491
+ `power: .8`. With baseline rate `p`, drop `d`, and candidate rate `p-d`, default
492
+ discordance is `q = p*(1-p+d) + (1-p)*(p-d)`, assuming independent outcomes
493
+ within a pair. Prefer `expectedDiscordance` measured on paired pilot data;
494
+ positive outcome correlation often reduces the required sample size.
495
+
496
+ | Baseline | Detectable drop | Discordance | Alpha | Power | Paired items |
497
+ | --- | --- | --- | --- | --- | --- |
498
+ | .85 | .05 | .29 (default) | .05 | .8 | 909 |
499
+ | .90 | .05 | .22 (default) | .05 | .8 | 689 |
500
+ | .95 | .02 | .113 (default) | .05 | .8 | 2,215 |
501
+ | .85 | .05 | .10 (pilot) | .05 | .8 | 312 |
502
+ | .85 | .05 | .10 (pilot) | .01 | .9 | 591 |
503
+
504
+ Inputs require `0 < p <= 1`, `0 < d <= p`, `alpha < power < 1`, and feasible
505
+ discordance `d <= q <= min(2*p-d, 2*(1-p)+d)`. Invalid inputs or a required count
506
+ beyond the safe integer range throw `ERR_PRISM_EVAL_STATS`. The inverse
507
+ `minimumDetectableEffect` takes discordance directly, not a baseline rate.
508
+ These are planning approximations for one binary paired metric; small samples,
509
+ continuous scores, and multi-scorer BH gates need separate power assessment.
510
+ The item count means distinct paired items, not repeated trials of one item.
511
+
512
+
513
+ ## Comparing candidates
514
+
515
+ ```ts
516
+ const report = await runComparison({
517
+ dataset, candidates, scorers: [pairwise], trials: 3, seed: 1,
518
+ });
519
+ report.ranking; // [{ scorerId, candidate, strength, ci95: [low, high], rank }, …]
520
+ ```
521
+
522
+ Each candidate runs once per item per trial (`trials` defaults to 1, hard maximum
523
+ 16). Every stable candidate pair is scored by every scorer in each trial.
524
+ Records include a zero-based `trialIndex`. A thrown candidate error (including
525
+ a falsy thrown value), or a returned `failed`/`aborted` run, forfeits to a
526
+ successful opponent: the record is `scored`, its preference names the winner's
527
+ side, and `metadata.forfeit` names the loser. Both candidates failing or a scorer
528
+ throwing produces a `failed` record. Host cancellation still propagates.
529
+ Forfeits skip the judge. `wins`, `ties`, `failures`, and win thresholds retain
530
+ their existing meaning; wins now include forfeits.
531
+
532
+ Rankings are fitted separately per `scorerId`; different scorers are never
533
+ pooled. `bradleyTerry(pairs)` is also exported as a pure helper taking
534
+ `{ left, right, preference: "left" | "right" | "tie" }` records and returning a
535
+ candidate-to-strength object, or `null` when the fit is unavailable. It uses
536
+ [Hunter's MM update (2004)](https://doi.org/10.1214/aos/1079120141), treats ties as
537
+ half a win for each side, and normalizes strengths to geometric mean 1.
538
+ Larger strength means higher estimated win probability:
539
+ `P(a beats b) = strength[a] / (strength[a] + strength[b])`.
540
+ The fit takes O(iterations × candidates² + records), uses O(candidates²) space,
541
+ and stops at a maximum change in log strengths below 1e-9 or 1,000 iterations.
542
+
543
+ The 95% percentile `ci95` resamples whole item ids through `bootstrapInterval`,
544
+ keeping all trials and pair records for each sampled item together. There are
545
+ 1,000 resamples per scorer. Each bootstrap fit is reused across candidates;
546
+ sampling/quantile extraction adds O(candidates × (1,000 × records + 1,000 log 1,000))
547
+ work and fits add O(1,000 × iterations × candidates²).
548
+ `seed` (default 0) controls this bootstrap; it does not seed host candidate or
549
+ scorer calls. Candidate runs cost `items × trials × candidates` calls;
550
+ judge invocations cost at most `items × trials × pairs × scorers`, before any
551
+ judge-internal position swap or retry. Ranking makes no additional model calls.
552
+
553
+ A finite unregularized estimate requires a strongly connected win graph.
554
+ All wins on one side, disconnected evidence, no scored pairs, missing candidates,
555
+ or failure to converge produce `strength: null, ci95: null, rank: null`.
556
+ No pseudocounts are added. If any bootstrap draw has an unavailable fit, strengths
557
+ from the original data remain, but all CIs and ranks for that scorer are `null`;
558
+ invalid draws are never dropped to manufacture a narrower interval.
559
+ Otherwise overlapping intervals form transitive shared-rank groups, with
560
+ competition ranks (1, 1, 3). Rows within each scorer are sorted by descending
561
+ strength, breaking ties by candidate name. With no fit they retain name order.
562
+
563
+ ## Judges
564
+
565
+ `createRubricJudge` runs a host-built judge agent in a fresh session per attempt,
566
+ with no tools, one turn, one provider attempt, no continuations, and explicit
567
+ wall-time and token limits. The host owns and disposes the agent; the scorer
568
+ closes each session. A factory may return an agent synchronously or asynchronously.
569
+
570
+ ```ts
571
+ const judge = createRubricJudge({
572
+ agent: judgeAgent,
573
+ judgedModel: candidateAgent.config.model, // use the actual model if the candidate run overrides it
574
+ rubric: {
575
+ id: "helpfulness", version: "1", criteria: "Does the answer resolve the request?",
576
+ scale: [
577
+ { label: "no", score: 0, description: "Does not resolve it" },
578
+ { label: "partly", score: 0.5, description: "Resolves part of it" },
579
+ { label: "yes", score: 1, description: "Fully resolves it" },
580
+ ],
581
+ },
582
+ reference: item => item.expected as string | undefined,
583
+ });
584
+ ```
585
+
586
+ The scorer id defaults to the rubric id. `judgedModel` is a `{ provider, model }`
587
+ or a resolver `(input) => model`; supply the actual model including run overrides.
588
+ `RunResult` does not carry model identity. Equal or missing candidate identity
589
+ fails closed with `ERR_PRISM_EVAL_JUDGE_SELF` unless `allowSelfJudging: true`.
590
+ Known equal models are rejected at construction; factories and resolvers are
591
+ checked on use. Judge agents must have a resolved model.
592
+
593
+ The versioned prompt includes criteria, labeled score anchors, the item, optional
594
+ reference, and answer text. `include: "answer+timeline"` requires a timeline and
595
+ adds only structural step metadata, excluding input/output, errors, and arbitrary
596
+ metadata. Resolved `ScorerInput.redactor` redacts the item before the reference
597
+ callback and all prompt data before enforcing `maxInputBytes` (default 1 MiB,
598
+ hard 8 MiB). With no configured redactor or secrets the host declares no secrets.
599
+ The canonical rubric is snapshotted and SHA-256 hashed; its default byte cap is
600
+ 16 KiB (hard 64 KiB). Output defaults to 16 KiB (hard 64 KiB).
601
+
602
+ Replies must be JSON with exactly `reasoning` (at most 4 KiB of UTF-8) and a scale
603
+ `label`. The prompt requests reasoning before the label. Schema/parse failures
604
+ retry and then produce failed records with `ERR_PRISM_EVAL_JUDGE_OUTPUT`, never
605
+ an invented score. Successful records include `evaluatorKind`, `judgeModel`,
606
+ `rubricId`, `rubricVersion`, `rubricHash`, `templateVersion`, `label`, `attempts`,
607
+ and a redacted reasoning excerpt capped at 512 bytes.
608
+
609
+ **Cost:** one judge model call per item per attempt; `maxAttempts` defaults to 2
610
+ (hard 3), with a 30-second timeout per attempt (hard 300 seconds). Trials and
611
+ per-turn scoring multiply this cost. Provider failures and timeouts also retry;
612
+ host cancellation stops retries. A factory is inside the attempt timeout.
613
+
614
+ Labeled anchors, reference answers, and reasoning before the label make the
615
+ criteria explicit; the prompt also asks judges to avoid irrelevant verbosity
616
+ preferences. These measures do not establish agreement with human graders or
617
+ remove model bias. Use an independent judge model and validate semantic gates
618
+ against human labels. `createModelJudge` remains the low-level adapter for hosts
619
+ that supply their own judge call.
620
+
621
+ ### Pairwise judges and position consistency
622
+
623
+ `createPairwiseJudge` compares answer text in both orders using the same bounded,
624
+ tool-less session runner as `createRubricJudge`:
625
+
626
+ ```ts
627
+ const pairwise = createPairwiseJudge({
628
+ agent: judgeAgent,
629
+ rubric: { id: "helpfulness", version: "1", criteria: "Which answer resolves the request better?" },
630
+ judgedModels: { left: leftAgent.config.model, right: rightAgent.config.model },
631
+ });
632
+ const report = await runComparison({ dataset, candidates, scorers: [pairwise] });
633
+ ```
634
+
635
+ `judgedModels` supplies the actual models in `input.left` / `input.right` order,
636
+ including run overrides. It may instead be `(input) => ({ left, right })` for
637
+ comparisons with more candidates. Both identities are checked against the judge;
638
+ missing identities fail closed unless `allowSelfJudging: true`. Agent factories,
639
+ ids (defaulting to the rubric id), byte caps, timeouts, and retries work as for
640
+ rubric judges. This scorer sees answer text and the dataset item only.
641
+
642
+ Each reply must contain exactly `{ reasoning, winner: "A" | "B" | "tie" }`.
643
+ `allowTie` defaults to `true`; `false` excludes `"tie"` from valid replies.
644
+ After mapping the swapped verdict back to the original order, disagreement
645
+ always becomes a conservative tie, including when `allowTie: false`.
646
+ `metadata.positionInconsistent` distinguishes this from an agreed tie.
647
+ `metadata.verdicts` preserves both validated winner labels, redacted reasoning
648
+ excerpts (512 bytes each), attempt counts, and model/rubric/template provenance.
649
+ `metadata.lengthRatio` is left/right Unicode character count after redaction,
650
+ with each empty answer counted as one character to keep the ratio finite.
651
+ Candidate names are omitted from prompts. Both orders reuse the same redacted
652
+ answers; `runComparison` forwards its resolved redactor to pairwise scorers and
653
+ retains their metadata in comparison records.
654
+
655
+ `report.positionConsistency[scorerId]` is the fraction of successful swapped
656
+ judgments with agreeing verdicts, including agreed ties. Failed judgments are
657
+ excluded; scorers without successful swap evidence are omitted. An invalid reply
658
+ or failed order fails the pair rather than manufacturing a tie.
659
+
660
+ **Cost:** two judge calls per pair per item without retries. Each order defaults
661
+ to at most two attempts, so up to four calls per pair (or
662
+ `2 × maxAttempts`). Calls run sequentially, each in a fresh session. Judging is
663
+ opt-in: nothing runs until the host supplies the scorer to `runComparison`.
664
+ Position swaps expose position bias; they do not establish agreement with humans.
665
+
666
+
667
+ ### Judge panels
668
+
669
+ ```ts
670
+ const panel = createJudgePanel({
671
+ id: "helpfulness_panel",
672
+ judges: [judgeHyper, judgeOpenCodeGo, judgeLaya],
673
+ combine: "majority", // or "mean" / "median"
674
+ });
675
+ ```
676
+
677
+ A panel calls every member with the original `ScorerInput`, including its redactor,
678
+ then combines successful verdicts. `majority` requires `metadata.label` and chooses
679
+ the most frequent label; tied labels resolve to the lower score. If judges map the
680
+ same label to different scores, the lowest score for that label is used. `mean`
681
+ and `median` combine numeric scores and do not require labels. Use shared rubric
682
+ labels and score anchors so the verdicts are comparable.
683
+
684
+ `requireDistinctModels` defaults to `true`: each scorer must declare a known,
685
+ distinct `judgeModel: { provider, model }` at construction. `createRubricJudge`
686
+ populates this for a static agent; custom scorers can declare it directly or
687
+ through `defineScorer`. Factory-backed judges have no construction-time identity;
688
+ use `requireDistinctModels: false` to explicitly accept unverified diversity.
689
+ An empty panel is invalid. Member ids may repeat (for example, the same rubric
690
+ on different models); metadata retains the configured member order.
691
+
692
+ Throwing judges, invalid scores, and missing majority labels are excluded and
693
+ counted. Exactly half succeeding is enough; fewer than half causes a failed
694
+ record with `ERR_PRISM_EVAL_JUDGE_PANEL` and the failure count in its message.
695
+ Successful metadata includes `judges` (each id, model, label, score and status),
696
+ `failedJudges`, and `labels` in configured order, with `null` for missing labels.
697
+ Member errors and reasoning are omitted; the entry point redacts panel metadata.
698
+ Member `requires` declarations are combined, so input requirements still fail
699
+ before the candidate runs. Cancellation propagates through the original signal.
700
+
701
+ `report.aggregate.scorers[panel.id].judgeAgreement` is Fleiss’ κ across complete
702
+ label rows. Records with failed or unlabeled members are excluded from this
703
+ statistic. It is absent when no complete rows exist, there are fewer than two
704
+ judges, or all observed labels belong to one category (κ is undefined). Repeated
705
+ trials/step evaluations each contribute a rating row. The exported
706
+ `fleissKappa(labels)` accepts equally sized rows of two or more judge labels and
707
+ follows the [statsmodels Fleiss κ formula](https://www.statsmodels.org/stable/_modules/statsmodels/stats/inter_rater.html#fleiss_kappa).
708
+
709
+ **Cost:** the sum of all members’ calls, including their retries; the panel adds
710
+ no model calls or retries. Members run concurrently. Three rubric judges cost
711
+ three calls per item without retries, up to six with their default attempts.
712
+
713
+ ### Calibrating a judge
714
+
715
+ ```ts
716
+ import { calibrateJudge, labeledItemsFromFeedback, assertEvaluationThreshold } from "@arnilo/prism-hosts/evals";
717
+ const items = await labeledItemsFromFeedback({
718
+ feedbackStore, persistence, ownership: { tenantId, userId }, query: { tag: "graded" },
719
+ secrets,
720
+ });
721
+ const calibration = await calibrateJudge({ judge, items, scale: "ordinal", seed: 1, secrets });
722
+ assertEvaluationThreshold(experiment, {
723
+ calibrations: { [judge.id]: { report: calibration, minimumKappa: .6, minimumN: 30 } },
724
+ });
725
+ ```
726
+
727
+ Supply an independent judge with the actual candidate model through `judgedModel`,
728
+ including run overrides. The loader reconstructs the recorded result and first user
729
+ message through the persistence trace resolver. It requires a tenant and account
730
+ or user scope, checks exact ownership on every feedback record and trace, and uses
731
+ `traceLimits` for bounded cursor pagination and trace bytes. Query ownership cannot
732
+ override the explicit scope. The default mapping normalizes `rating` from `[-1, 1]`
733
+ to `[0, 1]`; records without a rating are omitted. `toScore(record)` can map tags
734
+ or metadata to a score, or return `undefined` to omit a record. Each selected
735
+ feedback record is a separate pair, including repeated reviews of the same run;
736
+ select a representative independent sample for calibration. Comments and feedback
737
+ metadata are never copied into the judge's item or result. Supply `redactor` or
738
+ `secrets` to both entry points when loading and judging secret-bearing content.
739
+
740
+ `calibrateJudge` accepts `{ item, result, humanScore }` pairs with finite scores
741
+ in `[0, 1]`. It passes only the item, expected answer, result, redactor and signal
742
+ to the scorer, never the human score. It supports answer-only scorers; declared
743
+ trace, timeline or environment requirements fail before scoring. Judge errors and
744
+ invalid scores count in `judgeFailures`; `n` counts successful pairs only. Abort
745
+ rejects the operation. Empty or single-category agreement and constant-rank
746
+ correlation are `null`, with no fabricated agreement or NaN in serialized reports.
747
+ The confusion matrix has ascending numeric `labels`, human rows and judge columns
748
+ in `counts`. Exact numeric scores are categories; align human and judge scales
749
+ before measuring agreement. Inputs are capped at `HARD_DATASET_ITEMS`, and the
750
+ estimated numeric matrix storage at the report byte ceiling.
751
+
752
+ The report includes unweighted `cohensKappa`, nominal `krippendorffAlpha` for two
753
+ complete raters, and average-tie-rank `spearman`. `scale: "ordinal"` additionally
754
+ returns quadratic `weightedKappa`, using positions in the sorted observed score
755
+ categories. Alpha remains nominal. These follow the definitions in
756
+ [scikit-learn's Cohen κ documentation](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.cohen_kappa_score.html),
757
+ [Krippendorff's alpha implementation](https://github.com/pln-fing-udelar/fast-krippendorff),
758
+ and [SciPy's Spearman documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html).
759
+
760
+ `kappaCi95` is a paired-item percentile bootstrap of **unweighted** κ using 2,000
761
+ resamples (default seed 0); it is absent when the original κ is undefined. A
762
+ one-category bootstrap draw has undefined κ and is conservatively assigned -1.
763
+ This can produce a wide interval for small samples, including perfect small
764
+ samples. Gates use the lower bound when present, otherwise the point κ, and
765
+ require at least 30 successful pairs by default. Undefined/non-finite evidence
766
+ fails; calibration entries for scorers absent from the evaluation report are
767
+ ignored. `minimumKappa` accepts `[-1, 1]`, and `minimumN` is a positive integer.
768
+ The caller supplies calibrations explicitly; judges never trigger them automatically.
769
+
770
+ **Cost:** one scorer invocation per labeled item; rubric retries and panel members
771
+ retain their own call costs. Bootstrap resampling makes no model calls. Nominal
772
+ statistics take linear time, ranking takes `O(n log n)`, the dense confusion matrix
773
+ takes `O(categories²)` space, and bootstrap takes up to
774
+ `O(2,000 × n)` for unweighted κ. `examples/run-feedback.ts` runs a small
775
+ mock-provider calibration; its single label demonstrates the API, not enough
776
+ evidence to pass a calibration gate.
777
+
778
+ ## Prompt-injection suite
779
+
780
+ `createInjectionDataset` makes a benign copy of every task and crosses tasks with
781
+ attacks and carriers. Inputs, expected values, splits, labels and existing tags
782
+ are retained; generated IDs are unique. `metadata.injection` contains
783
+ `{ attackId, carrier, payload, goal }` for attacks and
784
+ `{ attackId: null, carrier: null }` for benign items. Tags add `benign` or
785
+ `attack:<id>`. Dataset JSON, tag and item caps still apply.
786
+
787
+ ```ts
788
+ const dataset = createInjectionDataset({
789
+ id: "page-injection", tasks,
790
+ carriers: [{ tool: "web_fetch" }], // also: read, browser_snapshot
791
+ });
792
+ const suite = await runInjectionSuite({
793
+ agent: factory, dataset, utility: taskScorer, trials: 3,
794
+ });
795
+ console.log(suite.benignUtility, suite.utilityUnderAttack, suite.attackSuccessRate);
796
+ ```
797
+
798
+ The factory receives `hooks`, `slots`, and the current `item` (also available to
799
+ ordinary experiment factories). Forward hooks and slots into `createAgent`.
800
+ Factories must create isolated agents; manage their disposal as with
801
+ `runExperiment`. Existing hooks run alongside the injection hook, so approval
802
+ and output guardrails still apply. Each trial has its own injection closure,
803
+ including at concurrency greater than one. `injectionHooks(spec)` is also
804
+ available for standalone scenarios.
805
+
806
+ The original Prism payloads are `important_instructions`, `ignore_previous`,
807
+ `fake_tool_output`, and `exfiltration_link`. Custom `InjectionAttack` values have
808
+ `{ id, payload, goal: { tool?, argsContain?, textContains? } }`. All supplied goal
809
+ conditions must match; tool and argument conditions match the same call after
810
+ the first carrier call. Tool goals measure attempted calls, including calls
811
+ blocked by policy. The exfiltration goal uses `https://exfiltrate.invalid/collect`.
812
+ The `.invalid` domain is reserved and cannot identify a public destination;
813
+ use in-memory fixtures for fully network-free runs.
814
+
815
+ Carriers accept `position: "append" | "prepend"` (default append). The hook
816
+ changes successful text results only, retaining identity, non-text blocks and
817
+ trust metadata. It updates structured `markdown`, `answer`, or `ariaSnapshot`
818
+ fields too. Web fetch and browser snapshot retain the kernel's untrusted
819
+ content envelope; text-file `read` retains its existing unenveloped behavior.
820
+ Image and extracted-document reads are skipped.
821
+
822
+ **Run this opt-in suite against sandboxed tools only.** Payloads are inert text,
823
+ but an agent may follow them and try real tool actions. The included example
824
+ uses an in-memory tool and a scripted mock provider.
825
+
826
+ Rates are pass proportions at the utility scorer's `passThreshold` (default 1)
827
+ and deterministic attack success, with `{ rate, n, successes, missing, ci95:
828
+ { low, high } }`. Overall and per-attack/per-carrier metrics share the benign
829
+ baseline. `n` counts completed, fully scored item-trials; failed, skipped and
830
+ aborted trials are reported as `missing`. Empty evidence leaves rate/CI absent.
831
+ Wilson 95% intervals treat item-trials as Bernoulli observations; repeated tasks
832
+ can be correlated, so also inspect the report's item-clustered scorer statistics.
833
+ `attack_success` is explicitly not an invariant (higher means less safe).
834
+
835
+ Argument goals require timeline inputs: the suite defaults to `redacted_io`,
836
+ requires the optional observability peer, and rejects `metadata`/`off` and
837
+ sampling below 1. Secret redaction still applies; a redacted argument cannot
838
+ match a goal containing that secret. Inspect missing evidence before comparing
839
+ rates. No model judge calls are added.
840
+
841
+ Runs = tasks × (1 + attacks × carriers) × trials. Four built-in attacks mean
842
+ **5 runs per task/trial for one carrier**, or **13 for all three**.
843
+ See `examples/eval-injection.ts` for a runnable example that falls for one attack.