@agenticprimitives/evaluation 0.0.0-alpha.1 → 0.0.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +2 -0
  2. package/dist/act.d.ts +97 -0
  3. package/dist/act.d.ts.map +1 -0
  4. package/dist/act.js +115 -0
  5. package/dist/act.js.map +1 -0
  6. package/dist/agent-record.d.ts +86 -0
  7. package/dist/agent-record.d.ts.map +1 -0
  8. package/dist/agent-record.js +108 -0
  9. package/dist/agent-record.js.map +1 -0
  10. package/dist/assessment.d.ts +158 -0
  11. package/dist/assessment.d.ts.map +1 -0
  12. package/dist/assessment.js +167 -0
  13. package/dist/assessment.js.map +1 -0
  14. package/dist/canonical.d.ts +2 -0
  15. package/dist/canonical.d.ts.map +1 -0
  16. package/dist/canonical.js +4 -0
  17. package/dist/canonical.js.map +1 -0
  18. package/dist/capture.d.ts +90 -0
  19. package/dist/capture.d.ts.map +1 -0
  20. package/dist/capture.js +195 -0
  21. package/dist/capture.js.map +1 -0
  22. package/dist/compare-runner.d.ts +211 -0
  23. package/dist/compare-runner.d.ts.map +1 -0
  24. package/dist/compare-runner.js +379 -0
  25. package/dist/compare-runner.js.map +1 -0
  26. package/dist/conformal.d.ts +113 -0
  27. package/dist/conformal.d.ts.map +1 -0
  28. package/dist/conformal.js +113 -0
  29. package/dist/conformal.js.map +1 -0
  30. package/dist/consensus.d.ts +53 -0
  31. package/dist/consensus.d.ts.map +1 -0
  32. package/dist/consensus.js +64 -0
  33. package/dist/consensus.js.map +1 -0
  34. package/dist/eval-file.d.ts +104 -0
  35. package/dist/eval-file.d.ts.map +1 -0
  36. package/dist/eval-file.js +92 -0
  37. package/dist/eval-file.js.map +1 -0
  38. package/dist/experiment.d.ts +301 -0
  39. package/dist/experiment.d.ts.map +1 -0
  40. package/dist/experiment.js +237 -0
  41. package/dist/experiment.js.map +1 -0
  42. package/dist/index.d.ts +38 -0
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +38 -0
  45. package/dist/index.js.map +1 -1
  46. package/dist/ledger.d.ts +128 -0
  47. package/dist/ledger.d.ts.map +1 -0
  48. package/dist/ledger.js +146 -0
  49. package/dist/ledger.js.map +1 -0
  50. package/dist/live-gates.d.ts +3 -0
  51. package/dist/live-gates.d.ts.map +1 -1
  52. package/dist/live-gates.js +3 -1
  53. package/dist/live-gates.js.map +1 -1
  54. package/dist/measure.d.ts +63 -0
  55. package/dist/measure.d.ts.map +1 -0
  56. package/dist/measure.js +95 -0
  57. package/dist/measure.js.map +1 -0
  58. package/dist/replay.d.ts +58 -0
  59. package/dist/replay.d.ts.map +1 -0
  60. package/dist/replay.js +65 -0
  61. package/dist/replay.js.map +1 -0
  62. package/dist/report.d.ts +249 -0
  63. package/dist/report.d.ts.map +1 -0
  64. package/dist/report.js +363 -0
  65. package/dist/report.js.map +1 -0
  66. package/dist/rollup.d.ts +91 -0
  67. package/dist/rollup.d.ts.map +1 -0
  68. package/dist/rollup.js +80 -0
  69. package/dist/rollup.js.map +1 -0
  70. package/dist/selection-gates.d.ts +283 -0
  71. package/dist/selection-gates.d.ts.map +1 -0
  72. package/dist/selection-gates.js +331 -0
  73. package/dist/selection-gates.js.map +1 -0
  74. package/dist/selection-score.d.ts +285 -0
  75. package/dist/selection-score.d.ts.map +1 -0
  76. package/dist/selection-score.js +392 -0
  77. package/dist/selection-score.js.map +1 -0
  78. package/dist/selection.d.ts +83 -0
  79. package/dist/selection.d.ts.map +1 -0
  80. package/dist/selection.js +86 -0
  81. package/dist/selection.js.map +1 -0
  82. package/dist/signals.d.ts +37 -0
  83. package/dist/signals.d.ts.map +1 -0
  84. package/dist/signals.js +44 -0
  85. package/dist/signals.js.map +1 -0
  86. package/dist/stats.d.ts +62 -0
  87. package/dist/stats.d.ts.map +1 -0
  88. package/dist/stats.js +279 -0
  89. package/dist/stats.js.map +1 -0
  90. package/package.json +17 -2
