@lelouchhe/agent-evals 0.1.1 → 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 (79) hide show
  1. package/README.md +27 -18
  2. package/dist/checkers/file/index.js +181 -13
  3. package/dist/checkers/judge/index.d.ts +1 -1
  4. package/dist/checkers/judge/index.js +243 -31
  5. package/dist/checkers/judge/prompt.d.ts +4 -3
  6. package/dist/checkers/judge/prompt.js +22 -3
  7. package/dist/cli.js +171 -35
  8. package/dist/engine/authoring.js +108 -13
  9. package/dist/engine/check-runner.js +18 -3
  10. package/dist/engine/check-sandbox.js +9 -6
  11. package/dist/engine/config.d.ts +31 -2
  12. package/dist/engine/config.js +16 -10
  13. package/dist/engine/env-source.js +82 -14
  14. package/dist/engine/files.d.ts +2 -5
  15. package/dist/engine/files.js +4 -6
  16. package/dist/engine/mocks.js +72 -46
  17. package/dist/engine/params.d.ts +2 -0
  18. package/dist/engine/params.js +10 -0
  19. package/dist/engine/registry.d.ts +11 -0
  20. package/dist/engine/report.js +43 -8
  21. package/dist/engine/results.d.ts +7 -0
  22. package/dist/engine/results.js +9 -6
  23. package/dist/engine/run.d.ts +4 -1
  24. package/dist/engine/run.js +171 -28
  25. package/dist/engine/skills.js +12 -5
  26. package/dist/engine/view.d.ts +1 -1
  27. package/dist/engine/view.js +125 -10
  28. package/dist/engine/workspace.d.ts +7 -0
  29. package/dist/engine/workspace.js +37 -27
  30. package/dist/index.d.ts +4 -4
  31. package/dist/index.js +2 -2
  32. package/dist/platform/index.d.ts +31 -0
  33. package/dist/platform/index.js +88 -0
  34. package/dist/platform/linux/index.d.ts +2 -0
  35. package/dist/platform/linux/index.js +40 -0
  36. package/dist/platform/linux/launch.d.ts +8 -0
  37. package/dist/platform/linux/launch.js +25 -0
  38. package/dist/platform/linux/policy.d.ts +46 -0
  39. package/dist/platform/linux/policy.js +388 -0
  40. package/dist/platform/linux/supervise.d.ts +8 -0
  41. package/dist/platform/linux/supervise.js +124 -0
  42. package/dist/platform/macos/index.d.ts +2 -0
  43. package/dist/platform/macos/index.js +59 -0
  44. package/dist/platform/macos/launch.d.ts +2 -8
  45. package/dist/platform/macos/launch.js +5 -3
  46. package/dist/platform/macos/policy.d.ts +3 -21
  47. package/dist/platform/macos/policy.js +5 -2
  48. package/dist/platform/macos/supervise.d.ts +3 -25
  49. package/dist/platform/posix-forwarder-client.mjs +129 -0
  50. package/dist/platform/posix-forwarder.sh +9 -0
  51. package/dist/platform/posix-helpers.d.ts +22 -0
  52. package/dist/platform/posix-helpers.js +97 -0
  53. package/dist/platform/types.d.ts +118 -0
  54. package/dist/platform/types.js +1 -0
  55. package/dist/platform/windows/forwarder-client.mjs +165 -0
  56. package/dist/platform/windows/forwarder.cmd +3 -0
  57. package/dist/platform/windows/forwarder.ps1 +2 -0
  58. package/dist/platform/windows/forwarder.sh +2 -0
  59. package/dist/platform/windows/index.d.ts +2 -0
  60. package/dist/platform/windows/index.js +225 -0
  61. package/dist/platform/windows/launch.d.ts +3 -0
  62. package/dist/platform/windows/launch.js +30 -0
  63. package/dist/platform/windows/policy.d.ts +17 -0
  64. package/dist/platform/windows/policy.js +155 -0
  65. package/dist/platform/windows/setup.ps1 +112 -0
  66. package/dist/platform/windows/supervise.d.ts +2 -0
  67. package/dist/platform/windows/supervise.js +142 -0
  68. package/dist/platform/windows/win-sandbox.exe +0 -0
  69. package/dist/runners/acp/commands.js +2 -3
  70. package/dist/runners/acp/environment.d.ts +1 -7
  71. package/dist/runners/acp/environment.js +18 -48
  72. package/dist/runners/acp/index.js +5 -1
  73. package/dist/runners/acp/session.d.ts +1 -1
  74. package/dist/runners/pi/index.js +2 -2
  75. package/dist/runners/pi/session.d.ts +1 -1
  76. package/dist/runners/pi/session.js +27 -44
  77. package/dist/runners/pi/supervisor.js +1 -0
  78. package/package.json +5 -3
  79. package/dist/engine/forwarder.sh +0 -61
