@lelouchhe/agent-evals 0.1.1 → 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.
@@ -220,7 +220,16 @@ function document(path, cases) {
220
220
  function instrument(cases) {
221
221
  const runs = [...cases.values()].flat();
222
222
  const counts = new Set([...cases.values()].map((entry) => entry.length));
223
- return `runner ${listed(runs.map((run) => value(run.resolvedConfig.runner["$type"])))} · harness ${listed(runs.map(harness))} · model ${listed(runs.map(model))} · ${counts.size === 1 ? `reps ${[...counts][0]}` : "reps mixed"} · cases ${cases.size}`;
223
+ const judges = judgeInstruments(runs);
224
+ const parts = [
225
+ `runner ${listed(runs.map((run) => value(run.resolvedConfig.runner["$type"])))}`,
226
+ `harness ${listed(runs.map(harness))}`,
227
+ `model ${listed(runs.map(model))}`,
228
+ ...(judges.length === 0 ? [] : [`judge ${listed(judges)}`]),
229
+ counts.size === 1 ? `reps ${[...counts][0]}` : "reps mixed",
230
+ `cases ${cases.size}`,
231
+ ];
232
+ return parts.join(" · ");
224
233
  }
225
234
  function caseLine(label, runs, width, verdictWidth) {
226
235
  const verdict = verdictOf(runs);
@@ -346,19 +355,45 @@ function longest(values) {
346
355
  return size;
347
356
  }
348
357
  function harness(record) {
349
- const agent = record.resolvedConfig.runner["agent"];
358
+ return harnessOf(record.resolvedConfig.runner);
359
+ }
360
+ function model(record) {
361
+ return modelOf(record.resolvedConfig.runner);
362
+ }
363
+ function harnessOf(runner) {
364
+ const agent = runner["agent"];
350
365
  if (typeof agent !== "string")
351
- return value(record.resolvedConfig.runner["$type"]);
366
+ return value(runner["$type"]);
352
367
  const name = basename(agent);
353
- return name.includes(".") ? name.slice(0, name.lastIndexOf(".")) : name;
368
+ return value(name.includes(".") ? name.slice(0, name.lastIndexOf(".")) : name);
354
369
  }
355
- function model(record) {
356
- const config = record.resolvedConfig.runner["config"];
370
+ function modelOf(runner) {
371
+ const config = runner["config"];
357
372
  const configured = typeof config === "object" && config !== null ? config["model"] : undefined;
358
- return value(configured ?? record.resolvedConfig.runner["model"]);
373
+ return value(configured ?? runner["model"]);
374
+ }
375
+ function judgeInstruments(runs) {
376
+ const result = [];
377
+ for (const run of runs) {
378
+ for (const check of run.resolvedConfig.checks) {
379
+ if (check["$type"] !== "judge")
380
+ continue;
381
+ const declared = check["runner"];
382
+ const runner = typeof declared === "object" && declared !== null && !Array.isArray(declared)
383
+ ? declared
384
+ : run.resolvedConfig.runner;
385
+ const judgeHarness = harnessOf(runner);
386
+ const judgeModel = modelOf(runner);
387
+ result.push(judgeModel === "—" ? judgeHarness : `${judgeHarness}/${judgeModel}`);
388
+ }
389
+ }
390
+ return result;
359
391
  }
360
392
  function value(input) {
361
- return typeof input === "string" && input !== "" ? input : "—";
393
+ if (typeof input !== "string")
394
+ return "—";
395
+ const singleLine = input.replace(/\r\n?|[\n\u0085\u2028\u2029]/gu, " ").trim();
396
+ return singleLine === "" ? "—" : singleLine;
362
397
  }
363
398
  function sum(runs, pick) {
364
399
  return runs.reduce((total, run) => total + pick(run), 0);
@@ -1,8 +1,10 @@
1
1
  import type { CaseConfig } from "./config.js";
2
2
  import type { MockRecord, RecordedCheckResult, RunnerUsage, TraceEntry } from "./registry.js";
3
3
  export type RunStatus = "pass" | "fail" | "error" | "timeout" | "cancelled";
4
+ export type RetainArtifacts = "none" | "on-failure" | "all";
4
5
  /** A run read against its case's expectation; the only place `expect` changes a status's meaning. */
5
6
  export type RunOutcome = RunStatus | "expected-fail" | "unexpected-pass";
7
+ export declare function classifyOutcome(status: RunStatus, expect: CaseConfig["expect"]): RunOutcome;
6
8
  export declare function runOutcome(run: EvaluationRecord): RunOutcome;
7
9
  export type RunnerStatus = "completed" | "error" | "timeout" | "cancelled";
8
10
  export interface RunnerRecord {
@@ -33,6 +35,11 @@ export interface EvaluationRecord {
33
35
  readonly status: "removed" | "failed";
34
36
  readonly error?: string;
35
37
  };
38
+ readonly artifacts?: {
39
+ readonly status: "retained" | "failed";
40
+ readonly path?: string;
41
+ readonly error?: string;
42
+ };
36
43
  }
37
44
  export interface ResultPaths {
38
45
  readonly directory: string;
@@ -1,14 +1,17 @@
1
1
  import { mkdir, rename, writeFile } from "node:fs/promises";
2
2
  import { join, resolve } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
- export function runOutcome(run) {
5
- if (run.status === "pass") {
6
- return run.resolvedConfig.expect === "fail" ? "unexpected-pass" : "pass";
4
+ export function classifyOutcome(status, expect) {
5
+ if (status === "pass") {
6
+ return expect === "fail" ? "unexpected-pass" : "pass";
7
7
  }
8
- if (run.status === "fail") {
9
- return run.resolvedConfig.expect === "fail" ? "expected-fail" : "fail";
8
+ if (status === "fail") {
9
+ return expect === "fail" ? "expected-fail" : "fail";
10
10
  }
11
- return run.status;
11
+ return status;
12
+ }
13
+ export function runOutcome(run) {
14
+ return classifyOutcome(run.status, run.resolvedConfig.expect);
12
15
  }
13
16
  export function newRunId(now = new Date()) {
14
17
  return `${now.toISOString().replaceAll(":", "-").replaceAll(".", "-")}-${randomUUID().slice(0, 8)}`;
@@ -1,11 +1,12 @@
1
1
  import { type ResolvedCase } from "./config.js";
2
2
  import { type Checker, type Registry, type Runner } from "./registry.js";
3
- import { type EvaluationRecord } from "./results.js";
3
+ import { type EvaluationRecord, type RetainArtifacts } from "./results.js";
4
4
  import { type EnvSource } from "./env-source.js";
5
5
  export interface RunRequest {
6
6
  readonly case: ResolvedCase;
7
7
  readonly registry: Registry;
8
8
  readonly resultsDir: string;
9
+ readonly retain?: RetainArtifacts;
9
10
  readonly signal?: AbortSignal;
10
11
  /** Parent directory for the temporary run root. Tests use this to inspect cleanup. */
11
12
  readonly tempParent?: string;
@@ -34,6 +35,8 @@ export interface PreparedEvaluation {
34
35
  readonly type: string;
35
36
  readonly checker: Checker;
36
37
  }[];
38
+ /** Shared mutable resource keys across all runners created for this evaluation (case + checkers). */
39
+ readonly concurrencyKeys: readonly string[];
37
40
  };
38
41
  }
39
42
  /**
@@ -1,11 +1,11 @@
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
4
  import { tmpdir } from "node:os";
5
5
  import { assertSeatbeltAvailable } from "../platform/macos/policy.js";
6
6
  import { ConfigError, errorMessage, resolveAuthoringAsset, } from "./config.js";
7
7
  import { requireChecker, requireRunner, } from "./registry.js";
8
- import { createResultDirectory, newRunId, writeResult, } from "./results.js";
8
+ import { classifyOutcome, createResultDirectory, newRunId, writeResult, } from "./results.js";
9
9
  import { createEnvSource } from "./env-source.js";
10
10
  import { authoringCopyFilter, copyPlacement, fileIdentity, homeEntries, placeCaseFiles, placedPaths, stageEntries, validateCheckFiles, } from "./files.js";
11
11
  import { startMockHost } from "./mocks.js";
@@ -13,7 +13,7 @@ import { createCheckSandbox } from "./check-sandbox.js";
13
13
  import { parseImplementationParams } from "./params.js";
14
14
  import { truncate, truncateNullable } from "./truncate.js";
15
15
  import { substituteValues } from "./values.js";
16
- import { isMissing, openRunRoot } from "./workspace.js";
16
+ import { assertRunRoot, isMissing, isProtectedHomePath, openRunRoot, resolveWorkspacePath, } from "./workspace.js";
17
17
  const DEFAULT_TIMEOUT_MS = 300_000;
18
18
  const CHECK_ABORT_GRACE_MS = 12_000;
19
19
  const MAX_RECORDED_TEXT = 4_000;
@@ -85,7 +85,13 @@ export async function executeEvaluation(prepared) {
85
85
  throw error;
86
86
  }
87
87
  let runner;
88
+ let workspaceRoot;
89
+ let homeRoot;
88
90
  let cleanup = { status: "removed" };
91
+ let artifacts;
92
+ let protectedPaths = registered.runner.homeFiles ?? [];
93
+ const protectedIdentities = [];
94
+ let protectedIdentitiesError;
89
95
  let runnerRecord = {
90
96
  type: registered.runnerType,
91
97
  status: "error",
@@ -100,10 +106,11 @@ export async function executeEvaluation(prepared) {
100
106
  let mockFailed = false;
101
107
  const diagnostics = [];
102
108
  let error;
103
- let status;
109
+ let status = "error";
104
110
  let timedOut = false;
105
111
  let stopFailed = false;
106
112
  let timer;
113
+ let paths;
107
114
  try {
108
115
  await Promise.all([
109
116
  mkdir(workspaceDir, { mode: 0o700 }),
@@ -113,6 +120,8 @@ export async function executeEvaluation(prepared) {
113
120
  mkdir(join(engineDir, "baseline", "workspace"), { recursive: true, mode: 0o700 }),
114
121
  mkdir(join(engineDir, "baseline", "home"), { recursive: true, mode: 0o700 }),
115
122
  ]);
123
+ // Capture root identities immediately after creation so setup failures still retain safely.
124
+ [workspaceRoot, homeRoot] = await Promise.all([openRunRoot(workspaceDir), openRunRoot(homeDir)]);
116
125
  const fixture = request.case.config.fixture;
117
126
  if (fixture !== undefined) {
118
127
  const source = resolveAuthoringAsset(request.case.dir, fixture, "case.fixture");
@@ -123,7 +132,6 @@ export async function executeEvaluation(prepared) {
123
132
  });
124
133
  }
125
134
  await placeCaseFiles(request.case, join(engineDir, "files", "workspace"), workspaceDir);
126
- const workspaceRoot = await openRunRoot(workspaceDir);
127
135
  // The runner places its own HOME content first; the case then overlays it without
128
136
  // touching login state, and only what the case placed becomes the HOME baseline.
129
137
  const context = {
@@ -138,20 +146,16 @@ export async function executeEvaluation(prepared) {
138
146
  signal: abort.signal,
139
147
  };
140
148
  runner = registered.runner;
141
- const protectedPaths = (await runner.prepareHome?.(context)) ?? [];
149
+ const preparedProtected = (await runner.prepareHome?.(context)) ?? [];
150
+ protectedPaths = [...new Set([...protectedPaths, ...preparedProtected])];
142
151
  // Login state is protected by the file the filesystem actually holds at each declared
143
152
  // 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
- }
153
+ try {
154
+ await recordProtectedIdentities(homeRoot, protectedPaths, protectedIdentities);
155
+ }
156
+ catch (caught) {
157
+ protectedIdentitiesError = errorMessage(caught);
158
+ throw caught;
155
159
  }
156
160
  const homePlacements = homeEntries(request.case.config.files);
157
161
  const homeStaging = join(engineDir, "files", "home");
@@ -170,7 +174,6 @@ export async function executeEvaluation(prepared) {
170
174
  await rm(homeStaging, { recursive: true, force: true });
171
175
  }
172
176
  }
173
- const homeRoot = await openRunRoot(homeDir);
174
177
  // Forwarders are written before the baseline snapshot, so it already holds them.
175
178
  const mocks = request.case.config.mocks;
176
179
  if (mocks !== undefined) {
@@ -237,6 +240,16 @@ export async function executeEvaluation(prepared) {
237
240
  trace = runner.trace?.();
238
241
  usage = runner.usage?.();
239
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
+ }
240
253
  }
241
254
  const runnerStatus = stopFailed
242
255
  ? "error"
@@ -254,9 +267,9 @@ export async function executeEvaluation(prepared) {
254
267
  finalText: outcome === undefined ? null : truncateNullable(outcome.finalText, MAX_RECORDED_TEXT),
255
268
  ...(usage === undefined ? {} : { usage }),
256
269
  };
257
- if (outcome !== undefined) {
270
+ if (outcome !== undefined && protectedIdentitiesError === undefined) {
258
271
  diagnostics.push(...outcome.diagnostics);
259
- checks = await runChecks(registered.checks, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, trace, mockRecords, timeoutMs, abort.signal, () => {
272
+ checks = await runChecks(registered.checks, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, { paths: protectedPaths, identities: protectedIdentities }, trace, mockRecords, timeoutMs, abort.signal, () => {
260
273
  cancelled = true;
261
274
  });
262
275
  }
@@ -272,6 +285,10 @@ export async function executeEvaluation(prepared) {
272
285
  status = "error";
273
286
  error ??= "runner failed before checks could run";
274
287
  }
288
+ else if (protectedIdentitiesError !== undefined) {
289
+ status = "error";
290
+ error ??= `failed to inspect protected login state: ${protectedIdentitiesError}`;
291
+ }
275
292
  else if (mockFailed) {
276
293
  status = "error";
277
294
  error ??= "a mock fault ended the run";
@@ -306,6 +323,33 @@ export async function executeEvaluation(prepared) {
306
323
  diagnostics.push(`failed to close mock host: ${errorMessage(caught)}`);
307
324
  }
308
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
+ }
309
353
  try {
310
354
  await rm(root, { recursive: true, force: true, maxRetries: 3 });
311
355
  }
@@ -333,11 +377,105 @@ export async function executeEvaluation(prepared) {
333
377
  ...(error === undefined ? {} : { error }),
334
378
  diagnostics: boundedDiagnostics(diagnostics),
335
379
  cleanup,
380
+ ...(artifacts === undefined ? {} : { artifacts }),
336
381
  };
337
- const paths = await createResultDirectory(request.resultsDir, runId);
382
+ paths ??= await createResultDirectory(request.resultsDir, runId);
338
383
  await writeResult(paths, record, trace, mockRecords);
339
384
  return record;
340
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
+ }
341
479
  async function prepareImplementations(request, values, signal) {
342
480
  const mockTargets = request.case.config.mocks === undefined ? undefined : Object.keys(request.case.config.mocks.shell);
343
481
  const runnerDefinition = requireRunner(request.registry, request.case.config.runner.$type);
@@ -351,6 +489,7 @@ async function prepareImplementations(request, values, signal) {
351
489
  // The case runner's placeholders resolve once; a checker-declared runner arrives resolved with
352
490
  // the checker parameters it was written in, so neither declaration is walked twice.
353
491
  const caseRunnerParams = await substituteValues(paramsOf(request.case.config.runner), "runner", values);
492
+ const concurrencyKeys = new Set();
354
493
  const createRunner = async (record) => {
355
494
  const declaration = record ?? request.case.config.runner;
356
495
  const definition = requireRunner(request.registry, declaration.$type);
@@ -358,7 +497,11 @@ async function prepareImplementations(request, values, signal) {
358
497
  // Each instance gets its own copy: a schema may keep a value it was given, and the case
359
498
  // runner's parameters are also the inherited judge's.
360
499
  structuredClone(record === undefined ? caseRunnerParams : paramsOf(record)), `runner "${definition.type}"`);
361
- return { type: definition.type, runner: await definition.create(params, context) };
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 };
362
505
  };
363
506
  const context = {
364
507
  authoringDir: request.case.dir,
@@ -377,7 +520,7 @@ async function prepareImplementations(request, values, signal) {
377
520
  const params = await parseImplementationParams(definition.params, await substituteValues(paramsOf(record), `checks[${index}]`, values), `checker "${definition.type}"`);
378
521
  checks.push({ type: definition.type, checker: await createChecker(definition, params, index, context) });
379
522
  }
380
- return { runnerType: runnerDefinition.type, runner, checks };
523
+ return { runnerType: runnerDefinition.type, runner, checks, concurrencyKeys: [...concurrencyKeys] };
381
524
  }
382
525
  /**
383
526
  * Create one checker and name the declaration in its failure: a checker may create a runner of its
@@ -444,7 +587,7 @@ async function validateAuthoringAssets(loadedCase) {
444
587
  }
445
588
  }
446
589
  }
447
- async function runChecks(prepared, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, trace, mockRecords, timeoutMs, signal, markCancelled) {
590
+ async function runChecks(prepared, request, root, workspaceRoot, baselineRoot, homeRoot, homeBaselineRoot, protectedHome, trace, mockRecords, timeoutMs, signal, markCancelled) {
448
591
  const results = [];
449
592
  for (const [declaration, check] of prepared.entries()) {
450
593
  if (signal.aborted) {
@@ -472,6 +615,7 @@ async function runChecks(prepared, request, root, workspaceRoot, baselineRoot, h
472
615
  baseline: baselineRoot,
473
616
  home: homeRoot,
474
617
  homeBaseline: homeBaselineRoot,
618
+ protectedHome,
475
619
  runRootDir: root,
476
620
  input: request.case.config.input,
477
621
  ...(trace === undefined ? {} : { trace }),
@@ -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 } 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");
@@ -33,6 +30,121 @@ export function formatResolvedCase(resolved, options) {
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
  }
@@ -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;