From 84986e1c32c0f81be888ed158f695132de093f9f Mon Sep 17 00:00:00 2001 From: pgermishuys Date: Sun, 20 Sep 2026 20:22:45 +0000 Subject: [PATCH 1/2] test(evals): migrate the sanitizer and report schemas to scenarios MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Finishes what #197 started. sanitizer.test.ts and report-schema.test.ts enumerated a denylist and a regex table — "contains composedPrompt", "includes a pattern for html_script_tag" — and said nothing about what a reader of a published bundle is promised. 113 scenarios now feed the equivalent hostile inputs through the real ArtifactBundleWriter and assert what comes out on disk. sanitizer.test.ts 140 -> 91 report-schema.test.ts 188 -> 112 scenarios 12 -> 125 total 340 -> 328 The count barely moves, and that is the honest result: the enumeration's user-visible form is an equally long table. What changes is that the tests now fail when a reader is put at risk rather than when a constant is renamed. What the scenarios cover: every one of the 24 sensitive field names fed in at once and absent from every written file, value and key; eight shapes the allowlist has never seen — nested objects, arrays of objects, prototype-shaped keys, extra keys inside an explanation and inside the closed trajectory allowlist; 30 injection payloads in an explanation, each kept out of every uploadable artifact while the case itself still publishes; the four allowed explanation sources and seven rejected ones; the 300-character bound at and one over; the score buckets a reader skims; a case id carrying markup, dropped from the Markdown and carried verbatim in the JSON where docs/eval-xss-policy.md puts escaping in the dashboard; and the schema versions the website pins on the report, its suite summaries and all six indexes. Proved by mutation before anything was deleted, against tests/evals alone: sanitizeCaseResultSummary returns its input 38 of 113 red explanation validation removed from assembly 42 red sanitizeMdValue returns its input verbatim 2 red sanitizeProvenanceRecord spreads its input 1 red The second one is the lesson again. On the first pass it turned exactly one scenario red: without validation the whole report fails schema parsing, so public-report.json is never written and "the payload appears in no public artifact" stays true for the wrong reason. Each payload case now also asserts the case is still published — the graceful degradation the pipeline actually promises — and the same mutation turns 42 red. Kept, with the reasoning in each file's docblock: assertPublishSafe and assertJsonPublishSafe, which never fire while the projection works and so are invisible from outside; the manifest schemas' rejection branches, unreachable from a writer that always stamps the version constant; and the strict-mode rejection of sensitive field names, a layer above the sanitizer rather than a duplicate of it. Three things turned up while observing rather than transcribing, all recorded in docs/testing-strategy.md: - A case with an empty caseId costs a run its entire dashboard presence, silently. Public-report assembly fails validation, writeBundle treats that as non-fatal, and no public-report.json, no Markdown and no index files are written — with an ok result. - Seven exported sanitizer surfaces have no production caller: sanitizeScoreRecord, dropUnknownFields, truncateExplanation, buildExplanation, assertExplanationSafe, REDACTED and FORBIDDEN_EXPLANATION_SOURCE_DESCRIPTORS. The runners build explanations through buildPublicExplanation and redact with their own patterns. About 60 unit cases cover code nothing calls; kept and flagged, because removing the API is a product decision. - A summary missing dimensionScores makes writeBundle throw a TypeError instead of returning a typed BundleError. docs/eval-sanitization-and-publish-pipeline.md claimed every index file carries updatedAt; model-comparison-.json does not, and carries runId instead. Corrected, with a scenario pinning it. Refs #183 (task group 14) Claude-Session: https://claude.ai/code/session_01DisVZW27sd6Pe7uhbjXNve Co-authored-by: Claude Opus 5 --- .codesight/CODESIGHT.md | 12 +- .codesight/coverage.md | 2 +- .codesight/graph.md | 8 +- docs/artifacts/cli-evals-migration-handoff.md | 30 +- .../eval-sanitization-and-publish-pipeline.md | 8 +- docs/testing-strategy.md | 61 ++ .../src/evals/__tests__/report-schema.test.ts | 669 +------------- .../cli/src/evals/__tests__/sanitizer.test.ts | 444 +--------- tests/evals/publish-safety.scenario.test.ts | 825 ++++++++++++++++++ 9 files changed, 986 insertions(+), 1073 deletions(-) create mode 100644 tests/evals/publish-safety.scenario.test.ts diff --git a/.codesight/CODESIGHT.md b/.codesight/CODESIGHT.md index 5488ce3e..de998e36 100644 --- a/.codesight/CODESIGHT.md +++ b/.codesight/CODESIGHT.md @@ -5,7 +5,7 @@ > 0 routes | 0 models | 0 components | 200 lib files | 25 env vars | 7 middleware | 1 events | 0% test coverage > **Token savings:** this file is ~18,200 tokens. Without it, AI exploration would cost ~66,400 tokens. **Saves ~48,200 tokens per conversation.** -> **Last scanned:** 2026-09-20 20:09 — re-run after significant changes +> **Last scanned:** 2026-09-20 20:22 — re-run after significant changes --- @@ -979,16 +979,16 @@ ## Most Imported Files (change these carefully) -- `packages/cli/src/evals/types.ts` — imported by **48** files +- `packages/cli/src/evals/types.ts` — imported by **49** files - `packages/cli/src/io/terminal.ts` — imported by **22** files - `packages/cli/src/theme/colors.ts` — imported by **22** files - `packages/cli/src/fs/file-system.ts` — imported by **20** files - `packages/cli/src/evals/openrouter-client.ts` — imported by **20** files -- `packages/cli/src/evals/report-schema.ts` — imported by **18** files - `packages/adapters/opencode2/src/sdk-types.ts` — imported by **16** files - `packages/engine/src/runtime/types.ts` — imported by **16** files - `packages/cli/src/args.ts` — imported by **15** files - `packages/engine/src/runtime/store.ts` — imported by **13** files +- `packages/cli/src/evals/report-schema.ts` — imported by **12** files - `packages/engine/src/logger.ts` — imported by **12** files - `packages/engine/src/compose.ts` — imported by **11** files - `packages/engine/src/runtime/errors.ts` — imported by **11** files @@ -1002,16 +1002,16 @@ ## Import Map (who imports what) -- `packages/cli/src/evals/types.ts` ← `packages/cli/src/evals/__tests__/case-loader.test.ts`, `packages/cli/src/evals/__tests__/case-loader.test.ts`, `packages/cli/src/evals/__tests__/dashboard-indexes.test.ts`, `packages/cli/src/evals/__tests__/github-contents-publisher.test.ts`, `packages/cli/src/evals/__tests__/input-validation.test.ts` +43 more +- `packages/cli/src/evals/types.ts` ← `packages/cli/src/evals/__tests__/case-loader.test.ts`, `packages/cli/src/evals/__tests__/case-loader.test.ts`, `packages/cli/src/evals/__tests__/dashboard-indexes.test.ts`, `packages/cli/src/evals/__tests__/github-contents-publisher.test.ts`, `packages/cli/src/evals/__tests__/input-validation.test.ts` +44 more - `packages/cli/src/io/terminal.ts` ← `packages/cli/src/__tests__/routing.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/config-validation-errors.test.ts`, `packages/cli/src/commands/__tests__/eval.test.ts`, `packages/cli/src/commands/__tests__/init.test.ts` +17 more - `packages/cli/src/theme/colors.ts` ← `packages/cli/src/__tests__/theme.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/config-validation-errors.test.ts`, `packages/cli/src/commands/__tests__/eval.test.ts`, `packages/cli/src/commands/__tests__/init.test.ts` +17 more - `packages/cli/src/fs/file-system.ts` ← `packages/cli/src/__tests__/file-system.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/init.test.ts`, `packages/cli/src/commands/__tests__/legacy-upgrade-regression.test.ts`, `packages/cli/src/commands/__tests__/migrate-conversion.test.ts` +15 more - `packages/cli/src/evals/openrouter-client.ts` ← `packages/cli/src/evals/__tests__/loom-routing-runner.test.ts`, `packages/cli/src/evals/__tests__/loom-routing-runner.trajectory.test.ts`, `packages/cli/src/evals/__tests__/pattern-planning-runner.test.ts`, `packages/cli/src/evals/__tests__/runner.test.ts`, `packages/cli/src/evals/__tests__/shuttle-execution-runner.test.ts` +15 more -- `packages/cli/src/evals/report-schema.ts` ← `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts` +13 more - `packages/adapters/opencode2/src/sdk-types.ts` ← `packages/adapters/opencode2/src/__tests__/reconcile-agent.test.ts`, `packages/adapters/opencode2/src/adapter.ts`, `packages/adapters/opencode2/src/errors.ts`, `packages/adapters/opencode2/src/plugin.ts`, `packages/adapters/opencode2/src/reconcile-agent.ts` +11 more - `packages/engine/src/runtime/types.ts` ← `packages/engine/src/__tests__/runtime-command-operations.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts` +11 more - `packages/cli/src/args.ts` ← `packages/cli/src/__tests__/args.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/config-validation-errors.test.ts`, `packages/cli/src/commands/__tests__/eval.test.ts`, `packages/cli/src/commands/__tests__/init.test.ts` +10 more - `packages/engine/src/runtime/store.ts` ← `packages/engine/src/__tests__/runtime-journal.test.ts`, `packages/engine/src/execution-lifecycle/artifacts.ts`, `packages/engine/src/execution-lifecycle/dispatch.ts`, `packages/engine/src/execution-lifecycle/inspection.ts`, `packages/engine/src/execution-lifecycle/interrupts.ts` +8 more +- `packages/cli/src/evals/report-schema.ts` ← `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/e2e-fixture-flow.test.ts`, `packages/cli/src/evals/__tests__/langchain-agent-evals.test.ts` +7 more --- @@ -1024,7 +1024,7 @@ # Test Coverage > **0%** of routes and models are covered by tests -> 203 test files found +> 205 test files found --- diff --git a/.codesight/coverage.md b/.codesight/coverage.md index 30ac1f7f..3f026d70 100644 --- a/.codesight/coverage.md +++ b/.codesight/coverage.md @@ -1,4 +1,4 @@ # Test Coverage > **0%** of routes and models are covered by tests -> 203 test files found +> 205 test files found diff --git a/.codesight/graph.md b/.codesight/graph.md index 478cc73f..33751dcf 100644 --- a/.codesight/graph.md +++ b/.codesight/graph.md @@ -2,16 +2,16 @@ ## Most Imported Files (change these carefully) -- `packages/cli/src/evals/types.ts` — imported by **48** files +- `packages/cli/src/evals/types.ts` — imported by **49** files - `packages/cli/src/io/terminal.ts` — imported by **22** files - `packages/cli/src/theme/colors.ts` — imported by **22** files - `packages/cli/src/fs/file-system.ts` — imported by **20** files - `packages/cli/src/evals/openrouter-client.ts` — imported by **20** files -- `packages/cli/src/evals/report-schema.ts` — imported by **18** files - `packages/adapters/opencode2/src/sdk-types.ts` — imported by **16** files - `packages/engine/src/runtime/types.ts` — imported by **16** files - `packages/cli/src/args.ts` — imported by **15** files - `packages/engine/src/runtime/store.ts` — imported by **13** files +- `packages/cli/src/evals/report-schema.ts` — imported by **12** files - `packages/engine/src/logger.ts` — imported by **12** files - `packages/engine/src/compose.ts` — imported by **11** files - `packages/engine/src/runtime/errors.ts` — imported by **11** files @@ -25,13 +25,13 @@ ## Import Map (who imports what) -- `packages/cli/src/evals/types.ts` ← `packages/cli/src/evals/__tests__/case-loader.test.ts`, `packages/cli/src/evals/__tests__/case-loader.test.ts`, `packages/cli/src/evals/__tests__/dashboard-indexes.test.ts`, `packages/cli/src/evals/__tests__/github-contents-publisher.test.ts`, `packages/cli/src/evals/__tests__/input-validation.test.ts` +43 more +- `packages/cli/src/evals/types.ts` ← `packages/cli/src/evals/__tests__/case-loader.test.ts`, `packages/cli/src/evals/__tests__/case-loader.test.ts`, `packages/cli/src/evals/__tests__/dashboard-indexes.test.ts`, `packages/cli/src/evals/__tests__/github-contents-publisher.test.ts`, `packages/cli/src/evals/__tests__/input-validation.test.ts` +44 more - `packages/cli/src/io/terminal.ts` ← `packages/cli/src/__tests__/routing.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/config-validation-errors.test.ts`, `packages/cli/src/commands/__tests__/eval.test.ts`, `packages/cli/src/commands/__tests__/init.test.ts` +17 more - `packages/cli/src/theme/colors.ts` ← `packages/cli/src/__tests__/theme.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/config-validation-errors.test.ts`, `packages/cli/src/commands/__tests__/eval.test.ts`, `packages/cli/src/commands/__tests__/init.test.ts` +17 more - `packages/cli/src/fs/file-system.ts` ← `packages/cli/src/__tests__/file-system.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/init.test.ts`, `packages/cli/src/commands/__tests__/legacy-upgrade-regression.test.ts`, `packages/cli/src/commands/__tests__/migrate-conversion.test.ts` +15 more - `packages/cli/src/evals/openrouter-client.ts` ← `packages/cli/src/evals/__tests__/loom-routing-runner.test.ts`, `packages/cli/src/evals/__tests__/loom-routing-runner.trajectory.test.ts`, `packages/cli/src/evals/__tests__/pattern-planning-runner.test.ts`, `packages/cli/src/evals/__tests__/runner.test.ts`, `packages/cli/src/evals/__tests__/shuttle-execution-runner.test.ts` +15 more -- `packages/cli/src/evals/report-schema.ts` ← `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts` +13 more - `packages/adapters/opencode2/src/sdk-types.ts` ← `packages/adapters/opencode2/src/__tests__/reconcile-agent.test.ts`, `packages/adapters/opencode2/src/adapter.ts`, `packages/adapters/opencode2/src/errors.ts`, `packages/adapters/opencode2/src/plugin.ts`, `packages/adapters/opencode2/src/reconcile-agent.ts` +11 more - `packages/engine/src/runtime/types.ts` ← `packages/engine/src/__tests__/runtime-command-operations.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts` +11 more - `packages/cli/src/args.ts` ← `packages/cli/src/__tests__/args.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/config-validation-errors.test.ts`, `packages/cli/src/commands/__tests__/eval.test.ts`, `packages/cli/src/commands/__tests__/init.test.ts` +10 more - `packages/engine/src/runtime/store.ts` ← `packages/engine/src/__tests__/runtime-journal.test.ts`, `packages/engine/src/execution-lifecycle/artifacts.ts`, `packages/engine/src/execution-lifecycle/dispatch.ts`, `packages/engine/src/execution-lifecycle/inspection.ts`, `packages/engine/src/execution-lifecycle/interrupts.ts` +8 more +- `packages/cli/src/evals/report-schema.ts` ← `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/e2e-fixture-flow.test.ts`, `packages/cli/src/evals/__tests__/langchain-agent-evals.test.ts` +7 more diff --git a/docs/artifacts/cli-evals-migration-handoff.md b/docs/artifacts/cli-evals-migration-handoff.md index ce88d494..984077ae 100644 --- a/docs/artifacts/cli-evals-migration-handoff.md +++ b/docs/artifacts/cli-evals-migration-handoff.md @@ -45,11 +45,11 @@ Largest files, by case count: | Cases | File | First read | | --- | --- | --- | -| 188 | `report-schema.test.ts` | mostly *"includes a pattern for X"* — enumerating a constant | +| 188 | `report-schema.test.ts` | **migrated** — 188 → 112 (task group 14) | | 169 | `loom-routing-runner.test.ts` | runner behaviour; mixed | | 161 | `artifact-bundle.test.ts` | bundle writing; largely observable | | 153 | `langchain-agent-evals.test.ts` | judge adapter; mixed | -| 140 | `sanitizer.test.ts` | *"contains X"* against a denylist | +| 140 | `sanitizer.test.ts` | **migrated** — 140 → 91 (task group 14) | | 114 | `report-markdown.test.ts` | rendering; observable | The observable promises are far fewer than the case count suggests, and they @@ -81,9 +81,9 @@ are worth stating plainly before writing anything: and the loader fills it from the matrix; a list restating the defaults is rejected. Tests written against the old shape will mislead. -## Two findings this work has already produced +## Findings this work has already produced -Both came from writing scenarios against observed behaviour, and both are the +All came from writing scenarios against observed behaviour, and they are the argument for doing the rest: - **`{{{delegation.section}}}` does not exist** and has not since ADR 0001, yet @@ -92,6 +92,28 @@ argument for doing the rest: a working agent on `sonnet`, because the list is filtered against what the adapter knows the harness can run (#195). Intended, but undocumented and worth a product decision. +- **An empty `caseId` makes a whole run vanish from the dashboard, silently.** + Public-report assembly fails validation and `writeBundle()` treats that as + non-fatal, so no `public-report.json`, no Markdown, no indexes — and an `ok` + result (task group 14). +- **Seven exported sanitizer surfaces have no production caller** and are + reached only from tests (task group 14). See the strategy doc. + +## Notes for whoever takes the next file + +- **Score files are local, public artifacts are uploaded.** Only + `bundle-index.json`, `public-report.json` and `public-report.md` are in + `RUN_ARTIFACT_ALLOWLIST`. `score-.json` *does* carry explanation text + that the public report drops, so "no published file contains X" must say + which files it means. +- **Absence assertions need a positive twin.** Dropping the whole report also + satisfies "the payload appears nowhere". Assert the case is still published + alongside it, or the scenario passes for the wrong reason. +- **Index files are not reproducible.** They stamp `new Date()` into + `updatedAt`; only the run artifacts are byte-identical across runs. +- [`tests/support/evals.ts`](../../tests/support/evals.ts) is the shared harness; + [`tests/evals/publish-safety.scenario.test.ts`](../../tests/evals/publish-safety.scenario.test.ts) + is the worked example for a hostile-input table. ## Still open elsewhere diff --git a/docs/eval-sanitization-and-publish-pipeline.md b/docs/eval-sanitization-and-publish-pipeline.md index 9c1412c5..52494b25 100644 --- a/docs/eval-sanitization-and-publish-pipeline.md +++ b/docs/eval-sanitization-and-publish-pipeline.md @@ -357,12 +357,18 @@ Immutable run artifacts under `runs/v1//` are written **once and never ov | `latest.json` | `LATEST_SNAPSHOT_SCHEMA_VERSION` | `updatedAt` | | `last-N-runs.json` | `LAST_N_RUNS_SCHEMA_VERSION` | `updatedAt` | | `suite-history-.json` (`SuiteHistoryManifest`) | `SUITE_HISTORY_SCHEMA_VERSION` | `updatedAt` | -| `model-comparison-.json` (`ModelComparisonManifest`) | `MODEL_COMPARISON_SCHEMA_VERSION` | `updatedAt` | +| `model-comparison-.json` (`ModelComparisonManifest`) | `MODEL_COMPARISON_SCHEMA_VERSION` | `runId` (no `updatedAt`) | Mutable index artifacts MUST be re-fetched on every dashboard load (or after a TTL). Consumers MUST: 1. Reject any index where `schemaVersion` does not match the expected version constant. 2. Compare `updatedAt` against a freshness threshold and re-fetch when stale. + `model-comparison-.json` is the exception: it is regenerated per run + rather than accumulated across runs, so it carries `runId` and no + `updatedAt`. Judge its freshness from the run it names. + +[`tests/evals/publish-safety.scenario.test.ts`](../tests/evals/publish-safety.scenario.test.ts) +pins both properties against the files the writer really produces. Use the typed validators in `dashboard-indexes.ts` for these checks: - `validateDashboardManifestCompatibility()` — returns `ok(parsed)` or `err(DashboardIndexError)` with `SchemaVersionMismatch` or `IndexParseError` variant diff --git a/docs/testing-strategy.md b/docs/testing-strategy.md index 333cb202..434e0bd3 100644 --- a/docs/testing-strategy.md +++ b/docs/testing-strategy.md @@ -265,6 +265,28 @@ internal branches. What stays is what a user cannot observe from outside: | `model-resolution.test.ts` | Pins the adapter↔engine `ModelResolutionInput` contract, which no generated file reveals. Its three cases pinning the adapter's model *constant* were deleted — those are observable | | `bootstrap.test.ts` | Integrity of a shipped asset. Closer to a repo guard than a unit test | +The same rule applied to the evals sanitizer and report schemas: + +| | Before | After | +| --- | --- | --- | +| `sanitizer.test.ts` | 140 | 91 | +| `report-schema.test.ts` | 188 | 112 | +| Scenario cases | 12 | 125 | +| Total | 340 | 328 | + +Here the count barely moves, and that is the honest result: 125 scenario cases +replaced 125 unit cases, because the deleted ones were an enumeration +(`"contains composedPrompt"`, `"includes a pattern for html_script_tag"`) whose +user-visible form is an equally long table of hostile inputs fed through the +real bundle writer. The gain is not fewer tests but tests that fail when a +reader is put at risk, rather than when a constant is renamed. What stayed: + +| Kept | Why | +| --- | --- | +| `assertPublishSafe()` / `assertJsonPublishSafe()` | The publish-mode guards. While the allowlist projection works they never fire, so no written file reveals their behaviour | +| The manifest schemas' rejection branches | The writer always passes the version constant, so a wrong `schemaVersion` is unreachable from outside; the branches guard a future producer | +| `sanitizeScoreRecord`, `dropUnknownFields`, `truncateExplanation`, `buildExplanation`, `assertExplanationSafe`, `REDACTED`, `FORBIDDEN_EXPLANATION_SOURCE_DESCRIPTORS` | Exported API with **no production caller** — see the finding below | + **Prove the deletion rather than asserting it.** Before deleting, break the source and confirm the scenarios fail. For this pilot: @@ -278,6 +300,24 @@ source and confirm the scenarios fail. For this pilot: All four were caught by `tests/adapters` alone, with every deleted unit test already gone. +The evals sanitizer migration repeated the exercise against `tests/evals` +alone: + +| Mutation | Result | +| --- | --- | +| `sanitizeCaseResultSummary()` returns its input | 38 of 113 scenarios red | +| Explanation validation removed from `assembleCaseEntry()` | 42 red | +| `sanitizeMdValue()` returns its input verbatim | 2 red | +| `sanitizeProvenanceRecord()` spreads its input | 1 red | + +The second mutation is the one worth reading twice. On the first pass it +turned **one** scenario red, because dropping validation makes +`PublicReportBundleSchema` reject the whole report, so `public-report.json` is +never written and *"the payload appears in no public artifact"* stays true. An +absence assertion was passing for the wrong reason again. Each payload case now +also asserts the case is still published — the graceful degradation the +pipeline actually promises — and the same mutation turns 42 red. + ### A scenario can pass without testing anything The evals bucket produced the sharpest lesson so far, and every migration @@ -308,6 +348,27 @@ dropped silently and resolution falls through to `DEFAULT_FALLBACK_MODEL`. A typo in `models` yields a working agent on the wrong model rather than an error. The scenario now records that. +The evals migration turned up three more: + +- **A case with an empty `caseId` costs the run its dashboard presence, + silently.** `PublicReportBundle` assembly fails validation, and + `writeBundle()` treats that failure as non-fatal: `public-report.json`, + `public-report.md` and every dashboard index are skipped, and the result is + still `ok`. Nothing in the write result says the run will never appear. +- **Seven exported sanitizer surfaces have no production caller.** + `sanitizeScoreRecord()`, `dropUnknownFields()`, `truncateExplanation()`, + `buildExplanation()`, `assertExplanationSafe()`, `REDACTED` and + `FORBIDDEN_EXPLANATION_SOURCE_DESCRIPTORS` are reached only from tests — the + runners build explanations through `buildPublicExplanation()` in + `langchain-agent-evals.ts` and redact with their own patterns. Roughly 60 + unit cases cover code nothing calls. They were kept and flagged rather than + deleted, because the decision is a product one. +- **A malformed summary throws instead of returning `err`.** A `CaseResult` + whose `summary` omits `dimensionScores` makes `writeBundle()` raise a + `TypeError` rather than a typed `BundleError`, against the `neverthrow` rule + in `AGENTS.md`. Reachable only by defeating the type system, so no scenario + asserts it. + ## What the buckets found Writing scenarios against real behaviour surfaced documentation that described diff --git a/packages/cli/src/evals/__tests__/report-schema.test.ts b/packages/cli/src/evals/__tests__/report-schema.test.ts index c1cacefb..2e26934a 100644 --- a/packages/cli/src/evals/__tests__/report-schema.test.ts +++ b/packages/cli/src/evals/__tests__/report-schema.test.ts @@ -1,28 +1,34 @@ /** - * Tests for `report-schema.ts`. + * Unit tests for `report-schema.ts` — the parts a user cannot observe. * - * Verifies: - * - All public schema types require `schemaVersion`. - * - Schemas reject incorrect or missing `schemaVersion` values. - * - `BoundedExplanationSchema` rejects raw text inputs (rationale markers, - * transcript role markers, chain-of-thought markers, prompt delimiters, - * secret patterns, justification markers, score markers). - * - `BoundedExplanationSchema` rejects overlong explanations. - * - `BoundedExplanationSchema` rejects empty explanations. - * - `BoundedExplanationSchema` accepts valid, sanitized explanations. - * - `BoundedExplanationSchema` rejects all forbidden `ExplanationSource` - * values (only allowlisted enum members pass). - * - `PublicCaseEntrySchema` rejects sensitive fields and raw text. - * - `SuiteSummaryEntrySchema` validates aggregate fields and nested cases. - * - `PublicReportBundleSchema` validates the full bundle shape. - * - `DashboardManifestSchema` validates entry manifest with run index. - * - `SuiteHistoryManifestSchema` validates history time series. - * - `ModelComparisonManifestSchema` validates per-model comparison entries. - * - `computeScoreBucket()` maps score values to correct buckets. - * - `FORBIDDEN_EXPLANATION_PATTERNS` covers all required forbidden pattern types. + * The explanation surface moved out of this file. What an explanation may + * contain, where it may come from, how long it may be, and which score bucket + * a weighted total lands in are all visible in the files a run publishes, and + * are asserted there in + * [`tests/evals/publish-safety.scenario.test.ts`](../../../../../tests/evals/publish-safety.scenario.test.ts) + * as a table of hostile inputs fed through the real bundle writer: + * `FORBIDDEN_EXPLANATION_PATTERNS`, `ExplanationSourceSchema`, + * `BoundedExplanationSchema`, `ScoreBucketSchema` and `computeScoreBucket()` + * were covered here by enumeration and are covered there by behaviour. Every + * one of those scenarios was watched fail against an assembler that skipped + * explanation validation before the deletion. + * + * What is left is unreachable from outside: + * + * - **`schemaVersion` rejection branches.** The writer always stamps the + * version constant, so a wrong or missing version cannot be produced by + * anything a user does. These branches guard a future producer, and the + * website's own rejection of a bad version depends on them holding. + * - **Strict-mode rejection of sensitive field names.** Layer on top of the + * sanitizer: the scenarios prove no sensitive field reaches a published + * file, these prove the schema would refuse one that did. + * - **Dashboard, suite-history, model-comparison and scenario-history + * validation.** The scenarios assert the published index files carry the + * right version and shape; the rejection branches here cover inputs the + * writer never constructs. * * Test isolation: - * - No file I/O, network, git, or shell calls. + * - No file I/O, no network, no spawned process. * - All fixtures are constructed inline. * - All schema validations use `safeParse()` to avoid thrown exceptions. */ @@ -30,13 +36,10 @@ import { describe, expect, it } from "bun:test"; import { BoundedExplanationSchema, - computeScoreBucket, DASHBOARD_MANIFEST_SCHEMA_VERSION, DashboardEntrySchema, DashboardManifestSchema, EXPLANATION_MAX_CHARS, - ExplanationSourceSchema, - FORBIDDEN_EXPLANATION_PATTERNS, MODEL_COMPARISON_SCHEMA_VERSION, ModelComparisonEntrySchema, ModelComparisonManifestSchema, @@ -48,7 +51,6 @@ import { ScenarioHistoryEntrySchema, ScenarioHistoryIndexSchema, ScenarioRunHistoryEntrySchema, - ScoreBucketSchema, SUITE_HISTORY_SCHEMA_VERSION, SUITE_SUMMARY_SCHEMA_VERSION, SuiteHistoryManifestSchema, @@ -188,549 +190,6 @@ function makeValidModelComparisonManifest( }; } -// --------------------------------------------------------------------------- -// FORBIDDEN_EXPLANATION_PATTERNS — pattern coverage -// --------------------------------------------------------------------------- - -describe("FORBIDDEN_EXPLANATION_PATTERNS", () => { - it("includes a pattern for chain_of_thought_xml", () => { - const names = FORBIDDEN_EXPLANATION_PATTERNS.map((p) => p.name); - expect(names).toContain("chain_of_thought_xml"); - }); - - it("includes a pattern for transcript_role_marker", () => { - const names = FORBIDDEN_EXPLANATION_PATTERNS.map((p) => p.name); - expect(names).toContain("transcript_role_marker"); - }); - - it("includes a pattern for prompt_delimiter", () => { - const names = FORBIDDEN_EXPLANATION_PATTERNS.map((p) => p.name); - expect(names).toContain("prompt_delimiter"); - }); - - it("includes a pattern for raw_rationale_marker", () => { - const names = FORBIDDEN_EXPLANATION_PATTERNS.map((p) => p.name); - expect(names).toContain("raw_rationale_marker"); - }); - - it("includes a pattern for raw_score_marker", () => { - const names = FORBIDDEN_EXPLANATION_PATTERNS.map((p) => p.name); - expect(names).toContain("raw_score_marker"); - }); - - it("includes a pattern for justification_marker", () => { - const names = FORBIDDEN_EXPLANATION_PATTERNS.map((p) => p.name); - expect(names).toContain("justification_marker"); - }); - - it("includes a pattern for secret_token_pattern", () => { - const names = FORBIDDEN_EXPLANATION_PATTERNS.map((p) => p.name); - expect(names).toContain("secret_token_pattern"); - }); - - it("chain_of_thought_xml matches ", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "chain_of_thought_xml", - ); - expect(entry).toBeDefined(); - expect(entry!.pattern.test("")).toBe(true); - }); - - it("chain_of_thought_xml matches ", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "chain_of_thought_xml", - ); - expect(entry!.pattern.test("")).toBe(true); - }); - - it("chain_of_thought_xml matches ", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "chain_of_thought_xml", - ); - expect(entry!.pattern.test("")).toBe(true); - }); - - it("chain_of_thought_xml matches ", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "chain_of_thought_xml", - ); - expect(entry!.pattern.test("")).toBe(true); - }); - - it("transcript_role_marker matches 'User:'", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "transcript_role_marker", - ); - expect(entry!.pattern.test("\nUser: some input")).toBe(true); - }); - - it("transcript_role_marker matches 'Assistant:'", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "transcript_role_marker", - ); - expect(entry!.pattern.test("\nAssistant: response")).toBe(true); - }); - - it("transcript_role_marker matches 'Human:'", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "transcript_role_marker", - ); - expect(entry!.pattern.test("\nHuman: some message")).toBe(true); - }); - - it("transcript_role_marker matches 'System:'", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "transcript_role_marker", - ); - expect(entry!.pattern.test("\nSystem: prompt")).toBe(true); - }); - - it("prompt_delimiter matches ", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "prompt_delimiter", - ); - expect(entry!.pattern.test("")).toBe(true); - }); - - it("prompt_delimiter matches ", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "prompt_delimiter", - ); - expect(entry!.pattern.test("")).toBe(true); - }); - - it("raw_rationale_marker matches 'rationale:'", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "raw_rationale_marker", - ); - expect(entry!.pattern.test("rationale: the model did X")).toBe(true); - }); - - it("raw_score_marker matches 'score: 0.8'", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "raw_score_marker", - ); - expect(entry!.pattern.test("score: 0.8")).toBe(true); - }); - - it("justification_marker matches 'justification:'", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "justification_marker", - ); - expect(entry!.pattern.test("justification: because...")).toBe(true); - }); - - it("justification_marker matches 'explanation:'", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "justification_marker", - ); - expect(entry!.pattern.test("explanation: the thing")).toBe(true); - }); - - it("secret_token_pattern matches 'sk-xxxxxxxxxxxx'", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "secret_token_pattern", - ); - expect(entry!.pattern.test("key: sk-abcdefghijklmno")).toBe(true); - }); - - it("secret_token_pattern matches 'Bearer xxxxxxxxxxxxx'", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "secret_token_pattern", - ); - expect(entry!.pattern.test("Authorization: Bearer abcdefghijk1234")).toBe( - true, - ); - }); - - it("secret_token_pattern matches 'ghp_xxxxxxxxxxxxx'", () => { - const entry = FORBIDDEN_EXPLANATION_PATTERNS.find( - (p) => p.name === "secret_token_pattern", - ); - expect(entry!.pattern.test("token: ghp_abcdefghijklmno")).toBe(true); - }); -}); - -// --------------------------------------------------------------------------- -// ExplanationSource enum -// --------------------------------------------------------------------------- - -describe("ExplanationSourceSchema", () => { - it("accepts rubric_template", () => { - expect(ExplanationSourceSchema.safeParse("rubric_template").success).toBe( - true, - ); - }); - - it("accepts score_bucket_label", () => { - expect( - ExplanationSourceSchema.safeParse("score_bucket_label").success, - ).toBe(true); - }); - - it("accepts structured_signal", () => { - expect(ExplanationSourceSchema.safeParse("structured_signal").success).toBe( - true, - ); - }); - - it("accepts operator_note", () => { - expect(ExplanationSourceSchema.safeParse("operator_note").success).toBe( - true, - ); - }); - - it("rejects raw_rationale (not an allowlisted enum value)", () => { - expect(ExplanationSourceSchema.safeParse("raw_rationale").success).toBe( - false, - ); - }); - - it("rejects transcript_content", () => { - expect( - ExplanationSourceSchema.safeParse("transcript_content").success, - ).toBe(false); - }); - - it("rejects llm_freeform_summary", () => { - expect( - ExplanationSourceSchema.safeParse("llm_freeform_summary").success, - ).toBe(false); - }); - - it("rejects empty string", () => { - expect(ExplanationSourceSchema.safeParse("").success).toBe(false); - }); - - it("rejects arbitrary unknown string", () => { - expect(ExplanationSourceSchema.safeParse("unknown_source").success).toBe( - false, - ); - }); -}); - -// --------------------------------------------------------------------------- -// BoundedExplanationSchema -// --------------------------------------------------------------------------- - -describe("BoundedExplanationSchema", () => { - // --- Happy path --- - - it("accepts a valid rubric_template explanation", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - source: "rubric_template", - text: "Agent routed correctly per rubric definition.", - }), - ); - expect(result.success).toBe(true); - }); - - it("accepts a valid score_bucket_label explanation", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ source: "score_bucket_label" }), - ); - expect(result.success).toBe(true); - }); - - it("accepts a valid structured_signal explanation", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - source: "structured_signal", - text: "routing_matched: true", - }), - ); - expect(result.success).toBe(true); - }); - - it("accepts a valid operator_note explanation", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - source: "operator_note", - text: "Reviewed by team lead on 2026-01-01.", - }), - ); - expect(result.success).toBe(true); - }); - - it("accepts explanation at exactly EXPLANATION_MAX_CHARS length", () => { - const text = "A".repeat(EXPLANATION_MAX_CHARS); - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ text }), - ); - expect(result.success).toBe(true); - }); - - // --- Overlong rejection --- - - it("rejects explanation exceeding EXPLANATION_MAX_CHARS", () => { - const text = "A".repeat(EXPLANATION_MAX_CHARS + 1); - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ text }), - ); - expect(result.success).toBe(false); - const error = result.error!.issues[0]; - expect(error?.message).toContain(String(EXPLANATION_MAX_CHARS)); - }); - - // --- Empty text rejection --- - - it("rejects empty explanation text", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ text: "" }), - ); - expect(result.success).toBe(false); - }); - - // --- Forbidden source rejection --- - - it("rejects raw_rationale as source (not an allowlisted enum)", () => { - const result = BoundedExplanationSchema.safeParse({ - text: "Correct routing.", - source: "raw_rationale", - }); - expect(result.success).toBe(false); - }); - - it("rejects transcript_content as source", () => { - const result = BoundedExplanationSchema.safeParse({ - text: "Some text.", - source: "transcript_content", - }); - expect(result.success).toBe(false); - }); - - it("rejects llm_freeform_summary as source", () => { - const result = BoundedExplanationSchema.safeParse({ - text: "The model performed well.", - source: "llm_freeform_summary", - }); - expect(result.success).toBe(false); - }); - - it("rejects raw_content as source", () => { - const result = BoundedExplanationSchema.safeParse({ - text: "Some content.", - source: "raw_content", - }); - expect(result.success).toBe(false); - }); - - // --- Forbidden pattern rejection --- - - it("rejects explanation text containing (chain-of-thought)", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "Internal reasoning goes here", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - const issue = result.error!.issues.find((i) => - i.message.includes("chain_of_thought_xml"), - ); - expect(issue).toBeDefined(); - }); - - it("rejects explanation text containing ", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "step by step...", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - }); - - it("rejects explanation text containing ", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "Therefore...", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - }); - - it("rejects explanation text containing transcript role marker (\\nUser:)", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "Start\nUser: some message\nAssistant: reply", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - const issue = result.error!.issues.find((i) => - i.message.includes("transcript_role_marker"), - ); - expect(issue).toBeDefined(); - }); - - it("rejects explanation text containing 'rationale:' (raw rationale marker)", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "rationale: the model correctly routed", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - const issue = result.error!.issues.find((i) => - i.message.includes("raw_rationale_marker"), - ); - expect(issue).toBeDefined(); - }); - - it("rejects explanation text containing 'score: 0.9' (raw score marker)", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "score: 0.9 for this case", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - }); - - it("rejects explanation text containing 'justification:' marker", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "justification: because the agent did X", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - }); - - it("rejects explanation text containing 'explanation:' marker", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "explanation: model selected shuttle correctly", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - }); - - it("rejects explanation text containing (prompt delimiter)", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "You are an agent.", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - }); - - it("rejects explanation text containing a Bearer token pattern", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "Authorization: Bearer sk-abc123xyz456pqr", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - }); - - it("rejects explanation text containing a secret key pattern (sk-)", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "key used: sk-abcdefghijklmnop", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - }); - - it("rejects explanation text containing a GitHub token pattern (ghp_)", () => { - const result = BoundedExplanationSchema.safeParse( - makeValidBoundedExplanation({ - text: "token: ghp_abcdefghijklmnop", - source: "operator_note", - }), - ); - expect(result.success).toBe(false); - }); - - // --- Missing fields --- - - it("rejects explanation without text field", () => { - const result = BoundedExplanationSchema.safeParse({ - source: "score_bucket_label", - }); - expect(result.success).toBe(false); - }); - - it("rejects explanation without source field", () => { - const result = BoundedExplanationSchema.safeParse({ - text: "Valid explanation.", - }); - expect(result.success).toBe(false); - }); -}); - -// --------------------------------------------------------------------------- -// ScoreBucketSchema -// --------------------------------------------------------------------------- - -describe("ScoreBucketSchema", () => { - it("accepts 'pass'", () => { - expect(ScoreBucketSchema.safeParse("pass").success).toBe(true); - }); - - it("accepts 'partial'", () => { - expect(ScoreBucketSchema.safeParse("partial").success).toBe(true); - }); - - it("accepts 'fail'", () => { - expect(ScoreBucketSchema.safeParse("fail").success).toBe(true); - }); - - it("accepts 'skip'", () => { - expect(ScoreBucketSchema.safeParse("skip").success).toBe(true); - }); - - it("rejects 'unknown'", () => { - expect(ScoreBucketSchema.safeParse("unknown").success).toBe(false); - }); - - it("rejects '1.0'", () => { - expect(ScoreBucketSchema.safeParse("1.0").success).toBe(false); - }); -}); - -// --------------------------------------------------------------------------- -// computeScoreBucket -// --------------------------------------------------------------------------- - -describe("computeScoreBucket", () => { - it("returns 'skip' for dryRun=true regardless of score", () => { - expect(computeScoreBucket(1.0, true)).toBe("skip"); - expect(computeScoreBucket(0.0, true)).toBe("skip"); - expect(computeScoreBucket(0.5, true)).toBe("skip"); - }); - - it("returns 'skip' when weightedTotal is undefined", () => { - expect(computeScoreBucket(undefined, false)).toBe("skip"); - }); - - it("returns 'pass' for score >= 0.9", () => { - expect(computeScoreBucket(0.9, false)).toBe("pass"); - expect(computeScoreBucket(1.0, false)).toBe("pass"); - expect(computeScoreBucket(0.95, false)).toBe("pass"); - }); - - it("returns 'partial' for score in [0.5, 0.9)", () => { - expect(computeScoreBucket(0.5, false)).toBe("partial"); - expect(computeScoreBucket(0.7, false)).toBe("partial"); - expect(computeScoreBucket(0.89, false)).toBe("partial"); - }); - - it("returns 'fail' for score < 0.5", () => { - expect(computeScoreBucket(0.0, false)).toBe("fail"); - expect(computeScoreBucket(0.3, false)).toBe("fail"); - expect(computeScoreBucket(0.49, false)).toBe("fail"); - }); -}); - // --------------------------------------------------------------------------- // PublicCaseEntrySchema // --------------------------------------------------------------------------- @@ -1711,80 +1170,6 @@ describe("Public schemas reject sensitive field names", () => { }); }); -// --------------------------------------------------------------------------- -// Explanation: raw text input rejection (explicit LLM/rationale channels) -// --------------------------------------------------------------------------- - -describe("BoundedExplanation rejects raw text explanation inputs", () => { - it("rejects a string that looks like a full rationale paragraph", () => { - // Simulates what a scorer might produce as rationale text - const rationaleText = - "The model correctly routed the request to the shuttle agent. " + - "rationale: it identified the backend keyword and selected shuttle-backend."; - const result = BoundedExplanationSchema.safeParse({ - text: rationaleText, - source: "operator_note", - }); - expect(result.success).toBe(false); - }); - - it("rejects text sourced from a transcript excerpt", () => { - const transcriptExcerpt = - "The following was observed:\nUser: Route this to backend.\nAssistant: I'll route it."; - const result = BoundedExplanationSchema.safeParse({ - text: transcriptExcerpt, - source: "operator_note", - }); - expect(result.success).toBe(false); - }); - - it("rejects text that is a chain-of-thought dump", () => { - const cot = - "Step 1: analyse the request. Step 2: pick shuttle. Done."; - const result = BoundedExplanationSchema.safeParse({ - text: cot, - source: "operator_note", - }); - expect(result.success).toBe(false); - }); - - it("rejects text sourced from a prompt template (system tag)", () => { - const promptText = "You are Loom, the orchestrator."; - const result = BoundedExplanationSchema.safeParse({ - text: promptText, - source: "operator_note", - }); - expect(result.success).toBe(false); - }); - - it("rejects score assignment text that mimics LLM freeform output", () => { - const freeform = "score: 1.0 — the model performed perfectly on this case."; - const result = BoundedExplanationSchema.safeParse({ - text: freeform, - source: "operator_note", - }); - expect(result.success).toBe(false); - }); - - it("accepts short, human-written, clean operator note", () => { - const note = "Verified manually by team lead."; - const result = BoundedExplanationSchema.safeParse({ - text: note, - source: "operator_note", - }); - expect(result.success).toBe(true); - }); - - it("accepts a score-bucket-derived label with no forbidden patterns", () => { - const label = "Correctly routed to shuttle (pass bucket)."; - const result = BoundedExplanationSchema.safeParse({ - text: label, - source: "score_bucket_label", - }); - expect(result.success).toBe(true); - }); -}); - // --------------------------------------------------------------------------- // ScenarioRunHistoryEntrySchema // --------------------------------------------------------------------------- diff --git a/packages/cli/src/evals/__tests__/sanitizer.test.ts b/packages/cli/src/evals/__tests__/sanitizer.test.ts index 92871ab2..fbcc29ef 100644 --- a/packages/cli/src/evals/__tests__/sanitizer.test.ts +++ b/packages/cli/src/evals/__tests__/sanitizer.test.ts @@ -1,24 +1,32 @@ /** - * Tests for `sanitizer.ts`. + * Unit tests for `sanitizer.ts` — the parts a user cannot observe. * - * Verifies: - * - Unknown fields in `CaseResultSummary` and `NormalizedScoreRecord` are dropped. - * - Sensitive subfields (tool args, env values, error payloads, log tails, - * rationales, raw content) are always excluded from sanitized output. - * - `assertPublishSafe()` rejects objects with sensitive fields. - * - `assertPublishSafe()` rejects objects containing `rawArtifact`. - * - `assertJsonPublishSafe()` rejects serialized JSON containing sensitive field names. - * - `dropUnknownFields()` retains only allowlisted fields. - * - Sanitized output is deterministic (same input → same output). - * - `sanitizeCaseResultSummary()` produces correct field values. - * - `sanitizeScoreRecord()` drops rationale from all dimensions. - * - `sanitizeProvenanceRecord()` keeps hash/summary/sources, no raw content. - * - `sanitizeProvenanceManifest()` sanitizes all records and manifest metadata. - * - `SENSITIVE_FIELD_NAMES` contains all expected sensitive fields. + * The promises a reader of a published bundle can check are asserted end to + * end in [`tests/evals/publish-safety.scenario.test.ts`](../../../../../tests/evals/publish-safety.scenario.test.ts): + * every sensitive field is stripped, unknown shapes are dropped, explanations + * carrying injection payloads never reach a public artifact, and provenance + * publishes hashes rather than prompt text. The cases that asserted those + * through `sanitizeCaseResultSummary()`, `sanitizeProvenanceRecord()`, + * `sanitizeProvenanceManifest()` and the `SENSITIVE_FIELD_NAMES` membership + * list were removed there; all four scenarios were watched fail against a + * neutered sanitizer before the deletion. * - * Test isolation: - * - No file I/O, network, git, or shell calls. - * - All fixtures are constructed inline. + * What is left here is deliberately internal: + * + * - **`assertPublishSafe()` / `assertJsonPublishSafe()`** — the publish-mode + * guards. While the allowlist projection works they never fire, so no + * written file reveals their behaviour. They exist to catch a future + * bypass, and these are the only tests that exercise one. + * - **`sanitizeScoreRecord()`, `dropUnknownFields()`, `REDACTED`, + * `truncateExplanation()`, `buildExplanation()`, `assertExplanationSafe()` + * and `FORBIDDEN_EXPLANATION_SOURCE_DESCRIPTORS`** — exported API with no + * production caller in this repository. The runners build explanations via + * `buildPublicExplanation()` in `langchain-agent-evals.ts` and redact with + * their own patterns, so nothing a user does reaches these, and no scenario + * can cover them. Kept, and flagged: while they stay uncalled they are + * candidates for removal, at which point these tests go with them. + * + * Test isolation: no file I/O, no network, no spawned process; fixtures inline. */ import { describe, expect, it } from "bun:test"; @@ -31,46 +39,15 @@ import { dropUnknownFields, FORBIDDEN_EXPLANATION_SOURCE_DESCRIPTORS, REDACTED, - SENSITIVE_FIELD_NAMES, - sanitizeCaseResultSummary, - sanitizeProvenanceManifest, - sanitizeProvenanceRecord, sanitizeScoreRecord, truncateExplanation, } from "../sanitizer.js"; -import type { - CaseResultSummary, - NormalizedScoreRecord, - PromptProvenanceManifest, - PromptProvenanceRecord, -} from "../types.js"; +import type { NormalizedScoreRecord } from "../types.js"; // --------------------------------------------------------------------------- // Fixture builders // --------------------------------------------------------------------------- -function makeCaseResultSummary( - overrides: Partial = {}, -): CaseResultSummary { - return { - caseId: "route-to-shuttle", - modelId: "anthropic/claude-sonnet-4.5", - suite: "loom-routing", - passed: true, - required: true, - weightedTotal: 0.85, - dimensionScores: { - routingCorrectness: { score: 1.0, applicable: true }, - delegationCorrectness: { score: 1.0, applicable: false }, - executionCompleteness: { score: 1.0, applicable: false }, - rationaleQuality: { score: 0.8, applicable: true }, - }, - scoredAt: "2026-01-01T00:00:00.000Z", - dryRun: false, - ...overrides, - }; -} - function makeNormalizedScoreRecord( overrides: Partial = {}, ): NormalizedScoreRecord { @@ -108,97 +85,6 @@ function makeNormalizedScoreRecord( }; } -function makeProvenanceRecord( - overrides: Partial = {}, -): PromptProvenanceRecord { - return { - agentName: "loom", - hash: "a".repeat(64), - byteLength: 4096, - charLength: 4000, - sources: [{ kind: "builtin", layer: "primary" }], - summary: - 'Agent "loom": 1 source(s) [builtin primary], hash sha256:aaaaaaaaaaaa…, 4000 chars, 4096 bytes', - gitSha: "abc123def456abc123def456abc123def456abc1", - capturedAt: "2026-01-01T00:00:00.000Z", - ...overrides, - }; -} - -function makeProvenanceManifest( - overrides: Partial = {}, -): PromptProvenanceManifest { - return { - version: 1, - producedAt: "2026-01-01T00:00:00.000Z", - gitSha: "abc123def456abc123def456abc123def456abc1", - records: [makeProvenanceRecord()], - ...overrides, - }; -} - -// --------------------------------------------------------------------------- -// SENSITIVE_FIELD_NAMES — blocklist completeness -// --------------------------------------------------------------------------- - -describe("SENSITIVE_FIELD_NAMES", () => { - it("contains composedPrompt", () => { - expect(SENSITIVE_FIELD_NAMES.has("composedPrompt")).toBe(true); - }); - - it("contains rawContent", () => { - expect(SENSITIVE_FIELD_NAMES.has("rawContent")).toBe(true); - }); - - it("contains rawPrompt", () => { - expect(SENSITIVE_FIELD_NAMES.has("rawPrompt")).toBe(true); - }); - - it("contains rawArtifact", () => { - expect(SENSITIVE_FIELD_NAMES.has("rawArtifact")).toBe(true); - }); - - it("contains rawArtifacts", () => { - expect(SENSITIVE_FIELD_NAMES.has("rawArtifacts")).toBe(true); - }); - - it("contains transcript", () => { - expect(SENSITIVE_FIELD_NAMES.has("transcript")).toBe(true); - }); - - it("contains rationale", () => { - expect(SENSITIVE_FIELD_NAMES.has("rationale")).toBe(true); - }); - - it("contains dimensionRationales", () => { - expect(SENSITIVE_FIELD_NAMES.has("dimensionRationales")).toBe(true); - }); - - it("contains toolArgs", () => { - expect(SENSITIVE_FIELD_NAMES.has("toolArgs")).toBe(true); - }); - - it("contains env", () => { - expect(SENSITIVE_FIELD_NAMES.has("env")).toBe(true); - }); - - it("contains cause", () => { - expect(SENSITIVE_FIELD_NAMES.has("cause")).toBe(true); - }); - - it("contains body", () => { - expect(SENSITIVE_FIELD_NAMES.has("body")).toBe(true); - }); - - it("contains logTail", () => { - expect(SENSITIVE_FIELD_NAMES.has("logTail")).toBe(true); - }); - - it("contains prompt (raw text)", () => { - expect(SENSITIVE_FIELD_NAMES.has("prompt")).toBe(true); - }); -}); - // --------------------------------------------------------------------------- // REDACTED constant // --------------------------------------------------------------------------- @@ -209,101 +95,6 @@ describe("REDACTED", () => { }); }); -// --------------------------------------------------------------------------- -// sanitizeCaseResultSummary -// --------------------------------------------------------------------------- - -describe("sanitizeCaseResultSummary", () => { - it("retains caseId", () => { - const summary = makeCaseResultSummary({ caseId: "my-case" }); - expect(sanitizeCaseResultSummary(summary).caseId).toBe("my-case"); - }); - - it("retains modelId", () => { - const summary = makeCaseResultSummary({ modelId: "openai/gpt-4o" }); - expect(sanitizeCaseResultSummary(summary).modelId).toBe("openai/gpt-4o"); - }); - - it("retains suite", () => { - const summary = makeCaseResultSummary({ suite: "tapestry-execution" }); - expect(sanitizeCaseResultSummary(summary).suite).toBe("tapestry-execution"); - }); - - it("retains passed", () => { - const summary = makeCaseResultSummary({ passed: false }); - expect(sanitizeCaseResultSummary(summary).passed).toBe(false); - }); - - it("retains required", () => { - const summary = makeCaseResultSummary({ required: false }); - expect(sanitizeCaseResultSummary(summary).required).toBe(false); - }); - - it("retains weightedTotal", () => { - const summary = makeCaseResultSummary({ weightedTotal: 0.42 }); - expect(sanitizeCaseResultSummary(summary).weightedTotal).toBeCloseTo(0.42); - }); - - it("retains scoredAt", () => { - const ts = "2026-06-10T12:00:00.000Z"; - const summary = makeCaseResultSummary({ scoredAt: ts }); - expect(sanitizeCaseResultSummary(summary).scoredAt).toBe(ts); - }); - - it("retains dryRun", () => { - const summary = makeCaseResultSummary({ dryRun: true }); - expect(sanitizeCaseResultSummary(summary).dryRun).toBe(true); - }); - - it("retains all four dimension scores", () => { - const summary = makeCaseResultSummary(); - const sanitized = sanitizeCaseResultSummary(summary); - const dims = sanitized.dimensionScores; - expect(dims.routingCorrectness.score).toBe(1.0); - expect(dims.delegationCorrectness.score).toBe(1.0); - expect(dims.executionCompleteness.score).toBe(1.0); - expect(dims.rationaleQuality.score).toBe(0.8); - }); - - it("retains applicable flags in dimensionScores", () => { - const summary = makeCaseResultSummary(); - const sanitized = sanitizeCaseResultSummary(summary); - expect(sanitized.dimensionScores.routingCorrectness.applicable).toBe(true); - expect(sanitized.dimensionScores.delegationCorrectness.applicable).toBe( - false, - ); - }); - - it("drops unknown top-level fields", () => { - // Cast to any to add extra fields simulating future additions - const summary = makeCaseResultSummary(); - (summary as unknown as Record).unknownField = - "should-be-dropped"; - - const sanitized = sanitizeCaseResultSummary(summary); - expect("unknownField" in sanitized).toBe(false); - }); - - it("output does not contain raw prompt text", () => { - const summary = makeCaseResultSummary(); - const sanitized = sanitizeCaseResultSummary(summary); - const json = JSON.stringify(sanitized); - expect(json).not.toContain("composedPrompt"); - expect(json).not.toContain("rawContent"); - expect(json).not.toContain('"transcript"'); - // "rationaleQuality" is a dimension name and is allowed; - // the literal field name "rationale" (with colon) must not appear - expect(json).not.toContain('"rationale":'); - }); - - it("is deterministic for identical inputs", () => { - const summary = makeCaseResultSummary(); - const s1 = JSON.stringify(sanitizeCaseResultSummary(summary)); - const s2 = JSON.stringify(sanitizeCaseResultSummary(summary)); - expect(s1).toBe(s2); - }); -}); - // --------------------------------------------------------------------------- // sanitizeScoreRecord // --------------------------------------------------------------------------- @@ -371,131 +162,6 @@ describe("sanitizeScoreRecord", () => { }); }); -// --------------------------------------------------------------------------- -// sanitizeProvenanceRecord -// --------------------------------------------------------------------------- - -describe("sanitizeProvenanceRecord", () => { - it("retains agentName", () => { - const record = makeProvenanceRecord({ agentName: "tapestry" }); - expect(sanitizeProvenanceRecord(record).agentName).toBe("tapestry"); - }); - - it("retains hash", () => { - const hash = "b".repeat(64); - const record = makeProvenanceRecord({ hash }); - expect(sanitizeProvenanceRecord(record).hash).toBe(hash); - }); - - it("retains byteLength and charLength", () => { - const record = makeProvenanceRecord({ byteLength: 8192, charLength: 8000 }); - const sanitized = sanitizeProvenanceRecord(record); - expect(sanitized.byteLength).toBe(8192); - expect(sanitized.charLength).toBe(8000); - }); - - it("retains summary", () => { - const record = makeProvenanceRecord({ summary: "Agent test summary" }); - expect(sanitizeProvenanceRecord(record).summary).toBe("Agent test summary"); - }); - - it("retains gitSha", () => { - const sha = `deadbeef${"0".repeat(32)}`; - const record = makeProvenanceRecord({ gitSha: sha }); - expect(sanitizeProvenanceRecord(record).gitSha).toBe(sha); - }); - - it("retains capturedAt", () => { - const ts = "2026-06-10T12:00:00.000Z"; - const record = makeProvenanceRecord({ capturedAt: ts }); - expect(sanitizeProvenanceRecord(record).capturedAt).toBe(ts); - }); - - it("retains sources", () => { - const sources = [ - { kind: "builtin" as const, layer: "primary" as const }, - { kind: "inline" as const, layer: "append" as const }, - ]; - const record = makeProvenanceRecord({ sources }); - const sanitized = sanitizeProvenanceRecord(record); - expect(sanitized.sources).toHaveLength(2); - expect(sanitized.sources[0]?.kind).toBe("builtin"); - }); - - it("does not contain raw prompt text fields", () => { - const record = makeProvenanceRecord(); - const sanitized = sanitizeProvenanceRecord(record); - expect("composedPrompt" in sanitized).toBe(false); - expect("rawPrompt" in sanitized).toBe(false); - expect("prompt" in sanitized).toBe(false); - }); - - it("serialized output contains no raw prompt fields", () => { - const record = makeProvenanceRecord(); - const json = JSON.stringify(sanitizeProvenanceRecord(record)); - expect(json).not.toContain('"composedPrompt"'); - expect(json).not.toContain('"rawPrompt"'); - }); - - it("is deterministic", () => { - const record = makeProvenanceRecord(); - const s1 = JSON.stringify(sanitizeProvenanceRecord(record)); - const s2 = JSON.stringify(sanitizeProvenanceRecord(record)); - expect(s1).toBe(s2); - }); -}); - -// --------------------------------------------------------------------------- -// sanitizeProvenanceManifest -// --------------------------------------------------------------------------- - -describe("sanitizeProvenanceManifest", () => { - it("retains version", () => { - const manifest = makeProvenanceManifest({ version: 2 }); - expect(sanitizeProvenanceManifest(manifest).version).toBe(2); - }); - - it("retains producedAt", () => { - const ts = "2026-06-10T12:00:00.000Z"; - const manifest = makeProvenanceManifest({ producedAt: ts }); - expect(sanitizeProvenanceManifest(manifest).producedAt).toBe(ts); - }); - - it("retains gitSha", () => { - const sha = `cafe${"0".repeat(36)}`; - const manifest = makeProvenanceManifest({ gitSha: sha }); - expect(sanitizeProvenanceManifest(manifest).gitSha).toBe(sha); - }); - - it("sanitizes all records", () => { - const manifest = makeProvenanceManifest({ - records: [ - makeProvenanceRecord({ agentName: "loom" }), - makeProvenanceRecord({ agentName: "tapestry", hash: "b".repeat(64) }), - ], - }); - const sanitized = sanitizeProvenanceManifest(manifest); - expect(sanitized.records).toHaveLength(2); - expect(sanitized.records[0]?.agentName).toBe("loom"); - expect(sanitized.records[1]?.agentName).toBe("tapestry"); - }); - - it("serialized manifest contains no raw prompt content", () => { - const manifest = makeProvenanceManifest(); - const json = JSON.stringify(sanitizeProvenanceManifest(manifest)); - expect(json).not.toContain('"composedPrompt"'); - expect(json).not.toContain('"rawPrompt"'); - expect(json).not.toContain('"prompt":'); - }); - - it("is deterministic", () => { - const manifest = makeProvenanceManifest(); - const s1 = JSON.stringify(sanitizeProvenanceManifest(manifest)); - const s2 = JSON.stringify(sanitizeProvenanceManifest(manifest)); - expect(s1).toBe(s2); - }); -}); - // --------------------------------------------------------------------------- // dropUnknownFields // --------------------------------------------------------------------------- @@ -750,62 +416,10 @@ describe("assertJsonPublishSafe", () => { }); // --------------------------------------------------------------------------- -// End-to-end: sanitize then assertPublishSafe +// localDiagnostic — blocked by the publish guards // --------------------------------------------------------------------------- -describe("sanitize then assertPublishSafe (round-trip)", () => { - it("sanitized CaseResultSummary passes assertPublishSafe", () => { - const summary = makeCaseResultSummary(); - const sanitized = sanitizeCaseResultSummary(summary); - const result = assertPublishSafe( - sanitized as unknown as Record, - ); - expect(result.isOk()).toBe(true); - }); - - it("sanitized ScoreRecord passes assertPublishSafe", () => { - const record = makeNormalizedScoreRecord(); - const sanitized = sanitizeScoreRecord(record); - const result = assertPublishSafe( - sanitized as unknown as Record, - ); - expect(result.isOk()).toBe(true); - }); - - it("sanitized CaseResultSummary passes assertJsonPublishSafe", () => { - const summary = makeCaseResultSummary(); - const sanitized = sanitizeCaseResultSummary(summary); - const json = JSON.stringify(sanitized); - const result = assertJsonPublishSafe(json); - expect(result.isOk()).toBe(true); - }); - - it("sanitized ScoreRecord passes assertJsonPublishSafe", () => { - const record = makeNormalizedScoreRecord(); - const sanitized = sanitizeScoreRecord(record); - const json = JSON.stringify(sanitized); - const result = assertJsonPublishSafe(json); - expect(result.isOk()).toBe(true); - }); - - it("sanitized ProvenanceManifest passes assertJsonPublishSafe", () => { - const manifest = makeProvenanceManifest(); - const sanitized = sanitizeProvenanceManifest(manifest); - const json = JSON.stringify(sanitized); - const result = assertJsonPublishSafe(json); - expect(result.isOk()).toBe(true); - }); -}); - -// --------------------------------------------------------------------------- -// localDiagnostic — blocked from publishable output -// --------------------------------------------------------------------------- - -describe("SENSITIVE_FIELD_NAMES includes localDiagnostic", () => { - it("SENSITIVE_FIELD_NAMES contains 'localDiagnostic'", () => { - expect(SENSITIVE_FIELD_NAMES.has("localDiagnostic")).toBe(true); - }); - +describe("the publish guards reject a local-only scorer diagnostic", () => { it("assertPublishSafe rejects an object with a localDiagnostic field", () => { const obj = { caseId: "some-case", diff --git a/tests/evals/publish-safety.scenario.test.ts b/tests/evals/publish-safety.scenario.test.ts new file mode 100644 index 00000000..555dff36 --- /dev/null +++ b/tests/evals/publish-safety.scenario.test.ts @@ -0,0 +1,825 @@ +/** + * Evals scenarios — what a hostile or careless result can push into a bundle. + * + * Bucket: Evals. The black box is the run directory `ArtifactBundleWriter` + * writes. Results go in — including results shaped in ways no runner is + * supposed to produce — and the files a reader, or tryweave.io, would find + * come out. + * + * [`published-bundle.scenario.test.ts`](./published-bundle.scenario.test.ts) + * covers the happy path: a run is written, traceable, immutable and + * reproducible. This file covers the adversarial one, and is the executable + * form of the promises in [`docs/eval-xss-policy.md`](../../docs/eval-xss-policy.md) + * and [`docs/eval-sanitization-and-publish-pipeline.md`](../../docs/eval-sanitization-and-publish-pipeline.md). + * Neither document may be weakened by what is asserted here. + * + * Two distinctions the assertions depend on: + * + * - **No file at all** may carry a value from a field the publish guard calls + * sensitive. That is an absolute: the run directory is local, but a leak + * into it is still a leak. + * - **No *public* artifact** may carry an injection payload. Only + * `bundle-index.json`, `public-report.json`, `public-report.md` and the + * dashboard indexes are ever uploaded; `score-.json` stays local and + * does carry the explanation text a reader never sees. + * + * Every absence assertion here has been watched go red against a neutered + * `sanitizeCaseResultSummary`, a neutered explanation validation step and a + * neutered Markdown value sanitizer. An absence that was never observed + * failing proves nothing. + */ + +import { describe, expect, it } from "bun:test"; +import { join } from "node:path"; +import { ArtifactBundleWriter } from "../../packages/cli/src/evals/artifact-bundle.js"; +import { EXPLANATION_MAX_CHARS } from "../../packages/cli/src/evals/report-schema.js"; +import { SENSITIVE_FIELD_NAMES } from "../../packages/cli/src/evals/sanitizer.js"; +import { + caseResult, + FIXED_GIT_SHA, + FIXED_TIMESTAMP, + filesUnder, + provenanceManifest, + runnerResult, + withBundleRoot, +} from "../support/evals.js"; + +// --------------------------------------------------------------------------- +// Publishing one run +// --------------------------------------------------------------------------- + +/** A summary carrying whatever a scenario wants to push at the publisher. */ +type HostileSummary = Record; + +/** + * Publishes one run containing a single case with `summary` merged in, with + * every optional artifact turned on — the Markdown report and the dashboard + * indexes are published too, so they are part of the black box. + */ +async function publishCase(root: string, summary: HostileSummary) { + const writer = new ArtifactBundleWriter(root); + const result = await writer.writeBundle({ + runnerResults: [ + runnerResult({ caseResults: [caseResult(summary as never)] }), + ], + provenanceManifest: provenanceManifest(), + gitSha: FIXED_GIT_SHA, + assembledAt: FIXED_TIMESTAMP, + writeMarkdown: true, + generateIndexes: true, + }); + + if (result.isErr()) { + expect(JSON.stringify(result.error)).toBe("bundle written"); + } + return result._unsafeUnwrap(); +} + +/** The names a run directory may ever upload, per `RUN_ARTIFACT_ALLOWLIST`. */ +const UPLOADED_RUN_FILES = new Set([ + "bundle-index.json", + "public-report.json", + "public-report.md", +]); + +/** Every file that can reach a reader: the uploaded run files and the indexes. */ +async function publicArtifacts(root: string): Promise { + const all = await filesUnder(root); + return all.filter((path) => { + const name = path.slice(path.lastIndexOf("/") + 1); + const isIndex = !path.includes(`${join(root, "runs")}/`); + return isIndex || UPLOADED_RUN_FILES.has(name); + }); +} + +/** The concatenated text of every artifact a reader could receive. */ +async function publicText(root: string): Promise { + const paths = await publicArtifacts(root); + const parts = await Promise.all(paths.map((p) => Bun.file(p).text())); + return parts.join("\n"); +} + +/** Names the offending file rather than failing on a bare boolean. */ +async function expectAbsentEverywhere( + root: string, + needle: string, +): Promise { + for (const path of await filesUnder(root)) { + const text = await Bun.file(path).text(); + if (text.includes(needle)) { + expect(`${path} contains ${needle}`).toBe("nothing contains it"); + } + } +} + +/** The single case entry in the published report, or `undefined`. */ +async function publishedCase( + root: string, +): Promise | undefined> { + const path = (await filesUnder(root)).find((p) => + p.endsWith("public-report.json"), + ); + if (path === undefined) return undefined; + const report = JSON.parse(await Bun.file(path).text()); + return report.suiteSummaries?.[0]?.cases?.[0]; +} + +/** + * The published case's id, asserted to carry no explanation. + * + * Returning the id rather than a boolean is deliberate: when assembly drops + * the whole report, `publishedCase` is `undefined` and a bare + * `expect(entry?.explanation).toBeUndefined()` passes while nothing was + * published at all. The caller compares the id, so the case must be there. + */ +async function caseWithoutExplanation(root: string): Promise { + const entry = await publishedCase(root); + expect(entry?.explanation).toBeUndefined(); + return entry?.caseId; +} + +/** The rendered Markdown report. */ +async function publishedMarkdown(root: string): Promise { + const path = (await filesUnder(root)).find((p) => + p.endsWith("public-report.md"), + ); + expect(path).toBeDefined(); + return Bun.file(path as string).text(); +} + +// --------------------------------------------------------------------------- +// Sensitive fields +// --------------------------------------------------------------------------- + +/** + * Every field name the publish guard blocks, listed here rather than read from + * the source. Reading `SENSITIVE_FIELD_NAMES` would make the table shrink + * silently when a name is removed; the drift check below compares the two. + */ +const SENSITIVE_FIELDS = [ + "composedPrompt", + "rawContent", + "rawPrompt", + "prompt", + "rawArtifact", + "rawArtifacts", + "toolArgs", + "arguments", + "tool_arguments", + "args", + "env", + "environment", + "envValue", + "cause", + "body", + "rawBody", + "errorBody", + "logTail", + "logs", + "logLines", + "rationale", + "dimensionRationales", + "transcript", + "localDiagnostic", +] as const; + +/** One unmistakable value per sensitive field, all on one case summary. */ +function everySensitiveField(): HostileSummary { + const summary: HostileSummary = {}; + for (const field of SENSITIVE_FIELDS) summary[field] = `LEAK-${field}`; + return summary; +} + +describe("a run's results carry every field the publish guard calls sensitive", () => { + it.each( + SENSITIVE_FIELDS.map((f) => [f] as const), + )("writes no file carrying what was in %s", async (field) => { + await withBundleRoot(async (root) => { + await publishCase(root, everySensitiveField()); + await expectAbsentEverywhere(root, `LEAK-${field}`); + }); + }); + + it("names none of those fields in any written file, so a grep for them stays clean", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, everySensitiveField()); + + for (const path of await filesUnder(root)) { + const text = await Bun.file(path).text(); + for (const field of SENSITIVE_FIELDS) { + if (text.includes(`"${field}"`)) { + expect(`${path} names ${field}`).toBe("no file names it"); + } + } + } + }); + }); + + it("publishes the score the run produced, so stripping the prompt does not strip the result", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, everySensitiveField()); + const entry = await publishedCase(root); + + expect(entry?.caseId).toBe("route-to-shuttle"); + expect(entry?.passed).toBe(true); + }); + }); + + it("has a case above for every field the guard blocks, so a new one cannot be added untested", () => { + expect([...SENSITIVE_FIELD_NAMES].sort()).toEqual( + [...SENSITIVE_FIELDS].sort(), + ); + }); +}); + +// --------------------------------------------------------------------------- +// Shapes no runner is supposed to produce +// --------------------------------------------------------------------------- + +/** + * Results shaped in ways the allowlist has never been told about. The promise + * is that the projection is positive — it copies named fields — so anything + * not named is dropped whatever shape it arrives in. + */ +const HOSTILE_SHAPES: ReadonlyArray< + readonly [name: string, summary: HostileSummary, needles: readonly string[]] +> = [ + [ + "an unknown scalar field", + { verdictNote: "SHAPE-scalar" }, + ["SHAPE-scalar", "verdictNote"], + ], + [ + "a sensitive field buried in a nested object", + { debug: { inner: { composedPrompt: "SHAPE-nested" } } }, + ["SHAPE-nested", '"debug"'], + ], + [ + "an array of objects each carrying a transcript", + { + turnLog: [{ transcript: "SHAPE-array" }, { transcript: "SHAPE-array2" }], + }, + ["SHAPE-array", "SHAPE-array2", '"turnLog"'], + ], + [ + "an array of bare strings", + { notes: ["SHAPE-bare-a", "SHAPE-bare-b"] }, + ["SHAPE-bare-a", "SHAPE-bare-b", '"notes"'], + ], + [ + "a field named after a prototype slot", + { constructorNote: "SHAPE-proto", toStringNote: "SHAPE-proto2" }, + ["SHAPE-proto", "SHAPE-proto2"], + ], + [ + "extra keys hidden inside an otherwise valid explanation", + { + publicExplanation: { + text: "routing matched", + source: "structured_signal", + rationale: "SHAPE-explanation", + }, + }, + ["SHAPE-explanation"], + ], + [ + "an extra key on the trajectory summary, whose allowlist is closed", + { + trajectorySummary: { + harnessDelegatedCorrectly: true, + observedSpawns: ["shuttle"], + observedToolCalls: 3, + harnessCompletedWithoutError: true, + rawTranscriptRef: "SHAPE-trajectory", + }, + }, + ["SHAPE-trajectory", "rawTranscriptRef"], + ], + [ + "a dimension score carrying the scorer's rationale alongside it", + { + dimensionScores: { + routingCorrectness: { + score: 1, + applicable: true, + rationale: "SHAPE-dimension", + }, + delegationCorrectness: { score: 1, applicable: false }, + executionCompleteness: { score: 1, applicable: false }, + rationaleQuality: { score: 0.8, applicable: true }, + }, + }, + ["SHAPE-dimension"], + ], +]; + +describe("a runner hands the publisher a result shaped in ways the allowlist never anticipated", () => { + it.each( + HOSTILE_SHAPES, + )("writes nothing from %s", async (_name, summary, needles) => { + await withBundleRoot(async (root) => { + await publishCase(root, summary); + for (const needle of needles) { + await expectAbsentEverywhere(root, needle); + } + }); + }); + + it.each( + HOSTILE_SHAPES, + )("publishes the case anyway when it carries %s, rather than failing the run", async (_name, summary) => { + await withBundleRoot(async (root) => { + await publishCase(root, summary); + + expect((await publishedCase(root))?.caseId).toBe("route-to-shuttle"); + }); + }); + + it("keeps the four trajectory fields a reader is allowed to see", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, { + trajectorySummary: { + harnessDelegatedCorrectly: true, + observedSpawns: ["shuttle"], + observedToolCalls: 3, + harnessCompletedWithoutError: true, + rawTranscriptRef: "SHAPE-trajectory", + }, + }); + + expect((await publishedCase(root))?.trajectorySummary).toEqual({ + harnessDelegatedCorrectly: true, + observedSpawns: ["shuttle"], + observedToolCalls: 3, + harnessCompletedWithoutError: true, + }); + }); + }); +}); + +// --------------------------------------------------------------------------- +// Explanation text +// --------------------------------------------------------------------------- + +/** + * Text that must never reach a rendering surface: chain-of-thought traces, + * transcript role markers, prompt delimiters, scorer-internal markers, secrets + * and the HTML injection vectors named in `docs/eval-xss-policy.md`. + */ +const INJECTION_PAYLOADS: ReadonlyArray = + [ + ["a trace", "it probably routed"], + ["a trace", "step one"], + ["a trace", "because"], + ["a trace", "notes"], + ["a User: transcript marker", "verdict\nUser: route this for me"], + ["an Assistant: transcript marker", "verdict\nAssistant: delegating now"], + ["a Human: transcript marker", "verdict\nHuman: route this"], + ["a System: transcript marker", "verdict\nSystem: you are loom"], + ["a Tool: transcript marker", "verdict\nTool: read(file)"], + ["a prompt delimiter", "you are loom"], + ["a delimiter", "route this"], + ["an delimiter", "route this"], + ["a delimiter", "the repo is"], + ["a rationale: marker", "rationale: the model chose shuttle"], + ["a score: marker", "score: 0.82 for routing"], + ["a justification: marker", "justification: it picked the right agent"], + ["an explanation: marker", "explanation: it picked the right agent"], + ["an sk- API key", "leaked sk-abcdefgh12345678"], + ["a Bearer token", "leaked Bearer abcdefghijklmnop"], + ["a GitHub token", "leaked ghp_abcdefgh12345678"], + ["a "], + ["a "], + ["an "], + ["an tag", ""], + ["an tag", ""], + ["a
tag", ""], + ["an inline event handler", ""], + ["a javascript: URI", "click javascript:alert(1)"], + ["a data: URI", "see data:text/html,hi"], + ["an attribute breakout", `" onmouseover="alert(1)`], + ]; + +describe("a case's explanation carries text a reader must never be shown", () => { + it.each( + INJECTION_PAYLOADS, + )("keeps %s out of every artifact a reader can receive, and still publishes the case", async (_name, text) => { + await withBundleRoot(async (root) => { + const marker = "PAYLOAD-MARKER"; + await publishCase(root, { + publicExplanation: { + text: `${marker} ${text}`, + source: "operator_note", + }, + }); + + const published = await publicText(root); + expect(published).not.toContain(marker); + expect(published).not.toContain(text); + + // Dropping the whole report would also satisfy the two assertions + // above. The promise is narrower: the explanation goes, the result + // stays, and the run still reaches the dashboard. + expect((await publishedCase(root))?.caseId).toBe("route-to-shuttle"); + }); + }); + + it("publishes the case without its explanation rather than losing the result", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, { + publicExplanation: { + text: "", + source: "operator_note", + }, + }); + const entry = await publishedCase(root); + + expect(entry?.caseId).toBe("route-to-shuttle"); + expect(entry?.scoreBucket).toBe("pass"); + expect(entry?.explanation).toBeUndefined(); + }); + }); +}); + +describe("a case's explanation declares where its text came from", () => { + const ALLOWED = [ + "rubric_template", + "score_bucket_label", + "structured_signal", + "operator_note", + ] as const; + + it.each( + ALLOWED.map((v) => [v] as const), + )("publishes an explanation sourced from %s", async (source) => { + await withBundleRoot(async (root) => { + await publishCase(root, { + publicExplanation: { text: "routing matched", source }, + }); + + expect((await publishedCase(root))?.explanation).toEqual({ + text: "routing matched", + source, + }); + }); + }); + + const REJECTED = [ + "raw_rationale", + "dimension_rationale", + "transcript_content", + "llm_freeform_summary", + "raw_content", + "", + "whatever-the-runner-felt-like", + ] as const; + + it.each( + REJECTED.map((v) => [v] as const), + )("drops an explanation sourced from %s, however clean its text looks", async (source) => { + await withBundleRoot(async (root) => { + await publishCase(root, { + publicExplanation: { text: "PLAUSIBLE-TEXT", source }, + }); + + expect(await caseWithoutExplanation(root)).toBe("route-to-shuttle"); + expect(await publicText(root)).not.toContain("PLAUSIBLE-TEXT"); + }); + }); + + it("drops an explanation that declares no source at all", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, { + publicExplanation: { text: "SOURCELESS-TEXT" }, + }); + + expect(await caseWithoutExplanation(root)).toBe("route-to-shuttle"); + expect(await publicText(root)).not.toContain("SOURCELESS-TEXT"); + }); + }); + + it("drops an explanation that carries no text", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, { + publicExplanation: { source: "operator_note" }, + }); + + expect(await caseWithoutExplanation(root)).toBe("route-to-shuttle"); + }); + }); + + it("drops an empty explanation instead of publishing a blank cell", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, { + publicExplanation: { text: "", source: "operator_note" }, + }); + + expect(await caseWithoutExplanation(root)).toBe("route-to-shuttle"); + }); + }); +}); + +describe("a case's explanation runs long", () => { + const atLimit = `LIMIT${"y".repeat(EXPLANATION_MAX_CHARS - 5)}`; + const overLimit = `${atLimit}z`; + + it("publishes an explanation of exactly the published limit", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, { + publicExplanation: { text: atLimit, source: "operator_note" }, + }); + + expect((await publishedCase(root))?.explanation).toEqual({ + text: atLimit, + source: "operator_note", + }); + }); + }); + + it("drops an explanation one character over the limit, rather than truncating it", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, { + publicExplanation: { text: overLimit, source: "operator_note" }, + }); + + expect(await caseWithoutExplanation(root)).toBe("route-to-shuttle"); + expect(await publicText(root)).not.toContain(overLimit); + }); + }); + + it("holds that limit at 300 characters, which the dashboard lays its cells out around", () => { + expect(EXPLANATION_MAX_CHARS).toBe(300); + }); +}); + +// --------------------------------------------------------------------------- +// The scores themselves +// --------------------------------------------------------------------------- + +describe("a maintainer reads the scores a published run recorded", () => { + it("publishes each case's identity, verdict and timing", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, {}); + + expect(await publishedCase(root)).toMatchObject({ + caseId: "route-to-shuttle", + modelId: "anthropic/claude-sonnet-4.5", + suite: "loom-routing", + passed: true, + required: true, + dryRun: false, + scoredAt: FIXED_TIMESTAMP, + }); + }); + }); + + it("publishes every scoring dimension with its score and whether it applied", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, {}); + const scorePath = (await filesUnder(root)).find((p) => + p.endsWith("score-loom-routing.json"), + ); + expect(scorePath).toBeDefined(); + const row = JSON.parse(await Bun.file(scorePath as string).text()) + .results[0]; + + expect(row.weightedTotal).toBe(0.9); + expect(row.dimensionScores).toEqual({ + routingCorrectness: { score: 1, applicable: true }, + delegationCorrectness: { score: 1, applicable: false }, + executionCompleteness: { score: 1, applicable: false }, + rationaleQuality: { score: 0.8, applicable: true }, + }); + }); + }); + + const BUCKETS: ReadonlyArray = [ + [1, "pass"], + [0.9, "pass"], + [0.89, "partial"], + [0.5, "partial"], + [0.49, "fail"], + [0, "fail"], + ]; + + it.each( + BUCKETS, + )("buckets a weighted total of %s as %s, which is what a reader skims", async (weightedTotal, bucket) => { + await withBundleRoot(async (root) => { + await publishCase(root, { + weightedTotal, + passed: weightedTotal >= 0.9, + }); + + expect((await publishedCase(root))?.scoreBucket).toBe(bucket); + }); + }); + + it("buckets a dry run as skip whatever it scored, so a fixture check never reads as a result", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, { weightedTotal: 0.95, dryRun: true }); + + expect((await publishedCase(root))?.scoreBucket).toBe("skip"); + }); + }); +}); + +// --------------------------------------------------------------------------- +// Values that are not explanations +// --------------------------------------------------------------------------- + +describe("a case id carries markup a dashboard would otherwise render", () => { + const hostileId = ""; + const pipedModel = "anthropic|claude-sonnet-4.5"; + + it("leaves the markup out of the Markdown report entirely", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, { caseId: hostileId, modelId: pipedModel }); + const markdown = await publishedMarkdown(root); + + expect(markdown).not.toContain(" { + await withBundleRoot(async (root) => { + await publishCase(root, { caseId: hostileId, modelId: pipedModel }); + + expect(await publishedMarkdown(root)).toContain( + "anthropic|claude-sonnet-4.5", + ); + }); + }); + + it("carries the case id verbatim in the JSON, where escaping is the dashboard's job", async () => { + // Recorded, not endorsed: `docs/eval-xss-policy.md` places case-id escaping + // in layer 3 (`escapeHtml()` before `innerHTML`), not at the schema. Case + // ids come from repo-owned fixtures rather than model output, so the JSON + // is allowed to carry them raw. A consumer that renders this field without + // escaping it is the vulnerability, and this pins the contract it must meet. + await withBundleRoot(async (root) => { + await publishCase(root, { caseId: hostileId, modelId: pipedModel }); + + expect((await publishedCase(root))?.caseId).toBe(hostileId); + }); + }); +}); + +// --------------------------------------------------------------------------- +// What the website is promised +// --------------------------------------------------------------------------- + +describe("the website fetches a published run", () => { + it("stamps the public report and each suite summary with the versions it pins", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, {}); + const path = (await filesUnder(root)).find((p) => + p.endsWith("public-report.json"), + ); + const report = JSON.parse(await Bun.file(path as string).text()); + + expect(report.schemaVersion).toBe(1); + expect(report.suiteSummaries[0].schemaVersion).toBe(2); + }); + }); + + it("stamps every dashboard index with a schema version, since an unversioned one is rejected", async () => { + await withBundleRoot(async (root) => { + const written = await publishCase(root, {}); + expect(written.indexFilesWritten.length).toBeGreaterThan(0); + + for (const name of written.indexFilesWritten) { + const parsed = JSON.parse(await Bun.file(join(root, name)).text()); + expect(`${name}:${parsed.schemaVersion}`).toBe(`${name}:1`); + } + }); + }); + + it("dates every index the dashboard re-fetches, so staleness can be judged", async () => { + // `model-comparison-.json` is the exception and carries `runId` + // instead: it is regenerated per run rather than accumulated across runs. + await withBundleRoot(async (root) => { + const written = await publishCase(root, {}); + + for (const name of written.indexFilesWritten) { + const parsed = JSON.parse(await Bun.file(join(root, name)).text()); + const freshness = name.startsWith("model-comparison-") + ? parsed.runId + : parsed.updatedAt; + expect(`${name}:${typeof freshness}`).toBe(`${name}:string`); + } + }); + }); + + it("publishes the indexes the dashboard's fetch chain walks", async () => { + await withBundleRoot(async (root) => { + const written = await publishCase(root, {}); + + expect([...written.indexFilesWritten].sort()).toEqual( + [ + "dashboard-manifest.json", + `model-comparison-${written.runId}.json`, + "last-N-runs.json", + "latest.json", + "scenario-history-loom-routing.json", + "suite-history-loom-routing.json", + ].sort(), + ); + }); + }); + + it("names only uploadable files in the bundle index, so no local artifact is advertised", async () => { + await withBundleRoot(async (root) => { + const written = await publishCase(root, {}); + const index = JSON.parse( + await Bun.file(join(written.bundleDir, "bundle-index.json")).text(), + ); + + for (const name of index.publicFiles) { + expect(`${name} is uploadable`).toBe( + `${UPLOADED_RUN_FILES.has(name) ? name : "NOT-UPLOADABLE"} is uploadable`, + ); + } + expect(index.publicFiles).toContain("public-report.json"); + }); + }); +}); + +describe("a run records a case with no id at all", () => { + it("publishes no public report for the run, because the report cannot be validated", async () => { + await withBundleRoot(async (root) => { + await publishCase(root, { caseId: "" }); + const names = (await filesUnder(root)).map((p) => + p.slice(p.lastIndexOf("/") + 1), + ); + + expect(names).not.toContain("public-report.json"); + expect(names).not.toContain("public-report.md"); + }); + }); + + it("reports the write as a success regardless, so the run goes missing from the dashboard without a word", async () => { + // Recorded as observed. `writeBundle` treats public-report assembly failure + // as non-fatal, so one malformed case id costs the whole run its dashboard + // presence and nothing in the result says so. + await withBundleRoot(async (root) => { + const written = await publishCase(root, { caseId: "" }); + + expect(written.runId).toBeTruthy(); + expect(written.indexFilesWritten).toEqual([]); + }); + }); +}); + +// --------------------------------------------------------------------------- +// Provenance +// --------------------------------------------------------------------------- + +describe("a maintainer publishes a run that traced the prompts it used", () => { + it("publishes each agent's prompt hash and size, so a score can be tied to a prompt", async () => { + await withBundleRoot(async (root) => { + const written = await publishCase(root, {}); + const manifest = JSON.parse( + await Bun.file( + join(written.bundleDir, "provenance-manifest.json"), + ).text(), + ); + + expect( + manifest.records.map((r: { agentName: string }) => r.agentName), + ).toEqual(["loom", "tapestry", "shuttle"]); + expect(manifest.records[0]).toMatchObject({ + hash: "a".repeat(64), + byteLength: 4096, + charLength: 4000, + gitSha: FIXED_GIT_SHA, + }); + }); + }); + + it("publishes the hash rather than the prompt, so provenance leaks no prompt text", async () => { + await withBundleRoot(async (root) => { + const writer = new ArtifactBundleWriter(root); + const manifest = provenanceManifest(); + const result = await writer.writeBundle({ + runnerResults: [runnerResult()], + provenanceManifest: { + ...manifest, + records: manifest.records.map((record) => ({ + ...record, + composedPrompt: "PROVENANCE-LEAK", + promptText: "PROVENANCE-LEAK-2", + })), + } as never, + gitSha: FIXED_GIT_SHA, + assembledAt: FIXED_TIMESTAMP, + writeMarkdown: true, + }); + expect(result.isOk()).toBe(true); + + await expectAbsentEverywhere(root, "PROVENANCE-LEAK"); + await expectAbsentEverywhere(root, "promptText"); + }); + }); +}); From be6688ec14d565b22765c023dfeb811c58993e17 Mon Sep 17 00:00:00 2001 From: pgermishuys Date: Sun, 20 Sep 2026 20:31:58 +0000 Subject: [PATCH 2/2] docs: count the sanitizer migration in one measure The migration table compared source it() lines for the unit files against runtime cases for the scenarios. A table-driven it.each is one case in the source and many at runtime, and the scenarios lean on tables far harder than the deleted unit tests did, so the totals were not like-for-like. Measured consistently: 328 unit source cases to 203, with 26 scenario source cases added that run as 113. The conclusion is unchanged and was if anything understated. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01DisVZW27sd6Pe7uhbjXNve --- .codesight/CODESIGHT.md | 8 ++++---- .codesight/coverage.md | 2 +- .codesight/graph.md | 4 ++-- docs/testing-strategy.md | 20 +++++++++++++------- 4 files changed, 20 insertions(+), 14 deletions(-) diff --git a/.codesight/CODESIGHT.md b/.codesight/CODESIGHT.md index de998e36..2ba07606 100644 --- a/.codesight/CODESIGHT.md +++ b/.codesight/CODESIGHT.md @@ -5,7 +5,7 @@ > 0 routes | 0 models | 0 components | 200 lib files | 25 env vars | 7 middleware | 1 events | 0% test coverage > **Token savings:** this file is ~18,200 tokens. Without it, AI exploration would cost ~66,400 tokens. **Saves ~48,200 tokens per conversation.** -> **Last scanned:** 2026-09-20 20:22 — re-run after significant changes +> **Last scanned:** 2026-09-20 20:32 — re-run after significant changes --- @@ -984,11 +984,11 @@ - `packages/cli/src/theme/colors.ts` — imported by **22** files - `packages/cli/src/fs/file-system.ts` — imported by **20** files - `packages/cli/src/evals/openrouter-client.ts` — imported by **20** files +- `packages/cli/src/evals/report-schema.ts` — imported by **19** files - `packages/adapters/opencode2/src/sdk-types.ts` — imported by **16** files - `packages/engine/src/runtime/types.ts` — imported by **16** files - `packages/cli/src/args.ts` — imported by **15** files - `packages/engine/src/runtime/store.ts` — imported by **13** files -- `packages/cli/src/evals/report-schema.ts` — imported by **12** files - `packages/engine/src/logger.ts` — imported by **12** files - `packages/engine/src/compose.ts` — imported by **11** files - `packages/engine/src/runtime/errors.ts` — imported by **11** files @@ -1007,11 +1007,11 @@ - `packages/cli/src/theme/colors.ts` ← `packages/cli/src/__tests__/theme.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/config-validation-errors.test.ts`, `packages/cli/src/commands/__tests__/eval.test.ts`, `packages/cli/src/commands/__tests__/init.test.ts` +17 more - `packages/cli/src/fs/file-system.ts` ← `packages/cli/src/__tests__/file-system.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/init.test.ts`, `packages/cli/src/commands/__tests__/legacy-upgrade-regression.test.ts`, `packages/cli/src/commands/__tests__/migrate-conversion.test.ts` +15 more - `packages/cli/src/evals/openrouter-client.ts` ← `packages/cli/src/evals/__tests__/loom-routing-runner.test.ts`, `packages/cli/src/evals/__tests__/loom-routing-runner.trajectory.test.ts`, `packages/cli/src/evals/__tests__/pattern-planning-runner.test.ts`, `packages/cli/src/evals/__tests__/runner.test.ts`, `packages/cli/src/evals/__tests__/shuttle-execution-runner.test.ts` +15 more +- `packages/cli/src/evals/report-schema.ts` ← `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts` +14 more - `packages/adapters/opencode2/src/sdk-types.ts` ← `packages/adapters/opencode2/src/__tests__/reconcile-agent.test.ts`, `packages/adapters/opencode2/src/adapter.ts`, `packages/adapters/opencode2/src/errors.ts`, `packages/adapters/opencode2/src/plugin.ts`, `packages/adapters/opencode2/src/reconcile-agent.ts` +11 more - `packages/engine/src/runtime/types.ts` ← `packages/engine/src/__tests__/runtime-command-operations.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts` +11 more - `packages/cli/src/args.ts` ← `packages/cli/src/__tests__/args.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/config-validation-errors.test.ts`, `packages/cli/src/commands/__tests__/eval.test.ts`, `packages/cli/src/commands/__tests__/init.test.ts` +10 more - `packages/engine/src/runtime/store.ts` ← `packages/engine/src/__tests__/runtime-journal.test.ts`, `packages/engine/src/execution-lifecycle/artifacts.ts`, `packages/engine/src/execution-lifecycle/dispatch.ts`, `packages/engine/src/execution-lifecycle/inspection.ts`, `packages/engine/src/execution-lifecycle/interrupts.ts` +8 more -- `packages/cli/src/evals/report-schema.ts` ← `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/e2e-fixture-flow.test.ts`, `packages/cli/src/evals/__tests__/langchain-agent-evals.test.ts` +7 more --- @@ -1024,7 +1024,7 @@ # Test Coverage > **0%** of routes and models are covered by tests -> 205 test files found +> 204 test files found --- diff --git a/.codesight/coverage.md b/.codesight/coverage.md index 3f026d70..121aea07 100644 --- a/.codesight/coverage.md +++ b/.codesight/coverage.md @@ -1,4 +1,4 @@ # Test Coverage > **0%** of routes and models are covered by tests -> 205 test files found +> 204 test files found diff --git a/.codesight/graph.md b/.codesight/graph.md index 33751dcf..8f406762 100644 --- a/.codesight/graph.md +++ b/.codesight/graph.md @@ -7,11 +7,11 @@ - `packages/cli/src/theme/colors.ts` — imported by **22** files - `packages/cli/src/fs/file-system.ts` — imported by **20** files - `packages/cli/src/evals/openrouter-client.ts` — imported by **20** files +- `packages/cli/src/evals/report-schema.ts` — imported by **19** files - `packages/adapters/opencode2/src/sdk-types.ts` — imported by **16** files - `packages/engine/src/runtime/types.ts` — imported by **16** files - `packages/cli/src/args.ts` — imported by **15** files - `packages/engine/src/runtime/store.ts` — imported by **13** files -- `packages/cli/src/evals/report-schema.ts` — imported by **12** files - `packages/engine/src/logger.ts` — imported by **12** files - `packages/engine/src/compose.ts` — imported by **11** files - `packages/engine/src/runtime/errors.ts` — imported by **11** files @@ -30,8 +30,8 @@ - `packages/cli/src/theme/colors.ts` ← `packages/cli/src/__tests__/theme.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/config-validation-errors.test.ts`, `packages/cli/src/commands/__tests__/eval.test.ts`, `packages/cli/src/commands/__tests__/init.test.ts` +17 more - `packages/cli/src/fs/file-system.ts` ← `packages/cli/src/__tests__/file-system.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/init.test.ts`, `packages/cli/src/commands/__tests__/legacy-upgrade-regression.test.ts`, `packages/cli/src/commands/__tests__/migrate-conversion.test.ts` +15 more - `packages/cli/src/evals/openrouter-client.ts` ← `packages/cli/src/evals/__tests__/loom-routing-runner.test.ts`, `packages/cli/src/evals/__tests__/loom-routing-runner.trajectory.test.ts`, `packages/cli/src/evals/__tests__/pattern-planning-runner.test.ts`, `packages/cli/src/evals/__tests__/runner.test.ts`, `packages/cli/src/evals/__tests__/shuttle-execution-runner.test.ts` +15 more +- `packages/cli/src/evals/report-schema.ts` ← `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts` +14 more - `packages/adapters/opencode2/src/sdk-types.ts` ← `packages/adapters/opencode2/src/__tests__/reconcile-agent.test.ts`, `packages/adapters/opencode2/src/adapter.ts`, `packages/adapters/opencode2/src/errors.ts`, `packages/adapters/opencode2/src/plugin.ts`, `packages/adapters/opencode2/src/reconcile-agent.ts` +11 more - `packages/engine/src/runtime/types.ts` ← `packages/engine/src/__tests__/runtime-command-operations.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts`, `packages/engine/src/__tests__/status-control.test.ts` +11 more - `packages/cli/src/args.ts` ← `packages/cli/src/__tests__/args.test.ts`, `packages/cli/src/cli.ts`, `packages/cli/src/commands/__tests__/config-validation-errors.test.ts`, `packages/cli/src/commands/__tests__/eval.test.ts`, `packages/cli/src/commands/__tests__/init.test.ts` +10 more - `packages/engine/src/runtime/store.ts` ← `packages/engine/src/__tests__/runtime-journal.test.ts`, `packages/engine/src/execution-lifecycle/artifacts.ts`, `packages/engine/src/execution-lifecycle/dispatch.ts`, `packages/engine/src/execution-lifecycle/inspection.ts`, `packages/engine/src/execution-lifecycle/interrupts.ts` +8 more -- `packages/cli/src/evals/report-schema.ts` ← `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/artifact-bundle.test.ts`, `packages/cli/src/evals/__tests__/e2e-fixture-flow.test.ts`, `packages/cli/src/evals/__tests__/langchain-agent-evals.test.ts` +7 more diff --git a/docs/testing-strategy.md b/docs/testing-strategy.md index 434e0bd3..e50c81d4 100644 --- a/docs/testing-strategy.md +++ b/docs/testing-strategy.md @@ -267,15 +267,21 @@ internal branches. What stays is what a user cannot observe from outside: The same rule applied to the evals sanitizer and report schemas: +Counts need one measure to be comparable. A table-driven `it.each` is one +case in the source and many at runtime, and the scenarios lean on tables far +harder than the unit tests did, so the two are quoted separately rather than +summed: + | | Before | After | | --- | --- | --- | -| `sanitizer.test.ts` | 140 | 91 | -| `report-schema.test.ts` | 188 | 112 | -| Scenario cases | 12 | 125 | -| Total | 340 | 328 | - -Here the count barely moves, and that is the honest result: 125 scenario cases -replaced 125 unit cases, because the deleted ones were an enumeration +| `sanitizer.test.ts` (source cases) | 140 | 91 | +| `report-schema.test.ts` (source cases) | 188 | 112 | +| **Unit total (source cases)** | **328** | **203** | +| Scenarios added (source cases) | — | 26 | +| Scenarios added (cases at runtime) | — | 113 | + +125 unit cases went and 26 scenario cases arrived, running as 113. The +reduction is real, but it is not the point: the deleted ones were an enumeration (`"contains composedPrompt"`, `"includes a pattern for html_script_tag"`) whose user-visible form is an equally long table of hostile inputs fed through the real bundle writer. The gain is not fewer tests but tests that fail when a