@@ -1,11 +1,10 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { cp, lstat, mkdir, realpath, rm, stat } from "node:fs/promises";
2
+ import { copyFile, cp, lstat, mkdir, readdir, realpath, rm, stat } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
- import { tmpdir } from "node:os";
5
- import { assertSeatbeltAvailable } from "../platform/macos/policy.js";
4
+ import { assertSandboxAvailable, defaultTempParent } from "../platform/index.js";
6
5
  import { ConfigError, errorMessage, resolveAuthoringAsset, } from "./config.js";
7
6
  import { requireChecker, requireRunner, } from "./registry.js";
8
- import { createResultDirectory, newRunId, writeResult, } from "./results.js";
7
+ import { classifyOutcome, createResultDirectory, newRunId, writeResult, } from "./results.js";
9
8
  import { createEnvSource } from "./env-source.js";
10
9
  import { authoringCopyFilter, copyPlacement, fileIdentity, homeEntries, placeCaseFiles, placedPaths, stageEntries, validateCheckFiles, } from "./files.js";
11
10
  import { startMockHost } from "./mocks.js";
@@ -13,7 +12,7 @@ import { createCheckSandbox } from "./check-sandbox.js";
13
12
  import { parseImplementationParams } from "./params.js";
14
13
  import { truncate, truncateNullable } from "./truncate.js";
15
14
  import { substituteValues } from "./values.js";
16
- import { isMissing, openRunRoot } from "./workspace.js";
15
+ import { assertRunRoot, isMissing, isProtectedHomePath, openRunRoot, resolveWorkspacePath, } from "./workspace.js";
17
16
  const DEFAULT_TIMEOUT_MS = 300_000;
18
17
  const CHECK_ABORT_GRACE_MS = 12_000;
19
18
  const MAX_RECORDED_TEXT = 4_000;
