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

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 +370 -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 +277 -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,92 @@
1
+ import { runTruthSet } from './truth.js';
2
+ import { answered, replyKindIs, neverClaims, claimsRequire, falseEmptiness, emptinessCarriesReason, evidenceFromTool, evidenceCountAgrees, noPlaceholderLeaks } from './checks.js';
3
+ const re = (s) => new RegExp(s, 'i');
4
+ export function compileCheck(c) {
5
+ switch (c.kind) {
6
+ case 'answered': return answered();
7
+ case 'replyKindIs': return replyKindIs(c.value);
8
+ case 'neverClaims': return neverClaims(re(c.pattern), c.why);
9
+ case 'claimsRequire': return claimsRequire(re(c.claim), re(c.requires), c.why);
10
+ case 'falseEmptiness': return falseEmptiness(c.truthKey, re(c.pattern));
11
+ case 'emptinessCarriesReason': return emptinessCarriesReason();
12
+ case 'evidenceFromTool': return evidenceFromTool(c.toolId);
13
+ case 'evidenceCountAgrees': return evidenceCountAgrees(c.toolId, c.truthKey, c.slack ?? 0);
14
+ case 'noPlaceholderLeaks': return noPlaceholderLeaks();
15
+ case 'textIncludes': return (o) => (re(c.pattern).test(o.text) ? null : `the prose does not say /${c.pattern}/${c.why ? ` — ${c.why}` : ''}`);
16
+ case 'textExcludes': return (o) => (re(c.pattern).test(o.text) ? `the prose says “${o.text.match(re(c.pattern))?.[0]}”${c.why ? ` — ${c.why}` : ''}` : null);
17
+ case 'evidenceNoneFrom': return (o) => (o.evidence.some((e) => e.toolId === c.toolId) ? `evidence came from ${c.toolId}${c.why ? ` — ${c.why}` : ''}` : null);
18
+ default: {
19
+ const k = c.kind;
20
+ return () => `unknown check kind "${k}"`;
21
+ }
22
+ }
23
+ }
24
+ export function parseEvalFile(raw) {
25
+ const f = raw;
26
+ if (!f || f.version !== 1 || !Array.isArray(f.cases))
27
+ throw new Error('an eval file is { version: 1, cases: [...] }');
28
+ const ids = new Set();
29
+ for (const c of f.cases) {
30
+ if (!c || typeof c.id !== 'string' || typeof c.message !== 'string' || !Array.isArray(c.checks) || !c.checks.length)
31
+ throw new Error(`case ${String(c?.id ?? '?')}: id, message and at least one check are required`);
32
+ if (ids.has(c.id))
33
+ throw new Error(`case ${c.id} is listed twice`);
34
+ ids.add(c.id);
35
+ for (const ch of c.checks)
36
+ if (!ch || typeof ch.kind !== 'string')
37
+ throw new Error(`case ${c.id}: every check names a kind`);
38
+ }
39
+ return f;
40
+ }
41
+ export function toTruthCases(file, ask, probes) {
42
+ return file.cases.map((c) => ({
43
+ id: c.id,
44
+ incident: c.incident ?? '',
45
+ question: c.message,
46
+ probes: { ...Object.fromEntries(Object.entries(c.truth ?? {}).map(([k, v]) => [k, async () => v])), ...(probes ? probes(c) : {}) },
47
+ run: () => ask(c),
48
+ checks: c.checks.map(compileCheck),
49
+ }));
50
+ }
51
+ export async function runEvalFile(file, ask, probes) {
52
+ return runTruthSet(toTruthCases(file, ask, probes));
53
+ }
54
+ /** Normalise a `/harness/ask` reply the way the truth set reads one (the kit's binding uses this). */
55
+ export function outcomeOfReply(rep) {
56
+ const req = rep.requirement;
57
+ const prompt = rep.prompt;
58
+ return {
59
+ kind: String(rep.kind ?? 'error'),
60
+ text: String(rep.text ?? rep.error ?? rep.summary ?? ''),
61
+ // A composed answer says how it knows (`evidence`); a supplied plan's reply carries its steps' `results` — the
62
+ // same fact for the judge: which tool the answer came from, and what it counted.
63
+ evidence: Array.isArray(rep.evidence) && rep.evidence.length ? rep.evidence : (Array.isArray(rep.results) ? rep.results.filter((r) => typeof r.toolId === 'string').map((r) => ({ toolId: r.toolId, ...(typeof r.result?.count === 'number' ? { count: r.result.count } : {}), ...(typeof r.result?.refused === 'string' ? { reason: r.result.refused } : {}) })) : []),
64
+ ...(req?.limits ? { requirementLimits: req.limits } : {}),
65
+ ...(prompt?.fields ? { promptFields: prompt.fields.map((f) => String(f.name ?? '')) } : {}),
66
+ raw: rep,
67
+ };
68
+ }
69
+ /** DATASETS FROM LIVE RUNS: the runs an agent recorded become case SKELETONS — the message and the kind it answered
70
+ * with, as a `replyKindIs` check to keep, and the tools its evidence came from, as `evidenceFromTool` checks. A person
71
+ * edits the file; nothing here judges. */
72
+ export function casesFromRunRecords(records, opts = {}) {
73
+ const cases = [];
74
+ for (const r of records.slice(0, opts.max ?? 50)) {
75
+ const message = r.intent?.goal?.trim();
76
+ if (!message)
77
+ continue;
78
+ if (r.canceled)
79
+ continue; // a run the person stopped is not a property to hold
80
+ const kind = r.kind ?? (r.outcome === 'completed' || r.outcome === 'done' ? 'answer' : r.outcome === 'authority_required' || r.outcome === 'awaiting-authority' ? 'authority_required' : undefined);
81
+ const tools = [...new Set([...(r.evidence ?? []).map((e) => e.toolId), ...(Array.isArray(r.steps) ? r.steps.map((s) => s.toolId) : [])].filter((t) => !!t))];
82
+ cases.push({
83
+ id: r.runRef ?? `run-${cases.length + 1}`,
84
+ incident: `from a live run${r.runRef ? ` (${r.runRef})` : ''} — edit the checks to what must hold`,
85
+ ...(opts.persona ? { persona: opts.persona } : {}), ...(opts.addressee ? { addressee: opts.addressee } : {}),
86
+ message,
87
+ checks: [...(kind ? [{ kind: 'replyKindIs', value: kind }] : [{ kind: 'answered' }]), ...tools.slice(0, 3).map((toolId) => ({ kind: 'evidenceFromTool', toolId })), { kind: 'noPlaceholderLeaks' }],
88
+ });
89
+ }
90
+ return { version: 1, name: 'from live runs', cases };
91
+ }
92
+ //# sourceMappingURL=eval-file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eval-file.js","sourceRoot":"","sources":["../src/eval-file.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,WAAW,EAAE,aAAa,EAAE,cAAc,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAkCnL,MAAM,EAAE,GAAG,CAAC,CAAS,EAAU,EAAE,CAAC,IAAI,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AACrD,MAAM,UAAU,YAAY,CAAC,CAAc;IACzC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;QACf,KAA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AE,CAAC,EAAE,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC5G,OAAO;YACP,MAAM,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,aAAsB,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,UAAmB,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,kBAA2B,EAAE,MAAM,EAAE,CAAC,CAAC,EAAE,EAAE,IAAI,EAAE,oBAA6B,EAAE,CAAC;SACxO,CAAC,CAAC;IACL,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,CAAC;AACvD,CAAC"}
@@ -0,0 +1,277 @@
1
+ import type { SelectionVerdictV1 } from './selection.js';
2
+ import type { SelectionScoreV1, SelectionVerdictReportV1, SelectionComparisonV1, SelectionThresholdsV1, SelectionRowV1 } from './selection-score.js';
3
+ import type { CaptureLevelV1 } from './capture.js';
4
+ /** What a run may be asked to differ in — the knob `/harness/ask` accepts on a development estate (A4). Every field
5
+ * is one COMPONENT of the variant; a request the estate does not know is refused, never ignored. */
6
+ export interface VariantRequestV1 {
7
+ /** model (the deployment's planner) | rule-based. */
8
+ plannerKind?: 'model' | 'rule-based';
9
+ /** How instruction skills are selected: `model` over the descriptions, `declared` by the contracts' utterances (holds). */
10
+ selection?: 'model' | 'declared' | 'ontology' | 'judgment' | 'ontology+judgment' | 'propose+judgment' | 'ontology-first' | 'framed-judgment' | 'outcome' | 'outcome-selective';
11
+ /** A provider the estate offers (`groq`, `anthropic`, …) — the one every role runs on unless a role names its own. */
12
+ provider?: string;
13
+ /** PER-AREA PROVIDERS (2026-10-01). A comparison may put a different provider on each of the three model roles —
14
+ * the SELECTOR (the planner and the selection judge), the ANSWER (an instruction skill's answer, the pairwise's
15
+ * second answer) and the JUDGE (quality, outcome and pairwise judges) — so "answered with Gemini, judged with Claude"
16
+ * is one variant and the confound it carries is named. Each falls back to `provider`, then the deployment default. */
17
+ selectionProvider?: string;
18
+ answerProvider?: string;
19
+ judgeProvider?: string;
20
+ /** Spec 434 §12 — who carries the model call: the town's gateway (`on`, the deployment's default) or the deployment's own provider (`off`). */
21
+ gateway?: 'on' | 'off';
22
+ /** Harness-capability toggles by notation (`retrieval/kb` → off | tool | playbook). */
23
+ toggles?: Record<string, string>;
24
+ /** The playbook this run must run under, by definition digest — refused when the agent's playbook differs. */
25
+ playbook?: string;
26
+ /** The seeded records the run begins from (a comparison's fixture). */
27
+ startingState?: {
28
+ domain: string;
29
+ scenarioId: string;
30
+ digest: string;
31
+ };
32
+ /** Spec 416 W3 — acceptance by a fitted conformal map (inline, cited by digest). */
33
+ acceptance?: {
34
+ method: 'conformal';
35
+ alpha: number;
36
+ temperature: number;
37
+ qhat: number;
38
+ mapDigest: string;
39
+ };
40
+ /** Spec 416 — the judge's profile (`fast`: one call, one question, the provider's light model). */
41
+ judgeProfile?: 'thorough' | 'fast' | 'logprob';
42
+ /** Spec 416 §4h — a seeded asker context (set per run by the runner from an intent's starting state). */
43
+ askerContext?: {
44
+ digest: string;
45
+ recentSkills?: Array<{
46
+ id: string;
47
+ times: number;
48
+ }>;
49
+ memoryTags?: string[];
50
+ heldClasses?: string[];
51
+ };
52
+ }
53
+ export declare const variantRequestDigest: (v: VariantRequestV1) => Promise<`sha256:${string}`>;
54
+ export declare const thresholdsDigest: (t: SelectionThresholdsV1) => Promise<`sha256:${string}`>;
55
+ /** The components two variant requests differ in. One ⇒ a clean comparison; more ⇒ confounded (spec 414 §7). */
56
+ export declare function confoundsOf(a: VariantRequestV1, b: VariantRequestV1): string[];
57
+ export interface ExperimentPlanV1 {
58
+ type: 'ap.experiment-plan.v1';
59
+ id: string;
60
+ replaySetDigest: string;
61
+ criterionDigest: string;
62
+ split: 'development' | 'held-out' | 'all';
63
+ repeats: number;
64
+ variants: Record<string, VariantRequestV1>;
65
+ thresholds: SelectionThresholdsV1;
66
+ /** Skill-selection observation policy. */
67
+ policy?: 'primary' | 'any-fire';
68
+ registeredAt: string;
69
+ }
70
+ /** The plan's identity: its COMPONENTS — set, criterion, split, repeats, variants, thresholds, policy. The moment of
71
+ * registration is not one of them (the same plan registered twice is the same plan; a changed component is a new plan). */
72
+ export declare const experimentPlanDigest: (p: ExperimentPlanV1) => Promise<`sha256:${string}`>;
73
+ export declare function validateExperimentPlan(raw: unknown): {
74
+ ok: true;
75
+ plan: ExperimentPlanV1;
76
+ } | {
77
+ ok: false;
78
+ errors: string[];
79
+ };
80
+ export declare function experimentPlan(input: Omit<ExperimentPlanV1, 'type' | 'thresholds' | 'registeredAt'> & {
81
+ thresholds?: SelectionThresholdsV1;
82
+ registeredAt?: string;
83
+ }): ExperimentPlanV1;
84
+ export type FailureCauseV1 = 'agent' | 'grader' | 'environment';
85
+ /** The declared rule from an error's words to its cause. Ordered: the grader's own failures first (a judge that timed
86
+ * out is still the grader's), then the environment's signatures, else the agent. Pure; the same text gives the same
87
+ * cause. Unknown wording is the AGENT's — an unexplained failure must not quietly leave the agent's denominator. */
88
+ export declare function failureCauseOf(error: string | undefined | null): FailureCauseV1;
89
+ /** Per-class verdict of the outcome judge (v4, one call per class): delivered · missing · unknown (= earl:cantTell). */
90
+ export type OutcomeVerdictV1 = 'delivered' | 'missing' | 'unknown';
91
+ /** One dispatched run, as the record keeps it. */
92
+ export interface ExperimentRunV1 {
93
+ intentId: string;
94
+ variant: string;
95
+ repeat: number;
96
+ /** The run reference (pseudonymised in the eval store). */
97
+ runRef: string | null;
98
+ status: 'ok' | 'failed' | 'unreadable';
99
+ /** WHY, when `status` is not `ok` — or when the run is `ok` but its GRADER failed (`graderError`): agent · grader ·
100
+ * environment. Only `agent` stays in the agent's denominator; the other two are counted beside it (W1). */
101
+ failureCause?: FailureCauseV1;
102
+ /** The outcome/quality judge's own failure on an otherwise complete run (cause `grader`): the selection verdict stands,
103
+ * the outcome number is absent and says why. */
104
+ graderError?: string;
105
+ /** W4 ISOLATION — a repeat the harness REFUSED TO SCORE because it was not a fresh context: the agent recalled earlier
106
+ * turns (`recalledTurns > 0`) or the run arrived under a context id another run of this experiment already used.
107
+ * Recorded, never scored (`status: 'unreadable'`, cause `environment`). */
108
+ isolation?: {
109
+ refused: true;
110
+ recalledTurns?: number;
111
+ contextId?: string;
112
+ because: string;
113
+ };
114
+ /** What the trace said was selected (canonical skill ids after mapping; tool ids when unmapped). */
115
+ selected: string[];
116
+ evidence: 'stamped' | 'inferred' | 'none';
117
+ /** The variant the run ACTUALLY ran under, from its trace — a mismatch with the request is a finding. */
118
+ ranUnder?: {
119
+ variantDigest?: string;
120
+ plannerKind?: string;
121
+ toggles?: string[];
122
+ } | null;
123
+ /** WHICH MODEL CARRIED EACH ROLE, from the trace's ModelInvocation activities (2026-10-01): a run that names no provider
124
+ * goes to the deployment's default, and the variant digest does not change when the provider does — so without this
125
+ * a record cannot say whether it ran on Gemini or Claude. One row per (role, provider, model) with the call count. */
126
+ models?: Array<{
127
+ role: string;
128
+ provider: string;
129
+ model: string;
130
+ calls: number;
131
+ }>;
132
+ verdict?: SelectionVerdictV1;
133
+ /** The level the run was exported at, or null when the firewall refused (the reason is counted on the record). */
134
+ captureLevel: CaptureLevelV1 | null;
135
+ /** What the run's model calls used, as providers REPORTED it: the selection (the model planner's or the judge's calls)
136
+ * and the whole run; `unreported` counts calls that reported nothing (so a total is never read as complete when it
137
+ * is not). Numbers only. */
138
+ tokens?: RunTokensV1;
139
+ /** Milliseconds the harness spent CHOOSING (the planner's call or the selection arm), apart from the whole ask. */
140
+ selectionMs?: number;
141
+ /** Milliseconds until the reply arrived (`ms` also counts reading the run back for judging). */
142
+ askMs?: number;
143
+ /** Milliseconds per runtime stage of the ask (stage names and numbers only). */
144
+ stages?: Record<string, number>;
145
+ /** Spec 416 §4h — the answer's quality by the rubric (P(true) per question and their mean); numbers only. */
146
+ quality?: {
147
+ score: number;
148
+ scores: Record<string, number>;
149
+ };
150
+ /** Spec 416 §4h — the two answers judged side by side: probability per answer id (and `tie`). */
151
+ pairwise?: Record<string, number>;
152
+ /** Spec 418 A2 — the outcome check: did the answer deliver each class the plan was for (mean P, and per class).
153
+ * W2/W4 (2026-10-14): `basis` says WHOSE plan the expected classes came from — the pre-registered GOLD plan (the
154
+ * expert's) or the AGENT's own plan (the only basis before W2); `judge` names the instrument; under the per-class judge
155
+ * (v4) `verdicts` carries each class's delivered · missing · unknown, `cantTell` how many were unknown (out of the
156
+ * denominator, counted), `counted` how many classes the score is over. */
157
+ outcome?: {
158
+ score: number;
159
+ classes: Record<string, number>;
160
+ basis?: 'gold-plan' | 'agent-plan';
161
+ judge?: string;
162
+ verdicts?: Record<string, OutcomeVerdictV1>;
163
+ cantTell?: number;
164
+ counted?: number;
165
+ };
166
+ /** W2 — the SECOND number: the same answer judged against the AGENT's plan when the gold plan scored it. A gap between
167
+ * the two is "wrong plan" (gold low, agent-plan high) vs "thin answer under the right plan" (both low). */
168
+ outcomeAgentPlan?: {
169
+ score: number;
170
+ classes: Record<string, number>;
171
+ };
172
+ /** W3 — THE OUTCOME IS STATE: per gold-plan produced class, whether a record of it exists in the vault after the run
173
+ * and whether it validates against its SHACL shape (required fields). `pass` = every class exists and is valid. */
174
+ stateCheck?: {
175
+ pass: boolean;
176
+ classes: Record<string, {
177
+ exists: boolean;
178
+ valid: boolean;
179
+ errors: string[];
180
+ }>;
181
+ };
182
+ /** Spec 418 §12 — the act laboratory: did the harness reach THE act asked for (capability, parties, amount, whose
183
+ * authority) and leave its receipt — every check by name, booleans only. */
184
+ act?: import('./act.js').ActVerdictV1;
185
+ ms?: number;
186
+ error?: string;
187
+ /** Spec 415 A4 — what the selection arm decided (its grounding, survivors, distribution) — what the gates read. */
188
+ selection?: import('./selection-gates.js').RunSelectionFactsV1;
189
+ }
190
+ export interface ExperimentRecordV1 {
191
+ type: 'ap.experiment.v1';
192
+ id: string;
193
+ planDigest: string;
194
+ plan: ExperimentPlanV1;
195
+ startedAt: string;
196
+ finishedAt: string;
197
+ runs: ExperimentRunV1[];
198
+ /** `capture.refused.<reason>=<n>` */
199
+ refused: string[];
200
+ scores: Record<string, SelectionScoreV1>;
201
+ verdicts: Record<string, SelectionVerdictReportV1>;
202
+ comparisons: Array<{
203
+ a: string;
204
+ b: string;
205
+ confounds: string[];
206
+ confounded: boolean;
207
+ comparison: SelectionComparisonV1 | null;
208
+ error?: string;
209
+ }>;
210
+ }
211
+ /** The scorer's rows for one variant: the first repeat is Stage 1, every later repeat a Stage-2 trial. A run whose
212
+ * trace could not be read is a row with `readActivity: false` (undetected — never a miss). */
213
+ export declare function selectionRowsOf(runs: readonly ExperimentRunV1[], variant: string): SelectionRowV1[];
214
+ /** The plan as JSON-LD (`apeval:ExperimentPlan`, a p-plan:Plan): digests only. */
215
+ export declare function experimentPlanToJsonLd(plan: ExperimentPlanV1, opts: {
216
+ context: Record<string, unknown> | string;
217
+ }): Promise<Record<string, unknown>>;
218
+ /** The experiment as JSON-LD (`apeval:Experiment`, a prov:Activity that used the plan and every run's bundle). */
219
+ export declare function experimentToJsonLd(rec: ExperimentRecordV1, opts: {
220
+ context: Record<string, unknown> | string;
221
+ runIri: (runRef: string) => string;
222
+ }): Record<string, unknown>;
223
+ export interface RunTokensV1 {
224
+ selectionIn: number;
225
+ selectionOut: number;
226
+ totalIn: number;
227
+ totalOut: number;
228
+ calls: number;
229
+ unreported: number; /** Input served from the provider's prompt cache, where it said so. */
230
+ cachedIn?: number; /** Steps the plan had (a turn's work, apart from model calls). */
231
+ planSteps?: number;
232
+ }
233
+ /** A run's reported usage from its planner trace: the planner and judge calls are SELECTION; everything is TOTAL. */
234
+ export declare function runTokensOf(trace: unknown): RunTokensV1 | undefined;
235
+ /** W1 — how many runs produced no verdict, by cause. A refused repeat (W4 isolation) is its own column. Pure. */
236
+ export declare function failureSplitOf(runs: ReadonlyArray<ExperimentRunV1>): Partial<Record<FailureCauseV1 | 'isolation', number>>;
237
+ export interface ScorecardRowV1 {
238
+ experiment: string;
239
+ variant: string;
240
+ runs: number;
241
+ right: number;
242
+ positives: number;
243
+ rightOnPositives: number;
244
+ negatives: number;
245
+ declined: number;
246
+ askP50: number | null;
247
+ askP90: number | null;
248
+ pickP50: number | null;
249
+ selectionIn: number | null;
250
+ selectionOut: number | null;
251
+ totalIn: number | null;
252
+ totalOut: number | null;
253
+ cachedIn: number | null;
254
+ modelCalls: number | null;
255
+ planSteps: number | null;
256
+ unreported: number;
257
+ /** Median milliseconds per runtime stage, for stages present in at least half the runs, slowest first. */
258
+ stagesP50: Record<string, number>;
259
+ /** Spec 416 §4h — mean answer quality over the runs that were scored, and how many were. */
260
+ quality: number | null;
261
+ qualityRuns: number;
262
+ /** Mean side-by-side preference over the runs that were compared (`default` · `light` · `tie`). */
263
+ preference: Record<string, number> | null;
264
+ preferenceRuns: number;
265
+ /** W1 — the runs that produced no verdict, by cause (`isolation` is the refused repeats of W4). Absent keys are 0. */
266
+ failed?: Partial<Record<FailureCauseV1 | 'isolation', number>>;
267
+ /** Spec 418 A2 / W2 — mean outcome score over the runs the judge scored, how many, and how many classes were cantTell. */
268
+ outcome?: {
269
+ mean: number;
270
+ runs: number;
271
+ cantTell: number;
272
+ };
273
+ }
274
+ export declare function scorecardOf(experiments: ReadonlyArray<Pick<ExperimentRecordV1, 'id' | 'runs'>>, criteria: Record<string, {
275
+ expected: string | null;
276
+ }>): ScorecardRowV1[];
277
+ //# sourceMappingURL=experiment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"experiment.d.ts","sourceRoot":"","sources":["../src/experiment.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAA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AAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;CAC5D;AAGD,wBAAgB,WAAW,CAAC,WAAW,EAAE,aAAa,CAAC,IAAI,CAAC,kBAAkB,EAAE,IAAI,GAAG,MAAM,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE;IAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC,GAAG,cAAc,EAAE,CA+BxK"}
@@ -0,0 +1,237 @@
1
+ // EXPERIMENTS — spec 414 §7 / 415 A4 + SEL-3. A comparison is PRE-REGISTERED: the plan fixes the replay set, the
2
+ // criterion, the variants and the thresholds BY DIGEST before the first run, and scoring refuses across them. Two
3
+ // variants that differ in more than one component are CONFOUNDED — the plan says so, and the comparison is labelled,
4
+ // never read as a lift (change one thing). The experiment record is what the eval store keeps: every run by
5
+ // pseudonymised reference, every judgment, the scores, the gate, the comparisons, and what the firewall refused.
6
+ import { canonicalJson } from './canonical.js';
7
+ import { DEFAULT_SELECTION_THRESHOLDS } from './selection-score.js';
8
+ const sha256 = async (s) => {
9
+ const b = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)));
10
+ return `sha256:${Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')}`;
11
+ };
12
+ export const variantRequestDigest = (v) => sha256(canonicalJson(v));
13
+ export const thresholdsDigest = (t) => sha256(canonicalJson(t));
14
+ /** The components two variant requests differ in. One ⇒ a clean comparison; more ⇒ confounded (spec 414 §7). */
15
+ export function confoundsOf(a, b) {
16
+ const out = [];
17
+ if ((a.plannerKind ?? 'model') !== (b.plannerKind ?? 'model'))
18
+ out.push('plannerKind');
19
+ if ((a.selection ?? 'model') !== (b.selection ?? 'model'))
20
+ out.push('selection');
21
+ if ((a.provider ?? '') !== (b.provider ?? ''))
22
+ out.push('provider');
23
+ for (const role of ['selectionProvider', 'answerProvider', 'judgeProvider'])
24
+ if ((a[role] ?? '') !== (b[role] ?? ''))
25
+ out.push(role);
26
+ if ((a.playbook ?? '') !== (b.playbook ?? ''))
27
+ out.push('playbook');
28
+ if (canonicalJson(a.startingState ?? null) !== canonicalJson(b.startingState ?? null))
29
+ out.push('startingState');
30
+ // Spec 416 W3 — the acceptance rule is a component (a missing one here once read "changed: nothing" for floor/margin
31
+ // against a conformal map).
32
+ if (canonicalJson(a.acceptance ?? null) !== canonicalJson(b.acceptance ?? null))
33
+ out.push('acceptance');
34
+ if ((a.judgeProfile ?? 'thorough') !== (b.judgeProfile ?? 'thorough'))
35
+ out.push('judgeProfile');
36
+ for (const k of new Set([...Object.keys(a.toggles ?? {}), ...Object.keys(b.toggles ?? {})]))
37
+ if ((a.toggles?.[k] ?? '') !== (b.toggles?.[k] ?? ''))
38
+ out.push(`toggles/${k}`);
39
+ return out.sort();
40
+ }
41
+ /** The plan's identity: its COMPONENTS — set, criterion, split, repeats, variants, thresholds, policy. The moment of
42
+ * registration is not one of them (the same plan registered twice is the same plan; a changed component is a new plan). */
43
+ export const experimentPlanDigest = (p) => { const { registeredAt: _t, ...rest } = p; return sha256(canonicalJson(rest)); };
44
+ export function validateExperimentPlan(raw) {
45
+ const p = raw;
46
+ const errors = [];
47
+ if (!p || p.type !== 'ap.experiment-plan.v1')
48
+ return { ok: false, errors: ['an experiment plan is { type: "ap.experiment-plan.v1", id, replaySetDigest, criterionDigest, split, repeats, variants, thresholds, registeredAt }'] };
49
+ if (typeof p.id !== 'string' || !p.id)
50
+ errors.push('id required');
51
+ for (const k of ['replaySetDigest', 'criterionDigest'])
52
+ if (typeof p[k] !== 'string' || !/^sha256:[0-9a-f]{64}$/.test(p[k]))
53
+ errors.push(`${k} must be a sha256: digest`);
54
+ if (!['development', 'held-out', 'all'].includes(String(p.split)))
55
+ errors.push('split must be development | held-out | all');
56
+ if (!Number.isInteger(p.repeats) || p.repeats < 1)
57
+ errors.push('repeats must be an integer ≥ 1');
58
+ const names = Object.keys(p.variants ?? {});
59
+ if (!names.length)
60
+ errors.push('at least one variant required');
61
+ for (const n of names) {
62
+ const v = p.variants[n];
63
+ if (v.plannerKind !== undefined && v.plannerKind !== 'model' && v.plannerKind !== 'rule-based')
64
+ errors.push(`variants.${n}.plannerKind must be model | rule-based`);
65
+ if (v.selection !== undefined && !['model', 'declared', 'ontology', 'judgment', 'ontology+judgment', 'propose+judgment', 'ontology-first', 'framed-judgment', 'outcome', 'outcome-selective'].includes(v.selection))
66
+ errors.push(`variants.${n}.selection must be model | declared | ontology | judgment | ontology+judgment | propose+judgment | ontology-first | framed-judgment`);
67
+ for (const role of ['provider', 'selectionProvider', 'answerProvider', 'judgeProvider'])
68
+ if (v[role] !== undefined && (typeof v[role] !== 'string' || !/^[a-z][a-z0-9-]{1,30}$/.test(v[role])))
69
+ errors.push(`variants.${n}.${role} must be a provider name`);
70
+ // Spec 434 §12 — `gateway: on | off` is a variant component the runtime admits (who carries the model call); the plan
71
+ // validator refused it (2026-10-15), which left the one arm that answers in full unregisterable.
72
+ if (v.gateway !== undefined && v.gateway !== 'on' && v.gateway !== 'off')
73
+ errors.push(`variants.${n}.gateway must be on | off`);
74
+ for (const k of Object.keys(v))
75
+ if (!['plannerKind', 'selection', 'provider', 'selectionProvider', 'answerProvider', 'judgeProvider', 'gateway', 'toggles', 'playbook', 'startingState', 'acceptance', 'judgeProfile', 'askerContext'].includes(k))
76
+ errors.push(`variants.${n}.${k}: not a variant component`);
77
+ }
78
+ if (!p.thresholds || typeof p.thresholds !== 'object')
79
+ errors.push('thresholds required (DEFAULT_SELECTION_THRESHOLDS when nothing is pre-registered)');
80
+ if (typeof p.registeredAt !== 'string' || Number.isNaN(Date.parse(p.registeredAt)))
81
+ errors.push('registeredAt must be an ISO date-time');
82
+ return errors.length ? { ok: false, errors } : { ok: true, plan: p };
83
+ }
84
+ export function experimentPlan(input) {
85
+ return { type: 'ap.experiment-plan.v1', ...input, thresholds: input.thresholds ?? DEFAULT_SELECTION_THRESHOLDS, registeredAt: input.registeredAt ?? new Date().toISOString() };
86
+ }
87
+ /** The declared rule from an error's words to its cause. Ordered: the grader's own failures first (a judge that timed
88
+ * out is still the grader's), then the environment's signatures, else the agent. Pure; the same text gives the same
89
+ * cause. Unknown wording is the AGENT's — an unexplained failure must not quietly leave the agent's denominator. */
90
+ export function failureCauseOf(error) {
91
+ const e = String(error ?? '').toLowerCase();
92
+ if (!e)
93
+ return 'agent';
94
+ if (/\b(judge|grader|outcome check|quality check|state check)\b/.test(e))
95
+ return 'grader';
96
+ if (/isolation:/.test(e))
97
+ return 'environment';
98
+ if (/\b(timeout|timed out|etimedout|econn\w*|enotfound|fetch failed|network|socket hang up|rate.?limit|overloaded|store refused|durable object|graphdb|\bkv\b|vault|provenance could not be read|unreadable|the ask threw|the case threw|was lost|not among the fixtures|does not match its pinned digest|no model is available)\b/.test(e))
99
+ return 'environment';
100
+ if (/\b(provider|http)\b.*\b(402|429|5\d\d)\b|\b(402|429|5\d\d)\b.*\b(provider|http|answered)\b|answered 5\d\d/.test(e))
101
+ return 'environment';
102
+ return 'agent';
103
+ }
104
+ /** The scorer's rows for one variant: the first repeat is Stage 1, every later repeat a Stage-2 trial. A run whose
105
+ * trace could not be read is a row with `readActivity: false` (undetected — never a miss). */
106
+ export function selectionRowsOf(runs, variant) {
107
+ return runs.filter((r) => r.variant === variant).map((r) => ({
108
+ caseId: r.intentId, trial: r.repeat, stage: r.repeat === 0 ? 1 : 2,
109
+ fired: r.status === 'ok' ? r.selected.map((skill) => ({ skill, tier: r.evidence })) : [],
110
+ readActivity: r.status === 'ok',
111
+ }));
112
+ }
113
+ /** The plan as JSON-LD (`apeval:ExperimentPlan`, a p-plan:Plan): digests only. */
114
+ export async function experimentPlanToJsonLd(plan, opts) {
115
+ const digests = await Promise.all(Object.entries(plan.variants).map(async ([n, v]) => [n, await variantRequestDigest(v)]));
116
+ const names = Object.keys(plan.variants);
117
+ const confounded = names.some((a, i) => names.slice(i + 1).some((b) => confoundsOf(plan.variants[a], plan.variants[b]).length > 1));
118
+ return {
119
+ '@context': opts.context,
120
+ id: `urn:ap:experiment-plan:${plan.id}`,
121
+ type: ['Entity', 'Plan', 'ExperimentPlan'],
122
+ replaySetDigest: plan.replaySetDigest,
123
+ criterionDigest: plan.criterionDigest,
124
+ thresholdsDigest: await thresholdsDigest(plan.thresholds),
125
+ variantDigest: digests.map(([, d]) => d),
126
+ split: plan.split,
127
+ repeats: plan.repeats,
128
+ confounded,
129
+ startedAtTime: plan.registeredAt,
130
+ };
131
+ }
132
+ /** The experiment as JSON-LD (`apeval:Experiment`, a prov:Activity that used the plan and every run's bundle). */
133
+ export function experimentToJsonLd(rec, opts) {
134
+ return {
135
+ '@context': opts.context,
136
+ id: `urn:ap:experiment:${rec.id}`,
137
+ type: ['Activity', 'Experiment'],
138
+ planDigest: rec.planDigest,
139
+ used: [`urn:ap:experiment-plan:${rec.plan.id}`],
140
+ hasRun: rec.runs.filter((r) => r.runRef && r.captureLevel).map((r) => opts.runIri(r.runRef)),
141
+ refusedCount: rec.refused,
142
+ startedAtTime: rec.startedAt,
143
+ endedAtTime: rec.finishedAt,
144
+ };
145
+ }
146
+ /** A run's reported usage from its planner trace: the planner and judge calls are SELECTION; everything is TOTAL. */
147
+ export function runTokensOf(trace) {
148
+ const t = trace;
149
+ if (!t || typeof t !== 'object')
150
+ return undefined;
151
+ const out = { selectionIn: 0, selectionOut: 0, totalIn: 0, totalOut: 0, calls: 0, unreported: 0 };
152
+ const add = (u, selection) => {
153
+ out.calls++;
154
+ if (!u || typeof u.tokensIn !== 'number') {
155
+ out.unreported++;
156
+ return;
157
+ }
158
+ out.totalIn += u.tokensIn;
159
+ out.totalOut += u.tokensOut ?? 0;
160
+ if (typeof u.cachedIn === 'number')
161
+ out.cachedIn = (out.cachedIn ?? 0) + u.cachedIn;
162
+ if (selection) {
163
+ out.selectionIn += u.tokensIn;
164
+ out.selectionOut += u.tokensOut ?? 0;
165
+ }
166
+ };
167
+ if (t.plannerUsage)
168
+ add(t.plannerUsage, true);
169
+ for (const c of t.structuredCalls ?? [])
170
+ add(c, c.role === 'judge');
171
+ if (t.composeUsage || t.route?.composer?.provider)
172
+ add(t.composeUsage, false);
173
+ if (Array.isArray(t.plan))
174
+ out.planSteps = t.plan.length;
175
+ return out.calls ? out : undefined;
176
+ }
177
+ /** W1 — how many runs produced no verdict, by cause. A refused repeat (W4 isolation) is its own column. Pure. */
178
+ export function failureSplitOf(runs) {
179
+ const out = {};
180
+ const bump = (k) => { out[k] = (out[k] ?? 0) + 1; };
181
+ for (const r of runs) {
182
+ if (r.isolation?.refused) {
183
+ bump('isolation');
184
+ continue;
185
+ }
186
+ if (r.status !== 'ok') {
187
+ bump(r.failureCause ?? (r.status === 'unreadable' ? 'environment' : failureCauseOf(r.error)));
188
+ continue;
189
+ }
190
+ if (r.graderError)
191
+ bump('grader');
192
+ }
193
+ return out;
194
+ }
195
+ const pct = (xs, q) => { if (!xs.length)
196
+ return null; const a = [...xs].sort((x, y) => x - y); return a[Math.min(a.length - 1, Math.floor(q * a.length))]; };
197
+ const mean = (xs) => (xs.length ? Math.round((xs.reduce((a, b) => a + b, 0) / xs.length) * 10) / 10 : null);
198
+ export function scorecardOf(experiments, criteria) {
199
+ const rows = [];
200
+ for (const e of experiments) {
201
+ const names = [...new Set(e.runs.map((r) => r.variant))];
202
+ for (const v of names) {
203
+ const rs = e.runs.filter((r) => r.variant === v);
204
+ const ok = (r) => r.verdict?.earl === 'passed';
205
+ const pos = rs.filter((r) => criteria[r.intentId]?.expected);
206
+ const neg = rs.filter((r) => criteria[r.intentId] && !criteria[r.intentId].expected);
207
+ const tk = rs.map((r) => r.tokens).filter((x) => !!x);
208
+ rows.push({ experiment: e.id, variant: v, runs: rs.length,
209
+ right: rs.filter(ok).length, positives: pos.length, rightOnPositives: pos.filter(ok).length, negatives: neg.length, declined: neg.filter(ok).length,
210
+ askP50: pct(rs.map((r) => r.askMs ?? r.ms).filter((x) => typeof x === 'number'), 0.5), askP90: pct(rs.map((r) => r.askMs ?? r.ms).filter((x) => typeof x === 'number'), 0.9),
211
+ pickP50: pct(rs.map((r) => r.selectionMs).filter((x) => typeof x === 'number'), 0.5),
212
+ selectionIn: mean(tk.map((t) => t.selectionIn)), selectionOut: mean(tk.map((t) => t.selectionOut)), totalIn: mean(tk.map((t) => t.totalIn)), totalOut: mean(tk.map((t) => t.totalOut)),
213
+ cachedIn: tk.some((t) => t.cachedIn !== undefined) ? mean(tk.map((t) => t.cachedIn ?? 0)) : null,
214
+ modelCalls: mean(tk.map((t) => t.calls)), planSteps: tk.some((t) => t.planSteps !== undefined) ? mean(tk.map((t) => t.planSteps ?? 0)) : null,
215
+ unreported: tk.reduce((n, t) => n + t.unreported, 0),
216
+ quality: (() => { const q = rs.map((r) => r.quality?.score).filter((x) => typeof x === 'number'); return q.length ? Math.round((q.reduce((a, b) => a + b, 0) / q.length) * 1000) / 1000 : null; })(),
217
+ qualityRuns: rs.filter((r) => typeof r.quality?.score === 'number').length,
218
+ preference: (() => { const ps = rs.map((r) => r.pairwise).filter((x) => !!x); if (!ps.length)
219
+ return null; const keys = [...new Set(ps.flatMap((p) => Object.keys(p)))]; return Object.fromEntries(keys.map((k) => [k, Math.round((ps.reduce((a, p) => a + (p[k] ?? 0), 0) / ps.length) * 1000) / 1000])); })(),
220
+ preferenceRuns: rs.filter((r) => !!r.pairwise).length,
221
+ ...(() => { const f = failureSplitOf(rs); return Object.keys(f).length ? { failed: f } : {}; })(),
222
+ ...(() => { const o = rs.map((r) => r.outcome).filter((x) => !!x); return o.length ? { outcome: { mean: Math.round((o.reduce((a, x) => a + x.score, 0) / o.length) * 1000) / 1000, runs: o.length, cantTell: o.reduce((a, x) => a + (x.cantTell ?? 0), 0) } } : {}; })(),
223
+ stagesP50: (() => {
224
+ const names = new Map();
225
+ for (const r of rs)
226
+ for (const [k, v] of Object.entries(r.stages ?? {})) {
227
+ const l = names.get(k) ?? [];
228
+ l.push(v);
229
+ names.set(k, l);
230
+ }
231
+ return Object.fromEntries([...names.entries()].filter(([, l]) => l.length * 2 >= rs.length).map(([k, l]) => [k, pct(l, 0.5)]).sort((a, b) => b[1] - a[1]));
232
+ })() });
233
+ }
234
+ }
235
+ return rows;
236
+ }
237
+ //# sourceMappingURL=experiment.js.map