@hawkeyexl/manni 4.1.0 → 4.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.
- package/README.md +2 -2
- package/dist/batch-7JJWXWSF.js +18 -0
- package/dist/batch-7JJWXWSF.js.map +1 -0
- package/dist/calibrate-IA2ARFMH.js +13 -0
- package/dist/calibrate-IA2ARFMH.js.map +1 -0
- package/dist/capture-C32JXIFN.js +15 -0
- package/dist/capture-C32JXIFN.js.map +1 -0
- package/dist/chunk-3R23C5DT.js +120 -0
- package/dist/chunk-3R23C5DT.js.map +1 -0
- package/dist/chunk-CI2GOU3A.js +4447 -0
- package/dist/chunk-CI2GOU3A.js.map +1 -0
- package/dist/{chunk-I57KBF45.js → chunk-DP2ZA3WH.js} +1203 -142
- package/dist/chunk-DP2ZA3WH.js.map +1 -0
- package/dist/chunk-ESJ5W7EV.js +297 -0
- package/dist/chunk-ESJ5W7EV.js.map +1 -0
- package/dist/chunk-IOYXPBCL.js +37 -0
- package/dist/chunk-IOYXPBCL.js.map +1 -0
- package/dist/chunk-KTSJ2ZHA.js +40 -0
- package/dist/chunk-KTSJ2ZHA.js.map +1 -0
- package/dist/{chunk-JODRT4NF.js → chunk-MFDD3YGU.js} +8 -37
- package/dist/chunk-MFDD3YGU.js.map +1 -0
- package/dist/chunk-MOQXWXSG.js +1941 -0
- package/dist/chunk-MOQXWXSG.js.map +1 -0
- package/dist/{chunk-S3NDEIOW.js → chunk-O6RVQKK6.js} +10502 -3017
- package/dist/chunk-O6RVQKK6.js.map +1 -0
- package/dist/chunk-QROCFW5S.js +174 -0
- package/dist/chunk-QROCFW5S.js.map +1 -0
- package/dist/chunk-RVVCA4WL.js +379 -0
- package/dist/chunk-RVVCA4WL.js.map +1 -0
- package/dist/cli.js +1293 -140
- package/dist/cli.js.map +1 -1
- package/dist/docmeta.js +3 -2
- package/dist/docmeta.js.map +1 -1
- package/dist/graph/embed.d.ts +154 -0
- package/dist/graph/embed.js +137 -0
- package/dist/graph/embed.js.map +1 -0
- package/dist/graph/runtime.d.ts +751 -0
- package/dist/graph/runtime.js +3067 -0
- package/dist/graph/runtime.js.map +1 -0
- package/dist/index.d.ts +6149 -799
- package/dist/index.js +682 -7
- package/dist/index.js.map +1 -1
- package/dist/picker-6HRMETE7.js +12 -0
- package/dist/picker-6HRMETE7.js.map +1 -0
- package/package.json +32 -4
- package/plugin/tracevals/.claude-plugin/plugin.json +9 -0
- package/plugin/tracevals/hooks/hooks.json +17 -0
- package/shapes/graph/shapes-1.0.0.ttl +689 -0
- package/dist/chunk-I57KBF45.js.map +0 -1
- package/dist/chunk-JODRT4NF.js.map +0 -1
- package/dist/chunk-S3NDEIOW.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tracevals/commands/batch.ts","../src/docevals/judge/budget.ts","../src/tracevals/aggregate.ts","../src/shared/duration.ts","../src/tracevals/reporters/batch.ts","../src/tracevals/reporters/calibration.ts","../src/shared/sarif-location.ts","../src/tracevals/reporters/ci.ts","../src/tracevals/reporters/github.ts","../src/tracevals/reporters/junit.ts","../src/tracevals/reporters/coverage.ts","../src/tracevals/reporters/pretty.ts","../src/tracevals/reporters/markdown.ts","../src/tracevals/reporters/sarif.ts","../src/tracevals/reporters/format.ts","../src/tracevals/reporters/index.ts","../src/tracevals/commands/run.ts","../src/tracevals/trace/claude.ts","../src/tracevals/trace/detect.ts","../src/tracevals/core/plan.ts","../src/tracevals/judge/prompt.ts","../src/tracevals/graders/glob.ts","../src/tracevals/graders/when.ts","../src/tracevals/graders/util.ts","../src/tracevals/graders/tool-usage.ts","../src/tracevals/graders/tool-order.ts","../src/tracevals/graders/skill-invoked.ts","../src/tracevals/graders/file-access.ts","../src/tracevals/graders/turn-count.ts","../src/tracevals/graders/cost.ts","../src/tracevals/core/target.ts","../src/tracevals/graders/regex.ts","../src/tracevals/graders/json-output.ts","../src/tracevals/graders/command.ts","../src/shared/exec.ts","../src/tracevals/graders/registry.ts","../src/tracevals/judge/render.ts","../src/tracevals/core/engine.ts","../src/tracevals/evals/external.ts","../src/tracevals/graders/plugins.ts","../src/tracevals/history.ts","../src/tracevals/judge/provider.ts","../src/tracevals/judge/trace-judge.ts","../src/tracevals/judge/verdict-schema.json","../src/tracevals/judge/cache.ts"],"sourcesContent":["/**\n * `manni tracevals run <trace...>` — evaluate many traces in one process and\n * report rates rather than a single verdict (ADR 01018).\n *\n * `runRun` stays the single-trace path and is untouched; this wraps the seams\n * it exposes. The reason a wrapper is not enough on its own is the budget: the\n * judge carries it, so it is built **once** by `prepareRun` and shared across\n * every trace. Building one per trace would make `maxTurns` a cap on the\n * largest trace instead of on the run, and a fifty-trace batch would spend\n * fifty times the configured ceiling while every report claimed to respect it.\n */\nimport { writeFile } from \"node:fs/promises\";\nimport {\n aggregate,\n type BatchOutcome,\n type BatchReportWithBudget,\n} from \"../aggregate.js\";\nimport { parseDuration } from \"../../shared/duration.js\";\nimport { discoverTraces, type TraceListing } from \"../trace/discover.js\";\nimport { renderBatch, type ReportFormat } from \"../reporters/index.js\";\nimport { TracevalsError, type RunReport } from \"../types.js\";\nimport type { HistoryComparison } from \"../history.js\";\nimport {\n prepareRun,\n runOne,\n type RunSharedOptions,\n} from \"./run.js\";\n\nexport interface BatchCommandOptions extends RunSharedOptions {\n /** Traces named on the command line, evaluated in this order. */\n traces?: string[];\n /** Discover every project in the session store instead of naming traces. */\n allProjects?: boolean;\n /** `--newer-than`: keep only traces modified within this duration, e.g. `7d`. */\n newerThan?: string;\n /** Maximum traces to evaluate, applied after newest-first sorting. */\n limit?: number;\n format?: ReportFormat;\n output?: string;\n}\n\nexport interface BatchCommandResult {\n /** Carries `budget` when the shared judge budget was exhausted mid-corpus. */\n report: BatchReportWithBudget;\n rendered: string;\n /** Per-trace reports in batch order; absent entries failed to parse. */\n reports: RunReport[];\n /**\n * File-to-report pairs in batch order, including the traces that failed to\n * parse. `reports` cannot carry that pairing — an entry drops out when a\n * trace errors, so the indices stop lining up with the corpus. `calibrate`\n * joins labels on the file, so it needs the pairing (ADR 01022).\n */\n outcomes: BatchOutcome[];\n /** `--history` comparisons, one per trace that had a previous run. */\n comparisons: HistoryComparison[];\n}\n\n/**\n * `--newer-than 7d` to milliseconds, through the family's one parser so the\n * grammar and the refusal match `manni docevals run --newer-than`.\n */\nexport function parseNewerThan(text: string): number {\n return parseDuration(text, (message) => new TracevalsError(message));\n}\n\n/**\n * The listings modified inside the `--newer-than` window, or all of them\n * without one. `list` and `run` share it, so a reader sees the selection a run\n * would evaluate.\n */\nexport function keepNewerThan<T extends Pick<TraceListing, \"mtimeMs\">>(\n listings: T[],\n newerThan: string | undefined,\n): T[] {\n if (newerThan === undefined) return listings;\n const floor = Date.now() - parseNewerThan(newerThan);\n return listings.filter((l) => l.mtimeMs >= floor);\n}\n\n/** True when any flag asks the session store to choose the traces. */\nfunction usesDiscovery(options: BatchCommandOptions): boolean {\n return (\n options.allProjects === true ||\n options.newerThan !== undefined ||\n options.limit !== undefined\n );\n}\n\n/**\n * Which traces this invocation evaluates, in the order they are reported.\n *\n * Named traces keep argv order; discovered ones keep `discoverTraces`' own\n * newest-first order. Both are stable for a fixed corpus, which is what makes\n * two runs comparable.\n */\nexport async function resolveBatchTraces(\n options: BatchCommandOptions,\n): Promise<string[]> {\n const named = options.traces ?? [];\n if (named.length > 0 && usesDiscovery(options)) {\n // Silently ignoring one or the other is the failure mode here: a\n // `--limit 5` that did nothing, or a named trace that was quietly dropped.\n throw new TracevalsError(\n \"name traces or select them with --all-projects/--newer-than/--limit, not both\",\n );\n }\n if (named.length > 0) return named;\n\n const listings = await discoverTraces({\n ...(options.allProjects !== undefined\n ? { allProjects: options.allProjects }\n : {}),\n ...(options.project !== undefined ? { project: options.project } : {}),\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n ...(options.env !== undefined ? { env: options.env } : {}),\n });\n\n const kept = keepNewerThan(listings, options.newerThan);\n\n if (kept.length === 0) {\n // Never exit 0 here. A gate that goes green because its selector matched\n // nothing is the false pass this tool exists to prevent, and it is\n // indistinguishable from a clean corpus in every downstream consumer.\n const how = [\n options.allProjects === true ? \"--all-projects\" : `project ${options.project ?? process.cwd()}`,\n options.newerThan !== undefined ? `--newer-than ${options.newerThan}` : undefined,\n options.limit !== undefined ? `--limit ${options.limit}` : undefined,\n ]\n .filter((s) => s !== undefined)\n .join(\", \");\n throw new TracevalsError(\n `no traces matched (${how}); run \\`manni tracevals list\\` to see what the session store holds`,\n );\n }\n return kept.map((l) => l.file);\n}\n\nexport async function runBatch(\n options: BatchCommandOptions,\n): Promise<BatchCommandResult> {\n const start = Date.now();\n const files = await resolveBatchTraces(options);\n\n // Once for the whole batch: the judge (and its budget), the resolved config,\n // and the grader plugins.\n const context = await prepareRun(options);\n\n const outcomes: BatchOutcome[] = [];\n const reports: RunReport[] = [];\n const comparisons: HistoryComparison[] = [];\n\n // Sequential on purpose. The budget gate is a running total, so traces have\n // to be charged against it in a defined order for an exhausted budget to be\n // reproducible; concurrency would make which traces got judged a race.\n for (const file of files) {\n const traceStart = Date.now();\n try {\n const { report, comparison } = await runOne(\n { ...options, tracePath: file },\n context,\n );\n outcomes.push({ file, report });\n reports.push(report);\n if (comparison) comparisons.push(comparison);\n } catch (err) {\n // ADR 01003's spirit: degrade, never abort. One unreadable file in a\n // corpus of fifty must not cost the other forty-nine their verdicts.\n outcomes.push({\n file,\n error: err instanceof Error ? err.message : String(err),\n durationMs: Date.now() - traceStart,\n });\n }\n }\n\n const report = aggregate(outcomes, {\n warnings: context.warnings,\n durationMs: Date.now() - start,\n });\n\n const rendered = renderBatch(report, options.format ?? \"pretty\", reports, {\n color: options.color === true,\n });\n if (options.output) {\n await writeFile(options.output, rendered, \"utf-8\");\n }\n return { report, rendered, reports, outcomes, comparisons };\n}\n","/**\n * The turn-budget skip marker (ADR 01019), in one place.\n *\n * `judge.ts` produces the skip reason; `core/engine.ts` and `commands/\n * calibrate.ts` both have to tell a budget truncation apart from every other\n * reason an eval went unjudged, because that distinction is what stops a\n * partial run from reporting as a complete one. They did it by matching the\n * bare substring `\"turn budget\"` against a message written in a third file,\n * so a reword in the producer would have left both detectors matching nothing\n * — silently, since the tests that exercise truncation supply the skip reason\n * themselves rather than getting it from the judge.\n *\n * Kept in its own module rather than exported from `judge.ts`: the detectors\n * need the marker, not the judge, and `engine.ts` deliberately takes the judge\n * by injection.\n */\n\n/** The substring every budget-truncation skip reason carries. */\nexport const TURN_BUDGET_SKIP = \"turn budget\";\n\n/** The skip reason recorded for an eval the budget stopped before dispatch. */\nexport function turnBudgetSkipReason(maxTurns: number): string {\n return `judge ${TURN_BUDGET_SKIP} exhausted (${maxTurns})`;\n}\n\n/**\n * Whether a skip reason is the budget's doing rather than the judge's.\n *\n * A type predicate, not a plain boolean: a budget skip always carries a\n * reason, and callers interpolate it into the message they report.\n */\nexport function isTurnBudgetSkip(reason: string | undefined): reason is string {\n return reason !== undefined && reason.includes(TURN_BUDGET_SKIP);\n}\n","/**\n * Fold N single-trace reports into rates (ADR 01018).\n *\n * \"Is this skill working?\" is a question about many sessions, and the answer is\n * a proportion. Everything here is pure — reports in, rows out — so the shape\n * of the aggregate is testable without running anything.\n */\nimport { isTurnBudgetSkip } from \"../docevals/judge/budget.js\";\nimport type {\n AggregateCounts,\n AggregateRow,\n BatchReport,\n BatchSummary,\n BatchTraceEntry,\n EvalResult,\n RunReport,\n} from \"./types.js\";\n\n/** A trace that produced a report, or one that could not be read at all. */\nexport type BatchOutcome =\n | { file: string; report: RunReport }\n | { file: string; error: string; durationMs: number };\n\n\n/**\n * What an exhausted budget cost this batch: how many evals it left unjudged,\n * across how many traces, and the reason as the judge stated it.\n *\n * Reported separately from the skip counts because the two mean different\n * things. An eval skipped for a trigger that never armed produced no evidence\n * *about the session*; an eval skipped for an exhausted budget produced no\n * evidence *about anything* — the tool simply stopped looking.\n */\nexport interface BatchBudget {\n /** Evals left unjudged, summed over every trace. */\n skippedEvals: number;\n /** Traces that carried at least one such skip. */\n traces: number;\n /** The judge's own wording, budget figure included. */\n reason: string;\n}\n\n/**\n * `BatchReport` plus the budget block.\n *\n * Declared here rather than in `types.ts` for the same reason `BatchOutcome`\n * is: the field exists because of how the batch is *folded*, and every\n * consumer reaches it through `aggregate`. `budget` is optional, so a plain\n * `BatchReport` is still assignable — nothing downstream has to change to\n * ignore it.\n */\nexport interface BatchReportWithBudget extends BatchReport {\n budget?: BatchBudget;\n}\n\nconst zero = (): AggregateCounts => ({\n pass: 0,\n fail: 0,\n error: 0,\n needsReview: 0,\n skipped: 0,\n});\n\nfunction tally(counts: AggregateCounts, outcome: EvalResult[\"outcome\"]): void {\n if (outcome === \"needs-review\") counts.needsReview += 1;\n else counts[outcome] += 1;\n}\n\n/** Byte-comparison sort, so ordering does not depend on the runner's locale. */\nconst byKey = (a: { key: string }, b: { key: string }): number =>\n a.key < b.key ? -1 : a.key > b.key ? 1 : 0;\n\ninterface Accumulator {\n key: string;\n artifactName: string;\n artifactType: AggregateRow[\"artifactType\"];\n evalName?: string;\n artifacts: Set<string>;\n graders: Set<string>;\n traces: Set<string>;\n counts: AggregateCounts;\n failingTraces: string[];\n reviewTraces: string[];\n skipReasons: Set<string>;\n}\n\nfunction accumulate(\n into: Map<string, Accumulator>,\n key: string,\n result: EvalResult,\n file: string,\n withEvalName: boolean,\n): void {\n let row = into.get(key);\n if (row === undefined) {\n row = {\n key,\n artifactName: result.artifactName,\n artifactType: result.artifactType,\n ...(withEvalName ? { evalName: result.evalName } : {}),\n artifacts: new Set(),\n graders: new Set(),\n traces: new Set(),\n counts: zero(),\n failingTraces: [],\n reviewTraces: [],\n skipReasons: new Set(),\n };\n into.set(key, row);\n }\n row.artifacts.add(result.artifact);\n row.graders.add(result.grader);\n row.traces.add(file);\n tally(row.counts, result.outcome);\n if (result.outcome === \"fail\" || result.outcome === \"error\") {\n if (!row.failingTraces.includes(file)) row.failingTraces.push(file);\n }\n if (result.outcome === \"needs-review\" && !row.reviewTraces.includes(file)) {\n row.reviewTraces.push(file);\n }\n if (result.outcome === \"skipped\" && result.skipReason !== undefined) {\n row.skipReasons.add(result.skipReason);\n }\n}\n\nfunction finish(row: Accumulator, withGraders: boolean): AggregateRow {\n const c = row.counts;\n const total = c.pass + c.fail + c.error + c.needsReview + c.skipped;\n const graded = total - c.skipped;\n return {\n key: row.key,\n artifactName: row.artifactName,\n artifactType: row.artifactType,\n artifacts: [...row.artifacts].sort(),\n ...(row.evalName !== undefined ? { evalName: row.evalName } : {}),\n ...(withGraders ? { graders: [...row.graders].sort() } : {}),\n traces: row.traces.size,\n total,\n counts: { ...c },\n graded,\n passRate: graded > 0 ? c.pass / graded : null,\n failingTraces: [...row.failingTraces],\n reviewTraces: [...row.reviewTraces],\n skipReasons: [...row.skipReasons].sort(),\n };\n}\n\n/**\n * Identity for a row. Type and name rather than path: two projects declaring\n * the same skill are one rate, which is the whole point of running a batch.\n */\nconst artifactKey = (r: EvalResult): string =>\n `${r.artifactType}:${r.artifactName}`;\n\nexport function aggregate(\n outcomes: BatchOutcome[],\n options: { warnings?: string[]; durationMs: number },\n): BatchReportWithBudget {\n const artifactRows = new Map<string, Accumulator>();\n const evalRows = new Map<string, Accumulator>();\n const traces: BatchTraceEntry[] = [];\n\n // An exhausted budget is a property of the run, not of any one trace, so it\n // is counted here rather than inside a row.\n let budgetSkips = 0;\n const budgetTraces = new Set<string>();\n let budgetReason = \"\";\n\n const summary: BatchSummary = {\n total: 0,\n pass: 0,\n fail: 0,\n error: 0,\n needsReview: 0,\n skipped: 0,\n passRate: 1,\n traces: outcomes.length,\n tracesPassed: 0,\n tracesFailed: 0,\n tracesErrored: 0,\n };\n let turns = 0;\n // Weighted over every trace's evals, not an average of the per-trace rates.\n // Averaging would give a 2-eval trace the same say as a 40-eval one, which\n // is the opposite of what a batch is for.\n let gradedWeight = 0;\n let passedWeight = 0;\n\n for (const outcome of outcomes) {\n if (\"error\" in outcome) {\n // A trace that never parsed has no summary to report and no evals to\n // aggregate — but it is still a trace that did not pass, so it counts\n // against the batch and against the exit code.\n traces.push({\n file: outcome.file,\n error: outcome.error,\n warnings: [],\n exitCode: 1,\n turns: 0,\n durationMs: outcome.durationMs,\n });\n summary.tracesErrored += 1;\n continue;\n }\n\n const { report } = outcome;\n traces.push({\n file: outcome.file,\n ...(report.trace.sessionId !== undefined\n ? { sessionId: report.trace.sessionId }\n : {}),\n summary: report.summary,\n warnings: report.warnings,\n exitCode: report.exitCode,\n turns: report.turns,\n durationMs: report.durationMs,\n });\n if (report.exitCode === 1) summary.tracesFailed += 1;\n else summary.tracesPassed += 1;\n turns += report.turns;\n\n summary.total += report.summary.total;\n summary.pass += report.summary.pass;\n summary.fail += report.summary.fail;\n summary.error += report.summary.error;\n summary.needsReview += report.summary.needsReview;\n summary.skipped += report.summary.skipped;\n\n for (const result of report.evalResults) {\n if (\n result.outcome === \"skipped\" &&\n isTurnBudgetSkip(result.skipReason)\n ) {\n budgetSkips += 1;\n budgetTraces.add(outcome.file);\n budgetReason = result.skipReason;\n }\n if (\n result.outcome === \"pass\" ||\n result.outcome === \"fail\" ||\n result.outcome === \"error\"\n ) {\n const weight = result.weight ?? 1;\n gradedWeight += weight;\n if (result.outcome === \"pass\") passedWeight += weight;\n }\n const base = artifactKey(result);\n accumulate(artifactRows, base, result, outcome.file, false);\n accumulate(\n evalRows,\n `${base}::${result.evalName}`,\n result,\n outcome.file,\n true,\n );\n }\n }\n\n // 1 when nothing was graded, matching the single-trace rule: a batch that\n // graded nothing has not failed anything.\n summary.passRate = gradedWeight === 0 ? 1 : passedWeight / gradedWeight;\n\n const budget: BatchBudget | undefined =\n budgetSkips > 0\n ? {\n skippedEvals: budgetSkips,\n traces: budgetTraces.size,\n reason: budgetReason,\n }\n : undefined;\n\n const warnings = [...(options.warnings ?? [])];\n if (budget !== undefined) {\n warnings.push(\n `${budget.reason}: ${budget.skippedEvals} eval(s) across ${budget.traces} of ` +\n `${outcomes.length} trace(s) were never judged — raise judge.maxTurns or narrow the corpus`,\n );\n }\n\n return {\n traces,\n artifacts: [...artifactRows.values()]\n .map((r) => finish(r, false))\n .sort(byKey),\n evals: [...evalRows.values()].map((r) => finish(r, true)).sort(byKey),\n summary,\n warnings,\n // A batch that ran out of money mid-corpus did not measure the corpus, and\n // \"did not measure\" must never render as \"measured clean\". Exit 1 rather\n // than 2: unlike an empty selector, the report is real and worth keeping —\n // the traces that were judged carry genuine verdicts, and throwing them\n // away to raise an operational error would cost more than it says.\n exitCode:\n summary.tracesFailed > 0 ||\n summary.tracesErrored > 0 ||\n budget !== undefined\n ? 1\n : 0,\n ...(budget !== undefined ? { budget } : {}),\n turns,\n durationMs: options.durationMs,\n };\n}\n","/**\n * `--newer-than <duration>`: a window of time back from now, shared by every\n * domain that selects its inputs by age.\n *\n * Deliberately strict. A duration this refuses is a usage error, because the\n * alternative (reading `7y` as zero, or as \"everything\") silently changes what\n * a gate looked at.\n */\n\nconst UNITS: Readonly<Record<string, number>> = {\n m: 60_000,\n h: 60 * 60_000,\n d: 24 * 60 * 60_000,\n w: 7 * 24 * 60 * 60_000,\n};\n\n/** The usage error for a value that is not a duration. */\nexport function durationMessage(value: string): string {\n return `--newer-than must be a duration such as 30m, 24h, 7d or 2w, got \"${value}\"`;\n}\n\n/**\n * `7d` to milliseconds. A count, which may carry a fraction, then one unit:\n * `m` minutes, `h` hours, `d` days or `w` weeks. `makeError` builds the\n * domain's own `ToolError` subclass, so the refusal exits 2 under its name.\n */\nexport function parseDuration(\n text: string,\n makeError: (message: string) => Error,\n): number {\n const match = /^(\\d+(?:\\.\\d+)?)([mhdw])$/.exec(text.trim());\n const count = match?.[1];\n const unit = match?.[2];\n const ms = unit === undefined ? undefined : UNITS[unit];\n if (count === undefined || ms === undefined) {\n throw makeError(durationMessage(text));\n }\n return Number(count) * ms;\n}\n","/**\n * Aggregate rendering for a batch run (ADR 01018).\n *\n * A batch answers a different question from a single run — \"how often does this\n * hold?\" rather than \"did it hold?\" — so the lead is the rate table, not the\n * eval list. The outlier traces are named inline: a rate with no way back to\n * the session that produced it is a number nobody can act on.\n */\nimport { palette } from \"../../shared/color.js\";\nimport type { ColorOptions } from \"./pretty.js\";\nimport type { BatchReportWithBudget } from \"../aggregate.js\";\nimport type { AggregateRow } from \"../types.js\";\n\n/**\n * `BatchReportWithBudget` rather than `BatchReport`: `budget` is optional, so\n * a plain report is still accepted, and a report that carries one is rendered\n * rather than silently dropped.\n */\ntype Report = BatchReportWithBudget;\n\n/**\n * One line, and never a quiet one. An exhausted budget means the rates below\n * it were computed over a corpus the tool stopped looking at, so it belongs\n * beside the headline — the warnings block at the foot carries the same fact,\n * but a reader scanning the rates would never reach it.\n */\nfunction budgetLine(report: Report): string | undefined {\n const b = report.budget;\n if (b === undefined) return undefined;\n return `${b.skippedEvals} eval(s) across ${b.traces} trace(s) were never judged — ${b.reason}`;\n}\n\n/** Escapes a value for a markdown table cell; see the note in markdown.ts. */\nconst cell = (value: string): string => value.replace(/\\|/g, \"\\\\|\");\n\n/** `null` means nothing was graded — say so rather than printing `0%`. */\nfunction rate(row: AggregateRow): string {\n return row.passRate === null\n ? \"—\"\n : `${Math.round(row.passRate * 1000) / 10}%`;\n}\n\nfunction detail(row: AggregateRow): string {\n const parts: string[] = [];\n const c = row.counts;\n parts.push(\n `${c.pass} pass, ${c.fail} fail, ${c.error} error, ${c.needsReview} review, ${c.skipped} skip`,\n );\n return parts.join(\" · \");\n}\n\n/** Keep a long outlier list readable without hiding that it was truncated. */\nfunction names(files: string[], limit = 3): string {\n const shown = files.slice(0, limit).map((f) => basename(f));\n return files.length > limit\n ? `${shown.join(\", \")} +${files.length - limit} more`\n : shown.join(\", \");\n}\n\n/** Last path segment, separator-agnostic so Windows and POSIX agree. */\nfunction basename(file: string): string {\n const parts = file.split(/[\\\\/]/);\n return parts[parts.length - 1] ?? file;\n}\n\n/**\n * The traces that make a row less than 100%, labelled by which kind they are.\n * A rate with no route back to the session that produced it is a number nobody\n * can act on — and a review-only row would otherwise read as an unexplained 0%.\n */\nfunction outliers(row: AggregateRow): string {\n const parts: string[] = [];\n if (row.failingTraces.length > 0) {\n parts.push(`fail: ${names(row.failingTraces)}`);\n }\n if (row.reviewTraces.length > 0) {\n parts.push(`review: ${names(row.reviewTraces)}`);\n }\n return parts.join(\"; \");\n}\n\nexport function renderBatchPretty(report: Report, opts: ColorOptions = {}): string {\n const pc = palette(opts.color === true);\n const lines: string[] = [];\n const s = report.summary;\n lines.push(pc.bold(`manni tracevals — ${s.traces} trace(s)`));\n lines.push(\n pc.dim(\n `${s.tracesPassed} passed · ${s.tracesFailed} failed · ${s.tracesErrored} unreadable`,\n ),\n );\n const cutShort = budgetLine(report);\n if (cutShort !== undefined) {\n lines.push(pc.red(`${pc.bold(\"BUDGET EXHAUSTED\")} ${cutShort}`));\n }\n lines.push(\"\");\n\n lines.push(pc.bold(\"Eval pass rates\"));\n if (report.evals.length === 0) {\n lines.push(pc.dim(\" no evals were planned for any trace\"));\n }\n for (const row of report.evals) {\n const label =\n row.passRate === null\n ? pc.dim(rate(row).padStart(6))\n : row.passRate === 1\n ? pc.green(rate(row).padStart(6))\n : pc.red(rate(row).padStart(6));\n lines.push(\n ` ${label} ${row.artifactName} › ${row.evalName ?? \"\"} ${pc.dim(`(${row.traces} trace(s))`)}`,\n );\n lines.push(` ${pc.dim(detail(row))}`);\n if (row.failingTraces.length > 0) {\n lines.push(` ${pc.red(`failing: ${names(row.failingTraces)}`)}`);\n }\n if (row.reviewTraces.length > 0) {\n lines.push(\n ` ${pc.yellow(`review: ${names(row.reviewTraces)}`)}`,\n );\n }\n for (const reason of row.skipReasons) {\n lines.push(` ${pc.dim(`skipped: ${reason}`)}`);\n }\n }\n\n lines.push(\"\");\n lines.push(pc.bold(\"Artifact pass rates\"));\n for (const row of report.artifacts) {\n lines.push(\n ` ${rate(row).padStart(6)} ${row.artifactType}: ${row.artifactName} ${pc.dim(detail(row))}`,\n );\n }\n\n lines.push(\"\");\n lines.push(pc.bold(\"Traces\"));\n for (const t of report.traces) {\n if (t.error !== undefined) {\n lines.push(` ${pc.red(\"ERROR \")} ${basename(t.file)}`);\n lines.push(` ${pc.red(t.error)}`);\n continue;\n }\n const mark = t.exitCode === 0 ? pc.green(\"PASS \") : pc.red(\"FAIL \");\n const ts = t.summary;\n lines.push(\n ` ${mark} ${basename(t.file)} ${pc.dim(\n `${ts?.pass ?? 0} pass, ${ts?.fail ?? 0} fail, ${ts?.error ?? 0} error, ${ts?.needsReview ?? 0} review, ${ts?.skipped ?? 0} skip`,\n )}`,\n );\n }\n\n if (report.warnings.length > 0) {\n lines.push(\"\");\n lines.push(pc.bold(\"Warnings\"));\n for (const warning of report.warnings) {\n lines.push(` ${pc.yellow(\"!\")} ${warning}`);\n }\n }\n\n lines.push(\"\");\n lines.push(\n pc.bold(\n `${s.total} eval(s) across ${s.traces} trace(s): ${pc.green(`${s.pass} pass`)}, ${\n s.fail > 0 ? pc.red(`${s.fail} fail`) : `${s.fail} fail`\n }, ${s.error} error, ${s.needsReview} needs-review, ${s.skipped} skipped`,\n ),\n );\n if (report.turns > 0) {\n lines.push(pc.dim(`judge turns ${report.turns}`));\n }\n return lines.join(\"\\n\");\n}\n\nexport function renderBatchMarkdown(report: Report): string {\n const lines: string[] = [];\n const s = report.summary;\n lines.push(`# manni tracevals batch report`);\n lines.push(\"\");\n lines.push(`- **Traces**: ${s.traces}`);\n lines.push(\n `- **Outcome**: ${s.tracesPassed} passed, ${s.tracesFailed} failed, ${s.tracesErrored} unreadable`,\n );\n const cutShort = budgetLine(report);\n if (cutShort !== undefined) lines.push(`- **Budget**: ${cutShort}`);\n lines.push(\"\");\n\n lines.push(`## Eval pass rates`);\n lines.push(\"\");\n lines.push(`| Rate | Artifact | Eval | Grader | Traces | Outcomes | Outliers |`);\n lines.push(`|---|---|---|---|---|---|---|`);\n for (const row of report.evals) {\n lines.push(\n `| ${rate(row)} | ${cell(row.artifactName)} | ${cell(row.evalName ?? \"\")} | ${cell(\n (row.graders ?? []).join(\", \"),\n )} | ${row.traces} | ${cell(detail(row))} | ${cell(outliers(row))} |`,\n );\n }\n lines.push(\"\");\n\n lines.push(`## Artifact pass rates`);\n lines.push(\"\");\n lines.push(`| Rate | Kind | Artifact | Traces | Outcomes |`);\n lines.push(`|---|---|---|---|---|`);\n for (const row of report.artifacts) {\n lines.push(\n `| ${rate(row)} | ${cell(row.artifactType)} | ${cell(row.artifactName)} | ${row.traces} | ${cell(detail(row))} |`,\n );\n }\n lines.push(\"\");\n\n lines.push(`## Traces`);\n lines.push(\"\");\n lines.push(`| Result | Trace | Evals | Detail |`);\n lines.push(`|---|---|---|---|`);\n for (const t of report.traces) {\n const result = t.error !== undefined ? \"error\" : t.exitCode === 0 ? \"pass\" : \"fail\";\n const evals =\n t.summary === undefined\n ? \"\"\n : `${t.summary.pass}/${t.summary.total} pass`;\n lines.push(\n `| ${result} | \\`${cell(t.file)}\\` | ${evals} | ${cell(t.error ?? \"\")} |`,\n );\n }\n lines.push(\"\");\n\n if (report.warnings.length > 0) {\n lines.push(`## Warnings`);\n lines.push(\"\");\n for (const warning of report.warnings) lines.push(`- ${warning}`);\n lines.push(\"\");\n }\n\n lines.push(\n `**${s.total} eval(s)** across ${s.traces} trace(s) — ${s.pass} pass, ${s.fail} fail, ${s.error} error, ${s.needsReview} needs-review, ${s.skipped} skipped.`,\n );\n return lines.join(\"\\n\");\n}\n","/**\n * Calibration rendering (ADR 01022).\n *\n * A calibration report answers \"was it right?\", so the lead is the two kinds\n * of mistake and the volume of deferrals — not a pass rate. Every count is\n * followed by the rows behind it, because \"one false pass\" with no way to see\n * which eval is a number nobody can act on.\n */\nimport { isAbsolute, relative } from \"node:path\";\nimport { palette } from \"../../shared/color.js\";\nimport type { ColorOptions } from \"./pretty.js\";\nimport type {\n CalibrationCounts,\n CalibrationReport,\n Disagreement,\n SweepCell,\n} from \"../calibrate/types.js\";\n\n/** Escapes a value for a markdown table cell; see the note in markdown.ts. */\nconst cell = (value: string): string => value.replace(/\\|/g, \"\\\\|\");\n\n/** Last path segment, separator-agnostic so Windows and POSIX agree. */\nfunction basename(file: string): string {\n const parts = file.split(/[\\\\/]/);\n return parts[parts.length - 1] ?? file;\n}\n\n/**\n * Absolute paths are what the report *carries*; they are not what a reader\n * wants to see, and they differ per machine — which would make a captured\n * sample in the docs unreproducible on the next runner.\n */\nfunction display(file: string): string {\n const rel = relative(process.cwd(), file);\n return rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel) ? file : rel;\n}\n\nconst pct = (value: number | null): string =>\n value === null ? \"—\" : `${Math.round(value * 1000) / 10}%`;\n\nconst settingOf = (c: SweepCell): string =>\n `runs=${c.setting.ensembleRuns} autoPass=${c.setting.zones.autoPass} autoFail=${c.setting.zones.autoFail}`;\n\n/**\n * The sweep table, header and rows built from one spec so they cannot drift.\n *\n * `scored` leads and `insuff` trails for the same reason: a count with no\n * denominator is unreadable, and a cell scored from fewer cached runs than its\n * setting asks for is a number that was quietly not measured. Without the two\n * of them a reader tuning thresholds cannot tell \"zero false passes\" from\n * \"nothing was scored\".\n */\nconst SWEEP_COLUMNS: {\n label: string;\n width: number;\n of: (c: CalibrationCounts) => number;\n}[] = [\n { label: \"scored\", width: 6, of: (c) => c.scored },\n { label: \"agree\", width: 5, of: (c) => c.agree },\n { label: \"false-pass\", width: 10, of: (c) => c.falsePass },\n { label: \"false-fail\", width: 10, of: (c) => c.falseFail },\n { label: \"review\", width: 6, of: (c) => c.review },\n { label: \"reviewVol\", width: 9, of: (c) => c.reviewVolume },\n { label: \"insuff\", width: 6, of: (c) => c.insufficient },\n];\n\nconst sweepRow = (axis: string, setting: string, cells: string[]): string =>\n ` ${axis.padEnd(20)} ${setting.padEnd(38)} ${cells.join(\" \")}`;\n\n/** The evidence behind a judged verdict, or nothing for a graded one. */\nfunction evidence(d: Disagreement): string {\n if (d.consensus === undefined) return \"\";\n const v = d.consensus.votes;\n return `${v.pass}p/${v.fail}f/${v.partial}?/${v.error}e over ${d.consensus.runs} run(s), confidence ${d.consensus.meanConfidence.toFixed(2)}`;\n}\n\nconst KIND_LABEL: Record<Disagreement[\"kind\"], string> = {\n agree: \"AGREE\",\n \"false-pass\": \"FALSE-PASS\",\n \"false-fail\": \"FALSE-FAIL\",\n review: \"REVIEW\",\n \"missed-review\": \"MISSED-REVIEW\",\n error: \"ERROR\",\n skipped: \"SKIPPED\",\n};\n\nexport function renderCalibrationPretty(\n report: CalibrationReport,\n opts: ColorOptions = {},\n): string {\n const pc = palette(opts.color === true);\n const lines: string[] = [];\n const c = report.counts;\n lines.push(\n pc.bold(\n `manni tracevals calibrate — ${report.corpus.length} trace(s), ${c.labels} label(s)`,\n ),\n );\n lines.push(\n pc.dim(\n `runs ${report.setting.ensembleRuns} · autoPass ${report.setting.zones.autoPass} · autoFail ${report.setting.zones.autoFail} · labels ${display(report.labelsFile)}`,\n ),\n );\n lines.push(\"\");\n\n lines.push(\n pc.bold(\n `Agreement ${c.agree}/${c.scored} (${pct(c.agreement)})`,\n ),\n );\n const headline = (\n count: number,\n label: string,\n gloss: string,\n colour: (s: string) => string,\n ): void => {\n const text = ` ${String(count).padStart(4)} ${label.padEnd(14)} ${pc.dim(gloss)}`;\n lines.push(count > 0 ? colour(text) : pc.dim(text));\n };\n headline(c.falsePass, \"false passes\", \"labelled fail, judged pass — the expensive error\", pc.red);\n headline(c.falseFail, \"false fails\", \"labelled pass, judged fail — erodes trust fastest\", pc.red);\n headline(c.reviewVolume, \"needs-review\", \"across the whole corpus — the review volume\", pc.yellow);\n headline(c.review, \"deferred\", \"labelled pass or fail, routed to a human instead\", pc.yellow);\n headline(c.missedReview, \"missed reviews\", \"labelled ambiguous, decided anyway\", pc.yellow);\n headline(c.errored, \"errors\", \"the eval could not be graded at all\", pc.red);\n headline(c.skipped, \"unscored\", \"labelled, but the eval never armed\", (s) => s);\n\n if (report.disagreements.length > 0) {\n lines.push(\"\");\n lines.push(pc.bold(\"Disagreements\"));\n for (const d of report.disagreements) {\n const tag = KIND_LABEL[d.kind];\n const colour =\n d.kind === \"false-pass\" || d.kind === \"false-fail\" || d.kind === \"error\"\n ? pc.red\n : pc.yellow;\n lines.push(\n ` ${colour(tag.padEnd(14))} ${basename(d.trace)} ${d.artifactName} › ${d.evalName} ${pc.dim(`(${d.grader})`)}`,\n );\n lines.push(\n ` ${pc.dim(`expected ${d.expected}, got ${d.actual}`)}${\n evidence(d) === \"\" ? \"\" : pc.dim(` · ${evidence(d)}`)\n }`,\n );\n if (d.note !== undefined) {\n lines.push(` ${pc.dim(`note: ${d.note}`)}`);\n }\n }\n }\n\n if (report.unscored.length > 0) {\n lines.push(\"\");\n lines.push(pc.bold(\"Unscored (no evidence either way)\"));\n for (const d of report.unscored) {\n lines.push(\n ` ${pc.dim(\"SKIPPED\".padEnd(14))} ${basename(d.trace)} ${d.artifactName} › ${d.evalName}`,\n );\n if (d.skipReason !== undefined) {\n lines.push(` ${pc.dim(d.skipReason)}`);\n }\n }\n }\n\n if (report.sweep !== undefined) {\n lines.push(\"\");\n lines.push(pc.bold(\"Sweep\"));\n lines.push(\n pc.dim(\n \" re-scored from the verdicts this run already produced — no further model calls\",\n ),\n );\n lines.push(\n pc.dim(\n sweepRow(\n \"axis\",\n \"setting\",\n SWEEP_COLUMNS.map((c) => c.label.padStart(c.width)),\n ),\n ),\n );\n for (const s of report.sweep) {\n lines.push(\n sweepRow(\n s.axis,\n settingOf(s),\n SWEEP_COLUMNS.map((c) => String(c.of(s.counts)).padStart(c.width)),\n ),\n );\n }\n }\n\n if (report.gates.length > 0) {\n lines.push(\"\");\n lines.push(pc.bold(\"Thresholds\"));\n for (const g of report.gates) {\n const text = ` ${g.name}: ${g.actual} of at most ${g.limit}`;\n lines.push(g.exceeded ? pc.red(`${text} — exceeded`) : pc.green(text));\n }\n }\n\n if (report.warnings.length > 0) {\n lines.push(\"\");\n lines.push(pc.bold(\"Warnings\"));\n for (const w of report.warnings) lines.push(` ${pc.yellow(\"!\")} ${w}`);\n }\n\n lines.push(\"\");\n lines.push(pc.dim(verdictLine(report)));\n if (report.turns > 0) {\n lines.push(pc.dim(`judge turns ${report.turns}`));\n }\n return lines.join(\"\\n\");\n}\n\nfunction countsRow(counts: CalibrationCounts): string {\n return `${counts.scored} | ${counts.agree} | ${counts.falsePass} | ${counts.falseFail} | ${counts.review} | ${counts.missedReview} | ${counts.reviewVolume} | ${counts.insufficient}`;\n}\n\n/**\n * The one sentence that says what the exit code means.\n *\n * A run that scored nothing gets its own wording rather than the generic\n * \"a threshold was exceeded\": the thresholds did *not* trip, and sending a\n * reader to look at one would send them to the wrong place.\n */\nfunction verdictLine(report: CalibrationReport): string {\n if (report.counts.scored === 0) {\n return (\n \"Exit 1: nothing was scored — every label joined to a skipped result, \" +\n \"so agreement and every threshold above rest on an empty denominator.\"\n );\n }\n return report.exitCode === 0\n ? \"Measured cleanly. Disagreement is the finding, not a failure — exit 0.\"\n : \"Exit 1: a threshold was exceeded, or the measurement is incomplete — a trace could not be evaluated, or the judge budget cut the corpus short.\";\n}\n\nexport function renderCalibrationMarkdown(report: CalibrationReport): string {\n const lines: string[] = [];\n const c = report.counts;\n lines.push(\"# manni tracevals calibration report\");\n lines.push(\"\");\n lines.push(`- **Corpus**: ${report.corpus.length} trace(s), ${c.labels} label(s)`);\n lines.push(\n `- **Setting**: \\`ensembleRuns\\` ${report.setting.ensembleRuns}, \\`zones.autoPass\\` ${report.setting.zones.autoPass}, \\`zones.autoFail\\` ${report.setting.zones.autoFail}`,\n );\n lines.push(`- **Agreement**: ${c.agree}/${c.scored} (${pct(c.agreement)})`);\n lines.push(`- **Labels**: \\`${cell(display(report.labelsFile))}\\``);\n lines.push(\"\");\n\n lines.push(\"| Measure | Count | What it means |\");\n lines.push(\"|---|---|---|\");\n lines.push(`| False passes | ${c.falsePass} | Labelled fail, judged pass — the expensive error. |`);\n lines.push(`| False fails | ${c.falseFail} | Labelled pass, judged fail — erodes trust fastest. |`);\n lines.push(`| Review volume | ${c.reviewVolume} | \\`needs-review\\` across the whole corpus. |`);\n lines.push(`| Deferred labels | ${c.review} | Labelled pass or fail, routed to a human instead. |`);\n lines.push(`| Missed reviews | ${c.missedReview} | Labelled ambiguous, decided anyway. |`);\n lines.push(`| Errors | ${c.errored} | The eval could not be graded at all. |`);\n lines.push(`| Unscored | ${c.skipped} | Labelled, but the eval never armed. |`);\n lines.push(\"\");\n\n lines.push(\"## Disagreements\");\n lines.push(\"\");\n if (report.disagreements.length === 0) {\n lines.push(\"None — every scored label agreed.\");\n } else {\n lines.push(\"| Kind | Trace | Artifact | Eval | Grader | Expected | Got | Evidence | Note |\");\n lines.push(\"|---|---|---|---|---|---|---|---|---|\");\n for (const d of report.disagreements) {\n lines.push(\n `| ${KIND_LABEL[d.kind]} | \\`${cell(basename(d.trace))}\\` | ${cell(d.artifactName)} | ${cell(\n d.evalName,\n )} | ${cell(d.grader)} | ${d.expected} | ${d.actual} | ${cell(evidence(d))} | ${cell(d.note ?? \"\")} |`,\n );\n }\n }\n lines.push(\"\");\n\n if (report.unscored.length > 0) {\n lines.push(\"## Unscored\");\n lines.push(\"\");\n lines.push(\"| Trace | Artifact | Eval | Reason |\");\n lines.push(\"|---|---|---|---|\");\n for (const d of report.unscored) {\n lines.push(\n `| \\`${cell(basename(d.trace))}\\` | ${cell(d.artifactName)} | ${cell(d.evalName)} | ${cell(\n d.skipReason ?? \"\",\n )} |`,\n );\n }\n lines.push(\"\");\n }\n\n if (report.sweep !== undefined) {\n lines.push(\"## Sweep\");\n lines.push(\"\");\n lines.push(\n \"Re-scored from the verdicts this run already produced — no further model calls.\",\n );\n lines.push(\"\");\n lines.push(\n \"| Axis | Setting | Scored | Agree | False passes | False fails | Deferred | Missed reviews | Review volume | Insufficient |\",\n );\n lines.push(\"|---|---|---|---|---|---|---|---|---|---|\");\n for (const s of report.sweep) {\n lines.push(`| ${s.axis} | ${cell(settingOf(s))} | ${countsRow(s.counts)} |`);\n }\n lines.push(\"\");\n }\n\n if (report.gates.length > 0) {\n lines.push(\"## Thresholds\");\n lines.push(\"\");\n lines.push(\"| Threshold | Limit | Actual | Result |\");\n lines.push(\"|---|---|---|---|\");\n for (const g of report.gates) {\n lines.push(\n `| ${g.name} | ${g.limit} | ${g.actual} | ${g.exceeded ? \"exceeded\" : \"ok\"} |`,\n );\n }\n lines.push(\"\");\n }\n\n if (report.warnings.length > 0) {\n lines.push(\"## Warnings\");\n lines.push(\"\");\n for (const w of report.warnings) lines.push(`- ${w}`);\n lines.push(\"\");\n }\n\n lines.push(\n report.exitCode === 0 ? verdictLine(report) : `**${verdictLine(report)}**`,\n );\n return lines.join(\"\\n\");\n}\n","/**\n * SARIF artifact locations, shared by every tool that writes SARIF over paths\n * it did not choose.\n *\n * Moved here from lint's reporter when tracevals needed the same mapping: a\n * tracevals finding points at the skill or instruction file that declared the\n * eval, which is often outside the checkout (`~/.claude/skills/...`), so the\n * absolute-path branch below is its ordinary case rather than an edge one.\n */\n\n/** The base every relative artifact URI resolves against. */\nexport const URI_BASE_ID = \"SRCROOT\";\n\nexport interface ArtifactLocation {\n uri: string;\n uriBaseId?: string;\n}\n\n/** Matches a Windows drive prefix on an already-forward-slashed path. */\nconst DRIVE = /^[A-Za-z]:\\//;\n\nexport function toPosix(p: string): string {\n return p.replace(/\\\\/g, \"/\");\n}\n\n/**\n * Path handling here is string-level rather than `node:path`, deliberately.\n *\n * `node:path` is platform-bound: on Linux, `isAbsolute(\"C:\\\\repo\\\\a.md\")` is\n * false and `relative()` treats the whole thing as one filename. That would\n * make this reporter's most important behaviour differ between the two CI\n * runners, and differ in the direction that fails silently - a Windows path\n * emitted verbatim as a URI resolves to no file in the repository. Doing the\n * work on strings makes the mapping identical everywhere.\n */\nfunction isAbsolutePath(posix: string): boolean {\n return posix.startsWith(\"/\") || DRIVE.test(posix);\n}\n\n/**\n * A path Windows resolves, and therefore compares without regard to case:\n * either a drive path or a UNC share. `//` is how `fileUri` recognises a share\n * too, so both places agree on what one looks like.\n */\nfunction isWindowsPath(posix: string): boolean {\n return DRIVE.test(posix) || posix.startsWith(\"//\");\n}\n\n/** `/repo/` + `/repo/docs/a.md` -> `docs/a.md`; null when not underneath. */\nexport function underRoot(posix: string, root: string): string | null {\n if (posix.startsWith(root)) return posix.slice(root.length);\n // Windows paths are case-insensitive: `C:/Repo` and `c:/repo` are one\n // directory, and so are `//server/Share` and `//SERVER/share` - a checkout on\n // a network share must relativize as readily as one on a drive, or its\n // findings upload as absolute URIs and attach to nothing. Retry this way only\n // when both sides are Windows-shaped - anywhere else, two paths differing in\n // case are two different files.\n if (isWindowsPath(posix) && isWindowsPath(root)) {\n // The comparison case-folds but the slice does not, which reads like a bug\n // and is not: case folding leaves length unchanged, so `root.length` still\n // indexes the same boundary, and slicing the original is what keeps the\n // reported path in the casing the author actually used.\n if (posix.toLowerCase().startsWith(root.toLowerCase())) {\n return posix.slice(root.length);\n }\n }\n return null;\n}\n\n/**\n * Percent-encode what a URI cannot carry raw. `encodeURI` leaves `/` and `:`\n * alone, which is what a path needs, but it also leaves `#` and `?` alone, and\n * either of those would be read as a fragment or a query rather than as part\n * of the name.\n *\n * This also covers labels that are not paths at all: the stdin document is\n * `<stdin>`, and `<`/`>` are not legal in a URI. It will not resolve to a file\n * anywhere, but an invalid URI can sink an entire upload, whereas a valid one\n * that resolves to nothing only sinks its own annotation.\n */\nfunction encodePath(p: string): string {\n return encodeURI(p).replace(/#/g, \"%23\").replace(/\\?/g, \"%3F\");\n}\n\n/** An absolute forward-slashed path as a `file:` URI. */\nexport function fileUri(posix: string): string {\n const encoded = encodePath(posix);\n if (posix.startsWith(\"//\")) return `file:${encoded}`; // UNC: file://host/share\n if (posix.startsWith(\"/\")) return `file://${encoded}`; // POSIX: file:///etc\n return `file:///${encoded}`; // Drive: file:///C:/repo\n}\n\n/** A relative path that climbs out of the directory it is relative to. */\nfunction escapesRoot(posix: string): boolean {\n return posix === \"..\" || posix.startsWith(\"../\");\n}\n\n/**\n * `C:/repo/` + `../sibling/a.md` -> `C:/sibling/a.md`.\n *\n * String-level, like everything else here, and one step per `..` rather than a\n * single strip: `../a.md` and `../../a.md` name two different files, and a\n * reporter that collapsed them would point an alert at the wrong one. The first\n * segment is never popped - it is the drive, the empty segment before a posix\n * root, or the first half of a UNC share - so a path cannot climb past the\n * filesystem root.\n */\nfunction resolveFromRoot(root: string, rel: string): string {\n const parts = root.replace(/\\/+$/, \"\").split(\"/\");\n for (const segment of rel.split(\"/\")) {\n if (segment === \"\" || segment === \".\") continue;\n if (segment === \"..\") {\n if (parts.length > 1) parts.pop();\n continue;\n }\n parts.push(segment);\n }\n const joined = parts.join(\"/\");\n return joined === \"\" ? \"/\" : joined;\n}\n\n/**\n * Forward-slashed with exactly one trailing slash, so a prefix match on it can\n * only ever land on a segment boundary.\n */\nexport function normalizeRoot(root: string): string {\n const posix = toPosix(root);\n return posix.endsWith(\"/\") ? posix : `${posix}/`;\n}\n\n/**\n * The artifact URI, which is the single most breakable thing in this file.\n *\n * SARIF URIs are URI references, not native paths. Relative plus `uriBaseId`\n * is what GitHub resolves against the checkout, so that is the default; a\n * backslashed path, or a bare absolute one, uploads fine and matches no file.\n *\n * A target outside the run root arrives as a **relative** path too - a `../`\n * chain, which is how `resolveTargets` reports it - and that is the one shape\n * a `uriBaseId` cannot carry. `SRCROOT` is the checkout, and code scanning\n * will not resolve above it: `../sibling/docs/a.md` uploads and annotates\n * nothing, which is this format's whole failure mode. So it is resolved\n * against the root and emitted the way the genuinely-absolute case below is,\n * with no base to resolve against.\n */\nexport function artifactLocation(file: string, root: string): ArtifactLocation {\n const posix = toPosix(file);\n if (!isAbsolutePath(posix)) {\n if (escapesRoot(posix)) return { uri: fileUri(resolveFromRoot(root, posix)) };\n return { uri: encodePath(posix), uriBaseId: URI_BASE_ID };\n }\n const rel = underRoot(posix, root);\n if (rel !== null) return { uri: encodePath(rel), uriBaseId: URI_BASE_ID };\n // Genuinely outside the run root. No relative URI reaches it, so say so with\n // an absolute `file:` URI rather than inventing a `../` chain that resolves\n // to nothing on the machine reading the report.\n return { uri: fileUri(posix) };\n}\n","/**\n * What the CI formats (`github`, `sarif`, `junit`) render from.\n *\n * A single trace and a batch reach them as the same shape: the per-trace\n * reports, plus the traces that could not be evaluated at all and the\n * warnings that belong to no one trace. A CI reporter is about findings and\n * where they live, so it reads the per-trace results rather than the batch's\n * aggregate rates, which carry no message to annotate with.\n */\nimport type { BatchReport, EvalResult, RunReport } from \"../types.js\";\nimport { classifyRef } from \"../../meta/index.js\";\nimport { normalizeRoot, toPosix, underRoot } from \"../../shared/sarif-location.js\";\n\nexport interface CiOptions {\n /**\n * The directory locations are made relative to. Defaults to the working\n * directory, which is where a CI job runs from.\n */\n root?: string;\n}\n\nexport interface CiInput {\n runs: readonly RunReport[];\n /** Traces a batch could not evaluate at all, by file. */\n traceErrors: readonly { file: string; error: string; durationMs: number }[];\n /** Warnings that belong to the batch rather than to one trace. */\n warnings: readonly string[];\n /** Forward-slashed, with one trailing slash. */\n root: string;\n}\n\nexport function ciInputFromRun(report: RunReport, opts: CiOptions = {}): CiInput {\n return {\n runs: [report],\n traceErrors: [],\n warnings: [],\n root: normalizeRoot(opts.root ?? process.cwd()),\n };\n}\n\nexport function ciInputFromBatch(\n batch: BatchReport,\n runs: readonly RunReport[],\n opts: CiOptions = {},\n): CiInput {\n const traceErrors: { file: string; error: string; durationMs: number }[] = [];\n for (const t of batch.traces) {\n if (t.error !== undefined) {\n traceErrors.push({ file: t.file, error: t.error, durationMs: t.durationMs });\n }\n }\n return {\n runs,\n traceErrors,\n warnings: batch.warnings,\n root: normalizeRoot(opts.root ?? process.cwd()),\n };\n}\n\n/**\n * A path as a reader in the checkout names it: relative and forward-slashed\n * under the root, absolute and forward-slashed outside it.\n */\nexport function displayPath(file: string, root: string): string {\n const posix = toPosix(file);\n return underRoot(posix, root) ?? posix;\n}\n\n/** A forward-slashed drive or POSIX path, as opposed to a relative one. */\nconst ABSOLUTE = /^(?:[A-Za-z]:)?\\//;\n\n/**\n * The file that declares an eval, as a reader in the checkout names it. A\n * result spells it relative to the working directory, so it is anchored there\n * before it is made relative to the root. A hosted manifest keeps its URL.\n */\nexport function locationPath(location: EvalResult[\"location\"], root: string): string {\n if (classifyRef(location.file).kind === \"url\") return location.file;\n const posix = toPosix(location.file);\n const abs = ABSOLUTE.test(posix) ? posix : `${normalizeRoot(process.cwd())}${posix}`;\n return underRoot(abs, root) ?? abs;\n}\n\n/** `<file>:<line>`, or the file alone when no line declares the eval. */\nexport function locationLabel(location: EvalResult[\"location\"]): string {\n return location.line === undefined\n ? location.file\n : `${location.file}:${String(location.line)}`;\n}\n\n/** `tracevals/<grader>`: the rule a result is filed under. */\nexport function ruleIdFor(grader: string): string {\n return `tracevals/${grader}`;\n}\n\n/** The rule an unreadable trace is filed under. It names no grader. */\nexport const TRACE_RULE_ID = \"tracevals/trace\";\n\n/** The message for a trace a batch could not evaluate. */\nexport function traceErrorText(error: string): string {\n return `trace could not be evaluated: ${error}`;\n}\n\n/** A judged failure, in the words docevals' reporters use. */\nexport function judgeFailText(result: EvalResult): string | undefined {\n if (result.outcome !== \"fail\" || !result.consensus) return undefined;\n const reasoning =\n result.consensus.runs.find((run) => run.verdict)?.verdict?.reasoning ?? \"\";\n return `AI judge: fail (confidence ${result.consensus.meanConfidence.toFixed(2)}). ${reasoning}`.trim();\n}\n\n/** Why an errored eval errored. */\nexport function errorText(result: EvalResult): string {\n return result.error ?? result.skipReason ?? \"eval errored\";\n}\n","/**\n * GitHub Actions reporter: workflow commands for inline PR annotations,\n * followed by the markdown summary (suitable for $GITHUB_STEP_SUMMARY).\n *\n * docevals' shape. An annotation lands on the entry that declares the eval,\n * in the artifact or in the manifest that supplied it, since that is what\n * someone edits to change the outcome. The trace it was graded against goes at\n * the end of the message, because a workflow command has nowhere else to\n * carry it.\n */\nimport {\n escapeWorkflowCommandMessage as escapeData,\n escapeWorkflowCommandProperty as escapeProperty,\n} from \"../../shared/github.js\";\nimport {\n displayPath,\n errorText,\n judgeFailText,\n locationPath,\n traceErrorText,\n type CiInput,\n} from \"./ci.js\";\n\nconst TITLE = \"manni tracevals\";\n\nfunction annotation(\n level: string,\n message: string,\n props: { file?: string; line?: number; title: string },\n): string {\n const parts = [\n props.file !== undefined ? `file=${escapeProperty(props.file)}` : undefined,\n props.line !== undefined ? `line=${String(props.line)}` : undefined,\n `title=${escapeProperty(props.title)}`,\n ].filter((p) => p !== undefined);\n return `::${level} ${parts.join(\",\")}::${escapeData(message)}`;\n}\n\nexport function renderGithub(input: CiInput, summary: string): string {\n const lines: string[] = [];\n for (const run of input.runs) {\n const trace = ` (trace: ${displayPath(run.trace.file, input.root)})`;\n for (const r of run.evalResults) {\n // A trace finding has no line of its own in the artifact, so every\n // annotation lands on the entry that declares the eval.\n const at = {\n file: locationPath(r.location, input.root),\n ...(r.location.line === undefined ? {} : { line: r.location.line }),\n title: `${TITLE}: ${r.evalName}`,\n };\n for (const f of r.findings ?? []) {\n // The family scale is GitHub's annotation levels, word for word.\n lines.push(annotation(f.severity, f.message + trace, at));\n }\n const judged = judgeFailText(r);\n if (judged !== undefined) {\n lines.push(annotation(\"error\", judged + trace, at));\n }\n // An errored eval has neither findings nor a verdict. Left out, it\n // shows in the log only inside the summary table, which a collapsed\n // step hides.\n if (r.outcome === \"error\") {\n lines.push(annotation(\"error\", errorText(r) + trace, at));\n }\n }\n for (const w of run.warnings) {\n // Plugin-loading warnings are prepended to every report in a batch and\n // also carried once at batch level; say them once.\n if (input.warnings.includes(w)) continue;\n lines.push(annotation(\"warning\", w + trace, { title: TITLE }));\n }\n }\n for (const t of input.traceErrors) {\n lines.push(\n annotation(\"error\", traceErrorText(t.error), {\n file: displayPath(t.file, input.root),\n title: TITLE,\n }),\n );\n }\n for (const w of input.warnings) {\n lines.push(annotation(\"warning\", w, { title: TITLE }));\n }\n lines.push(\"\", summary);\n return lines.join(\"\\n\");\n}\n","/**\n * JUnit XML reporter.\n *\n * docevals' mapping, with the trace standing where docevals' eval suite\n * stands: one `<testsuite>` per trace, one `<testcase>` per (artifact, eval)\n * pair. `classname` is the artifact and `name` is the eval, so a JUnit viewer\n * groups by the file someone edits to change the outcome. Each `<failure>` and\n * `<error>` carries its rule, `tracevals/<grader>`, as `type`.\n *\n * A trace a batch could not read at all is a suite of one errored testcase, so\n * the CI test tab counts it rather than showing a corpus one trace short.\n */\nimport { xmlEscape as esc } from \"../../shared/xml.js\";\nimport type { EvalResult, RunReport } from \"../types.js\";\nimport {\n displayPath,\n errorText,\n judgeFailText,\n locationPath,\n ruleIdFor,\n TRACE_RULE_ID,\n type CiInput,\n} from \"./ci.js\";\n\nfunction attr(name: string, value: string | number): string {\n return `${name}=\"${esc(String(value))}\"`;\n}\n\nconst seconds = (ms: number): string => (ms / 1000).toFixed(3);\n\n/** The message body for a failing eval: findings, or the judge's reasoning. */\nfunction failureText(result: EvalResult): string {\n const findings = (result.findings ?? []).map((f) => f.message);\n if (findings.length > 0) return findings.join(\"\\n\");\n return judgeFailText(result) ?? `${result.evalName} failed`;\n}\n\nfunction testcase(result: EvalResult, root: string): string {\n // `file` and `line` are the entry that declares the eval, the attributes a\n // JUnit viewer that links to source reads.\n const line = result.location.line;\n const open = ` <testcase ${attr(\"classname\", displayPath(result.artifact, root))} ${attr(\n \"name\",\n result.evalName,\n )} ${attr(\"file\", locationPath(result.location, root))}${\n line === undefined ? \"\" : ` ${attr(\"line\", line)}`\n } ${attr(\"time\", seconds(result.durationMs))}`;\n const type = attr(\"type\", ruleIdFor(result.grader));\n switch (result.outcome) {\n case \"pass\":\n return `${open} />`;\n case \"skipped\":\n return `${open}>\\n <skipped ${attr(\n \"message\",\n result.skipReason ?? \"skipped\",\n )} />\\n </testcase>`;\n case \"error\":\n return `${open}>\\n <error ${attr(\n \"message\",\n `${result.evalName} errored`,\n )} ${type}>${esc(errorText(result))}</error>\\n </testcase>`;\n case \"needs-review\":\n // Not a failure and not a pass. JUnit has no third state, and calling it\n // a failure would make a human-review queue look like a broken build.\n return `${open}>\\n <skipped ${attr(\n \"message\",\n \"needs human review\",\n )} />\\n </testcase>`;\n case \"fail\":\n return `${open}>\\n <failure ${attr(\n \"message\",\n `${result.evalName} failed`,\n )} ${type}>${esc(failureText(result))}</failure>\\n </testcase>`;\n }\n}\n\ninterface Counts {\n tests: number;\n failures: number;\n errors: number;\n skipped: number;\n}\n\nfunction counts(run: RunReport): Counts {\n const r = run.evalResults;\n return {\n tests: r.length,\n failures: r.filter((x) => x.outcome === \"fail\").length,\n errors: r.filter((x) => x.outcome === \"error\").length,\n skipped: r.filter((x) => x.outcome === \"skipped\" || x.outcome === \"needs-review\")\n .length,\n };\n}\n\nfunction suiteOpen(name: string, c: Counts, ms: number): string {\n return ` <testsuite ${attr(\"name\", name)} ${attr(\"tests\", c.tests)} ${attr(\n \"failures\",\n c.failures,\n )} ${attr(\"errors\", c.errors)} ${attr(\"skipped\", c.skipped)} ${attr(\n \"time\",\n seconds(ms),\n )}>`;\n}\n\nexport function renderJunit(input: CiInput): string {\n const total: Counts = { tests: 0, failures: 0, errors: 0, skipped: 0 };\n const suites: string[] = [];\n\n for (const run of input.runs) {\n const c = counts(run);\n total.tests += c.tests;\n total.failures += c.failures;\n total.errors += c.errors;\n suites.push(\n [\n suiteOpen(displayPath(run.trace.file, input.root), c, run.durationMs),\n ...run.evalResults.map((r) => testcase(r, input.root)),\n \" </testsuite>\",\n ].join(\"\\n\"),\n );\n }\n\n for (const t of input.traceErrors) {\n total.tests += 1;\n total.errors += 1;\n const name = displayPath(t.file, input.root);\n suites.push(\n [\n suiteOpen(name, { tests: 1, failures: 0, errors: 1, skipped: 0 }, t.durationMs),\n ` <testcase ${attr(\"classname\", name)} ${attr(\"name\", \"trace\")} ${attr(\n \"time\",\n seconds(t.durationMs),\n )}>`,\n ` <error ${attr(\"message\", \"trace could not be evaluated\")} ${attr(\n \"type\",\n TRACE_RULE_ID,\n )}>${esc(t.error)}</error>`,\n \" </testcase>\",\n \" </testsuite>\",\n ].join(\"\\n\"),\n );\n }\n\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n `<testsuites ${attr(\"name\", \"manni-tracevals\")} ${attr(\"tests\", total.tests)} ${attr(\n \"failures\",\n total.failures,\n )} ${attr(\"errors\", total.errors)}>`,\n ...suites,\n \"</testsuites>\",\n \"\",\n ].join(\"\\n\");\n}\n","/** Coverage rendering shared by every reporter. */\nimport type { AvailabilityReport, CoverageEntry } from \"../artifacts/types.js\";\nimport type { ManifestReport } from \"../capture/types.js\";\n\n/**\n * The \"where\" cell for one coverage entry.\n *\n * Shared rather than duplicated per reporter: this logic existed twice and the\n * copies drifted, so the markdown table interpolated an absent `path` and\n * printed the literal string \"undefined\" for an entry the human reporter\n * rendered correctly.\n *\n * A resolved entry usually names the file it resolved to, but not always —\n * project rules aggregate several files (`CLAUDE.md` *and* `AGENTS.md`) into one\n * entry with no single `path`. Fall through to the note, then to empty. `note`\n * is independent of `resolved` in the type, so a producer that supplies one is\n * honoured rather than having it silently dropped.\n */\nexport function coverageLocation(entry: CoverageEntry): string {\n if (entry.resolved) return entry.path ?? entry.note ?? \"\";\n if (entry.availability === \"offered-not-used\") {\n // Never looked for on disk, so \"not found\" would be a false claim.\n return entry.note ?? \"offered, never used\";\n }\n return entry.note ?? `not found (${entry.tried.length} location(s) tried)`;\n}\n\n/**\n * The roster line for one coverage row (ADR 01016). Only the two states a\n * reader has to act on are labelled: an artifact that was offered and used is\n * the ordinary case and says nothing, and `unknown` means the trace carried no\n * roster, which is not this row's problem to announce.\n */\nexport function availabilityTag(entry: CoverageEntry): string | undefined {\n if (entry.availability === \"not-offered\") return \"not offered\";\n if (entry.availability === \"offered-not-used\") return \"offered, unused\";\n return undefined;\n}\n\n/**\n * The offered-versus-used summary. Counts by default — a real roster runs to\n * hundreds of skills, and listing them would bury the evals above.\n */\nexport function availabilityLines(report: AvailabilityReport): string[] {\n if (!report.recorded) {\n // Unknown, not zero: older sessions and stream transcripts carry no\n // listing records at all (ADR 01003).\n return [\n \"no availability roster in this trace, so what the session was offered is unknown\",\n ];\n }\n const lines = [\n `${report.skills.offered} skill(s) offered, ${report.skills.used} used, ${report.skills.unused} never used`,\n `${report.agents.offered} agent(s) offered, ${report.agents.used} used, ${report.agents.unused} never used`,\n ];\n if (!report.listed && report.skills.unused + report.agents.unused > 0) {\n lines.push(\"pass --report-unused-artifacts to list them\");\n }\n return lines;\n}\n\n/**\n * The staleness note for one coverage entry, or \"\" when it is not stale.\n *\n * Kept beside `coverageLocation` and separate from it: the location answers\n * \"which file\", and this answers \"is that file still what the session saw\"\n * (ADR 01021). Collapsing them would drop the path for a stale entry, which is\n * exactly the row where a reader most wants to open the file.\n *\n * The wording says which evidence answered, because they are not the same\n * claim (ADR 01024). A manifest mismatch is content identity — the file *is*\n * different. mtime is a guess that a checkout defeats. A reader deciding\n * whether to act on the row needs to know which of the two they are reading,\n * and the mtime phrasing is left byte-identical so that nothing downstream has\n * to re-learn it.\n */\nexport function coverageStaleness(entry: CoverageEntry): string {\n if (entry.stale !== true) return \"\";\n if (entry.contentCheck?.status === \"mismatch\") {\n return \"changed since the session started (session manifest sha256)\";\n }\n return entry.modifiedAt !== undefined\n ? `modified after the session ended (${entry.modifiedAt})`\n : \"modified after the session ended\";\n}\n\n/**\n * The session-manifest block, or nothing when no manifest was found.\n *\n * Silence is the right default for the absent case: a line on every run of\n * every project that has not adopted `capture` is noise, and the machine-\n * readable answer is already on each coverage row as a `skipped` content check\n * with its reason.\n *\n * `unrecorded` is reported rather than folded into `matched`, because those\n * rows still rest on the mtime heuristic and a reader has to be able to see how\n * many of them there are.\n */\nexport function manifestLines(report: ManifestReport): string[] {\n const lines = [\n `${report.path} captured ${report.capturedAt}${\n report.gitSha !== undefined ? ` at ${report.gitSha.slice(0, 12)}` : \"\"\n }`,\n `${report.matched} artifact(s) unchanged, ${report.changed} changed, ${report.unrecorded} not recorded`,\n ];\n if (report.unrecorded > 0) {\n lines.push(\n \"artifacts the manifest did not record keep the mtime heuristic\",\n );\n }\n return lines;\n}\n","/** Human-readable terminal report. */\nimport { palette, type Colors } from \"../../shared/color.js\";\nimport type { EvalResult, RunReport } from \"../types.js\";\nimport { locationLabel } from \"./ci.js\";\nimport type { CoverageEntry } from \"../artifacts/types.js\";\nimport {\n availabilityLines,\n availabilityTag,\n coverageLocation,\n coverageStaleness,\n manifestLines,\n} from \"./coverage.js\";\n\nconst OUTCOME_LABEL: Record<EvalResult[\"outcome\"], string> = {\n pass: \"PASS\",\n fail: \"FAIL\",\n error: \"ERROR\",\n \"needs-review\": \"REVIEW\",\n skipped: \"SKIP\",\n};\n\nfunction paintFor(\n pc: Colors,\n outcome: EvalResult[\"outcome\"],\n): (s: string) => string {\n switch (outcome) {\n case \"pass\":\n return pc.green;\n case \"fail\":\n case \"error\":\n return pc.red;\n case \"needs-review\":\n return pc.yellow;\n default:\n return pc.dim;\n }\n}\n\n/**\n * `✓` resolved, `·` offered and never used (nothing was looked for, so it is\n * not an unresolved reference), `○` referenced but not found.\n */\nfunction coverageMark(pc: Colors, entry: CoverageEntry): string {\n if (entry.resolved) return pc.green(\"✓\");\n if (entry.availability === \"offered-not-used\") return pc.dim(\"·\");\n return pc.yellow(\"○\");\n}\n\n/** Colour is off unless the caller turns it on (the CLI decides, per clig.dev). */\nexport interface ColorOptions {\n color?: boolean;\n}\n\nexport function renderPretty(report: RunReport, opts: ColorOptions = {}): string {\n const pc = palette(opts.color === true);\n const lines: string[] = [];\n const t = report.trace;\n lines.push(pc.bold(`manni tracevals — ${t.file}`));\n lines.push(\n pc.dim(\n `${t.source} · ${t.model ?? \"unknown model\"} · ${t.turnCount} turn(s) · ${t.cwd}`,\n ),\n );\n lines.push(\"\");\n\n for (const result of report.evalResults) {\n const paint = paintFor(pc, result.outcome);\n const label = paint(OUTCOME_LABEL[result.outcome].padEnd(6));\n const name = `${result.artifactName} › ${result.evalName}`;\n lines.push(\n ` ${label} ${name}${result.implicit ? pc.dim(\" (implicit)\") : \"\"} ${pc.dim(locationLabel(result.location))}`,\n );\n for (const finding of result.findings ?? []) {\n if (result.outcome !== \"pass\" || finding.severity !== \"error\") {\n lines.push(` ${pc.dim(`[${finding.severity}]`)} ${finding.message}`);\n }\n }\n if (result.error) lines.push(` ${pc.red(result.error)}`);\n if (result.skipReason) lines.push(` ${pc.dim(result.skipReason)}`);\n if (result.consensus && result.outcome !== \"pass\") {\n const v = result.consensus.votes;\n lines.push(\n ` ${pc.dim(`votes pass:${v.pass} fail:${v.fail} partial:${v.partial} error:${v.error} · confidence ${result.consensus.meanConfidence.toFixed(2)}`)}`,\n );\n const observed = result.consensus.runs.find((r) => r.verdict)?.verdict\n ?.observed;\n if (observed) lines.push(` ${pc.dim(observed)}`);\n }\n }\n\n lines.push(\"\");\n lines.push(pc.bold(\"Artifact coverage\"));\n for (const entry of report.coverage) {\n const tag = availabilityTag(entry);\n const location = coverageLocation(entry);\n const stale = coverageStaleness(entry);\n // Joined from the non-empty parts: an aggregated entry has no location, and\n // interpolating one anyway leaves a double space before the note. The two\n // markers are independent — a row can be both offered-but-unused and stale.\n lines.push(\n [\n ` ${coverageMark(pc, entry)} ${entry.kind}: ${entry.ref}`,\n tag === undefined ? \"\" : pc.yellow(`[${tag}]`),\n location ? pc.dim(location) : \"\",\n stale ? pc.yellow(`⚠ ${stale}`) : \"\",\n ]\n .filter((part) => part !== \"\")\n .join(\" \"),\n );\n }\n\n if (report.manifest !== undefined) {\n // Only when there is one: a line saying \"no manifest\" on every run of every\n // project that has not adopted `capture` is noise, and the per-row skipped\n // content check already carries the machine-readable answer (ADR 01024).\n lines.push(\"\");\n lines.push(pc.bold(\"Session manifest\"));\n for (const line of manifestLines(report.manifest)) {\n lines.push(` ${pc.dim(line)}`);\n }\n }\n\n lines.push(\"\");\n lines.push(pc.bold(\"Availability\"));\n for (const line of availabilityLines(report.availability)) {\n lines.push(` ${pc.dim(line)}`);\n }\n\n if (report.warnings.length > 0) {\n lines.push(\"\");\n lines.push(pc.bold(\"Warnings\"));\n for (const warning of report.warnings) {\n lines.push(` ${pc.yellow(\"!\")} ${warning}`);\n }\n }\n\n const s = report.summary;\n lines.push(\"\");\n lines.push(\n pc.bold(\n `${s.total} eval(s): ${pc.green(`${s.pass} pass`)}, ${\n s.fail > 0 ? pc.red(`${s.fail} fail`) : `${s.fail} fail`\n }, ${s.error} error, ${s.needsReview} needs-review, ${s.skipped} skipped`,\n ),\n );\n // Only when it says something the counts do not. With every weight at 1 the\n // rate is just pass/graded, which the line above already shows; printing it\n // anyway would be a second way to read the same number.\n const weighted = report.evalResults.some(\n (r) => r.weight !== undefined && r.weight !== 1,\n );\n if (weighted) {\n lines.push(\n pc.dim(`weighted pass rate ${(s.passRate * 100).toFixed(0)}%`),\n );\n }\n if (report.turns > 0) {\n lines.push(pc.dim(`judge turns ${report.turns}`));\n }\n return lines.join(\"\\n\");\n}\n","/** Markdown report, suitable for PR comments and docs. */\nimport type { RunReport } from \"../types.js\";\nimport { locationLabel } from \"./ci.js\";\nimport {\n availabilityLines,\n coverageLocation,\n coverageStaleness,\n manifestLines,\n} from \"./coverage.js\";\n\n/**\n * Escapes a value for a markdown table cell. Every cell needs this, not just\n * the free-text ones: `ref` is a skill name or `subagent_type` read straight\n * out of the trace, so an unescaped pipe there silently adds columns to a table\n * that ends up pasted into a pull request comment.\n */\nconst cell = (value: string): string => value.replace(/\\|/g, \"\\\\|\");\n\nexport function renderMarkdown(report: RunReport): string {\n const lines: string[] = [];\n const t = report.trace;\n lines.push(`# manni tracevals report`);\n lines.push(\"\");\n lines.push(`- **Trace**: \\`${t.file}\\``);\n lines.push(`- **Source**: ${t.source} (${t.model ?? \"unknown model\"})`);\n lines.push(`- **Project**: \\`${t.cwd}\\``);\n lines.push(`- **Turns**: ${t.turnCount}`);\n lines.push(\"\");\n\n lines.push(`## Evals`);\n lines.push(\"\");\n lines.push(`| Outcome | Artifact | Eval | Grader | Detail |`);\n lines.push(`|---|---|---|---|---|`);\n for (const r of report.evalResults) {\n const detail =\n r.error ??\n r.skipReason ??\n r.findings?.map((f) => f.message).join(\"; \") ??\n (r.consensus\n ? `votes p:${r.consensus.votes.pass} f:${r.consensus.votes.fail} e:${r.consensus.votes.error}`\n : \"\");\n lines.push(\n `| ${r.outcome} | ${cell(r.artifactName)} | ${cell(r.evalName)}${r.implicit ? \" (implicit)\" : \"\"} \\`${cell(locationLabel(r.location))}\\` | ${cell(r.grader)} | ${cell(detail)} |`,\n );\n }\n lines.push(\"\");\n\n lines.push(`## Artifact coverage`);\n lines.push(\"\");\n lines.push(`| Resolved | Kind | Ref | Availability | Where |`);\n lines.push(`|---|---|---|---|---|`);\n for (const entry of report.coverage) {\n const location = cell(coverageLocation(entry));\n // Code-span only a real path; wrapping an empty string in backticks would\n // render an empty code span rather than an empty cell.\n const where =\n entry.resolved && entry.path !== undefined ? `\\`${location}\\`` : location;\n // An artifact that was offered and never used was never looked for, so\n // \"no\" under Resolved would be a claim about a search that never ran.\n const resolved =\n entry.availability === \"offered-not-used\"\n ? \"n/a\"\n : entry.resolved\n ? \"yes\"\n : \"no\";\n // Staleness is appended to the same cell rather than given a column of its\n // own: an extra column would be empty on almost every row of almost every\n // report, and Availability already claims the one column worth spending.\n const stale = coverageStaleness(entry);\n const cellText = stale\n ? `${where}${where ? \" — \" : \"\"}⚠ ${cell(stale)}`\n : where;\n lines.push(\n `| ${resolved} | ${cell(entry.kind)} | ${cell(entry.ref)} | ${cell(entry.availability ?? \"\")} | ${cellText} |`,\n );\n }\n lines.push(\"\");\n\n if (report.manifest !== undefined) {\n // Only when there is one — see the human reporter (ADR 01024).\n lines.push(`## Session manifest`);\n lines.push(\"\");\n for (const line of manifestLines(report.manifest)) {\n lines.push(`- ${cell(line)}`);\n }\n lines.push(\"\");\n }\n\n lines.push(`## Availability`);\n lines.push(\"\");\n for (const line of availabilityLines(report.availability)) {\n lines.push(`- ${line}`);\n }\n lines.push(\"\");\n\n if (report.warnings.length > 0) {\n lines.push(`## Warnings`);\n lines.push(\"\");\n for (const warning of report.warnings) lines.push(`- ${warning}`);\n lines.push(\"\");\n }\n\n const s = report.summary;\n lines.push(\n `**${s.total} eval(s)** — ${s.pass} pass, ${s.fail} fail, ${s.error} error, ${s.needsReview} needs-review, ${s.skipped} skipped.`,\n );\n return lines.join(\"\\n\");\n}\n","/**\n * SARIF 2.1.0 reporter.\n *\n * docevals' shape: one run, every reported rule declared in\n * `tool.driver.rules`, findings at error/warning/note, a judged failure and an\n * errored eval reported rather than left to read as \"all clear\".\n *\n * Two things are tracevals' own:\n *\n * - **Rules are graders.** The id is `tracevals/<grader>`, so a dashboard\n * groups by what checked the session (`tracevals/tool-usage`,\n * `tracevals/ai`); the eval's own name is in `properties.eval`.\n * - **Locations are declaring entries, often outside the checkout.** A\n * finding points at the entry that declares the eval, in the skill or\n * instruction file or in the manifest that supplied it, with its line as\n * the region. Under the run root that is a relative URI against `SRCROOT`.\n * A user-level skill in `~/.claude` gets an absolute `file:` URI, since no\n * relative one reaches it, and a hosted manifest keeps its URL. The trace\n * graded is `properties.trace`.\n */\nimport type { Severity } from \"../../shared/severity.js\";\nimport {\n artifactLocation,\n fileUri,\n URI_BASE_ID,\n type ArtifactLocation,\n} from \"../../shared/sarif-location.js\";\nimport { classifyRef } from \"../../meta/index.js\";\nimport type { EvalResult, RunReport } from \"../types.js\";\nimport {\n displayPath,\n errorText,\n judgeFailText,\n locationPath,\n ruleIdFor,\n TRACE_RULE_ID,\n traceErrorText,\n type CiInput,\n} from \"./ci.js\";\n\nconst SARIF_SCHEMA =\n \"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json\";\n\ntype SarifLevel = \"error\" | \"warning\" | \"note\";\n\n/** SARIF has three levels; `notice` is `note`, not a dropped finding. */\nconst LEVELS: Record<Severity, SarifLevel> = {\n error: \"error\",\n warning: \"warning\",\n notice: \"note\",\n};\n\ninterface SarifRule {\n id: string;\n name: string;\n shortDescription: { text: string };\n defaultConfiguration: { level: SarifLevel };\n}\n\n/** The declaring file as a SARIF artifact location. A hosted manifest is its URL. */\nfunction declaringLocation(r: EvalResult, root: string): ArtifactLocation {\n if (classifyRef(r.location.file).kind === \"url\") return { uri: r.location.file };\n return artifactLocation(locationPath(r.location, root), root);\n}\n\nexport function renderSarif(input: CiInput): string {\n const rules = new Map<string, SarifRule>();\n const results: unknown[] = [];\n\n const declare = (id: string, name: string, text: string, level: SarifLevel) => {\n if (!rules.has(id)) {\n rules.set(id, {\n id,\n name,\n shortDescription: { text },\n defaultConfiguration: { level },\n });\n }\n };\n\n const push = (\n run: RunReport,\n r: EvalResult,\n level: SarifLevel,\n text: string,\n ) => {\n const id = ruleIdFor(r.grader);\n declare(\n id,\n r.grader,\n r.grader === \"ai\"\n ? \"manni tracevals AI judge\"\n : `manni tracevals ${r.grader} grader`,\n level,\n );\n results.push({\n ruleId: id,\n level,\n message: { text },\n locations: [\n {\n physicalLocation: {\n artifactLocation: declaringLocation(r, input.root),\n // SARIF regions are 1-based and need `startLine`, so a location\n // with no line has no region rather than an invented line 1.\n ...(r.location.line === undefined\n ? {}\n : { region: { startLine: r.location.line } }),\n },\n },\n ],\n properties: {\n eval: r.evalName,\n artifactName: r.artifactName,\n artifactType: r.artifactType,\n trace: displayPath(run.trace.file, input.root),\n ...(run.trace.sessionId !== undefined\n ? { sessionId: run.trace.sessionId }\n : {}),\n },\n });\n };\n\n for (const run of input.runs) {\n for (const r of run.evalResults) {\n for (const f of r.findings ?? []) {\n push(run, r, LEVELS[f.severity], f.message);\n }\n const judged = judgeFailText(r);\n if (judged !== undefined) push(run, r, \"error\", judged);\n if (r.outcome === \"error\") push(run, r, \"error\", errorText(r));\n }\n }\n\n for (const t of input.traceErrors) {\n declare(TRACE_RULE_ID, \"trace\", \"manni tracevals could not read the trace\", \"error\");\n results.push({\n ruleId: TRACE_RULE_ID,\n level: \"error\",\n message: { text: traceErrorText(t.error) },\n locations: [\n {\n physicalLocation: {\n artifactLocation: artifactLocation(t.file, input.root),\n },\n },\n ],\n });\n }\n\n const log = {\n $schema: SARIF_SCHEMA,\n version: \"2.1.0\",\n runs: [\n {\n tool: {\n driver: {\n name: \"manni-tracevals\",\n informationUri: \"https://hawkeyexl.github.io/manni/tracevals/\",\n rules: [...rules.values()],\n },\n },\n originalUriBaseIds: { [URI_BASE_ID]: { uri: fileUri(input.root) } },\n results,\n },\n ],\n };\n return `${JSON.stringify(log, null, 2)}\\n`;\n}\n","/**\n * The single source of truth for `-f/--format` values.\n *\n * The same shape docevals' `reporters/format.ts` carries, and for the same\n * reason: the constant a command validates against and the type its renderer\n * accepts cannot drift, and an unknown value is a usage error (exit 2) rather\n * than a silent fall-through to the pretty renderer.\n */\nimport { TracevalsError } from \"../types.js\";\n\n/** Formats `run` can emit: docevals' `run` set, less `html`. */\nexport const REPORT_FORMATS = [\n \"pretty\",\n \"json\",\n \"markdown\",\n \"github\",\n \"sarif\",\n \"junit\",\n] as const;\n\n/**\n * Formats `calibrate` can emit. Not the CI three: a calibration report\n * measures the judge rather than listing findings to annotate, and docevals'\n * `calibrate` has no CI format either.\n */\nexport const CALIBRATE_FORMATS = [\"pretty\", \"json\", \"markdown\"] as const;\n\n/** Formats the summary commands (`list`, `fill`, `capture`) can emit. */\nexport const SUMMARY_FORMATS = [\"pretty\", \"json\"] as const;\n\nexport type ReportFormat = (typeof REPORT_FORMATS)[number];\nexport type CalibrateFormat = (typeof CALIBRATE_FORMATS)[number];\nexport type SummaryFormat = (typeof SUMMARY_FORMATS)[number];\n\n/**\n * Narrow a raw `--format` value to one of `allowed`, or throw.\n *\n * Matching is exact: no trimming, no case folding. A near-miss is a typo the\n * caller should see, not something to guess at. `flag` names whatever the\n * caller actually supplied, so the CLI passes `--format` and a library caller's\n * render entry point passes `format`.\n */\nexport function parseFormat<T extends string>(\n value: string,\n allowed: readonly T[],\n flag: string,\n): T {\n if (!(allowed as readonly string[]).includes(value)) {\n throw new TracevalsError(\n `${flag} must be one of ${allowed.join(\" | \")}, got \"${value}\"`,\n );\n }\n return value as T;\n}\n","/** Report rendering. */\nimport type { BatchReportWithBudget } from \"../aggregate.js\";\nimport type { CalibrationReport } from \"../calibrate/types.js\";\nimport { TracevalsError, type RunReport } from \"../types.js\";\nimport { renderBatchMarkdown, renderBatchPretty } from \"./batch.js\";\nimport {\n renderCalibrationMarkdown,\n renderCalibrationPretty,\n} from \"./calibration.js\";\nimport { ciInputFromBatch, ciInputFromRun, type CiInput } from \"./ci.js\";\nimport { renderGithub } from \"./github.js\";\nimport { renderJunit } from \"./junit.js\";\nimport { renderPretty, type ColorOptions } from \"./pretty.js\";\nimport { renderMarkdown } from \"./markdown.js\";\nimport { renderSarif } from \"./sarif.js\";\nimport {\n CALIBRATE_FORMATS,\n REPORT_FORMATS,\n parseFormat,\n type ReportFormat,\n} from \"./format.js\";\n\nexport {\n CALIBRATE_FORMATS,\n REPORT_FORMATS,\n SUMMARY_FORMATS,\n parseFormat,\n type ReportFormat,\n type SummaryFormat,\n} from \"./format.js\";\n\nexport type { ColorOptions } from \"./pretty.js\";\n\nexport function render(\n report: RunReport,\n format: ReportFormat,\n opts: ColorOptions = {},\n): string {\n // The same entry guard the sibling entry points carry, and for docevals'\n // reason: these are exported from `src/index.ts`, so a library caller\n // arrives with no CLI parser in front of them. A `default:` branch would\n // silently render pretty for a misspelt format instead of saying so.\n parseFormat(format, REPORT_FORMATS, \"format\");\n switch (format) {\n case \"json\":\n return JSON.stringify(report, null, 2);\n case \"markdown\":\n return renderMarkdown(report);\n case \"pretty\":\n return renderPretty(report, opts);\n case \"github\":\n return renderGithub(ciInputFromRun(report), renderMarkdown(report));\n case \"sarif\":\n return renderSarif(ciInputFromRun(report));\n case \"junit\":\n return renderJunit(ciInputFromRun(report));\n }\n}\n\n/**\n * The aggregate counterpart. Kept a separate entry point rather than an\n * overload of `render`, because the two carry different questions and the JSON\n * shapes must stay distinguishable to a downstream consumer (ADR 01018).\n *\n * The CI formats annotate findings, and findings live in the per-trace\n * reports, not in the aggregate's rates. So they need `runs`, the reports the\n * batch was aggregated from, and refuse to render without them rather than\n * emit a clean-looking report with every finding missing.\n */\nexport function renderBatch(\n // The widened shape: `budget` is optional, so a plain `BatchReport` still\n // passes, and one carrying an exhausted budget is rendered rather than\n // narrowed away (ADR 01018's aggregate owns the field).\n report: BatchReportWithBudget,\n format: ReportFormat,\n runs?: readonly RunReport[],\n opts: ColorOptions = {},\n): string {\n parseFormat(format, REPORT_FORMATS, \"format\");\n const ci = (): CiInput => {\n if (runs === undefined) {\n throw new TracevalsError(\n `format \"${format}\" annotates findings, which live in the per-trace reports; pass them as renderBatch's third argument`,\n );\n }\n return ciInputFromBatch(report, runs);\n };\n switch (format) {\n case \"json\":\n return JSON.stringify(report, null, 2);\n case \"markdown\":\n return renderBatchMarkdown(report);\n case \"pretty\":\n return renderBatchPretty(report, opts);\n case \"github\":\n return renderGithub(ci(), renderBatchMarkdown(report));\n case \"sarif\":\n return renderSarif(ci());\n case \"junit\":\n return renderJunit(ci());\n }\n}\n\n/**\n * The calibration counterpart (ADR 01022). A third entry point rather than a\n * mode of the other two: a calibration report answers \"was it right?\", and a\n * consumer must be able to tell that shape apart from a verdict report without\n * inspecting it. It takes `run`'s format type, because `calibrate` shares\n * `run`'s flags, and refuses the CI formats here.\n */\nexport function renderCalibration(\n report: CalibrationReport,\n format: ReportFormat,\n opts: ColorOptions = {},\n): string {\n const narrowed = parseFormat(format, CALIBRATE_FORMATS, \"format\");\n switch (narrowed) {\n case \"json\":\n return JSON.stringify(report, null, 2);\n case \"markdown\":\n return renderCalibrationMarkdown(report);\n case \"pretty\":\n return renderCalibrationPretty(report, opts);\n }\n}\n","/**\n * `manni tracevals run <trace>` — evaluate one trace end to end.\n *\n * Split into three exports so the batch path can reuse them (ADR 01018):\n * `prepareRun` builds what is shared across traces, `runOne` evaluates one, and\n * `runRun` is the two of them plus rendering, unchanged for callers.\n */\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { discoverConfig } from \"../core/config.js\";\nimport { runEvals } from \"../core/engine.js\";\nimport type { ArtifactMetadataLoader } from \"../core/plan.js\";\nimport { loadExternalEvals } from \"../evals/external.js\";\nimport { loadGraderPlugins } from \"../graders/plugins.js\";\nimport {\n appendHistory,\n compareToLast,\n loadHistory,\n type HistoryComparison,\n} from \"../history.js\";\nimport {\n announceSelection,\n assertProviderSelection,\n constructProvider,\n resolveProviderIdentity,\n selectProvider,\n} from \"../judge/provider.js\";\nimport { makeTraceJudge, type TraceJudge } from \"../judge/trace-judge.js\";\nimport type { InferenceProvider } from \"@hawkeyexl/inference\";\nimport { render, type ReportFormat } from \"../reporters/index.js\";\nimport { TracevalsError, type RunReport } from \"../types.js\";\nimport {\n grantsFor,\n isExecutionGrant,\n unknownGrantsMessage,\n type ExecutionGrant,\n} from \"../../shared/execution.js\";\nimport type { TracevalsConfig } from \"../core/config.js\";\n\n/**\n * Everything that is the same for every trace in a run. `runRun` adds the one\n * per-trace field; the batch path (ADR 01018) carries a list instead.\n */\nexport interface RunSharedOptions {\n project?: string;\n provider?: string;\n model?: string;\n /** `--local`: run inference on this machine, over every configured choice. */\n local?: boolean;\n runs?: number;\n deterministicOnly?: boolean;\n noCache?: boolean;\n /** `--max-turns`: ensemble runs for the whole invocation; overrides config. */\n maxTurns?: number;\n format?: ReportFormat;\n output?: string;\n /** Colour the pretty report. Off unless the caller turns it on. */\n color?: boolean;\n /** Append this run to history and compare against the previous run. */\n history?: boolean;\n /** Overrides config.failOnReview; undefined defers to the config. */\n failOnReview?: boolean;\n /**\n * `--allow-execution`: run only these grants, of those `execution.allow`\n * holds. Absent keeps them all; `[]` (`--no-execution`) runs none. Never\n * widens what the config narrowed.\n */\n allowExecution?: string[];\n /** `--require`: grader plugins to load *in addition to* `config.plugins`. */\n require?: string[];\n /** Overrides config.reportUnusedArtifacts; undefined defers to the config. */\n reportUnusedArtifacts?: boolean;\n /**\n * An explicitly named session manifest (ADR 01024). Without it the engine\n * looks in the conventional places and says nothing when there is none.\n */\n manifest?: string;\n /** Directory holding manni.config.yaml; defaults to cwd. */\n configDir?: string;\n /** `-c/--config`: read this file instead of discovering one. */\n config?: string;\n /** `--no-config`: skip discovery and run on the built-in defaults. */\n noConfig?: boolean;\n /**\n * `--offline`: never fetch a remote external-metadata manifest; read the\n * local ones only. A relocated artifact's evals may live in a manifest a\n * collection declares (0047), and a `https://` one is refused rather than\n * fetched.\n */\n offline?: boolean;\n env?: Record<string, string | undefined>;\n /** Test seam: overrides judge construction entirely. */\n judge?: TraceJudge;\n}\n\nexport interface RunCommandOptions extends RunSharedOptions {\n tracePath: string;\n}\n\nexport interface RunCommandResult {\n report: RunReport;\n rendered: string;\n comparison?: HistoryComparison;\n}\n\n/**\n * Grants, checked rather than asserted. The CLI validates its own flag, but\n * this is also the programmatic entry point. An unknown grant that silently\n * matched nothing would narrow the run to no grant at all: every command eval\n * skipped, which reads as a clean corpus rather than a misspelled grant.\n */\nfunction asGrants(values: readonly string[]): ExecutionGrant[] {\n const unknown = values.filter((v) => !isExecutionGrant(v));\n if (unknown.length > 0) throw new TracevalsError(unknownGrantsMessage(unknown));\n return values.filter(isExecutionGrant);\n}\n\n/**\n * Everything a run needs that is *not* per-trace: the resolved config, the\n * plugin-loading warnings, and the judge.\n *\n * Split out for the batch path (ADR 01018), and the split is not cosmetic. The\n * judge carries the turn budget, so building one per trace would turn\n * `maxTurns` from a ceiling on the run into a ceiling on the largest trace.\n * Config and plugins are hoisted for a smaller reason: a plugin imports once\n * per process (ADR 01017), so re-running the loader would attach its warnings\n * to the first trace's report and to no other.\n */\nexport interface RunContext {\n config: TracevalsConfig;\n configDir: string;\n /** Plugin-loading warnings, prepended to every report in the batch. */\n warnings: string[];\n judge?: TraceJudge;\n /**\n * Where each artifact's `metadata` block lives, loaded once per invocation\n * rather than per trace: the manifests are the config's, not the trace's, and\n * a URL one would otherwise be fetched once per trace in a corpus.\n */\n metadataFor?: ArtifactMetadataLoader;\n}\n\nexport async function prepareRun(\n options: RunSharedOptions,\n): Promise<RunContext> {\n const {\n config: loaded,\n dir: configDir,\n collections,\n path: configPath,\n } = await discoverConfig(\n options.configDir ?? process.cwd(),\n {\n ...(options.config === undefined ? {} : { configPath: options.config }),\n ...(options.noConfig === undefined ? {} : { noConfig: options.noConfig }),\n },\n );\n // Flags override the config rather than bypassing it, so the engine still\n // reads one fully-resolved value (CLAUDE.md, \"Config <-> CLI flags\").\n const config = {\n ...loaded,\n failOnReview: options.failOnReview ?? loaded.failOnReview,\n execution: {\n allow: [\n ...grantsFor(loaded.execution.allow, {\n ...(options.allowExecution === undefined\n ? {}\n : { allowExecution: asGrants(options.allowExecution) }),\n }),\n ],\n },\n // A set-valued knob, so `--require` *adds* instead of replacing. A one-off\n // flag must not silently unregister the house graders a repo's config\n // names — every eval declaring one would flip to `unknown grader kind`,\n // which reads as a typo in an artifact nobody touched. Config entries load\n // first, so a deliberate `--require` still wins a colliding kind\n // (ADR 01017).\n plugins: [...loaded.plugins, ...(options.require ?? [])],\n reportUnusedArtifacts:\n options.reportUnusedArtifacts ?? loaded.reportUnusedArtifacts,\n };\n\n // Before planning: `planEvals` is downstream of the registry, and a grader\n // registered after it has been read is a grader that does not exist.\n const plugins = await loadGraderPlugins({\n plugins: config.plugins,\n configDir,\n });\n\n // The command line's say over every configured level. Checked even on a\n // `--deterministic-only` run, where no provider is built: `--provider gemini`\n // is a usage error whatever the run then does with it.\n const flags = {\n ...(options.provider !== undefined ? { provider: options.provider } : {}),\n ...(options.model !== undefined ? { model: options.model } : {}),\n ...(options.local !== undefined ? { local: options.local } : {}),\n };\n const selection = selectProvider(config, flags);\n assertProviderSelection(selection);\n\n let judge = options.judge;\n if (judge === undefined && options.deterministicOnly !== true) {\n const provider = constructProvider(\n config,\n await resolveProviderIdentity(config, flags),\n );\n // Memoized on the selection an eval *resolves to*, not on what it wrote:\n // with `--provider mock` in force, an eval naming `openai` and one naming\n // `anthropic` both resolve to the same provider, and keying on the authored\n // value would build it twice. Memoized as a promise, so a selection that\n // detects or fails does so once and every eval sharing it gets the same\n // provider or the same error.\n const overridden = new Map<string, Promise<InferenceProvider>>();\n const keyOf = (s: { provider: string; model: string | undefined }): string =>\n `${s.provider}:${s.model ?? \"\"}`;\n const defaultKey = keyOf(selection);\n judge = makeTraceJudge({\n provider,\n // An eval may name its own provider or model. It is selected by the same\n // rule the run's own was — flag, then eval, then `tracevals.provider`,\n // then the family's `providers:` — so an eval cannot quietly outrank a\n // flag someone just typed.\n providerFor: async (ev) => {\n const chosen = selectProvider(config, flags, ev);\n // Said before the short-circuit: under `--local` an eval naming a\n // hosted provider resolves to the run's own selection, and is still\n // replaced.\n announceSelection(chosen);\n const key = keyOf(chosen);\n if (key === defaultKey) return provider;\n let built = overridden.get(key);\n if (built === undefined) {\n // The eval's own choice follows the run's rules: an unknown name, or\n // a model with no provider to own it, is refused before anything is\n // built.\n built = (async () => {\n assertProviderSelection(chosen);\n return constructProvider(\n config,\n await resolveProviderIdentity(config, flags, ev),\n );\n })();\n overridden.set(key, built);\n }\n return built;\n },\n runs: options.runs ?? config.judge.ensembleRuns,\n temperature: config.judge.temperature,\n zones: config.judge.zones,\n cacheDir: resolve(configDir, config.judge.cacheDir),\n ...(options.noCache !== undefined ? { noCache: options.noCache } : {}),\n maxTurns: options.maxTurns ?? config.judge.maxTurns,\n });\n }\n\n // The evals an artifact no longer carries inline. Collections never selected\n // this run's traces and never will; what they say here is where a relocated\n // `metadata` block lives (proposals 0047 and 0049 §1).\n const external = await loadExternalEvals({\n collections,\n configDir,\n ...(configPath === undefined ? {} : { configPath }),\n ...(options.offline === undefined ? {} : { offline: options.offline }),\n });\n\n return {\n config,\n configDir,\n warnings: plugins.warnings,\n ...(judge !== undefined ? { judge } : {}),\n ...(external === null\n ? {}\n : {\n metadataFor: (artifact) => external.forArtifact(artifact),\n }),\n };\n}\n\n/**\n * One trace, through the engine and the history file. No rendering: the batch\n * path renders once over the aggregate rather than per trace.\n */\nexport async function runOne(\n options: RunCommandOptions,\n context: RunContext,\n): Promise<{ report: RunReport; comparison?: HistoryComparison }> {\n const { config } = context;\n const report = await runEvals({\n tracePath: options.tracePath,\n ...(options.project !== undefined ? { projectDir: options.project } : {}),\n ...(options.env !== undefined ? { env: options.env } : {}),\n config,\n ...(context.judge !== undefined ? { judge: context.judge } : {}),\n ...(options.deterministicOnly !== undefined\n ? { deterministicOnly: options.deterministicOnly }\n : {}),\n ...(options.manifest !== undefined ? { manifest: options.manifest } : {}),\n ...(context.warnings.length > 0 ? { warnings: context.warnings } : {}),\n ...(context.metadataFor !== undefined\n ? { metadataFor: context.metadataFor }\n : {}),\n });\n\n let comparison: HistoryComparison | undefined;\n if (options.history) {\n const historyFile = resolve(context.configDir, config.history.file);\n comparison =\n compareToLast(await loadHistory(historyFile), report) ?? undefined;\n await appendHistory(historyFile, report);\n }\n return { report, ...(comparison ? { comparison } : {}) };\n}\n\nexport async function runRun(\n options: RunCommandOptions,\n): Promise<RunCommandResult> {\n const context = await prepareRun(options);\n const { report, comparison } = await runOne(options, context);\n\n const format = options.format ?? \"pretty\";\n // Colour reaches the pretty report only; every CI format stays plain text.\n let rendered = render(report, format, { color: options.color === true });\n // Prose only. Appended to JSON, SARIF or JUnit it would leave a document no\n // parser accepts; `github` ends in the markdown summary, so it reads there.\n if (\n comparison &&\n (format === \"pretty\" || format === \"markdown\" || format === \"github\")\n ) {\n rendered += `\\n\\n${renderComparison(comparison)}`;\n }\n if (options.output) {\n await writeFile(options.output, rendered, \"utf-8\");\n }\n return { report, rendered, ...(comparison ? { comparison } : {}) };\n}\n\n/** Exported for the batch reporter, which renders one block per trace. */\nexport function renderComparison(comparison: HistoryComparison): string {\n const lines = [`History vs ${comparison.previousTimestamp}:`];\n for (const r of comparison.regressions) {\n lines.push(` regression: ${r.evalName} (${r.outcome})`);\n }\n for (const i of comparison.improvements) {\n lines.push(` improvement: ${i.evalName} (${i.outcome})`);\n }\n if (comparison.added.length) lines.push(` added: ${comparison.added.join(\", \")}`);\n if (comparison.removed.length) {\n lines.push(` removed: ${comparison.removed.join(\", \")}`);\n }\n if (lines.length === 1) lines.push(\" no changes\");\n return lines.join(\"\\n\");\n}\n","/**\n * Claude Code trace adapter. Parses both dialects behind one entry point:\n * session files (~/.claude/projects/<slug>/*.jsonl) and legacy `claude -p`\n * stream-json transcripts. Produces the normalized Trace model.\n */\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { detectContentFormat } from \"./detect.js\";\nimport {\n applyAvailabilityRecord,\n foldBranchAvailability,\n newAvailability,\n newReplay,\n remapAvailability,\n} from \"./availability.js\";\nimport type {\n AgentSpawn,\n FileAccess,\n SkillInvocation,\n SubagentBranch,\n ToolCall,\n Trace,\n TraceEvent,\n} from \"./types.js\";\n\ntype Rec = Record<string, unknown>;\n\nexport async function parseTraceFile(filePath: string): Promise<Trace> {\n const absolute = resolve(filePath);\n const content = await readFile(absolute, \"utf-8\");\n const trace = parseTraceContent(content, absolute);\n await mergeSidecarBranches(trace, absolute);\n return trace;\n}\n\nexport function parseTraceContent(content: string, filePath: string): Trace {\n const format = detectContentFormat(content);\n const { records, unparseable } = parseLines(content);\n const trace =\n format === \"claude-session\"\n ? parseSession(records, filePath)\n : parseStream(records, filePath);\n if (unparseable > 0) {\n trace.warnings.push(\n `${unparseable} unparseable JSONL line(s) were skipped`,\n );\n }\n return trace;\n}\n\nfunction parseLines(content: string): { records: Rec[]; unparseable: number } {\n const records: Rec[] = [];\n let unparseable = 0;\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const rec = JSON.parse(trimmed) as unknown;\n if (typeof rec === \"object\" && rec !== null) records.push(rec as Rec);\n else unparseable += 1;\n } catch {\n unparseable += 1;\n }\n }\n return { records, unparseable };\n}\n\n/** Record types that carry no conversation content. */\nconst SESSION_META_TYPES = new Set([\n \"queue-operation\",\n \"attachment\",\n \"last-prompt\",\n \"custom-title\",\n \"summary\",\n \"mode\",\n \"pr-link\",\n]);\n\nconst COMMAND_NAME_RE = /<command-name>([^<]+)<\\/command-name>/;\nconst COMMAND_ARGS_RE = /<command-args>([^<]*)<\\/command-args>/;\n\n/**\n * An `Agent` tool_use waiting for the sidechain records it spawned. `claimed`\n * disambiguates the case where one assistant turn spawns several subagents at\n * once and their records interleave.\n */\ninterface PendingBranch {\n toolUseId: string;\n prompt?: string;\n claimed: boolean;\n}\n\n/**\n * Subagent branch attribution. A sidechain record chains by `parentUuid` back\n * to the assistant record that carried the spawning `Agent` tool_use, so that\n * tool_use id is the branch identity. Records are written parent-first, which\n * is what lets one forward pass resolve the whole tree.\n */\ninterface BranchIndex {\n /** Agent spawns keyed by the uuid of the assistant record carrying them. */\n spawns: Map<string, PendingBranch[]>;\n /** Branch already resolved for a record, so its children inherit it. */\n resolved: Map<string, string>;\n}\n\n/** What a single on-disk record contributes to every event it produces. */\ninterface RecordContext {\n sidechain: boolean;\n timestamp?: string;\n branchId?: string;\n /** Session records only: lets `Agent` spawns be indexed by record uuid. */\n uuid?: string;\n branches?: BranchIndex;\n}\n\nfunction newTrace(filePath: string): Trace {\n return {\n source: \"claude-code\",\n file: filePath,\n cwd: \"\",\n events: [],\n toolCalls: [],\n skillInvocations: [],\n agentSpawns: [],\n subagentBranches: [],\n availability: newAvailability(),\n fileAccesses: [],\n userMessages: [],\n assistantTexts: [],\n turnCount: 0,\n warnings: [],\n };\n}\n\n/** Append an event, stamping its own ordinal, and hand that ordinal back. */\nfunction pushEvent(trace: Trace, event: Omit<TraceEvent, \"index\">): number {\n const index = trace.events.length;\n trace.events.push({ ...event, index });\n return index;\n}\n\n/** A sidechain root's message is the Agent prompt verbatim — the tiebreak. */\nfunction plainMessageText(rec: Rec): string | undefined {\n const content = (rec.message as Rec | undefined)?.content;\n return typeof content === \"string\" ? content : undefined;\n}\n\nfunction resolveBranch(\n branches: BranchIndex,\n parentUuid: unknown,\n rootText: string | undefined,\n): string | undefined {\n if (typeof parentUuid !== \"string\") return undefined;\n const inherited = branches.resolved.get(parentUuid);\n if (inherited !== undefined) return inherited;\n const pending = branches.spawns.get(parentUuid);\n if (pending === undefined || pending.length === 0) return undefined;\n const byPrompt =\n rootText !== undefined\n ? pending.find((b) => !b.claimed && b.prompt === rootText)\n : undefined;\n const branch = byPrompt ?? pending.find((b) => !b.claimed) ?? pending[0];\n if (branch === undefined) return undefined;\n branch.claimed = true;\n return branch.toolUseId;\n}\n\nfunction parseSession(records: Rec[], filePath: string): Trace {\n const trace = newTrace(filePath);\n const branches: BranchIndex = { spawns: new Map(), resolved: new Map() };\n // Availability is replayed in record order: `isInitial` replaces the set,\n // a delta adds or removes, and each entry keeps the ordinal it changed at\n // (ADR 01016).\n const availability = newReplay();\n // Resolving a continuation pointer needs the whole file's uuids up front.\n const uuids = new Set<string>();\n for (const rec of records) {\n if (typeof rec.uuid === \"string\") uuids.add(rec.uuid);\n }\n // A leading `summary` record describes the *previous* session and its\n // `leafUuid` names a record there; a pointer that resolves in this file is\n // this session's own summary, not a continuation.\n const continuations: string[] = [];\n let sawMessage = false;\n let compactions = 0;\n let inputTokens = 0;\n let outputTokens = 0;\n let sawUsage = false;\n\n for (const rec of records) {\n const type = rec.type as string | undefined;\n const timestamp = rec.timestamp as string | undefined;\n if (timestamp) {\n trace.startedAt ??= timestamp;\n trace.endedAt = timestamp;\n }\n if (rec.sessionId) trace.sessionId ??= rec.sessionId as string;\n if (rec.subtype === \"compact_boundary\") compactions += 1;\n\n if (type !== undefined && SESSION_META_TYPES.has(type)) {\n if (\n type === \"summary\" &&\n !sawMessage &&\n typeof rec.leafUuid === \"string\" &&\n !uuids.has(rec.leafUuid)\n ) {\n continuations.push(rec.leafUuid);\n }\n const index = pushEvent(trace, { kind: \"meta\", timestamp, raw: rec });\n // An `attachment` record is bookkeeping to every other consumer, but the\n // listing ones are the only record of what the session was *offered*.\n if (\n type === \"attachment\" &&\n applyAvailabilityRecord(availability, rec.attachment, index)\n ) {\n availability.roster.recorded = true;\n }\n continue;\n }\n\n const sidechain = rec.isSidechain === true;\n // cwd/gitBranch follow the latest non-sidechain message record.\n if (!sidechain && typeof rec.cwd === \"string\") trace.cwd = rec.cwd;\n if (!sidechain && typeof rec.gitBranch === \"string\") {\n trace.gitBranch = rec.gitBranch;\n }\n\n const context: RecordContext = { sidechain, timestamp, branches };\n if (typeof rec.uuid === \"string\") context.uuid = rec.uuid;\n if (sidechain) {\n const branchId = resolveBranch(\n branches,\n rec.parentUuid,\n plainMessageText(rec),\n );\n if (branchId !== undefined) {\n context.branchId = branchId;\n if (context.uuid) branches.resolved.set(context.uuid, branchId);\n }\n }\n\n const message = rec.message as Rec | undefined;\n if (type === \"user\" && message) {\n sawMessage = true;\n handleUserMessage(trace, message, context, rec);\n } else if (type === \"assistant\" && message) {\n sawMessage = true;\n const usage = handleAssistantMessage(trace, message, context, rec);\n if (usage && !sidechain) {\n inputTokens += usage.input;\n outputTokens += usage.output;\n sawUsage = true;\n }\n } else {\n pushEvent(trace, { kind: \"system\", timestamp, raw: rec });\n }\n }\n\n if (sawUsage) trace.usage = { inputTokens, outputTokens };\n // Grading a fragment as if it were the whole session is a false verdict, so\n // both ways of losing earlier turns are reported rather than assumed away.\n for (const leaf of continuations) {\n trace.warnings.push(\n `this trace is a fragment of a longer session: it resumes an earlier ` +\n `one recorded elsewhere (summary leafUuid ${leaf} is not in this ` +\n `file), so evals see only the turns recorded here`,\n );\n }\n if (compactions > 0) {\n trace.warnings.push(\n `the conversation was compacted ${compactions} time(s): the agent ` +\n `stopped seeing the turns before each boundary, so early transcript ` +\n `content is not what it was working from`,\n );\n }\n trace.availability = availability.roster;\n trace.subagentBranches = buildBranches(trace);\n return trace;\n}\n\n/**\n * Derive the branch list from whatever branch identity the events already\n * carry. Runs for inline sidechains at parse time and again after sidecar\n * transcripts are spliced in, so both shapes produce the same descriptions.\n */\nfunction buildBranches(\n trace: Trace,\n sidecars: Map<string, Partial<SubagentBranch>> = new Map(),\n): SubagentBranch[] {\n const ranges = new Map<string, { min: number; max: number }>();\n for (const event of trace.events) {\n const id = event.branchId;\n if (id === undefined) continue;\n const range = ranges.get(id);\n if (range === undefined) ranges.set(id, { min: event.index, max: event.index });\n else range.max = Math.max(range.max, event.index);\n }\n if (ranges.size === 0) return [];\n\n const spawnFor = new Map<string, AgentSpawn>();\n for (const spawn of trace.agentSpawns) {\n if (spawn.toolUseId) spawnFor.set(spawn.toolUseId, spawn);\n }\n\n // A branch's parent is whichever branch owns its spawning `Agent` call.\n const parentOf = new Map<string, string | undefined>();\n for (const id of ranges.keys()) {\n const spawn = spawnFor.get(id);\n parentOf.set(\n id,\n spawn ? trace.events[spawn.index]?.branchId : undefined,\n );\n }\n const depthOf = (id: string): number => {\n let depth = 1;\n let cursor = parentOf.get(id);\n const seen = new Set<string>([id]);\n while (cursor !== undefined && !seen.has(cursor)) {\n seen.add(cursor);\n depth += 1;\n cursor = parentOf.get(cursor);\n }\n return depth;\n };\n\n const branches: SubagentBranch[] = [];\n for (const [id, range] of ranges) {\n const spawn = spawnFor.get(id);\n const sidecar = sidecars.get(id);\n const branch: SubagentBranch = {\n branchId: id,\n agentType: sidecar?.agentType ?? spawn?.subagentType ?? id,\n origin: sidecar ? \"sidecar\" : \"inline\",\n spawnDepth: sidecar?.spawnDepth ?? depthOf(id),\n spawnIndex: spawn?.index ?? range.min,\n startIndex: range.min,\n endIndex: range.max + 1,\n };\n const description = sidecar?.description ?? spawn?.description;\n if (description !== undefined) branch.description = description;\n if (sidecar?.agentId) branch.agentId = sidecar.agentId;\n if (sidecar?.parentAgentId) branch.parentAgentId = sidecar.parentAgentId;\n if (sidecar?.file) branch.file = sidecar.file;\n branches.push(branch);\n }\n\n // A branch's span covers the branches nested under it, so widen deepest\n // first and every ancestor inherits the reach of its whole subtree.\n branches.sort((a, b) => b.spawnDepth - a.spawnDepth);\n const byId = new Map(branches.map((b) => [b.branchId, b]));\n for (const branch of branches) {\n const parentId = parentOf.get(branch.branchId);\n const parent = parentId === undefined ? undefined : byId.get(parentId);\n if (parent === undefined) continue;\n parent.startIndex = Math.min(parent.startIndex, branch.startIndex);\n parent.endIndex = Math.max(parent.endIndex, branch.endIndex);\n }\n branches.sort((a, b) => a.startIndex - b.startIndex);\n return branches;\n}\n\nfunction handleUserMessage(\n trace: Trace,\n message: Rec,\n context: RecordContext,\n raw: Rec,\n): void {\n const { sidechain, timestamp, branchId } = context;\n const content = message.content;\n if (typeof content === \"string\") {\n const index = pushEvent(trace, {\n kind: \"user\",\n timestamp,\n text: content,\n sidechain,\n branchId,\n raw,\n });\n if (sidechain) return;\n const command = COMMAND_NAME_RE.exec(content);\n if (command?.[1]) {\n const invocation: SkillInvocation = {\n name: command[1].replace(/^\\//, \"\"),\n via: \"command-injection\",\n index,\n };\n const args = COMMAND_ARGS_RE.exec(content)?.[1]?.trim();\n if (args) invocation.args = args;\n trace.skillInvocations.push(invocation);\n }\n trace.userMessages.push(content);\n trace.turnCount += 1;\n return;\n }\n if (Array.isArray(content)) {\n // Tool results (and mixed blocks). Text blocks alongside tool results are\n // rare; only pure text turns count as prompts.\n let hasToolResult = false;\n const texts: string[] = [];\n // `Rec | null`, because a JSON array really can hold a null and the\n // guards below are what handle it.\n for (const block of content as (Rec | null)[]) {\n if (block?.type === \"tool_result\") hasToolResult = true;\n if (block?.type === \"text\" && typeof block.text === \"string\") {\n texts.push(block.text);\n }\n }\n if (hasToolResult) {\n pushEvent(trace, {\n kind: \"tool_result\",\n timestamp,\n sidechain,\n branchId,\n raw,\n });\n return;\n }\n const text = texts.join(\"\\n\");\n pushEvent(trace, {\n kind: \"user\",\n timestamp,\n text,\n sidechain,\n branchId,\n raw,\n });\n if (!sidechain && text) {\n trace.userMessages.push(text);\n trace.turnCount += 1;\n }\n }\n}\n\nfunction handleAssistantMessage(\n trace: Trace,\n message: Rec,\n context: RecordContext,\n raw: Rec,\n): { input: number; output: number } | undefined {\n const { sidechain, timestamp, branchId } = context;\n if (!sidechain && typeof message.model === \"string\") {\n trace.model ??= message.model;\n }\n const content = message.content;\n if (Array.isArray(content)) {\n for (const block of content as (Rec | null)[]) {\n if (block?.type === \"text\" && typeof block.text === \"string\") {\n pushEvent(trace, {\n kind: \"assistant\",\n timestamp,\n text: block.text,\n sidechain,\n branchId,\n raw,\n });\n if (!sidechain) trace.assistantTexts.push(block.text);\n } else if (block?.type === \"tool_use\") {\n extractToolUse(trace, block, context);\n }\n }\n }\n const usage = message.usage as Rec | undefined;\n if (usage) {\n return {\n input: typeof usage.input_tokens === \"number\" ? usage.input_tokens : 0,\n output: typeof usage.output_tokens === \"number\" ? usage.output_tokens : 0,\n };\n }\n return undefined;\n}\n\nfunction extractToolUse(\n trace: Trace,\n block: Rec,\n context: RecordContext,\n): void {\n const { sidechain, timestamp, branchId } = context;\n const name = block.name as string;\n const input = (block.input as Rec | undefined) ?? {};\n const toolUseId = typeof block.id === \"string\" ? block.id : undefined;\n const index = pushEvent(trace, {\n kind: \"tool_call\",\n timestamp,\n toolName: name,\n sidechain,\n branchId,\n raw: block,\n });\n const call: ToolCall = { name, input, index, sidechain };\n if (timestamp) call.timestamp = timestamp;\n if (branchId) call.branchId = branchId;\n trace.toolCalls.push(call);\n\n switch (name) {\n case \"Skill\": {\n if (typeof input.skill === \"string\") {\n const invocation: SkillInvocation = {\n name: input.skill,\n via: \"skill-tool\",\n index,\n };\n if (toolUseId) invocation.toolUseId = toolUseId;\n if (typeof input.args === \"string\" && input.args) {\n invocation.args = input.args;\n }\n trace.skillInvocations.push(invocation);\n }\n break;\n }\n case \"Agent\": {\n if (typeof input.subagent_type === \"string\") {\n const spawn: AgentSpawn = {\n subagentType: input.subagent_type,\n index,\n };\n if (typeof input.description === \"string\") {\n spawn.description = input.description;\n }\n if (toolUseId) spawn.toolUseId = toolUseId;\n trace.agentSpawns.push(spawn);\n }\n // The spawn opens a branch its sidechain records chain back to.\n if (context.branches && context.uuid && toolUseId) {\n const pending = context.branches.spawns.get(context.uuid) ?? [];\n pending.push({\n toolUseId,\n prompt: typeof input.prompt === \"string\" ? input.prompt : undefined,\n claimed: false,\n });\n context.branches.spawns.set(context.uuid, pending);\n }\n break;\n }\n case \"Read\":\n case \"Write\":\n case \"Edit\": {\n if (typeof input.file_path === \"string\") {\n const op: FileAccess[\"op\"] =\n name === \"Read\" ? \"read\" : name === \"Write\" ? \"write\" : \"edit\";\n trace.fileAccesses.push({ path: input.file_path, op, index });\n }\n break;\n }\n }\n}\n\nfunction parseStream(records: Rec[], filePath: string): Trace {\n const trace = newTrace(filePath);\n // stream-json has no sidechains, so every record shares one flat context.\n const context: RecordContext = { sidechain: false };\n let inputTokens = 0;\n let outputTokens = 0;\n let sawMessageUsage = false;\n\n for (const rec of records) {\n const type = rec.type as string | undefined;\n\n if (type === \"system\" && (rec.subtype === \"init\" || !rec.subtype)) {\n if (typeof rec.cwd === \"string\") trace.cwd = rec.cwd;\n if (typeof rec.model === \"string\") trace.model = rec.model;\n if (typeof rec.session_id === \"string\") trace.sessionId = rec.session_id;\n pushEvent(trace, { kind: \"system\", raw: rec });\n continue;\n }\n\n if (type === \"assistant\" || type === \"user\") {\n const message = (rec.message as Rec | undefined) ?? rec;\n if (type === \"assistant\") {\n const usage = handleAssistantMessage(trace, message, context, rec);\n if (usage) {\n inputTokens += usage.input;\n outputTokens += usage.output;\n sawMessageUsage = true;\n }\n } else {\n handleUserMessage(trace, message, context, rec);\n }\n continue;\n }\n\n if (type === \"result\") {\n trace.isError = rec.is_error === true;\n if (typeof rec.num_turns === \"number\") trace.turnCount = rec.num_turns;\n const usage = rec.usage as Rec | undefined;\n const totalCost =\n typeof rec.total_cost_usd === \"number\" ? rec.total_cost_usd : undefined;\n if (usage) {\n trace.usage = {\n inputTokens:\n typeof usage.input_tokens === \"number\" ? usage.input_tokens : 0,\n outputTokens:\n typeof usage.output_tokens === \"number\" ? usage.output_tokens : 0,\n };\n if (totalCost !== undefined) trace.usage.totalCostUsd = totalCost;\n } else if (sawMessageUsage) {\n trace.usage = { inputTokens, outputTokens };\n if (totalCost !== undefined) trace.usage.totalCostUsd = totalCost;\n }\n pushEvent(trace, { kind: \"meta\", raw: rec });\n continue;\n }\n\n pushEvent(trace, { kind: \"meta\", raw: rec });\n }\n\n if (!trace.usage && sawMessageUsage) {\n trace.usage = { inputTokens, outputTokens };\n }\n return trace;\n}\n\n/* ------------------------------------------------------------------------ *\n * Sidecar subagent transcripts (ADR 01014)\n *\n * Current Claude Code no longer writes subagent turns into the session file.\n * It writes each branch to `<session>/subagents/agent-<id>.jsonl` beside an\n * `agent-<id>.meta.json` naming the `Agent` tool_use that spawned it, so the\n * join is exact rather than heuristic. Every branch is spliced into\n * `trace.events` immediately after that spawning call, which keeps a branch\n * (and any branch nested inside it) contiguous and keeps `index` a gap-free\n * ordinal over the merged list.\n * ------------------------------------------------------------------------ */\n\n/** `agent-<id>.meta.json`. Every member is optional in real stores. */\ninterface SidecarMeta {\n agentType?: string;\n description?: string;\n toolUseId?: string;\n parentAgentId?: string;\n spawnDepth?: number;\n}\n\n/** One transcript to splice: the base session file, or a loaded sidecar. */\ninterface MergeSource {\n id: string;\n events: TraceEvent[];\n toolCalls: ToolCall[];\n fileAccesses: FileAccess[];\n skillInvocations: SkillInvocation[];\n agentSpawns: AgentSpawn[];\n}\n\ninterface LoadedSidecar {\n agentId: string;\n file: string;\n meta: SidecarMeta;\n sub: Trace;\n source: MergeSource;\n}\n\nconst AGENT_META_RE = /^agent-(.+)\\.meta\\.json$/;\nconst AGENT_JSONL_RE = /^agent-(.+)\\.jsonl$/;\n\n/** `<dir>/<session>.jsonl` -> `<dir>/<session>/subagents`. */\nfunction sidecarDirFor(traceFile: string): string {\n const stem = basename(traceFile).replace(/\\.jsonl$/i, \"\");\n return join(dirname(traceFile), stem, \"subagents\");\n}\n\nfunction asSource(id: string, trace: Trace): MergeSource {\n return {\n id,\n events: trace.events,\n toolCalls: trace.toolCalls,\n fileAccesses: trace.fileAccesses,\n skillInvocations: trace.skillInvocations,\n agentSpawns: trace.agentSpawns,\n };\n}\n\n/**\n * Every record in one sidecar carries the same `agentId`, so the whole file is\n * one branch and that file-level fact overrides anything inferred inside it.\n * It has to: `isSidechain` is uniformly true within a sidecar, so the inline\n * `parentUuid` heuristic would hand this agent's own later turns to a nested\n * `Agent` call whose records actually live in a different file.\n */\nfunction stampBranch(sub: Trace, branchId: string): void {\n for (const event of sub.events) {\n event.sidechain = true;\n event.branchId = branchId;\n }\n for (const call of sub.toolCalls) {\n call.sidechain = true;\n call.branchId = branchId;\n }\n}\n\n/**\n * Read every `agent-*.meta.json` beside a session file and parse its\n * transcript. A directory that is not there is the ordinary case and says\n * nothing; anything else that goes wrong becomes a warning (ADR 01003).\n */\nasync function loadSidecars(\n dir: string,\n trace: Trace,\n): Promise<LoadedSidecar[]> {\n let names: string[];\n try {\n names = await readdir(dir);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== \"ENOENT\" && code !== \"ENOTDIR\") {\n trace.warnings.push(\n `could not read the subagent transcript directory ${dir} ` +\n `(${code ?? \"unknown error\"}), so subagent turns are missing here`,\n );\n }\n return [];\n }\n\n const metas = new Set<string>();\n const transcripts = new Set<string>();\n for (const name of names) {\n const meta = AGENT_META_RE.exec(name);\n if (meta?.[1] !== undefined) {\n metas.add(meta[1]);\n continue;\n }\n const jsonl = AGENT_JSONL_RE.exec(name);\n if (jsonl?.[1] !== undefined) transcripts.add(jsonl[1]);\n }\n for (const orphan of [...transcripts].sort()) {\n if (!metas.has(orphan)) {\n trace.warnings.push(\n `subagent transcript agent-${orphan}.jsonl has no ` +\n `agent-${orphan}.meta.json, so it names no Agent spawn and was ` +\n `not merged`,\n );\n }\n }\n\n const loaded: LoadedSidecar[] = [];\n for (const agentId of [...metas].sort()) {\n let meta: SidecarMeta;\n try {\n const raw = await readFile(\n join(dir, `agent-${agentId}.meta.json`),\n \"utf-8\",\n );\n const parsed: unknown = JSON.parse(raw);\n // An array is `typeof \"object\"` too, and would merge with every member\n // undefined while the warning below never fired.\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(\"shape\");\n }\n meta = parsed;\n } catch {\n trace.warnings.push(\n `subagent metadata agent-${agentId}.meta.json is unreadable or not ` +\n `an object, so that branch was not merged`,\n );\n continue;\n }\n const file = join(dir, `agent-${agentId}.jsonl`);\n let sub: Trace;\n try {\n sub = parseTraceContent(await readFile(file, \"utf-8\"), file);\n } catch {\n trace.warnings.push(\n `subagent transcript agent-${agentId}.jsonl is missing or ` +\n `unreadable, so that branch was not merged`,\n );\n continue;\n }\n for (const warning of sub.warnings) {\n trace.warnings.push(`subagent ${meta.agentType ?? agentId}: ${warning}`);\n }\n loaded.push({ agentId, file, meta, sub, source: asSource(agentId, sub) });\n }\n return loaded;\n}\n\nasync function mergeSidecarBranches(\n trace: Trace,\n traceFile: string,\n): Promise<void> {\n const loaded = await loadSidecars(sidecarDirFor(traceFile), trace);\n if (loaded.length === 0) return;\n\n const base = asSource(\"\", trace);\n const sources = new Map<string, MergeSource>([[\"\", base]]);\n // Which transcript holds the `Agent` call a branch hangs off, and where in\n // that transcript. A depth-2 branch's spawn lives inside a depth-1 sidecar,\n // never in the session file, so ascending depth is what makes the join work.\n const spawnOwner = new Map<string, { sourceId: string; local: number }>();\n const registerSpawns = (source: MergeSource): void => {\n for (const spawn of source.agentSpawns) {\n if (spawn.toolUseId !== undefined) {\n spawnOwner.set(spawn.toolUseId, {\n sourceId: source.id,\n local: spawn.index,\n });\n }\n }\n };\n registerSpawns(base);\n\n // Ownership is resolved **iteratively**, not in one depth-sorted pass.\n //\n // The pass assumed `meta.spawnDepth` was always there, but `SidecarMeta`\n // documents every member as optional — and with the depths equal the order\n // fell to the agent-id tiebreak, so a depth-2 branch whose id happened to\n // sort first was visited before its parent had registered the `Agent` call\n // it hangs off, and was discarded with a warning. Renaming the same file\n // made it merge. Repeating until nothing new attaches reaches every branch\n // whose owner is reachable at all, whatever the metadata says.\n const children = new Map<string, LoadedSidecar[]>();\n const attached: Array<{ sidecar: LoadedSidecar; branchId: string }> = [];\n // Byte comparison, not `localeCompare`: sibling modules already sort this\n // way so the ubuntu and windows CI legs order reports identically.\n const pending = [...loaded].sort(\n (a, b) =>\n (a.meta.spawnDepth ?? 1) - (b.meta.spawnDepth ?? 1) ||\n (a.agentId < b.agentId ? -1 : a.agentId > b.agentId ? 1 : 0),\n );\n let progress = true;\n while (progress) {\n progress = false;\n for (let i = 0; i < pending.length; i += 1) {\n const sidecar = pending[i] as LoadedSidecar;\n const branchId = sidecar.meta.toolUseId;\n const owner = branchId === undefined ? undefined : spawnOwner.get(branchId);\n if (branchId === undefined || owner === undefined) continue;\n pending.splice(i, 1);\n i -= 1;\n progress = true;\n stampBranch(sidecar.sub, branchId);\n sources.set(sidecar.agentId, sidecar.source);\n const key = `${owner.sourceId}\\u0000${owner.local}`;\n children.set(key, [...(children.get(key) ?? []), sidecar]);\n registerSpawns(sidecar.source);\n attached.push({ sidecar, branchId });\n }\n }\n // Whatever is left names an `Agent` call no reachable transcript makes.\n for (const sidecar of pending) {\n trace.warnings.push(\n `subagent transcript agent-${sidecar.agentId}.jsonl names Agent call ` +\n `${sidecar.meta.toolUseId ?? \"(none recorded)\"}, which is not in this ` +\n `trace, so that branch was not merged`,\n );\n }\n if (attached.length === 0) return;\n\n // Depth-first assembly: a transcript's own events in order, and after each\n // one the whole subtree of any branch that event spawned.\n const slots: Array<{ sourceId: string; local: number }> = [];\n const emit = (sourceId: string): void => {\n const source = sources.get(sourceId);\n if (source === undefined) return;\n for (let local = 0; local < source.events.length; local += 1) {\n slots.push({ sourceId, local });\n for (const kid of children.get(`${sourceId}\\u0000${local}`) ?? []) {\n emit(kid.agentId);\n }\n }\n };\n emit(\"\");\n\n const remap = new Map<string, number[]>();\n slots.forEach((slot, final) => {\n const row = remap.get(slot.sourceId) ?? [];\n row[slot.local] = final;\n remap.set(slot.sourceId, row);\n });\n const finalIndex = (sourceId: string, local: number): number =>\n remap.get(sourceId)?.[local] ?? local;\n\n trace.events = slots.map((slot, final) => {\n const event = sources.get(slot.sourceId)?.events[slot.local];\n return { ...(event as TraceEvent), index: final };\n });\n\n const gather = <T extends { index: number }>(\n pick: (source: MergeSource) => T[],\n ): T[] =>\n [...sources.values()]\n .flatMap((source) =>\n pick(source).map((item) => ({\n ...item,\n index: finalIndex(source.id, item.index),\n })),\n )\n .sort((a, b) => a.index - b.index);\n\n trace.toolCalls = gather((s) => s.toolCalls);\n trace.fileAccesses = gather((s) => s.fileAccesses);\n trace.skillInvocations = gather((s) => s.skillInvocations);\n trace.agentSpawns = gather((s) => s.agentSpawns);\n\n // The roster's ordinals are positions in `trace.events`, which the splice\n // just renumbered. Then each branch's own roster contributes whatever the\n // session never saw elsewhere, anchored at the spawn (ADR 01016).\n trace.availability = remapAvailability(trace.availability, (index) =>\n finalIndex(\"\", index),\n );\n for (const { sidecar, branchId } of attached) {\n const owner = spawnOwner.get(branchId);\n foldBranchAvailability(\n trace.availability,\n sidecar.sub.availability,\n branchId,\n owner === undefined ? 0 : finalIndex(owner.sourceId, owner.local),\n );\n }\n\n const described = new Map<string, Partial<SubagentBranch>>();\n for (const { sidecar, branchId } of attached) {\n const info: Partial<SubagentBranch> = {\n agentId: sidecar.agentId,\n file: sidecar.file,\n };\n if (sidecar.meta.agentType) info.agentType = sidecar.meta.agentType;\n if (sidecar.meta.description) info.description = sidecar.meta.description;\n if (sidecar.meta.parentAgentId) {\n info.parentAgentId = sidecar.meta.parentAgentId;\n }\n if (typeof sidecar.meta.spawnDepth === \"number\") {\n info.spawnDepth = sidecar.meta.spawnDepth;\n }\n described.set(branchId, info);\n }\n trace.subagentBranches = buildBranches(trace, described);\n}\n","/**\n * Trace format sniffing. Session files and stream-json are both JSONL, but\n * session records carry camelCase `sessionId` (and `parentUuid` on message\n * records) while stream-json uses snake_case `session_id`.\n */\nimport { TracevalsError } from \"../types.js\";\nimport type { TraceFormat } from \"./types.js\";\n\nconst SUPPORTED =\n \"supported formats: Claude Code session files (~/.claude/projects/**.jsonl) and claude -p stream-json\";\n\n/** Detect the dialect from one JSONL line (typically the first parseable). */\nexport function detectFormat(line: string): TraceFormat {\n // Parsed as `unknown`, not asserted to an object: `JSON.parse(\"5\")` and\n // `JSON.parse(\"null\")` both succeed, and a cast here would make the guard\n // below look dead while leaving the bug.\n let rec: unknown;\n try {\n rec = JSON.parse(line);\n } catch {\n throw new TracevalsError(`trace is not JSONL (${SUPPORTED})`);\n }\n if (typeof rec !== \"object\" || rec === null) {\n throw new TracevalsError(`unrecognized trace format (${SUPPORTED})`);\n }\n if (\"parentUuid\" in rec || \"sessionId\" in rec) return \"claude-session\";\n if (\"session_id\" in rec) return \"claude-stream\";\n throw new TracevalsError(`unrecognized trace format (${SUPPORTED})`);\n}\n\n/**\n * Detect the dialect of a whole file's content: the first line that *identifies*\n * a format decides. Malformed lines and parseable-but-unidentifiable records\n * (e.g. a leading `{\"type\":\"summary\",…}`, which real session files carry) are\n * skipped, so a metadata record at the top never masks the format below it.\n */\nexport function detectContentFormat(content: string): TraceFormat {\n let sawParseable = false;\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n let rec: unknown;\n try {\n rec = JSON.parse(trimmed);\n } catch {\n continue; // Malformed line — keep scanning.\n }\n if (typeof rec !== \"object\" || rec === null) continue;\n sawParseable = true;\n const r = rec as Record<string, unknown>;\n if (\"parentUuid\" in r || \"sessionId\" in r) return \"claude-session\";\n if (\"session_id\" in r) return \"claude-stream\";\n // Parseable but unidentifiable (summary, and other metadata records) —\n // keep scanning for a line that names the format.\n }\n throw new TracevalsError(\n sawParseable\n ? `unrecognized trace format (${SUPPORTED})`\n : `empty or unparseable trace file (${SUPPORTED})`,\n );\n}\n","/**\n * Eval planning: turn resolved artifacts + extracted evals into a flat list of\n * evals to run. Artifacts without declared evals get one implicit\n * whole-artifact adherence eval (ADR 01002).\n */\nimport {\n extractFrontmatter,\n type ExtractedMetadata,\n type SourceLocation,\n} from \"../../meta/index.js\";\nimport { declaredAt } from \"../../meta/internal.js\";\nimport type { ResolvedArtifact } from \"../artifacts/types.js\";\nimport {\n extractEvals,\n type EvalEntry,\n type Severity,\n} from \"../evals/extract.js\";\nimport type { TraceTarget } from \"./target.js\";\n\nexport interface EvalPlan {\n artifact: ResolvedArtifact;\n evalName: string;\n /** Absent on graders whose options say everything (artifact-evals proposal.2). */\n assertion?: string;\n /** \"ai\", \"human\", \"command\", or a deterministic grader kind. */\n grader: string;\n options?: Record<string, unknown>;\n severity: Severity;\n evidence?: string;\n examples?: EvalEntry[\"examples\"];\n /** Overrides the configured judge provider for this eval only. */\n provider?: string;\n /** Overrides the judge model for this eval only; a CLI --model still wins. */\n model?: string;\n /** Ensemble runs for this eval only; a CLI --runs still wins. */\n runs?: number;\n /** Which bytes the grader receives. Absent means the whole transcript. */\n target?: TraceTarget;\n /**\n * Relative contribution to the run's pass rate. Defaults to 1, which is what\n * makes weighting inert until someone asks for it.\n */\n weight?: number;\n /** Command-graded evals: argv, with `{trace}` substituted at grade time. */\n command?: string[];\n successExitCodes?: number[];\n timeoutMs?: number;\n /** sha256 of `assertion` when the check script was generated. */\n generatedAssertionHash?: string;\n /**\n * Models that proposed this assertion, from `metadata.meta-provenance`.\n * A judge whose model appears here is grading a criterion it wrote.\n */\n proposedBy?: string[];\n /** True for the zero-config whole-artifact adherence eval. */\n implicit: boolean;\n /**\n * Where the eval is declared: the item of `metadata.evals` that names it, in\n * the artifact or in the manifest that supplied the block (proposal 0037).\n * `file` is an absolute path, or a URL for a hosted manifest. `line` is\n * absent when nothing records one, as for the implicit eval, which no entry\n * declares.\n */\n location: EvalLocation;\n /** Set when the artifact's evals block failed schema validation. */\n error?: string;\n /** Set when the artifact or the entry opted out. */\n skipped?: boolean;\n /** Why it was skipped, when it was. */\n skipReason?: string;\n}\n\nexport const IMPLICIT_EVAL_NAME = \"adheres-to-artifact\";\n\n/** A file, and the 1-based line in it when one is known. */\nexport interface EvalLocation {\n file: string;\n line?: number;\n}\n\n/**\n * The artifact's front matter as the run reads it, with the merge's `locate`\n * when a manifest was read for it. `locate` names the manifest and line behind\n * a value the manifest supplied; `evals/external.ts` spells that file as an\n * absolute path, or a URL.\n */\nexport interface SuppliedMetadata {\n extracted: ExtractedMetadata;\n locate?: (pointer: string) => SourceLocation | undefined;\n}\n\n/**\n * The artifact's front matter as the run reads it: its own, or its own with a\n * manifest-supplied `metadata` block merged in (`evals/external.ts`). Absent\n * when no collection declares a manifest that owns `metadata`, which is every\n * run that has no `collections:` to read.\n */\nexport type ArtifactMetadataFor = (\n artifact: ResolvedArtifact,\n) => SuppliedMetadata | undefined;\n\n/**\n * `ArtifactMetadataFor`, before the manifests are read. Reading is async: a\n * `{page}` manifest (proposal 0058) is read for the artifact that names it,\n * and a keyless one (proposal 0068) asks the artifact's schemas what it owns.\n */\nexport type ArtifactMetadataLoader = (\n artifact: ResolvedArtifact,\n) => Promise<SuppliedMetadata | undefined>;\n\nexport function planEvals(\n artifacts: ResolvedArtifact[],\n metadataFor?: ArtifactMetadataFor,\n): EvalPlan[] {\n const plans: EvalPlan[] = [];\n for (const artifact of artifacts) {\n const supplied = metadataFor?.(artifact);\n const metadata = {\n extracted: supplied?.extracted ?? extractFrontmatter(artifact.content, \"markdown\"),\n ...(supplied?.locate === undefined ? {} : { locate: supplied.locate }),\n };\n const extracted = extractEvals(artifact, metadata.extracted);\n const at = (pointer: string): EvalLocation =>\n declaredAt(artifact.path, pointer, metadata);\n const whole: EvalLocation = { file: artifact.path };\n\n if (extracted.errors.length > 0) {\n const detail = extracted.errors\n .map(\n (e) =>\n `${e.instancePath || \"/\"}${e.line !== undefined ? ` (line ${e.line})` : \"\"}: ${e.message}`,\n )\n .join(\"; \");\n plans.push({\n artifact,\n evalName: \"evals-block-valid\",\n assertion: \"The artifact's metadata.evals block matches the schema.\",\n grader: \"ai\",\n severity: \"error\",\n implicit: false,\n location: at(\"/metadata/evals\"),\n error: `invalid metadata.evals block: ${detail}`,\n });\n continue;\n }\n\n if (extracted.skip) {\n plans.push({\n artifact,\n evalName: IMPLICIT_EVAL_NAME,\n assertion: \"Artifact skipped via metadata.eval-skip.\",\n grader: \"ai\",\n severity: \"error\",\n implicit: true,\n location: at(\"/metadata/eval-skip\"),\n skipped: true,\n skipReason: \"artifact skipped via metadata.eval-skip\",\n });\n continue;\n }\n\n if (extracted.evals.length === 0) {\n plans.push({\n artifact,\n evalName: IMPLICIT_EVAL_NAME,\n assertion:\n `The session adhered to the instructions in this ${artifact.type} ` +\n `(\"${artifact.name}\"). Cite the specific instructions followed or violated.`,\n grader: \"ai\",\n severity: \"error\",\n implicit: true,\n location: whole,\n });\n continue;\n }\n\n for (const [index, entry] of extracted.evals.entries()) {\n const plan: EvalPlan = {\n artifact,\n evalName: entry.id,\n assertion: entry.assertion,\n grader: entry.grader,\n ...(entry.model !== undefined ? { model: entry.model } : {}),\n ...(entry.runs !== undefined ? { runs: entry.runs } : {}),\n ...(entry.target !== undefined ? { target: entry.target } : {}),\n ...(entry.weight !== undefined ? { weight: entry.weight } : {}),\n severity: entry.severity,\n implicit: false,\n // A string block is one entry at index 0, and the pointer walks up to\n // the block's own line.\n location: at(`/metadata/evals/${String(index)}`),\n };\n if (entry.options) plan.options = entry.options;\n if (entry.evidence) plan.evidence = entry.evidence;\n if (entry.examples) plan.examples = entry.examples;\n if (entry.provider) plan.provider = entry.provider;\n if (entry.command) plan.command = entry.command;\n if (entry.successExitCodes) plan.successExitCodes = entry.successExitCodes;\n if (entry.timeoutMs !== undefined) plan.timeoutMs = entry.timeoutMs;\n if (entry.generatedAssertionHash !== undefined) {\n plan.generatedAssertionHash = entry.generatedAssertionHash;\n }\n const proposedBy = extracted.proposedBy.get(entry.id);\n if (proposedBy !== undefined && proposedBy.length > 0) {\n plan.proposedBy = proposedBy;\n }\n if (entry.skip) {\n plan.skipped = true;\n plan.skipReason = \"eval skipped via its own skip: true\";\n }\n plans.push(plan);\n }\n }\n return plans;\n}\n","/**\n * Judge prompts. PROMPT_VERSION is part of the cache key — bump it on ANY\n * change to the prompts in this file, or stale cached verdicts survive the\n * revision.\n */\nimport type { EvalPlan } from \"../core/plan.js\";\n\n/**\n * 4 — the verdict schema's `$id` became `manni:tracevals:verdict` and the\n * vocabulary moved to artifact-evals proposal.4. The schema is prompt surface,\n * so a cache written before the family rename misses once rather than\n * replaying a verdict formed against the old wording.\n */\nexport const PROMPT_VERSION = 4;\n\nexport const JUDGE_SYSTEM_PROMPT = `You are an adherence judge for AI agent sessions. You are given some evidence from an agent session and one assertion drawn from the instructions the session was operating under — a skill definition, an agent definition, or project rules.\n\nThe evidence is whatever the eval asked to be graded, and its heading says which: usually the session transcript (messages, tool calls, skills used), but it may instead be the session's final message, the list of files it touched, the instruction artifact itself, or one named file. Judge the assertion against what you were actually given.\n\nDecide whether the session adhered to the assertion:\n- \"pass\" only when the session fully satisfied it.\n- \"partial\" when it partly satisfied it.\n- \"fail\" when it violated it or plainly did not do it.\n\nGround every judgment in the graded content: quote or cite the specific part of it — a message, a tool call, a line, or a telling omission — that supports your verdict in the \"observed\" field. If the assertion concerns something the graded content cannot show (e.g. events outside what you were given), say so and lower your confidence.\n\nRespond with a single JSON object matching the provided schema. No prose outside the JSON.`;\n\n/**\n * Cap for the artifact excerpt included alongside the assertion.\n *\n * The prompt says when it truncates, so the judge knows it is reading part of\n * an artifact. What was missing is the *reader* knowing: a verdict formed\n * without sight of an artifact's second half looked identical in every report\n * to one formed with it. `artifactWasTruncated` lets the engine say so.\n */\nexport const MAX_ARTIFACT_CHARS = 8_000;\n\n/** Whether this artifact will be cut before the judge sees it. */\nexport function artifactWasTruncated(content: string): boolean {\n return content.length > MAX_ARTIFACT_CHARS;\n}\n\nexport function buildUserContent(\n plan: EvalPlan,\n graded: string,\n targetLabel = \"transcript\",\n): string {\n const parts: string[] = [];\n parts.push(`# Assertion\\n${plan.assertion ?? \"\"}`);\n if (plan.evidence) {\n parts.push(`# Where to look\\n${plan.evidence}`);\n }\n if (plan.examples?.pass?.length) {\n parts.push(`# Examples of passing behavior\\n- ${plan.examples.pass.join(\"\\n- \")}`);\n }\n if (plan.examples?.fail?.length) {\n parts.push(`# Examples of failing behavior\\n- ${plan.examples.fail.join(\"\\n- \")}`);\n }\n let artifactBody = plan.artifact.content;\n if (artifactBody.length > MAX_ARTIFACT_CHARS) {\n artifactBody = `${artifactBody.slice(0, MAX_ARTIFACT_CHARS)}\\n[... artifact truncated ...]`;\n }\n\n // `target: artifact` makes the source and the graded content the same bytes.\n // Sending them twice under two headings costs tokens and invites the judge\n // to treat them as two documents to reconcile — and it defeats the\n // truncation cap, because the copy under \"graded content\" is not cut.\n const gradingTheArtifact = targetLabel === \"artifact\";\n const artifactHeading = `${plan.artifact.type} (\"${plan.artifact.name}\")`;\n if (!gradingTheArtifact) {\n parts.push(`# Source ${artifactHeading}\\n${artifactBody}`);\n }\n\n // Name what the judge is looking at. Told \"session transcript\" while being\n // handed a written file or a final assistant message, a judge reasons about\n // the wrong thing and says so confidently.\n parts.push(\n targetLabel === \"transcript\"\n ? `# Session transcript\\n${graded}`\n : gradingTheArtifact\n ? `# Graded content: the ${artifactHeading} itself\\n${artifactBody}`\n : `# Graded content (${targetLabel})\\n${graded}`,\n );\n return parts.join(\"\\n\\n\");\n}\n","/**\n * A small path glob, for grader options that name a set of files rather than\n * one (ADR 01016).\n *\n * Deliberately not a dependency: the syntax needed here is `**`, `*`, and `?`\n * over already-normalized paths, and a matcher that small is easier to pin than\n * to pick. Matching follows the same rule as the `file-access` grader's\n * suffix compare — separators normalized, case folded, anchored at a path\n * segment boundary — so `docs/**` reads the same whatever the checkout root is.\n * `file-access` reaches that rule by compiling its literal path through here,\n * so the two cannot drift.\n *\n * **The pattern is untrusted input.** It comes from the *evaluated* project's\n * front matter and is tested against every file access in a window, so a\n * pattern that compiles to nested optional-greedy groups is a denial of service\n * on the runner rather than a slow match. Two things keep that impossible: a\n * run of double-star segments collapses to one, so the optional greedy group\n * never nests, and compilation is memoised per pattern string.\n */\n\n/** Escapes every regex metacharacter; `*` and `?` are handled by the caller. */\nconst literal = (ch: string): string => ch.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/**\n * Compiled patterns, keyed by the pattern string. Bounded because the key\n * space is: a run grades a fixed set of evals, each carrying a fixed set of\n * globs, and the compiled form depends on nothing else.\n */\nconst compiled = new Map<string, RegExp>();\n\nexport function globToRegExp(glob: string): RegExp {\n const cached = compiled.get(glob);\n if (cached !== undefined) return cached;\n const built = compile(glob);\n compiled.set(glob, built);\n return built;\n}\n\nfunction compile(glob: string): RegExp {\n // A run of `**/` means exactly what one does — \"any number of segments\" —\n // so collapsing it here is a normalization, not an approximation. Left\n // uncollapsed, each repeat added another optional greedy group over the same\n // input and the cost of a failed match grew multiplicatively.\n const spec = glob\n .replace(/\\\\/g, \"/\")\n .toLowerCase()\n .replace(/(?:\\*\\*\\/)+/g, \"**/\");\n let out = \"\";\n for (let i = 0; i < spec.length; i += 1) {\n const ch = spec[i] as string;\n if (ch === \"?\") {\n out += \"[^/]\";\n continue;\n }\n if (ch !== \"*\") {\n out += literal(ch);\n continue;\n }\n if (spec[i + 1] !== \"*\") {\n out += \"[^/]*\";\n continue;\n }\n // `**` spans separators, and must allow *zero* segments: `docs/**` has to\n // match `docs` itself, and `docs/**/x` has to match `docs/x`. Both cases\n // absorb one adjacent separator rather than requiring it.\n i += 1;\n if (spec[i + 1] === \"/\") {\n i += 1;\n // A leading `**/` is already covered by the unconditional ancestor\n // prefix below, so emitting a second optional group here would give the\n // engine two interchangeable ways to consume the same segments — the\n // shape that turns a failed match exponential.\n if (out !== \"\") out += \"(?:.*/)?\";\n } else if (out.endsWith(\"/\")) {\n out = `${out.slice(0, -1)}(?:/.*)?`;\n } else {\n out += \".*\";\n }\n }\n // Trace paths are absolute and machine-specific, so a spec matches any\n // ancestor prefix — but only whole segments, so `docs/**` does not match\n // `docsite/`.\n return new RegExp(`^(?:.*/)?${out}$`);\n}\n\n/** Separators normalized and case folded, the one way both matchers see paths. */\nexport function normalizePath(path: string): string {\n return path.replace(/\\\\/g, \"/\").toLowerCase();\n}\n\n/** True when `path` matches `glob`, both normalized the same way. */\nexport function matchesGlob(path: string, glob: string): boolean {\n return globToRegExp(glob).test(normalizePath(path));\n}\n","/**\n * Conditional triggers (ADR 01016): `options.when` arms an eval only for the\n * sessions it is about.\n *\n * The point is to make the *absence* of an artifact checkable. You cannot hang\n * an eval on a skill that never loaded — nothing resolves it, so nothing plans\n * it — but you can hang it on `CLAUDE.md`, which resolves for every session.\n * `when` is what lets that always-planned eval stay quiet on the sessions it\n * has nothing to say about.\n *\n * **A trigger that does not fire is `skipped`, never `pass`.** A check that\n * never armed has not been satisfied, and reporting it as a pass would make a\n * green report out of an eval that never ran — the same reasoning that makes an\n * empty window a skip (ADR 01015).\n *\n * **`when` is a general trigger, not one grader's feature.** Every windowed\n * grader routes its options through `validateWhen` and its window through\n * `evaluateWhen`, because `options` is an open bag: a grader that merely\n * ignored an unrecognised `when` would leave the eval armed on every session,\n * which is the exact failure this module exists to prevent. `cost` and\n * `json-output` are the abstainers, and they say so: both grade the whole\n * session rather than a window (ADR 01015), so there is nothing to evaluate a\n * predicate over, and `rejectWhen` turns the option into a loud error.\n *\n * Predicates are pure trace facts, evaluated over the artifact's window, and\n * every listed one must hold.\n *\n * `options` is an open object by schema decree — \"validated by the grader at\n * run time — a grader's options evolve on the grader's schedule\" — so this\n * costs no schema change and no upstream docmeta proposal (ADR 01010).\n */\nimport { matchesGlob } from \"./glob.js\";\nimport type { TraceWindow } from \"./util.js\";\nimport type { Options } from \"./util.js\";\n\n/**\n * One condition, defined once.\n *\n * The three facets used to live in three unlinked places — the name list, the\n * validator's type grouping, and the evaluator's if-chain — so adding a\n * condition meant three coordinated edits, and an incomplete one failed\n * *silently in the arming direction*: an unvalidated key would be rejected as\n * unknown, but an unevaluated one would simply never constrain anything.\n * Keeping them together makes an incomplete condition a type error.\n */\ninterface Condition {\n /** Rejects a malformed value without a trace, for `fill` (ADR 01004). */\n validate(value: unknown): string | undefined;\n /** True when the condition holds over the window. */\n test(value: unknown, window: TraceWindow): boolean;\n /** The half of the reason that names what was missing. */\n reason(value: unknown, window: TraceWindow): string;\n}\n\nconst stringValue =\n (kind: string) =>\n (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0\n ? undefined\n : `options.when.${kind} must be a string`;\n\n/**\n * Compiled once per pattern, as `globToRegExp` does. The pattern is fixed by\n * the artifact, so rebuilding it for every eval on every trace of a batch is\n * work with no new answer. No `g` flag here, so a shared instance carries no\n * `lastIndex` between calls.\n */\nconst prompts = new Map<string, RegExp>();\n\nfunction promptRe(pattern: string): RegExp {\n const cached = prompts.get(pattern);\n if (cached !== undefined) return cached;\n const built = new RegExp(pattern);\n prompts.set(pattern, built);\n return built;\n}\n\nconst CONDITIONS = {\n \"file-access\": {\n validate: stringValue(\"file-access\"),\n test: (value, window) =>\n window.fileAccesses.some((a) => matchesGlob(a.path, value as string)),\n reason: (value) => `no file matching \"${value as string}\" was accessed`,\n },\n \"tool-used\": {\n validate: stringValue(\"tool-used\"),\n test: (value, window) => window.toolCalls.some((c) => c.name === value),\n reason: (value) => `the ${value as string} tool was never used`,\n },\n \"prompt-matches\": {\n validate: (value) => {\n const shape = stringValue(\"prompt-matches\")(value);\n if (shape !== undefined) return shape;\n try {\n new RegExp(value as string);\n } catch (err) {\n return `options.when.prompt-matches is not a valid regular expression: ${(err as Error).message}`;\n }\n return undefined;\n },\n test: (value, window) => {\n const re = promptRe(value as string);\n return window.userMessages.some((text) => re.test(text));\n },\n reason: (value) => `no prompt matched /${value as string}/`,\n },\n \"turn-count-above\": {\n validate: (value) => {\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n return \"options.when.turn-count-above must be a whole number\";\n }\n if (value < 0) return \"options.when.turn-count-above must be at least 0\";\n return undefined;\n },\n test: (value, window) => window.turnCount > (value as number),\n reason: (value, window) =>\n `${window.turnCount} turn(s) is not more than ${value as number}`,\n },\n} satisfies Record<string, Condition>;\n\n/** Every recognised condition. Unknown keys are an error, never ignored. */\nexport const WHEN_CONDITIONS = Object.keys(\n CONDITIONS,\n) as readonly WhenCondition[];\n\nexport type WhenCondition = keyof typeof CONDITIONS;\n\n/** What a trigger decided, and — when it did not fire — why. */\nexport interface TriggerResult {\n armed: boolean;\n /** Reason phrase for the skip; set only when `armed` is false. */\n reason?: string;\n}\n\n/**\n * Validate `options.when` without a trace, so `fill` can ground-check a\n * proposal before writing it (ADR 01004).\n *\n * An unrecognised condition is rejected rather than dropped. A silently\n * ignored `file-acess` would leave the eval armed on every session — the loud\n * failure is the safe one, and it mirrors how `metadata.eval*` reserves its\n * own prefix in `src/evals/extract.ts`.\n */\nexport function validateWhen(options: Options): string | undefined {\n const when = options.when;\n if (when === undefined) return undefined;\n if (typeof when !== \"object\" || when === null || Array.isArray(when)) {\n return \"options.when must be an object of conditions\";\n }\n const conditions = when as Record<string, unknown>;\n const keys = Object.keys(conditions);\n if (keys.length === 0) {\n // A trigger with no conditions arms on every session, which is the same as\n // having no trigger — but reads like a scoped check.\n return `options.when needs at least one of: ${WHEN_CONDITIONS.join(\", \")}`;\n }\n for (const key of keys) {\n const condition = (CONDITIONS as Record<string, Condition>)[key];\n if (condition === undefined) {\n return `options.when.${key} is not a known condition; expected one of: ${WHEN_CONDITIONS.join(\", \")}`;\n }\n const invalid = condition.validate(conditions[key]);\n if (invalid !== undefined) return invalid;\n }\n return undefined;\n}\n\n/**\n * Decide whether the trigger fires over a window. Conjunctive: the first\n * condition that fails names itself in the reason, so a skipped eval says\n * which half of its trigger was missing rather than only that it was.\n *\n * Evaluation walks `WHEN_CONDITIONS`, not the caller's key order, so the\n * reason a skip carries is stable across two spellings of the same trigger.\n */\nexport function evaluateWhen(options: Options, window: TraceWindow): TriggerResult {\n const when = options.when as Record<string, unknown> | undefined;\n if (when === undefined) return { armed: true };\n\n for (const name of WHEN_CONDITIONS) {\n const value = when[name];\n if (value === undefined) continue;\n const condition = CONDITIONS[name] as Condition;\n if (condition.test(value, window)) continue;\n return {\n armed: false,\n reason: `trigger not met (${window.label}): ${condition.reason(value, window)}`,\n };\n }\n\n return { armed: true };\n}\n\n/**\n * Reject `when` outright, for a grader that has no window to evaluate it over.\n *\n * Silence is the one answer not available. `options` is an open bag, so a\n * `when` a grader neither evaluates nor rejects validates clean and is\n * ignored — and an ignored trigger is an eval left armed on every session,\n * which is precisely the outcome its author wrote `when` to avoid. `cost` is\n * unwindowed by design (ADR 01015) and `json-output` reads the session's final\n * text; for both, the honest answer is that the option does not apply.\n */\nexport function rejectWhen(kind: string, options: Options): string | undefined {\n if (options.when === undefined) return undefined;\n return (\n `options.when is not supported by the ${kind} grader, ` +\n \"which grades the whole session rather than a window\"\n );\n}\n\n/**\n * The skip a grader returns for an unfired trigger. One helper rather than one\n * per grader, so every grader's wording — and the fact that it is a skip and\n * not a pass — comes from a single place.\n */\nexport function skippedTrigger(trigger: TriggerResult): {\n findings: never[];\n skipped: string;\n} {\n return { findings: [], skipped: trigger.reason ?? \"trigger not met\" };\n}\n","/** Shared helpers for deterministic graders. */\nimport type { EvalPlan } from \"../core/plan.js\";\nimport type {\n FileAccess,\n SkillInvocation,\n ToolCall,\n Trace,\n TraceEvent,\n} from \"../trace/types.js\";\nimport type { Finding, GradeResult } from \"./types.js\";\n\nexport function finding(plan: EvalPlan, message: string): Finding {\n return {\n evalName: plan.evalName,\n artifact: plan.artifact.path,\n message,\n severity: plan.severity,\n };\n}\n\nexport function fail(plan: EvalPlan, message: string): GradeResult {\n return { findings: [finding(plan, message)] };\n}\n\nexport const pass: GradeResult = { findings: [] };\n\nexport function optionsError(kind: string, message: string): GradeResult {\n return { findings: [], error: `${kind}: ${message}` };\n}\n\n/** An option-validation outcome: a message when invalid, undefined when fine. */\nexport type OptionCheck = string | undefined;\n\nexport type Options = Record<string, unknown>;\n\n/** First failing check, so callers read as a flat list of constraints. */\nexport function firstError(...checks: OptionCheck[]): OptionCheck {\n return checks.find((check) => check !== undefined);\n}\n\nexport function requiredString(options: Options, key: string): OptionCheck {\n const value = options[key];\n if (typeof value !== \"string\" || value.length === 0) {\n return `options.${key} is required`;\n }\n return undefined;\n}\n\nexport function optionalString(options: Options, key: string): OptionCheck {\n const value = options[key];\n if (value === undefined) return undefined;\n if (typeof value !== \"string\" || value.length === 0) {\n return `options.${key} must be a non-empty string`;\n }\n return undefined;\n}\n\nexport function optionalEnum(\n options: Options,\n key: string,\n allowed: readonly string[],\n): OptionCheck {\n const value = options[key];\n if (value === undefined) return undefined;\n if (typeof value !== \"string\" || !allowed.includes(value)) {\n return `options.${key} must be one of: ${allowed.join(\", \")}`;\n }\n return undefined;\n}\n\nexport function optionalNumber(\n options: Options,\n key: string,\n bounds: { min?: number; integer?: boolean } = {},\n): OptionCheck {\n const value = options[key];\n if (value === undefined) return undefined;\n // Number.isFinite also rejects NaN and both infinities.\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return `options.${key} must be a finite number`;\n }\n if (bounds.integer === true && !Number.isInteger(value)) {\n return `options.${key} must be a whole number`;\n }\n if (bounds.min !== undefined && value < bounds.min) {\n return `options.${key} must be at least ${bounds.min}`;\n }\n return undefined;\n}\n\nexport function optionalBoolean(options: Options, key: string): OptionCheck {\n if (options[key] !== undefined && typeof options[key] !== \"boolean\") {\n return `options.${key} must be a boolean`;\n }\n return undefined;\n}\n\n/** Rejects min > max once both are present and already known to be numbers. */\nexport function orderedBounds(\n options: Options,\n minKey: string,\n maxKey: string,\n): OptionCheck {\n const min = options[minKey];\n const max = options[maxKey];\n if (typeof min === \"number\" && typeof max === \"number\" && min > max) {\n return `options.${maxKey} must be greater than or equal to options.${minKey}`;\n }\n return undefined;\n}\n\n/**\n * Rejects a criterion that configures no bound at all. Such a criterion can\n * never fail, so it reads as coverage while asserting nothing.\n */\nexport function requireOneOf(options: Options, keys: string[]): OptionCheck {\n if (keys.some((key) => options[key] !== undefined)) return undefined;\n return `at least one of ${keys.map((k) => `options.${k}`).join(\" or \")} is required`;\n}\n\n// ── Scoped grading ───────────────────────────────────────────────\n\n/**\n * The slice of a trace an artifact was actually governing (ADR 01015). The\n * window is derived from the artifact's *type*, never declared: a skill governs\n * from its invocation until the next skill takes over, an agent governs its own\n * branch, and project rules govern the whole session.\n */\nexport interface TraceWindow {\n /** Which rule produced this window. */\n scope: \"session\" | \"skill\" | \"agent\" | \"slash-command\";\n /** Names the window in reasons and in the judge digest. */\n label: string;\n /**\n * True when the artifact governed no turn at all. Graders must report\n * `skipped` on an empty window — never a pass, which would be a verdict\n * about turns the artifact had no part in.\n */\n empty: boolean;\n /** Why the window is empty; set only when `empty`. */\n reason?: string;\n events: TraceEvent[];\n toolCalls: ToolCall[];\n fileAccesses: FileAccess[];\n skillInvocations: SkillInvocation[];\n /** Prompts on the window's own chain; nested subagent turns are excluded. */\n userMessages: string[];\n assistantTexts: string[];\n turnCount: number;\n}\n\n/** Half-open ordinal range over `trace.events`; `end` may be Infinity. */\ninterface Span {\n start: number;\n end: number;\n}\n\nexport function windowFor(trace: Trace, plan: EvalPlan): TraceWindow {\n const { name, type } = plan.artifact;\n if (type === \"skill\") return skillWindow(trace, name);\n if (type === \"agent\") return agentWindow(trace, name);\n if (type === \"slash-command\") return slashCommandWindow(trace, name);\n // Project rules govern everything, so the window is the trace itself —\n // handed back by reference, so a session-scoped eval grades exactly what it\n // graded before scoping existed.\n return {\n scope: \"session\",\n label: \"whole session\",\n empty: false,\n events: trace.events,\n toolCalls: trace.toolCalls,\n fileAccesses: trace.fileAccesses,\n skillInvocations: trace.skillInvocations,\n userMessages: trace.userMessages,\n assistantTexts: trace.assistantTexts,\n turnCount: trace.turnCount,\n };\n}\n\n/** A grader's response to an empty window: a stated skip, never a verdict. */\nexport function skippedWindow(window: TraceWindow): GradeResult {\n return { findings: [], skipped: window.reason ?? \"the artifact governed no turns\" };\n}\n\nfunction skillWindow(trace: Trace, name: string): TraceWindow {\n // A skill loads either way: through the `Skill` tool, or by someone typing\n // its slash form.\n return injectionWindow(trace, \"skill\", `skill \"${name}\"`, (s) => s.name === name);\n}\n\n/**\n * A slash command's window is a skill's window, because the mechanism is the\n * same one: an instruction set injected at a point in the session, in force\n * until the next injection takes over (ADR 01023). Only the opening differs —\n * a `Skill` tool call is not the slash-command mechanism, so it can close a\n * command's window but never open it.\n */\nfunction slashCommandWindow(trace: Trace, name: string): TraceWindow {\n return injectionWindow(\n trace,\n \"slash-command\",\n `slash command \"/${name}\"`,\n (s) => s.name === name && s.via === \"command-injection\",\n );\n}\n\n/**\n * The window an injected instruction set governed: from each of its own\n * injections until the next injection of any kind — including another of its\n * own, which simply reopens the window — or to the end of the session.\n */\nfunction injectionWindow(\n trace: Trace,\n scope: \"skill\" | \"slash-command\",\n label: string,\n opensHere: (invocation: SkillInvocation) => boolean,\n): TraceWindow {\n const opens = trace.skillInvocations.filter(opensHere).map((s) => s.index);\n if (opens.length === 0) {\n return emptyWindow(\n scope,\n label,\n `${label} was never invoked in this trace, so it governed no turns`,\n );\n }\n // An instruction set injected inside a subagent branch governs that branch's\n // chain; one injected on the main chain governs the main chain.\n const chainOf = (index: number): string | undefined =>\n trace.events[index]?.branchId;\n const own = new Set<string | undefined>(opens.map(chainOf));\n // **Boundaries are drawn from the opening chain only** (ADR 01015: the next\n // invocation *on the same chain*). Drawn from every invocation, a subagent\n // that loaded a skill of its own closed the parent's window at the spawn —\n // so a `not-used` eval passed on turns it never saw, and the judge digest\n // stopped where the subagent started.\n const boundaries = trace.skillInvocations\n .filter((s) => own.has(chainOf(s.index)))\n .map((s) => s.index)\n .sort((a, b) => a - b);\n const spans = opens.map((start) => ({\n start,\n end: boundaries.find((b) => b > start) ?? Number.POSITIVE_INFINITY,\n }));\n return materialize(trace, scope, label, spans, undefined, own);\n}\n\nfunction agentWindow(trace: Trace, name: string): TraceWindow {\n const label = `agent \"${name}\"`;\n const mine = trace.subagentBranches.filter((b) => b.agentType === name);\n if (mine.length === 0) {\n const spawned = trace.agentSpawns.some((a) => a.subagentType === name);\n return emptyWindow(\n \"agent\",\n label,\n spawned\n ? `${label} was spawned but recorded no subagent turns (no inline ` +\n `sidechain records and no sidecar transcript), so it governed no turns`\n : `${label} was never spawned in this trace, so it governed no turns`,\n );\n }\n // A branch's span already covers everything nested under it (ADR 01014), so\n // one containment pass reaches subagents at any depth.\n const branchIds = new Set(mine.map((b) => b.branchId));\n for (const branch of trace.subagentBranches) {\n if (branchIds.has(branch.branchId)) continue;\n const nested = mine.some(\n (m) => m.startIndex <= branch.startIndex && branch.endIndex <= m.endIndex,\n );\n if (nested) branchIds.add(branch.branchId);\n }\n const spans = mine.map((b) => ({ start: b.startIndex, end: b.endIndex }));\n return materialize(\n trace,\n \"agent\",\n label,\n spans,\n branchIds,\n new Set<string | undefined>(mine.map((b) => b.branchId)),\n );\n}\n\nfunction emptyWindow(\n scope: TraceWindow[\"scope\"],\n label: string,\n reason: string,\n): TraceWindow {\n return {\n scope,\n label,\n empty: true,\n reason,\n events: [],\n toolCalls: [],\n fileAccesses: [],\n skillInvocations: [],\n userMessages: [],\n assistantTexts: [],\n turnCount: 0,\n };\n}\n\n/**\n * Cut every derived list to the spans. `branchIds`, when given, additionally\n * drops events that fall inside an *inline* branch's bounding range without\n * belonging to it — a sidecar branch is contiguous and loses nothing here, but\n * an inline one can enclose interleaved main-chain turns (ADR 01014).\n *\n * `own` names the chain the window is anchored to. Prompts and assistant text\n * are taken from that chain alone, so a subagent spawned inside the window\n * contributes tool calls and file accesses but not turns.\n */\nfunction materialize(\n trace: Trace,\n scope: TraceWindow[\"scope\"],\n label: string,\n spans: Span[],\n branchIds: Set<string> | undefined,\n own: Set<string | undefined>,\n): TraceWindow {\n const inSpan = (index: number): boolean =>\n spans.some((s) => index >= s.start && index < s.end);\n const excluded = new Set<number>();\n if (branchIds !== undefined) {\n for (const event of trace.events) {\n if (!inSpan(event.index)) continue;\n if (event.branchId === undefined || !branchIds.has(event.branchId)) {\n excluded.add(event.index);\n }\n }\n }\n const inWindow = (index: number): boolean =>\n inSpan(index) && !excluded.has(index);\n\n const events = trace.events.filter((e) => inWindow(e.index));\n const textOf = (kind: TraceEvent[\"kind\"]): string[] =>\n events\n .filter((e) => e.kind === kind && own.has(e.branchId) && e.text)\n .map((e) => e.text as string);\n const userMessages = textOf(\"user\");\n\n return {\n scope,\n label,\n empty: false,\n events,\n toolCalls: trace.toolCalls.filter((c) => inWindow(c.index)),\n fileAccesses: trace.fileAccesses.filter((a) => inWindow(a.index)),\n skillInvocations: trace.skillInvocations.filter((s) => inWindow(s.index)),\n userMessages,\n assistantTexts: textOf(\"assistant\"),\n turnCount: userMessages.length,\n };\n}\n","/** tool-usage: assert a tool was used / not used / used within count bounds. */\nimport type { TraceGrader } from \"./types.js\";\nimport { evaluateWhen, skippedTrigger, validateWhen } from \"./when.js\";\nimport {\n fail,\n firstError,\n optionalBoolean,\n optionalEnum,\n optionalNumber,\n optionsError,\n orderedBounds,\n pass,\n requiredString,\n skippedWindow,\n windowFor,\n type Options,\n} from \"./util.js\";\n\n/**\n * A criterion that can never pass is as useless as one that can never fail:\n * `expect: not-used` with `min >= 1` demands the tool be both absent and\n * called, and `expect: used` with `max: 0` is the mirror image.\n */\nfunction checkContradiction(options: Options): string | undefined {\n const expect = (options.expect as string | undefined) ?? \"used\";\n const { min, max } = options;\n if (expect === \"not-used\" && typeof min === \"number\" && min > 0) {\n return \"options.min is unsatisfiable with expect: not-used\";\n }\n if (expect === \"used\" && typeof max === \"number\" && max === 0) {\n return \"options.max of 0 is unsatisfiable with expect: used\";\n }\n return undefined;\n}\n\nfunction validateOptions(options: Options): string | undefined {\n return firstError(\n requiredString(options, \"tool\"),\n optionalEnum(options, \"expect\", [\"used\", \"not-used\"]),\n optionalNumber(options, \"min\", { min: 0, integer: true }),\n optionalNumber(options, \"max\", { min: 0, integer: true }),\n orderedBounds(options, \"min\", \"max\"),\n checkContradiction(options),\n optionalBoolean(options, \"includeSidechains\"),\n validateWhen(options),\n );\n}\n\nexport const toolUsageGrader: TraceGrader = {\n kind: \"tool-usage\",\n validateOptions,\n grade({ trace, plan }) {\n const options = plan.options ?? {};\n const invalid = validateOptions(options);\n if (invalid !== undefined) return optionsError(\"tool-usage\", invalid);\n const tool = options.tool as string;\n const expect = (options.expect as string | undefined) ?? \"used\";\n const includeSidechains = options.includeSidechains === true;\n\n // Count only the calls the artifact was governing (ADR 01015).\n const window = windowFor(trace, plan);\n if (window.empty) return skippedWindow(window);\n const trigger = evaluateWhen(options, window);\n if (!trigger.armed) return skippedTrigger(trigger);\n\n // `includeSidechains` asks whether calls from *somebody else's* branch\n // count toward this artifact. Inside an agent's own window there is no\n // such thing: every call in a branch is `sidechain: true`, so honouring\n // the default there emptied the window and made an agent-artifact eval\n // structurally unable to fail — `{tool: Edit, expect: not-used}` on\n // `.claude/agents/reviewer.md` passed however much the reviewer edited.\n // The window *is* the branch, so the branch's calls are the subject.\n // Agent only, deliberately. An agent window *is* a branch, so its calls\n // are the subject. A skill or slash-command window sits on the chain that\n // invoked it, so sidechain calls inside it belong to subagents it spawned\n // — someone else's work, excluded unless asked for. A slash command reached\n // from inside a branch would count nothing by default; that needs a user to\n // type one there, which is not a path the harness offers.\n const branchScoped = window.scope === \"agent\";\n const count = window.toolCalls.filter(\n (c) => c.name === tool && (branchScoped || includeSidechains || !c.sidechain),\n ).length;\n\n if (expect === \"not-used\" && count > 0) {\n return fail(plan, `tool ${tool} was used ${count} time(s) but must not be`);\n }\n if (expect === \"used\" && count === 0 && options.min === undefined) {\n return fail(plan, `tool ${tool} was never used`);\n }\n if (typeof options.min === \"number\" && count < options.min) {\n return fail(\n plan,\n `tool ${tool} was used ${count} time(s); at least ${options.min} required`,\n );\n }\n if (typeof options.max === \"number\" && count > options.max) {\n return fail(\n plan,\n `tool ${tool} was used ${count} time(s); at most ${options.max} allowed`,\n );\n }\n return pass;\n },\n};\n","/**\n * tool-order: assert one tool was used before another.\n *\n * `tool-usage` answers \"did it happen, and how often\". A large share of what\n * an instruction artifact actually asks for is about *sequence*: read before\n * you write, run the tests after you edit, look at the config before changing\n * it. None of that was expressible — an adherence suite could say Read and\n * Write both happened and still miss a session that wrote first and read\n * afterwards to see what it had done.\n *\n * Adopted from `claude plugin eval`'s `tool_order`, including its\n * `{tool, input_match}` shape: \"Read something, then Write to src/\" is a\n * different claim from \"Read anything, then Write anything\", and only the\n * first catches the case where the session read an unrelated file.\n *\n * Semantics are deliberately the weakest useful ones: **some** occurrence of\n * `before` precedes **some** occurrence of `after`. Requiring every `after` to\n * be preceded by a `before` would fail an otherwise adherent session that\n * did the right thing once and then repeated the second half.\n */\nimport type { ToolCall } from \"../trace/types.js\";\nimport type { TraceGrader } from \"./types.js\";\nimport { evaluateWhen, skippedTrigger, validateWhen } from \"./when.js\";\nimport {\n fail,\n firstError,\n optionalBoolean,\n optionalString,\n optionsError,\n pass,\n requiredString,\n skippedWindow,\n windowFor,\n type Options,\n} from \"./util.js\";\n\nfunction validateOptions(options: Options): string | undefined {\n return firstError(\n requiredString(options, \"before\"),\n requiredString(options, \"after\"),\n optionalString(options, \"beforeInputMatch\"),\n optionalString(options, \"afterInputMatch\"),\n optionalBoolean(options, \"includeSidechains\"),\n validateWhen(options),\n // A pattern that will not compile is the eval's bug, not the session's.\n ...([\"beforeInputMatch\", \"afterInputMatch\"] as const).map((key) => {\n const value = options[key];\n if (typeof value !== \"string\") return undefined;\n try {\n new RegExp(value);\n return undefined;\n } catch (err) {\n return `options.${key} is not a valid regular expression (${\n err instanceof Error ? err.message : String(err)\n })`;\n }\n }),\n );\n}\n\n/**\n * Ordinals of the calls matching `tool`, in `trace.events` order.\n *\n * Position in `trace.toolCalls` is deliberately not what this reads. `index`\n * is each call's ordinal in `trace.events` (ADR 01013), and it is the only\n * thing that stays true after the list is filtered — and after sidecar\n * subagent branches are spliced in (ADR 01014), where a branch's calls sit\n * together in the array but interleave in time with the main chain.\n */\nfunction ordinalsOf(\n calls: ToolCall[],\n tool: string,\n inputMatch: string | undefined,\n): number[] {\n const re = inputMatch === undefined ? undefined : new RegExp(inputMatch);\n return calls\n .filter(\n (c) =>\n c.name === tool &&\n (re === undefined || re.test(JSON.stringify(c.input))),\n )\n .map((c) => c.index);\n}\n\nfunction describe(tool: string, inputMatch: string | undefined): string {\n return inputMatch === undefined ? tool : `${tool} matching /${inputMatch}/`;\n}\n\nexport const toolOrderGrader: TraceGrader = {\n kind: \"tool-order\",\n validateOptions,\n grade({ trace, plan }) {\n const options = plan.options ?? {};\n const invalid = validateOptions(options);\n if (invalid !== undefined) return optionsError(\"tool-order\", invalid);\n\n const before = options.before as string;\n const after = options.after as string;\n const beforeMatch = options.beforeInputMatch as string | undefined;\n const afterMatch = options.afterInputMatch as string | undefined;\n const includeSidechains = options.includeSidechains === true;\n\n // Order only the calls the artifact was governing (ADR 01015), as\n // tool-usage counts them. Over the whole session, a call made before the\n // skill was invoked would satisfy a claim the skill never governed.\n const window = windowFor(trace, plan);\n if (window.empty) return skippedWindow(window);\n const trigger = evaluateWhen(options, window);\n if (!trigger.armed) return skippedTrigger(trigger);\n\n // An agent's window is its own branch, so every call in it is the subject\n // even though each one is a sidechain call; tool-usage says why.\n const branchScoped = window.scope === \"agent\";\n const calls = window.toolCalls.filter(\n (c) => branchScoped || includeSidechains || !c.sidechain,\n );\n const beforeOrdinals = ordinalsOf(calls, before, beforeMatch);\n const afterOrdinals = ordinalsOf(calls, after, afterMatch);\n // `undefined` rather than -1: an ordinal of 0 is the session's very first\n // event, and a sentinel that collides with a real position is how an\n // off-by-one becomes a wrong verdict.\n const firstBefore =\n beforeOrdinals.length > 0 ? Math.min(...beforeOrdinals) : undefined;\n const lastAfter =\n afterOrdinals.length > 0 ? Math.max(...afterOrdinals) : undefined;\n\n // Neither happened: the ordering claim has nothing to bite on. That is a\n // pass, not a silent one — a suite that wants the calls to happen at all\n // says so with tool-usage, which is the grader for that question.\n if (firstBefore === undefined && lastAfter === undefined) return pass;\n\n if (lastAfter === undefined) {\n return fail(\n plan,\n `${describe(after, afterMatch)} was never used, so it could not follow ${describe(before, beforeMatch)}`,\n );\n }\n if (firstBefore === undefined) {\n return fail(\n plan,\n `${describe(after, afterMatch)} was used without ${describe(before, beforeMatch)} ever being used first`,\n );\n }\n if (firstBefore > lastAfter) {\n return fail(\n plan,\n `${describe(before, beforeMatch)} was only used after ${describe(after, afterMatch)}`,\n );\n }\n return pass;\n },\n};\n","/** skill-invoked: assert a skill was invoked (or not) during the session. */\nimport type { TraceGrader } from \"./types.js\";\nimport { evaluateWhen, skippedTrigger, validateWhen } from \"./when.js\";\nimport {\n fail,\n firstError,\n optionalEnum,\n optionsError,\n pass,\n requiredString,\n skippedWindow,\n windowFor,\n type Options,\n} from \"./util.js\";\n\nfunction validateOptions(options: Options): string | undefined {\n return firstError(\n requiredString(options, \"skill\"),\n optionalEnum(options, \"expect\", [\"used\", \"not-used\"]),\n validateWhen(options),\n );\n}\n\nexport const skillInvokedGrader: TraceGrader = {\n kind: \"skill-invoked\",\n validateOptions,\n grade({ trace, plan }) {\n const options = plan.options ?? {};\n const invalid = validateOptions(options);\n if (invalid !== undefined) return optionsError(\"skill-invoked\", invalid);\n const skill = options.skill as string;\n const expect = (options.expect as string | undefined) ?? \"used\";\n const window = windowFor(trace, plan);\n // No evidence at all outranks \"the trigger did not fire\", so the empty\n // window is reported first and with its own reason (ADR 01015).\n if (window.empty) return skippedWindow(window);\n // A trigger that never armed has not been satisfied: skipped, never a\n // pass (ADR 01016).\n const trigger = evaluateWhen(options, window);\n if (!trigger.armed) return skippedTrigger(trigger);\n const used = window.skillInvocations.some((s) => s.name === skill);\n\n if (expect === \"used\" && !used) {\n return fail(plan, `skill ${skill} was never invoked`);\n }\n if (expect === \"not-used\" && used) {\n return fail(plan, `skill ${skill} was invoked but must not be`);\n }\n return pass;\n },\n};\n","/** file-access: assert a file was read/written/edited (or not) in the session. */\nimport type { TraceGrader } from \"./types.js\";\nimport { matchesGlob } from \"./glob.js\";\nimport { evaluateWhen, skippedTrigger, validateWhen } from \"./when.js\";\nimport {\n fail,\n firstError,\n optionalEnum,\n optionsError,\n pass,\n requiredString,\n skippedWindow,\n windowFor,\n type Options,\n} from \"./util.js\";\n\n/** Mirrors FileAccess[\"op\"] in the normalized trace model. */\nconst OPS = [\"read\", \"write\", \"edit\"] as const;\n\nfunction validateOptions(options: Options): string | undefined {\n return firstError(\n requiredString(options, \"path\"),\n optionalEnum(options, \"op\", OPS),\n optionalEnum(options, \"expect\", [\"accessed\", \"not-accessed\"]),\n validateWhen(options),\n );\n}\n\n/**\n * Match a spec against an access, through the one matcher `glob.ts` already\n * documents: separators normalized, case folded, **anchored at a path segment\n * boundary**.\n *\n * A plain `endsWith` was neither of the last two: `db/migrations` also matched\n * `.../legacydb/migrations`, which is a different directory, and the eval read\n * as covering a path it had never been pointed at. A literal path carries no\n * glob metacharacters, so compiling it here resolves to exactly the anchored\n * suffix the docs promise — and a spec that *does* carry `*` or `**` now means\n * here what it means in `options.when`, rather than being taken literally.\n */\nfunction matches(accessPath: string, spec: string): boolean {\n return matchesGlob(accessPath, spec);\n}\n\nexport const fileAccessGrader: TraceGrader = {\n kind: \"file-access\",\n validateOptions,\n grade({ trace, plan }) {\n const options = plan.options ?? {};\n const invalid = validateOptions(options);\n if (invalid !== undefined) return optionsError(\"file-access\", invalid);\n const path = options.path as string;\n const op = options.op as string | undefined;\n const expect = (options.expect as string | undefined) ?? \"accessed\";\n\n const window = windowFor(trace, plan);\n if (window.empty) return skippedWindow(window);\n const trigger = evaluateWhen(options, window);\n if (!trigger.armed) return skippedTrigger(trigger);\n const accessed = window.fileAccesses.some(\n (a) => matches(a.path, path) && (op === undefined || a.op === op),\n );\n\n const opLabel = op ?? \"any\";\n if (expect === \"accessed\" && !accessed) {\n return fail(plan, `file ${path} was never accessed (op: ${opLabel})`);\n }\n if (expect === \"not-accessed\" && accessed) {\n return fail(plan, `file ${path} was accessed (op: ${opLabel}) but must not be`);\n }\n return pass;\n },\n};\n","/** turn-count: assert the session stayed within turn bounds. */\nimport type { TraceGrader } from \"./types.js\";\nimport { evaluateWhen, skippedTrigger, validateWhen } from \"./when.js\";\nimport {\n fail,\n firstError,\n optionalNumber,\n optionsError,\n orderedBounds,\n pass,\n requireOneOf,\n skippedWindow,\n windowFor,\n type Options,\n} from \"./util.js\";\n\nfunction validateOptions(options: Options): string | undefined {\n return firstError(\n requireOneOf(options, [\"min\", \"max\"]),\n optionalNumber(options, \"min\", { min: 0, integer: true }),\n optionalNumber(options, \"max\", { min: 0, integer: true }),\n orderedBounds(options, \"min\", \"max\"),\n validateWhen(options),\n );\n}\n\nexport const turnCountGrader: TraceGrader = {\n kind: \"turn-count\",\n validateOptions,\n grade({ trace, plan }) {\n const options = plan.options ?? {};\n const invalid = validateOptions(options);\n if (invalid !== undefined) return optionsError(\"turn-count\", invalid);\n const window = windowFor(trace, plan);\n if (window.empty) return skippedWindow(window);\n const trigger = evaluateWhen(options, window);\n if (!trigger.armed) return skippedTrigger(trigger);\n const { turnCount } = window;\n if (typeof options.max === \"number\" && turnCount > options.max) {\n return fail(plan, `${turnCount} turn(s); at most ${options.max} allowed`);\n }\n if (typeof options.min === \"number\" && turnCount < options.min) {\n return fail(plan, `${turnCount} turn(s); at least ${options.min} required`);\n }\n return pass;\n },\n};\n","/**\n * cost: assert the session stayed within cost/token budgets.\n *\n * Deliberately **not** windowed (ADR 01015). Every other deterministic grader\n * counts events, which are attributable to the artifact that was governing when\n * they happened; tokens are not. Usage is reported per assistant message for\n * the whole context, so charging a slice of it to one skill would be an\n * invented number. `cost` therefore grades the session no matter which artifact\n * declared it — including one whose window is empty, where a session that blew\n * its budget must still fail rather than quietly skip.\n */\nimport type { TraceGrader } from \"./types.js\";\nimport { rejectWhen } from \"./when.js\";\nimport {\n fail,\n firstError,\n optionalNumber,\n optionsError,\n pass,\n requireOneOf,\n type Options,\n} from \"./util.js\";\n\nfunction validateOptions(options: Options): string | undefined {\n return firstError(\n requireOneOf(options, [\"maxUsd\", \"maxTokens\"]),\n optionalNumber(options, \"maxUsd\", { min: 0 }),\n optionalNumber(options, \"maxTokens\", { min: 0 }),\n rejectWhen(\"cost\", options),\n );\n}\n\nexport const costGrader: TraceGrader = {\n kind: \"cost\",\n validateOptions,\n grade({ trace, plan }) {\n const options = plan.options ?? {};\n const invalid = validateOptions(options);\n if (invalid !== undefined) return optionsError(\"cost\", invalid);\n const usage = trace.usage;\n // Each configured budget is evaluated independently: a missing-data skip on\n // one must not suppress the other. Only skip the whole eval when no\n // configured budget could be checked at all.\n const skips: string[] = [];\n let checked = false;\n\n if (typeof options.maxUsd === \"number\") {\n if (usage?.totalCostUsd === undefined) {\n skips.push(\"no cost data (maxUsd not checkable)\");\n } else {\n checked = true;\n if (usage.totalCostUsd > options.maxUsd) {\n return fail(\n plan,\n `session cost $${usage.totalCostUsd.toFixed(4)}; at most $${options.maxUsd} allowed`,\n );\n }\n }\n }\n\n if (typeof options.maxTokens === \"number\") {\n if (usage === undefined) {\n skips.push(\"no usage data (maxTokens not checkable)\");\n } else {\n checked = true;\n const total = usage.inputTokens + usage.outputTokens;\n if (total > options.maxTokens) {\n return fail(\n plan,\n `session used ${total} tokens; at most ${options.maxTokens} allowed`,\n );\n }\n }\n }\n\n if (!checked && skips.length > 0) {\n return {\n findings: [],\n skipped: `trace carries insufficient cost data: ${skips.join(\"; \")}`,\n };\n }\n return pass;\n },\n};\n","/**\n * `target` — which bytes a grader receives.\n *\n * Distinct from `evidence`, which only hints where to look *within* what is\n * graded, and distinct again from the narrowing options individual graders\n * carry. `regex`'s `on: assistant | user | all` picks a **speaker** inside the\n * transcript; `tool-usage`'s `includeSidechains` picks a **scope**. `target`\n * picks the **subject**: the session, its final answer, the files it wrote, or\n * the instruction artifact itself. The three axes compose rather than replace\n * one another.\n *\n * A target that cannot be served is an explicit failure, never a silent\n * substitution: grading the transcript when the author asked for a written\n * file would report a verdict about the wrong bytes, which is worse than no\n * verdict at all.\n */\nimport { readFileSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport type { Trace } from \"../trace/types.js\";\n\n/** The subject a grader is pointed at. */\nexport type TraceTarget =\n | \"transcript\"\n | \"last-message\"\n | \"files\"\n | \"artifact\"\n | { source: \"file\"; path: string };\n\nexport const DEFAULT_TARGET: TraceTarget = \"transcript\";\n\nexport type TargetResult =\n | { ok: true; text: string; label: string }\n | { ok: false; reason: string };\n\n/** Human-readable name for a target, for messages and report lines. */\nexport function describeTarget(target: TraceTarget | undefined): string {\n const t = target ?? DEFAULT_TARGET;\n return typeof t === \"string\" ? t : `file ${t.path}`;\n}\n\nexport interface TargetContext {\n trace: Trace;\n /** The transcript as the judge would otherwise have seen it. */\n renderedTrace: string;\n /** The instruction artifact this eval came from. */\n artifactContent: string;\n /**\n * Root a relative `{source: file}` target resolves against — the run's\n * project root when one was pinned, else the session's own cwd.\n */\n root: string;\n}\n\n/** Read what `target` selects for this session. */\nexport function readTarget(\n target: TraceTarget | undefined,\n ctx: TargetContext,\n): TargetResult {\n const t = target ?? DEFAULT_TARGET;\n if (t === \"transcript\") {\n return { ok: true, text: ctx.renderedTrace, label: \"transcript\" };\n }\n if (t === \"last-message\") {\n const last = ctx.trace.assistantTexts.at(-1);\n // An empty final message is a fact about the session, not a failure to\n // read it — a run that ended on a tool call genuinely has no final text.\n return { ok: true, text: last ?? \"\", label: \"last-message\" };\n }\n if (t === \"files\") {\n // Paths only, never contents: \"which files did it touch\" is a different\n // question from \"what is in them\", and the second is what a\n // `{source: file}` target is for.\n const paths = [...new Set(ctx.trace.fileAccesses.map((f) => f.path))];\n return { ok: true, text: paths.join(\"\\n\"), label: \"files\" };\n }\n if (t === \"artifact\") {\n return { ok: true, text: ctx.artifactContent, label: \"artifact\" };\n }\n\n if (isAbsolute(t.path)) {\n return {\n ok: false,\n reason: `target file \"${t.path}\" is an absolute path; name it relative to the project root`,\n };\n }\n const abs = resolve(ctx.root, t.path);\n // `startsWith(\"..\")` alone rejects a legitimate file whose name merely\n // begins with two dots — `..rc`, `..config/x` — so the segment has to end\n // there. `isAbsolute` catches the Windows case where the target is on\n // another drive and `relative` cannot express the step at all.\n const rel = relative(ctx.root, abs);\n if (rel === \"..\" || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {\n return {\n ok: false,\n reason: `target file \"${t.path}\" resolves outside the project root`,\n };\n }\n try {\n return { ok: true, text: readFileSync(abs, \"utf8\"), label: `file ${t.path}` };\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code ?? \"unknown error\";\n return { ok: false, reason: `target file \"${t.path}\" could not be read (${code})` };\n }\n}\n","/** regex: assert a pattern does/doesn't appear in session text. */\nimport type { TraceGrader } from \"./types.js\";\nimport { evaluateWhen, skippedTrigger, validateWhen } from \"./when.js\";\nimport {\n fail,\n firstError,\n optionalEnum,\n optionsError,\n pass,\n requiredString,\n skippedWindow,\n windowFor,\n type Options,\n} from \"./util.js\";\nimport { readTarget } from \"../core/target.js\";\n\n/** Flags are checked alone first, so the message names the actual culprit. */\nfunction checkFlags(options: Options): string | undefined {\n const flags = options.flags;\n if (flags === undefined) return undefined;\n if (typeof flags !== \"string\") return \"options.flags must be a string\";\n try {\n new RegExp(\"\", flags);\n } catch (err) {\n return `options.flags is invalid: ${(err as Error).message}`;\n }\n return undefined;\n}\n\n/**\n * Pattern and flags must be validated *together*, exactly as `grade()` builds\n * them: `a{` is legal on its own but not under the `u` flag, so checking them\n * separately would pass options that then throw at grade time.\n */\nfunction checkPattern(options: Options): string | undefined {\n const required = requiredString(options, \"pattern\");\n if (required !== undefined) return required;\n try {\n new RegExp(\n options.pattern as string,\n (options.flags as string | undefined) ?? \"\",\n );\n } catch (err) {\n return `options.pattern is not a valid regular expression: ${(err as Error).message}`;\n }\n return undefined;\n}\n\nfunction validateOptions(options: Options): string | undefined {\n return firstError(\n checkFlags(options),\n checkPattern(options),\n optionalEnum(options, \"on\", [\"assistant\", \"user\", \"all\"]),\n optionalEnum(options, \"expect\", [\"match\", \"no-match\"]),\n validateWhen(options),\n );\n}\n\nexport const regexGrader: TraceGrader = {\n kind: \"regex\",\n validateOptions,\n grade({ trace, plan, projectRoot }) {\n const options = plan.options ?? {};\n const invalid = validateOptions(options);\n if (invalid !== undefined) return optionsError(\"regex\", invalid);\n const pattern = options.pattern as string;\n const re = new RegExp(pattern, (options.flags as string | undefined) ?? \"\");\n const on = (options.on as string | undefined) ?? \"assistant\";\n const expect = (options.expect as string | undefined) ?? \"match\";\n\n const window = windowFor(trace, plan);\n if (window.empty) return skippedWindow(window);\n const trigger = evaluateWhen(options, window);\n if (!trigger.armed) return skippedTrigger(trigger);\n\n // Two axes that compose rather than compete. `target` picks the *subject*\n // — the session, its final answer, the files it wrote, the artifact — and\n // `on` picks the *speaker* within a transcript. Only the transcript has\n // speakers, so `on` applies there and nowhere else. Both read the window\n // this artifact governed (ADR 01015), never the whole session.\n const target = plan.target ?? \"transcript\";\n let corpus: string[];\n let where: string;\n if (target === \"transcript\") {\n corpus =\n on === \"user\"\n ? window.userMessages\n : on === \"all\"\n ? [...window.userMessages, ...window.assistantTexts]\n : window.assistantTexts;\n where = `${on} text`;\n } else {\n const selected = readTarget(target, {\n trace,\n // Never consulted: `transcript` took the branch above.\n renderedTrace: \"\",\n artifactContent: plan.artifact.content,\n root: projectRoot ?? trace.cwd,\n });\n if (!selected.ok) return optionsError(\"regex\", selected.reason);\n corpus = [selected.text];\n where = selected.label;\n }\n const matched = corpus.some((text) => re.test(text));\n\n if (expect === \"match\" && !matched) {\n return fail(plan, `pattern /${pattern}/ never matched ${where}`);\n }\n if (expect === \"no-match\" && matched) {\n return fail(plan, `pattern /${pattern}/ matched ${where} but must not`);\n }\n return pass;\n },\n};\n","/** json-output: validate the session's final assistant text as JSON. */\nimport { Ajv2020 } from \"ajv/dist/2020.js\";\nimport type { ValidateFunction } from \"ajv\";\nimport type { TraceGrader } from \"./types.js\";\nimport { rejectWhen } from \"./when.js\";\nimport { fail, finding, optionsError, pass } from \"./util.js\";\n\n/**\n * One Ajv instance per compile, keyed by the schema's own text.\n *\n * A shared instance keeps every `$id` it has seen, so a schema declaring one\n * compiles on the first trace and throws `schema with key or id \"…\" already\n * exists` on traces 2..N — erroring every trace after the first in a batch run\n * or a `calibrate` sweep, for a schema that was correct all along. Keying the\n * cache on the schema *content* means an identical schema compiles once and a\n * different one gets a clean registry, which is the property `$id` reuse\n * actually needs.\n */\nconst compiled = new Map<string, ValidateFunction>();\n\nfunction compileSchema(schema: Record<string, unknown>): ValidateFunction {\n const key = JSON.stringify(schema);\n const hit = compiled.get(key);\n if (hit !== undefined) return hit;\n const built = new Ajv2020({ allErrors: true, strict: false }).compile(schema);\n compiled.set(key, built);\n return built;\n}\n\n/**\n * Shape-only. Compiling here as well would double the work for an option set\n * that `grade()` compiles anyway, and a schema that fails to compile is a\n * grade-time `error` with the compiler's own message.\n */\nfunction validateOptions(options: Record<string, unknown>): string | undefined {\n const schema = options.schema;\n if (\n schema === undefined ||\n schema === null ||\n typeof schema !== \"object\" ||\n Array.isArray(schema)\n ) {\n return \"options.schema is required and must be a JSON Schema object\";\n }\n return rejectWhen(\"json-output\", options);\n}\n\nexport const jsonOutputGrader: TraceGrader = {\n kind: \"json-output\",\n validateOptions,\n grade({ trace, plan }) {\n const options = plan.options ?? {};\n const invalid = validateOptions(options);\n if (invalid !== undefined) return optionsError(\"json-output\", invalid);\n const schema = options.schema;\n\n const last = trace.assistantTexts.at(-1);\n if (last === undefined) {\n return fail(plan, \"session produced no assistant text to validate\");\n }\n let data: unknown;\n try {\n data = JSON.parse(last);\n } catch {\n return fail(plan, \"final assistant output is not valid JSON\");\n }\n\n let validate: ValidateFunction;\n try {\n validate = compileSchema(schema as Record<string, unknown>);\n } catch (err) {\n return optionsError(\n \"json-output\",\n `schema failed to compile: ${(err as Error).message}`,\n );\n }\n if (validate(data)) return pass;\n return {\n findings: (validate.errors ?? []).map((e) =>\n finding(plan, `${e.instancePath || \"/\"} ${e.message ?? \"invalid\"}`),\n ),\n };\n },\n};\n","/**\n * Command-graded evals: run an executable over the trace and read its exit\n * code (ADR 01011).\n *\n * This grader executes a program named in an artifact's front matter, and\n * artifacts are resolved from the trace's own project tree — so running an\n * eval over someone else's trace can run code that repository declares. That\n * is the documented behavior, not an oversight. The engine runs it only under\n * the `frontmatter-commands` execution grant, which every run holds unless the\n * operator narrows it (proposal 0075). Two properties bound it:\n *\n * - argv is passed as an array with `shell: false`, so nothing in an artifact\n * is ever parsed as shell syntax — no pipes, redirects, or `$(...)`.\n * - `timeout-ms` always has a finite value, so a hung check fails the eval\n * rather than the run.\n *\n * `{trace}` is substituted in every argv element (the artifact-side analog of\n * the page side's `{file}`).\n */\nimport { createHash } from \"node:crypto\";\nimport { realExec } from \"../../shared/exec.js\";\nimport type { GradeResult, TraceGrader, TraceGraderContext } from \"./types.js\";\n\n/** Bounded by default: a check with no stated timeout still cannot hang. */\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\n/** Enough stderr to diagnose a failure without pasting a log into a report. */\nconst STDERR_LIMIT = 2000;\n\n/**\n * Deliberately no `validateOptions`. This grader takes no `options`: its whole\n * configuration is the entry's own `command` family, whose shape and guard\n * rails the schema already pins. Omitting the hook is also what keeps `fill`\n * from ever proposing a command grader — \"a kind without it cannot be\n * proposed\" is the registry's existing contract (ADR 01004).\n */\nexport const commandGrader: TraceGrader = {\n kind: \"command\",\n\n async grade(ctx: TraceGraderContext): Promise<GradeResult> {\n const { plan, trace } = ctx;\n\n if (!plan.command || plan.command.length === 0) {\n // The schema permits `grader: command` with no command: it is the\n // generation contract's first state, where tooling is expected to write\n // a check script back. This tool generates nothing, and an eval that\n // cannot run must not read as a pass.\n return {\n findings: [],\n error:\n \"command-graded eval has no `command`; add one (or remove the eval) — manni tracevals does not generate check scripts\",\n };\n }\n\n if (plan.generatedAssertionHash !== undefined) {\n // A hash without an assertion is a half write-back: the hash exists to\n // detect that the assertion it was generated from has changed, and with\n // no assertion there is nothing it could be checked against. Reporting\n // it beats hashing the empty string and passing.\n if (plan.assertion === undefined) {\n return {\n findings: [],\n error:\n \"generated-assertion-hash is present but the eval has no assertion, \" +\n \"so the hash cannot be checked against anything; remove the hash or restore the assertion\",\n };\n }\n const actual = createHash(\"sha256\").update(plan.assertion).digest(\"hex\");\n if (actual !== plan.generatedAssertionHash) {\n return {\n findings: [],\n error:\n \"assertion has changed since the command was generated \" +\n `(generated-assertion-hash ${plan.generatedAssertionHash.slice(0, 12)}…, ` +\n `assertion now hashes to ${actual.slice(0, 12)}…); regenerate the command or update the hash`,\n };\n }\n }\n\n const argv = plan.command.map((part) => part.replaceAll(\"{trace}\", trace.file));\n const timeoutMs = plan.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const successCodes = plan.successExitCodes ?? [0];\n\n const run = await execute(argv, ctx.projectRoot ?? trace.cwd, timeoutMs);\n\n if (run.timedOut) {\n return {\n findings: [],\n error: `command timed out after ${timeoutMs}ms: ${argv.join(\" \")}`,\n };\n }\n if (run.spawnError !== undefined) {\n return { findings: [], error: `could not run command: ${run.spawnError}` };\n }\n if (run.code !== null && successCodes.includes(run.code)) {\n return { findings: [] };\n }\n\n const detail = run.stderr.trim();\n return {\n findings: [\n {\n evalName: plan.evalName,\n artifact: plan.artifact.path,\n severity: plan.severity,\n message:\n `command exited ${run.code ?? \"on a signal\"} ` +\n `(expected ${successCodes.join(\" or \")})` +\n (detail ? `: ${detail.slice(0, STDERR_LIMIT)}` : \"\"),\n },\n ],\n };\n },\n};\n\n/**\n * One run of the check, through the family's exec wrapper (`src/shared/exec.ts`),\n * the one `manni docevals` runs its command evals through. It spawns argv as\n * an array without a shell, resolves npm `.cmd` shims on Windows, and settles\n * on the timeout itself rather than waiting for a child that ignores it.\n */\nasync function execute(\n argv: string[],\n cwd: string,\n timeoutMs: number,\n): Promise<Execution> {\n const result = await realExec(argv, { cwd, timeoutMs });\n return {\n code: result.code,\n // Capped here, not merely when printed: a check script can write far more\n // to stderr than a report should carry.\n stderr: result.stderr.slice(0, STDERR_LIMIT),\n timedOut: result.timedOut,\n ...(result.spawnError === undefined ? {} : { spawnError: result.spawnError }),\n };\n}\n\ninterface Execution {\n code: number | null;\n stderr: string;\n timedOut: boolean;\n spawnError?: string;\n}\n","/**\n * Process execution for every grader in the family that runs a program. The\n * implementation lives in `@hawkeyexl/inference`: the judge's subprocess\n * provider and the command graders were running copies of the same\n * cross-spawn wrapper, and the Windows-specific parts (npm `.cmd` shim\n * resolution without `shell: true`, stdin piping past the ~32K command-line\n * limit, and StringDecoder-backed output so multi-byte UTF-8 survives chunk\n * boundaries) are exactly the parts worth having in one place.\n *\n * Shared rather than per domain: `manni docevals` and `manni tracevals` both\n * run `command` evals, and both reach the OS through this one wrapper.\n */\nimport type { ExecResult } from \"@hawkeyexl/inference\";\n\nexport { realExec } from \"@hawkeyexl/inference\";\n\n/** Truncate command output for finding messages. */\nexport function outputTail(result: ExecResult, maxChars = 400): string {\n const text = (result.stderr.trim() || result.stdout.trim()).trim();\n if (text.length <= maxChars) return text;\n return `…${text.slice(-maxChars)}`;\n}\n\n/**\n * How a finished process is described in a finding: \"exited 2\", or the truth\n * when there was no exit code.\n *\n * `code` is null when the process was killed by a signal rather than exiting.\n * \"exited null\" describes nothing a reader can act on, and it is the case a\n * timeout produces — so it is the one worth naming.\n */\nexport function exited(code: number | null): string {\n return code === null ? \"was killed before exiting\" : `exited ${code}`;\n}\n","/** Grader registry: static built-ins plus consumer-registered kinds. */\nimport type { TraceGrader } from \"./types.js\";\nimport { toolUsageGrader } from \"./tool-usage.js\";\nimport { toolOrderGrader } from \"./tool-order.js\";\nimport { skillInvokedGrader } from \"./skill-invoked.js\";\nimport { fileAccessGrader } from \"./file-access.js\";\nimport { turnCountGrader } from \"./turn-count.js\";\nimport { costGrader } from \"./cost.js\";\nimport { regexGrader } from \"./regex.js\";\nimport { jsonOutputGrader } from \"./json-output.js\";\nimport { commandGrader } from \"./command.js\";\n\nconst graders = new Map<string, TraceGrader>(\n [\n toolUsageGrader,\n toolOrderGrader,\n skillInvokedGrader,\n fileAccessGrader,\n turnCountGrader,\n costGrader,\n regexGrader,\n jsonOutputGrader,\n commandGrader,\n ].map((g) => [g.kind, g]),\n);\n\n/**\n * The kinds this package ships, frozen before anything can register over them.\n * Plugin loading (ADR 01017) reads it to tell \"a plugin added a kind\" from\n * \"a plugin took over a built-in\" — the second silently changes what every\n * eval declaring that kind means, including evals the plugin's author does not\n * own, so it has to be said out loud.\n */\nexport const BUILTIN_GRADER_KINDS: ReadonlySet<string> = new Set(graders.keys());\n\nexport function registerGrader(grader: TraceGrader): void {\n graders.set(grader.kind, grader);\n}\n\nexport function graderFor(kind: string): TraceGrader | undefined {\n return graders.get(kind);\n}\n\nexport function listGraderKinds(): string[] {\n return [...graders.keys()];\n}\n","/**\n * Render a trace into judge-readable text. Session files can be tens of MB,\n * so every block is capped and the whole digest is bounded by a head/tail\n * window — the opening (instructions, intent) and the ending (outcome) matter\n * most for adherence judging.\n *\n * Given an eval plan, only the turns that plan's artifact was governing are\n * rendered (ADR 01015). That is both the correct evidence to judge against and\n * a large cut in tokens: a skill's window is usually a fraction of a session.\n *\n * This is also the only place trace content is turned into text bound for a\n * third-party API, so it is where redaction happens (ADR 01020). Every block is\n * scrubbed *before* it is clipped, so truncation can never bisect a secret and\n * leave a usable prefix behind.\n */\nimport type { Trace, TraceEvent } from \"../trace/types.js\";\nimport type { EvalPlan } from \"../core/plan.js\";\nimport { windowFor } from \"../graders/util.js\";\nimport { makeRedactor } from \"./redact.js\";\n\nexport interface RenderOptions {\n /** Per-block character cap (messages, tool inputs). */\n maxBlockChars?: number;\n /** Whole-digest character cap; overflow keeps head and tail. */\n maxTotalChars?: number;\n /**\n * Extra redaction patterns, applied on top of the built-in shapes rather\n * than instead of them. Sources are compiled with the `g` flag.\n */\n redact?: string[];\n}\n\nconst DEFAULTS: Required<RenderOptions> = {\n maxBlockChars: 2_000,\n maxTotalChars: 150_000,\n redact: [],\n};\n\n/**\n * The smallest timeline the head/tail window will ever leave.\n *\n * The cap used to be skipped outright when the header grew past it — the guard\n * was `budget > 0`, so a non-positive budget *disabled* truncation and shipped\n * the entire unclipped transcript to a third-party provider, precisely when the\n * user had asked for the tightest cap. A floor keeps truncation running; the\n * header is bounded separately so the whole digest still honours the cap.\n */\nconst MIN_TIMELINE_CHARS = 200;\n\nconst HEADER_TRUNCATED = \"\\n[... header truncated ...]\";\nconst TIMELINE_SHELL = \"\\n\\n## Timeline\\n\";\n\nexport function renderTrace(\n trace: Trace,\n options: RenderOptions = {},\n plan?: EvalPlan,\n): string {\n const { maxBlockChars, maxTotalChars, redact } = { ...DEFAULTS, ...options };\n const scrub = makeRedactor(redact);\n // Redact, then truncate. The other order would let a cap land mid-secret and\n // ship the surviving prefix.\n const clip = (text: string, max: number): string => {\n const safe = scrub(text);\n if (safe.length <= max) return safe;\n return `${safe.slice(0, max)} [... truncated ${safe.length - max} chars ...]`;\n };\n const window = plan === undefined ? undefined : windowFor(trace, plan);\n // Project rules govern the whole session, so their digest is the session's —\n // byte-identical to an unscoped render, and cached as such.\n const scoped =\n window !== undefined && window.scope !== \"session\" ? window : undefined;\n const events: TraceEvent[] = scoped?.events ?? trace.events;\n\n // Scrubbed too: `cwd` and a branch name are author-supplied strings, and the\n // header is as much a thing that leaves the machine as the timeline is.\n const fullHeader = scrub(\n [\n \"# Session\",\n `source: ${trace.source}`,\n trace.model ? `model: ${trace.model}` : undefined,\n `cwd: ${trace.cwd}`,\n trace.gitBranch ? `branch: ${trace.gitBranch}` : undefined,\n scoped\n ? `scope: ${scoped.label} — ${events.length} of ${trace.events.length} session events`\n : undefined,\n // Everything below describes what the judge can actually see. On a\n // scoped render the timeline is the window, so a session-wide count here\n // reads as evidence that the rest was truncated away — the judge would\n // discount a digest that is complete for what it was asked about. The\n // session totals stay, in parentheses, because \"3 of 87\" is context the\n // window count alone does not carry.\n scoped\n ? `turns: ${scoped.turnCount} (of ${trace.turnCount} in the session)`\n : `turns: ${trace.turnCount}`,\n ((): string => {\n const used = (scoped ?? trace).skillInvocations.map((s) => s.name);\n return used.length > 0\n ? `skills used: ${used.join(\", \")}`\n : \"skills used: none\";\n })(),\n ((): string | undefined => {\n // Spawns and branches inside the window only: an agent the parent\n // session started after this skill handed over is not this artifact's\n // to answer for.\n const inWindow = new Set(events.map((e) => e.index));\n const spawns = trace.agentSpawns.filter(\n (a) => !scoped || inWindow.has(a.index),\n );\n return spawns.length > 0\n ? `agents spawned: ${spawns.map((a) => a.subagentType).join(\", \")}`\n : undefined;\n })(),\n ((): string | undefined => {\n const inWindow = new Set(events.map((e) => e.index));\n const branches = trace.subagentBranches.filter(\n (b) => !scoped || inWindow.has(b.spawnIndex),\n );\n return branches.length > 0\n ? `subagent transcripts: ${branches\n .map((b) => `${b.agentType} (depth ${b.spawnDepth})`)\n .join(\", \")}`\n : undefined;\n })(),\n ]\n .filter((line): line is string => line !== undefined)\n .join(\"\\n\"),\n );\n\n // The header lists every skill name, agent type and branch, so on a busy\n // session it can outgrow a tight cap on its own. Bound it first, leaving the\n // timeline its floor, so `maxTotalChars` stays a cap on the whole digest\n // rather than on one half of it.\n const headerRoom = Math.max(\n maxTotalChars - TIMELINE_SHELL.length - MIN_TIMELINE_CHARS,\n 0,\n );\n const header =\n fullHeader.length <= headerRoom\n ? fullHeader\n : fullHeader.slice(\n 0,\n Math.max(headerRoom - HEADER_TRUNCATED.length, 0),\n ) + HEADER_TRUNCATED;\n\n // Two concurrent subagents are indistinguishable under a flat `:sidechain`\n // tag, so each branch becomes a labelled block named for the subagent that\n // ran it. The header can fall outside the head/tail window below, so every\n // line keeps a short tag of its own as well. Inline and sidecar branches\n // render through this one path; a sidecar branch is named by its meta file's\n // `agentType`, which is the recorder's own statement of what ran.\n const branchTypes = new Map<string, string>();\n for (const spawn of trace.agentSpawns) {\n if (spawn.toolUseId) branchTypes.set(spawn.toolUseId, spawn.subagentType);\n }\n for (const branch of trace.subagentBranches) {\n branchTypes.set(branch.branchId, branch.agentType);\n }\n const label = (branchId: string): string =>\n branchTypes.get(branchId) ?? branchId;\n const callAt = new Map(trace.toolCalls.map((call) => [call.index, call]));\n\n if (scoped?.empty === true) {\n return `${header}${TIMELINE_SHELL}[no turns: ${scrub(scoped.reason ?? \"\")}]`;\n }\n\n const lines: string[] = [];\n let branch: string | undefined;\n for (const event of events) {\n const tag = event.branchId\n ? `:${label(event.branchId)}`\n : event.sidechain\n ? \":sidechain\"\n : \"\";\n let line: string | undefined;\n switch (event.kind) {\n case \"user\":\n if (event.text) line = `[user${tag}] ${clip(event.text, maxBlockChars)}`;\n break;\n case \"assistant\":\n if (event.text) {\n line = `[assistant${tag}] ${clip(event.text, maxBlockChars)}`;\n }\n break;\n case \"tool_call\": {\n const call = callAt.get(event.index);\n const input = call ? JSON.stringify(call.input) : \"\";\n line = `[tool${tag}] ${event.toolName ?? call?.name ?? \"?\"} ${clip(input, Math.min(maxBlockChars, 500))}`;\n break;\n }\n default:\n break;\n }\n if (line === undefined) continue;\n if (event.branchId !== branch) {\n if (branch !== undefined) lines.push(`[/subagent ${label(branch)}]`);\n branch = event.branchId;\n if (branch !== undefined) {\n lines.push(`[subagent ${label(branch)} (${branch})]`);\n }\n }\n lines.push(line);\n }\n if (branch !== undefined) lines.push(`[/subagent ${label(branch)}]`);\n\n // One more pass over the assembled timeline. Every message and tool input\n // already went through `clip`, so this pass is the belt to that pair of\n // braces: it covers what is assembled here rather than clipped — tool names,\n // branch labels — and anything a later change adds to this loop without\n // remembering to scrub it. Redaction is idempotent, so it costs nothing.\n let timeline = scrub(lines.join(\"\\n\"));\n // A floor, never a switch: `budget > 0` used to turn truncation *off* for a\n // non-positive budget, which is the one case where it matters most.\n const budget = Math.max(\n maxTotalChars - header.length - TIMELINE_SHELL.length,\n MIN_TIMELINE_CHARS,\n );\n if (timeline.length > budget) {\n // The marker counts against the budget, so the digest never exceeds what\n // the caller asked for. `omitted` is at most `timeline.length`, so the\n // width reserved for it is always enough.\n const marker = (omitted: number): string =>\n `\\n[... truncated ${omitted} chars of transcript ...]\\n`;\n const room = Math.max(budget - marker(timeline.length).length, 0);\n const headLen = Math.floor(room * 0.6);\n const tailLen = room - headLen;\n const omitted = timeline.length - headLen - tailLen;\n timeline = `${timeline.slice(0, headLen)}${marker(omitted)}${\n tailLen > 0 ? timeline.slice(-tailLen) : \"\"\n }`;\n }\n\n return `${header}${TIMELINE_SHELL}${timeline}`;\n}\n","/**\n * Orchestration: parse trace → resolve artifacts → plan evals → deterministic\n * graders → AI judge → aggregate. The judge is injectable so the engine\n * tests fully offline.\n */\nimport { NOT_GRANTED_REASON } from \"../../shared/execution.js\";\nimport { parseTraceFile } from \"../trace/claude.js\";\nimport { resolveArtifacts } from \"../artifacts/resolve.js\";\nimport { findManifest, type FoundManifest } from \"../capture/manifest.js\";\nimport { TracevalsError } from \"../types.js\";\nimport type { CoverageEntry, ResolvedArtifact } from \"../artifacts/types.js\";\nimport { classifyRef } from \"../../meta/index.js\";\nimport { normalizeRoot, toPosix, underRoot } from \"../../shared/sarif-location.js\";\nimport type { ManifestReport } from \"../capture/types.js\";\nimport {\n planEvals,\n type ArtifactMetadataLoader,\n type EvalLocation,\n type EvalPlan,\n type SuppliedMetadata,\n} from \"./plan.js\";\nimport { MAX_ARTIFACT_CHARS, artifactWasTruncated } from \"../judge/prompt.js\";\nimport { graderFor, listGraderKinds } from \"../graders/registry.js\";\nimport { windowFor } from \"../graders/util.js\";\nimport { renderTrace } from \"../judge/render.js\";\nimport type { TraceJudge } from \"../judge/trace-judge.js\";\nimport type { TracevalsConfig } from \"./config.js\";\nimport type { EvalResult, RunReport, RunSummary } from \"../types.js\";\n\nexport interface EngineOptions {\n tracePath: string;\n /** Artifact-lookup override; when set it is also the parent-walk ceiling. */\n projectDir?: string;\n env?: Record<string, string | undefined>;\n config: TracevalsConfig;\n /** Injected judge; required unless deterministicOnly. */\n judge?: TraceJudge;\n deterministicOnly?: boolean;\n /**\n * An explicitly named session manifest (ADR 01024). Without it the engine\n * looks in the conventional places and degrades silently when there is none;\n * with it, a manifest that cannot be used is an error rather than a shrug.\n */\n manifest?: string;\n /**\n * Warnings raised before the engine ran — grader-plugin loading is the one\n * source today. They belong in the report because they change how a verdict\n * should be read, and they happened first, so they lead the list.\n */\n warnings?: string[];\n /**\n * Where each artifact's `metadata` block lives (`evals/external.ts`). A\n * relocated artifact keeps its evals, its `eval-skip` and its\n * `meta-provenance` in a collection's manifest, and without this the run\n * would grade it as declaring nothing at all. Absent when no collection\n * declares a manifest that owns `metadata`.\n */\n metadataFor?: ArtifactMetadataLoader;\n}\n\nexport async function runEvals(options: EngineOptions): Promise<RunReport> {\n const start = Date.now();\n const { config } = options;\n\n const trace = await parseTraceFile(options.tracePath);\n\n // Read-only, and optional. A manifest sharpens staleness for the artifacts it\n // recorded (ADR 01024); an absent one leaves the mtime heuristic exactly as\n // ADR 01021 shipped it, and every hash check reports `skipped` with a reason.\n const refusals: { path: string; reason: string }[] = [];\n const found = await findManifest({\n tracePath: options.tracePath,\n ...(trace.sessionId !== undefined ? { sessionId: trace.sessionId } : {}),\n projectDir: options.projectDir ?? trace.cwd,\n captureDir: config.capture.dir,\n ...(options.manifest !== undefined ? { explicit: options.manifest } : {}),\n onRefused: (path, reason) => refusals.push({ path, reason }),\n });\n if (found === null && options.manifest !== undefined) {\n // An explicitly named manifest that is not there is a mistake, not a\n // degradation: the caller asked for exactness and did not get it.\n throw new TracevalsError(\n `no usable session manifest at ${options.manifest} — ${\n refusals[0]?.reason ??\n \"it is missing, unreadable, or was recorded for a different session\"\n }`,\n );\n }\n // A manifest that was found and then refused is a different situation from\n // no manifest at all, and an unexplained fallback to the mtime guess gives a\n // reader no way to tell them apart. Name the file, and say why.\n const manifestWarnings =\n found === null\n ? refusals.map(\n (r) => `ignoring the session manifest at ${r.path} — ${r.reason}`,\n )\n : [];\n\n const resolved = await resolveArtifacts(trace, {\n ...(options.projectDir !== undefined\n ? { projectDir: options.projectDir, projectRoot: options.projectDir }\n : {}),\n ...(options.env !== undefined ? { env: options.env } : {}),\n reportUnusedArtifacts: config.reportUnusedArtifacts,\n ...(found !== null ? { manifest: found.manifest } : {}),\n });\n // Read before planning, because planning is synchronous and reading a\n // manifest is not.\n const loader = options.metadataFor;\n const metadata = new Map<ResolvedArtifact, SuppliedMetadata | undefined>();\n if (loader !== undefined) {\n for (const artifact of resolved.artifacts) {\n metadata.set(artifact, await loader(artifact));\n }\n }\n const plans = planEvals(\n resolved.artifacts,\n loader === undefined ? undefined : (artifact) => metadata.get(artifact),\n );\n\n const results: EvalResult[] = [];\n const aiPlans: EvalPlan[] = [];\n\n const root = normalizeRoot(process.cwd());\n for (const plan of plans) {\n const base = {\n evalName: plan.evalName,\n artifact: plan.artifact.path,\n artifactName: plan.artifact.name,\n artifactType: plan.artifact.type,\n grader: plan.grader,\n implicit: plan.implicit,\n location: spelled(plan.location, root),\n };\n\n if (plan.error !== undefined) {\n results.push({ ...base, outcome: \"error\", error: plan.error, durationMs: 0 });\n continue;\n }\n if (plan.skipped) {\n results.push({\n ...base,\n outcome: \"skipped\",\n skipReason: plan.skipReason ?? \"eval skipped\",\n durationMs: 0,\n });\n continue;\n }\n // An artifact that governed no turn in this trace grades nothing. Saying\n // so is the only honest outcome: a judge handed an empty window would\n // answer about the parent session's work, and a `human` reviewer would be\n // queued to review nothing (ADR 01015). Deterministic graders make the\n // same call for themselves, since only they know whether they are windowed.\n if (plan.grader === \"ai\" || plan.grader === \"human\") {\n const window = windowFor(trace, plan);\n if (window.empty) {\n results.push({\n ...base,\n outcome: \"skipped\",\n skipReason: window.reason ?? \"the artifact governed no turns\",\n durationMs: 0,\n });\n continue;\n }\n }\n if (plan.grader === \"ai\") {\n aiPlans.push(plan);\n continue;\n }\n // `human` is judged per session: every trace is new, so unlike the page\n // side there is no verdict to cache and nothing to defer to a later run.\n // It reports in deterministic-only runs too — a review queue is not an\n // inference call.\n if (plan.grader === \"human\") {\n results.push({\n ...base,\n outcome: \"needs-review\",\n skipReason: \"awaiting human review\",\n durationMs: 0,\n });\n continue;\n }\n\n // The one grader that executes something. On by default, and narrowed by\n // the operator's grants (proposal 0075). An ungranted check is `skipped`\n // with a reason, never `pass`: an unrun check has not been satisfied.\n if (\n plan.grader === \"command\" &&\n !config.execution.allow.includes(\"frontmatter-commands\")\n ) {\n results.push({\n ...base,\n outcome: \"skipped\",\n skipReason: NOT_GRANTED_REASON,\n durationMs: 0,\n });\n continue;\n }\n\n const grader = graderFor(plan.grader);\n if (!grader) {\n // The grader vocabulary is an open enum: any kebab name validates, and\n // the registry is the authority that rejects it. This is where a stale\n // `llm` — the pre-1.0 spelling of `ai` — surfaces.\n results.push({\n ...base,\n outcome: \"error\",\n error: `unknown grader kind \"${plan.grader}\"; the grader registry knows ${listGraderKinds().sort().join(\", \")}, \"ai\", and \"human\"`,\n durationMs: 0,\n });\n continue;\n }\n const graded = Date.now();\n // A grader that throws must fail its own eval, not the whole run: one\n // malformed eval should never cost the report every other verdict.\n let result;\n try {\n result = await grader.grade({\n trace,\n plan,\n ...(options.projectDir !== undefined\n ? { projectRoot: options.projectDir }\n : {}),\n });\n } catch (err) {\n results.push({\n ...base,\n outcome: \"error\",\n error: `${plan.grader}: ${err instanceof Error ? err.message : String(err)}`,\n durationMs: Date.now() - graded,\n });\n continue;\n }\n if (result.error !== undefined) {\n results.push({\n ...base,\n outcome: \"error\",\n error: result.error,\n durationMs: Date.now() - graded,\n });\n continue;\n }\n if (result.skipped !== undefined) {\n results.push({\n ...base,\n outcome: \"skipped\",\n skipReason: result.skipped,\n durationMs: Date.now() - graded,\n });\n continue;\n }\n // Deterministic evals fail only on error-severity findings; warning and\n // notice findings report but pass.\n const failing = result.findings.some((f) => f.severity === \"error\");\n results.push({\n ...base,\n outcome: failing ? \"fail\" : \"pass\",\n findings: result.findings,\n durationMs: Date.now() - graded,\n });\n }\n\n if (aiPlans.length > 0) {\n if (options.deterministicOnly || options.judge === undefined) {\n const skipReason = options.deterministicOnly\n ? \"ai evals skipped (deterministic-only run)\"\n : \"ai evals skipped (no judge provided)\";\n for (const plan of aiPlans) {\n results.push({\n evalName: plan.evalName,\n artifact: plan.artifact.path,\n artifactName: plan.artifact.name,\n artifactType: plan.artifact.type,\n grader: plan.grader,\n implicit: plan.implicit,\n location: spelled(plan.location, root),\n outcome: \"skipped\",\n skipReason,\n durationMs: 0,\n });\n }\n } else {\n // `judge.redact` rides along with the render caps: the digest is the one\n // thing that leaves the machine, so its size limits and its redaction\n // list are decided in the same place (ADR 01020).\n const judged = await options.judge(\n aiPlans,\n (plan) =>\n renderTrace(\n trace,\n { ...config.render, redact: config.judge.redact },\n plan,\n ),\n {\n trace,\n ...(options.projectDir !== undefined\n ? { projectRoot: options.projectDir }\n : {}),\n },\n );\n // One result per plan, in order: that is the TraceJudge contract. The\n // `?? \"skill\"` below satisfies noUncheckedIndexedAccess; it is not a\n // fallback for a judge that returned a different count.\n judged.forEach((j, i) => {\n const plan = aiPlans[i];\n results.push({\n ...(j.selfPreference ? { selfPreference: j.selfPreference } : {}),\n evalName: j.evalName,\n artifact: j.artifact,\n artifactName: j.artifactName,\n artifactType: plan?.artifact.type ?? \"skill\",\n grader: j.grader,\n implicit: j.implicit,\n location: spelled(plan?.location ?? { file: j.artifact }, root),\n outcome: j.outcome,\n ...(j.consensus !== undefined ? { consensus: j.consensus } : {}),\n ...(j.skipReason !== undefined ? { skipReason: j.skipReason } : {}),\n ...(j.error !== undefined ? { error: j.error } : {}),\n turns: j.turns,\n durationMs: j.durationMs,\n });\n });\n }\n }\n\n // Weight rides on the result so the summary can read it without threading\n // the plan list through, and so `--format json` consumers can see why a rate\n // moved. Counts stay unweighted: \"1 failed\" answers how many evals failed,\n // the rate answers how much that mattered, and weighting both would make\n // each answer the other's question.\n const weightOf = new Map<string, number>();\n for (const plan of plans) {\n weightOf.set(weightKey(plan.artifact.path, plan.evalName), plan.weight ?? 1);\n }\n for (const r of results) {\n r.weight = weightOf.get(weightKey(r.artifact, r.evalName)) ?? 1;\n }\n const gradedRows = results.filter(\n (r) => r.outcome === \"pass\" || r.outcome === \"fail\" || r.outcome === \"error\",\n );\n const gradedWeight = gradedRows.reduce((n, r) => n + (r.weight ?? 1), 0);\n\n const summary: RunSummary = {\n total: results.length,\n pass: results.filter((r) => r.outcome === \"pass\").length,\n fail: results.filter((r) => r.outcome === \"fail\").length,\n error: results.filter((r) => r.outcome === \"error\").length,\n needsReview: results.filter((r) => r.outcome === \"needs-review\").length,\n skipped: results.filter((r) => r.outcome === \"skipped\").length,\n passRate:\n gradedWeight > 0\n ? gradedRows\n .filter((r) => r.outcome === \"pass\")\n .reduce((n, r) => n + (r.weight ?? 1), 0) / gradedWeight\n : 1,\n };\n const failing =\n summary.fail > 0 ||\n summary.error > 0 ||\n (config.failOnReview && summary.needsReview > 0);\n\n return {\n trace: {\n file: trace.file,\n source: trace.source,\n ...(trace.sessionId !== undefined ? { sessionId: trace.sessionId } : {}),\n cwd: trace.cwd,\n ...(trace.model !== undefined ? { model: trace.model } : {}),\n turnCount: trace.turnCount,\n },\n warnings: [\n ...(options.warnings ?? []),\n ...trace.warnings,\n ...manifestWarnings,\n ...resolved.warnings,\n ...vanityMetricWarnings(plans),\n ...truncatedArtifactWarnings(plans),\n ],\n coverage: resolved.coverage,\n // An observation about the session's configuration, never a verdict: it is\n // deliberately not part of `summary` and never moves `exitCode`.\n availability: resolved.availability,\n ...(found !== null\n ? { manifest: summariseManifest(found, resolved.coverage) }\n : {}),\n evalResults: results,\n summary,\n exitCode: failing ? 1 : 0,\n turns: results.reduce((sum, r) => sum + (r.turns ?? 0), 0),\n durationMs: Date.now() - start,\n };\n}\n\n\n/**\n * Key for the plan-to-result weight lookup.\n *\n * `U+0000` is written as an escape and never as a literal character. A raw NUL\n * in the source makes git classify this file as **binary**, and a binary file\n * does not merge: git reports the conflict, writes \"ours\" to the working tree\n * with no markers, and renders every diff as `Binary files differ`. This file\n * carried one for exactly one merge, which silently dropped the other side.\n *\n * The separator itself is defensive rather than load-bearing — an artifact\n * path ends in a filename, so the two halves cannot currently be forged into\n * a colliding key. A separator that cannot appear in either half keeps that\n * true if artifact naming ever loosens.\n */\n/**\n * A declaring location as a result reports it: relative and forward-slashed\n * under the working directory, absolute outside it, and a hosted manifest's\n * URL as it is.\n */\nfunction spelled(location: EvalLocation, root: string): EvalLocation {\n if (classifyRef(location.file).kind === \"url\") return location;\n const posix = toPosix(location.file);\n return { ...location, file: underRoot(posix, root) ?? posix };\n}\n\nfunction weightKey(artifact: string, evalName: string): string {\n return `${artifact}\\u0000${evalName}`;\n}\n\n/**\n * Artifacts whose only check is that their skill fired.\n *\n * `claude plugin eval` treats the trigger check as display-only: it reports\n * whether the plugin fired but excludes it from the score in both arms, and\n * its authoring interview refuses to let it stand as a case's only grader.\n * The reasoning transfers exactly — \"the skill fired\" is not \"the session\n * adhered to the skill\", and a suite whose only criterion is `skill-invoked`\n * reports coverage while asserting nothing about behavior.\n *\n * A warning rather than an error: it is a statement about how much the suite\n * is worth, not about whether this run is valid.\n */\nfunction vanityMetricWarnings(plans: EvalPlan[]): string[] {\n const byArtifact = new Map<string, EvalPlan[]>();\n for (const plan of plans) {\n if (plan.implicit) continue;\n const list = byArtifact.get(plan.artifact.path) ?? [];\n list.push(plan);\n byArtifact.set(plan.artifact.path, list);\n }\n const warnings: string[] = [];\n for (const [path, group] of byArtifact) {\n if (group.length > 0 && group.every((p) => p.grader === \"skill-invoked\")) {\n warnings.push(\n `${path}: every eval here is skill-invoked, which checks that the skill fired, ` +\n `not that the session followed it. Add at least one eval about what the ` +\n `session actually did.`,\n );\n }\n }\n return warnings;\n}\n\n\n/**\n * Artifacts the judge only saw part of.\n *\n * The prompt already tells the judge it is reading an excerpt; nothing told\n * the person reading the report. A verdict about adherence to a 20,000-word\n * skill, formed from its first 8,000 characters, is not wrong so much as\n * unlabelled — and an unlabelled partial verdict is the kind that gets\n * trusted.\n */\nfunction truncatedArtifactWarnings(plans: EvalPlan[]): string[] {\n const seen = new Set<string>();\n const warnings: string[] = [];\n for (const plan of plans) {\n if (plan.grader !== \"ai\") continue;\n const path = plan.artifact.path;\n if (seen.has(path)) continue;\n if (!artifactWasTruncated(plan.artifact.content)) continue;\n seen.add(path);\n warnings.push(\n `${path}: only the first ${String(MAX_ARTIFACT_CHARS)} characters were shown to the judge ` +\n `(the artifact is ${String(plan.artifact.content.length)}). Verdicts about instructions ` +\n `beyond that point rest on text the judge never read.`,\n );\n }\n return warnings;\n}\n\n/**\n * What the manifest was able to say, counted over the coverage rows it was\n * compared against. Three numbers rather than two, because \"the manifest had\n * nothing to say about this artifact\" is not a shade of \"unchanged\" — those\n * rows still rest on the mtime guess and a reader has to be able to see how\n * many.\n */\nfunction summariseManifest(\n found: FoundManifest,\n coverage: CoverageEntry[],\n): ManifestReport {\n const checked = coverage.filter((c) => c.contentCheck !== undefined);\n return {\n path: found.path,\n sessionId: found.manifest.sessionId,\n capturedAt: found.manifest.capturedAt,\n ...(found.manifest.git !== undefined\n ? { gitSha: found.manifest.git.sha }\n : {}),\n matched: checked.filter((c) => c.contentCheck?.status === \"match\").length,\n changed: checked.filter((c) => c.contentCheck?.status === \"mismatch\").length,\n unrecorded: checked.filter((c) => c.contentCheck?.status === \"skipped\")\n .length,\n };\n}\n","/**\n * The eval trail kept outside the artifact, in an external-metadata manifest a\n * collection declares (proposal 0037, and 0047's `x-manni-location`).\n *\n * `manni:artifact-evals:1.0.0-proposal.4` marks the whole top-level `metadata`\n * key `x-manni-location: external`, so `manni meta relocate` can move an\n * artifact's `evals`, `eval-skip` and `meta-provenance` out of the page and\n * into a manifest, together. Reading only the artifact's own front matter\n * therefore graded a relocated artifact as if it declared nothing: no evals, no\n * trail, no error, a clean gate. This module is why that is no longer true.\n *\n * Reading is meta's merge, not a second loader. `loadExternalEvals` keeps every\n * manifest that may own `metadata`, and `forArtifact` merges one artifact\n * through `mergeWithMarks`. So the join rules, the ownership rules and the\n * per-item lines are the ones `meta validate` already applies. That includes a\n * manifest with no `keys` (proposal 0068), which owns what the artifact's\n * schemas mark external. It also includes a `{page}` manifest (proposal 0058),\n * which is read for the artifact it names and no other.\n *\n * Two things follow `manni cite`'s sidecar, for cite's reasons:\n *\n * - **Membership is decided by every declared collection**, not by the ones\n * the run selected. `run` and `calibrate` select traces and `fill` selects\n * artifacts under `--project`; no collection ever chooses tracevals' inputs\n * (proposal 0049 §1). But an artifact `fill` was handed by path is still a\n * member of the collection that contains it, and its evals are still in that\n * collection's manifest. A run that read frontmatter instead would report\n * the artifact as declaring nothing and then write a second copy.\n * - **A page whose collections own `metadata` twice is refused**, because\n * picking one would be the tiebreak 0020 refuses.\n *\n * Where tracevals differs from cite: a URL manifest is *readable* here. cite\n * writes citations, so a URL is nowhere to write and is refused at load. `run`\n * and `calibrate` only read, so a hosted trail grades fine; `fill` refuses to\n * write into one at the point of writing (`write-location.ts`).\n *\n * `--no-config` never reaches here: with no config there are no collections, so\n * an artifact's evals are its frontmatter's.\n */\nimport { relative, resolve, sep } from \"node:path\";\nimport { ownsKey } from \"../../shared/collections.js\";\nimport { hasPagePlaceholder } from \"../../shared/page-manifest.js\";\nimport { familyMarks, mergeWithMarks } from \"../../meta/internal.js\";\nimport {\n classifyRef,\n DocmetaError,\n externalMetadataJoin,\n extractFrontmatter,\n loadExternalMetadata,\n memberOf,\n PATH_JOIN,\n type CollectionConfig,\n type ExternalMetadataConfig,\n type ExternalMetadataIndex,\n type ExtractedMetadata,\n type SourceLocation,\n} from \"../../meta/index.js\";\nimport { TracevalsError } from \"../types.js\";\nimport type { ResolvedArtifact } from \"../artifacts/types.js\";\n\n/**\n * The one key a manifest owns on tracevals' behalf. Not `evals`: 0047 puts the\n * mark on the whole `metadata` map, so `evals`, `eval-skip` and\n * `meta-provenance` relocate as one block and cannot be split across a page and\n * a manifest.\n */\nexport const METADATA_KEY = \"metadata\";\n\n/**\n * What the vocabulary tracevals reads marks `x-manni-location: external`. A\n * manifest with no `keys` may own it, less what a sibling manifest of its\n * collection names. That decides which manifests a run reads and the\n * two-collection refusal. The merge itself reads each artifact's own marks,\n * as meta's does.\n */\nconst MARKED: ReadonlySet<string> = new Set([METADATA_KEY]);\n\nconst toPosix = (path: string): string => path.split(sep).join(\"/\");\n\n/** The manifest that supplied one artifact's `metadata` block. */\nexport interface ArtifactManifest {\n /** The collection that declares it. */\n collection: string;\n /** Absolute path of the manifest file, or the URL when `url` is true. */\n path: string;\n /** The manifest as the run reports it. */\n file: string;\n /** `path`, or the artifact field the manifest joins on. */\n join: string;\n /** A hosted manifest: readable by `run`, never written by `fill`. */\n url: boolean;\n}\n\n/** Where one artifact's `metadata` block lives, and what it holds. */\nexport interface ArtifactMetadata {\n /** The artifact's front matter, with a manifest-supplied `metadata` merged in. */\n extracted: ExtractedMetadata;\n /**\n * The manifest file and line behind a merged JSON Pointer, as the merge\n * reports it, with the file absolute (or the URL of a hosted manifest).\n * Absent when no manifest was read for the artifact, and `undefined` for\n * anything the artifact itself carries.\n */\n locate?: (pointer: string) => SourceLocation | undefined;\n /** The manifest that supplied `metadata`, when one did. */\n owner?: ArtifactManifest;\n /**\n * The key under which this artifact is written in `owner`: its path relative\n * to the config directory, or its value of the join field. Undefined when the\n * manifest joins on a field the artifact does not carry.\n */\n entry?: string;\n}\n\nexport interface ExternalEvals {\n /** Directory manifest paths and manifest keys resolve from. */\n configDir: string;\n /** The artifact's metadata, merged with whatever a manifest supplies. */\n forArtifact(artifact: Pick<ResolvedArtifact, \"path\" | \"content\">): Promise<ArtifactMetadata>;\n}\n\nexport interface LoadExternalEvalsOptions {\n /** Every collection the config declares, not only the ones the run selected. */\n collections: readonly CollectionConfig[];\n /** The config file's directory. */\n configDir: string;\n /**\n * The config file itself. A manifest with no `keys` owns what an artifact's\n * schemas mark external, and those schemas are meta's section of this file.\n * Without it, meta's default set decides.\n */\n configPath?: string;\n /** `--offline`: refuse a remote manifest rather than fetch it (0038). */\n offline?: boolean;\n /** The family encryption key, for a join field an artifact holds encrypted. */\n key?: string;\n}\n\n/** `<artifact> is in collections a and b, and both keep metadata in a manifest.` */\nexport function twoManifestsRefusal(label: string, a: string, b: string): string {\n return `${label} is in collections ${a} and ${b}, and both keep ${METADATA_KEY} in a manifest.`;\n}\n\n/** `manni tracevals fill` cannot write into a hosted manifest. */\nexport function urlManifestRefusal(label: string, file: string): string {\n return `${label}: ${METADATA_KEY} is owned by ${file}, and a URL manifest cannot be written. Vendor it to a path, or run fill with --dry-run.`;\n}\n\n/** Whether one manifest declaration of `collection` may own `metadata`. */\nfunction ownsMetadata(\n collection: Pick<CollectionConfig, \"externalMetadata\">,\n manifest: ExternalMetadataConfig,\n): boolean {\n return ownsKey(collection, manifest, METADATA_KEY, MARKED);\n}\n\n/**\n * Every manifest that may own `metadata`, or `null` when none does. That is\n * every setup that keeps its evals in front matter, and it costs nothing.\n *\n * Only the metadata-owning manifests are read. A sibling manifest of the same\n * collection, supplying meta's own keys from a URL, is none of tracevals'\n * business and is never fetched here.\n *\n * Nothing is read until an artifact asks. A `{page}` manifest (proposal 0058)\n * names one file per artifact, and meta reads one only for the pages it is\n * handed, so the artifacts have to be known first. `run` learns them from a\n * trace, and `fill` from its scan.\n */\nexport function loadExternalEvals(\n opts: LoadExternalEvalsOptions,\n): Promise<ExternalEvals | null> {\n const scoped: CollectionConfig[] = [];\n for (const collection of opts.collections) {\n const owning = collection.externalMetadata.filter((m) => ownsMetadata(collection, m));\n if (owning.length === 0) continue;\n scoped.push({ ...collection, externalMetadata: owning });\n }\n return Promise.resolve(scoped.length === 0 ? null : reader(scoped, opts));\n}\n\nfunction reader(\n scoped: readonly CollectionConfig[],\n opts: LoadExternalEvalsOptions,\n): ExternalEvals {\n const { configDir } = opts;\n const base = configDir;\n const declared = opts.collections;\n const marks = familyMarks({ configPath: opts.configPath, configDir, cwd: base });\n\n // A concrete manifest is the same file for every artifact, so it is read\n // once per invocation, and a URL one is fetched once. A `{page}` manifest is\n // read per artifact, and the concrete ones beside it come back out of meta's\n // per-process parse cache.\n const perPage = scoped.some((c) =>\n c.externalMetadata.some((m) => hasPagePlaceholder(m.file)),\n );\n // A manifest that cannot be read is the run's problem, not one artifact's,\n // so it surfaces as this tool's operational error (exit 2) wherever it is\n // first read.\n const load = async (pages?: readonly string[]): Promise<ExternalMetadataIndex | null> => {\n try {\n return await loadExternalMetadata(scoped, {\n configDir,\n base,\n ...(opts.offline === undefined ? {} : { offline: opts.offline }),\n ...(pages === undefined ? {} : { pages }),\n });\n } catch (err) {\n if (err instanceof DocmetaError) throw new TracevalsError(err.message);\n throw err;\n }\n };\n let shared: Promise<ExternalMetadataIndex | null> | undefined;\n const own = new Map<string, Promise<ExternalMetadataIndex | null>>();\n const indexFor = (abs: string): Promise<ExternalMetadataIndex | null> => {\n if (!perPage) return (shared ??= load());\n let index = own.get(abs);\n if (index === undefined) {\n index = load([abs]);\n own.set(abs, index);\n }\n return index;\n };\n\n const forArtifact = async (\n artifact: Pick<ResolvedArtifact, \"path\" | \"content\">,\n ): Promise<ArtifactMetadata> => {\n const label = artifact.path;\n const extracted = extractFrontmatter(artifact.content, \"markdown\");\n // Membership is answered against every declared collection, so an\n // artifact `fill` was handed by path is still a member of the collection\n // that holds its manifest. Ownership is then narrowed to the collections\n // whose manifests may own `metadata`, which is what `scoped` is.\n const members = memberOf(declared, configDir, base, label);\n const [first, second] = scoped.filter((c) => members.includes(c.name));\n if (first === undefined) return { extracted };\n if (second !== undefined) {\n throw new TracevalsError(twoManifestsRefusal(label, first.name, second.name));\n }\n\n const merged = await mergeWithMarks(\n label,\n extracted,\n await indexFor(resolve(base, label)),\n [first.name],\n base,\n { encryptionKey: () => opts.key, marks: await marks() },\n );\n\n // The merge spells a manifest relative to `base`; a result names it\n // absolutely, as it names the artifact.\n const locate = (pointer: string): SourceLocation | undefined => {\n const found = merged.locate(pointer);\n if (found === undefined || classifyRef(found.file).kind === \"url\") return found;\n return { ...found, file: resolve(base, found.file) };\n };\n // The manifest supplied the block exactly when `locate` answers for it; an\n // artifact carrying its own `metadata:` keeps it (the collision is meta's\n // finding, not a tiebreak), and `locate` then answers `undefined`.\n const at = merged.locate(`/${METADATA_KEY}`);\n const [declaration] = first.externalMetadata;\n if (at === undefined || declaration === undefined) {\n return { extracted: merged.extracted, locate };\n }\n\n const url = classifyRef(at.file).kind === \"url\";\n const owner: ArtifactManifest = {\n collection: first.name,\n path: url ? at.file : resolve(base, at.file),\n file: at.file,\n join: externalMetadataJoin(declaration),\n url,\n };\n const out: ArtifactMetadata = { extracted: merged.extracted, locate, owner };\n if (owner.join === PATH_JOIN) {\n out.entry = toPosix(relative(configDir, resolve(base, label)));\n } else {\n const value =\n merged.joins.find((j) => j.field === owner.join)?.value ??\n extracted.data[owner.join];\n if (typeof value === \"string\" && value !== \"\") out.entry = value;\n else if (typeof value === \"number\" || typeof value === \"boolean\") {\n out.entry = String(value);\n }\n }\n return out;\n };\n\n return { configDir, forArtifact };\n}\n","/**\n * Grader plugins: modules named by `tracevals.plugins` or `--require`, imported\n * before evals are planned so a `registerGrader` call from outside this package\n * lands before the registry is read (ADR 01017).\n *\n * Loading is deliberately loud. A specifier that will not import is a\n * `TracevalsError` rather than a skip, because a run that quietly went ahead\n * without the plugin reports `unknown grader kind` — a message that reads like\n * a typo in an artifact and sends the reader to the wrong file entirely.\n *\n * The code being loaded is named by the *evaluating* repo's config, not by the\n * evaluated trace's artifacts. That is a strictly smaller surface than the\n * `command` grader already accepts (ADR 01011); the ADR states the comparison.\n */\nimport { createRequire } from \"node:module\";\nimport { isAbsolute, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n BUILTIN_GRADER_KINDS,\n graderFor,\n listGraderKinds,\n registerGrader,\n} from \"./registry.js\";\nimport { TracevalsError } from \"../types.js\";\nimport type { TraceGrader } from \"./types.js\";\n\n/** What a plugin's `register` export is handed. */\nexport interface GraderPluginApi {\n registerGrader: (grader: TraceGrader) => void;\n}\n\nexport type GraderPluginRegister = (\n api: GraderPluginApi,\n) => void | Promise<void>;\n\nexport interface LoadGraderPluginsOptions {\n /** Module specifiers in load order; a later one wins a colliding kind. */\n plugins: string[];\n /** Directory holding manni.config.yaml. Specifiers resolve against it. */\n configDir: string;\n}\n\nexport interface LoadedGraderPlugins {\n /** Specifiers newly imported by this call; already-loaded ones are omitted. */\n loaded: string[];\n /** Non-fatal problems: a plugin that registered nothing, or took a kind over. */\n warnings: string[];\n}\n\n/**\n * Every module location loaded so far in this process, so a plugin is loaded\n * exactly once however many times it is named — across calls, not just within\n * one.\n *\n * ESM already gives that guarantee to a plugin that registers while it is\n * imported: the second `import()` returns the cached module and its body does\n * not re-run. A plugin exporting `register` would otherwise get called again on\n * every load, so the two shapes would disagree — a batch that evaluates N\n * traces in one process would re-register on each, and report N-1 spurious\n * \"replaced the grader\" warnings. Tracking it here makes them agree.\n */\nconst alreadyLoaded = new Set<string>();\n\n/** `./x`, `../x`, and their backslash spellings — never a bare package name. */\nconst RELATIVE = /^\\.\\.?[/\\\\]/;\n\ninterface Located {\n /** What `import()` is given. */\n href: string;\n /** What the error message shows, when it says more than the specifier. */\n shown?: string;\n}\n\n/**\n * Where a specifier points.\n *\n * Paths resolve against the **config file's directory**, not `process.cwd()`,\n * so a committed config naming `./tracevals/graders.mjs` means the same thing\n * from any working directory — including a CI step that runs the CLI from the\n * repository root against a project one level down.\n *\n * A bare name goes through Node's own algorithm rooted at that same directory,\n * so a plugin installed beside the config beats one installed beside this\n * package. If nothing resolves there the bare specifier is handed to `import()`\n * unchanged, which gives a plugin sitting next to manni itself a\n * chance and keeps the failure message worded the way the user wrote it.\n */\nfunction locate(specifier: string, configDir: string): Located {\n if (specifier.startsWith(\"file:\")) return { href: specifier };\n if (RELATIVE.test(specifier) || isAbsolute(specifier)) {\n const path = resolve(configDir, specifier);\n return { href: pathToFileURL(path).href, shown: path };\n }\n try {\n // createRequire needs an absolute filename; the \"package.json\" leaf never\n // has to exist — it only anchors the node_modules walk to configDir.\n const path = createRequire(join(resolve(configDir), \"package.json\")).resolve(\n specifier,\n );\n return { href: pathToFileURL(path).href, shown: path };\n } catch {\n return { href: specifier };\n }\n}\n\n/**\n * Two supported shapes, in this order:\n *\n * - `export function register({ registerGrader })` (also `export default`) —\n * the registrar is handed in, so the plugin needs no import of this package\n * and cannot bind to the wrong copy of it.\n * - Nothing exported, having called `registerGrader` at import time. That is\n * what the extend guide has always documented, and it keeps working; it just\n * depends on the specifier resolving to the copy of the registry the process\n * is running.\n */\nfunction registrarIn(\n mod: Record<string, unknown>,\n): GraderPluginRegister | undefined {\n if (typeof mod.register === \"function\") {\n return mod.register as GraderPluginRegister;\n }\n if (typeof mod.default === \"function\") {\n return mod.default as GraderPluginRegister;\n }\n return undefined;\n}\n\nfunction snapshot(): Map<string, TraceGrader> {\n const registered = new Map<string, TraceGrader>();\n for (const kind of listGraderKinds()) {\n const grader = graderFor(kind);\n // `listGraderKinds` reads the same registry, so the lookup always hits.\n // Skipping rather than asserting keeps a future registry that can forget a\n // kind mid-iteration from turning this into a crash during a run.\n if (grader !== undefined) registered.set(kind, grader);\n }\n return registered;\n}\n\n/** What one plugin changed, phrased for the report's warnings list. */\nfunction changesSince(\n specifier: string,\n before: Map<string, TraceGrader>,\n): string[] {\n const added: string[] = [];\n const replaced: string[] = [];\n for (const kind of listGraderKinds()) {\n const previous = before.get(kind);\n if (previous === undefined) added.push(kind);\n else if (previous !== graderFor(kind)) replaced.push(kind);\n }\n\n const warnings: string[] = [];\n if (added.length === 0 && replaced.length === 0) {\n warnings.push(\n `grader plugin \"${specifier}\" registered no grader kinds — export a ` +\n `\\`register({ registerGrader })\\` function, or call registerGrader while ` +\n `the module is imported. Any eval naming a custom grader will report ` +\n `\\`unknown grader kind\\`.`,\n );\n }\n for (const kind of replaced) {\n warnings.push(\n BUILTIN_GRADER_KINDS.has(kind)\n ? `grader plugin \"${specifier}\" replaced the built-in grader \"${kind}\"; ` +\n `every eval declaring that kind now runs the plugin's implementation`\n : `grader plugin \"${specifier}\" replaced the grader \"${kind}\" registered ` +\n `by an earlier plugin`,\n );\n }\n return warnings;\n}\n\n/**\n * Import each plugin in order and let it register. Throws `TracevalsError`\n * (exit 2) on the first specifier that will not load; returns warnings for the\n * problems that are real but not fatal.\n */\nexport async function loadGraderPlugins(\n options: LoadGraderPluginsOptions,\n): Promise<LoadedGraderPlugins> {\n const loaded: string[] = [];\n const warnings: string[] = [];\n\n for (const specifier of options.plugins) {\n const { href, shown } = locate(specifier, options.configDir);\n if (alreadyLoaded.has(href)) continue;\n\n const before = snapshot();\n let mod: Record<string, unknown>;\n try {\n mod = (await import(href)) as Record<string, unknown>;\n } catch (err) {\n throw new TracevalsError(\n `could not load grader plugin \"${specifier}\"` +\n (shown !== undefined ? ` (resolved to ${shown})` : \"\") +\n `: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n const register = registrarIn(mod);\n if (register !== undefined) {\n try {\n await register({ registerGrader });\n } catch (err) {\n throw new TracevalsError(\n `grader plugin \"${specifier}\" threw while registering: ` +\n (err instanceof Error ? err.message : String(err)),\n );\n }\n }\n\n // Marked only once it is actually in: a failed load throws, and a retry\n // must not find the specifier recorded as already handled.\n alreadyLoaded.add(href);\n warnings.push(...changesSince(specifier, before));\n loaded.push(specifier);\n }\n\n return { loaded, warnings };\n}\n","/**\n * Run history: append-only JSONL of run summaries plus a comparison against\n * the previous run of the same trace, for spotting regressions after criteria\n * or artifact changes. History failures never abort a run.\n */\nimport { appendFile, mkdir, readFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { EvalResult, RunReport } from \"./types.js\";\nimport { errorMessage } from \"../shared/errors.js\";\nimport { warn } from \"../shared/warn.js\";\n\nexport interface HistoryEval {\n artifact: string;\n evalName: string;\n outcome: EvalResult[\"outcome\"];\n}\n\nexport interface HistoryEntry {\n timestamp: string;\n traceFile: string;\n sessionId?: string;\n project: string;\n summary: RunReport[\"summary\"];\n exitCode: number;\n turns: number;\n evals: HistoryEval[];\n}\n\nexport interface HistoryComparison {\n previousTimestamp: string;\n regressions: HistoryEval[];\n improvements: HistoryEval[];\n added: string[];\n removed: string[];\n}\n\nexport function entryFor(report: RunReport): HistoryEntry {\n return {\n timestamp: new Date().toISOString(),\n traceFile: report.trace.file,\n ...(report.trace.sessionId !== undefined\n ? { sessionId: report.trace.sessionId }\n : {}),\n project: report.trace.cwd,\n summary: report.summary,\n exitCode: report.exitCode,\n turns: report.turns,\n evals: report.evalResults.map((r) => ({\n artifact: r.artifact,\n evalName: r.evalName,\n outcome: r.outcome,\n })),\n };\n}\n\nexport async function appendHistory(\n file: string,\n report: RunReport,\n): Promise<void> {\n try {\n await mkdir(dirname(file), { recursive: true });\n await appendFile(file, `${JSON.stringify(entryFor(report))}\\n`, \"utf-8\");\n } catch (err) {\n warn(\n `could not write history at ${file} (${errorMessage(err)}). Continuing.`,\n );\n }\n}\n\nexport async function loadHistory(file: string): Promise<HistoryEntry[]> {\n let content: string;\n try {\n content = await readFile(file, \"utf-8\");\n } catch {\n return [];\n }\n const entries: HistoryEntry[] = [];\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n entries.push(JSON.parse(trimmed) as HistoryEntry);\n } catch {\n continue; // Corrupt line — skip, never fatal.\n }\n }\n return entries;\n}\n\nconst GOOD = new Set<EvalResult[\"outcome\"]>([\"pass\"]);\nconst BAD = new Set<EvalResult[\"outcome\"]>([\"fail\", \"error\"]);\n\n/** Compare against the most recent prior entry for the same session/trace. */\nexport function compareToLast(\n history: HistoryEntry[],\n report: RunReport,\n): HistoryComparison | null {\n const key = report.trace.sessionId ?? report.trace.file;\n const previous = [...history]\n .reverse()\n .find((e) => (e.sessionId ?? e.traceFile) === key);\n if (!previous) return null;\n\n const keyOf = (e: HistoryEval) => `${e.artifact}::${e.evalName}`;\n const before = new Map(previous.evals.map((e) => [keyOf(e), e]));\n const current = entryFor(report).evals;\n const currentKeys = new Set(current.map(keyOf));\n\n const regressions: HistoryEval[] = [];\n const improvements: HistoryEval[] = [];\n const added: string[] = [];\n for (const e of current) {\n const prior = before.get(keyOf(e));\n if (!prior) {\n added.push(e.evalName);\n continue;\n }\n if (GOOD.has(prior.outcome) && BAD.has(e.outcome)) regressions.push(e);\n if (BAD.has(prior.outcome) && GOOD.has(e.outcome)) improvements.push(e);\n }\n const removed = previous.evals\n .filter((e) => !currentKeys.has(keyOf(e)))\n .map((e) => e.evalName);\n\n return {\n previousTimestamp: previous.timestamp,\n regressions,\n improvements,\n added,\n removed,\n };\n}\n","/**\n * Choosing the provider and model, and building the shared inference\n * library's `ProviderSpec` for it.\n *\n * The providers themselves live in `@hawkeyexl/inference` (ADR 01006). The\n * names a provider may have, the two refusals, `--local`, the detection call,\n * the level-bound precedence and the mapping of the family's `providers:`\n * connection settings are `src/shared/providers.ts`, the same code\n * `manni meta fill` and `manni docevals` run. What stays here is what only\n * manni tracevals can decide: which levels it reads (a flag, an eval's own\n * `provider:`/`model:`, `tracevals.provider`/`model`, then the family's\n * `providers:`), and the judge-shaped options a verdict call wants.\n *\n * No model id is named in this file. A model the tool pinned would go stale\n * the week the provider shipped a better one, and would override the default\n * the library keeps current.\n */\nimport {\n makeProvider as makeInferenceProvider,\n mockVerdict,\n type InferenceProvider,\n type MockResponse,\n type ProviderName as ConcreteProvider,\n type ProviderSelector,\n type ProviderSpec,\n} from \"@hawkeyexl/inference\";\nimport { TracevalsError } from \"../types.js\";\nimport type { TracevalsConfig } from \"../core/config.js\";\nimport {\n assertKnownProvider,\n assertLocalFlag,\n assertModelHasProvider,\n localNotice,\n providerSpecFor as sharedProviderSpecFor,\n resolveIdentity,\n selectProvider as selectFromLevels,\n type ProviderChoice,\n type ProviderFlags,\n type ProviderSelection,\n} from \"../../shared/providers.js\";\nimport { errorMessage } from \"../../shared/errors.js\";\nimport { noticeOnce } from \"../../shared/warn.js\";\n\nexport type { MockResponse, ProviderChoice, ProviderFlags, ProviderSelection };\n\n/** The key a tracevals user writes, named by the refusal a bare model gets. */\nconst CONFIG_KEY = \"tracevals.provider\";\n\nconst toTracevalsError = (message: string): Error => new TracevalsError(message);\n\n/** What a caller wants of the provider beyond which one it is. */\nexport interface JudgeProviderOptions {\n /**\n * Responses for the `mock` seam. The default is verdict-shaped, which suits\n * judging; callers with a different response schema (criteria proposals,\n * say) must supply their own. `mock` is accepted when named but never\n * offered, so nothing that lists providers mentions it.\n */\n mockResponses?: MockResponse[];\n}\n\n/**\n * The provider and model in force: a flag, then the eval's own choice, then\n * `tracevals.provider`/`model`, then the family's `providers.provider`/`model`,\n * then `auto`. A model is carried only to the provider its own level names, so\n * an eval that names a different provider takes that provider's default\n * instead of a model it cannot run (`selectProvider` in the shared module).\n *\n * `--local` runs llama-cpp over all of them. A `--provider` it contradicts is\n * refused here, so no path selects past it. `ev.origin` names the eval in the\n * notice for a provider `--local` replaced; the caller knows its artifact.\n */\nexport function selectProvider(\n config: TracevalsConfig,\n flags: ProviderFlags = {},\n ev: ProviderChoice = {},\n): ProviderSelection {\n assertLocalFlag(flags, toTracevalsError);\n return selectFromLevels(flags, [\n {\n ...(ev.provider !== undefined ? { provider: ev.provider } : {}),\n ...(ev.model !== undefined ? { model: ev.model } : {}),\n ...(ev.origin !== undefined ? { origin: ev.origin } : {}),\n },\n {\n ...(config.provider !== null ? { provider: config.provider } : {}),\n ...(config.model !== null ? { model: config.model } : {}),\n origin: CONFIG_KEY,\n },\n {\n ...(config.providers.provider !== undefined\n ? { provider: config.providers.provider }\n : {}),\n ...(config.providers.model !== undefined ? { model: config.providers.model } : {}),\n origin: \"providers.provider\",\n },\n ]);\n}\n\n/**\n * Say what `--local` set aside, once per source. Called where a selection is\n * about to be used, never where it is only checked, so a run that sends\n * nothing to a model says nothing.\n */\nexport function announceSelection(selection: ProviderSelection): void {\n const message = localNotice(selection);\n if (message !== undefined) noticeOnce(message);\n}\n\n/**\n * Refuse a selection that cannot be right, with `manni meta fill`'s messages:\n * an unknown name, or a model under `auto`. Both are `TracevalsError`s, which\n * is what maps them to exit 2.\n */\nexport function assertProviderSelection(selection: ProviderSelection): void {\n assertKnownProvider(selection.provider, toTracevalsError);\n assertModelHasProvider(selection.provider, selection.model, CONFIG_KEY, toTracevalsError);\n}\n\n/**\n * The spec for a selection, with the family's connection settings for the\n * provider it names, and under `auto` the settings detection reads.\n */\nexport function providerSpecFor(\n config: TracevalsConfig,\n selection: { provider: ProviderSelector; model: string | null },\n options: JudgeProviderOptions = {},\n): ProviderSpec {\n const spec = sharedProviderSpecFor(config.providers, selection);\n switch (selection.provider) {\n case \"anthropic\":\n // A verdict-shaped tool name steers the model better than a generic\n // one, and it is free to keep.\n return { ...spec, anthropic: { toolName: \"record_verdict\" } };\n case \"openai\":\n return { ...spec, openai: { schemaName: \"verdict\" } };\n case \"mock\":\n return {\n ...spec,\n mockResponses: options.mockResponses ?? [mockVerdict(\"pass\", 0.95)],\n };\n default:\n return spec;\n }\n}\n\n/**\n * The concrete provider and model, WITHOUT constructing the provider: cache\n * keys need it, and a fully cached run must not require an API key.\n *\n * Under `auto` this is where detection runs, exactly as `manni meta fill` runs\n * it, seeing the same connection settings. The model is the RESOLVED one (the\n * provider's default when none was named, a llama-cpp tier's concrete\n * weights), so a library default that changes changes every cache key built\n * from it.\n */\nexport async function resolveProviderIdentity(\n config: TracevalsConfig,\n flags: ProviderFlags = {},\n ev: ProviderChoice = {},\n): Promise<{ provider: ConcreteProvider; model: string }> {\n const selection = selectProvider(config, flags, ev);\n const { provider, model } = selection;\n assertKnownProvider(provider, toTracevalsError);\n assertModelHasProvider(provider, model, CONFIG_KEY, toTracevalsError);\n announceSelection(selection);\n return resolveIdentity(\n providerSpecFor(config, { provider, model: model ?? null }),\n toTracevalsError,\n );\n}\n\n/** Construct a provider for an identity already resolved. */\nexport function constructProvider(\n config: TracevalsConfig,\n identity: { provider: ConcreteProvider; model: string },\n options: JudgeProviderOptions = {},\n): InferenceProvider {\n try {\n return makeInferenceProvider(providerSpecFor(config, identity, options));\n } catch (e) {\n // The library raises its own InferenceError (a missing API key). It must\n // surface as a TracevalsError: `cli.ts`'s fail() maps only that to exit 2,\n // and letting a foreign error type through turns \"no API key configured\"\n // into an unhandled stack trace.\n throw new TracevalsError(errorMessage(e));\n }\n}\n\n/** Select, check, detect and construct: the provider a verb judges with. */\nexport async function makeJudgeProvider(\n config: TracevalsConfig,\n flags: ProviderFlags = {},\n ev: ProviderChoice = {},\n options: JudgeProviderOptions = {},\n): Promise<InferenceProvider> {\n return constructProvider(\n config,\n await resolveProviderIdentity(config, flags, ev),\n options,\n );\n}\n","/**\n * The trace-adherence ensemble judge: N independent runs per eval plan, each a\n * fresh request with no shared context, aggregated by consensus and routed\n * through confidence zones.\n *\n * The ensemble mechanics (retry-once, errored runs counting against consensus,\n * cache replay) now live in the inference library; what stays here is what is\n * manni tracevals-specific — the per-instance turn budget, the trace-worded\n * verdict schema, and the `JudgedEval` shape the reporters consume.\n */\nimport {\n computeConsensus,\n runEnsemble,\n zoneFor,\n type ConsensusResult,\n type InferenceProvider,\n} from \"@hawkeyexl/inference\";\nimport verdictSchemaJson from \"./verdict-schema.json\" with { type: \"json\" };\nimport type { EvalPlan } from \"../core/plan.js\";\nimport { VerdictCache, cacheKey } from \"./cache.js\";\nimport { turnBudgetSkipReason } from \"../../docevals/judge/budget.js\";\nimport { buildUserContent, JUDGE_SYSTEM_PROMPT } from \"./prompt.js\";\nimport { readTarget, describeTarget } from \"../core/target.js\";\nimport type { Trace } from \"../trace/types.js\";\n\n/**\n * manni tracevals' own verdict wording. Structurally identical to the library's\n * canonical schema, but the field descriptions talk about sessions and tool\n * calls rather than pages — and those descriptions are prompt surface that\n * steers the model, so they are worth keeping (inference ADR 01001).\n */\nconst verdictSchema = verdictSchemaJson as Record<string, unknown>;\n\nexport interface TraceJudgeOptions {\n provider: InferenceProvider;\n /**\n * The provider for an eval that names its own `provider:` or `model:`.\n *\n * The choice is passed through rather than resolved here: precedence across\n * the flag, the eval, `tracevals.provider` and the family's `providers:` is\n * one rule, in `judge/provider.ts`, and a second copy of it inside the judge\n * is how a run and an eval come to disagree about which model answered.\n * Without this hook an eval naming a provider errors rather than being\n * judged silently by the default model — an eval that names a provider is\n * asking for that one.\n */\n providerFor?: (choice: {\n provider?: string;\n model?: string;\n origin?: string;\n }) => Promise<InferenceProvider>;\n /** Ensemble size; default 3. */\n runs?: number;\n /** Default 0; nonzero adds verdict noise. */\n temperature?: number;\n zones?: { autoPass: number; autoFail: number };\n cacheDir?: string;\n noCache?: boolean;\n /**\n * Ensemble runs this judge may spend, over every call of it. `null` or\n * absent is unbounded. A cached ensemble makes no inference call, so it\n * spends none (docevals ADR 01019).\n */\n maxTurns?: number | null;\n}\n\nexport interface JudgedEval {\n evalName: string;\n artifact: string;\n artifactName: string;\n grader: string;\n implicit: boolean;\n outcome: \"pass\" | \"fail\" | \"needs-review\" | \"skipped\" | \"error\";\n consensus?: ConsensusResult;\n skipReason?: string;\n /** Set when the eval could not be judged at all. */\n error?: string;\n /** Set when the judge model also produced what it graded. See EvalResult. */\n selfPreference?: { axis: \"session\" | \"criterion\"; model: string };\n /**\n * Uncached ensemble runs this eval spent. `0` when the ensemble came from\n * cache, when the budget stopped it, and when it never reached a provider.\n */\n turns: number;\n durationMs: number;\n}\n\n/** What the judge needs about the session beyond its rendered form. */\nexport interface TraceJudgeContext {\n /**\n * The parsed session. Supplies `target` selection and the model that\n * produced the run — absent means \"unknown\", which is reported rather than\n * treated as \"not the same model\".\n */\n trace?: Trace;\n /** Root a relative `{source: file}` target resolves against. */\n projectRoot?: string;\n}\n\n/**\n * The digest is requested per plan rather than handed over once: each eval is\n * judged against the window its artifact was governing (ADR 01015), so the\n * transcript differs from eval to eval. `target` then selects within that\n * window, which is why it reads the rendered result rather than the trace.\n *\n * The returned function is callable repeatedly — once per trace in a batch —\n * and `maxTurns` spans every call, because the budget lives on the instance\n * rather than on the call (ADR 01018).\n */\nexport type TraceJudge = (\n plans: EvalPlan[],\n renderFor: (plan: EvalPlan) => string,\n context?: TraceJudgeContext,\n) => Promise<JudgedEval[]>;\n\nexport function makeTraceJudge(options: TraceJudgeOptions): TraceJudge {\n const provider = options.provider;\n // CLI > eval > default. The flag is an explicit operator act (\"run cheap\n // right now\"), so it outranks an eval asking for more agreement; the eval\n // outranks the run default, which is the point of having it.\n const runsFor = (plan: EvalPlan): number => options.runs ?? plan.runs ?? 3;\n const temperature = options.temperature ?? 0;\n const zones = options.zones ?? { autoPass: 0.8, autoFail: 0.8 };\n const cache = new VerdictCache(\n options.cacheDir ?? \".manni/tracevals/cache\",\n options.noCache !== true && options.cacheDir !== undefined,\n \"manni-tracevals\",\n );\n const maxTurns = options.maxTurns ?? null;\n\n // Deliberately outside the returned function: the budget belongs to the\n // *judge instance*, not to one call of it. A batch calls the judge once per\n // trace (ADR 01018), so a per-call counter would make `maxTurns` a cap on\n // the largest trace rather than on the run — 50 traces would spend 50x the\n // configured ceiling and every report would look like it obeyed it. A\n // single-trace run calls the judge exactly once, so this is invisible there.\n let turnsSpent = 0;\n\n return async (plans, renderFor, context) => {\n const trace = context?.trace;\n const sessionModel = trace?.model;\n const results: JudgedEval[] = [];\n\n for (const plan of plans) {\n const start = Date.now();\n const base = {\n evalName: plan.evalName,\n artifact: plan.artifact.path,\n artifactName: plan.artifact.name,\n grader: plan.grader,\n implicit: plan.implicit,\n };\n\n // An eval may name its own provider or model. Resolve it before the\n // budget gate so a typo is reported as the eval's own error rather than\n // hidden behind an exhausted budget.\n //\n // Which provider the pair resolves to is `providerFor`'s to decide, not\n // this loop's: the flag outranks the eval, the eval outranks the config,\n // and that ladder is one rule in `judge/provider.ts`. An eval whose\n // choice resolves to the run's own gets the run's already-constructed\n // provider back.\n let evalProvider = provider;\n if (plan.provider !== undefined || plan.model !== undefined) {\n const resolved = await resolveOverride(plan, options);\n if (\"error\" in resolved) {\n results.push({\n ...base,\n outcome: \"error\",\n error: resolved.error,\n turns: 0,\n durationMs: Date.now() - start,\n });\n continue;\n }\n evalProvider = resolved.provider;\n }\n\n // The window this artifact was governing (ADR 01015). `target` selects\n // within it, so the two compose: a `transcript` target means \"this\n // eval's window\", not \"the whole session\".\n const renderedTrace = renderFor(plan);\n\n // What this eval asked to be graded. A target that cannot be served\n // errors rather than falling back to the transcript: a verdict about the\n // wrong bytes is worse than no verdict.\n // Without a parsed trace only the transcript and the artifact can be\n // served. Saying so beats quietly grading the transcript instead.\n const selected =\n trace === undefined\n ? plan.target === undefined ||\n plan.target === \"transcript\" ||\n plan.target === \"artifact\"\n ? ({\n ok: true as const,\n text:\n plan.target === \"artifact\"\n ? plan.artifact.content\n : renderedTrace,\n label: plan.target === \"artifact\" ? \"artifact\" : \"transcript\",\n })\n : ({\n ok: false as const,\n reason: `target \"${describeTarget(plan.target)}\" needs the parsed session, which this run did not supply`,\n })\n : readTarget(plan.target, {\n trace,\n renderedTrace,\n artifactContent: plan.artifact.content,\n root: context?.projectRoot ?? trace.cwd,\n });\n if (!selected.ok) {\n results.push({\n ...base,\n outcome: \"error\",\n error: selected.reason,\n turns: 0,\n durationMs: Date.now() - start,\n });\n continue;\n }\n\n const runsPerEval = runsFor(plan);\n const key = cacheKey(\n evalProvider.provider(),\n evalProvider.modelName(),\n runsPerEval,\n temperature,\n // The selected bytes, not always the transcript: two targets on one\n // session are two different questions and must not share a verdict.\n selected.text,\n plan,\n );\n const cached = cache.get(key) !== undefined;\n\n // A cached ensemble makes no inference call, so it never touches the\n // budget — a committed cache replays under any cap. For an uncached one\n // the turns are claimed *before* dispatching, which is the whole point\n // of counting turns rather than dollars: the claim is synchronous, so\n // nothing can clear an almost-exhausted budget and then overspend it\n // (docevals ADR 01019).\n if (maxTurns !== null && !cached) {\n if (turnsSpent + runsPerEval > maxTurns) {\n results.push({\n ...base,\n outcome: \"skipped\",\n skipReason: turnBudgetSkipReason(maxTurns),\n turns: 0,\n durationMs: 0,\n });\n continue;\n }\n // One turn per ensemble run. A run can make a second provider call\n // when the first response fails schema validation (the inference layer\n // retries once), so this is a floor on calls, not an exact count — the\n // cap is exact in *runs*, which is the unit the ensemble is\n // configured in.\n turnsSpent += runsPerEval;\n }\n\n const runs = await runEnsemble({\n provider: evalProvider,\n system: JUDGE_SYSTEM_PROMPT,\n user: buildUserContent(plan, selected.text, selected.label),\n runs: runsPerEval,\n temperature,\n schema: verdictSchema,\n cache,\n cacheKey: key,\n label: \"manni-tracevals\",\n });\n\n const consensusBase = computeConsensus(runs);\n const zone = zoneFor(consensusBase, zones);\n const consensus: ConsensusResult = { ...consensusBase, zone };\n\n // Compared against the model that actually judged this eval, not the\n // run's default: an eval that names its own model is exactly the case a\n // run-wide check would miss.\n const judgeModel = evalProvider.modelName();\n // Two distinct biases, and the session axis is reported first because\n // its remedy is the stronger one. Judging your own session is bias about\n // the behavior under test; judging your own assertion is bias about the\n // yardstick — the fix there is a human confirming the criterion, not a\n // second model, since another model would still grade the same wording.\n const selfPreference =\n sessionModel !== undefined && sessionModel === judgeModel\n ? ({ axis: \"session\", model: judgeModel } as const)\n : plan.proposedBy?.includes(judgeModel) === true\n ? ({ axis: \"criterion\", model: judgeModel } as const)\n : undefined;\n\n results.push({\n ...base,\n outcome:\n zone === \"auto-pass\"\n ? \"pass\"\n : zone === \"auto-fail\"\n ? \"fail\"\n : \"needs-review\",\n consensus,\n turns: cached ? 0 : runsPerEval,\n ...(selfPreference ? { selfPreference } : {}),\n durationMs: Date.now() - start,\n });\n }\n return results;\n };\n}\n\n/**\n * Build the provider an eval named, or say why it could not be built. Kept\n * out of the loop so the failure is one shape: never a throw that costs the\n * report every other verdict, never a silent fall back to the default model.\n */\nasync function resolveOverride(\n plan: EvalPlan,\n options: TraceJudgeOptions,\n): Promise<{ provider: InferenceProvider } | { error: string }> {\n // Either half is enough to need a different instance, so the message names\n // whichever the eval actually wrote.\n const named =\n plan.provider !== undefined\n ? `provider \"${plan.provider}\"`\n : `model \"${plan.model ?? \"\"}\"`;\n if (options.providerFor === undefined) {\n return {\n error: `eval names ${named}, but this run cannot construct providers by name`,\n };\n }\n try {\n // The origin a `--local` notice names. The caller knows the artifact; the\n // eval's own id is what tells one line of it from another.\n return {\n provider: await options.providerFor({\n ...(plan.provider !== undefined ? { provider: plan.provider } : {}),\n ...(plan.model !== undefined ? { model: plan.model } : {}),\n origin: `eval \"${plan.evalName}\" in ${plan.artifact.path}`,\n }),\n };\n } catch (err) {\n return {\n error: `could not construct ${named}${\n plan.provider === undefined || plan.model === undefined\n ? \"\"\n : ` at model \"${plan.model}\"`\n } for this eval: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"manni:tracevals:verdict\",\n \"title\": \"manni tracevals judge verdict\",\n \"type\": \"object\",\n \"required\": [\"claim\", \"observed\", \"match\", \"confidence\", \"reasoning\"],\n \"properties\": {\n \"claim\": {\n \"type\": \"string\",\n \"description\": \"The specific instruction or assertion under evaluation.\"\n },\n \"observed\": {\n \"type\": \"string\",\n \"description\": \"What actually happened in the session, citing specific messages, tool calls, or instructions followed/violated.\"\n },\n \"match\": {\n \"enum\": [\"pass\", \"fail\", \"partial\"],\n \"description\": \"pass only if the session fully adhered; partial for partial adherence.\"\n },\n \"confidence\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 1,\n \"description\": \"Self-reported confidence in this verdict.\"\n },\n \"reasoning\": {\n \"type\": \"string\",\n \"description\": \"Why this conclusion was reached.\"\n }\n },\n \"additionalProperties\": false\n}\n","/**\n * Judge cache key composition. The cache itself is the inference library's\n * `JsonCache`; what stays here is the part only manni tracevals can decide — what\n * invalidates an entry: provider, model, prompt version, run count,\n * temperature, the rendered trace, and the plan.\n */\nimport { JsonCache, buildCacheKey, sha256, type JudgeRun } from \"@hawkeyexl/inference\";\nimport type { EvalPlan } from \"../core/plan.js\";\nimport { PROMPT_VERSION } from \"./prompt.js\";\n\nexport { sha256 };\n\n/**\n * A judge cache that refuses to persist an ensemble containing an errored run\n * (docevals ADR 01038, which found this the hard way and whose reasoning\n * applies here unchanged).\n *\n * The library's `runEnsemble` caches unconditionally — it has no way to know\n * whether an error is a property of the request or of the moment. Here we do:\n * an error is an infrastructure failure (VRAM exhausted, rate limited,\n * connection dropped), never a verdict about the session. Writing one to the\n * cache turns a transient outage into a permanent answer, and `--no-cache`\n * becomes the only way out of a state nothing explains.\n *\n * Reading applies the same predicate, which is what makes the property total\n * rather than merely forward-looking: guarding the write alone cannot heal an\n * entry written before this class existed, and treating such an entry as a\n * miss costs one re-judge and converges. The predicate matches the library's\n * own definition rather than ours, since `computeConsensus` counts a run with\n * no `verdict` as an error vote.\n *\n * Subclassed rather than wrapped because `JsonCache` has private fields, so a\n * structurally identical object does not satisfy its type.\n */\nexport class VerdictCache extends JsonCache<JudgeRun[]> {\n /** An ensemble is cacheable only if every run produced a verdict. */\n private static usable(runs: JudgeRun[]): boolean {\n return runs.every((r) => r.error === undefined && r.verdict !== undefined);\n }\n\n override set(key: string, value: JudgeRun[]): void {\n if (!VerdictCache.usable(value)) return;\n super.set(key, value);\n }\n\n override get(key: string): JudgeRun[] | undefined {\n const hit = super.get(key);\n if (hit === undefined) return undefined;\n return VerdictCache.usable(hit) ? hit : undefined;\n }\n}\n\nexport function cacheKey(\n provider: string,\n model: string,\n runs: number,\n temperature: number,\n renderedTrace: string,\n plan: EvalPlan,\n promptVersion: number = PROMPT_VERSION,\n): string {\n const planFingerprint = JSON.stringify({\n assertion: plan.assertion,\n evidence: plan.evidence,\n examples: plan.examples,\n artifact: plan.artifact.content,\n });\n return buildCacheKey([\n provider,\n model,\n `v${promptVersion}`,\n `r${runs}`,\n `t${temperature}`,\n // Pre-hashed: traces and artifacts are large, and key parts stay short.\n sha256(renderedTrace),\n sha256(planFingerprint),\n ]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,aAAAA,kBAAiB;;;ACOnB,IAAM,mBAAmB;AAGzB,SAAS,qBAAqB,UAA0B;AAC7D,SAAO,SAAS,gBAAgB,eAAe,QAAQ;AACzD;AAQO,SAAS,iBAAiB,QAA8C;AAC7E,SAAO,WAAW,UAAa,OAAO,SAAS,gBAAgB;AACjE;;;ACsBA,IAAM,OAAO,OAAwB;AAAA,EACnC,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,SAAS;AACX;AAEA,SAAS,MAAMC,SAAyB,SAAsC;AAC5E,MAAI,YAAY,eAAgB,CAAAA,QAAO,eAAe;AAAA,MACjD,CAAAA,QAAO,OAAO,KAAK;AAC1B;AAGA,IAAM,QAAQ,CAAC,GAAoB,MACjC,EAAE,MAAM,EAAE,MAAM,KAAK,EAAE,MAAM,EAAE,MAAM,IAAI;AAgB3C,SAAS,WACP,MACA,KACA,QACA,MACA,cACM;AACN,MAAI,MAAM,KAAK,IAAI,GAAG;AACtB,MAAI,QAAQ,QAAW;AACrB,UAAM;AAAA,MACJ;AAAA,MACA,cAAc,OAAO;AAAA,MACrB,cAAc,OAAO;AAAA,MACrB,GAAI,eAAe,EAAE,UAAU,OAAO,SAAS,IAAI,C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eAAS,KAAK,EAAE,MAAM,QAAAA,QAAO,CAAC;AAC9B,cAAQ,KAAKA,OAAM;AACnB,UAAI,WAAY,aAAY,KAAK,UAAU;AAAA,IAC7C,SAAS,KAAK;AAGZ,eAAS,KAAK;AAAA,QACZ;AAAA,QACA,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,QACtD,YAAY,KAAK,IAAI,IAAI;AAAA,MAC3B,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,SAAS,UAAU,UAAU;AAAA,IACjC,UAAU,QAAQ;AAAA,IAClB,YAAY,KAAK,IAAI,IAAI;AAAA,EAC3B,CAAC;AAED,QAAM,WAAW,YAAY,QAAQ,QAAQ,UAAU,UAAU,SAAS;AAAA,IACxE,OAAO,QAAQ,UAAU;AAAA,EAC3B,CAAC;AACD,MAAI,QAAQ,QAAQ;AAClB,UAAMC,WAAU,QAAQ,QAAQ,UAAU,OAAO;AAAA,EACnD;AACA,SAAO,EAAE,QAAQ,UAAU,SAAS,UAAU,YAAY;AAC5D;","names":["writeFile","counts","cell","basename","c","counts","finding","cell","detail","resolve","basename","basename","names","detail","validateOptions","validateOptions","validateOptions","validateOptions","validateOptions","isAbsolute","relative","resolve","validateOptions","compiled","validateOptions","detail","branch","omitted","failing","relative","resolve","sep","toPosix","sep","resolve","locate","relative","isAbsolute","join","resolve","isAbsolute","resolve","join","readFile","dirname","dirname","readFile","selectProvider","providerSpecFor","selectProvider","resolve","report","writeFile"]}
|