@@ -27,7 +26,7 @@ export async function prepareEvaluation(request) {
27
26
  // Placeholders need the run directories' paths; they are created only after validation.
28
27
  // The parent is canonicalized first: the sandbox authorizes the `deps` link only when the
29
28
  // run-root path and its target carry no symlink spelling such as `/tmp` for `/private/tmp`.
30
- const parent = await realpath(request.tempParent ?? tmpdir());
29
+ const parent = await realpath(request.tempParent ?? defaultTempParent());
31
30
  const root = join(parent, `run-${randomBytes(6).toString("hex")}`);
32
31
  const workspaceDir = join(root, "workspace");
33
32
  const homeDir = join(root, "home");
@@ -85,7 +84,13 @@ export async function executeEvaluation(prepared) {
85
84
  throw error;
86
85
  }
87
86
  let runner;
87
+ let workspaceRoot;
88
+ let homeRoot;
88
89
  let cleanup = { status: "removed" };
90
+ let artifacts;
91
+ let protectedPaths = registered.runner.homeFiles ?? [];
92
+ const protectedIdentities = [];
93
+ let protectedIdentitiesError;
89
94
  let runnerRecord = {
90
95
  type: registered.runnerType,
91
96
  status: "error",
@@ -100,10 +105,11 @@ export async function executeEvaluation(prepared) {
100
105
  let mockFailed = false;
101
106
  const diagnostics = [];
102
107
  let error;
103
- let status;
108
+ let status = "error";
104
109
  let timedOut = false;
105
110
  let stopFailed = false;
106
111
  let timer;
112
+ let paths;
107
113
  try {
108
114
  await Promise.all([
109
115
  mkdir(workspaceDir, { mode: 0o700 }),
@@ -113,6 +119,8 @@ export async function executeEvaluation(prepared) {
113
119
  mkdir(join(engineDir, "baseline", "workspace"), { recursive: true, mode: 0o700 }),
114
120
  mkdir(join(engineDir, "baseline", "home"), { recursive: true, mode: 0o700 }),
115
121
  ]);
122
+ // Capture root identities immediately after creation so setup failures still retain safely.
123
+ [workspaceRoot, homeRoot] = await Promise.all([openRunRoot(workspaceDir), openRunRoot(homeDir)]);
116
124
  const fixture = request.case.config.fixture;
117
125
  if (fixture !== undefined) {
118
126
  const source = resolveAuthoringAsset(request.case.dir, fixture, "case.fixture");
@@ -123,7 +131,6 @@ export async function executeEvaluation(prepared) {
123
131
  });
124
132
  }
125
133
  await placeCaseFiles(request.case, join(engineDir, "files", "workspace"), workspaceDir);
126
- const workspaceRoot = await openRunRoot(workspaceDir);
127
134
  // The runner places its own HOME content first; the case then overlays it without
128
135
  // touching login state, and only what the case placed becomes the HOME baseline.
129
136
  const context = {
@@ -138,20 +145,16 @@ export async function executeEvaluation(prepared) {
138
145
  signal: abort.signal,
139
146
  };
140
147
  runner = registered.runner;
141
- const protectedPaths = (await runner.prepareHome?.(context)) ?? [];
148
+ const preparedProtected = (await runner.prepareHome?.(context)) ?? [];
149
+ protectedPaths = [...new Set([...protectedPaths, ...preparedProtected])];
142
150
  // Login state is protected by the file the filesystem actually holds at each declared
143
151
  // 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
- }
152
+ try {
153
+ await recordProtectedIdentities(homeRoot, protectedPaths, protectedIdentities);
154
+ }
155
+ catch (caught) {
156
+ protectedIdentitiesError = errorMessage(caught);
157
+ throw caught;
155
158
  }
156
159
  const homePlacements = homeEntries(request.case.config.files);
157
160
  const homeStaging = join(engineDir, "files", "home");
@@ -170,7 +173,6 @@ export async function executeEvaluation(prepared) {
170
173
  await rm(homeStaging, { recursive: true, force: true });
171
174
  }
172
175
  }
173
- const homeRoot = await openRunRoot(homeDir);
174
176
  // Forwarders are written before the baseline snapshot, so it already holds them.
175
177
  const mocks = request.case.config.mocks;
176
178
  if (mocks !== undefined) {
@@ -237,6 +239,16 @@ export async function executeEvaluation(prepared) {
237
239
  trace = runner.trace?.();
238
240
  usage = runner.usage?.();
239
241
  }
242
+ // Re-record login file identities after the runner stops so an atomic credential refresh
243
+ // (new inode) stays protected from checks and artifact retention.
244
+ try {
245
+ await recordProtectedIdentities(homeRoot, protectedPaths, protectedIdentities);
246
+ }
247
+ catch (caught) {
248
+ protectedIdentitiesError = errorMessage(caught);
249
+ diagnostics.push(`failed to inspect protected login state: ${protectedIdentitiesError}`);
250
+ error ??= `failed to inspect protected login state: ${protectedIdentitiesError}`;
251
+ }
240
252
  }
241
253
  const runnerStatus = stopFailed
242
254
  ? "error"
@@ -254,9 +266,9 @@ export async function executeEvaluation(prepared) {
254
266
  finalText: outcome === undefined ? null : truncateNullable(outcome.finalText, MAX_RECORDED_TEXT),
255
267
  ...(usage === undefined ? {} : { usage }),
256
268
  };
257
- if (outcome !== undefined) {
269
+ if (outcome !== undefined && protectedIdentitiesError === undefined) {
258
270
  diagnostics.push(...outcome.diagnostics);
259
- checks = await runChecks(registered.checks, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, trace, mockRecords, timeoutMs, abort.signal, () => {
271
+ checks = await runChecks(registered.checks, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, { paths: protectedPaths, identities: protectedIdentities }, trace, mockRecords, timeoutMs, abort.signal, () => {
260
272
  cancelled = true;
261
273
  });
262
274
  }
@@ -272,6 +284,10 @@ export async function executeEvaluation(prepared) {
272
284
  status = "error";
273
285
  error ??= "runner failed before checks could run";
274
286
  }
287
+ else if (protectedIdentitiesError !== undefined) {
288
+ status = "error";
289
+ error ??= `failed to inspect protected login state: ${protectedIdentitiesError}`;
290
+ }
275
291
  else if (mockFailed) {
276
292
  status = "error";
277
293
  error ??= "a mock fault ended the run";
@@ -306,6 +322,33 @@ export async function executeEvaluation(prepared) {
306
322
  diagnostics.push(`failed to close mock host: ${errorMessage(caught)}`);
307
323
  }
308
324
  }
325
+ if (shouldRetain(request.retain ?? "none", status, request.case.config.expect)) {
326
+ if (protectedIdentitiesError !== undefined) {
327
+ const message = `cannot verify protected login state: ${protectedIdentitiesError}`;
328
+ artifacts = { status: "failed", error: message };
329
+ diagnostics.push(`failed to retain artifacts: ${message}`);
330
+ }
331
+ else {
332
+ let artifactsDir;
333
+ try {
334
+ paths = await createResultDirectory(request.resultsDir, runId);
335
+ artifactsDir = join(paths.directory, "artifacts");
336
+ await retainRunArtifacts(workspaceRoot, homeRoot, artifactsDir, {
337
+ paths: protectedPaths,
338
+ identities: protectedIdentities,
339
+ });
340
+ artifacts = { status: "retained", path: "artifacts" };
341
+ }
342
+ catch (caught) {
343
+ if (artifactsDir !== undefined) {
344
+ await rm(artifactsDir, { recursive: true, force: true }).catch(() => { });
345
+ }
346
+ const message = errorMessage(caught);
347
+ artifacts = { status: "failed", error: message };
348
+ diagnostics.push(`failed to retain artifacts: ${message}`);
349
+ }
350
+ }
351
+ }
309
352
  try {
310
353
  await rm(root, { recursive: true, force: true, maxRetries: 3 });
311
354
  }
@@ -333,11 +376,105 @@ export async function executeEvaluation(prepared) {
333
376
  ...(error === undefined ? {} : { error }),
334
377
  diagnostics: boundedDiagnostics(diagnostics),
335
378
  cleanup,
379
+ ...(artifacts === undefined ? {} : { artifacts }),
336
380
  };
337
- const paths = await createResultDirectory(request.resultsDir, runId);
381
+ paths ??= await createResultDirectory(request.resultsDir, runId);
338
382
  await writeResult(paths, record, trace, mockRecords);
339
383
  return record;
340
384
  }
385
+ function shouldRetain(retain, status, expect) {
386
+ if (retain === "all")
387
+ return true;
388
+ if (retain === "none")
389
+ return false;
390
+ const outcome = classifyOutcome(status, expect);
391
+ return outcome !== "pass" && outcome !== "expected-fail" && outcome !== "cancelled";
392
+ }
393
+ async function recordProtectedIdentities(homeRoot, protectedPaths, identities) {
394
+ const seen = new Set(identities);
395
+ for (const path of protectedPaths) {
396
+ let resolved;
397
+ try {
398
+ // Follow in-HOME symlinks (matching ACP login copy-back) while rejecting escaping/broken links.
399
+ resolved = await resolveWorkspacePath(homeRoot, path);
400
+ }
401
+ catch (error) {
402
+ if (isMissing(error))
403
+ continue;
404
+ throw error;
405
+ }
406
+ try {
407
+ const info = await lstat(resolved, { bigint: true });
408
+ if (info.isFile()) {
409
+ const id = fileIdentity(info);
410
+ if (!seen.has(id)) {
411
+ seen.add(id);
412
+ identities.push(id);
413
+ }
414
+ }
415
+ }
416
+ catch (error) {
417
+ if (!isMissing(error))
418
+ throw error;
419
+ }
420
+ }
421
+ }
422
+ async function retainRunArtifacts(workspaceRoot, homeRoot, artifactsDir, excludeHome) {
423
+ await mkdir(artifactsDir, { recursive: true, mode: 0o700 });
424
+ if (workspaceRoot !== undefined) {
425
+ await assertRunRoot(workspaceRoot);
426
+ await retainTree(workspaceRoot.path, join(artifactsDir, "workspace"), {
427
+ paths: [],
428
+ identities: excludeHome.identities,
429
+ });
430
+ }
431
+ if (homeRoot !== undefined) {
432
+ await assertRunRoot(homeRoot);
433
+ await retainTree(homeRoot.path, join(artifactsDir, "home"), excludeHome);
434
+ }
435
+ }
436
+ async function retainTree(sourceDir, destinationDir, exclude) {
437
+ const excludedPaths = exclude?.paths ?? [];
438
+ const excludedIdentities = new Set(exclude?.identities ?? []);
439
+ const walk = async (currentSource, currentDest, relPrefix) => {
440
+ let entries;
441
+ try {
442
+ entries = await readdir(currentSource, { withFileTypes: true });
443
+ }
444
+ catch (caught) {
445
+ if (isMissing(caught))
446
+ return;
447
+ throw caught;
448
+ }
449
+ await mkdir(currentDest, { recursive: true, mode: 0o700 });
450
+ for (const entry of entries) {
451
+ const rel = relPrefix.length === 0 ? entry.name : `${relPrefix}/${entry.name}`;
452
+ if (isProtectedHomePath(rel, excludedPaths))
453
+ continue;
454
+ const srcPath = join(currentSource, entry.name);
455
+ let info;
456
+ try {
457
+ info = await lstat(srcPath, { bigint: true });
458
+ }
459
+ catch (caught) {
460
+ if (isMissing(caught))
461
+ continue;
462
+ throw caught;
463
+ }
464
+ if (info.isFile()) {
465
+ if (excludedIdentities.has(fileIdentity(info)))
466
+ continue;
467
+ await copyFile(srcPath, join(currentDest, entry.name));
468
+ }
469
+ else if (info.isDirectory()) {
470
+ await walk(srcPath, join(currentDest, entry.name), rel);
471
+ }
472
+ // Symlinks, sockets, FIFOs and devices are skipped so an agent-created link can never
473
+ // pull host files into the retained results directory.
474
+ }
475
+ };
476
+ await walk(sourceDir, destinationDir, "");
477
+ }
341
478
  async function prepareImplementations(request, values, signal) {
342
479
  const mockTargets = request.case.config.mocks === undefined ? undefined : Object.keys(request.case.config.mocks.shell);
343
480
  const runnerDefinition = requireRunner(request.registry, request.case.config.runner.$type);
@@ -351,6 +488,7 @@ async function prepareImplementations(request, values, signal) {
351
488
  // The case runner's placeholders resolve once; a checker-declared runner arrives resolved with
352
489
  // the checker parameters it was written in, so neither declaration is walked twice.
353
490
  const caseRunnerParams = await substituteValues(paramsOf(request.case.config.runner), "runner", values);
491
+ const concurrencyKeys = new Set();
354
492
  const createRunner = async (record) => {
355
493
  const declaration = record ?? request.case.config.runner;
356
494
  const definition = requireRunner(request.registry, declaration.$type);
@@ -358,7 +496,11 @@ async function prepareImplementations(request, values, signal) {
358
496
  // Each instance gets its own copy: a schema may keep a value it was given, and the case
359
497
  // runner's parameters are also the inherited judge's.
360
498
  structuredClone(record === undefined ? caseRunnerParams : paramsOf(record)), `runner "${definition.type}"`);
361
- return { type: definition.type, runner: await definition.create(params, context) };
499
+ const created = await definition.create(params, context);
500
+ if (created.concurrencyKey !== undefined) {
501
+ concurrencyKeys.add(created.concurrencyKey);
502
+ }
503
+ return { type: definition.type, runner: created };
362
504
  };
363
505
  const context = {
364
506
  authoringDir: request.case.dir,
@@ -366,7 +508,7 @@ async function prepareImplementations(request, values, signal) {
366
508
  validateFiles: (files) => validateCheckFiles(files, request.case.dir, "check files", signal),
367
509
  ...(mockTargets === undefined ? {} : { mockTargets }),
368
510
  runnerSupportsHome,
369
- validateCheckPlatform: async () => assertSeatbeltAvailable(),
511
+ validateCheckPlatform: async () => assertSandboxAvailable(),
370
512
  createRunner,
371
513
  };
372
514
  const { runner } = await createRunner();
@@ -377,7 +519,7 @@ async function prepareImplementations(request, values, signal) {
377
519
  const params = await parseImplementationParams(definition.params, await substituteValues(paramsOf(record), `checks[${index}]`, values), `checker "${definition.type}"`);
378
520
  checks.push({ type: definition.type, checker: await createChecker(definition, params, index, context) });
379
521
  }
380
- return { runnerType: runnerDefinition.type, runner, checks };
522
+ return { runnerType: runnerDefinition.type, runner, checks, concurrencyKeys: [...concurrencyKeys] };
381
523
  }
382
524
  /**
383
525
  * Create one checker and name the declaration in its failure: a checker may create a runner of its
@@ -444,7 +586,7 @@ async function validateAuthoringAssets(loadedCase) {
444
586
  }
445
587
  }
446
588
  }
447
- async function runChecks(prepared, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, trace, mockRecords, timeoutMs, signal, markCancelled) {
589
+ async function runChecks(prepared, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, protectedHome, trace, mockRecords, timeoutMs, signal, markCancelled) {
448
590
  const results = [];
449
591
  for (const [declaration, check] of prepared.entries()) {
450
592
  if (signal.aborted) {
@@ -472,6 +614,7 @@ async function runChecks(prepared, request, root, workspaceRoot, baselineRoot, h
472
614
  baseline: baselineRoot,
473
615
  home: homeRoot,
474
616
  homeBaseline: homeBaselineRoot,
617
+ protectedHome,
475
618
  runRootDir: root,
476
619
  input: request.case.config.input,
477
620
  ...(trace === undefined ? {} : { trace }),
@@ -1,5 +1,6 @@
1
1
  import { realpath } from "node:fs/promises";
2
- import { basename, dirname, isAbsolute, join, resolve } from "node:path";
2
+ import { basename, dirname, isAbsolute, join, parse as parsePath, resolve } from "node:path";
3
+ import { caseInsensitivePaths } from "../platform/index.js";
3
4
  import { parse } from "yaml";
4
5
  import { readRunFile } from "./workspace.js";
5
6
  /** The file every harness's skill loader reads when it consults a skill's body. */
@@ -185,16 +186,22 @@ async function canonicalExternalPath(target) {
185
186
  * Walking from `/` downward finds the host's root before entering any of its children.
186
187
  */
187
188
  async function relativeWithin(rootPath, target) {
188
- const segments = resolve(target).split("/").filter(Boolean);
189
- let probe = "/";
189
+ const resolved = resolve(target);
190
+ const root = parsePath(resolved).root;
191
+ const segments = resolved
192
+ .slice(root.length)
193
+ .split(/[\\/]+/)
194
+ .filter(Boolean);
195
+ const matchesRoot = (candidate) => caseInsensitivePaths ? candidate.toLowerCase() === rootPath.toLowerCase() : candidate === rootPath;
196
+ let probe = root;
190
197
  for (const [index, segment] of segments.entries()) {
191
198
  probe = join(probe, segment);
192
199
  const rest = segments.slice(index + 1);
193
- if (probe === rootPath) {
200
+ if (matchesRoot(probe)) {
194
201
  return rest.length === 0 ? undefined : join(...rest);
195
202
  }
196
203
  try {
197
- if ((await realpath(probe)) === rootPath) {
204
+ if (matchesRoot(await realpath(probe))) {
198
205
  return rest.length === 0 ? undefined : join(...rest);
199
206
  }
200
207
  }
@@ -6,5 +6,5 @@ export interface ViewOptions {
6
6
  /** List every placed and excluded path instead of the entry counts. */
7
7
  readonly files: boolean;
8
8
  }
9
- /** Render the declared configuration, its field origins and what it would place. */
9
+ /** Render the resolved configuration with inline `# <file>:<line>` origins and placement. */
10
10
  export declare function formatResolvedCase(resolved: ResolvedCase, options: ViewOptions): string;
@@ -1,19 +1,16 @@
1
- import { stringify } from "yaml";
2
- /** Render the declared configuration, its field origins and what it would place. */
1
+ import { randomBytes } from "node:crypto";
2
+ import { basename, sep } from "node:path";
3
+ import { Document, isMap, isNode, isScalar, isSeq } from "yaml";
4
+ /** Render the resolved configuration with inline `# <file>:<line>` origins and placement. */
3
5
  export function formatResolvedCase(resolved, options) {
4
6
  const lines = [
5
7
  `configuration: ${resolved.path}`,
6
8
  `case: ${resolved.name === undefined ? "(ordinary)" : JSON.stringify(resolved.name)}`,
7
9
  "resolved configuration:",
8
10
  ];
9
- for (const line of stringify(resolved.config).trimEnd().split("\n")) {
11
+ for (const line of formatAnnotatedConfig(resolved).trimEnd().split("\n")) {
10
12
  lines.push(` ${line}`);
11
13
  }
12
- lines.push("field origins:");
13
- for (const [field, origin] of Object.entries(resolved.origins)) {
14
- const source = origin.kind === "common" ? "common" : `case ${JSON.stringify(origin.caseName)}`;
15
- lines.push(` ${field}: ${source} ${origin.file}:${origin.line}`);
16
- }
17
14
  lines.push("placement:");
18
15
  if (options.placement.length === 0) {
19
16
  lines.push(" none");
@@ -24,15 +21,133 @@ export function formatResolvedCase(resolved, options) {
24
21
  continue;
25
22
  }
26
23
  for (const placed of summary.placed) {
27
- lines.push(` place ${placed.path} <- ${placed.source}`);
24
+ lines.push(` place ${toPosix(placed.path)} <- ${toPosix(placed.source)}`);
28
25
  }
29
26
  for (const excluded of summary.excluded) {
30
27
  const kind = excluded.directory ? " (directory)" : "";
31
- lines.push(` exclude ${excluded.path}${kind} <- .agentevalsignore at ${excluded.ignoreDir}`);
28
+ lines.push(` exclude ${toPosix(excluded.path)}${kind} <- .agentevalsignore at ${toPosix(excluded.ignoreDir)}`);
32
29
  }
33
30
  }
34
31
  return lines.join("\n") + "\n";
35
32
  }
33
+ const MAX_ALIGN_COLUMN = 44;
34
+ function formatAnnotatedConfig(resolved) {
35
+ const marker = `__AE_ORIGIN_${randomBytes(6).toString("hex")}__`;
36
+ const doc = new Document(resolved.config);
37
+ if (isMap(doc.contents)) {
38
+ for (const pair of doc.contents.items) {
39
+ if (!isScalar(pair.key) || typeof pair.key.value !== "string")
40
+ continue;
41
+ const origin = resolved.origins[pair.key.value];
42
+ if (origin === undefined)
43
+ continue;
44
+ applyOrigin(pair, origin, marker);
45
+ }
46
+ }
47
+ return alignOriginComments(doc.toString(), marker);
48
+ }
49
+ /**
50
+ * Align only the origin comments emitted by this function (tagged with `marker`), so literal
51
+ * `# ...` text inside user scalars is never altered. Capped so one long scalar does not push
52
+ * every other line's comment far to the right.
53
+ */
54
+ function alignOriginComments(yamlText, marker) {
55
+ const token = ` #${marker}`;
56
+ const lines = yamlText.trimEnd().split("\n");
57
+ const parsed = lines.map((line) => {
58
+ const index = line.lastIndexOf(token);
59
+ if (index === -1)
60
+ return { line };
61
+ return { body: line.slice(0, index), comment: `#${line.slice(index + token.length)}` };
62
+ });
63
+ let column = 0;
64
+ for (const entry of parsed) {
65
+ if ("comment" in entry && entry.body.length + 2 <= MAX_ALIGN_COLUMN) {
66
+ column = Math.max(column, entry.body.length + 2);
67
+ }
68
+ }
69
+ return parsed
70
+ .map((entry) => {
71
+ if (!("comment" in entry))
72
+ return entry.line;
73
+ const pad = Math.max(2, column - entry.body.length);
74
+ return `${entry.body}${" ".repeat(pad)}${entry.comment}`;
75
+ })
76
+ .join("\n");
77
+ }
78
+ function applyOrigin(pair, origin, marker) {
79
+ const uniform = uniformSource(origin);
80
+ if (uniform !== undefined) {
81
+ annotatePair(pair, formatSource(uniform, marker));
82
+ return;
83
+ }
84
+ if (origin.kind === "list") {
85
+ if (!isSeq(pair.value))
86
+ return;
87
+ for (const [index, item] of pair.value.items.entries()) {
88
+ const entryOrigin = origin.items[index];
89
+ if (entryOrigin === undefined)
90
+ continue;
91
+ const comment = formatSource(entryOrigin, marker);
92
+ if (isMap(item) && item.items[0] !== undefined) {
93
+ annotatePair(item.items[0], comment);
94
+ }
95
+ else if (isNode(item)) {
96
+ item.comment = comment;
97
+ }
98
+ }
99
+ return;
100
+ }
101
+ if (origin.kind === "map") {
102
+ if (!isMap(pair.value))
103
+ return;
104
+ for (const entryPair of pair.value.items) {
105
+ if (!isScalar(entryPair.key) || typeof entryPair.key.value !== "string")
106
+ continue;
107
+ const childOrigin = origin.entries[entryPair.key.value];
108
+ if (childOrigin !== undefined) {
109
+ applyOrigin(entryPair, childOrigin, marker);
110
+ }
111
+ }
112
+ }
113
+ }
114
+ /**
115
+ * If an entire field or subtree originates from one block (`common` or `case`) with no overrides,
116
+ * return that single source so `view` annotates only the highest node instead of every entry.
117
+ */
118
+ function uniformSource(origin) {
119
+ if (origin.kind === "common" || origin.kind === "case") {
120
+ return origin;
121
+ }
122
+ if (origin.kind === "list") {
123
+ const allSame = origin.items.every((item) => item.kind === origin.base.kind && item.overrides === undefined);
124
+ return allSame ? origin.base : undefined;
125
+ }
126
+ const children = Object.values(origin.entries);
127
+ const allSame = children.every((child) => {
128
+ const sub = uniformSource(child);
129
+ return sub !== undefined && sub.kind === origin.base.kind && sub.overrides === undefined;
130
+ });
131
+ return allSame ? origin.base : undefined;
132
+ }
133
+ function annotatePair(pair, comment) {
134
+ if (isScalar(pair.value)) {
135
+ pair.value.comment = comment;
136
+ }
137
+ else if (isNode(pair.key)) {
138
+ pair.key.comment = comment;
139
+ }
140
+ }
141
+ function formatSource(origin, marker) {
142
+ const self = `${basename(origin.file)}:${origin.line}`;
143
+ if (origin.overrides === undefined)
144
+ return `${marker} ${self}`;
145
+ const prev = `${basename(origin.overrides.file)}:${origin.overrides.line}`;
146
+ return `${marker} ${self} (overrides ${prev})`;
147
+ }
36
148
  function count(value, label) {
37
149
  return `${value} ${label}`;
38
150
  }
151
+ function toPosix(path) {
152
+ return sep === "/" ? path : path.split(sep).join("/");
153
+ }
@@ -54,3 +54,10 @@ export declare function runPathExists(root: RunRoot, requestedPath: string): Pro
54
54
  export declare function requireConfigurationPath(declaringDir: string, relativePath: string, label: string): string;
55
55
  export declare function isWithin(root: string, target: string): boolean;
56
56
  export declare function isMissing(error: unknown): boolean;
57
+ /** The identity a filesystem uses for one file, independent of the spelling that reached it. */
58
+ export declare function fileIdentity(info: {
59
+ readonly dev: bigint;
60
+ readonly ino: bigint;
61
+ }): string;
62
+ /** True when `relativePath` is or lies under any protected HOME-relative path. */
63
+ export declare function isProtectedHomePath(relativePath: string, protectedPaths: readonly string[]): boolean;
@@ -1,7 +1,7 @@
1
- import { constants } from "node:fs";
2
- import { lstat, open, readdir, realpath } from "node:fs/promises";
3
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
1
+ import { lstat, readdir, realpath } from "node:fs/promises";
2
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
4
3
  import { ConfigError, errorMessage } from "./config.js";
4
+ import { caseInsensitivePaths, openDirectoryIdentity, openRegularFileNoFollow } from "../platform/index.js";
5
5
  /** Largest file a check will read. Checks stay bounded and predictable. */
6
6
  export const MAX_CHECK_BYTES = 1024 * 1024;
7
7
  export class WorkspacePathError extends Error {
@@ -12,23 +12,13 @@ export class WorkspacePathError extends Error {
12
12
  }
13
13
  export async function openRunRoot(path) {
14
14
  const canonical = await realpath(path);
15
- let handle;
16
15
  try {
17
- handle = await open(canonical, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
16
+ const identity = await openDirectoryIdentity(canonical);
17
+ return { path: canonical, dev: identity.dev, ino: identity.ino };
18
18
  }
19
19
  catch (error) {
20
20
  throw new WorkspacePathError(`could not open run directory ${path}: ${errorMessage(error)}`);
21
21
  }
22
- try {
23
- const stats = await handle.stat({ bigint: true });
24
- if (!stats.isDirectory()) {
25
- throw new WorkspacePathError(`run path is not a directory: ${path}`);
26
- }
27
- return { path: canonical, dev: stats.dev, ino: stats.ino };
28
- }
29
- finally {
30
- await handle.close();
31
- }
32
22
  }
33
23
  /**
34
24
  * Verify the directory path still refers to the prepared directory. A path
@@ -45,21 +35,15 @@ export async function assertRunRoot(root) {
45
35
  if (entry.isSymbolicLink() || !entry.isDirectory() || entry.dev !== root.dev || entry.ino !== root.ino) {
46
36
  throw new WorkspacePathError(`run directory was replaced after preparation: ${root.path}`);
47
37
  }
48
- let handle;
38
+ let identity;
49
39
  try {
50
- handle = await open(root.path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
40
+ identity = await openDirectoryIdentity(root.path);
51
41
  }
52
42
  catch (error) {
53
43
  throw new WorkspacePathError(`run directory can no longer be opened safely: ${root.path}: ${errorMessage(error)}`);
54
44
  }
55
- try {
56
- const stats = await handle.stat({ bigint: true });
57
- if (!stats.isDirectory() || stats.dev !== root.dev || stats.ino !== root.ino) {
58
- throw new WorkspacePathError(`run directory was replaced while opening it: ${root.path}`);
59
- }
60
- }
61
- finally {
62
- await handle.close();
45
+ if (identity.dev !== root.dev || identity.ino !== root.ino) {
46
+ throw new WorkspacePathError(`run directory was replaced while opening it: ${root.path}`);
63
47
  }
64
48
  }
65
49
  /**
@@ -210,7 +194,7 @@ export async function readRunTree(root, requestedPath) {
210
194
  async function readBoundedFile(absolute, requestedPath) {
211
195
  let handle;
212
196
  try {
213
- handle = await open(absolute, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
197
+ handle = await openRegularFileNoFollow(absolute);
214
198
  }
215
199
  catch (error) {
216
200
  if (isMissing(error)) {
@@ -263,7 +247,7 @@ export async function runPathExists(root, requestedPath) {
263
247
  }
264
248
  }
265
249
  export function requireConfigurationPath(declaringDir, relativePath, label) {
266
- if (relativePath.startsWith("/") || relativePath.includes("\0")) {
250
+ if (isAbsolute(relativePath) || relativePath.startsWith("/") || relativePath.includes("\0")) {
267
251
  throw new ConfigError(`${label} must be a relative path`);
268
252
  }
269
253
  return resolve(declaringDir, relativePath);
@@ -278,3 +262,29 @@ export function isMissing(error) {
278
262
  "code" in error &&
279
263
  (error.code === "ENOENT" || error.code === "ENOTDIR"));
280
264
  }
265
+ /** The identity a filesystem uses for one file, independent of the spelling that reached it. */
266
+ export function fileIdentity(info) {
267
+ return `${info.dev}:${info.ino}`;
268
+ }
269
+ /** True when `relativePath` is or lies under any protected HOME-relative path. */
270
+ export function isProtectedHomePath(relativePath, protectedPaths) {
271
+ if (protectedPaths.length === 0)
272
+ return false;
273
+ const candidate = normalizeProtectedPath(relativePath);
274
+ if (candidate.length === 0)
275
+ return false;
276
+ return protectedPaths.some((entry) => {
277
+ const excluded = normalizeProtectedPath(entry);
278
+ return excluded.length > 0 && (candidate === excluded || candidate.startsWith(`${excluded}/`));
279
+ });
280
+ }
281
+ function normalizeProtectedPath(path) {
282
+ const withSlashes = sep === "/" ? path : path.split(sep).join("/");
283
+ const cleaned = withSlashes.replace(/^\/+/u, "").replace(/\/+$/u, "");
284
+ if (cleaned.length === 0)
285
+ return "";
286
+ const normalized = posix.normalize(cleaned).replace(/\/+$/u, "");
287
+ if (normalized === ".")
288
+ return "";
289
+ return caseInsensitivePaths ? normalized.toLowerCase() : normalized;
290
+ }