@lelouchhe/agent-evals 0.0.0-stage → 0.1.1

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 (105) hide show
  1. package/.env.example +27 -0
  2. package/LICENSE +21 -0
  3. package/README.md +117 -2
  4. package/dist/checkers/file/index.d.ts +26 -0
  5. package/dist/checkers/file/index.js +228 -0
  6. package/dist/checkers/judge/index.d.ts +20 -0
  7. package/dist/checkers/judge/index.js +262 -0
  8. package/dist/checkers/judge/prompt.d.ts +18 -0
  9. package/dist/checkers/judge/prompt.js +36 -0
  10. package/dist/checkers/judge/trace.d.ts +6 -0
  11. package/dist/checkers/judge/trace.js +41 -0
  12. package/dist/checkers/mock/index.d.ts +18 -0
  13. package/dist/checkers/mock/index.js +127 -0
  14. package/dist/checkers/shell/index.d.ts +10 -0
  15. package/dist/checkers/shell/index.js +61 -0
  16. package/dist/checkers/trace/index.d.ts +22 -0
  17. package/dist/checkers/trace/index.js +183 -0
  18. package/dist/cli.d.ts +2 -0
  19. package/dist/cli.js +352 -0
  20. package/dist/engine/authoring.d.ts +24 -0
  21. package/dist/engine/authoring.js +261 -0
  22. package/dist/engine/check-runner.d.ts +1 -0
  23. package/dist/engine/check-runner.js +127 -0
  24. package/dist/engine/check-sandbox.d.ts +18 -0
  25. package/dist/engine/check-sandbox.js +171 -0
  26. package/dist/engine/config.d.ts +142 -0
  27. package/dist/engine/config.js +362 -0
  28. package/dist/engine/env-source.d.ts +10 -0
  29. package/dist/engine/env-source.js +114 -0
  30. package/dist/engine/files.d.ts +87 -0
  31. package/dist/engine/files.js +307 -0
  32. package/dist/engine/forwarder.sh +61 -0
  33. package/dist/engine/ignore.d.ts +29 -0
  34. package/dist/engine/ignore.js +67 -0
  35. package/dist/engine/messages.d.ts +8 -0
  36. package/dist/engine/messages.js +9 -0
  37. package/dist/engine/mock-match.d.ts +44 -0
  38. package/dist/engine/mock-match.js +104 -0
  39. package/dist/engine/mocks.d.ts +35 -0
  40. package/dist/engine/mocks.js +336 -0
  41. package/dist/engine/params.d.ts +16 -0
  42. package/dist/engine/params.js +86 -0
  43. package/dist/engine/placement.d.ts +26 -0
  44. package/dist/engine/placement.js +107 -0
  45. package/dist/engine/regex.d.ts +10 -0
  46. package/dist/engine/regex.js +16 -0
  47. package/dist/engine/registry.d.ts +234 -0
  48. package/dist/engine/registry.js +127 -0
  49. package/dist/engine/report.d.ts +17 -0
  50. package/dist/engine/report.js +385 -0
  51. package/dist/engine/results.d.ts +43 -0
  52. package/dist/engine/results.js +39 -0
  53. package/dist/engine/run.d.ts +47 -0
  54. package/dist/engine/run.js +566 -0
  55. package/dist/engine/runtime-assets.d.ts +6 -0
  56. package/dist/engine/runtime-assets.js +11 -0
  57. package/dist/engine/skills.d.ts +49 -0
  58. package/dist/engine/skills.js +270 -0
  59. package/dist/engine/truncate.d.ts +3 -0
  60. package/dist/engine/truncate.js +7 -0
  61. package/dist/engine/values.d.ts +18 -0
  62. package/dist/engine/values.js +75 -0
  63. package/dist/engine/view.d.ts +10 -0
  64. package/dist/engine/view.js +38 -0
  65. package/dist/engine/workspace.d.ts +56 -0
  66. package/dist/engine/workspace.js +280 -0
  67. package/dist/index.d.ts +16 -0
  68. package/dist/index.js +7 -0
  69. package/dist/platform/macos/launch.d.ts +13 -0
  70. package/dist/platform/macos/launch.js +14 -0
  71. package/dist/platform/macos/policy.d.ts +33 -0
  72. package/dist/platform/macos/policy.js +131 -0
  73. package/dist/platform/macos/supervise.d.ts +26 -0
  74. package/dist/platform/macos/supervise.js +98 -0
  75. package/dist/platform/macos/supervisor.sh +13 -0
  76. package/dist/runners/acp/agent.d.ts +17 -0
  77. package/dist/runners/acp/agent.js +38 -0
  78. package/dist/runners/acp/commands.d.ts +2 -0
  79. package/dist/runners/acp/commands.js +112 -0
  80. package/dist/runners/acp/environment.d.ts +71 -0
  81. package/dist/runners/acp/environment.js +280 -0
  82. package/dist/runners/acp/index.d.ts +21 -0
  83. package/dist/runners/acp/index.js +131 -0
  84. package/dist/runners/acp/session.d.ts +7 -0
  85. package/dist/runners/acp/session.js +48 -0
  86. package/dist/runners/acp/trace.d.ts +23 -0
  87. package/dist/runners/acp/trace.js +44 -0
  88. package/dist/runners/acp/usage.d.ts +12 -0
  89. package/dist/runners/acp/usage.js +56 -0
  90. package/dist/runners/noop/index.d.ts +12 -0
  91. package/dist/runners/noop/index.js +22 -0
  92. package/dist/runners/pi/index.d.ts +21 -0
  93. package/dist/runners/pi/index.js +116 -0
  94. package/dist/runners/pi/params.d.ts +10 -0
  95. package/dist/runners/pi/params.js +3 -0
  96. package/dist/runners/pi/rpc.d.ts +30 -0
  97. package/dist/runners/pi/rpc.js +341 -0
  98. package/dist/runners/pi/safe-process-group.d.ts +7 -0
  99. package/dist/runners/pi/safe-process-group.js +13 -0
  100. package/dist/runners/pi/session.d.ts +56 -0
  101. package/dist/runners/pi/session.js +298 -0
  102. package/dist/runners/pi/shell-wrapper.sh +46 -0
  103. package/dist/runners/pi/supervisor.d.ts +1 -0
  104. package/dist/runners/pi/supervisor.js +101 -0
  105. package/package.json +77 -4
