@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,47 @@
1
+ import Type from "typebox";
2
+ import { type GraderEntry, GraderEntrySchema } from "../format/records";
3
+ import { checkSchema, describeProblems, explainProblems } from "../shared/validate";
4
+
5
+ /** What a grader returns: its entry's verdict, numbers, reasons, parts and notApplies. */
6
+ const AnswerSchema = Type.Object(
7
+ {
8
+ verdict: Type.Optional(Type.Index(GraderEntrySchema, ["verdict"])),
9
+ numbers: Type.Optional(Type.Index(GraderEntrySchema, ["numbers"])),
10
+ reasons: Type.Optional(Type.Index(GraderEntrySchema, ["reasons"])),
11
+ parts: Type.Optional(Type.Index(GraderEntrySchema, ["parts"])),
12
+ notApplies: Type.Optional(Type.Index(GraderEntrySchema, ["notApplies"])),
13
+ },
14
+ { additionalProperties: false },
15
+ );
16
+
17
+ export type Answer = Pick<GraderEntry, "verdict" | "numbers" | "parts" | "notApplies"> & {
18
+ reasons: GraderEntry["reasons"];
19
+ };
20
+
21
+ /**
22
+ * A grader's answer, checked: a verdict or numbers, or `notApplies` alone. Throws grading's error,
23
+ * naming the grader, otherwise.
24
+ */
25
+ export function checkAnswer(name: string, raw: unknown): Answer {
26
+ const value = raw ?? {};
27
+ const checked = checkSchema(AnswerSchema, value);
28
+ if (!checked.ok) {
29
+ const problems = explainProblems(checked.problems, {
30
+ schema: AnswerSchema,
31
+ value,
32
+ noun: "an answer",
33
+ });
34
+ throw new Error(describeProblems(`grader ${name}'s answer`, problems));
35
+ }
36
+ const grade = checked.value;
37
+ const judged = grade.verdict !== undefined || grade.numbers !== undefined;
38
+ if (!judged && grade.notApplies === undefined) {
39
+ throw new Error(
40
+ `grader ${name} gave no verdict, numbers or notApplies: did grade return its answer?`,
41
+ );
42
+ }
43
+ if (judged && grade.notApplies !== undefined) {
44
+ throw new Error(`grader ${name} gave notApplies with a verdict or numbers: one or the other`);
45
+ }
46
+ return { ...grade, reasons: grade.reasons ?? [] };
47
+ }
@@ -0,0 +1,204 @@
1
+ import type { Errored } from "../format/records";
2
+ import type { EnvValue } from "../format/trial-env";
3
+ import {
4
+ type Gathered,
5
+ type Phase,
6
+ type Refused,
7
+ type TrialLine,
8
+ TrialLineSchema,
9
+ } from "../format/trial-file";
10
+ import { checkSchema } from "../shared/validate";
11
+ import type { RunTurn } from "./run-logs";
12
+
13
+ /** The trial file's lines, each checked; a line that isn't one is the lab's to report. */
14
+ export function readTrialLines(text: string): { lines: TrialLine[]; bad: number } {
15
+ const lines: TrialLine[] = [];
16
+ let bad = 0;
17
+ for (const raw of text.split("\n")) {
18
+ if (raw.trim() === "") continue;
19
+ try {
20
+ const checked = checkSchema(TrialLineSchema, JSON.parse(raw));
21
+ if (checked.ok) lines.push(checked.value);
22
+ else bad++;
23
+ } catch {
24
+ bad++;
25
+ }
26
+ }
27
+ return { lines, bad };
28
+ }
29
+
30
+ /** What `awf run` gave back, as far as blame needs it. */
31
+ export type RunEnding = {
32
+ /** Absent: awf printed no record. */
33
+ outcome?: string;
34
+ reason?: string;
35
+ value?: unknown;
36
+ stderr: string;
37
+ /** The run was refused at its first agent for a missing login, with no agent opened. */
38
+ loginRefused: boolean;
39
+ };
40
+
41
+ export type Blamed = {
42
+ errored?: Errored;
43
+ workflowError?: string;
44
+ /** Where `workflowError` came from: the body failed, or it timed out. */
45
+ erred?: "body" | "timeout";
46
+ stopped?: string;
47
+ workflow?: { name: string; version?: string };
48
+ /** What the trial gathered, kept however the workflow ended: absent when `evidence` never ran. */
49
+ gathered?: Gathered;
50
+ unused: string[];
51
+ refused: Refused[];
52
+ };
53
+
54
+ const tail = (text: string) => text.trim().split("\n").slice(-5).join(" ").trim();
55
+
56
+ /**
57
+ * Whose doing a trial's ending was, from the trial file and the run's record. An error or a
58
+ * timeout is the workflow's only inside the body; anything before the trial file's first line,
59
+ * a refused call, and `setup`, `evidence` or teardown are the dataset's, and the dataset's error
60
+ * wins over the workflow's whatever their order. A cancelled run is the lab's: no one's code
61
+ * decided its ending.
62
+ */
63
+ export function blame(allLines: readonly TrialLine[], ending: RunEnding): Blamed {
64
+ const cut = allLines.findIndex((line) => "timedOut" in line);
65
+ const lines = cut === -1 ? allLines : allLines.slice(0, cut + 1);
66
+ let phase: Phase | undefined;
67
+ const refused: Refused[] = [];
68
+ let unused: string[] = [];
69
+ let workflow: Blamed["workflow"];
70
+ let datasetError: Extract<TrialLine, { error: unknown }>["error"] | undefined;
71
+ let workflowError: Extract<TrialLine, { error: unknown }>["error"] | undefined;
72
+ let cancelled: Phase | undefined;
73
+ let timedOut: Phase | undefined;
74
+ let stopped: string | undefined;
75
+ let end: Extract<TrialLine, { end: unknown }>["end"] | undefined;
76
+ for (const line of lines) {
77
+ if ("phase" in line) phase = line.phase === "teardown" ? (phase ?? line.phase) : line.phase;
78
+ else if ("refused" in line) refused.push(line.refused);
79
+ else if ("unused" in line) unused = line.unused;
80
+ else if ("workflow" in line) workflow = line.workflow;
81
+ else if ("error" in line) {
82
+ if (line.error.by === "dataset") datasetError ??= line.error;
83
+ else workflowError ??= line.error;
84
+ } else if ("cancelled" in line) cancelled ??= line.cancelled;
85
+ else if ("timedOut" in line) timedOut = line.timedOut;
86
+ else if ("stopped" in line) stopped = line.stopped.reason;
87
+ else if ("end" in line) end = line.end;
88
+ }
89
+ const value =
90
+ ending.outcome === "completed" ? (ending.value as Partial<EnvValue> | undefined) : undefined;
91
+ const gathered = end ?? gatheredOf(value);
92
+ const base: Blamed = {
93
+ unused: value?.unused ?? unused,
94
+ refused: refused.length > 0 ? refused : (value?.refused ?? []),
95
+ ...((value?.workflow ?? workflow) ? { workflow: value?.workflow ?? workflow } : {}),
96
+ ...(gathered ? { gathered } : {}),
97
+ };
98
+ const dataset = (at: Phase | "after", code: Errored["code"], reason: string): Blamed => ({
99
+ ...base,
100
+ errored: { by: "dataset", phase: at, ...(code ? { code } : {}), reason },
101
+ });
102
+
103
+ if (cancelled !== undefined || ending.outcome === "cancelled") {
104
+ return {
105
+ ...base,
106
+ errored: {
107
+ by: "lab",
108
+ phase: cancelled ?? phase ?? "body",
109
+ reason: `the run was cancelled${ending.reason ? `: ${ending.reason}` : ""}`,
110
+ },
111
+ };
112
+ }
113
+ if (ending.loginRefused) {
114
+ return {
115
+ ...base,
116
+ errored: {
117
+ by: "provider",
118
+ phase: phase ?? "body",
119
+ code: "login",
120
+ reason: ending.reason ?? "",
121
+ },
122
+ };
123
+ }
124
+ if (base.refused.length > 0) {
125
+ const first = base.refused[0]!;
126
+ return dataset(first.phase, "refused", first.message);
127
+ }
128
+ if (datasetError) return dataset(datasetError.phase, datasetError.code, datasetError.reason);
129
+ if (timedOut) {
130
+ return timedOut === "body"
131
+ ? { ...base, workflowError: "timed out in body", erred: "timeout" }
132
+ : dataset(timedOut, "timed-out", `timed out in ${timedOut}`);
133
+ }
134
+ if (workflowError) return { ...base, workflowError: workflowError.reason, erred: "body" };
135
+ if (lines.length === 0 && ending.outcome !== "completed") {
136
+ // Died before defineTrial wrote anything: trial.ts or what it imports statically, the fix is there.
137
+ const said = tail(ending.stderr) || ending.reason || "awf run printed nothing";
138
+ return dataset("setup", "threw", said);
139
+ }
140
+
141
+ if (stopped) return { ...base, stopped };
142
+ if (gathered) return base;
143
+ if (ending.outcome === "completed") {
144
+ return dataset("evidence", "threw", "the run completed with no trial record");
145
+ }
146
+ const reason = ending.reason ?? (tail(ending.stderr) || `awf run printed no record`);
147
+ if (phase === "body") {
148
+ return {
149
+ ...base,
150
+ workflowError: reason,
151
+ erred: ending.outcome === "timed-out" ? "timeout" : "body",
152
+ };
153
+ }
154
+ const code = ending.outcome === "timed-out" ? "timed-out" : "threw";
155
+ return dataset(phase ?? "setup", code, reason);
156
+ }
157
+
158
+ /**
159
+ * The turn outcomes that are the harness's: it stopped the agent, or failed under it. A turn that
160
+ * timed out ran to the workflow's deadline, and one unanswered answered the workflow's prompt
161
+ * otherwise: both stay the workflow's.
162
+ */
163
+ const HARNESS_STOPS: ReadonlySet<string> = new Set(["blocked", "failed"]);
164
+
165
+ /**
166
+ * A harness's words for a login it lacks or had refused, as a failed turn's reason gives them
167
+ * (`… needs a login …`) and awf's own check at the first agent (`… authentication is required …`).
168
+ * The turn line holds no reason: only a workflow that passes the turn's reason on shows one.
169
+ */
170
+ const LOGIN_LOST = /needs a login|authentication is required/;
171
+
172
+ /**
173
+ * A workflow's ending that a harness's stop explains: the workflow's body failed, or it stopped
174
+ * itself, right after the run's last settled turn ended blocked or failed. Not the body's timeout,
175
+ * the workflow's own deadline. A login lost on the way is the provider's, when the ending's reason
176
+ * says so.
177
+ */
178
+ export function harnessStop(
179
+ blamed: Pick<Blamed, "workflowError" | "erred" | "stopped">,
180
+ turns: readonly RunTurn[],
181
+ ): Errored | undefined {
182
+ const ending =
183
+ blamed.erred === "body" && blamed.workflowError !== undefined
184
+ ? `the run: ${blamed.workflowError}`
185
+ : blamed.stopped !== undefined
186
+ ? `the workflow stopped: ${blamed.stopped}`
187
+ : undefined;
188
+ if (ending === undefined) return undefined;
189
+ const turn = turns.findLast((t) => t.kind === "turn");
190
+ if (!turn || !HARNESS_STOPS.has(turn.outcome)) return undefined;
191
+ const where = turn.stage ? `in stage ${turn.stage}` : "between stages";
192
+ const reason = `${turn.agent}'s turn ${where} ended ${turn.outcome}; ${ending}`;
193
+ if (turn.outcome === "failed" && LOGIN_LOST.test(ending)) {
194
+ return { by: "provider", phase: "body", code: "login", reason };
195
+ }
196
+ return { by: "harness", phase: "body", reason };
197
+ }
198
+
199
+ /** The run's value as what the trial gathered, when it holds one. */
200
+ function gatheredOf(value: Partial<EnvValue> | undefined): Gathered | undefined {
201
+ if (!value || typeof value.stages !== "object" || !Array.isArray(value.files)) return undefined;
202
+ const { workflow: _, unused: __, refused: ___, ...rest } = value;
203
+ return rest as Gathered;
204
+ }
package/src/lab/box.ts ADDED
@@ -0,0 +1,249 @@
1
+ import { existsSync, lstatSync, readdirSync, realpathSync, writeFileSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
+ import type { ResolvedNetwork } from "../format/settings";
4
+ import { type CaseWorkspace, ignored, inside, recordsFolders } from "./workspace";
5
+
6
+ // The "lab" box: a whole trial, `awf run --in` with trial.ts, the workflow's code and its agents
7
+ // inside, so code an agent wrote reads no key. awf makes the box and carries the logins in; the
8
+ // lab decides only what it reaches: these paths, and the hosts the case's code reaches.
9
+
10
+ /** `awf run --in`'s spec, as much of it as the lab uses. */
11
+ export type BoxSpec = {
12
+ srt: Record<string, never>;
13
+ /** Read, beside the run's working directory. A read path inside a written one stays read-only. */
14
+ read: string[];
15
+ /** Written: `.` is the run's working directory. */
16
+ write: string[];
17
+ /** Inside the paths above, what nothing in the box reads or writes. */
18
+ hide: string[];
19
+ network: string[];
20
+ webSearch: boolean;
21
+ /** Host unix sockets the trial may connect to; absent, none. */
22
+ sockets?: string[];
23
+ };
24
+
25
+ const unique = (xs: readonly string[]) => [...new Set(xs)];
26
+
27
+ /** The box's spec: the reach the trial needs, and nothing of keys, the store or `hide`'s paths. */
28
+ export function boxSpec(reach: {
29
+ read: readonly string[];
30
+ write: readonly string[];
31
+ hide: readonly string[];
32
+ network: readonly string[];
33
+ webSearch?: boolean;
34
+ sockets?: readonly string[];
35
+ }): BoxSpec {
36
+ return {
37
+ srt: {},
38
+ read: unique(reach.read),
39
+ write: unique(reach.write),
40
+ hide: unique(reach.hide),
41
+ network: unique(reach.network),
42
+ webSearch: reach.webSearch === true,
43
+ ...(reach.sockets && reach.sockets.length > 0 ? { sockets: unique(reach.sockets) } : {}),
44
+ };
45
+ }
46
+
47
+ /** Writes the spec where `awf run --in` reads it, and returns that path. */
48
+ export function writeBoxSpec(spec: BoxSpec, file: string): string {
49
+ writeFileSync(file, JSON.stringify(spec, null, 2), { mode: 0o600 });
50
+ return file;
51
+ }
52
+
53
+ /** The box's network: where agents and the workflow's code may go; awf adds the models'. */
54
+ export function boxNetwork(network: ResolvedNetwork, codeHosts: readonly string[]): string[] {
55
+ return unique([
56
+ ...network.agents,
57
+ ...codeHosts.filter((h) => h !== "localhost" && h !== "127.0.0.1"),
58
+ ]);
59
+ }
60
+
61
+ /** The trial a box is made for: its dataset's data folder and its case's folder there. */
62
+ export type BoxedCase = { data: string; dir: string };
63
+
64
+ /** What an eval folder holds that grades a trial, which no trial reads. */
65
+ const GRADING_FILES = ["grading.ts", "graders", "capture.ts", "brief.md"];
66
+
67
+ /**
68
+ * What the box hides inside the code folder it lets the trial read: `.git` (a committed key is in
69
+ * its history), every dataset's keys, the records folders, `ignore`'s files, and the store and the
70
+ * lab's home but `keep`, the box's own folder there, such as a loop's copy of the code. The home
71
+ * folder is denied whole by the box. A trial's box, given its `trial`, hides every case and data
72
+ * folder but its own case's `input/` and its dataset's `shared/`, every eval folder's grading
73
+ * files, the loops' briefs, the config and the local file too.
74
+ */
75
+ export function hiddenOf(
76
+ root: string,
77
+ workspace: CaseWorkspace,
78
+ options: { keep?: readonly string[]; trial?: BoxedCase } = {},
79
+ ): string[] {
80
+ const { keep = [root], trial } = options;
81
+ // By real paths, as srt denies them: a store, or the lab's home, may be a link to another disk.
82
+ const kept = keep.map(realOf);
83
+ const hidden = [
84
+ ...hiddenAround(realOf(workspace.labHome), kept),
85
+ ...hiddenAround(realOf(workspace.store), kept),
86
+ ];
87
+ const records = recordsFolders(workspace);
88
+ hidden.push(...records);
89
+ // The code folder's, and the workspace's checkout's wherever it is: another folder of code, such
90
+ // as a loop's copy, may reach the checkout through a read the box was given.
91
+ const roots = [...new Set([root, workspace.root])];
92
+ // A folder inside your checkout as each root holds it: an `--against` worktree has its own.
93
+ const inEach = (path: string) =>
94
+ inside(workspace.root, path)
95
+ ? roots.map((at) => join(at, relative(workspace.root, path)))
96
+ : [path];
97
+ for (const at of roots) {
98
+ const project = join(at, relative(workspace.root, workspace.project));
99
+ hidden.push(join(at, ".git"), ...ignoredOf(at), ...ignoredFiles(project, workspace.ignore));
100
+ }
101
+ for (const folder of records) hidden.push(...inEach(folder));
102
+ const evalDirs = new Set(workspace.datasets.flatMap((d) => inEach(d.eval.value)));
103
+ // Every eval folder in evals/ too, whose cases no dataset of this checkout may name.
104
+ for (const at of roots) {
105
+ const evals = join(at, relative(workspace.root, workspace.evals));
106
+ if (!existsSync(evals)) continue;
107
+ for (const name of readdirSync(evals)) {
108
+ if (lstatSync(join(evals, name)).isDirectory()) evalDirs.add(join(evals, name));
109
+ }
110
+ }
111
+ const data = new Set([...workspace.datasets.flatMap((d) => inEach(d.data.value)), ...evalDirs]);
112
+ if (!trial) {
113
+ for (const dir of data) {
114
+ const cases = join(dir, "cases");
115
+ if (!existsSync(cases)) continue;
116
+ for (const name of readdirSync(cases)) {
117
+ hidden.push(join(cases, name, "key.md"), join(cases, name, "key"));
118
+ }
119
+ }
120
+ return hidden;
121
+ }
122
+ const own = new Set(inEach(trial.data));
123
+ const input = relative(trial.data, join(trial.dir, "input"));
124
+ for (const dir of data) {
125
+ const cases = join(dir, "cases");
126
+ if (own.has(dir)) {
127
+ // srt denies a folder over a path allowed inside it: the other cases, one by one.
128
+ if (existsSync(cases))
129
+ hidden.push(...hiddenAround(realOf(cases), [realOf(join(dir, input))]));
130
+ } else {
131
+ hidden.push(...[cases, join(dir, "shared")].filter((path) => existsSync(path)));
132
+ }
133
+ }
134
+ for (const dir of evalDirs) {
135
+ hidden.push(...GRADING_FILES.map((name) => join(dir, name)).filter((path) => existsSync(path)));
136
+ }
137
+ for (const loop of workspace.loops) hidden.push(...inEach(loop.brief.value));
138
+ for (const file of [workspace.configFile, workspace.localFile]) {
139
+ if (file) hidden.push(...inEach(file));
140
+ }
141
+ return [...new Set(hidden)];
142
+ }
143
+
144
+ /**
145
+ * A loop's held-out cases, each folder whole, as your checkout and the try's copy at `copyRoot`
146
+ * hold it: its proposer never sees them.
147
+ */
148
+ export function heldOutOf(
149
+ dirs: readonly string[],
150
+ workspace: CaseWorkspace,
151
+ copyRoot: string,
152
+ ): string[] {
153
+ return dirs.flatMap((dir) =>
154
+ inside(workspace.root, dir) ? [dir, join(copyRoot, relative(workspace.root, dir))] : [dir],
155
+ );
156
+ }
157
+
158
+ /** The files of a project folder `ignore` names, and each folder it names whole. */
159
+ function ignoredFiles(root: string, globs: readonly string[]): string[] {
160
+ if (globs.length === 0) return [];
161
+ const folders = globs.flatMap((glob) => {
162
+ const folder = glob.replace(/\/\*\*$/, "").replace(/\/+$/, "");
163
+ return /[*?[\]{}]/.test(folder) ? [] : [join(root, folder)];
164
+ });
165
+ const listed = Bun.spawnSync(
166
+ ["git", "-C", root, "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
167
+ { stdout: "pipe", stderr: "ignore", stdin: "ignore" },
168
+ );
169
+ const files =
170
+ listed.exitCode === 0
171
+ ? listed.stdout
172
+ .toString()
173
+ .split("\0")
174
+ .filter((path) => path && ignored(globs, path))
175
+ .map((path) => join(root, path))
176
+ // A folder hidden whole hides its files: listing each could pass the spawn's limit.
177
+ .filter((path) => !folders.some((folder) => path.startsWith(`${folder}/`)))
178
+ : [];
179
+ return [...new Set([...folders, ...files])];
180
+ }
181
+
182
+ /**
183
+ * What git ignores in the code folder, such as a `.env`, but `node_modules`: the box shows the
184
+ * code as git would hold it, and an install. A folder outside git hides nothing this way.
185
+ */
186
+ function ignoredOf(root: string): string[] {
187
+ const listed = Bun.spawnSync(
188
+ [
189
+ "git",
190
+ "-C",
191
+ root,
192
+ "ls-files",
193
+ "-z",
194
+ "--others",
195
+ "--ignored",
196
+ "--exclude-standard",
197
+ "--directory",
198
+ ],
199
+ { stdout: "pipe", stderr: "ignore", stdin: "ignore" },
200
+ );
201
+ if (listed.exitCode !== 0) return [];
202
+ return listed.stdout
203
+ .toString()
204
+ .split("\0")
205
+ .filter(Boolean)
206
+ .map((path) => path.replace(/\/$/, ""))
207
+ .filter((path) => !path.split("/").includes("node_modules"))
208
+ .map((path) => join(root, path));
209
+ }
210
+
211
+ /**
212
+ * Everything under `dir` but the paths to `keep`: each folder on the way to one, its other
213
+ * entries. srt lets a denied folder win over a path allowed inside it, so a folder the box must
214
+ * reach inside a hidden one is kept by hiding around it. `dir` and `keep` are real paths. A link
215
+ * is never hidden: srt denies what it leads to, such as the checkout's install a loop's copy links;
216
+ * what it leads to is hidden where it lies, when that is the store or the lab's home.
217
+ */
218
+ export function hiddenAround(dir: string, keep: readonly string[]): string[] {
219
+ if (keep.includes(dir) || !existsSync(dir)) return [];
220
+ const toward = keep.filter((path) => path.startsWith(`${dir}/`));
221
+ if (toward.length === 0) return [dir];
222
+ return readdirSync(dir).flatMap((entry) => {
223
+ const path = join(dir, entry);
224
+ if (toward.some((k) => k === path || k.startsWith(`${path}/`))) {
225
+ return hiddenAround(path, toward);
226
+ }
227
+ return lstatSync(path).isSymbolicLink() ? [] : [path];
228
+ });
229
+ }
230
+
231
+ const realOf = (path: string) => (existsSync(path) ? realpathSync(path) : path);
232
+
233
+ /** The trial's reach under the box: the box itself, which every agent ran in. */
234
+ export function boxReach(spec: BoxSpec, agents: readonly string[]) {
235
+ return {
236
+ ok: true,
237
+ problems: [],
238
+ sockets: [],
239
+ sandboxes: [
240
+ {
241
+ key: "lab",
242
+ provider: "srt",
243
+ network: spec.network,
244
+ webSearch: spec.webSearch,
245
+ agents: [...agents],
246
+ },
247
+ ],
248
+ };
249
+ }