@@ -0,0 +1,211 @@
1
+ import { type ReplaySetV1, type ReplayIntentV1 } from './replay.js';
2
+ import { type SelectionCriterionV1, type SelectionVerdictV1 } from './selection.js';
3
+ import { type SelectionCaseV1, type SelectionScoringV1 } from './selection-score.js';
4
+ import { type ActCaptureV1, type ActGoldV1 } from './act.js';
5
+ import { type EvalCaptureWindowV1, type Pseudonymiser, type CaptureRefusalV1 } from './capture.js';
6
+ import { type ExperimentPlanV1, type ExperimentRecordV1, type ExperimentRunV1, type VariantRequestV1 } from './experiment.js';
7
+ /** The eval store — structurally a `ProvenanceStorePort` (spec 414 §5); this package names no binding. */
8
+ export interface EvalStoreLike {
9
+ put(ref: {
10
+ agent: string;
11
+ key: string;
12
+ }, document: Record<string, unknown>): Promise<{
13
+ ok: boolean;
14
+ error?: string;
15
+ }>;
16
+ get(ref: {
17
+ agent: string;
18
+ key: string;
19
+ }): Promise<{
20
+ status: 'found';
21
+ document: Record<string, unknown>;
22
+ } | {
23
+ status: 'absent';
24
+ } | {
25
+ status: 'refused';
26
+ reason: string;
27
+ }>;
28
+ }
29
+ export interface ComparisonPorts {
30
+ /** Dispatch one intent under one variant; the run reference comes back, never the reply's words. */
31
+ ask(input: {
32
+ intentId: string;
33
+ message: string;
34
+ variant: VariantRequestV1;
35
+ variantName: string;
36
+ repeat: number;
37
+ }): Promise<{
38
+ ok: true;
39
+ runRef: string; /** Spec 418 §12 — what the reply said about the act (the act laboratory). */
40
+ act?: ActCaptureV1; /** The reply's `plannerTrace.selection`, when the arm left one. */
41
+ selection?: unknown; /** The reply's planner trace, for its reported token usage (numbers read here; nothing else kept). */
42
+ trace?: unknown; /** THE REPLY'S WORDS — present only when the caller asked to keep them (`keep` below); the runner never reads or stores them, it hands them on. */
43
+ reply?: KeptReplyV1;
44
+ } | {
45
+ ok: false;
46
+ error: string;
47
+ }>;
48
+ /** The run's JSON-LD bundle by PROV-AQ (the binding polls until the export lands, or gives up ⇒ null). */
49
+ readProvenance(runRef: string): Promise<Record<string, unknown> | null>;
50
+ readMeasures?(runRef: string): Promise<Record<string, unknown> | null>;
51
+ /** KEEP THE WORDS (2026-10-01). The store never holds a reply's text — L3 is refused by design (415 S6) — and the record
52
+ * holds numbers, so a comparison could say an answer scored 0.35 and nobody could read it. This port receives, per run,
53
+ * what the ask returned (the reply, when the ask port carried it) and the run's provenance graph (its activities — the
54
+ * run, each step, each model call — and what each generated), and puts them wherever the caller decided, OUTSIDE the
55
+ * store. Synthetic estates only: a window must admit the addressee, which the CLI checks before wiring it. */
56
+ keep?(entry: KeptRunV1): Promise<void>;
57
+ }
58
+ /** The reply as the estate returned it, words included. */
59
+ export interface KeptReplyV1 {
60
+ kind?: string;
61
+ text?: string;
62
+ spoken?: string;
63
+ error?: string;
64
+ results?: unknown;
65
+ plannerTrace?: unknown;
66
+ skillProvenance?: unknown;
67
+ }
68
+ /** One run, kept whole: the ask, the reply, the activities the run spawned (from its PROV bundle) and the judge's reading. */
69
+ export interface KeptRunV1 {
70
+ intentId: string;
71
+ variant: string;
72
+ repeat: number;
73
+ runRef: string;
74
+ message: string;
75
+ reply?: KeptReplyV1;
76
+ /** The run's JSON-LD bundle: `graph` holds the run activity (ServiceExecution), one SkillExecution per step, one
77
+ * ModelInvocation per model call, and the entities each generated (receipts, the plan, the variant). */
78
+ provenance: Record<string, unknown> | null;
79
+ verdict: SelectionVerdictV1;
80
+ selected: string[];
81
+ outcome?: {
82
+ score: number;
83
+ classes: Record<string, number>;
84
+ };
85
+ quality?: {
86
+ score: number;
87
+ scores: Record<string, number>;
88
+ };
89
+ }
90
+ /** Spec 416 §4h — a seeded starting state's content, by scenario id: what an intent's `startingState` names. Its digest is
91
+ * sha256 over its canonical JSON and must equal the digest the replay set pins. */
92
+ export interface StartingStateFixtureV1 {
93
+ askerContext?: {
94
+ recentSkills?: Array<{
95
+ id: string;
96
+ times: number;
97
+ }>;
98
+ memoryTags?: string[];
99
+ heldClasses?: string[];
100
+ };
101
+ }
102
+ export declare function startingStateDigest(f: StartingStateFixtureV1): Promise<string>;
103
+ export interface ComparisonInput {
104
+ /** Seeded starting states by scenario id (an intent's `startingState.scenarioId`). */
105
+ fixtures?: Record<string, StartingStateFixtureV1>;
106
+ set: ReplaySetV1;
107
+ criterion: SelectionCriterionV1;
108
+ plan: ExperimentPlanV1;
109
+ window: EvalCaptureWindowV1 | null;
110
+ /** The Home origin the runs are asked at, and its `EVAL_CAPTURE` setting. */
111
+ estate: string;
112
+ estateCapture: 'on' | 'off';
113
+ asker: string;
114
+ addressee: string;
115
+ store: EvalStoreLike;
116
+ pseudo: Pseudonymiser;
117
+ ports: ComparisonPorts;
118
+ /** Tool id → canonical skill id, for a harness that has not stamped `governedBySkill` (415 S1): evidence `inferred`. */
119
+ skillMap?: Record<string, string>;
120
+ /** Spec 418 §12 — the act laboratory's gold, names already resolved to addresses (`resolveActGold`): each run is also
121
+ * judged on the act it reached and the receipt it left. */
122
+ actGold?: ActGoldV1;
123
+ scoring?: SelectionScoringV1;
124
+ context?: Record<string, unknown> | string;
125
+ now?: () => Date;
126
+ log?: (line: string) => void;
127
+ }
128
+ /** `skill:<ns>/<name>@<version>#<digest>` (415 S1) → the canonical id `skill:<ns>/<name>`. */
129
+ /** `urn:ap:prov:skill-contract:skill:<ns>/<name>@<version>#<digest>` (the provenance projection of a step's contract) →
130
+ * the canonical id `skill:<ns>/<name>`. */
131
+ export declare const skillIdOf: (iri: string) => string;
132
+ /** Criterion cases as the scorer's cases: the split's intents, each with its gold. */
133
+ export declare function casesOf(set: ReplaySetV1, criterion: SelectionCriterionV1, split: ExperimentPlanV1['split']): {
134
+ intents: ReplayIntentV1[];
135
+ cases: SelectionCaseV1[];
136
+ skillIds: string[];
137
+ };
138
+ /** What one run's trace says was selected, and by which evidence. */
139
+ /** The evidence KIND is a property of how the trace is read, not of whether anything was selected: a harness that stamps
140
+ * `governedBySkill` and selected nothing is a STAMPED observation of no selection (a `tn` or a `miss`), never an
141
+ * unreadable one. `inferred` only when a tool map stood in for the stamp. */
142
+ export declare function observeSelection(graph: Record<string, unknown>, skillMap: Record<string, string> | undefined): {
143
+ selected: string[];
144
+ evidence: 'stamped' | 'inferred';
145
+ chose: string[];
146
+ };
147
+ /** Score an experiment's runs: per variant (stamped and inferred never pooled — J4), the gate, and every pairwise
148
+ * comparison. Pure: what `runComparison` does after the runs, callable again over a stored record. */
149
+ export declare function scoreExperimentRuns(input: {
150
+ plan: ExperimentPlanV1;
151
+ setDigest: string;
152
+ cases: readonly SelectionCaseV1[];
153
+ skillIds: readonly string[];
154
+ pairs: ReadonlyArray<[string, string]>;
155
+ runs: readonly ExperimentRunV1[];
156
+ scoring?: SelectionScoringV1;
157
+ log?: (line: string) => void;
158
+ }): Promise<Pick<ExperimentRecordV1, 'scores' | 'verdicts' | 'comparisons'>>;
159
+ /** THE COMPARISON IN THREE PIECES (2026-10-01). `runComparison` was one loop; a runner that must survive between
160
+ * requests — the Home's Lab, one Durable Object alarm per case — needs the same pre-registration, the same per-case
161
+ * judgement and the same scoring without a duplicate. So the loop body is `runOneCase`, the setup `startComparison`
162
+ * (its result is plain data a store can keep) and the scoring `finishComparison`; `runComparison` composes them and
163
+ * behaves exactly as before. */
164
+ export interface ComparisonState {
165
+ setDigest: string;
166
+ planDigest: string;
167
+ startedAt: string;
168
+ intents: ReplayIntentV1[];
169
+ cases: SelectionCaseV1[];
170
+ skillIds: string[];
171
+ pairs: Array<[string, string]>;
172
+ pseudoAddressee: string;
173
+ /** Capture refusals so far, by reason — `CaptureRefusals` rebuilt at the finish. */
174
+ refusedCounts: Partial<Record<CaptureRefusalV1, number>>;
175
+ /** W4 ISOLATION — the conversation context ids the experiment's runs have arrived under so far. A later run under one
176
+ * of them is not a fresh context and is refused, not scored. Absent on a state kept before this field existed. */
177
+ seenContexts?: string[];
178
+ }
179
+ /** One (intent, variant, repeat) of the plan — what a stepper dispatches, in the plan's interleaved order. */
180
+ export interface ComparisonStep {
181
+ intent: ReplayIntentV1;
182
+ variantName: string;
183
+ variant: VariantRequestV1;
184
+ repeat: number;
185
+ }
186
+ /** The plan's steps in the order `runComparison` runs them: every intent under every variant, repeat by repeat
187
+ * (INTERLEAVED, spec 418 §8 — a paired comparison's two runs share the estate's load and the time of day). */
188
+ export declare function comparisonSteps(plan: ExperimentPlanV1, intents: ReadonlyArray<ReplayIntentV1>): ComparisonStep[];
189
+ /** Pre-registration: the digests in hand are the digests in the plan, or nothing runs; the plan is registered once. */
190
+ export declare function startComparison(input: ComparisonInput): Promise<ComparisonState>;
191
+ /** One case under one variant: ask, read the trace, judge, export at the window's level or count the refusal, and hand
192
+ * the words (if the ask carried them) to the keep port. Returns the run; mutates only `state.refusedCounts`. */
193
+ export declare function runOneCase(input: ComparisonInput, state: ComparisonState, step: ComparisonStep): Promise<ExperimentRunV1>;
194
+ /** W4 — whether this run was a fresh context: no recalled turns on the trace, and a door context id not seen before in
195
+ * this experiment. A seen-before id is recorded on the state as a side effect of the check (the first run under an id
196
+ * is the fresh one; the second is not). Mutates `state.seenContexts` only. */
197
+ export declare function isolationRefusalOf(trace: unknown, graph: Record<string, unknown>, state: Pick<ComparisonState, 'seenContexts'>): NonNullable<ExperimentRunV1['isolation']> | null;
198
+ /** The models a run's trace says carried it: every `ModelInvocation` activity in the PROV graph, folded to one row per
199
+ * (role, provider, model) with its call count, in first-seen order. Empty when the graph names none. */
200
+ export declare function modelCallsOf(graph: Record<string, unknown>): Array<{
201
+ role: string;
202
+ provider: string;
203
+ model: string;
204
+ calls: number;
205
+ }>;
206
+ /** Score every variant (stamped and inferred never pooled), gate it, compare the pairs, and write the record. */
207
+ export declare function finishComparison(input: ComparisonInput, state: ComparisonState, runs: ExperimentRunV1[]): Promise<ExperimentRecordV1>;
208
+ export declare function runComparison(input: ComparisonInput): Promise<ExperimentRecordV1>;
209
+ /** A one-screen table of an experiment: per variant, the headline numbers and the gate; then each comparison. */
210
+ export declare function formatExperiment(rec: ExperimentRecordV1): string;
211
+ //# sourceMappingURL=compare-runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compare-runner.d.ts","sourceRoot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 415 A4 (`ap eval compare`). Pure orchestration over PORTS: the ask, the provenance read
2
+ // (PROV-AQ), the measures read, and the eval store. Every intent of the chosen split is dispatched under every variant,
3
+ // `repeats` times; each run's trace is read back (never the reply's words), the selection judged mechanically, the run
4
+ // exported through the capture firewall at the window's level or refused by name, and one experiment record written.
5
+ //
6
+ // Pre-registration first (SEL-3): the plan's digests must match the set and the criterion in hand, and a plan already
7
+ // registered under this id with a different digest is a refusal — never an overwrite. Stamped and inferred evidence are
8
+ // never pooled: a variant whose runs carry both is scored on neither and says so.
9
+ import { replaySetDigest, splitOf } from './replay.js';
10
+ import { criterionDigest, judgeSelection } from './selection.js';
11
+ import { scoreSelectionRun, stage2Of, pairsOf, gateSelectionRun, compareSelectionRuns, classifyRows, ComparisonRefusedError } from './selection-score.js';
12
+ import { runSelectionFactsOf } from './selection-gates.js';
13
+ import { canonicalJson } from './canonical.js';
14
+ import { judgeAct, actStepsOf } from './act.js';
15
+ import { captureGate, CaptureRefusals, projectRunForExport, selectionFactsOf, runActivityOf } from './capture.js';
16
+ import { experimentPlanDigest, experimentPlanToJsonLd, experimentToJsonLd, confoundsOf, selectionRowsOf, variantRequestDigest, runTokensOf, failureCauseOf, failureSplitOf } from './experiment.js';
17
+ export async function startingStateDigest(f) {
18
+ const b = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonicalJson(f))));
19
+ return `sha256:${Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')}`;
20
+ }
21
+ /** `skill:<ns>/<name>@<version>#<digest>` (415 S1) → the canonical id `skill:<ns>/<name>`. */
22
+ /** `urn:ap:prov:skill-contract:skill:<ns>/<name>@<version>#<digest>` (the provenance projection of a step's contract) →
23
+ * the canonical id `skill:<ns>/<name>`. */
24
+ export const skillIdOf = (iri) => iri.replace(/^urn:ap:prov:skill-contract:|^urn:ap:skill:/, '').replace(/[@#].*$/, '');
25
+ const toolIdOf = (iri) => iri.replace(/^urn:ap:capability:/, '');
26
+ /** Criterion cases as the scorer's cases: the split's intents, each with its gold. */
27
+ export function casesOf(set, criterion, split) {
28
+ const intents = split === 'all' ? set.intents : splitOf(set, split);
29
+ const skills = new Set();
30
+ const cases = intents.map((i) => {
31
+ const g = criterion.cases[i.id];
32
+ if (!g)
33
+ throw new ComparisonRefusedError(`the criterion has no case for intent ${i.id}`);
34
+ if (g.expected)
35
+ skills.add(g.expected);
36
+ for (const s of g.acceptable ?? [])
37
+ skills.add(s);
38
+ for (const s of g.forbidden ?? [])
39
+ skills.add(s);
40
+ // The CRITERION says whether a case is a negative (`expected: null`); the scorer reads it from the bucket's `negative`
41
+ // prefix. A slate whose buckets name their origin instead (stratum 2's `external-…`) is normalised here so a negative
42
+ // is counted as one — otherwise its TN/spur outcomes leave every denominator and a TA can exceed 1 (seen 2026-09-26).
43
+ const bucket = i.bucket ?? (g.expected ? 'explicit' : 'negative-out');
44
+ return {
45
+ id: i.id, expected: g.expected, ...(g.acceptable?.length ? { acceptable: g.acceptable } : {}),
46
+ bucket: g.expected === null && !bucket.startsWith('negative') ? `negative-${bucket}` : bucket,
47
+ slateSkill: g.expected ?? g.forbidden?.[0] ?? null,
48
+ clusterId: i.seedId ?? i.id, provenance: i.provenance,
49
+ collisionPair: g.collisionPair ?? null, locked: i.split === 'held-out',
50
+ };
51
+ });
52
+ for (const [a, b] of criterion.collisionPairs ?? []) {
53
+ skills.add(a);
54
+ skills.add(b);
55
+ }
56
+ return { intents, cases, skillIds: [...skills].sort() };
57
+ }
58
+ /** What one run's trace says was selected, and by which evidence. */
59
+ /** The evidence KIND is a property of how the trace is read, not of whether anything was selected: a harness that stamps
60
+ * `governedBySkill` and selected nothing is a STAMPED observation of no selection (a `tn` or a `miss`), never an
61
+ * unreadable one. `inferred` only when a tool map stood in for the stamp. */
62
+ export function observeSelection(graph, skillMap) {
63
+ const facts = selectionFactsOf(graph);
64
+ if (facts.governed.length)
65
+ return { selected: [...new Set(facts.governed.map(skillIdOf))], evidence: 'stamped', chose: facts.chose };
66
+ if (!skillMap)
67
+ return { selected: [], evidence: 'stamped', chose: facts.chose };
68
+ const mapped = facts.chose.map(toolIdOf).map((t) => skillMap[t]).filter((s) => !!s);
69
+ return { selected: [...new Set(mapped)], evidence: 'inferred', chose: facts.chose };
70
+ }
71
+ /** Score an experiment's runs: per variant (stamped and inferred never pooled — J4), the gate, and every pairwise
72
+ * comparison. Pure: what `runComparison` does after the runs, callable again over a stored record. */
73
+ export function scoreExperimentRuns(input) {
74
+ const { plan, cases, skillIds, pairs, runs } = input;
75
+ const log = input.log ?? (() => undefined);
76
+ const scores = {};
77
+ const verdicts = {};
78
+ const scoring = { tiers: ['stamped', 'inferred'], minConfidence: 'inferred', stage2Trials: Math.max(1, plan.repeats - 1), ...(plan.policy === 'any-fire' ? { primary: 'any-fire' } : {}), ...input.scoring };
79
+ const evidenceOf = (name) => {
80
+ const kinds = new Set(runs.filter((r) => r.variant === name && r.status === 'ok').map((r) => r.evidence));
81
+ return kinds.size > 1 ? 'mixed' : (kinds.values().next().value ?? 'none');
82
+ };
83
+ for (const name of Object.keys(plan.variants)) {
84
+ if (evidenceOf(name) === 'mixed') {
85
+ log(`variant ${name}: runs carry both stamped and inferred evidence — not scored (J4)`);
86
+ continue;
87
+ }
88
+ const rows = selectionRowsOf(runs, name);
89
+ const score = scoreSelectionRun({ skillIds, cases, rows, pairs }, scoring);
90
+ const stage2 = plan.repeats > 1 ? stage2Of({ cases, stage1: score.outcomes, stage2: classifyRows(cases, rows, pairs, { ...scoring, stage: 2 }), perSkill: score.perSkill, skillIds }, scoring) : null;
91
+ const pairScores = pairsOf({ skillIds, cases, pairs, confusion: score.confusion, perSkill: score.perSkill, stage2 }, plan.thresholds);
92
+ scores[name] = score;
93
+ verdicts[name] = gateSelectionRun({ score, skillIds, pairs: pairScores, stage2, tier: plan.repeats > 1 ? 'B' : 'A' }, plan.thresholds);
94
+ }
95
+ const names = Object.keys(plan.variants);
96
+ const comparisons = [];
97
+ return (async () => {
98
+ for (let i = 0; i < names.length; i++)
99
+ for (let j = i + 1; j < names.length; j++) {
100
+ const a = names[i], b = names[j];
101
+ const confounds = confoundsOf(plan.variants[a], plan.variants[b]);
102
+ if (!scores[a] || !scores[b]) {
103
+ comparisons.push({ a, b, confounds, confounded: confounds.length > 1, comparison: null, error: 'a side was not scored' });
104
+ continue;
105
+ }
106
+ try {
107
+ const side = async (n) => ({ datasetDigest: input.setDigest, variantDigest: await variantRequestDigest(plan.variants[n]), split: plan.split === 'held-out' ? 'held-out' : 'development', score: scores[n], cases });
108
+ comparisons.push({ a, b, confounds, confounded: confounds.length > 1, comparison: compareSelectionRuns(await side(a), await side(b)) });
109
+ }
110
+ catch (e) {
111
+ comparisons.push({ a, b, confounds, confounded: confounds.length > 1, comparison: null, error: e instanceof Error ? e.message : String(e) });
112
+ }
113
+ }
114
+ return { scores, verdicts, comparisons };
115
+ })();
116
+ }
117
+ /** The plan's steps in the order `runComparison` runs them: every intent under every variant, repeat by repeat
118
+ * (INTERLEAVED, spec 418 §8 — a paired comparison's two runs share the estate's load and the time of day). */
119
+ export function comparisonSteps(plan, intents) {
120
+ const out = [];
121
+ for (let repeat = 0; repeat < plan.repeats; repeat++)
122
+ for (const intent of intents)
123
+ for (const [variantName, variant] of Object.entries(plan.variants))
124
+ out.push({ intent, variantName, variant, repeat });
125
+ return out;
126
+ }
127
+ /** Pre-registration: the digests in hand are the digests in the plan, or nothing runs; the plan is registered once. */
128
+ export async function startComparison(input) {
129
+ const { set, criterion, plan, store, pseudo } = input;
130
+ const now = input.now ?? (() => new Date());
131
+ const log = input.log ?? (() => undefined);
132
+ const context = input.context ?? 'https://agenticprimitives.dev/ns/evaluation.jsonld';
133
+ const setDigest = await replaySetDigest(set);
134
+ const critDigest = await criterionDigest(criterion);
135
+ if (criterion.replaySetDigest !== setDigest)
136
+ throw new ComparisonRefusedError(`the criterion is gold for ${criterion.replaySetDigest}, not this set (${setDigest})`);
137
+ if (plan.replaySetDigest !== setDigest)
138
+ throw new ComparisonRefusedError(`the plan pre-registered set ${plan.replaySetDigest}; this set is ${setDigest}`);
139
+ if (plan.criterionDigest !== critDigest)
140
+ throw new ComparisonRefusedError(`the plan pre-registered criterion ${plan.criterionDigest}; this criterion is ${critDigest}`);
141
+ const planDigest = await experimentPlanDigest(plan);
142
+ const existing = await store.get({ agent: 'experiments', key: `experiment-plan:${plan.id}` });
143
+ if (existing.status === 'refused')
144
+ throw new ComparisonRefusedError(`the eval store refused the plan read: ${existing.reason}`);
145
+ if (existing.status === 'found' && existing.document['planDigest'] !== planDigest)
146
+ throw new ComparisonRefusedError(`a plan is already registered as ${plan.id} with digest ${String(existing.document['planDigest'])}; this one is ${planDigest} — a changed plan is a new plan`);
147
+ if (existing.status === 'absent') {
148
+ const w = await store.put({ agent: 'experiments', key: `experiment-plan:${plan.id}` }, { planDigest, ...(await experimentPlanToJsonLd(plan, { context })) });
149
+ if (!w.ok)
150
+ throw new ComparisonRefusedError(`the plan could not be registered: ${w.error ?? 'store refused'}`);
151
+ log(`registered plan ${plan.id} (${planDigest.slice(0, 18)}…)`);
152
+ }
153
+ const { intents, cases, skillIds } = casesOf(set, criterion, plan.split);
154
+ const pairs = criterion.collisionPairs ?? [];
155
+ const startedAt = now().toISOString();
156
+ const pseudoAddressee = await pseudo.agent(input.addressee);
157
+ return { setDigest, planDigest, startedAt, intents, cases, skillIds, pairs: [...pairs], pseudoAddressee, refusedCounts: {} };
158
+ }
159
+ /** One case under one variant: ask, read the trace, judge, export at the window's level or count the refusal, and hand
160
+ * the words (if the ask carried them) to the keep port. Returns the run; mutates only `state.refusedCounts`. */
161
+ export async function runOneCase(input, state, step) {
162
+ const { criterion, plan, store, pseudo, ports } = input;
163
+ const now = input.now ?? (() => new Date());
164
+ const log = input.log ?? (() => undefined);
165
+ const { intent, variantName, variant, repeat } = step;
166
+ const { pairs, pseudoAddressee } = state;
167
+ const refuse = (reason) => { state.refusedCounts[reason] = (state.refusedCounts[reason] ?? 0) + 1; };
168
+ const t = Date.now();
169
+ // A SEEDED STARTING STATE (416 §4h): the intent names a scenario; its fixture is checked against the pinned digest and
170
+ // its asker context rides in this run's variant. Missing or changed is a failed run, said by name — never a run
171
+ // without its state.
172
+ let runVariant = variant;
173
+ if (intent.startingState?.scenarioId) {
174
+ const fx = input.fixtures?.[intent.startingState.scenarioId];
175
+ const why = !fx ? `starting state ${intent.startingState.scenarioId} is not among the fixtures` : intent.startingState.digest && (await startingStateDigest(fx)) !== intent.startingState.digest ? `starting state ${intent.startingState.scenarioId} does not match its pinned digest` : null;
176
+ if (why) {
177
+ log(`✗ ${variantName}#${repeat} ${intent.id}: ${why}`);
178
+ return { intentId: intent.id, variant: variantName, repeat, runRef: null, status: 'failed', failureCause: 'environment', selected: [], evidence: 'none', captureLevel: null, ms: 0, error: why };
179
+ }
180
+ if (fx.askerContext)
181
+ runVariant = { ...variant, askerContext: { digest: intent.startingState.digest ?? (await startingStateDigest(fx)), ...fx.askerContext } };
182
+ }
183
+ // One flaky request must not throw away an experiment: a thrown ask or read is a FAILED run, recorded and counted.
184
+ const asked = await ports.ask({ intentId: intent.id, message: intent.message, variant: runVariant, variantName, repeat })
185
+ .catch((e) => ({ ok: false, error: `the ask threw: ${e instanceof Error ? e.message : String(e)}` }));
186
+ // The ASK's latency — until the reply arrived — apart from `ms`, which also counts reading the run back.
187
+ const askMs = Date.now() - t;
188
+ if (!asked.ok) {
189
+ log(`✗ ${variantName}#${repeat} ${intent.id}: ${asked.error}`);
190
+ return { intentId: intent.id, variant: variantName, repeat, runRef: null, status: 'failed', failureCause: failureCauseOf(asked.error), selected: [], evidence: 'none', captureLevel: null, ms: Date.now() - t, error: asked.error };
191
+ }
192
+ const graph = await ports.readProvenance(asked.runRef).catch(() => null);
193
+ if (!graph) {
194
+ log(`? ${variantName}#${repeat} ${intent.id}: trace unreadable`);
195
+ return { intentId: intent.id, variant: variantName, repeat, runRef: asked.runRef, status: 'unreadable', failureCause: 'environment', selected: [], evidence: 'none', captureLevel: null, ms: Date.now() - t, error: 'the run\'s provenance could not be read (undetected, never a miss)' };
196
+ }
197
+ // W4 ISOLATION — a repeat is a measurement only from a FRESH context. A run whose trace says the agent recalled earlier
198
+ // turns, or that arrived under a context id another run of this experiment already used, is REFUSED: recorded with the
199
+ // reason, never judged — a score it would have earned is contaminated by what it remembered.
200
+ const isolation = isolationRefusalOf(asked.trace, graph, state);
201
+ if (isolation) {
202
+ log(`⊘ ${variantName}#${repeat} ${intent.id}: ${isolation.because}`);
203
+ return { intentId: intent.id, variant: variantName, repeat, runRef: asked.runRef, status: 'unreadable', failureCause: 'environment', isolation, selected: [], evidence: 'none', captureLevel: null, ms: Date.now() - t, error: `isolation: ${isolation.because}` };
204
+ }
205
+ const obs = observeSelection(graph, input.skillMap);
206
+ const g = criterion.cases[intent.id];
207
+ const verdict = judgeSelection(g, { selected: obs.selected, evidence: obs.evidence, readActivity: true }, { collisionPairs: pairs, policy: plan.policy ?? 'primary' });
208
+ const run = runActivityOf(graph);
209
+ const variantNode = run?.['underVariant'] ? (graph['graph'] ?? []).find((n) => n['id'] === run['underVariant']) : undefined;
210
+ const ranUnder = variantNode ? { ...(variantNode['variantDigest'] ? { variantDigest: String(variantNode['variantDigest']) } : {}), ...(variantNode['plannerKind'] ? { plannerKind: String(variantNode['plannerKind']) } : {}), ...(variantNode['capabilityToggle'] ? { toggles: [].concat(variantNode['capabilityToggle']) } : {}) } : null;
211
+ // The firewall: the window's level, or a refusal by name. A refused run is still JUDGED (the verdict is a number
212
+ // about the harness, not a record of the person) — it is the EXPORT that does not happen.
213
+ const level = input.window?.level ?? 'L0';
214
+ const gate = captureGate({ window: input.window, now: now(), asker: input.asker, addressee: input.addressee, estate: input.estate, estateCapture: input.estateCapture, level });
215
+ let captureLevel = null;
216
+ if (gate.ok) {
217
+ const measures = ports.readMeasures ? await ports.readMeasures(asked.runRef).catch(() => null) : null;
218
+ const doc = await projectRunForExport({ runRef: asked.runRef, graph, measures, level: gate.level, pseudo });
219
+ const w = await store.put({ agent: pseudoAddressee, key: `run:${String(doc['runRef'])}` }, doc);
220
+ if (w.ok)
221
+ captureLevel = gate.level;
222
+ else
223
+ log(`! export of ${intent.id} failed: ${w.error ?? 'store refused'}`);
224
+ }
225
+ else
226
+ refuse(gate.reason);
227
+ const selection = runSelectionFactsOf(asked.selection);
228
+ const tokens = runTokensOf(asked.trace);
229
+ const sms = asked.trace?.selectionMs;
230
+ const selectionMs = typeof sms === 'number' && Number.isFinite(sms) ? Math.round(sms) : undefined;
231
+ const rawStages = asked.trace?.stages;
232
+ const rq = asked.trace?.quality;
233
+ const quality = rq && typeof rq.score === 'number' && !rq.error && rq.scores && typeof rq.scores === 'object'
234
+ ? { score: rq.score, scores: Object.fromEntries(Object.entries(rq.scores).filter(([, v]) => typeof v === 'number')) } : undefined;
235
+ const pw = asked.trace?.pairwise;
236
+ const pairwise = pw && !pw.error && pw.preference && typeof pw.preference === 'object' ? Object.fromEntries(Object.entries(pw.preference).filter(([, v]) => typeof v === 'number')) : undefined;
237
+ const oc = asked.trace?.outcomeCheck;
238
+ const outcome = oc && typeof oc.score === 'number' && !oc.error && oc.classes && typeof oc.classes === 'object' ? outcomeFactsOf(oc) : undefined;
239
+ // W1 — the judge's own failure is the GRADER's, on the record by name; the selection verdict below still stands.
240
+ const graderError = oc && oc.error ? `outcome judge: ${String(oc.error).slice(0, 200)}` : undefined;
241
+ const oa = asked.trace?.outcomeCheckAgentPlan;
242
+ const outcomeAgentPlan = oa && typeof oa.score === 'number' && !oa.error && oa.classes && typeof oa.classes === 'object' ? { score: oa.score, classes: numbersOf(oa.classes) } : undefined;
243
+ const sc = asked.trace?.stateCheck;
244
+ const stateCheck = sc && typeof sc.pass === 'boolean' && sc.classes && typeof sc.classes === 'object'
245
+ ? { pass: sc.pass, classes: Object.fromEntries(Object.entries(sc.classes).map(([k, v]) => [k, { exists: v?.exists === true, valid: v?.valid === true, errors: Array.isArray(v?.errors) ? v.errors.map(String).slice(0, 20) : [] }])) }
246
+ : undefined;
247
+ // 2026-10-15 — the rubric check off the trace, as the runtime wrote it (validated to the shape; a malformed one is an error by name).
248
+ const rc = asked.trace?.rubricCheck;
249
+ const rubric = !rc || typeof rc !== 'object' ? undefined
250
+ : typeof rc['error'] === 'string' ? { error: String(rc['error']).slice(0, 200) }
251
+ : (typeof rc['score'] === 'number' || rc['score'] === null) && rc['criteria'] && typeof rc['criteria'] === 'object'
252
+ ? { score: rc['score'], pass: typeof rc['pass'] === 'boolean' ? rc['pass'] : null, passAt: typeof rc['passAt'] === 'number' ? rc['passAt'] : 0.7, awardable: Number(rc['awardable'] ?? 0), awarded: Number(rc['awarded'] ?? 0), deducted: Number(rc['deducted'] ?? 0), cannotTell: Number(rc['cannotTell'] ?? 0), requiredFailed: Array.isArray(rc['requiredFailed']) ? rc['requiredFailed'].map(String) : [],
253
+ criteria: Object.fromEntries(Object.entries(rc['criteria']).map(([k, v]) => [k, { verdict: v?.verdict === 'met' || v?.verdict === 'not-met' ? v.verdict : 'cannot-tell', ...(typeof v?.because === 'string' ? { because: v.because.slice(0, 300) } : {}), points: Number(v?.points ?? 0), kind: v?.kind === 'deduct' ? 'deduct' : 'award', ...(v?.required === true ? { required: true } : {}) }])),
254
+ ...(typeof rc['judge'] === 'string' ? { judge: rc['judge'] } : {}), ...(typeof rc['judgeModel'] === 'string' ? { judgeModel: rc['judgeModel'] } : {}) }
255
+ : { error: 'the rubric check on the trace is not of the shape the runtime writes' };
256
+ const ag = input.actGold?.cases[intent.id];
257
+ const act = ag ? judgeAct(ag, asked.act ?? { kind: 'none' }, actStepsOf(graph)) : undefined;
258
+ const qualityMs = (rq && typeof rq.ms === 'number' ? rq.ms : 0) + (pw && typeof pw.ms === 'number' ? pw.ms : 0) + (oc && typeof oc.ms === 'number' ? oc.ms : 0);
259
+ const stages = rawStages && typeof rawStages === 'object' ? Object.fromEntries(Object.entries(rawStages).filter(([k, v]) => typeof v === 'number' && /^[a-z0-9:_.-]{1,60}$/i.test(k)).map(([k, v]) => [k, Math.round(v)])) : undefined;
260
+ // The words, if anyone asked for them, go to the keep port and nowhere else: not into the run, not into the store.
261
+ if (ports.keep)
262
+ await ports.keep({ intentId: intent.id, variant: variantName, repeat, runRef: asked.runRef, message: intent.message, ...(asked.reply ? { reply: asked.reply } : {}), provenance: graph, verdict, selected: obs.selected, ...(outcome ? { outcome } : {}), ...(quality ? { quality } : {}) }).catch((e) => log(`! keep of ${intent.id} failed: ${e instanceof Error ? e.message : String(e)}`));
263
+ const models = modelCallsOf(graph);
264
+ const result = { intentId: intent.id, variant: variantName, repeat, runRef: asked.runRef, status: 'ok', ...(graderError ? { failureCause: 'grader', graderError } : {}), selected: obs.selected, evidence: obs.evidence, ranUnder, ...(rubric ? { rubric } : {}), ...(models.length ? { models } : {}), verdict, captureLevel, ms: Date.now() - t, ...(selection ? { selection } : {}), ...(tokens ? { tokens } : {}), ...(selectionMs !== undefined ? { selectionMs } : {}), askMs: askMs - qualityMs, ...(stages && Object.keys(stages).length ? { stages } : {}), ...(quality ? { quality } : {}), ...(pairwise && Object.keys(pairwise).length ? { pairwise } : {}), ...(outcome ? { outcome } : {}), ...(outcomeAgentPlan ? { outcomeAgentPlan } : {}), ...(stateCheck ? { stateCheck } : {}), ...(act ? { act } : {}) };
265
+ log(`${verdict.earl === 'passed' ? '✓' : verdict.earl === 'failed' ? '✗' : '?'} ${variantName}#${repeat} ${intent.id} → ${verdict.outcome}${obs.selected.length ? ` (${obs.selected.join(', ')})` : ''}${act ? ` · act ${act.right ? 'right' : `WRONG (${Object.entries(act.checks).filter(([, v]) => !v).map(([k]) => k).join(', ')})`}` : ''}`);
266
+ return result;
267
+ }
268
+ const numbersOf = (m) => Object.fromEntries(Object.entries((m ?? {})).filter(([, v]) => typeof v === 'number'));
269
+ const VERDICTS = new Set(['delivered', 'missing', 'unknown']);
270
+ /** The outcome check as the record keeps it: numbers, the basis, the judge's name, and (v4) the per-class verdicts. */
271
+ function outcomeFactsOf(oc) {
272
+ const verdicts = oc.verdicts && typeof oc.verdicts === 'object' ? Object.fromEntries(Object.entries(oc.verdicts).filter(([, v]) => VERDICTS.has(v))) : undefined;
273
+ return {
274
+ score: oc.score, classes: numbersOf(oc.classes),
275
+ ...(oc.basis === 'gold-plan' || oc.basis === 'agent-plan' ? { basis: oc.basis } : {}),
276
+ ...(typeof oc.judge === 'string' ? { judge: oc.judge } : {}),
277
+ ...(verdicts && Object.keys(verdicts).length ? { verdicts } : {}),
278
+ ...(typeof oc.cantTell === 'number' ? { cantTell: oc.cantTell } : {}),
279
+ ...(typeof oc.counted === 'number' ? { counted: oc.counted } : {}),
280
+ };
281
+ }
282
+ /** W4 — whether this run was a fresh context: no recalled turns on the trace, and a door context id not seen before in
283
+ * this experiment. A seen-before id is recorded on the state as a side effect of the check (the first run under an id
284
+ * is the fresh one; the second is not). Mutates `state.seenContexts` only. */
285
+ export function isolationRefusalOf(trace, graph, state) {
286
+ const rt = trace?.recalledTurns;
287
+ const recalledTurns = typeof rt === 'number' && Number.isFinite(rt) ? rt : undefined;
288
+ const run = runActivityOf(graph);
289
+ const doorId = run?.['arrivedBy'];
290
+ const door = typeof doorId === 'string' ? (graph['graph'] ?? []).find((n) => n['id'] === doorId) : undefined;
291
+ const contextId = typeof door?.['contextId'] === 'string' ? door['contextId'] : undefined;
292
+ if (recalledTurns !== undefined && recalledTurns > 0)
293
+ return { refused: true, recalledTurns, ...(contextId ? { contextId } : {}), because: `the agent recalled ${recalledTurns} earlier turn${recalledTurns === 1 ? '' : 's'} — not a fresh context` };
294
+ if (contextId) {
295
+ state.seenContexts ??= [];
296
+ if (state.seenContexts.includes(contextId))
297
+ return { refused: true, ...(recalledTurns !== undefined ? { recalledTurns } : {}), contextId, because: `context ${contextId} already carried a run of this experiment — not a fresh context` };
298
+ state.seenContexts.push(contextId);
299
+ }
300
+ return null;
301
+ }
302
+ /** The models a run's trace says carried it: every `ModelInvocation` activity in the PROV graph, folded to one row per
303
+ * (role, provider, model) with its call count, in first-seen order. Empty when the graph names none. */
304
+ export function modelCallsOf(graph) {
305
+ const nodes = graph['graph'] ?? [];
306
+ const out = new Map();
307
+ for (const n of nodes) {
308
+ const types = Array.isArray(n['type']) ? n['type'] : [n['type']];
309
+ if (!types.includes('ModelInvocation'))
310
+ continue;
311
+ const role = String(n['invocationRole'] ?? 'unknown'), provider = String(n['modelProvider'] ?? 'unknown'), model = String(n['modelId'] ?? 'unknown');
312
+ const k = `${role}\u0000${provider}\u0000${model}`;
313
+ const row = out.get(k) ?? { role, provider, model, calls: 0 };
314
+ row.calls++;
315
+ out.set(k, row);
316
+ }
317
+ return [...out.values()];
318
+ }
319
+ /** Score every variant (stamped and inferred never pooled), gate it, compare the pairs, and write the record. */
320
+ export async function finishComparison(input, state, runs) {
321
+ const { plan, store, pseudo } = input;
322
+ const now = input.now ?? (() => new Date());
323
+ const log = input.log ?? (() => undefined);
324
+ const context = input.context ?? 'https://agenticprimitives.dev/ns/evaluation.jsonld';
325
+ const { setDigest, planDigest, startedAt, cases, skillIds, pairs } = state;
326
+ const refusals = new CaptureRefusals();
327
+ for (const [reason, n] of Object.entries(state.refusedCounts))
328
+ for (let i = 0; i < n; i++)
329
+ refusals.refuse(reason);
330
+ const { scores, verdicts, comparisons } = await scoreExperimentRuns({ plan, setDigest, cases, skillIds, pairs, runs, ...(input.scoring ? { scoring: input.scoring } : {}), log });
331
+ const record = { type: 'ap.experiment.v1', id: plan.id, planDigest, plan, startedAt, finishedAt: now().toISOString(), runs, refused: refusals.toRecord(), scores, verdicts, comparisons };
332
+ // ── 4. The record, to the store: run references pseudonymised the way the exported runs were ──
333
+ const kept = { ...record, runs: await Promise.all(runs.map(async (r) => ({ ...r, runRef: r.runRef ? await pseudo.digest(r.runRef) : null }))) };
334
+ const w = await store.put({ agent: 'experiments', key: `experiment:${plan.id}` }, { ...experimentToJsonLd(kept, { context, runIri: (ref) => `urn:ap:prov:bundle:${ref}` }), record: kept });
335
+ if (!w.ok)
336
+ log(`! the experiment record could not be written: ${w.error ?? 'store refused'}`);
337
+ return record;
338
+ }
339
+ export async function runComparison(input) {
340
+ const state = await startComparison(input);
341
+ const runs = [];
342
+ // ── 2. Dispatch: every intent × every variant × every repeat; read the trace, judge, export or refuse ──
343
+ for (const step of comparisonSteps(input.plan, state.intents))
344
+ runs.push(await runOneCase(input, state, step));
345
+ return finishComparison(input, state, runs);
346
+ }
347
+ /** A one-screen table of an experiment: per variant, the headline numbers and the gate; then each comparison. */
348
+ export function formatExperiment(rec) {
349
+ const f = (v) => (v === null || v === undefined ? ' n/a' : v.toFixed(3));
350
+ const lines = [`experiment ${rec.id} · plan ${rec.planDigest.slice(0, 18)}… · split ${rec.plan.split} · repeats ${rec.plan.repeats} · ${rec.runs.length} run(s)`];
351
+ for (const [name, s] of Object.entries(rec.scores)) {
352
+ const v = rec.verdicts[name];
353
+ const ev = rec.runs.find((r) => r.variant === name && r.status === 'ok')?.evidence ?? 'none';
354
+ lines.push(` ${name.padEnd(18)} macro TA ${f(s.aggregate.macro_ta.value)} [${f(s.aggregate.macro_ta.ci?.[0])}, ${f(s.aggregate.macro_ta.ci?.[1])}] micro ${f(s.aggregate.micro_ta.value)} hold ${f(s.aggregate.hold_rate.value)} undetected ${f(s.aggregate.undetected_rate.value)} n=${s.aggregate.n_scored} evidence=${ev} gate ${v.status} — ${v.binding_reason}`);
355
+ }
356
+ for (const name of Object.keys(rec.plan.variants))
357
+ if (!rec.scores[name])
358
+ lines.push(` ${name.padEnd(18)} not scored`);
359
+ for (const c of rec.comparisons) {
360
+ const tag = c.confounded ? `CONFOUNDED (${c.confounds.join(', ')})` : `changed: ${c.confounds.join(', ') || 'nothing'}`;
361
+ if (!c.comparison) {
362
+ lines.push(` ${c.a} → ${c.b}: ${tag}; ${c.error ?? 'no comparison'}`);
363
+ continue;
364
+ }
365
+ const k = c.comparison;
366
+ lines.push(` ${c.a} → ${c.b}: ${tag}; Δ macro ${f(k.delta_macro)} [${f(k.ci_delta?.[0])}, ${f(k.ci_delta?.[1])}]; McNemar fixed ${k.fixed} broken ${k.broken} p=${k.p_value.toFixed(4)} (${k.mcnemar_scope}, n=${k.n_paired})${k.regression ? '; REGRESSION' : k.degraded ? '; degraded' : ''}${k.warnings.length ? `; ${k.warnings.join('; ')}` : ''}`);
367
+ }
368
+ if (rec.refused.length)
369
+ lines.push(` refused: ${rec.refused.join(' · ')}`);
370
+ // W1 — what produced no number, by cause, per variant: an environment failure is the estate's, not the agent's.
371
+ for (const name of Object.keys(rec.plan.variants)) {
372
+ const f = failureSplitOf(rec.runs.filter((r) => r.variant === name));
373
+ const parts = ['agent', 'grader', 'environment', 'isolation'].filter((k) => f[k]).map((k) => `${k} ${f[k]}`);
374
+ if (parts.length)
375
+ lines.push(` ${name.padEnd(18)} no verdict: ${parts.join(' · ')}`);
376
+ }
377
+ return lines.join('\n');
378
+ }
379
+ //# sourceMappingURL=compare-runner.js.map