@@ -0,0 +1,566 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { cp, lstat, mkdir, realpath, rm, stat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { assertSeatbeltAvailable } from "../platform/macos/policy.js";
6
+ import { ConfigError, errorMessage, resolveAuthoringAsset, } from "./config.js";
7
+ import { requireChecker, requireRunner, } from "./registry.js";
8
+ import { createResultDirectory, newRunId, writeResult, } from "./results.js";
9
+ import { createEnvSource } from "./env-source.js";
10
+ import { authoringCopyFilter, copyPlacement, fileIdentity, homeEntries, placeCaseFiles, placedPaths, stageEntries, validateCheckFiles, } from "./files.js";
11
+ import { startMockHost } from "./mocks.js";
12
+ import { createCheckSandbox } from "./check-sandbox.js";
13
+ import { parseImplementationParams } from "./params.js";
14
+ import { truncate, truncateNullable } from "./truncate.js";
15
+ import { substituteValues } from "./values.js";
16
+ import { isMissing, openRunRoot } from "./workspace.js";
17
+ const DEFAULT_TIMEOUT_MS = 300_000;
18
+ const CHECK_ABORT_GRACE_MS = 12_000;
19
+ const MAX_RECORDED_TEXT = 4_000;
20
+ /**
21
+ * Validate a case and bind it to new run directories without creating them, so a caller can
22
+ * validate every selected case before the first one runs.
23
+ */
24
+ export async function prepareEvaluation(request) {
25
+ const runId = newRunId();
26
+ const startedAt = new Date().toISOString();
27
+ // Placeholders need the run directories' paths; they are created only after validation.
28
+ // The parent is canonicalized first: the sandbox authorizes the `deps` link only when the
29
+ // run-root path and its target carry no symlink spelling such as `/tmp` for `/private/tmp`.
30
+ const parent = await realpath(request.tempParent ?? tmpdir());
31
+ const root = join(parent, `run-${randomBytes(6).toString("hex")}`);
32
+ const workspaceDir = join(root, "workspace");
33
+ const homeDir = join(root, "home");
34
+ const tmpDir = join(root, "tmp");
35
+ const mocksDir = join(root, "mocks");
36
+ const engineDir = join(root, "engine");
37
+ const configDir = join(root, "config");
38
+ const baselineWorkspaceDir = join(engineDir, "baseline", "workspace");
39
+ const baselineHomeDir = join(engineDir, "baseline", "home");
40
+ const registered = await prepareImplementations(request, {
41
+ env: request.envSource ?? createEnvSource(process.cwd(), request.signal),
42
+ run: { HOME: homeDir, TMPDIR: tmpDir },
43
+ }, request.signal);
44
+ await validateAuthoringAssets(request.case);
45
+ return {
46
+ request,
47
+ runId,
48
+ startedAt,
49
+ root,
50
+ workspaceDir,
51
+ homeDir,
52
+ tmpDir,
53
+ mocksDir,
54
+ engineDir,
55
+ configDir,
56
+ baselineWorkspaceDir,
57
+ baselineHomeDir,
58
+ registered,
59
+ };
60
+ }
61
+ /** Validate configuration, execute one runner, run all checks, and clean up. */
62
+ export async function runEvaluation(request) {
63
+ return executeEvaluation(await prepareEvaluation(request));
64
+ }
65
+ /** Execute one prepared case: prepare the run root, drive the runner, check, record and clean up. */
66
+ export async function executeEvaluation(prepared) {
67
+ const { request, runId, startedAt, root, workspaceDir, homeDir, tmpDir, mocksDir, engineDir, configDir, baselineWorkspaceDir, baselineHomeDir, registered, } = prepared;
68
+ const timeoutMs = request.case.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
69
+ const abort = new AbortController();
70
+ let cancelled = request.signal?.aborted ?? false;
71
+ const onAbort = () => {
72
+ cancelled = true;
73
+ abort.abort();
74
+ };
75
+ if (request.signal?.aborted === true) {
76
+ abort.abort();
77
+ }
78
+ request.signal?.addEventListener("abort", onAbort, { once: true });
79
+ try {
80
+ // Exclusive creation, like mkdtemp: an existing path is an error, not reused.
81
+ await mkdir(root, { mode: 0o700 });
82
+ }
83
+ catch (error) {
84
+ request.signal?.removeEventListener("abort", onAbort);
85
+ throw error;
86
+ }
87
+ let runner;
88
+ let cleanup = { status: "removed" };
89
+ let runnerRecord = {
90
+ type: registered.runnerType,
91
+ status: "error",
92
+ durationMs: 0,
93
+ finalText: null,
94
+ };
95
+ let checks = [];
96
+ let trace;
97
+ let usage;
98
+ let mockRecords;
99
+ let mockHost;
100
+ let mockFailed = false;
101
+ const diagnostics = [];
102
+ let error;
103
+ let status;
104
+ let timedOut = false;
105
+ let stopFailed = false;
106
+ let timer;
107
+ try {
108
+ await Promise.all([
109
+ mkdir(workspaceDir, { mode: 0o700 }),
110
+ mkdir(homeDir, { mode: 0o700 }),
111
+ mkdir(tmpDir, { mode: 0o700 }),
112
+ mkdir(mocksDir, { mode: 0o700 }),
113
+ mkdir(join(engineDir, "baseline", "workspace"), { recursive: true, mode: 0o700 }),
114
+ mkdir(join(engineDir, "baseline", "home"), { recursive: true, mode: 0o700 }),
115
+ ]);
116
+ const fixture = request.case.config.fixture;
117
+ if (fixture !== undefined) {
118
+ const source = resolveAuthoringAsset(request.case.dir, fixture, "case.fixture");
119
+ await cp(source, workspaceDir, {
120
+ recursive: true,
121
+ preserveTimestamps: true,
122
+ filter: authoringCopyFilter(source),
123
+ });
124
+ }
125
+ await placeCaseFiles(request.case, join(engineDir, "files", "workspace"), workspaceDir);
126
+ const workspaceRoot = await openRunRoot(workspaceDir);
127
+ // The runner places its own HOME content first; the case then overlays it without
128
+ // touching login state, and only what the case placed becomes the HOME baseline.
129
+ const context = {
130
+ workspaceDir,
131
+ homeDir,
132
+ tmpDir,
133
+ engineDir,
134
+ configDir,
135
+ runRootDir: root,
136
+ input: request.case.config.input,
137
+ timeoutMs,
138
+ signal: abort.signal,
139
+ };
140
+ runner = registered.runner;
141
+ const protectedPaths = (await runner.prepareHome?.(context)) ?? [];
142
+ // Login state is protected by the file the filesystem actually holds at each declared
143
+ // path, so a differently-cased or otherwise normalised spelling cannot alias it.
144
+ const protectedIdentities = [];
145
+ for (const path of protectedPaths) {
146
+ try {
147
+ const info = await lstat(join(homeDir, path), { bigint: true });
148
+ if (info.isFile())
149
+ protectedIdentities.push(fileIdentity(info));
150
+ }
151
+ catch (error) {
152
+ if (!isMissing(error))
153
+ throw error;
154
+ }
155
+ }
156
+ const homePlacements = homeEntries(request.case.config.files);
157
+ const homeStaging = join(engineDir, "files", "home");
158
+ if (homePlacements.length > 0) {
159
+ await stageEntries(homePlacements, request.case.dir, homeStaging, "files", abort.signal);
160
+ try {
161
+ await copyPlacement(homeStaging, homeDir, {
162
+ label: "files",
163
+ overwrite: true,
164
+ protect: { paths: protectedPaths, identities: protectedIdentities },
165
+ signal: abort.signal,
166
+ });
167
+ await cp(homeStaging, baselineHomeDir, { recursive: true, preserveTimestamps: true });
168
+ }
169
+ finally {
170
+ await rm(homeStaging, { recursive: true, force: true });
171
+ }
172
+ }
173
+ const homeRoot = await openRunRoot(homeDir);
174
+ // Forwarders are written before the baseline snapshot, so it already holds them.
175
+ const mocks = request.case.config.mocks;
176
+ if (mocks !== undefined) {
177
+ mockHost = await startMockHost({
178
+ runRootDir: root,
179
+ engineDir,
180
+ mocksDir,
181
+ workspaceDir: workspaceRoot.path,
182
+ tmpDir,
183
+ authoringDir: request.case.dir,
184
+ shell: mocks.shell,
185
+ timeoutMs,
186
+ signal: abort.signal,
187
+ });
188
+ }
189
+ await cp(workspaceDir, baselineWorkspaceDir, { recursive: true, preserveTimestamps: true });
190
+ const baselineRoot = await openRunRoot(baselineWorkspaceDir);
191
+ const homeBaselineRoot = await openRunRoot(baselineHomeDir);
192
+ const started = performance.now();
193
+ let outcome;
194
+ timer = setTimeout(() => {
195
+ timedOut = true;
196
+ abort.abort();
197
+ void runner?.stop().catch(() => { });
198
+ }, timeoutMs);
199
+ try {
200
+ outcome = await runner.run({
201
+ ...context,
202
+ ...(mockHost === undefined ? {} : { mocks: mockHost.wiring }),
203
+ });
204
+ }
205
+ catch (caught) {
206
+ if (!abort.signal.aborted) {
207
+ error = errorMessage(caught);
208
+ }
209
+ diagnostics.push(...diagnosticsOf(caught));
210
+ }
211
+ finally {
212
+ if (timer !== undefined) {
213
+ clearTimeout(timer);
214
+ timer = undefined;
215
+ }
216
+ try {
217
+ await runner.stop();
218
+ }
219
+ catch (caught) {
220
+ stopFailed = true;
221
+ diagnostics.push(`failed to stop runner: ${errorMessage(caught)}`);
222
+ error ??= `failed to stop runner: ${errorMessage(caught)}`;
223
+ }
224
+ // Closing the host must not depend on the runner's trace, and vice versa.
225
+ try {
226
+ if (mockHost !== undefined) {
227
+ const outcome = await mockHost.close();
228
+ mockRecords = outcome.records;
229
+ if (outcome.faults.length > 0) {
230
+ mockFailed = true;
231
+ diagnostics.push(...outcome.faults);
232
+ error ??= outcome.faults[0];
233
+ }
234
+ }
235
+ }
236
+ finally {
237
+ trace = runner.trace?.();
238
+ usage = runner.usage?.();
239
+ }
240
+ }
241
+ const runnerStatus = stopFailed
242
+ ? "error"
243
+ : outcome !== undefined
244
+ ? "completed"
245
+ : cancelled
246
+ ? "cancelled"
247
+ : timedOut
248
+ ? "timeout"
249
+ : "error";
250
+ runnerRecord = {
251
+ type: registered.runnerType,
252
+ status: runnerStatus,
253
+ durationMs: Math.round(performance.now() - started),
254
+ finalText: outcome === undefined ? null : truncateNullable(outcome.finalText, MAX_RECORDED_TEXT),
255
+ ...(usage === undefined ? {} : { usage }),
256
+ };
257
+ if (outcome !== undefined) {
258
+ diagnostics.push(...outcome.diagnostics);
259
+ checks = await runChecks(registered.checks, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, trace, mockRecords, timeoutMs, abort.signal, () => {
260
+ cancelled = true;
261
+ });
262
+ }
263
+ if (cancelled) {
264
+ status = "cancelled";
265
+ error ??= "run was cancelled";
266
+ }
267
+ else if (timedOut) {
268
+ status = "timeout";
269
+ error ??= `runner exceeded the ${timeoutMs}ms execution timeout`;
270
+ }
271
+ else if (runnerStatus !== "completed") {
272
+ status = "error";
273
+ error ??= "runner failed before checks could run";
274
+ }
275
+ else if (mockFailed) {
276
+ status = "error";
277
+ error ??= "a mock fault ended the run";
278
+ }
279
+ else if (checks.some((check) => check.status === "error")) {
280
+ status = "error";
281
+ error ??= "one or more checks could not be evaluated";
282
+ }
283
+ else if (checks.some((check) => check.status === "fail")) {
284
+ status = "fail";
285
+ }
286
+ else {
287
+ status = "pass";
288
+ }
289
+ }
290
+ catch (caught) {
291
+ status = cancelled ? "cancelled" : "error";
292
+ error ??= errorMessage(caught);
293
+ diagnostics.push(...diagnosticsOf(caught));
294
+ }
295
+ finally {
296
+ if (timer !== undefined) {
297
+ clearTimeout(timer);
298
+ }
299
+ request.signal?.removeEventListener("abort", onAbort);
300
+ // A backstop for any failure before the runner's own teardown; close is idempotent.
301
+ if (mockHost !== undefined) {
302
+ try {
303
+ await mockHost.close();
304
+ }
305
+ catch (caught) {
306
+ diagnostics.push(`failed to close mock host: ${errorMessage(caught)}`);
307
+ }
308
+ }
309
+ try {
310
+ await rm(root, { recursive: true, force: true, maxRetries: 3 });
311
+ }
312
+ catch (caught) {
313
+ cleanup = { status: "failed", error: errorMessage(caught) };
314
+ }
315
+ }
316
+ if (cleanup.status === "failed") {
317
+ status = "error";
318
+ error = error === undefined ? `cleanup failed: ${cleanup.error}` : `${error}; cleanup failed: ${cleanup.error}`;
319
+ }
320
+ const record = {
321
+ schemaVersion: 1,
322
+ runId,
323
+ startedAt,
324
+ finishedAt: new Date().toISOString(),
325
+ case: {
326
+ path: request.case.path,
327
+ ...(request.case.name === undefined ? {} : { name: request.case.name }),
328
+ },
329
+ resolvedConfig: request.case.config,
330
+ status,
331
+ runner: runnerRecord,
332
+ checks,
333
+ ...(error === undefined ? {} : { error }),
334
+ diagnostics: boundedDiagnostics(diagnostics),
335
+ cleanup,
336
+ };
337
+ const paths = await createResultDirectory(request.resultsDir, runId);
338
+ await writeResult(paths, record, trace, mockRecords);
339
+ return record;
340
+ }
341
+ async function prepareImplementations(request, values, signal) {
342
+ const mockTargets = request.case.config.mocks === undefined ? undefined : Object.keys(request.case.config.mocks.shell);
343
+ const runnerDefinition = requireRunner(request.registry, request.case.config.runner.$type);
344
+ if (request.case.config.mocks !== undefined && runnerDefinition.mocks !== true) {
345
+ throw new ConfigError(`runner "${runnerDefinition.type}" does not support mocks`);
346
+ }
347
+ const runnerSupportsHome = runnerDefinition.home === true;
348
+ if (!runnerSupportsHome && homeEntries(request.case.config.files).length > 0) {
349
+ throw new ConfigError(`runner "${runnerDefinition.type}" does not support case files under "~"`);
350
+ }
351
+ // The case runner's placeholders resolve once; a checker-declared runner arrives resolved with
352
+ // the checker parameters it was written in, so neither declaration is walked twice.
353
+ const caseRunnerParams = await substituteValues(paramsOf(request.case.config.runner), "runner", values);
354
+ const createRunner = async (record) => {
355
+ const declaration = record ?? request.case.config.runner;
356
+ const definition = requireRunner(request.registry, declaration.$type);
357
+ const params = await parseImplementationParams(definition.params,
358
+ // Each instance gets its own copy: a schema may keep a value it was given, and the case
359
+ // runner's parameters are also the inherited judge's.
360
+ structuredClone(record === undefined ? caseRunnerParams : paramsOf(record)), `runner "${definition.type}"`);
361
+ return { type: definition.type, runner: await definition.create(params, context) };
362
+ };
363
+ const context = {
364
+ authoringDir: request.case.dir,
365
+ values,
366
+ validateFiles: (files) => validateCheckFiles(files, request.case.dir, "check files", signal),
367
+ ...(mockTargets === undefined ? {} : { mockTargets }),
368
+ runnerSupportsHome,
369
+ validateCheckPlatform: async () => assertSeatbeltAvailable(),
370
+ createRunner,
371
+ };
372
+ const { runner } = await createRunner();
373
+ await validateCaseHomePlacement(request.case, runner.homeFiles ?? [], signal);
374
+ const checks = [];
375
+ for (const [index, record] of request.case.config.checks.entries()) {
376
+ const definition = requireChecker(request.registry, record.$type);
377
+ const params = await parseImplementationParams(definition.params, await substituteValues(paramsOf(record), `checks[${index}]`, values), `checker "${definition.type}"`);
378
+ checks.push({ type: definition.type, checker: await createChecker(definition, params, index, context) });
379
+ }
380
+ return { runnerType: runnerDefinition.type, runner, checks };
381
+ }
382
+ /**
383
+ * Create one checker and name the declaration in its failure: a checker may create a runner of its
384
+ * own, so the nested error has to say which check asked for it.
385
+ */
386
+ async function createChecker(definition, params, index, context) {
387
+ try {
388
+ return await definition.create(params, context);
389
+ }
390
+ catch (error) {
391
+ if (error instanceof ConfigError) {
392
+ throw new ConfigError(`checks[${index}] (checker "${definition.type}"): ${error.message}`, { cause: error });
393
+ }
394
+ throw error;
395
+ }
396
+ }
397
+ /**
398
+ * Reject a case's `~/` placement that would land on login state, including a directory source
399
+ * whose contents name a login file. Runs while every selected case is prepared, before any
400
+ * case executes; the filesystem-level alias guard still applies at placement time.
401
+ */
402
+ async function validateCaseHomePlacement(loadedCase, loginFiles, signal) {
403
+ const entries = homeEntries(loadedCase.config.files);
404
+ if (entries.length === 0 || loginFiles.length === 0) {
405
+ return;
406
+ }
407
+ let placed;
408
+ try {
409
+ placed = await placedPaths(entries, loadedCase.dir, "files", signal);
410
+ }
411
+ catch (error) {
412
+ if (signal?.aborted)
413
+ throw error;
414
+ throw new ConfigError(`case files: ${errorMessage(error)}`, { cause: error });
415
+ }
416
+ for (const target of placed) {
417
+ const file = loginFiles.find((login) => target === login || target.startsWith(`${login}/`));
418
+ if (file !== undefined) {
419
+ throw new ConfigError(`case files place ${target}, which collides with login state at ${file}`);
420
+ }
421
+ }
422
+ }
423
+ async function validateAuthoringAssets(loadedCase) {
424
+ const fixture = loadedCase.config.fixture;
425
+ if (fixture !== undefined) {
426
+ const source = resolveAuthoringAsset(loadedCase.dir, fixture, "case.fixture");
427
+ let info;
428
+ try {
429
+ info = await stat(source);
430
+ }
431
+ catch (caught) {
432
+ throw new ConfigError(`case fixture ${fixture} is not accessible: ${errorMessage(caught)}`);
433
+ }
434
+ if (!info.isDirectory()) {
435
+ throw new ConfigError(`case fixture ${fixture} must be a directory`);
436
+ }
437
+ }
438
+ for (const [destination, source] of Object.entries(loadedCase.config.files ?? {})) {
439
+ try {
440
+ await stat(resolveAuthoringAsset(loadedCase.dir, source, `case.files["${destination}"]`));
441
+ }
442
+ catch (caught) {
443
+ throw new ConfigError(`case files source ${source} for "${destination}" is not accessible: ${errorMessage(caught)}`);
444
+ }
445
+ }
446
+ }
447
+ async function runChecks(prepared, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, trace, mockRecords, timeoutMs, signal, markCancelled) {
448
+ const results = [];
449
+ for (const [declaration, check] of prepared.entries()) {
450
+ if (signal.aborted) {
451
+ results.push({
452
+ declaration,
453
+ checker: check.type,
454
+ subject: `${check.type} check`,
455
+ status: "error",
456
+ reason: "run was cancelled before this check ran",
457
+ });
458
+ continue;
459
+ }
460
+ const controller = new AbortController();
461
+ const combined = AbortSignal.any([signal, controller.signal]);
462
+ let timedOutCheck = false;
463
+ let rejectTimer;
464
+ const checkTimer = setTimeout(() => {
465
+ timedOutCheck = true;
466
+ controller.abort();
467
+ }, timeoutMs);
468
+ // Called inside an async function so that an implementation which returns its results
469
+ // directly, or throws before it can, becomes a rejection this loop already handles.
470
+ const promise = (async () => check.checker.check({
471
+ workspace: workspaceRoot,
472
+ baseline: baselineRoot,
473
+ home: homeRoot,
474
+ homeBaseline: homeBaselineRoot,
475
+ runRootDir: root,
476
+ input: request.case.config.input,
477
+ ...(trace === undefined ? {} : { trace }),
478
+ ...(mockRecords === undefined ? {} : { mockRecords }),
479
+ checkSandbox: createCheckSandbox({
480
+ workspaceDir: workspaceRoot.path,
481
+ engineDir: join(root, "engine"),
482
+ authoringDir: request.case.dir,
483
+ signal: combined,
484
+ cancelled: signal,
485
+ }),
486
+ timeoutMs,
487
+ signal: combined,
488
+ }))();
489
+ promise.catch(() => { });
490
+ try {
491
+ const timeout = new Promise((_, reject) => {
492
+ rejectTimer = setTimeout(() => {
493
+ reject(new Error(`checker exceeded the ${timeoutMs}ms execution timeout`));
494
+ }, timeoutMs + 1_000);
495
+ });
496
+ const settled = await Promise.race([promise, timeout]);
497
+ // A verdict that arrives after the budget signal fired is not trusted in either direction:
498
+ // a late pass claims success past the deadline, and a late fail may be a partial comparison
499
+ // that a negative case would otherwise read as the expected outcome.
500
+ results.push(...settled.map((result) => timedOutCheck && result.status !== "error"
501
+ ? {
502
+ declaration,
503
+ checker: result.checker,
504
+ subject: result.subject,
505
+ status: "error",
506
+ reason: truncate(`checker exceeded the ${timeoutMs}ms execution timeout: ${result.reason}`, 800),
507
+ }
508
+ : { ...result, declaration }));
509
+ }
510
+ catch (caught) {
511
+ const reason = signal.aborted
512
+ ? "run was cancelled while this check was running"
513
+ : timedOutCheck
514
+ ? `checker exceeded the ${timeoutMs}ms execution timeout`
515
+ : errorMessage(caught);
516
+ if (signal.aborted) {
517
+ markCancelled();
518
+ }
519
+ results.push({
520
+ declaration,
521
+ checker: check.type,
522
+ subject: `${check.type} check`,
523
+ status: "error",
524
+ reason: truncate(reason, 800),
525
+ });
526
+ await settleWithin(promise, CHECK_ABORT_GRACE_MS);
527
+ }
528
+ finally {
529
+ clearTimeout(checkTimer);
530
+ if (rejectTimer !== undefined) {
531
+ clearTimeout(rejectTimer);
532
+ }
533
+ }
534
+ }
535
+ return results;
536
+ }
537
+ async function settleWithin(promise, timeoutMs) {
538
+ let timer;
539
+ const timeout = new Promise((resolveTimeout) => {
540
+ timer = setTimeout(resolveTimeout, timeoutMs);
541
+ });
542
+ try {
543
+ await Promise.race([promise.catch(() => { }), timeout]);
544
+ }
545
+ finally {
546
+ if (timer !== undefined) {
547
+ clearTimeout(timer);
548
+ }
549
+ }
550
+ }
551
+ function paramsOf(record) {
552
+ const { $type: _type, ...params } = record;
553
+ return params;
554
+ }
555
+ function diagnosticsOf(error) {
556
+ if (typeof error === "object" && error !== null && "diagnostics" in error) {
557
+ const diagnostics = error.diagnostics;
558
+ if (Array.isArray(diagnostics)) {
559
+ return diagnostics.filter((item) => typeof item === "string").slice(0, 20);
560
+ }
561
+ }
562
+ return [];
563
+ }
564
+ function boundedDiagnostics(diagnostics) {
565
+ return diagnostics.slice(0, 20).map((line) => truncate(line, 2_000));
566
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Resolve a sibling runtime module that is executed separately from this module
3
+ * (a worker, or sandbox-resident supervisor). Source runs use `.ts`; built
4
+ * package runs use emitted `.js`.
5
+ */
6
+ export declare function siblingRuntimeModule(moduleUrl: string, name: string): URL;
@@ -0,0 +1,11 @@
1
+ import { extname } from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ /**
4
+ * Resolve a sibling runtime module that is executed separately from this module
5
+ * (a worker, or sandbox-resident supervisor). Source runs use `.ts`; built
6
+ * package runs use emitted `.js`.
7
+ */
8
+ export function siblingRuntimeModule(moduleUrl, name) {
9
+ const extension = extname(fileURLToPath(moduleUrl)) === ".ts" ? ".ts" : ".js";
10
+ return new URL(`./${name}${extension}`, moduleUrl);
11
+ }
@@ -0,0 +1,49 @@
1
+ import type { TraceEntry } from "./registry.js";
2
+ import { type RunRoot } from "./workspace.js";
3
+ /** One skill a run consulted, as far as its trace and workspace show. */
4
+ export interface SkillConsultation {
5
+ /** The skill's frontmatter `name`, or the parent directory's when no source gives a frontmatter name. */
6
+ readonly name: string;
7
+ /** True when `name` is the parent directory's, because neither the baseline nor the output named it. */
8
+ readonly fromDirectory: boolean;
9
+ }
10
+ /**
11
+ * The run directories the derivation reads: the live workspace and HOME a trace names, and what
12
+ * the case placed in each before the agent started.
13
+ */
14
+ export interface SkillSources {
15
+ /** The workspace as the agent left it; relative trace paths are resolved against it. */
16
+ readonly workspace: RunRoot;
17
+ /** The run HOME as the agent left it; `~/` and absolute paths inside it resolve here. */
18
+ readonly home: RunRoot;
19
+ /** The workspace's initial snapshot, where a placed skill's frontmatter is read. */
20
+ readonly workspaceBaseline: RunRoot;
21
+ /** What the case placed in HOME; agent-file and login content is not part of it. */
22
+ readonly homeBaseline: RunRoot;
23
+ }
24
+ /**
25
+ * The skills one run consulted, derived from its trace and the run's workspace and baseline.
26
+ *
27
+ * ACP has no skill update, so this reads the two forms harnesses report: a completed
28
+ * non-read tool call carrying `rawInput.skill` (Claude Code, GitHub Copilot CLI), and a
29
+ * completed `read` of a `SKILL.md` (Pi). Only completed tool calls count, and a skill is
30
+ * one consultation however many times or chunks it was read.
31
+ *
32
+ * A skill the case placed, in the workspace or in HOME, is named from its frontmatter in that
33
+ * root's baseline. A read outside both roots is named from the text it returned, then from the
34
+ * skill's parent directory.
35
+ */
36
+ export declare function skillConsultations(trace: readonly TraceEntry[], sources: SkillSources): Promise<readonly SkillConsultation[]>;
37
+ /** A skill whose placed `SKILL.md` an executed command's text named, reported but never counted. */
38
+ export interface ShellSkillAccess {
39
+ /** The skill's frontmatter `name` in the baseline, or its parent directory's. */
40
+ readonly name: string;
41
+ }
42
+ /**
43
+ * The placed skills whose `SKILL.md` path an executed command's text named.
44
+ *
45
+ * Whether reading a skill body through a shell is a consultation is ambiguous, so this is
46
+ * reported separately and never counts as one. Only a `SKILL.md` a baseline placed is
47
+ * recognized; a file the agent created is not the skill it started with.
48
+ */
49
+ export declare function shellSkillAccess(trace: readonly TraceEntry[], sources: SkillSources): Promise<readonly ShellSkillAccess[]>;