@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,727 @@
1
+ import { type EnvValue, TRIAL_ENV, type TrialSettings } from "../format/trial-env";
2
+ import type { DatasetError, Gathered, Phase } from "../format/trial-file";
3
+ import { describing, type RequiredParam, TRIAL_SPEC } from "./files";
4
+ import { asJson, fileOf, Mocks } from "./mock";
5
+ import { copiedModule } from "./sources";
6
+ import { type HttpRequest, shared, trialParams, trialSettings, writeLine } from "./state";
7
+ import { CaseWiring, makeTrial, PreconditionFailed, type Trial } from "./trial";
8
+
9
+ export {
10
+ type Capture,
11
+ type CapturedCase,
12
+ type CapturedRun,
13
+ defineCapture,
14
+ } from "./capture";
15
+ export {
16
+ better,
17
+ type CaseComparison,
18
+ type ComparedTrial,
19
+ type ComparisonCall,
20
+ defineComparison,
21
+ type MetricOptions,
22
+ type Room,
23
+ type RoomCall,
24
+ type Verdict,
25
+ } from "./compare";
26
+ export {
27
+ defineGrading,
28
+ defineLab,
29
+ type Grader,
30
+ type Grading,
31
+ type GradingSpec,
32
+ type Lab,
33
+ type LabSpec,
34
+ type LoopSpec,
35
+ type RequiredParam,
36
+ required,
37
+ type SentencesGrader,
38
+ sentences,
39
+ type WorkflowGrader,
40
+ workflowGrader,
41
+ } from "./files";
42
+ export { type GradeCase, gradeCase } from "./grade-case";
43
+ export {
44
+ type CodeGrader,
45
+ defineGrader,
46
+ type Grade,
47
+ type GradeInput,
48
+ type GradeNumber,
49
+ type Reads,
50
+ type TrialInput,
51
+ } from "./grader";
52
+ export type { RouteHandler } from "./routes";
53
+ export type { HttpRequest } from "./state";
54
+ export type { Faked, Spies, Spy, Trial } from "./trial";
55
+
56
+ /** One fact `grading.ts`'s `facts` returns for the key's `expect`: a flat value. */
57
+ export type Fact = string | number | boolean | null;
58
+ /** `undefined` is allowed here and refused at run time (`facts-missing`), so branches may differ. */
59
+ export type Facts = Record<string, Fact | undefined>;
60
+
61
+ /**
62
+ * Stages given their value by the case, in place of their work: the value itself, or a function
63
+ * returning it, called when the stage is entered. A stage's value is data, never a function.
64
+ */
65
+ export type StubStages = Record<string, unknown>;
66
+
67
+ /** What `evidence` returns: what grading needs that only the world can tell. */
68
+ export type Evidence<V = unknown> = {
69
+ /** Paths in `trial.scratch`, copied out for the graders that read the trial. */
70
+ files?: readonly string[];
71
+ /** Raw JSON, read in `grading.ts`'s `facts`: gathered here, never judged. */
72
+ values?: V;
73
+ };
74
+
75
+ /** What `evidence` is given: how the workflow ended. */
76
+ export type Ended<R> = {
77
+ /** What the workflow returned: `undefined` when it stopped after a stage, or threw. */
78
+ result: R | undefined;
79
+ /** What the workflow's own stages returned, by name; never a stubbed stage's. */
80
+ stages: Partial<Record<string, unknown>>;
81
+ };
82
+
83
+ /** What `setup` returns: what the run needs. */
84
+ export type Setup<R, V = unknown> = {
85
+ /** The workflow's arguments, as `awf run … -- {argv}` would give them. */
86
+ argv?: readonly string[];
87
+ /** Stages given a value in place of their work. */
88
+ stubStages?: StubStages;
89
+ /** Ends the run once this stage returns: the stages after it never run, and there's no result. */
90
+ stopAfterStage?: string;
91
+ /**
92
+ * Runs once, in the world, after the workflow ends however it ended: what grading needs that
93
+ * only the world can tell. It gathers and never grades.
94
+ */
95
+ evidence?: (ended: Ended<R>) => Evidence<V> | Promise<Evidence<V>>;
96
+ };
97
+
98
+ /**
99
+ * The trial record, as `grading.ts`'s `facts` reads it. `import type trial from "./trial"` and
100
+ * `defineGrading<typeof trial>` type `result` and `values`; the rest went through JSON, and is cast.
101
+ */
102
+ export type TrialRecord<R = unknown, V = unknown> = {
103
+ /** What the workflow returned; `undefined` for a run that stopped after a stage. */
104
+ readonly result: R | undefined;
105
+ /** What the workflow's own stages returned, by name; never a stubbed stage's. */
106
+ readonly stages: Partial<Record<string, unknown>>;
107
+ /** The values the case gave its stubbed stages. */
108
+ readonly stubbedStages: Partial<Record<string, unknown>>;
109
+ /** The `stopAfterStage` stage, once it returned. */
110
+ readonly stoppedAfter?: string;
111
+ /** `calls.{mock}.{function}`: each call's arguments, as JSON. */
112
+ readonly calls: Partial<Record<string, Partial<Record<string, unknown[][]>>>>;
113
+ /** The requests the workflow's `fetch` made. */
114
+ readonly requests: readonly HttpRequest[];
115
+ /** `evidence`'s `values`. */
116
+ readonly values: V | undefined;
117
+ /** `evidence`'s `files`, as copied out. */
118
+ readonly files: readonly string[];
119
+ };
120
+
121
+ declare const RECORD: unique symbol;
122
+
123
+ /** The trial record a `trial.ts`'s trials end in, typed from it. */
124
+ export type RecordOf<T> = T extends {
125
+ readonly [RECORD]?: { result: infer R; values: infer V };
126
+ }
127
+ ? TrialRecord<R, V>
128
+ : TrialRecord;
129
+
130
+ // Structural, never the lab's own `agentswf` types: a project's copy brands them apart.
131
+ // biome-ignore lint/suspicious/noExplicitAny: any workflow's `run`, whatever its context and args.
132
+ type WorkflowModule = { default: { run(...args: any[]): Promise<unknown> } };
133
+ // biome-ignore lint/suspicious/noExplicitAny: any workflow's `run`, whatever its context and args.
134
+ type ResultOf<M> = M extends { default: { run(...args: any[]): Promise<infer R> } } ? R : unknown;
135
+
136
+ /** The declared parameters: each a default, or `required()`. */
137
+ export type ParamsSpec = Record<string, string | RequiredParam>;
138
+ /** The values a trial gets for its declared parameters. */
139
+ export type ParamValues<P extends ParamsSpec> = { readonly [K in keyof P]: string };
140
+
141
+ type Duration = `${number}${"ms" | "s" | "m" | "h"}`;
142
+
143
+ export type TrialSpec<M extends WorkflowModule, P extends ParamsSpec, V = undefined> = {
144
+ /**
145
+ * Semver, required: when kept trials go stale. Bump its major or minor, or give it a pre-release
146
+ * tag, for any change to the workflow, `setup`, a fake or anything else a trial runs that should
147
+ * rerun trials; a patch or build part is recorded and reruns nothing. A function is called once
148
+ * per command, in each column's own checkout, such as `() => pkg.version`.
149
+ */
150
+ version: string | (() => string | Promise<string>);
151
+ /** The workflow as it ships, imported lazily so the mocks exist before it loads. */
152
+ workflow: (trial: Trial<ParamValues<P>>) => Promise<M>;
153
+ /** Builds the case's world, and returns what the run needs. */
154
+ setup: (trial: Trial<ParamValues<P>>) => Setup<ResultOf<M>, V> | Promise<Setup<ResultOf<M>, V>>;
155
+ /** Every parameter, with its default or `required()`; one not declared here is refused. */
156
+ params?: P;
157
+ /** Who isolates a trial, with what, and where it may go; each part closed when absent. */
158
+ sandbox?: {
159
+ /** `"lab"`, the default: the whole trial in the lab's sandbox. `"workflow"`: the workflow's own sandboxes, its network checked after each trial. */
160
+ by?: "lab" | "workflow";
161
+ /** The lab's sandbox, `"srt"` by default; used only with `by: "lab"`. */
162
+ provider?: "srt";
163
+ network?: {
164
+ /** Where an agent's own commands may go besides its model. */
165
+ agents?: readonly string[];
166
+ /** Where the workflow's own code may `fetch` unfaked. */
167
+ code?: readonly string[];
168
+ /** Whether agents keep their web search. */
169
+ webSearch?: boolean;
170
+ /** Host unix sockets an agent may connect to: a socket, or a folder of them. */
171
+ sockets?: readonly string[];
172
+ };
173
+ };
174
+ /** Each phase's limit: `setup` 10m, the workflow's `run` 30m, `after` (evidence and cleanup) 10m unless set. */
175
+ limits?: { setup?: Duration; run?: Duration; after?: Duration };
176
+ };
177
+
178
+ /**
179
+ * The workflow `defineTrial` makes, which `awf run` loads; opaque to `trial.ts`. It carries the
180
+ * types of its record for `defineGrading<typeof trial>`.
181
+ */
182
+ export type TrialDefinition<R = unknown, V = unknown> = {
183
+ readonly kind: string;
184
+ readonly meta: { readonly name: string };
185
+ readonly [RECORD]?: { result: R; values: V };
186
+ };
187
+
188
+ const NOT_IN_A_TRIAL = `this is a trial, run by awf-lab: \`awf-lab run\` in the project runs its cases, and sets ${TRIAL_ENV.case} and the rest for each trial`;
189
+
190
+ /** How a case becomes a run of one workflow, as `trial.ts`'s default export. */
191
+ export function defineTrial<
192
+ M extends WorkflowModule,
193
+ const P extends ParamsSpec = Record<never, never>,
194
+ V = undefined,
195
+ >(spec: TrialSpec<M, P, V>): TrialDefinition<ResultOf<M>, V> {
196
+ const made = describing()
197
+ ? {}
198
+ : defineWorkflow({
199
+ meta: {
200
+ name: trialSettings()?.dataset ? `case-env-${trialSettings()?.dataset}` : "case-env",
201
+ description: "Runs a workflow on one case of an awf-lab dataset.",
202
+ },
203
+ prepare: () => {
204
+ if (!process.env[TRIAL_ENV.case] || !trialSettings()) throw new Error(NOT_IN_A_TRIAL);
205
+ return null;
206
+ },
207
+ // biome-ignore lint/suspicious/noExplicitAny: the engine's context, typed structurally here.
208
+ run: async (wf: any) =>
209
+ (await runInTrial(spec as unknown as TrialSpec<M, ParamsSpec, unknown>, wf)) as never,
210
+ });
211
+ Object.defineProperty(made, TRIAL_SPEC, { value: spec });
212
+ return made as TrialDefinition<ResultOf<M>, V>;
213
+ }
214
+
215
+ /**
216
+ * The running engine's `defineWorkflow`, which its loader serves to every importer. Required, not
217
+ * imported: an import would lead a project's type check into the lab's own `agentswf`, the same
218
+ * name and version as the project's, and TypeScript then mixes the two copies' types.
219
+ */
220
+ function defineWorkflow(definition: unknown): unknown {
221
+ const surface: {
222
+ defineWorkflow: (definition: unknown) => unknown;
223
+ } = require("agentswf/workflow");
224
+ return surface.defineWorkflow(definition);
225
+ }
226
+
227
+ // The engine's context, as far as `defineEnv` uses it.
228
+ type EngineContext = {
229
+ readonly cwd: string;
230
+ readonly deadline?: Date;
231
+ stage(name: string, ...rest: unknown[]): Promise<unknown>;
232
+ };
233
+
234
+ type InnerWorkflow = {
235
+ meta?: { name?: string; version?: string };
236
+ events?: unknown;
237
+ prepare?: (invocation: { argv: readonly string[]; cwd: string }) => unknown;
238
+ run(context: unknown, args: unknown): Promise<unknown>;
239
+ };
240
+
241
+ class TimedOut extends Error {
242
+ constructor(readonly phase: Phase) {
243
+ super(`timed out in ${phase}`);
244
+ }
245
+ }
246
+
247
+ /** Thrown by the lab's `stage` once `stopAfterStage` returned: the run ends there. */
248
+ class StoppedAfter extends Error {
249
+ constructor(stage: string) {
250
+ super(`the case stops once ${stage} returned`);
251
+ this.name = "StoppedAfter";
252
+ }
253
+ }
254
+
255
+ /** A failure that is the dataset's, by its code. */
256
+ class DatasetFailure extends Error {
257
+ constructor(
258
+ readonly code: DatasetError | undefined,
259
+ reason: string,
260
+ ) {
261
+ super(reason);
262
+ }
263
+ }
264
+
265
+ // What a phase stops short of the run's deadline by, so teardown runs before the engine's backstop.
266
+ const DEADLINE_RESERVE_MS = 10_000;
267
+ // An exit this close to the run's deadline, or past it, is the engine's backstop.
268
+ const EXIT_SLACK_MS = 1_000;
269
+
270
+ const isStop = (error: unknown) => error instanceof Error && error.name === "WorkflowStopped";
271
+ const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
272
+
273
+ class TrialRun {
274
+ readonly #cleanups: (() => unknown)[];
275
+ #ended = false;
276
+ #cancelled = false;
277
+ #tornDown: Promise<void> | undefined;
278
+
279
+ constructor(
280
+ readonly settings: TrialSettings,
281
+ readonly deadline: Date | undefined,
282
+ cleanups: (() => unknown)[],
283
+ ) {
284
+ this.#cleanups = cleanups;
285
+ // The engine's `--timeout` abandons the body and exits after its grace, sending no signal:
286
+ // only a synchronous `exit` handler runs then. Any other exit before the trial ended, a
287
+ // `process.exit` or a crash, is no timeout.
288
+ process.on("exit", () => {
289
+ if (this.#ended) return;
290
+ if (!this.#cancelled) {
291
+ const late =
292
+ this.deadline !== undefined && Date.now() >= this.deadline.getTime() - EXIT_SLACK_MS;
293
+ writeLine(late ? { timedOut: shared().phase } : { exited: shared().phase });
294
+ }
295
+ if (this.#tornDown) return;
296
+ for (const cleanup of this.#cleanups.toReversed()) {
297
+ try {
298
+ cleanup();
299
+ } catch {
300
+ // The process is ending: what teardown managed is all it gets.
301
+ }
302
+ }
303
+ });
304
+ // A cancel: the engine exits after its grace, so teardown starts at once.
305
+ const cancel = () => {
306
+ if (this.#ended || this.#cancelled) return;
307
+ this.#cancelled = true;
308
+ writeLine({ cancelled: shared().phase });
309
+ void this.teardown(this.settings.afterMs).then(() => {
310
+ shared().closed = true;
311
+ this.end();
312
+ });
313
+ };
314
+ process.once("SIGTERM", cancel);
315
+ process.once("SIGINT", cancel);
316
+ }
317
+
318
+ enter(phase: Phase): void {
319
+ shared().phase = phase;
320
+ writeLine({ phase });
321
+ }
322
+
323
+ /** A timer for a phase, at its limit or short of the run's deadline, whichever comes first. */
324
+ timer(phase: Phase, ms: number, reserve = DEADLINE_RESERVE_MS) {
325
+ const left = this.deadline ? this.deadline.getTime() - Date.now() - reserve : ms;
326
+ let handle: ReturnType<typeof setTimeout> | undefined;
327
+ const expired = new Promise<never>((_, reject) => {
328
+ handle = setTimeout(() => reject(new TimedOut(phase)), Math.max(0, Math.min(ms, left)));
329
+ });
330
+ expired.catch(() => {});
331
+ const started = Date.now();
332
+ return {
333
+ race: <T>(work: Promise<T>): Promise<T> => Promise.race([work, expired]),
334
+ left: () => ms - (Date.now() - started),
335
+ clear: () => clearTimeout(handle),
336
+ };
337
+ }
338
+
339
+ /** Writes how the trial failed, runs teardown, and throws: the run fails. */
340
+ async fail(error: unknown, by: "dataset" | "workflow", code?: DatasetError): Promise<never> {
341
+ if (error instanceof TimedOut) {
342
+ writeLine({ timedOut: error.phase });
343
+ await this.teardown(this.settings.afterMs);
344
+ shared().closed = true;
345
+ this.end();
346
+ throw error;
347
+ }
348
+ const failure =
349
+ error instanceof DatasetFailure
350
+ ? error
351
+ : error instanceof PreconditionFailed
352
+ ? new DatasetFailure("precondition", error.message)
353
+ : error instanceof CaseWiring
354
+ ? new DatasetFailure("threw", error.message)
355
+ : undefined;
356
+ const reason = messageOf(error);
357
+ writeLine({
358
+ error: {
359
+ by: failure ? "dataset" : by,
360
+ phase: shared().phase,
361
+ ...((failure?.code ?? code) ? { code: failure?.code ?? code } : {}),
362
+ reason,
363
+ },
364
+ });
365
+ await this.teardown(this.settings.afterMs);
366
+ this.end();
367
+ throw error;
368
+ }
369
+
370
+ teardown(ms: number): Promise<void> {
371
+ this.#tornDown ??= (async () => {
372
+ this.enter("teardown");
373
+ const timer = this.timer("teardown", ms, 1_000);
374
+ try {
375
+ await timer.race(runCleanups(this.#cleanups));
376
+ } catch (error) {
377
+ if (error instanceof TimedOut) writeLine({ timedOut: "teardown" });
378
+ else {
379
+ writeLine({
380
+ error: { by: "dataset", phase: "teardown", code: "threw", reason: messageOf(error) },
381
+ });
382
+ }
383
+ } finally {
384
+ timer.clear();
385
+ }
386
+ })();
387
+ return this.#tornDown;
388
+ }
389
+
390
+ end(): void {
391
+ this.#ended = true;
392
+ }
393
+ }
394
+
395
+ async function runCleanups(cleanups: readonly (() => unknown)[]): Promise<void> {
396
+ let first: unknown;
397
+ for (const cleanup of cleanups.toReversed()) {
398
+ try {
399
+ await cleanup();
400
+ } catch (error) {
401
+ first ??= error;
402
+ }
403
+ }
404
+ if (first !== undefined) throw first;
405
+ }
406
+
407
+ async function runInTrial<M extends WorkflowModule>(
408
+ spec: TrialSpec<M, ParamsSpec, unknown>,
409
+ wf: EngineContext,
410
+ ): Promise<EnvValue> {
411
+ const settings = trialSettings();
412
+ const caseDir = process.env[TRIAL_ENV.case];
413
+ if (!settings || !caseDir) throw new Error(NOT_IN_A_TRIAL);
414
+ const state = shared();
415
+ const mocks = new Mocks();
416
+ const cleanups: (() => unknown)[] = [];
417
+ const run = new TrialRun(settings, wf.deadline, cleanups);
418
+ const unmet = () =>
419
+ state.precondition ? new DatasetFailure("precondition", state.precondition) : undefined;
420
+ const folders = {
421
+ dir: caseDir,
422
+ scratch: process.env[TRIAL_ENV.scratch] ?? wf.cwd,
423
+ root: process.env[TRIAL_ENV.root] ?? process.cwd(),
424
+ params: trialParams(),
425
+ };
426
+
427
+ run.enter("setup");
428
+ const loadedBefore = new Set(Object.keys(require.cache));
429
+ let setup: Setup<unknown>;
430
+ const trial = makeTrial(folders, mocks, cleanups);
431
+ const setupTimer = run.timer("setup", settings.setupMs);
432
+ try {
433
+ setup = (await setupTimer.race(
434
+ Promise.resolve().then(() => spec.setup(trial)),
435
+ )) as Setup<unknown>;
436
+ } catch (error) {
437
+ // A precondition failed, caught, then setup threw: the precondition is why.
438
+ return run.fail(unmet() ?? error, "dataset", "threw");
439
+ } finally {
440
+ setupTimer.clear();
441
+ }
442
+ // A precondition setup caught, or never awaited, still holds the workflow back.
443
+ const unmetBefore = unmet();
444
+ if (unmetBefore) return run.fail(unmetBefore, "dataset");
445
+ const wrong = setupProblem(setup);
446
+ if (wrong) return run.fail(new DatasetFailure("threw", wrong), "dataset");
447
+ const unused = () => [
448
+ ...mocks.unused(),
449
+ ...state.routes.filter((route) => route.calls === 0).map((route) => route.key),
450
+ ];
451
+ let refusedWritten = false;
452
+ const writeRefused = () => {
453
+ const first = state.refused[0];
454
+ if (refusedWritten || !first) return;
455
+ refusedWritten = true;
456
+ writeLine({
457
+ error: { by: "dataset", phase: first.phase, code: "refused", reason: first.message },
458
+ });
459
+ };
460
+ const ready = setup;
461
+ const stubs = setup.stubStages ?? {};
462
+ const stopAfter = setup.stopAfterStage;
463
+
464
+ /**
465
+ * `evidence` on how the workflow ended, the trial file's `end` line and teardown: the run's
466
+ * value, or the workflow's own ending thrown again.
467
+ */
468
+ const gatherAndEnd = async (ended: {
469
+ /** Present only when the workflow returned. */
470
+ returned?: { value: unknown };
471
+ stages: Record<string, unknown>;
472
+ stubbed: Record<string, unknown>;
473
+ stoppedAfter?: string;
474
+ /** The workflow's own ending, thrown again once the trial is written. */
475
+ rethrow?: unknown;
476
+ workflow?: EnvValue["workflow"];
477
+ }): Promise<EnvValue> => {
478
+ run.enter("evidence");
479
+ const evidenceTimer = run.timer("evidence", settings.afterMs);
480
+ let gathered: Evidence | undefined;
481
+ try {
482
+ const evidence = ready.evidence;
483
+ gathered = evidence
484
+ ? await evidenceTimer.race(
485
+ Promise.resolve().then(() =>
486
+ evidence({ result: ended.returned?.value, stages: { ...ended.stages } }),
487
+ ),
488
+ )
489
+ : undefined;
490
+ } catch (error) {
491
+ evidenceTimer.clear();
492
+ return run.fail(error, "dataset", "threw");
493
+ }
494
+ evidenceTimer.clear();
495
+ const problem = unmet() ?? evidenceProblem(gathered);
496
+ if (problem) return run.fail(problem, "dataset");
497
+ writeRefused();
498
+ const unusedNow = unused();
499
+ writeLine({ unused: unusedNow });
500
+ const record: Gathered = {
501
+ ...(ended.returned ? { result: asJson(ended.returned.value) } : {}),
502
+ stages: asJson(ended.stages) as Gathered["stages"],
503
+ stubbedStages: asJson(ended.stubbed) as Gathered["stubbedStages"],
504
+ ...(ended.stoppedAfter !== undefined ? { stoppedAfter: ended.stoppedAfter } : {}),
505
+ calls: mocks.calls(),
506
+ requests: state.requests.map((request) => ({ ...request })),
507
+ ...(gathered?.values !== undefined ? { values: asJson(gathered.values) } : {}),
508
+ files: [...(gathered?.files ?? [])],
509
+ };
510
+ writeLine({ end: record });
511
+ await run.teardown(Math.max(evidenceTimer.left(), 1_000));
512
+ run.end();
513
+ if (ended.rethrow !== undefined) throw ended.rethrow;
514
+ return {
515
+ ...(ended.workflow ? { workflow: ended.workflow } : {}),
516
+ ...record,
517
+ unused: unusedNow,
518
+ refused: state.refused,
519
+ };
520
+ };
521
+
522
+ run.enter("body");
523
+ const body = run.timer("body", settings.runMs);
524
+ let module: unknown;
525
+ try {
526
+ module = await body.race(Promise.resolve().then(() => spec.workflow(trial)));
527
+ } catch (error) {
528
+ body.clear();
529
+ const missing =
530
+ (error as { code?: unknown })?.code === "ERR_MODULE_NOT_FOUND" &&
531
+ loadedBefore.has(String((error as { referrer?: unknown }).referrer));
532
+ return missing
533
+ ? run.fail(new DatasetFailure("workflow-missing", messageOf(error)), "dataset")
534
+ : run.fail(error, "workflow");
535
+ }
536
+ const inner = (module as { default?: unknown } | undefined)?.default as InnerWorkflow | undefined;
537
+ const refuse = (code: DatasetError | undefined, reason: string) => {
538
+ body.clear();
539
+ return run.fail(new DatasetFailure(code, reason), "dataset");
540
+ };
541
+ if (typeof inner !== "object" || inner === null || typeof inner.run !== "function") {
542
+ return refuse("workflow-missing", "the module workflow(trial) imported exports no workflow");
543
+ }
544
+ const workflow = {
545
+ name: inner.meta?.name ?? "",
546
+ ...(inner.meta?.version ? { version: inner.meta.version } : {}),
547
+ };
548
+ writeLine({ workflow });
549
+ const file = module && typeof module === "object" ? fileOf(module) : undefined;
550
+ if (file && loadedBefore.has(file)) {
551
+ return refuse(
552
+ "workflow-loaded-early",
553
+ `${file} was loaded before setup, so mocks missed what it took as it loaded: trial.ts reaches the workflow only through its lazy workflow import, and imports its types with import type`,
554
+ );
555
+ }
556
+ if (inner.events !== undefined) {
557
+ return refuse("events", "a workflow with events can't be run on a case");
558
+ }
559
+ const copied = copiedModule(mocks.files, folders.root, folders.scratch);
560
+ if (copied) {
561
+ return refuse(undefined, `mocked ${copied} in your checkout; the workflow loads the copy`);
562
+ }
563
+ let args: unknown = null;
564
+ try {
565
+ args = inner.prepare ? inner.prepare({ argv: setup.argv ?? [], cwd: wf.cwd }) : null;
566
+ } catch (error) {
567
+ return refuse("prepare", `the workflow's prepare refused the case's argv: ${messageOf(error)}`);
568
+ }
569
+
570
+ const reached = {
571
+ stopped: false,
572
+ entered: new Set<string>(),
573
+ values: {} as Record<string, unknown>,
574
+ stubbed: {} as Record<string, unknown>,
575
+ };
576
+ let stubProblem: DatasetFailure | undefined;
577
+ const stage = async (name: string, ...rest: unknown[]) => {
578
+ if (reached.stopped && stopAfter !== undefined) throw new StoppedAfter(stopAfter);
579
+ reached.entered.add(name);
580
+ const stub = Object.hasOwn(stubs, name);
581
+ const value = stub ? stubs[name] : undefined;
582
+ const work = stub
583
+ ? async () => {
584
+ try {
585
+ return typeof value === "function" ? await value() : value;
586
+ } catch (error) {
587
+ stubProblem ??= new DatasetFailure(
588
+ "threw",
589
+ `the value stubStages gave ${name} threw: ${messageOf(error)}`,
590
+ );
591
+ throw error;
592
+ }
593
+ }
594
+ : rest.at(-1);
595
+ let returned: unknown;
596
+ try {
597
+ returned = await wf.stage(name, ...rest.slice(0, -1), work);
598
+ } catch (error) {
599
+ if (stub && !isStop(error)) {
600
+ stubProblem ??= new DatasetFailure(
601
+ "given-refused",
602
+ `${name} refused the value stubStages gave it: ${messageOf(error)}`,
603
+ );
604
+ }
605
+ throw error;
606
+ }
607
+ // A stage with no result is `undefined`, which a run's value can't hold. A stubbed stage's
608
+ // value is the case's, kept apart from the workflow's own work.
609
+ if (returned !== undefined) (stub ? reached.stubbed : reached.values)[name] = returned;
610
+ if (name === stopAfter) {
611
+ reached.stopped = true;
612
+ throw new StoppedAfter(name);
613
+ }
614
+ return returned;
615
+ };
616
+ const labWf = Object.create(wf, { stage: { value: stage } });
617
+
618
+ let ending: { returned: unknown } | { threw: unknown };
619
+ try {
620
+ ending = { returned: await body.race(Promise.resolve().then(() => inner.run(labWf, args))) };
621
+ } catch (error) {
622
+ ending = { threw: error };
623
+ } finally {
624
+ body.clear();
625
+ }
626
+ if (stubProblem) return run.fail(stubProblem, "dataset");
627
+ // A precondition not awaited that failed while the body ran: the workflow ran unready.
628
+ const unmetInBody = unmet();
629
+ if (unmetInBody) return run.fail(unmetInBody, "dataset");
630
+
631
+ writeRefused();
632
+ const gathered = { stages: reached.values, stubbed: reached.stubbed, workflow };
633
+ if ("threw" in ending && ending.threw instanceof TimedOut) {
634
+ // The workflow's own timeout: the world is gathered still, then the trial fails as its.
635
+ const timedOut = ending.threw;
636
+ try {
637
+ await gatherAndEnd({ ...gathered, rethrow: timedOut });
638
+ } catch (error) {
639
+ if (error !== timedOut) throw error;
640
+ }
641
+ return run.fail(timedOut, "workflow");
642
+ }
643
+ if (!reached.stopped && "threw" in ending) {
644
+ const stop = isStop(ending.threw) ? (ending.threw as Error) : undefined;
645
+ if (stop) writeLine({ stopped: { reason: stop.message } });
646
+ else if (!refusedWritten) {
647
+ writeLine({ error: { by: "workflow", phase: "body", reason: messageOf(ending.threw) } });
648
+ }
649
+ return gatherAndEnd({ ...gathered, rethrow: ending.threw });
650
+ }
651
+ // A stage the case named that the run never entered, misspelt or skipped, is the dataset's: no
652
+ // source scan, which can't see a stage named at run time or in another package.
653
+ const named = [...Object.keys(stubs), ...(stopAfter !== undefined ? [stopAfter] : [])];
654
+ const missed = [...new Set(named.filter((name) => !reached.entered.has(name)))];
655
+ if (missed.length > 0) {
656
+ const field = Object.hasOwn(stubs, missed[0]!) ? "stubStages" : "stopAfterStage";
657
+ return run.fail(
658
+ new DatasetFailure(
659
+ "stage-not-entered",
660
+ `the run never entered stage ${missed.join(", ")}, which ${field} names: check its spelling, or leave it out of what setup returns for a case whose workflow ends before it`,
661
+ ),
662
+ "dataset",
663
+ );
664
+ }
665
+ // A `wf.stop` once the run stopped after its stage passes through, the record written first.
666
+ const stop = "threw" in ending && isStop(ending.threw) ? (ending.threw as Error) : undefined;
667
+ if (stop) writeLine({ stopped: { reason: stop.message } });
668
+ return gatherAndEnd({
669
+ ...gathered,
670
+ ...(stop ? { rethrow: stop } : {}),
671
+ ...(reached.stopped && stopAfter !== undefined
672
+ ? { stoppedAfter: stopAfter }
673
+ : { returned: { value: (ending as { returned: unknown }).returned } }),
674
+ });
675
+ }
676
+
677
+ const SETUP_FIELDS = ["argv", "stubStages", "stopAfterStage", "evidence"];
678
+ const GONE: Record<string, string> = {
679
+ answer:
680
+ "a case's known good record is its key/good/record.json, which case check grades with no setup",
681
+ observe: "facts are read off the trial record by grading.ts's facts",
682
+ stages: "it is stubStages",
683
+ until: "it is stopAfterStage",
684
+ };
685
+
686
+ /** What is wrong with what `setup` returned, if anything. */
687
+ function setupProblem(setup: unknown): string | undefined {
688
+ if (typeof setup !== "object" || setup === null || Array.isArray(setup)) {
689
+ return "setup returned no object: return { argv, stubStages?, stopAfterStage?, evidence? }";
690
+ }
691
+ for (const field of Object.keys(setup)) {
692
+ if (SETUP_FIELDS.includes(field)) continue;
693
+ return `setup returned ${field}, which it doesn't take${GONE[field] ? `: ${GONE[field]}` : ""}; it returns ${SETUP_FIELDS.join(", ")}`;
694
+ }
695
+ const { evidence, stubStages, stopAfterStage } = setup as Setup<unknown>;
696
+ if (evidence !== undefined && typeof evidence !== "function") {
697
+ return "setup's evidence is a function: evidence: ({ result, stages }) => ({ files?, values? })";
698
+ }
699
+ if (stubStages !== undefined && (typeof stubStages !== "object" || stubStages === null)) {
700
+ return "setup's stubStages is an object: { stage: value }";
701
+ }
702
+ if (stopAfterStage !== undefined && typeof stopAfterStage !== "string") {
703
+ return "setup's stopAfterStage is a stage's name";
704
+ }
705
+ return undefined;
706
+ }
707
+
708
+ /** What is wrong with what `evidence` returned, if anything. */
709
+ function evidenceProblem(evidence: unknown): DatasetFailure | undefined {
710
+ if (evidence === undefined) return undefined;
711
+ const bad = (reason: string) => new DatasetFailure("evidence", reason);
712
+ if (typeof evidence !== "object" || evidence === null || Array.isArray(evidence)) {
713
+ return bad("evidence returned no object: return { files?, values? }");
714
+ }
715
+ const extra = Object.keys(evidence).filter((field) => field !== "files" && field !== "values");
716
+ if (extra.length > 0) {
717
+ return bad(`evidence returned ${extra.join(", ")}: it returns files and values`);
718
+ }
719
+ const { files } = evidence as Evidence;
720
+ if (files === undefined) return undefined;
721
+ if (!Array.isArray(files) || files.some((file) => typeof file !== "string" || file === "")) {
722
+ return bad("evidence's files is a list of paths in trial.scratch");
723
+ }
724
+ const outside = files.find((file) => file.startsWith("/") || file.split(/[\\/]/).includes(".."));
725
+ if (outside) return bad(`evidence's files: ${outside} reaches outside trial.scratch`);
726
+ return undefined;
727
+ }