@agentswf/lab 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +15 -2
  3. package/package.json +46 -4
  4. package/schema/case-check.schema.json +64 -0
  5. package/schema/case-config.schema.json +187 -0
  6. package/schema/case-final.schema.json +48 -0
  7. package/schema/case-good-record.schema.json +70 -0
  8. package/schema/case-grade.schema.json +49 -0
  9. package/schema/case-key.schema.json +117 -0
  10. package/schema/case-label.schema.json +32 -0
  11. package/schema/case-loop-report.schema.json +210 -0
  12. package/schema/case-loop.schema.json +141 -0
  13. package/schema/case-plan.schema.json +117 -0
  14. package/schema/case-previous.schema.json +70 -0
  15. package/schema/case-proposal.schema.json +52 -0
  16. package/schema/case-report.schema.json +892 -0
  17. package/schema/case-run.schema.json +253 -0
  18. package/schema/case-runs.schema.json +125 -0
  19. package/schema/case-score.schema.json +319 -0
  20. package/schema/case-spread.schema.json +110 -0
  21. package/schema/case-trial.schema.json +543 -0
  22. package/schema/case-try.schema.json +113 -0
  23. package/schema/local.json +155 -0
  24. package/src/cli.ts +9 -0
  25. package/src/env/capture.ts +48 -0
  26. package/src/env/compare.ts +201 -0
  27. package/src/env/facts.ts +51 -0
  28. package/src/env/fetch.ts +57 -0
  29. package/src/env/files.ts +228 -0
  30. package/src/env/grade-case.ts +80 -0
  31. package/src/env/grade-helper.ts +352 -0
  32. package/src/env/grader.ts +128 -0
  33. package/src/env/index.ts +727 -0
  34. package/src/env/mock.ts +374 -0
  35. package/src/env/routes.ts +90 -0
  36. package/src/env/sources.ts +19 -0
  37. package/src/env/state.ts +79 -0
  38. package/src/env/trial.ts +182 -0
  39. package/src/format/key.ts +144 -0
  40. package/src/format/loop.ts +178 -0
  41. package/src/format/output.ts +481 -0
  42. package/src/format/records.ts +440 -0
  43. package/src/format/schema-files.ts +64 -0
  44. package/src/format/settings.ts +552 -0
  45. package/src/format/trial-env.ts +64 -0
  46. package/src/format/trial-file.ts +134 -0
  47. package/src/help/awf-lab.txt +29 -0
  48. package/src/help/case.txt +38 -0
  49. package/src/help/config.txt +14 -0
  50. package/src/help/label.txt +12 -0
  51. package/src/help/loop.txt +44 -0
  52. package/src/help/report.txt +20 -0
  53. package/src/help/run.txt +60 -0
  54. package/src/help/runs.txt +10 -0
  55. package/src/help/score.txt +27 -0
  56. package/src/judge/criteria.workflow.ts +237 -0
  57. package/src/judge/version.ts +6 -0
  58. package/src/lab/answer.ts +47 -0
  59. package/src/lab/blame.ts +204 -0
  60. package/src/lab/box.ts +249 -0
  61. package/src/lab/capture-command.ts +298 -0
  62. package/src/lab/capture.ts +234 -0
  63. package/src/lab/check-command.ts +187 -0
  64. package/src/lab/cli.ts +324 -0
  65. package/src/lab/code-graders.ts +108 -0
  66. package/src/lab/columns.ts +138 -0
  67. package/src/lab/command-context.ts +436 -0
  68. package/src/lab/compare.ts +123 -0
  69. package/src/lab/config-command.ts +278 -0
  70. package/src/lab/criteria.ts +69 -0
  71. package/src/lab/dataset.ts +356 -0
  72. package/src/lab/eval-files.ts +185 -0
  73. package/src/lab/expect.ts +79 -0
  74. package/src/lab/facts.ts +59 -0
  75. package/src/lab/families.ts +32 -0
  76. package/src/lab/folders.ts +153 -0
  77. package/src/lab/git.ts +128 -0
  78. package/src/lab/good.ts +224 -0
  79. package/src/lab/grading-stub.txt +8 -0
  80. package/src/lab/grading.ts +332 -0
  81. package/src/lab/inspect.ts +226 -0
  82. package/src/lab/labels.ts +206 -0
  83. package/src/lab/loop-code.ts +255 -0
  84. package/src/lab/loop-command.ts +770 -0
  85. package/src/lab/loop-records.ts +144 -0
  86. package/src/lab/loop.ts +859 -0
  87. package/src/lab/marker.ts +23 -0
  88. package/src/lab/outcome.ts +196 -0
  89. package/src/lab/pooled.ts +106 -0
  90. package/src/lab/project-env.ts +39 -0
  91. package/src/lab/rates.ts +150 -0
  92. package/src/lab/reach.ts +111 -0
  93. package/src/lab/record-copies.ts +202 -0
  94. package/src/lab/refusal.ts +2 -0
  95. package/src/lab/report-command.ts +156 -0
  96. package/src/lab/report.ts +838 -0
  97. package/src/lab/reuse.ts +126 -0
  98. package/src/lab/run-command.ts +853 -0
  99. package/src/lab/run-logs.ts +89 -0
  100. package/src/lab/run-report.ts +259 -0
  101. package/src/lab/runs-command.ts +163 -0
  102. package/src/lab/runs.ts +172 -0
  103. package/src/lab/scaffold.ts +91 -0
  104. package/src/lab/score-command.ts +189 -0
  105. package/src/lab/score.ts +396 -0
  106. package/src/lab/store.ts +383 -0
  107. package/src/lab/text.ts +29 -0
  108. package/src/lab/trial-settings.ts +100 -0
  109. package/src/lab/trial-stub.txt +18 -0
  110. package/src/lab/trial.ts +443 -0
  111. package/src/lab/usage.ts +273 -0
  112. package/src/lab/verdict.ts +161 -0
  113. package/src/lab/workflow-graders.ts +161 -0
  114. package/src/lab/workspace.ts +489 -0
  115. package/src/loop/propose.workflow.ts +84 -0
  116. package/src/shared/allowance.ts +185 -0
  117. package/src/shared/compare/index.ts +3 -0
  118. package/src/shared/compare/paired.ts +397 -0
  119. package/src/shared/compare/stats.ts +139 -0
  120. package/src/shared/compare/types.ts +75 -0
  121. package/src/shared/config.ts +15 -0
  122. package/src/shared/runner.ts +321 -0
  123. package/src/shared/validate.ts +181 -0
  124. package/src/shared/version.ts +41 -0
  125. package/src/write-schemas.ts +10 -0
