@lelouchhe/agent-evals 0.0.0-stage → 0.2.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 (105) hide show
  1. package/.env.example +27 -0
  2. package/LICENSE +21 -0
  3. package/README.md +121 -2
  4. package/dist/checkers/file/index.d.ts +26 -0
  5. package/dist/checkers/file/index.js +396 -0
  6. package/dist/checkers/judge/index.d.ts +20 -0
  7. package/dist/checkers/judge/index.js +474 -0
  8. package/dist/checkers/judge/prompt.d.ts +19 -0
  9. package/dist/checkers/judge/prompt.js +55 -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 +453 -0
  20. package/dist/engine/authoring.d.ts +24 -0
  21. package/dist/engine/authoring.js +356 -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 +171 -0
  27. package/dist/engine/config.js +368 -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 +84 -0
  31. package/dist/engine/files.js +304 -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 +18 -0
  42. package/dist/engine/params.js +96 -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 +243 -0
  48. package/dist/engine/registry.js +127 -0
  49. package/dist/engine/report.d.ts +17 -0
  50. package/dist/engine/report.js +420 -0
  51. package/dist/engine/results.d.ts +50 -0
  52. package/dist/engine/results.js +42 -0
  53. package/dist/engine/run.d.ts +50 -0
  54. package/dist/engine/run.js +710 -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 +150 -0
  65. package/dist/engine/workspace.d.ts +63 -0
  66. package/dist/engine/workspace.js +305 -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 +135 -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,710 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { copyFile, cp, lstat, mkdir, readdir, 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 { classifyOutcome, 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 { assertRunRoot, isMissing, isProtectedHomePath, openRunRoot, resolveWorkspacePath, } 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 workspaceRoot;
89
+ let homeRoot;
90
+ let cleanup = { status: "removed" };
91
+ let artifacts;
92
+ let protectedPaths = registered.runner.homeFiles ?? [];
93
+ const protectedIdentities = [];
94
+ let protectedIdentitiesError;
95
+ let runnerRecord = {
96
+ type: registered.runnerType,
97
+ status: "error",
98
+ durationMs: 0,
99
+ finalText: null,
100
+ };
101
+ let checks = [];
102
+ let trace;
103
+ let usage;
104
+ let mockRecords;
105
+ let mockHost;
106
+ let mockFailed = false;
107
+ const diagnostics = [];
108
+ let error;
109
+ let status = "error";
110
+ let timedOut = false;
111
+ let stopFailed = false;
112
+ let timer;
113
+ let paths;
114
+ try {
115
+ await Promise.all([
116
+ mkdir(workspaceDir, { mode: 0o700 }),
117
+ mkdir(homeDir, { mode: 0o700 }),
118
+ mkdir(tmpDir, { mode: 0o700 }),
119
+ mkdir(mocksDir, { mode: 0o700 }),
120
+ mkdir(join(engineDir, "baseline", "workspace"), { recursive: true, mode: 0o700 }),
121
+ mkdir(join(engineDir, "baseline", "home"), { recursive: true, mode: 0o700 }),
122
+ ]);
123
+ // Capture root identities immediately after creation so setup failures still retain safely.
124
+ [workspaceRoot, homeRoot] = await Promise.all([openRunRoot(workspaceDir), openRunRoot(homeDir)]);
125
+ const fixture = request.case.config.fixture;
126
+ if (fixture !== undefined) {
127
+ const source = resolveAuthoringAsset(request.case.dir, fixture, "case.fixture");
128
+ await cp(source, workspaceDir, {
129
+ recursive: true,
130
+ preserveTimestamps: true,
131
+ filter: authoringCopyFilter(source),
132
+ });
133
+ }
134
+ await placeCaseFiles(request.case, join(engineDir, "files", "workspace"), workspaceDir);
135
+ // The runner places its own HOME content first; the case then overlays it without
136
+ // touching login state, and only what the case placed becomes the HOME baseline.
137
+ const context = {
138
+ workspaceDir,
139
+ homeDir,
140
+ tmpDir,
141
+ engineDir,
142
+ configDir,
143
+ runRootDir: root,
144
+ input: request.case.config.input,
145
+ timeoutMs,
146
+ signal: abort.signal,
147
+ };
148
+ runner = registered.runner;
149
+ const preparedProtected = (await runner.prepareHome?.(context)) ?? [];
150
+ protectedPaths = [...new Set([...protectedPaths, ...preparedProtected])];
151
+ // Login state is protected by the file the filesystem actually holds at each declared
152
+ // path, so a differently-cased or otherwise normalised spelling cannot alias it.
153
+ try {
154
+ await recordProtectedIdentities(homeRoot, protectedPaths, protectedIdentities);
155
+ }
156
+ catch (caught) {
157
+ protectedIdentitiesError = errorMessage(caught);
158
+ throw caught;
159
+ }
160
+ const homePlacements = homeEntries(request.case.config.files);
161
+ const homeStaging = join(engineDir, "files", "home");
162
+ if (homePlacements.length > 0) {
163
+ await stageEntries(homePlacements, request.case.dir, homeStaging, "files", abort.signal);
164
+ try {
165
+ await copyPlacement(homeStaging, homeDir, {
166
+ label: "files",
167
+ overwrite: true,
168
+ protect: { paths: protectedPaths, identities: protectedIdentities },
169
+ signal: abort.signal,
170
+ });
171
+ await cp(homeStaging, baselineHomeDir, { recursive: true, preserveTimestamps: true });
172
+ }
173
+ finally {
174
+ await rm(homeStaging, { recursive: true, force: true });
175
+ }
176
+ }
177
+ // Forwarders are written before the baseline snapshot, so it already holds them.
178
+ const mocks = request.case.config.mocks;
179
+ if (mocks !== undefined) {
180
+ mockHost = await startMockHost({
181
+ runRootDir: root,
182
+ engineDir,
183
+ mocksDir,
184
+ workspaceDir: workspaceRoot.path,
185
+ tmpDir,
186
+ authoringDir: request.case.dir,
187
+ shell: mocks.shell,
188
+ timeoutMs,
189
+ signal: abort.signal,
190
+ });
191
+ }
192
+ await cp(workspaceDir, baselineWorkspaceDir, { recursive: true, preserveTimestamps: true });
193
+ const baselineRoot = await openRunRoot(baselineWorkspaceDir);
194
+ const homeBaselineRoot = await openRunRoot(baselineHomeDir);
195
+ const started = performance.now();
196
+ let outcome;
197
+ timer = setTimeout(() => {
198
+ timedOut = true;
199
+ abort.abort();
200
+ void runner?.stop().catch(() => { });
201
+ }, timeoutMs);
202
+ try {
203
+ outcome = await runner.run({
204
+ ...context,
205
+ ...(mockHost === undefined ? {} : { mocks: mockHost.wiring }),
206
+ });
207
+ }
208
+ catch (caught) {
209
+ if (!abort.signal.aborted) {
210
+ error = errorMessage(caught);
211
+ }
212
+ diagnostics.push(...diagnosticsOf(caught));
213
+ }
214
+ finally {
215
+ if (timer !== undefined) {
216
+ clearTimeout(timer);
217
+ timer = undefined;
218
+ }
219
+ try {
220
+ await runner.stop();
221
+ }
222
+ catch (caught) {
223
+ stopFailed = true;
224
+ diagnostics.push(`failed to stop runner: ${errorMessage(caught)}`);
225
+ error ??= `failed to stop runner: ${errorMessage(caught)}`;
226
+ }
227
+ // Closing the host must not depend on the runner's trace, and vice versa.
228
+ try {
229
+ if (mockHost !== undefined) {
230
+ const outcome = await mockHost.close();
231
+ mockRecords = outcome.records;
232
+ if (outcome.faults.length > 0) {
233
+ mockFailed = true;
234
+ diagnostics.push(...outcome.faults);
235
+ error ??= outcome.faults[0];
236
+ }
237
+ }
238
+ }
239
+ finally {
240
+ trace = runner.trace?.();
241
+ usage = runner.usage?.();
242
+ }
243
+ // Re-record login file identities after the runner stops so an atomic credential refresh
244
+ // (new inode) stays protected from checks and artifact retention.
245
+ try {
246
+ await recordProtectedIdentities(homeRoot, protectedPaths, protectedIdentities);
247
+ }
248
+ catch (caught) {
249
+ protectedIdentitiesError = errorMessage(caught);
250
+ diagnostics.push(`failed to inspect protected login state: ${protectedIdentitiesError}`);
251
+ error ??= `failed to inspect protected login state: ${protectedIdentitiesError}`;
252
+ }
253
+ }
254
+ const runnerStatus = stopFailed
255
+ ? "error"
256
+ : outcome !== undefined
257
+ ? "completed"
258
+ : cancelled
259
+ ? "cancelled"
260
+ : timedOut
261
+ ? "timeout"
262
+ : "error";
263
+ runnerRecord = {
264
+ type: registered.runnerType,
265
+ status: runnerStatus,
266
+ durationMs: Math.round(performance.now() - started),
267
+ finalText: outcome === undefined ? null : truncateNullable(outcome.finalText, MAX_RECORDED_TEXT),
268
+ ...(usage === undefined ? {} : { usage }),
269
+ };
270
+ if (outcome !== undefined && protectedIdentitiesError === undefined) {
271
+ diagnostics.push(...outcome.diagnostics);
272
+ checks = await runChecks(registered.checks, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, { paths: protectedPaths, identities: protectedIdentities }, trace, mockRecords, timeoutMs, abort.signal, () => {
273
+ cancelled = true;
274
+ });
275
+ }
276
+ if (cancelled) {
277
+ status = "cancelled";
278
+ error ??= "run was cancelled";
279
+ }
280
+ else if (timedOut) {
281
+ status = "timeout";
282
+ error ??= `runner exceeded the ${timeoutMs}ms execution timeout`;
283
+ }
284
+ else if (runnerStatus !== "completed") {
285
+ status = "error";
286
+ error ??= "runner failed before checks could run";
287
+ }
288
+ else if (protectedIdentitiesError !== undefined) {
289
+ status = "error";
290
+ error ??= `failed to inspect protected login state: ${protectedIdentitiesError}`;
291
+ }
292
+ else if (mockFailed) {
293
+ status = "error";
294
+ error ??= "a mock fault ended the run";
295
+ }
296
+ else if (checks.some((check) => check.status === "error")) {
297
+ status = "error";
298
+ error ??= "one or more checks could not be evaluated";
299
+ }
300
+ else if (checks.some((check) => check.status === "fail")) {
301
+ status = "fail";
302
+ }
303
+ else {
304
+ status = "pass";
305
+ }
306
+ }
307
+ catch (caught) {
308
+ status = cancelled ? "cancelled" : "error";
309
+ error ??= errorMessage(caught);
310
+ diagnostics.push(...diagnosticsOf(caught));
311
+ }
312
+ finally {
313
+ if (timer !== undefined) {
314
+ clearTimeout(timer);
315
+ }
316
+ request.signal?.removeEventListener("abort", onAbort);
317
+ // A backstop for any failure before the runner's own teardown; close is idempotent.
318
+ if (mockHost !== undefined) {
319
+ try {
320
+ await mockHost.close();
321
+ }
322
+ catch (caught) {
323
+ diagnostics.push(`failed to close mock host: ${errorMessage(caught)}`);
324
+ }
325
+ }
326
+ if (shouldRetain(request.retain ?? "none", status, request.case.config.expect)) {
327
+ if (protectedIdentitiesError !== undefined) {
328
+ const message = `cannot verify protected login state: ${protectedIdentitiesError}`;
329
+ artifacts = { status: "failed", error: message };
330
+ diagnostics.push(`failed to retain artifacts: ${message}`);
331
+ }
332
+ else {
333
+ let artifactsDir;
334
+ try {
335
+ paths = await createResultDirectory(request.resultsDir, runId);
336
+ artifactsDir = join(paths.directory, "artifacts");
337
+ await retainRunArtifacts(workspaceRoot, homeRoot, artifactsDir, {
338
+ paths: protectedPaths,
339
+ identities: protectedIdentities,
340
+ });
341
+ artifacts = { status: "retained", path: "artifacts" };
342
+ }
343
+ catch (caught) {
344
+ if (artifactsDir !== undefined) {
345
+ await rm(artifactsDir, { recursive: true, force: true }).catch(() => { });
346
+ }
347
+ const message = errorMessage(caught);
348
+ artifacts = { status: "failed", error: message };
349
+ diagnostics.push(`failed to retain artifacts: ${message}`);
350
+ }
351
+ }
352
+ }
353
+ try {
354
+ await rm(root, { recursive: true, force: true, maxRetries: 3 });
355
+ }
356
+ catch (caught) {
357
+ cleanup = { status: "failed", error: errorMessage(caught) };
358
+ }
359
+ }
360
+ if (cleanup.status === "failed") {
361
+ status = "error";
362
+ error = error === undefined ? `cleanup failed: ${cleanup.error}` : `${error}; cleanup failed: ${cleanup.error}`;
363
+ }
364
+ const record = {
365
+ schemaVersion: 1,
366
+ runId,
367
+ startedAt,
368
+ finishedAt: new Date().toISOString(),
369
+ case: {
370
+ path: request.case.path,
371
+ ...(request.case.name === undefined ? {} : { name: request.case.name }),
372
+ },
373
+ resolvedConfig: request.case.config,
374
+ status,
375
+ runner: runnerRecord,
376
+ checks,
377
+ ...(error === undefined ? {} : { error }),
378
+ diagnostics: boundedDiagnostics(diagnostics),
379
+ cleanup,
380
+ ...(artifacts === undefined ? {} : { artifacts }),
381
+ };
382
+ paths ??= await createResultDirectory(request.resultsDir, runId);
383
+ await writeResult(paths, record, trace, mockRecords);
384
+ return record;
385
+ }
386
+ function shouldRetain(retain, status, expect) {
387
+ if (retain === "all")
388
+ return true;
389
+ if (retain === "none")
390
+ return false;
391
+ const outcome = classifyOutcome(status, expect);
392
+ return outcome !== "pass" && outcome !== "expected-fail" && outcome !== "cancelled";
393
+ }
394
+ async function recordProtectedIdentities(homeRoot, protectedPaths, identities) {
395
+ const seen = new Set(identities);
396
+ for (const path of protectedPaths) {
397
+ let resolved;
398
+ try {
399
+ // Follow in-HOME symlinks (matching ACP login copy-back) while rejecting escaping/broken links.
400
+ resolved = await resolveWorkspacePath(homeRoot, path);
401
+ }
402
+ catch (error) {
403
+ if (isMissing(error))
404
+ continue;
405
+ throw error;
406
+ }
407
+ try {
408
+ const info = await lstat(resolved, { bigint: true });
409
+ if (info.isFile()) {
410
+ const id = fileIdentity(info);
411
+ if (!seen.has(id)) {
412
+ seen.add(id);
413
+ identities.push(id);
414
+ }
415
+ }
416
+ }
417
+ catch (error) {
418
+ if (!isMissing(error))
419
+ throw error;
420
+ }
421
+ }
422
+ }
423
+ async function retainRunArtifacts(workspaceRoot, homeRoot, artifactsDir, excludeHome) {
424
+ await mkdir(artifactsDir, { recursive: true, mode: 0o700 });
425
+ if (workspaceRoot !== undefined) {
426
+ await assertRunRoot(workspaceRoot);
427
+ await retainTree(workspaceRoot.path, join(artifactsDir, "workspace"), {
428
+ paths: [],
429
+ identities: excludeHome.identities,
430
+ });
431
+ }
432
+ if (homeRoot !== undefined) {
433
+ await assertRunRoot(homeRoot);
434
+ await retainTree(homeRoot.path, join(artifactsDir, "home"), excludeHome);
435
+ }
436
+ }
437
+ async function retainTree(sourceDir, destinationDir, exclude) {
438
+ const excludedPaths = exclude?.paths ?? [];
439
+ const excludedIdentities = new Set(exclude?.identities ?? []);
440
+ const walk = async (currentSource, currentDest, relPrefix) => {
441
+ let entries;
442
+ try {
443
+ entries = await readdir(currentSource, { withFileTypes: true });
444
+ }
445
+ catch (caught) {
446
+ if (isMissing(caught))
447
+ return;
448
+ throw caught;
449
+ }
450
+ await mkdir(currentDest, { recursive: true, mode: 0o700 });
451
+ for (const entry of entries) {
452
+ const rel = relPrefix.length === 0 ? entry.name : `${relPrefix}/${entry.name}`;
453
+ if (isProtectedHomePath(rel, excludedPaths))
454
+ continue;
455
+ const srcPath = join(currentSource, entry.name);
456
+ let info;
457
+ try {
458
+ info = await lstat(srcPath, { bigint: true });
459
+ }
460
+ catch (caught) {
461
+ if (isMissing(caught))
462
+ continue;
463
+ throw caught;
464
+ }
465
+ if (info.isFile()) {
466
+ if (excludedIdentities.has(fileIdentity(info)))
467
+ continue;
468
+ await copyFile(srcPath, join(currentDest, entry.name));
469
+ }
470
+ else if (info.isDirectory()) {
471
+ await walk(srcPath, join(currentDest, entry.name), rel);
472
+ }
473
+ // Symlinks, sockets, FIFOs and devices are skipped so an agent-created link can never
474
+ // pull host files into the retained results directory.
475
+ }
476
+ };
477
+ await walk(sourceDir, destinationDir, "");
478
+ }
479
+ async function prepareImplementations(request, values, signal) {
480
+ const mockTargets = request.case.config.mocks === undefined ? undefined : Object.keys(request.case.config.mocks.shell);
481
+ const runnerDefinition = requireRunner(request.registry, request.case.config.runner.$type);
482
+ if (request.case.config.mocks !== undefined && runnerDefinition.mocks !== true) {
483
+ throw new ConfigError(`runner "${runnerDefinition.type}" does not support mocks`);
484
+ }
485
+ const runnerSupportsHome = runnerDefinition.home === true;
486
+ if (!runnerSupportsHome && homeEntries(request.case.config.files).length > 0) {
487
+ throw new ConfigError(`runner "${runnerDefinition.type}" does not support case files under "~"`);
488
+ }
489
+ // The case runner's placeholders resolve once; a checker-declared runner arrives resolved with
490
+ // the checker parameters it was written in, so neither declaration is walked twice.
491
+ const caseRunnerParams = await substituteValues(paramsOf(request.case.config.runner), "runner", values);
492
+ const concurrencyKeys = new Set();
493
+ const createRunner = async (record) => {
494
+ const declaration = record ?? request.case.config.runner;
495
+ const definition = requireRunner(request.registry, declaration.$type);
496
+ const params = await parseImplementationParams(definition.params,
497
+ // Each instance gets its own copy: a schema may keep a value it was given, and the case
498
+ // runner's parameters are also the inherited judge's.
499
+ structuredClone(record === undefined ? caseRunnerParams : paramsOf(record)), `runner "${definition.type}"`);
500
+ const created = await definition.create(params, context);
501
+ if (created.concurrencyKey !== undefined) {
502
+ concurrencyKeys.add(created.concurrencyKey);
503
+ }
504
+ return { type: definition.type, runner: created };
505
+ };
506
+ const context = {
507
+ authoringDir: request.case.dir,
508
+ values,
509
+ validateFiles: (files) => validateCheckFiles(files, request.case.dir, "check files", signal),
510
+ ...(mockTargets === undefined ? {} : { mockTargets }),
511
+ runnerSupportsHome,
512
+ validateCheckPlatform: async () => assertSeatbeltAvailable(),
513
+ createRunner,
514
+ };
515
+ const { runner } = await createRunner();
516
+ await validateCaseHomePlacement(request.case, runner.homeFiles ?? [], signal);
517
+ const checks = [];
518
+ for (const [index, record] of request.case.config.checks.entries()) {
519
+ const definition = requireChecker(request.registry, record.$type);
520
+ const params = await parseImplementationParams(definition.params, await substituteValues(paramsOf(record), `checks[${index}]`, values), `checker "${definition.type}"`);
521
+ checks.push({ type: definition.type, checker: await createChecker(definition, params, index, context) });
522
+ }
523
+ return { runnerType: runnerDefinition.type, runner, checks, concurrencyKeys: [...concurrencyKeys] };
524
+ }
525
+ /**
526
+ * Create one checker and name the declaration in its failure: a checker may create a runner of its
527
+ * own, so the nested error has to say which check asked for it.
528
+ */
529
+ async function createChecker(definition, params, index, context) {
530
+ try {
531
+ return await definition.create(params, context);
532
+ }
533
+ catch (error) {
534
+ if (error instanceof ConfigError) {
535
+ throw new ConfigError(`checks[${index}] (checker "${definition.type}"): ${error.message}`, { cause: error });
536
+ }
537
+ throw error;
538
+ }
539
+ }
540
+ /**
541
+ * Reject a case's `~/` placement that would land on login state, including a directory source
542
+ * whose contents name a login file. Runs while every selected case is prepared, before any
543
+ * case executes; the filesystem-level alias guard still applies at placement time.
544
+ */
545
+ async function validateCaseHomePlacement(loadedCase, loginFiles, signal) {
546
+ const entries = homeEntries(loadedCase.config.files);
547
+ if (entries.length === 0 || loginFiles.length === 0) {
548
+ return;
549
+ }
550
+ let placed;
551
+ try {
552
+ placed = await placedPaths(entries, loadedCase.dir, "files", signal);
553
+ }
554
+ catch (error) {
555
+ if (signal?.aborted)
556
+ throw error;
557
+ throw new ConfigError(`case files: ${errorMessage(error)}`, { cause: error });
558
+ }
559
+ for (const target of placed) {
560
+ const file = loginFiles.find((login) => target === login || target.startsWith(`${login}/`));
561
+ if (file !== undefined) {
562
+ throw new ConfigError(`case files place ${target}, which collides with login state at ${file}`);
563
+ }
564
+ }
565
+ }
566
+ async function validateAuthoringAssets(loadedCase) {
567
+ const fixture = loadedCase.config.fixture;
568
+ if (fixture !== undefined) {
569
+ const source = resolveAuthoringAsset(loadedCase.dir, fixture, "case.fixture");
570
+ let info;
571
+ try {
572
+ info = await stat(source);
573
+ }
574
+ catch (caught) {
575
+ throw new ConfigError(`case fixture ${fixture} is not accessible: ${errorMessage(caught)}`);
576
+ }
577
+ if (!info.isDirectory()) {
578
+ throw new ConfigError(`case fixture ${fixture} must be a directory`);
579
+ }
580
+ }
581
+ for (const [destination, source] of Object.entries(loadedCase.config.files ?? {})) {
582
+ try {
583
+ await stat(resolveAuthoringAsset(loadedCase.dir, source, `case.files["${destination}"]`));
584
+ }
585
+ catch (caught) {
586
+ throw new ConfigError(`case files source ${source} for "${destination}" is not accessible: ${errorMessage(caught)}`);
587
+ }
588
+ }
589
+ }
590
+ async function runChecks(prepared, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, protectedHome, trace, mockRecords, timeoutMs, signal, markCancelled) {
591
+ const results = [];
592
+ for (const [declaration, check] of prepared.entries()) {
593
+ if (signal.aborted) {
594
+ results.push({
595
+ declaration,
596
+ checker: check.type,
597
+ subject: `${check.type} check`,
598
+ status: "error",
599
+ reason: "run was cancelled before this check ran",
600
+ });
601
+ continue;
602
+ }
603
+ const controller = new AbortController();
604
+ const combined = AbortSignal.any([signal, controller.signal]);
605
+ let timedOutCheck = false;
606
+ let rejectTimer;
607
+ const checkTimer = setTimeout(() => {
608
+ timedOutCheck = true;
609
+ controller.abort();
610
+ }, timeoutMs);
611
+ // Called inside an async function so that an implementation which returns its results
612
+ // directly, or throws before it can, becomes a rejection this loop already handles.
613
+ const promise = (async () => check.checker.check({
614
+ workspace: workspaceRoot,
615
+ baseline: baselineRoot,
616
+ home: homeRoot,
617
+ homeBaseline: homeBaselineRoot,
618
+ protectedHome,
619
+ runRootDir: root,
620
+ input: request.case.config.input,
621
+ ...(trace === undefined ? {} : { trace }),
622
+ ...(mockRecords === undefined ? {} : { mockRecords }),
623
+ checkSandbox: createCheckSandbox({
624
+ workspaceDir: workspaceRoot.path,
625
+ engineDir: join(root, "engine"),
626
+ authoringDir: request.case.dir,
627
+ signal: combined,
628
+ cancelled: signal,
629
+ }),
630
+ timeoutMs,
631
+ signal: combined,
632
+ }))();
633
+ promise.catch(() => { });
634
+ try {
635
+ const timeout = new Promise((_, reject) => {
636
+ rejectTimer = setTimeout(() => {
637
+ reject(new Error(`checker exceeded the ${timeoutMs}ms execution timeout`));
638
+ }, timeoutMs + 1_000);
639
+ });
640
+ const settled = await Promise.race([promise, timeout]);
641
+ // A verdict that arrives after the budget signal fired is not trusted in either direction:
642
+ // a late pass claims success past the deadline, and a late fail may be a partial comparison
643
+ // that a negative case would otherwise read as the expected outcome.
644
+ results.push(...settled.map((result) => timedOutCheck && result.status !== "error"
645
+ ? {
646
+ declaration,
647
+ checker: result.checker,
648
+ subject: result.subject,
649
+ status: "error",
650
+ reason: truncate(`checker exceeded the ${timeoutMs}ms execution timeout: ${result.reason}`, 800),
651
+ }
652
+ : { ...result, declaration }));
653
+ }
654
+ catch (caught) {
655
+ const reason = signal.aborted
656
+ ? "run was cancelled while this check was running"
657
+ : timedOutCheck
658
+ ? `checker exceeded the ${timeoutMs}ms execution timeout`
659
+ : errorMessage(caught);
660
+ if (signal.aborted) {
661
+ markCancelled();
662
+ }
663
+ results.push({
664
+ declaration,
665
+ checker: check.type,
666
+ subject: `${check.type} check`,
667
+ status: "error",
668
+ reason: truncate(reason, 800),
669
+ });
670
+ await settleWithin(promise, CHECK_ABORT_GRACE_MS);
671
+ }
672
+ finally {
673
+ clearTimeout(checkTimer);
674
+ if (rejectTimer !== undefined) {
675
+ clearTimeout(rejectTimer);
676
+ }
677
+ }
678
+ }
679
+ return results;
680
+ }
681
+ async function settleWithin(promise, timeoutMs) {
682
+ let timer;
683
+ const timeout = new Promise((resolveTimeout) => {
684
+ timer = setTimeout(resolveTimeout, timeoutMs);
685
+ });
686
+ try {
687
+ await Promise.race([promise.catch(() => { }), timeout]);
688
+ }
689
+ finally {
690
+ if (timer !== undefined) {
691
+ clearTimeout(timer);
692
+ }
693
+ }
694
+ }
695
+ function paramsOf(record) {
696
+ const { $type: _type, ...params } = record;
697
+ return params;
698
+ }
699
+ function diagnosticsOf(error) {
700
+ if (typeof error === "object" && error !== null && "diagnostics" in error) {
701
+ const diagnostics = error.diagnostics;
702
+ if (Array.isArray(diagnostics)) {
703
+ return diagnostics.filter((item) => typeof item === "string").slice(0, 20);
704
+ }
705
+ }
706
+ return [];
707
+ }
708
+ function boundedDiagnostics(diagnostics) {
709
+ return diagnostics.slice(0, 20).map((line) => truncate(line, 2_000));
710
+ }