@@ -0,0 +1,23 @@
1
+ // Plain words, so `awf logs` never takes a marker for a credential and hides it.
2
+ const WORDS = `
3
+ acorn amber anchor anvil apple apricot arch arrow aspen atlas autumn badger bamboo banjo barley
4
+ basket beacon beetle birch biscuit blanket bloom boulder bramble breeze brick bridge bronze
5
+ bucket buffalo bundle butter cabin cactus camel candle canoe canyon carrot castle cedar cello
6
+ cherry chestnut cinder clover cobalt comet copper coral cotton cricket crystal cypress daisy
7
+ dolphin dragon drum eagle ember falcon feather fennel fern fiddle finch flint forest fossil fox
8
+ garnet ginger glacier goose granite grape gravel harbor harvest hazel heron hickory honey
9
+ horizon iris ivory jasmine juniper kettle kiwi ladder lagoon lantern lemon lichen lily linen
10
+ lobster maple marble meadow melon mint mitten moose moss nectar nickel nutmeg oak oasis ocean
11
+ olive onyx orchid otter owl paddle panda pebble pepper pine plum pond poppy prairie pumpkin
12
+ quail quartz quill rabbit raven reed ribbon river robin rocket saffron sage salmon sapphire
13
+ satchel shell silver sparrow spruce squash star stone sunset swan tangerine thistle thunder
14
+ timber toast topaz tulip turnip velvet violet walnut walrus willow wren yarrow zephyr
15
+ `
16
+ .trim()
17
+ .split(/\s+/);
18
+
19
+ /** A key's marker: four random plain words, `lantern-copper-walrus-tangerine`. */
20
+ export function newMarker(count = 4): string {
21
+ const picks = crypto.getRandomValues(new Uint32Array(count));
22
+ return [...picks].map((n) => WORDS[n % WORDS.length]).join("-");
23
+ }
@@ -0,0 +1,196 @@
1
+ import type { Errored, GraderEntry, Outcome, ScoreRecord, TrialRecord } from "../format/records";
2
+ import { type CaseTally, type CaseVerdict, caseVerdict, isBroken, outcomeOf } from "./verdict";
3
+
4
+ /** The voters a judge's agent gives, 3 when it says none. */
5
+ export const votersOf = (agent: { voters?: number } | undefined) => agent?.voters ?? 3;
6
+
7
+ /** Each grader's newest entry across a trial's scores. */
8
+ export function newestEntries(scores: readonly ScoreRecord[]): GraderEntry[] {
9
+ const byGrader = new Map<string, GraderEntry>();
10
+ for (const score of scores) {
11
+ for (const entry of score.entries) byGrader.set(entry.grader, entry);
12
+ }
13
+ return [...byGrader.values()];
14
+ }
15
+
16
+ /** What grades are estimated at: their entries' estimates, summed. */
17
+ export const gradingSpend = (scores: readonly { entries: readonly GraderEntry[] }[]) =>
18
+ scores.reduce((sum, s) => sum + s.entries.reduce((n, e) => n + (e.estimate ?? 0), 0), 0);
19
+
20
+ /**
21
+ * What one of a run's trials is estimated at, as `--budget` counts it, a loop's ledger and a plan's
22
+ * estimate: a trial of its own, its workflow run; a reused one, nothing, its workflow run counted
23
+ * where it ran; and either, the grades made while the run ran. Grades `score` makes later are not
24
+ * the run's.
25
+ */
26
+ export function trialSpend(
27
+ trial: StoredTrialView,
28
+ run: { started: string; finished?: string | undefined },
29
+ ): number {
30
+ return (
31
+ (trial.record.reused ? 0 : (trial.record.estimate ?? 0)) +
32
+ gradingSpend(scoresInRun(trial.scores, run))
33
+ );
34
+ }
35
+
36
+ /** The grades made while a run ran, from its start to its finish, or on when it has none. */
37
+ export const scoresInRun = (
38
+ scores: readonly ScoreRecord[],
39
+ run: { started: string; finished?: string | undefined },
40
+ ) =>
41
+ scores.filter((s) => s.at >= run.started && (run.finished === undefined || s.at <= run.finished));
42
+
43
+ export type TrialView = { outcome: Outcome; errored?: Pick<Errored, "by" | "reason"> };
44
+
45
+ /**
46
+ * The newest grades that decide: those of `deciders`, the graders the current dataset and key
47
+ * name; every grade when they can't be read.
48
+ */
49
+ export function decidingEntries(
50
+ scores: readonly ScoreRecord[],
51
+ deciders: ReadonlySet<string> | undefined,
52
+ ): GraderEntry[] {
53
+ return newestEntries(scores).filter((e) => !deciders || deciders.has(e.grader));
54
+ }
55
+
56
+ /** A trial's outcome, from its record and its deciding graders' newest entries. */
57
+ export function trialOutcome(
58
+ trial: TrialRecord,
59
+ scores: readonly ScoreRecord[],
60
+ deciders?: ReadonlySet<string>,
61
+ ): TrialView {
62
+ const entries = decidingEntries(scores, deciders).filter((e) => !e.skipped);
63
+ const broken = entries.find((e) => e.errored);
64
+ const errored =
65
+ trial.errored ??
66
+ (broken ? { by: "grading" as const, reason: broken.errored!.reason } : undefined);
67
+ const applies = entries.filter((e) => !e.notApplies && !e.errored);
68
+ const outcome = outcomeOf({
69
+ leaked: trial.leaked,
70
+ ...(errored ? { errored } : {}),
71
+ workflowErred: trial.workflowError !== undefined,
72
+ stopped: trial.stopped !== undefined,
73
+ verdicts: applies.flatMap((e) => (e.verdict ? [e.verdict] : [])),
74
+ numbers: applies.some((e) => e.numbers && Object.keys(e.numbers).length > 0),
75
+ notGraded: applies.length === 0,
76
+ });
77
+ return { outcome, ...(errored ? { errored } : {}) };
78
+ }
79
+
80
+ export type StoredTrialView = { record: TrialRecord; scores: readonly ScoreRecord[] };
81
+
82
+ /** The facts the newest grading read off a trial's record; facts are never kept with the trial. */
83
+ export function factsOf(scores: readonly ScoreRecord[]): ScoreRecord["facts"] {
84
+ return scores.findLast((score) => score.facts !== undefined)?.facts;
85
+ }
86
+
87
+ /** Why a run stopped: a stage its case named was never entered, by the trial that said so. */
88
+ export function stageFailure(trials: readonly StoredTrialView[]): string | undefined {
89
+ return trials.find((t) => t.record.errored?.code === "stage-not-entered")?.record.errored?.reason;
90
+ }
91
+
92
+ /** Why a run stopped starting trials on its preconditions. */
93
+ export const PRECONDITION_STOP = "two trials in a row failed a precondition";
94
+
95
+ /** Whether a trial failed a precondition its `setup` required. */
96
+ export const failedPrecondition = (record: TrialRecord) =>
97
+ record.errored?.by === "dataset" && record.errored.code === "precondition";
98
+
99
+ /**
100
+ * The precondition of the trial that ended last of those that failed one, as `"{what}" failed:
101
+ * {message}`: shown after `PRECONDITION_STOP`, which names it a precondition already.
102
+ */
103
+ export function preconditionFailure(
104
+ trials: readonly Pick<StoredTrialView, "record">[],
105
+ ): string | undefined {
106
+ const ended = (record: TrialRecord) => Date.parse(record.at) + record.ms;
107
+ return trials
108
+ .filter((t) => failedPrecondition(t.record))
109
+ .toSorted((a, b) => ended(a.record) - ended(b.record))
110
+ .at(-1)
111
+ ?.record.errored?.reason.replace(/^precondition /, "");
112
+ }
113
+
114
+ export type CaseRow = {
115
+ name: string;
116
+ tally: CaseTally;
117
+ knownFailing: boolean;
118
+ brokenTrial: boolean;
119
+ /** Every broken trial of it failed a precondition: a stop on them exits 3, not 5. */
120
+ onlyPreconditions: boolean;
121
+ /** A trial errored by the lab: exit 4. */
122
+ labTrial: boolean;
123
+ outcomes: Outcome[];
124
+ /** What kept the rest from passing: the first trial not passed, and why. */
125
+ why?: string;
126
+ /** Unused mocks and stages never reached, for a case that passed. */
127
+ notes: string[];
128
+ history: CaseVerdict[];
129
+ };
130
+
131
+ /** Why a trial didn't pass, in a line. */
132
+ export function whyNot(trial: StoredTrialView, deciders?: ReadonlySet<string>): string | undefined {
133
+ const { record } = trial;
134
+ const view = trialOutcome(record, trial.scores, deciders);
135
+ switch (view.outcome) {
136
+ case "passed":
137
+ case "graded by numbers":
138
+ case "not graded":
139
+ return undefined;
140
+ case "leaked":
141
+ return "leaked: the key turned up where the workflow ran";
142
+ case "errored":
143
+ return `errored by ${view.errored?.by}${record.errored?.code ? ` (${record.errored.code})` : ""}: ${view.errored?.reason}`;
144
+ case "stopped":
145
+ return `stopped: ${record.stopped}`;
146
+ default: {
147
+ if (record.workflowError !== undefined)
148
+ return `failed: the workflow erred: ${record.workflowError}`;
149
+ const entries = decidingEntries(trial.scores, deciders);
150
+ const failing = entries.find((e) => e.verdict === view.outcome) ?? entries[0];
151
+ const reason = failing?.reasons[0];
152
+ return reason ? `${failing.grader}: ${reason.text}` : view.outcome;
153
+ }
154
+ }
155
+ }
156
+
157
+ export function caseRow(
158
+ name: string,
159
+ trials: readonly StoredTrialView[],
160
+ asked: number,
161
+ pass: string,
162
+ knownFailing: boolean,
163
+ history: CaseVerdict[],
164
+ deciders?: ReadonlySet<string>,
165
+ ): CaseRow {
166
+ const views = trials.map((t) => trialOutcome(t.record, t.scores, deciders));
167
+ const outcomes = views.map((v) => v.outcome);
168
+ const broken = trials.filter((_, i) => isBroken(views[i]!.outcome, views[i]!.errored));
169
+ const firstAt = trials.findIndex((t, i) => views[i]!.outcome !== "passed" && whyNot(t, deciders));
170
+ const firstNot = trials[firstAt];
171
+ // A why that says the trial errored or leaked says what "1 errored" would.
172
+ const said = views[firstAt]?.outcome;
173
+ const tally = caseVerdict(
174
+ outcomes,
175
+ asked,
176
+ pass,
177
+ said === "errored" || said === "leaked" ? said : undefined,
178
+ );
179
+ const notes = [
180
+ ...new Set(
181
+ trials.flatMap((t) => [...t.record.unused.map((u) => `${u} was faked but never called`)]),
182
+ ),
183
+ ];
184
+ return {
185
+ name,
186
+ tally,
187
+ knownFailing,
188
+ brokenTrial: broken.length > 0,
189
+ onlyPreconditions: broken.length > 0 && broken.every((t) => failedPrecondition(t.record)),
190
+ labTrial: views.some((v) => v.outcome === "errored" && v.errored?.by === "lab"),
191
+ outcomes,
192
+ ...(firstNot ? { why: whyNot(firstNot, deciders)! } : {}),
193
+ notes,
194
+ history,
195
+ };
196
+ }
@@ -0,0 +1,106 @@
1
+ import type { GraderEntry } from "../format/records";
2
+ import { newestEntries, type StoredTrialView } from "./outcome";
3
+
4
+ /** One number pooled over a column's trials: counts summed, or values, shown as a median. */
5
+ export type Pooled = { count: number; of: number } | { values: number[] };
6
+
7
+ export type PooledNumbers = {
8
+ /** By grader, then by number. */
9
+ graders: Map<string, Map<string, Pooled>>;
10
+ /** Trials left out because the workflow failed them: they gave no numbers to pool. */
11
+ left: number;
12
+ };
13
+
14
+ const usable = (e: GraderEntry) => !e.errored && !e.skipped && !e.notApplies;
15
+
16
+ /**
17
+ * Each grader's numbers, pooled over the trials given. A trial the workflow failed (its body
18
+ * erred, it stopped) is left out and counted; a grader that errored, was skipped or does not
19
+ * apply adds nothing.
20
+ */
21
+ export function poolNumbers(trials: readonly StoredTrialView[]): PooledNumbers {
22
+ const graders = new Map<string, Map<string, Pooled>>();
23
+ let left = 0;
24
+ for (const trial of trials) {
25
+ if (trial.record.workflowError !== undefined || trial.record.stopped !== undefined) {
26
+ left++;
27
+ continue;
28
+ }
29
+ for (const entry of newestEntries(trial.scores).filter(usable)) {
30
+ for (const [name, number] of Object.entries(entry.numbers ?? {})) {
31
+ const byName = graders.get(entry.grader) ?? new Map<string, Pooled>();
32
+ graders.set(entry.grader, byName);
33
+ const was = byName.get(name);
34
+ if ("count" in number) {
35
+ const sum = was && "count" in was ? was : { count: 0, of: 0 };
36
+ byName.set(name, { count: sum.count + number.count, of: sum.of + number.of });
37
+ } else {
38
+ byName.set(name, {
39
+ values: [...(was && "values" in was ? was.values : []), number.value],
40
+ });
41
+ }
42
+ }
43
+ }
44
+ }
45
+ return { graders, left };
46
+ }
47
+
48
+ export type Agreement = {
49
+ a: string;
50
+ b: string;
51
+ /** Trials both gave a verdict on, and on how many the verdicts were the same. */
52
+ verdicts: { alike: number; of: number };
53
+ /** Parts both judged, matched by `about`, and how many got the same label or verdict. */
54
+ parts: { alike: number; of: number };
55
+ };
56
+
57
+ /**
58
+ * How often two graders of the same thing agreed on the same trials: their verdicts, and their
59
+ * parts' labels or verdicts matched by `about`. Shown for two graders that judged the same parts,
60
+ * and for a grader set aside (on demand, or no longer deciding) against each deciding grader but
61
+ * `expect`: a second judge tried beside the first. `expect` beside a tone grader agrees by chance.
62
+ */
63
+ export function agreements(
64
+ trials: readonly StoredTrialView[],
65
+ decidersOf: (caseName: string) => ReadonlySet<string> | undefined = () => undefined,
66
+ ): Agreement[] {
67
+ const pairs = new Map<string, Agreement & { aside: boolean }>();
68
+ for (const trial of trials) {
69
+ const deciders = decidersOf(trial.record.case);
70
+ const entries = newestEntries(trial.scores).filter(usable);
71
+ for (let i = 0; i < entries.length; i++) {
72
+ for (let j = i + 1; j < entries.length; j++) {
73
+ const [a, b] = [entries[i]!, entries[j]!].sort((x, y) => x.grader.localeCompare(y.grader));
74
+ const id = `${a!.grader}\0${b!.grader}`;
75
+ const pair = pairs.get(id) ?? {
76
+ a: a!.grader,
77
+ b: b!.grader,
78
+ verdicts: { alike: 0, of: 0 },
79
+ parts: { alike: 0, of: 0 },
80
+ aside: false,
81
+ };
82
+ pairs.set(id, pair);
83
+ if (deciders) {
84
+ const decides = (g: string) => deciders.has(g);
85
+ const oneAside =
86
+ (!decides(a!.grader) && decides(b!.grader) && b!.grader !== "expect") ||
87
+ (!decides(b!.grader) && decides(a!.grader) && a!.grader !== "expect");
88
+ if (oneAside) pair.aside = true;
89
+ }
90
+ if (a!.verdict && b!.verdict) {
91
+ pair.verdicts.of++;
92
+ if (a!.verdict === b!.verdict) pair.verdicts.alike++;
93
+ }
94
+ const theirs = new Map((b!.parts ?? []).map((p) => [p.about, p.label ?? p.verdict]));
95
+ for (const part of a!.parts ?? []) {
96
+ if (!theirs.has(part.about)) continue;
97
+ pair.parts.of++;
98
+ if (theirs.get(part.about) === (part.label ?? part.verdict)) pair.parts.alike++;
99
+ }
100
+ }
101
+ }
102
+ }
103
+ return [...pairs.values()]
104
+ .filter((p) => p.parts.of > 0 || (p.aside && p.verdicts.of > 0))
105
+ .map(({ aside: _, ...pair }) => pair);
106
+ }
@@ -0,0 +1,39 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+
4
+ /**
5
+ * The project's `.env`, the nearest from `cwd` up to its repository's root, into `environment`
6
+ * where a name is not already set: what the shell exports wins, as with dotenv. A run's tokens and
7
+ * keys come from the project it runs in. Returns the file read, if any.
8
+ */
9
+ export function loadProjectEnv(
10
+ cwd: string,
11
+ environment: Record<string, string | undefined> = process.env,
12
+ ): string | undefined {
13
+ for (let dir = cwd; ; dir = dirname(dir)) {
14
+ const file = join(dir, ".env");
15
+ if (existsSync(file)) {
16
+ for (const [name, value] of envEntries(readFileSync(file, "utf8")))
17
+ environment[name] ??= value;
18
+ return file;
19
+ }
20
+ if (existsSync(join(dir, ".git")) || dirname(dir) === dir) return undefined;
21
+ }
22
+ }
23
+
24
+ /** The folder whose `.env` a command reads: `-C {folder}`'s when given, as the command runs there. */
25
+ export function envFolder(cwd: string, argv: readonly string[]): string {
26
+ const at = argv.indexOf("-C");
27
+ const given = at < 0 ? undefined : argv[at + 1];
28
+ return given === undefined ? cwd : resolve(cwd, given);
29
+ }
30
+
31
+ /** `NAME=value` lines; `export ` and one pair of matching quotes dropped, `#` lines skipped. */
32
+ export function envEntries(text: string): [string, string][] {
33
+ const entries: [string, string][] = [];
34
+ for (const line of text.split("\n")) {
35
+ const found = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line);
36
+ if (found) entries.push([found[1]!, found[2]!.replace(/^(["'])(.*)\1$/, "$2")]);
37
+ }
38
+ return entries;
39
+ }
@@ -0,0 +1,150 @@
1
+ import type { CaseRow } from "./outcome";
2
+
3
+ const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;
4
+
5
+ // How sure a column's pass rate is. Cases are the independent units: trials of one case share its
6
+ // input and are never pooled as if independent. The intervals are 95%.
7
+
8
+ const Z = 1.96;
9
+
10
+ /** Student's t at 97.5% by degrees of freedom, for intervals from a few cases; Z beyond 30. */
11
+ const T = [
12
+ 12.71, 4.3, 3.18, 2.78, 2.57, 2.45, 2.36, 2.31, 2.26, 2.23, 2.2, 2.18, 2.16, 2.14, 2.13, 2.12,
13
+ 2.11, 2.1, 2.09, 2.09, 2.08, 2.07, 2.07, 2.06, 2.06, 2.06, 2.05, 2.05, 2.05, 2.04,
14
+ ];
15
+ const tOf = (df: number) => T[df - 1] ?? Z;
16
+
17
+ export type Interval = [low: number, high: number];
18
+
19
+ const clip = (x: number) => Math.min(1, Math.max(0, x));
20
+
21
+ /** Wilson's interval for x of n, which stays inside 0 to 1 and is sound at small n. */
22
+ export function wilson(x: number, n: number): Interval | undefined {
23
+ if (n === 0) return undefined;
24
+ const p = x / n;
25
+ const z2 = Z * Z;
26
+ const centre = (p + z2 / (2 * n)) / (1 + z2 / n);
27
+ const half = (Z * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / (1 + z2 / n);
28
+ return [clip(centre - half), clip(centre + half)];
29
+ }
30
+
31
+ /** A mean of per-case values with its interval from their spread across cases. */
32
+ export function meanWithInterval(
33
+ values: readonly number[],
34
+ bounds: Interval = [0, 1],
35
+ ): { mean: number; interval?: Interval } | undefined {
36
+ const n = values.length;
37
+ if (n === 0) return undefined;
38
+ const mean = values.reduce((a, b) => a + b, 0) / n;
39
+ if (n < 2) return { mean };
40
+ const variance = values.reduce((a, b) => a + (b - mean) ** 2, 0) / (n - 1);
41
+ const half = tOf(n - 1) * Math.sqrt(variance / n);
42
+ const [lo, hi] = bounds;
43
+ return { mean, interval: [Math.max(lo, mean - half), Math.min(hi, mean + half)] };
44
+ }
45
+
46
+ export type Rates = {
47
+ /** Cases with a verdict, and how many passed. */
48
+ cases: number;
49
+ passed: number;
50
+ interval?: Interval;
51
+ /** With more than one trial a case: the mean of each case's pass fraction. */
52
+ mean?: { mean: number; interval?: Interval };
53
+ /** At k trials a case, every case run k times: those whose k trials all passed, and any. */
54
+ k?: number;
55
+ passAll?: number;
56
+ passAny?: number;
57
+ };
58
+
59
+ /** The trials of a case that a verdict counts, and how many of them passed. */
60
+ const graded = (row: CaseRow) => row.tally.trials > 0 && row.tally.verdict !== undefined;
61
+
62
+ export function ratesOf(rows: readonly CaseRow[]): Rates {
63
+ const counted = rows.filter(graded);
64
+ const passed = counted.filter((r) => r.tally.verdict === "passed").length;
65
+ const interval = wilson(passed, counted.length);
66
+ const rates: Rates = { cases: counted.length, passed, ...(interval ? { interval } : {}) };
67
+ const trials = new Set(counted.map((r) => r.tally.trials));
68
+ if (counted.length > 0 && [...trials].some((t) => t > 1)) {
69
+ const mean = meanWithInterval(counted.map((r) => r.tally.passed / r.tally.trials));
70
+ if (mean) rates.mean = mean;
71
+ }
72
+ if (trials.size === 1) {
73
+ const k = [...trials][0]!;
74
+ if (k > 1) {
75
+ rates.k = k;
76
+ rates.passAll = counted.filter((r) => r.tally.passed === k).length;
77
+ rates.passAny = counted.filter((r) => r.tally.passed > 0).length;
78
+ }
79
+ }
80
+ return rates;
81
+ }
82
+
83
+ /**
84
+ * A column's difference from the reference on the same cases: the mean of each case's pass
85
+ * fraction there less the reference's, with its interval from the per-case differences. Two
86
+ * columns' own intervals can overlap while this one is clear of 0.
87
+ */
88
+ export function pairedDifference(
89
+ reference: readonly CaseRow[],
90
+ other: readonly CaseRow[],
91
+ ): { cases: number; mean: number; interval?: Interval; shown: boolean } | undefined {
92
+ const theirs = new Map(other.filter(graded).map((r) => [r.name, r]));
93
+ const differences = reference.filter(graded).flatMap((mine) => {
94
+ const there = theirs.get(mine.name);
95
+ return there
96
+ ? [there.tally.passed / there.tally.trials - mine.tally.passed / mine.tally.trials]
97
+ : [];
98
+ });
99
+ const found = meanWithInterval(differences, [-1, 1]);
100
+ if (!found) return undefined;
101
+ return { cases: differences.length, ...found, shown: signTest(differences) < 0.05 };
102
+ }
103
+
104
+ /**
105
+ * The two-sided sign test on the cases that came out differently: how likely so many went one
106
+ * way if neither column were better. Sound at a few cases, where an interval from their spread
107
+ * says too much (every case moving alike has no spread at all).
108
+ */
109
+ export function signTest(differences: readonly number[]): number {
110
+ const moved = differences.filter((d) => d !== 0);
111
+ const m = moved.length;
112
+ if (m === 0) return 1;
113
+ const up = moved.filter((d) => d > 0).length;
114
+ const tail = Math.min(up, m - up);
115
+ let choose = 1;
116
+ let sum = 0;
117
+ for (let i = 0; i <= tail; i++) {
118
+ sum += choose;
119
+ choose = (choose * (m - i)) / (i + 1);
120
+ }
121
+ return Math.min(1, (2 * sum) / 2 ** m);
122
+ }
123
+
124
+ const pct = (x: number) => `${Math.round(x * 100)}%`;
125
+ const range = ([lo, hi]: Interval) => `${Math.round(lo * 100)}–${pct(hi)}`;
126
+ const points = (x: number) => `${x > 0 ? "+" : x < 0 ? "−" : ""}${Math.abs(Math.round(x * 100))}`;
127
+
128
+ /** `5/7 cases passed, 95% 36–92% · mean per case 81%, 95% 62–100% · pass^3 4/7 · pass@3 6/7`. */
129
+ export function describeRates(rates: Rates): string {
130
+ if (rates.cases === 0) return "no case graded";
131
+ const parts = [
132
+ `${rates.passed}/${rates.cases} cases passed${rates.interval ? `, 95% ${range(rates.interval)}` : ""}`,
133
+ ];
134
+ if (rates.mean) {
135
+ parts.push(
136
+ `mean per case ${pct(rates.mean.mean)}${rates.mean.interval ? `, 95% ${range(rates.mean.interval)}` : ""}`,
137
+ );
138
+ }
139
+ if (rates.k !== undefined) {
140
+ parts.push(`pass^${rates.k} ${rates.passAll}/${rates.cases}`);
141
+ parts.push(`pass@${rates.k} ${rates.passAny}/${rates.cases}`);
142
+ }
143
+ return parts.join(" · ");
144
+ }
145
+
146
+ /** `−14 points, 95% −40 to +11: no difference shown`. */
147
+ export function describeDifference(d: NonNullable<ReturnType<typeof pairedDifference>>): string {
148
+ const interval = d.interval ? `, 95% ${points(d.interval[0])} to ${points(d.interval[1])}` : "";
149
+ return `${points(d.mean)} points on ${plural(d.cases, "case")}${interval}${d.shown ? "" : ": no difference shown"}`;
150
+ }
@@ -0,0 +1,111 @@
1
+ import type { SandboxRecord } from "@agentswf/contract/records";
2
+ import type { TrialRecord } from "../format/records";
3
+ import type { ResolvedNetwork } from "../format/settings";
4
+
5
+ export type Reach = NonNullable<TrialRecord["reach"]>;
6
+
7
+ /** An agent as its `agent-opened` line has it. */
8
+ export type OpenedAgent = {
9
+ agent: string;
10
+ harness: string;
11
+ sandbox?: string;
12
+ /** The model domains its harness added to its sandbox. */
13
+ domains?: readonly string[];
14
+ };
15
+
16
+ export type ReachInput = {
17
+ opened: readonly OpenedAgent[];
18
+ /** Every agent the run's sessions and turns name. */
19
+ named: readonly string[];
20
+ /** Each sandbox the run opened: the run record's, else its `sandbox-opened` lines. */
21
+ sandboxes: readonly Pick<SandboxRecord, "key" | "provider" | "spec">[];
22
+ /** `sandbox.network`, resolved. */
23
+ network: ResolvedNetwork;
24
+ };
25
+
26
+ /** Harnesses that keep their web tools whatever a sandbox says. */
27
+ const KEEPS_WEB = new Set(["cursor"]);
28
+
29
+ /**
30
+ * Whether `domain` is within `allowed`: the same name, or `*.x` covering `a.x` and `*.a.x`, never
31
+ * `x` itself.
32
+ */
33
+ export function covers(allowed: string, domain: string): boolean {
34
+ if (allowed === domain) return true;
35
+ if (!allowed.startsWith("*.")) return false;
36
+ const suffix = allowed.slice(1);
37
+ return domain.endsWith(suffix) && domain.length > suffix.length;
38
+ }
39
+
40
+ /** Whether a socket is one `allowed` names, or inside a folder it names. */
41
+ function socketCovered(allowed: readonly string[], socket: string): boolean {
42
+ const path = socket.replace(/\/+$/, "");
43
+ return allowed.some((each) => {
44
+ const listed = each.replace(/\/+$/, "");
45
+ return path === listed || path.startsWith(`${listed}/`);
46
+ });
47
+ }
48
+
49
+ /**
50
+ * Every agent of a trial ran in a sandbox reaching no more than `sandbox.network`: checked after
51
+ * the run from its own records. A check after the fact, not a wall.
52
+ */
53
+ export function checkReach({ opened, named, sandboxes, network: allowed }: ReachInput): Reach {
54
+ const problems: string[] = [];
55
+ const known = new Set(opened.map((a) => a.agent));
56
+ const keys = new Set(sandboxes.map((sandbox) => sandbox.key));
57
+ for (const agent of opened) {
58
+ if (!agent.sandbox) problems.push(`agent ${agent.agent} ran with no sandbox`);
59
+ else if (!keys.has(agent.sandbox)) {
60
+ problems.push(
61
+ `agent ${agent.agent} ran in sandbox ${agent.sandbox}, which the run's records never open, so its reach is unknown`,
62
+ );
63
+ }
64
+ }
65
+ for (const agent of new Set(named)) {
66
+ if (!known.has(agent)) {
67
+ problems.push(`agent ${agent} has no agent-opened line, so its reach is unknown`);
68
+ }
69
+ }
70
+ const sockets: string[] = [];
71
+ const seen = sandboxes.map((sandbox) => {
72
+ const admitted = opened.filter((a) => a.sandbox === sandbox.key);
73
+ const models = new Set(admitted.flatMap((a) => a.domains ?? []));
74
+ const network = [...(sandbox.spec.network ?? [])];
75
+ for (const domain of network) {
76
+ if (models.has(domain) || allowed.agents.some((each) => covers(each, domain))) continue;
77
+ problems.push(
78
+ `sandbox ${sandbox.key} reaches ${domain}, which sandbox.network.agents doesn't list`,
79
+ );
80
+ }
81
+ const webSearch = sandbox.spec.webSearch === true;
82
+ if (!allowed.webSearch) {
83
+ if (webSearch) {
84
+ problems.push(
85
+ `sandbox ${sandbox.key} keeps web search, which sandbox.network.webSearch doesn't allow`,
86
+ );
87
+ }
88
+ for (const agent of admitted.filter((a) => KEEPS_WEB.has(a.harness))) {
89
+ problems.push(
90
+ `agent ${agent.agent} runs ${agent.harness}, which keeps its web tools, and sandbox.network.webSearch doesn't allow web search`,
91
+ );
92
+ }
93
+ }
94
+ const own = [...(sandbox.spec.sockets ?? [])];
95
+ sockets.push(...own);
96
+ const outside = own.filter((socket) => !socketCovered(allowed.sockets, socket));
97
+ if (outside.length > 0) {
98
+ problems.push(
99
+ `sandbox ${sandbox.key} opens sockets ${outside.join(", ")}, which sandbox.network.sockets doesn't list`,
100
+ );
101
+ }
102
+ return {
103
+ key: sandbox.key,
104
+ provider: sandbox.provider,
105
+ network,
106
+ webSearch,
107
+ agents: admitted.map((a) => a.agent),
108
+ };
109
+ });
110
+ return { ok: problems.length === 0, problems, sockets, sandboxes: seen };
111
+ }