diff --git a/.github/workflows/ci-docs.yml b/.github/workflows/ci-docs.yml deleted file mode 100644 index b45551c..0000000 --- a/.github/workflows/ci-docs.yml +++ /dev/null @@ -1,19 +0,0 @@ -# Companion to ci.yml: docs/deploy-only PRs produce the SAME check name ("ci / test") as a no-op, -# so "test" can be a required branch-protection check without docs PRs hanging at "Expected" — -# and without burning a full build (~5s vs ~3min). GitHub's documented pattern for paths-ignore -# with required checks. -name: ci - -on: - pull_request: - paths: ['**.md', 'docs/**', 'deploy/**', '.gitignore'] - -permissions: - contents: read - -jobs: - test: - runs-on: ubuntu-latest - timeout-minutes: 2 - steps: - - run: echo "Docs/deploy-only change — build not required; gate satisfied." diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0aa2e46..3bd0fef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,19 +1,14 @@ -# CI: the impartial merge gate — build + tests + coverage threshold. -# Tuned for minimal Actions minutes: -# - Linux runner only (1x minute multiplier) -# - one job, one `dotnet test` (restore+build+test in a single invocation) -# - NuGet cache keyed on csproj + build-props hashes (warm restore = seconds) -# - docs/deploy-only PRs are handled by ci-docs.yml (same check name, no-op) so the -# required check is always satisfiable without a full build -# - superseded PR runs are cancelled; main pushes always complete (evidence trail) +# CI: the impartial merge gate — ONE workflow, ONE job, ONE required check name ("ci / test"). +# Every PR and every main push runs this job, so the required check always reports exactly once. +# A cheap first step decides whether code changed; docs/deploy-only changes finish in seconds with +# success, anything else runs the full build + tests + coverage gate. (Previously a docs-only twin +# workflow shared the check name, and a mixed change could produce two "test" results.) name: ci on: pull_request: - paths-ignore: ['**.md', 'docs/**', 'deploy/**', '.gitignore'] push: branches: [main] - paths-ignore: ['**.md', 'docs/**', 'deploy/**', '.gitignore'] permissions: contents: read @@ -25,24 +20,51 @@ concurrency: jobs: test: runs-on: ubuntu-latest - timeout-minutes: 10 + timeout-minutes: 15 steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Decide whether code changed + id: scope + shell: bash + run: | + if [ "${{ github.event_name }}" = "pull_request" ]; then + BASE="${{ github.event.pull_request.base.sha }}"; HEAD="${{ github.event.pull_request.head.sha }}" + else + BASE="${{ github.event.before }}"; HEAD="${{ github.sha }}" + fi + if [ -z "$BASE" ] || [ "$BASE" = "0000000000000000000000000000000000000000" ] || ! git cat-file -e "$BASE" 2>/dev/null; then + echo "code=true" >> "$GITHUB_OUTPUT"; echo "No usable base — running the full build."; exit 0 + fi + CHANGED=$(git diff --name-only "$BASE" "$HEAD") + echo "$CHANGED" + CODE=$(echo "$CHANGED" | grep -Ev '(\.md$|^docs/|^deploy/|^\.gitignore$)' || true) + if [ -n "$CODE" ]; then echo "code=true" >> "$GITHUB_OUTPUT"; else echo "code=false" >> "$GITHUB_OUTPUT"; fi + + - name: Docs/deploy-only change — build not required + if: steps.scope.outputs.code != 'true' + run: echo "Only docs/deploy files changed; gate satisfied without a build." - uses: actions/setup-dotnet@v4 + if: steps.scope.outputs.code == 'true' with: dotnet-version: 10.0.x - uses: actions/cache@v4 + if: steps.scope.outputs.code == 'true' with: path: ~/.nuget/packages key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/Directory.Build.props', '**/Directory.Packages.props') }} restore-keys: nuget-${{ runner.os }}- - name: Test with coverage - run: dotnet test -c Release --collect:"XPlat Code Coverage" --settings tests/coverlet.runsettings --results-directory ./coverage + if: steps.scope.outputs.code == 'true' + run: dotnet test tests/Covenant.Tests -c Release --disable-build-servers --collect:"XPlat Code Coverage" --settings tests/coverlet.runsettings --results-directory ./coverage - name: Enforce coverage threshold (line >= 0.80) + if: steps.scope.outputs.code == 'true' run: | COUNT=$(find ./coverage -name 'coverage.cobertura.xml' | wc -l) test "$COUNT" -eq 1 || { echo "expected exactly 1 coverage report (single test project), found $COUNT"; exit 1; } diff --git a/CLAUDE.md b/CLAUDE.md index 93793d7..913173f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,7 +5,7 @@ Covenant is a **regulated AI governance & FinOps control plane** for LLM inferen This file is always loaded. Area-specific rules live in nested `CLAUDE.md` files (see Map). Keep this file thin; put detail in the area files. ## Prime directives (never violate) -1. **We are not building a gateway.** Implement the smallest viable canonical proxy core; spend effort on governance, FinOps, and evidence — that is the moat. Don't chase provider breadth. +1. **We are not building a gateway.** Implement the smallest viable canonical proxy core; spend effort on governance, FinOps, and evidence — that is the moat. Don't chase provider breadth (OpenAI, Anthropic, Ollama/OpenAI-compatible only). Governed routing, approved fallback, cost attribution and request inspection ARE in scope (ADR-0013) — they are governance, not gateway breadth. 2. **Governance is pipeline middleware, never a bolt-on.** Policy, attribution, audit, and budgets are ordered stages in the request pipeline. 3. **Fail-closed.** No policy match → deny. Misconfig → refuse to start. Never default to an unapproved model. 4. **The perimeter is sacred.** No prompt, response, or metadata leaves the customer boundary. No phone-home. Egress only to the customer-approved model allow-list. @@ -29,6 +29,5 @@ This file is always loaded. Area-specific rules live in nested `CLAUDE.md` files - Prefer the standard library and minimal dependencies; every dependency is audited (license + provenance). ## Status / source of truth -Product spec: `docs/PRD-regulated-ai-governance-finops-v0.1.md`. -Current phase: pre-build, defining architecture. -First build target — the **P0 demo**: governed proxy → classification routing → real-time attribution → budget/kill switch → tamper-evident audit → one compliance-evidence export. +Product spec: `docs/PRD-regulated-ai-governance-finops-v0.1.md` (not yet written). Current iteration: `docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md`. +Current phase: P0 built (governed proxy, classification routing, attribution, budgets/pause, tamper-evident audit, evidence export, embedded console). Now: console v2 — editable versioned configuration (ADR-0011), console inference as authorized test applications (ADR-0012), fallback + real traces (ADR-0013), budget reservations (ADR-0014). diff --git a/docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md b/docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md new file mode 100644 index 0000000..4832cf0 --- /dev/null +++ b/docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md @@ -0,0 +1,285 @@ +# Covenant console v2 implementation specification + +Owner: Alex Kaziuka. Prepared 16 October 2026. +Baseline: `main`, PR #6 merge `9371dbe` (310 local tests passing at review). +Audience: Claude Code implementing the next iteration, and Codex reviewing it. + +## 1. Assignment and scope + +Turn Covenant into a usable governance control plane and a credible conference demonstration. Implement the work below; do not deliver another static prototype or a visual reskin over read-only configuration. + +The intended operator journey is: + +Connect once → configure approved local/cloud models → define routes and budgets → run a request as an application → watch the actual decision and execution → inspect cost and evidence. + +Read root and area-specific `CLAUDE.md`, existing ADRs, `docs/ui-api-contract.md`, and the current implementation first. This specification supersedes the read-only UI requirements in the earlier UI brief/tasks. Update the old documents to point to this specification so contradictory instructions do not persist. Preserve the existing .NET/Blazor architecture and embedded single-appliance packaging. Do not migrate to React or add an external database/service solely for this redesign. + +The root statement 'we are not building a gateway' means avoid unrelated provider breadth. It does not exclude the governed routing, fallback, cost attribution and request inspection explicitly required here. Update stale product-status wording and record the clarified scope. + +Create a new feature branch from current main. Preserve unrelated user work. Make small conventional commits. Do not automatically merge this iteration: deliver a reviewable branch with executed verification results. + +Required now: editable connections, routing policies, budgets and operational settings; a usable request workspace; authenticated test-application selection; real processing traces; approved fallback; exact cache visibility; cost and evidence workflows; visual and responsive improvements. + +Not required in this iteration: general-purpose enterprise IAM, additional providers beyond OpenAI/Anthropic/Ollama, model training, autonomous agents, semantic caching, RAG ingestion, or automatic prompt rewriting/compression. Do not imply these exist. Quality-preserving prompt optimization cannot be promised without task-specific evaluation. Provide the cost/route/cache explanations and evaluation fixtures described below instead. + +## 2. Non-negotiable behavior + +- No match, invalid active configuration, or no approved destination means refusal. Never silently send sensitive data to cloud. +- Keep administrator, application and provider credentials distinct internally. Fix the workflow rather than treating an admin token as an application key. +- Provider secrets stay server-side. Existing environment/vault references are sufficient; adding a browser secret editor is not required. UI can choose a configured secret reference and show whether it is available, never its value. +- Configuration changes are authenticated, validated, versioned, auditable and reversible. A failed update must leave the last valid configuration active. +- Every request binds to one configuration version. No mixture of old policy/new pricing/new provider settings during one request. +- Preserve legacy audit verification. New fields are additive; absent historical data is 'Not recorded', never invented. +- No fabricated stage timing, savings, model health, evaluation scores or fallback demonstrations. Simulation and replay must be labeled. +- Never clear existing accounting or audit data to make a demonstration work. Use an isolated demo profile and files. +- Preserve NativeAOT-safe serialization and existing project dependency direction. + +## 3. Product decisions for this implementation + +### Classification and egress + +Current `RegexDataClassifier` never emits Public. Fix this deliberately; absence of a regex match does not establish that content is public. + +Use an application-bound, server-configured workload/data profile with an explicit baseline classification. Requests may select only profiles granted to their application. Content detection may escalate classification but may never lower the trusted baseline. Arbitrary request headers, prompt instructions or a client-side Public dropdown cannot bypass this rule. Missing profile defaults to Internal for compatibility and receives the restrictive default policy below. + +Default demonstration policy: + +- Public: approved economical cloud model, with an explicitly configured approved fallback. +- Internal: approved local model. +- PII and PHI: approved local model; never a cloud fallback in the demo policy. +- No eligible destination: refuse and explain why. + +A deliberately Public demo profile uses synthetic public content. The regex classifier remains a limited demonstration detector; describe its coverage honestly. Do not claim it prevents all sensitive-data leakage. Keep the detector behind its existing interface. + +Preserve explicit local-only mode, where cloud configuration cannot execute. Display that mode prominently. Add a clear hybrid mode for local and approved cloud routes. Migrate legacy cloud mode explicitly: show its existing effective rules in the migration preview rather than silently changing production routing. Fresh demo configuration uses the defaults above. Do not require OpenAI credentials for an Anthropic-only setup. + +### Scope of policies + +Each policy has a stable ID, name, classification/profile applicability, enabled state, ordered eligible targets, routing strategy, and explanation. Application/profile grants further restrict eligibility. Use clear precedence and reject ambiguous overlaps; do not silently choose an arbitrary matching rule. + +In v2, support fixed-primary routing plus ordered fallback. Preserve the existing length-threshold strategy as an explicitly named 'Length-based heuristic', with configurable threshold and targets; do not call it quality-aware routing. No automatic switch to a supposedly 'best' model based on invented quality rankings. + +A paused policy denies its matching traffic. A paused route removes that target from eligibility; the next explicitly approved target may be used. A global provider-call pause retains its existing defined semantics, including cache behavior, and the UI must explain them. Do not turn a pause into a governance bypass. + +## 4. Backend design and contracts + +Write ADRs before implementing these changes: runtime configuration lifecycle; authorized console inference; routing/fallback and request trace; budget reservations/accounting periods. Use the next available ADR numbers. Document updates to earlier decisions explicitly. + +### 4.1 Versioned runtime configuration + +Implement a single-appliance configuration repository with immutable version snapshots and atomic persistence. Avoid introducing an external database. Persist only non-secret configuration and secret references. The ADR must define crash recovery, write ordering, concurrency, bootstrap precedence and how the activation event is durably auditable. + +Core entities: + +- Connection: ID, display name, provider kind, endpoint, enabled state, secret reference, permitted models, transport settings and probe status. +- Model: stable composite identity using connection ID plus exact model ID; display name, context/output constraints, pricing reference. Bare model names are not globally unique. +- Application/test identity: stable ID, team, enabled state, granted workload profiles and whether console testing is allowed. Never expose its API credential. +- Workload profile: ID, name, trusted baseline classification and application grants. +- Policy and route: applicability, active/paused state, ordered destinations, strategy and bounded retry settings. +- Budget: scope, currency USD, cap, period, warning thresholds and enforcement mode. +- Operational settings: cache TTL, permitted preview retention, trace retention, presentation preferences where appropriate. +- Pricing: connection/model identity, input/output rates, effective version/date and source/basis. Unknown price must remain unknown. + +Proposed API surface (finalize in `docs/ui-api-contract.md`; reuse existing equivalents rather than duplicate them): + +- `GET /admin/config`: redacted active configuration, version and ETag. +- `POST /admin/config/validate`: candidate plus base version; returns field errors, warnings and impact summary, without mutation. +- `PUT /admin/config` with `If-Match`: atomically apply the validated candidate; return new version. Stale edit returns 409/412; validation failure 422. Require version preconditions. +- `GET /admin/config/versions`: bounded history and change summaries. +- `POST /admin/config/rollback`: target historical version plus expected active version; validate and activate as a NEW version. +- Existing catalog/probe/status endpoints extended compatibly for multiple connections. + +Impact preview must identify affected classifications/applications, unavailable destinations, pricing gaps and requests that would now be refused. Applying a configuration must not reset spend or audit history. Existing in-flight calls finish using their captured snapshot; global emergency pause remains separately defined. Dispose retired provider clients only after their in-flight use ends. + +Probe configured/allow-listed endpoints only, with bounded timeout/body size and no redirects. A policy edit must not silently expand the probe/egress allow-list. Revalidate at apply and execution; never forward Covenant credentials to providers. Endpoint validation must cover scheme, destination and redirect behavior. + +### 4.2 Console inference without a second pasted key + +Add an authenticated console-inference endpoint, for example `POST /admin/playground/requests`, accepting application ID, allowed workload profile and the canonical inference input. The backend resolves the authorized test application and invokes the same governed pipeline as normal inference. Do not call providers directly from the UI or create an ungoverned shortcut. + +A shared admin credential can currently represent only a shared console operator; record that honestly. Do not fabricate individual operator attribution. Record operator/session reference, application, team and entry point independently. Disabled/non-test applications and ungranted profiles must be refused. Preserve normal `/v1` application-key authentication unchanged. + +Return the existing request ID/correlation semantics and support streaming/cancellation. A browser reload must not replay inference. Authorization failures and validation failures need clear UI outcomes; distinguish rejection before the pipeline from governed refusal. + +### 4.3 Actual request trace + +Introduce canonical stage/attempt events with request ID, configuration version, monotonic sequence, stage ID, attempt ID when relevant, state, server timestamp, duration and bounded reason code. States: pending, running, passed, refused, failed, cancelled, skipped. Do not put prompt/response content or credentials in trace events. + +Expose an authenticated per-request event stream and bounded snapshot/replay lookup. Specify how very early events are retained so subscribing after submission does not miss them. Handle reconnects, deduplication, retention expiry and out-of-order delivery. Preserve existing OpenAI/Anthropic response compatibility; internal trace belongs in admin APIs. + +Persist a compact final trace/attempt summary with audit evidence. Detailed transient event retention must be bounded. Audit persistence may lag response completion: show 'Evidence pending', retry for a bounded interval, then 'Evidence unavailable' if necessary. Never display verified evidence before it exists. + +### 4.4 Routing and fallback + +Select only policy-approved, enabled, application-authorized destinations within the classification boundary. Explain primary selection and each attempted fallback. Availability is separate from policy eligibility. + +Allow bounded fallback for explicitly configured transient errors such as connection failure, timeout, 429 or selected 5xx responses. Do not retry on policy denial, client cancellation, global pause or arbitrary provider 4xx errors. Do not fail over after response content has already been emitted to the client. Record partial output and terminal failure accurately. + +Recheck relevant budget/pause conditions before each attempt. Account for potentially chargeable failed attempts. Cap total attempts and total deadline. Never interpret an ordered allow-list alone as authorization for unbounded retries. + +### 4.5 Budgets and cost + +Support global, team and application scopes with atomic reservation across all applicable caps. Define period boundaries in UTC and persist the period identity independently of audit segments. Audit rotation must not reopen a budget. Preserve historical spend across configuration updates and restarts. + +Estimate a conservative reservation using configured prices and enforced input/output bounds. Settle against reported usage, or retain an explicit conservative estimate when usage is unavailable. Release unused reservation exactly once on completion/cancellation. Handle provider failures, fallback attempts, process crashes and concurrent requests without free capacity or double charging. If a provider cannot support a reliable bound, label enforcement as estimated rather than promising an exact invoice cap. + +Unpriced paid routes must not silently consume $0 under a hard monetary budget: reject eligibility until priced or use a clearly documented explicit conservative rate. Local zero marginal provider charge remains distinct from infrastructure cost. + +Changing a cap below current spend does not erase spend; block new paid work. Raising a cap is audited. Use configurable warnings, default 80% and 95%. Show actual monetary precision appropriate to tiny charges rather than rounding all requests to $0.00. + +Savings: label 'Estimated provider charge avoided', define the counterfactual approved baseline and calculation, and distinguish cache reuse from route selection. Hide the metric when the baseline is missing or incomparable. It is not total business savings and not evidence of equal answer quality. + +### 4.6 Exact caching + +Retain exact caching and explain it. Scope entries to effective authorization, application/team isolation as appropriate, classification, relevant configuration version, connection/model identity, request parameters and content. Configuration changes must not expose results authorized only under prior settings. Never cache denials, failures or partial streams. A cache hit still requires current authentication/policy checks and appropriate audit attribution. Document its interaction with global pause and budget enforcement. + +## 5. UI specification + +Use the existing Blazor components and CSS; improve them rather than building an unrelated second console. Existing mockups are visual references, not authority over these operating requirements. + +### Shell and shared patterns + +Sidebar: Overview, Playground, Requests, Models & connections, Policies, Budgets, Audit & evidence, Settings. Each has a consistent small icon and text label; active page is obvious. Use locally bundled/licensed icons or original SVGs, and update provenance for reused assets. No external icon/font CDN. + +Header: environment, prominent Local-only/Hybrid mode, compact health state, global pause/resume with icon and explicit label, theme sun/moon with accessible action label. Replace the 0/1-second counter with 'Live'; show age only when stale and expose exact timestamp in details. Do not announce every timer tick via aria-live. + +Use one accent plus consistent semantic colors: success, warning, failure, informational/local/cloud distinctions. Always pair meaning with text/icon. Consistent field widths, aligned labels/actions, readable typography and compact spacing. Avoid giant empty cards and repeated instruction paragraphs. Move API paths, ADR IDs, raw config keys and diagnostic prose into expandable details. + +Editable pages use clear View/Edit state, Save/Cancel, inline validation, unsaved-change warning, visible applied version and stale-edit conflict handling. No success toast before the backend confirms activation. Loading/error/empty/stale/disabled states must all be implemented. + +### Overview + +Compact health/readiness summary, useful spend/requests metrics, recent outcomes and modest activity chart. Missing setup should link to the exact action needed. Do not equate 'no recent errors' with 'demo ready'. + +Provide a compact preset/prompt composer with application/profile selection and an explicit Run action. The same component/state should be reused with Playground. Alternatively a 'New request' shortcut opens a focused composer; do not label a navigation-only link 'Run'. One click runs a selected ready preset; merely opening a page never submits a request. + +### Playground + +Primary two-pane workspace: prompt on the left, streamed response on the right. Always-visible Run/Cancel action area. Above prompt: 'Run as' application and allowed workload profile. Show the resulting classification separately; do not confuse trusted profile with detected classification. + +Advanced disclosure: model override, workflow/use case, output cap and streaming controls. Overrides remain policy constrained. No permanent application-key field in the normal console workflow. + +Below/alongside the response: compact outcome, actual destination, duration, token usage and cost basis. A horizontal/compact trace animates real stage events. Clicking a stage opens its reason and timing. Skipped stages are visibly skipped. Put full request facts and evidence in a drawer; do not repeat all information in three panels. + +Safely render Markdown without executable HTML. Copy response and inspect raw output as secondary actions. Cancel preserves the partial response and truthful terminal status. Session history selection never resubmits a request. + +Presentation mode shows only prompt, response, route/trace and key cost/outcome facts. It must be usable at 1280x720, not a normal page with overflow hidden. Escape exits; focus returns sensibly. Respect reduced-motion preferences. + +### Models & connections + +List existing connections first. Each shows provider icon/name, local/cloud boundary, enabled state, endpoint summary, configured models and health. Actions: Add, Edit, Test, Disable/Enable. Editing prefills actual values. Discovery never silently approves every discovered model. + +Ollama setup: endpoint → bounded discovery/test → select exact model tags → review affected routes → save/apply. No seven-step wizard that ends by telling users to edit a file. Show an actionable error if host access is denied or Ollama is unreachable. Never assume Open WebUI itself is the inference server. + +Cloud setup: provider, endpoint where supported, configured secret reference, model IDs and prices. Explain missing server-side secret configuration with concise instructions; never present an unusable Save as success. + +Distinguish last connection probe from last successful inference. One clear summary, expandable supporting timestamps; no contradictory 'ready' and 'never succeeded' without explanation. + +### Policies + +Use a colored route view plus a compact editable list, not repeated paragraphs and tables of the same facts. Show classification/profile → primary destination → approved fallback(s), state and strategy. Label cloud/local explicitly. + +Actions: edit targets, reorder fallback, pause/resume route, pause/resume policy, preview impact, save. Explain the difference between paused policy and paused route in context. A policy simulator returns a clearly labeled dry-run decision without calling a provider or recording fake spend. It must use the real policy engine. + +Replace 'Public requests may use local:qwen…' with definite effective state, e.g. 'Public → Qwen · Local-only mode' or 'Public → configured cloud model · fallback: …'. Refusal conditions belong in the detail panel. + +### Budgets + +Show period, spend, reserved amount, remaining amount, cap and warning state by scope. Edit caps/thresholds/period settings with impact preview. Drill into contributing requests. Show provider cost versus optional local infrastructure estimate separately. + +Do not make historical charts from fabricated seed values. Empty local-only spend gets an explanatory state and a connection/configuration link, not an enormous flat chart. Budget period rollover and audit archive are different operations. + +### Requests and Audit & evidence + +Requests: useful outcome/model/team/time filters, clickable rows, compact readable costs, request details drawer with keyboard focus management. Clearly indicate current-segment/snapshot scope. Add bounded cursor pagination and archived-segment selection/search so old evidence is reachable; do not imply loaded-snapshot filtering searches all history. + +Audit & evidence: lead with request decisions and evidence completeness. Explain who, which rule/version, selected/attempted/served destination, cost and why. Show 'Audit integrity verified' independently of answer quality. Put chain hashes and anchors behind details. Export a selected request/report with version, attempts, costs and integrity status; default export excludes prompt/response content. Do not accept arbitrary filesystem paths in archive APIs. + +### Settings + +Group editable operational settings, console preferences, diagnostics and maintenance. Theme/presentation preferences are browser-local; provider/policy/budget configuration belongs to the server. Explain restart-only settings explicitly. Save only changes that are actually supported. + +Separate archive maintenance from accounting changes. Destructive or accounting-affecting maintenance requires a precise confirmation with current environment and impact; normal harmless preference edits do not need confirmation dialogs. + +## 6. Layout and accessibility acceptance + +Test both light/dark themes at 1280x720 and 1920x1080, 100% zoom. Test a narrower responsive layout as well. Core actions and outcome must remain visible without scrolling nested panels. One main page scroll is acceptable; long answer/detail content may have an intentional scroll area. Do not hide inaccessible content to pass a screenshot check. + +No horizontal page scrolling, clipped controls or overlapping fields. Keyboard-accessible navigation, forms, menus and drawers; visible focus, Escape dismissal, focus restoration. Icons have accessible names; color is not the sole signal. Dynamic announcements report meaningful state changes only. Long model IDs/errors wrap without breaking layout. Sanitize server/provider errors before rendering. + +## 7. Implementation tasks and dependencies + +T01 — Architecture and contracts +Read current source, write ADRs and migration plan, update API contract and stale instructions. Record field schemas, atomicity, auth, classification semantics, failure behavior and budget periods. Deliver reviewable design before dependent code; proceed within this specification without repeatedly asking routine design questions. + +T02 — Configuration repository and migration (depends T01) +Implement immutable snapshots, validation, version conflicts, activation/rollback, redacted APIs and recovery. Preserve legacy startup configuration via explicit import/migration. Add tests for invalid edits, stale edits, interrupted persistence and request snapshot isolation. + +T03 — Connections and classification/policies (depends T02) +Multiple approved connections/models, independent provider enablement, trusted profiles, restrictive demo defaults, clear mode migration and editable policies. Include simulator and route pause behavior. Tests must prove Public is reachable legitimately and clients cannot downgrade sensitivity. + +T04 — Budget periods and reservations (depends T02) +Implement scope enforcement, persistence/recovery, pricing identity, settlement and audited cap changes. Include deterministic concurrency, failure/cancellation, restart and archive independence tests. + +T05 — Console request execution and trace (depends T01/T03) +Authorized test-application endpoint, shared governed pipeline, event stream/snapshot, final evidence and disconnect/reconnect behavior. Application credentials never return to the browser. + +T06 — Fallback/cache/cost explanations (depends T03/T04/T05) +Bounded approved fallback, attempt-level evidence and charges, cache isolation/invalidation, explicit selection reasons and defensible savings display. Test streaming failure and no cloud fallback for sensitive data. + +T07 — UI shell and request workspace (contract-first; complete after T05) +Implement navigation/icons/theme/live status, dashboard composer, focused Playground, real trace, drawers and presentation mode. Remove nested scrolling and repetitive diagnostic prose. All actions use real APIs. + +T08 — Editable admin pages and evidence (depends relevant backend tasks) +Connections, Policies, Budgets, Settings editors; validation/conflicts/apply feedback; request archive navigation and evidence export. Complete all loading/error/empty states. No disabled placeholder feature disguised as completion. + +T09 — Demo scenarios, documentation and packaging +Update the local demo launcher and runbook without logging secrets unnecessarily. Add isolated Local-only and Hybrid demo profiles. Do not modify the user's active 5201 process/configuration. Make server-side credential setup clear. Verify embedded console packaging and deep links. Include screenshots from the implemented app, not mockups. + +T10 — Acceptance and CI +Fix the duplicate CI gate: docs no-op and real build currently share a check name, and mixed code/docs changes can trigger both. Provide a single unambiguous required result that runs real tests whenever relevant code changes. Perform the acceptance matrix below and report evidence. + +Do not declare T07 complete while actions depend on mocks. If UI/backend work is split, mark integration as pending until it actually works. + +## 8. Demonstration and verification matrix + +Use synthetic bounded tasks such as extracting an explicitly supplied ticket priority into a fixed JSON schema. Do not ask the model to invent medical notes. Each scenario has known expected governance behavior and an independently checkable answer condition. + +A. Public/cloud: authorized Public profile; eligible economical cloud model; actual usage/cost attributed to correct team/application. +B. Sensitive/local: synthetic PII/PHI marker escalates Public baseline and reaches approved Qwen locally. Attempted explicit cloud override is refused. +C. Missing local: sensitive request with no eligible local destination is refused; no cloud call occurs. +D. Approved fallback: isolated stub provider fails before output; next approved route runs; both attempts and charges/estimates appear. Test 429, timeout, 5xx and non-retryable failures. +E. Streaming failure: provider fails after first content chunk; no second provider silently continues the answer; partial output/failure preserved. +F. Budget: deterministic requests reserve/settle across scopes; cap blocks correctly; changing cap does not lose spend. Concurrent requests cannot each claim the same remaining allowance. +G. Cache: repeat an exact eligible request; no provider call; current policy enforced; zero new provider charge and explicit cache provenance. Policy/model changes do not reuse incompatible results. +H. Policy editing: pause primary route and observe approved fallback; pause all eligible routes/policy and observe refusal. Resume restores eligibility with a new version. +I. Global pause/cancellation: correct existing pause semantics, cancelled request not mislabeled provider failure, exactly-once settlement and final evidence. +J. Config recovery: stale browser edit rejected; invalid configuration leaves active version unchanged; restart restores active configuration and accounting; rollback creates new version. +K. Evidence: old and new audit formats verify; archive search and export work; UI distinguishes pending, unavailable and verified evidence. +L. Browser usability: new operator connects once, selects an authorized app and runs without another token; edits a connection/policy/budget without a terminal; operates at both target sizes/themes with keyboard. + +Unit/integration tests use mock adapters, never paid providers. Real Ollama/cloud smoke tests are a separate opt-in rehearsal using owner-supplied credentials, synthetic prompts and an explicit small spending cap. If unavailable, mark these BLOCKED/NOT RUN; do not fabricate results or claim full demo readiness. + +Run the current equivalent of: + + dotnet build Covenant.sln -c Release --disable-build-servers + dotnet test tests/Covenant.Tests -c Release --disable-build-servers --collect:"XPlat Code Coverage" --settings tests/coverlet.runsettings + dotnet test tests/Covenant.Tests -c Release -p:SkipConsolePublish=true -o + dotnet publish src/Covenant.Host -c Release -r osx-arm64 --self-contained -p:PublishSingleFile=true -o + +Verify /ui redirects once to /ui/, /ui/ serves the embedded app, nested route reloads work, static assets load, and publish output contains the current UI. Use an isolated port. Linux/NativeAOT checks run on a supported runner and are reported separately. A successful ordinary publish is not proof of NativeAOT compatibility. + +If dotnet cannot execute in your environment, report that immediately and continue implementable work. Do not call an unbuilt branch complete. Provide exact commands and expected observations for the verifier, with a clear 'not executed' status. + +## 9. Required handoff + +Deliver: + +1. Branch/commit list and changed files grouped by task. +2. Updated ADRs, API contract, migration notes and demo runbook. +3. Task status table: implemented / executed verification / remaining gap. Separate claims from observations. +4. Test and publish logs, browser acceptance results and actual screenshots at required sizes/themes. +5. Short demo walkthrough for A/B/C/D/F/G/H, including expected trace and cost/evidence behavior. +6. Known limitations, explicitly including detector coverage, price/usage uncertainty and answer-quality scope. + +No generic 'all done' statement based on unit tests alone. The release gate is a working operator journey: edit → apply → request → visible decision → cost → evidence, including refusal and failure paths. diff --git a/docs/UI-implementation-tasks.txt b/docs/UI-implementation-tasks.txt index b44746b..bd84591 100644 --- a/docs/UI-implementation-tasks.txt +++ b/docs/UI-implementation-tasks.txt @@ -1,3 +1,5 @@ +NOTE (2026-10-16): Superseded where they conflict by docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md (editable configuration, console inference without pasted keys, real traces). Kept as history. + COVENANT UI + BACKEND IMPLEMENTATION TASKS Implementation brief for Claude — 16 October 2026 diff --git a/docs/UI-redesign-brief.txt b/docs/UI-redesign-brief.txt index e773c1f..b2219dd 100644 --- a/docs/UI-redesign-brief.txt +++ b/docs/UI-redesign-brief.txt @@ -1,3 +1,5 @@ +NOTE (2026-10-16): Superseded where they conflict by docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md (editable configuration, console inference without pasted keys, real traces). Kept as history. + Covenant UI redesign brief for Claude Purpose diff --git a/docs/adr/ADR-0001-core-engine-and-provider-layer.md b/docs/adr/ADR-0001-core-engine-and-provider-layer.md index a8b5efe..376fc6f 100644 --- a/docs/adr/ADR-0001-core-engine-and-provider-layer.md +++ b/docs/adr/ADR-0001-core-engine-and-provider-layer.md @@ -38,3 +38,18 @@ Patterns we **study as influences** (logged in `docs/PROVENANCE.md`; not code we ## Follow-ups - **Spike:** NativeAOT vs self-contained single-file publish for the required connectors (feeds `deploy/`, may warrant its own ADR). - **ADR-0002 candidate:** single-tenant vs multi-tenant control plane (already flagged in the PRD). + +## Status update 2026-10-17 — NativeAOT spike result +- **Result:** self-contained single-file publish (`PublishSingleFile=true`, `--self-contained`) is the **supported** + appliance artifact; it was verified on osx-arm64 (process start, `/ui` and framework assets served — see + `docs/verification-2026-10-16/v2/CODEX-REVIEW.txt`). This is the fallback this ADR anticipated and still satisfies + "one deployable". +- **NativeAOT is blocked by dependencies, not by our code:** an AOT publish emits **IL2104** ("assembly produced trim + warnings") and **IL3053** ("assembly produced AOT analysis warnings") for **Anthropic 12.8.0** (the Anthropic + connector) and **Neo4j.Driver 6.2.1** (the optional evidence-graph projector, ADR-0006). The warnings are **not + suppressed** and the artifact is **not** claimed AOT-verified. Our own projects keep `IsAotCompatible=true` and + source-generated JSON only, so the path stays honest. +- **What would unblock it:** (1) AOT/trim-clean releases of both libraries (re-run the publish; zero IL2104/IL3053), or + (2) an AOT-clean in-house `IChatClient` for Anthropic's Messages API (small, already-owned wire surface) and shipping + the Neo4j projector as a separate optional component outside the appliance binary; then (3) a CI gate on + `PublishAot=true` with warnings-as-errors. Until then `deploy/` targets the single-file artifact. diff --git a/docs/adr/ADR-0011-runtime-configuration-lifecycle.md b/docs/adr/ADR-0011-runtime-configuration-lifecycle.md new file mode 100644 index 0000000..c3f5c59 --- /dev/null +++ b/docs/adr/ADR-0011-runtime-configuration-lifecycle.md @@ -0,0 +1,94 @@ +# ADR-0011 — Runtime configuration: versioned snapshots, validated apply, rollback + +**Status:** Accepted +**Date:** 2026-10-16 +**Supersedes in part:** ADR-0010 ("runtime apply is deferred"; probe allow-list source), ADR-0004 trigger +("a policy or budget editor") is now fired. Spec: `docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md` §4.1. + +## Context +Routing, connections, budgets and operational settings were fixed at startup from configuration keys and +changed only by editing secrets and restarting. The console must edit them safely: validated, versioned, +auditable, reversible, never half-applied, and without letting a request see a mixture of old and new rules. + +## Decision +**Repository.** One directory, `Config:Path` (default `.config/`, so every audit log — and every +isolated test or demo — gets its own repository), holds immutable snapshots `versions/v000001.json …`, +`active.json` = `{ "version": N, "sha256": "" }`, and `activations.jsonl`, an append-only +**activation journal** (one line per activation: version, base, rolled-back-from, utc, summary). The journal, +not the presence of a version file, defines history: version files that were never activated (orphans) are +excluded from history, `GET /admin/config/versions/{n}` and rollback, and their numbers are never reused. +Only non-secret configuration and **secret references** are persisted. No database. + +**Write ordering (apply/rollback):** take the single writer lock → validate the candidate against the +current active version (`If-Match: "vN"` must equal active; else 412) → **compile the runtime snapshot +(provider clients included); any compile failure aborts here with nothing durable written** → choose +M = max(existing version file numbers, journal max) + 1 → write `versions/vM.json.tmp`, flush, rename to +`versions/vM.json` (create-new) → write `active.json.tmp`, flush, rename over `active.json` → append the +journal line (flush) → swap the in-memory snapshot reference → enqueue the `config.activated` audit event +(v3 `EventType`: version, base, operator reference, bounded redacted change summary — never secret values) +→ release the lock. Rollback validates the historical snapshot as a NEW candidate and +activates it as version M+1 (`RolledBackFrom = K`); history is never rewritten. + +**Crash recovery at boot:** read `active.json`; verify the referenced file's SHA-256. Missing/corrupt +pointer or hash mismatch ⇒ **refuse to start** with a diagnostic (fail-closed; the operator restores the +pointer, never a silent "latest"). Version files not in the journal are reported as orphans. If the active +version is missing from the journal (crash between pointer rename and journal append) it is appended with +`recovered: true`. If the active version has no `config.activated` audit event, boot appends one marked +`recovered: true`. + +**Live audit-write failure.** The activation event goes through the same audit sink as requests, whose write +failure is already fail-closed (`Environment.FailFast`: an appliance that cannot write evidence stops). So a +failing evidence write after the pointer swap halts the process; at the next boot the active version is +missing its activation event and boot appends it with `recovered: true` before serving. The configuration +change therefore never runs unevidenced: either the event is written, or nothing is served until it is. + +**Validation is total.** Every enum value must be a defined member (numeric out-of-range values are errors), +required objects/lists and their elements must be non-null, ids are unique and non-empty, and every error is a +422 with a field path — never an exception or 500. A validated candidate is deep-copied into immutable +collections when compiled; later mutation of the caller's objects cannot change an active snapshot. +**Boundary is not self-declared:** a connection may be `Local` only if its endpoint authority is on the +startup local-endpoint allow-list (`Providers:LocalEndpoints`, plus the legacy `Local:Endpoint`); cloud SDK +kinds (`OpenAi`, `Anthropic`) are always `Cloud`. A cloud host cannot be relabelled Local to reach PII/PHI. + +**Bootstrap precedence:** (1) existing repository wins; (2) empty repository + `Config:Seed` ∈ +{`demo-local-only`, `demo-hybrid`} ⇒ that seed becomes v1; (3) otherwise the legacy startup keys +(`Providers:Mode`, `OpenAI:*`, `Anthropic:*`, `Local:*`, `Budget:*`, `Pricing:*`, `Cache:*`, +`Routing:*`, `Auth:Keys` identities) are **imported** into v1 with `origin = legacy-import`, reproducing the +existing effective routing exactly (legacy cloud mode stays legacy cloud mode; the migration preview shows +its effective rules). A legacy local route without `Local:*` imports as an **explicitly disabled +placeholder connection** `local` ("not configured — import placeholder"), so the migration preview shows why +PII/PHI are refused; disabled connections are never eligible, in any mode. After v1 exists, those legacy keys +are ignored for routing and reported as such. +Startup-only (never console-editable): `Admin:Token`, all secret values, `Auth:Keys` key values, +`Audit:*`, `Config:Path`, and **`Providers:ProbeAllowList` — the egress allow-list**: a configuration edit +can never widen where Covenant may connect. Connection endpoints must be on the allow-list (or be the +legacy-imported endpoints, which are added to it at import) at validate, apply and execution time. + +**Secrets.** A connection names a `secretRef`: an `IConfiguration` key, restricted to `Secrets:` and +the legacy keys `OpenAI:ApiKey`, `Anthropic:ApiKey`, `Local:ApiKey`. The API reports `available: true|false`, +never the value. Saving a cloud connection whose secret is unavailable is a validation **error** (an +unusable save is not shown as success). + +**Provider clients** are built with automatic redirects disabled, SDK-internal retries disabled (attempts are +Covenant's, counted and accounted per ADR-0013/0014) and the connection's timeout as the effective network +timeout. A target whose client cannot be built makes the candidate invalid (no silently skipped target). + +**Snapshots and isolation.** A validated version compiles into an immutable `RuntimeSnapshot` (policies, +provider clients, price book, budgets, cache settings, profiles, applications). Each request acquires the +current snapshot once at entry (ref-counted) and uses only it; the snapshot id is the request's +`ConfigVersion` in trace and audit. A retired snapshot disposes its provider clients when its last request +releases it. Spend, reservations and audit history are never reset by apply/rollback. + +**Concurrency:** one writer (lock); readers lock-free via a volatile reference. Version numbers are +monotonic; ETag = `"v"`. + +## Consequences +- (+) Edits are atomic, conflict-safe (412 on stale `If-Match`), reversible, and evidenced in the chain. +- (+) A request can never mix rules from two versions. +- (−) Boot fails if the active pointer is damaged — deliberate; recovery is a manual pointer fix. +- (−) Secret values still come only from startup configuration/vault; the console references them. + +## Alternatives considered +- SQLite/Postgres — rejected: new dependency/service for a single-appliance, low-write workload. +- Mutable single file — rejected: no history, torn writes, no rollback. +- Auto-select the latest version on a corrupt pointer — rejected: could activate an unvalidated write. diff --git a/docs/adr/ADR-0012-authorized-console-inference-and-workload-profiles.md b/docs/adr/ADR-0012-authorized-console-inference-and-workload-profiles.md new file mode 100644 index 0000000..3ce8066 --- /dev/null +++ b/docs/adr/ADR-0012-authorized-console-inference-and-workload-profiles.md @@ -0,0 +1,46 @@ +# ADR-0012 — Console inference as an authorized test application; trusted workload profiles + +**Status:** Accepted +**Date:** 2026-10-16 +**Spec:** `docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md` §3, §4.2. + +## Context +The console asked operators to paste an application key, conflating roles, and `RegexDataClassifier` +returned Internal on no match, so Public was unreachable. A client cannot be allowed to declare its own data +public. + +## Decision +**Applications** are configuration entities: `id`, `team`, `enabled`, `consoleTesting`, `grantedProfiles`, +`defaultProfile`. `/v1` keys (`Auth:Keys:N:Key`, startup secrets) bind to an application via +`Auth:Keys:N:Application` (default: the key's `Principal`, preserving existing keys). Legacy import creates +one application per existing key **once**. After that, a key whose application is missing from the active +configuration (removed, renamed, never added) is **refused** (403, stopped at `auth`, "application not +configured") — fail-closed; there is no implicit legacy fallback. + +**Workload profiles** carry a **trusted baseline classification** and are granted to applications. A +request selects a profile (`X-Covenant-Profile` on `/v1`, `profileId` on the console endpoint); an ungranted +profile is a governed refusal (403, stopped at `auth`). No profile ⇒ the application's `defaultProfile`; +none ⇒ `legacy-internal` (baseline Internal). **Final classification = max(baseline, detected)**: the +detector can only escalate. `RegexDataClassifier` keeps its interface and its narrow coverage (US SSN +pattern; MRN/diagnosis/patient-id keywords) — documented as a demonstration detector, not DLP. Its +no-match result means "no escalation", never "public". No header, prompt or UI control can lower the +baseline. Evidence records `ProfileId`, `BaselineClassification`, detected escalation and final class. + +**Console inference.** `POST /admin/playground/requests` (admin token) with `applicationId`, `profileId`, +canonical input, optional model override / max tokens / stream / workflow / use case / `clientRequestId`. +The Host resolves the application server-side and runs **the same `InferencePipeline`** with a +pre-resolved identity (a server-side field the `/v1` ingress can never set); the auth stage enforces `enabled`, `consoleTesting` and the profile grant (governed +refusals, audited). Body validation failures are 400 **before** the pipeline (no audit record; the response +says so). Evidence records `EntryPoint = console`, `OperatorRef = shared-admin-token` (honest: one shared +admin credential cannot attribute an individual), `ApplicationId`, `Team`. Application credentials are never +sent to or returned from the browser. `clientRequestId` makes a resubmission within 10 minutes return 409 +with the original request id — a reload never replays inference. `/v1` authentication is unchanged. + +## Consequences +- (+) One token for the operator; applications stay the unit of identity, team and budget. +- (+) Public becomes reachable only through a trusted, granted profile. +- (−) Console actions are attributable to "the shared admin credential", not a person, until real IAM. + +## Alternatives considered +- Console holds application keys — rejected (credential sprawl into the browser). +- Treat "no regex match" as Public — rejected (absence of detection is not evidence of public data). diff --git a/docs/adr/ADR-0013-routing-fallback-request-trace-and-exact-cache.md b/docs/adr/ADR-0013-routing-fallback-request-trace-and-exact-cache.md new file mode 100644 index 0000000..120d14b --- /dev/null +++ b/docs/adr/ADR-0013-routing-fallback-request-trace-and-exact-cache.md @@ -0,0 +1,59 @@ +# ADR-0013 — Policies with approved fallback, real request trace, exact cache isolation + +**Status:** Accepted +**Date:** 2026-10-16 +**Supersedes in part:** ADR-0001 single-route provider call; ADR-0010 fixed local-only routing. +**Spec:** `docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md` §3, §4.3, §4.4, §4.6. + +## Decision — policies +A **policy**: `id`, `name`, `enabled`, `paused`, applicability (`classifications[]`, optional +`profiles[]`), ordered `targets[]` (each `{connectionId, modelId, paused}`), `strategy` +(`fixed` = primary then ordered fallback; `length-heuristic` = targets[0] when the chars/4 estimate ≤ +`thresholdTokens`, else the last target, remaining targets as ordered fallback — named honestly, not +"quality-aware"), `retry` (`maxAttempts` ≤ 3, `deadlineMs`, `on` ⊆ {`connect`,`timeout`,`429`,`5xx`}). **Precedence:** a policy naming the request's profile beats one +that names only classifications; two enabled policies at the same specificity covering the same +(classification, profile) pair are a **validation error** (no arbitrary winner). No match ⇒ refusal. +Paused policy ⇒ refuses its matching traffic. Paused target ⇒ removed from eligibility; the next approved +target may serve. Eligibility also requires: connection enabled; model permitted on the connection; +mode allows the boundary (local-only ⇒ cloud targets never eligible); **PII/PHI ⇒ cloud targets are never +eligible** (no escape hatch in v2; a policy listing a cloud target for PII/PHI is a validation error); priced +for paid targets under a hard budget. A **paused policy refuses** its traffic — it never falls through to a +less specific policy. A model override must resolve to exactly one eligible target: `connection/model`, or a +bare model id only when exactly one eligible target has it (ambiguous bare ids are refused); it pins that +target (no fallback). +**Modes:** `local-only` and `hybrid` (and `legacy-cloud` for imported pre-v2 configurations). + +## Decision — fallback +The provider stage iterates eligible candidates. Before **each** attempt: re-check global pause and reserve +budget for that target (ADR-0014). Retry the next candidate only for the policy's configured transient +failures (connection failure, provider-side timeout, 429, 500/502/503/504), never for policy denial, +client cancellation, pause or other 4xx, and **never after any content was emitted** (partial output and +terminal failure are recorded). Total attempts ≤ `maxAttempts`, total time ≤ `deadlineMs`. Each attempt +is recorded (`attemptId`, target, outcome, error class, duration, usage/charge basis) and possibly-billed +failed attempts are charged an estimate (ADR-0009). Failure classification of SDK exceptions lives in the +Host (it knows the SDK types) behind `IProviderFailureClassifier`. + +## Decision — trace +Canonical events `{requestId, configVersion, seq, stage, attemptId?, state, tsUtc, durationMs?, reasonCode?}`, +`state` ∈ pending|running|passed|refused|failed|cancelled|skipped, emitted by the pipeline itself +(Stopwatch-measured, server time). Stages not entered after a refusal/cache hit are emitted as `skipped` +with `reasonCode` (`not_reached`, `cache_hit`). No content, credentials or free-text provider errors (only +bounded codes). `TraceHub` (in-memory) creates the per-request buffer **before** the pipeline starts, so +early events are retained: ≤ 64 events per request, ≤ 2 000 requests, 10-minute TTL. APIs: +`GET /admin/requests/{id}/trace` (snapshot) and `/trace/stream` (SSE replay-then-live; `Last-Event-ID` +resume; clients de-duplicate by `seq`; `410` after expiry). The audit record (v3) persists `ConfigVersion`, +`Attempts[]` and a compact `Trace[]` (stage:state:ms) — the durable summary. + +## Decision — exact cache +Key = SHA-256 over: application id, team, profile, **final** classification, config version, connection +id + model id, max output tokens, stream-independent request parameters, and the message content. +Any configuration activation changes the key space (no reuse across versions). Denials, failures and +partial streams are never stored. A hit runs after auth/shape/classify/policy (current checks), skips +rate-limit/pause/budget/provider (unchanged semantics: **a global provider-call pause does not stop cache +hits** — the UI says so), costs $0 provider charge with `CostBasis = no_call`, and is audited with +`CacheHit = true` and the original served model. + +## Consequences +- (+) Fallback is bounded, explainable, evidenced, and cannot route sensitive data to cloud by accident. +- (+) The console shows real stage execution, not a configured-order animation. +- (−) Every config activation cold-starts the cache. diff --git a/docs/adr/ADR-0014-budget-periods-and-reservations.md b/docs/adr/ADR-0014-budget-periods-and-reservations.md new file mode 100644 index 0000000..e5bee09 --- /dev/null +++ b/docs/adr/ADR-0014-budget-periods-and-reservations.md @@ -0,0 +1,52 @@ +# ADR-0014 — Budget scopes, UTC periods and atomic reservations + +**Status:** Accepted +**Date:** 2026-10-16 +**Supersedes in part:** ADR-0009 §5 (post-call threshold check only), the in-memory ledger rebuilt from +the audit segment. **Spec:** `docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md` §4.5. + +## Decision +**Budgets** (configuration): `id`, `scope` (`global` | `team:` | `application:`), `capUsd`, +`period` (`none` | `daily` | `monthly`, UTC boundaries; identity e.g. `2026-10`, `2026-10-16`, `all`), +`warnAt` (default [0.80, 0.95]), `enforcement` (`hard` | `warn-only`). + +**Ledger** (`Budget:LedgerPath`, default `.ledger.jsonl`): an append-only journal, independent +of audit segments, of `reserve`/`settle`/`release` operations keyed by `(requestId, attemptId)` and recording +the **scopes charged** (`global`, `team:`, `application:`) with a UTC timestamp — **not** a budget id or +a period id — replayed at boot. A budget's spend is computed at read time as the sum of settled amounts for its +scope inside its current period window. Renaming a budget id, changing its period or editing its cap therefore +never resets accrued usage; changing a budget's scope shows that scope's own accrued history. An attempt is +charged to the scopes that applied **when it was reserved** (in-flight attempts across an activation settle +against their original reservation). **Audit archive never reopens a budget.** +Config apply never resets it. Boot recovery: a reservation with no settle/release is settled at its +reserved amount (`settle-recovered`) — conservative, never free capacity. + +**Reservation.** Before each provider attempt, compute an upper-bound estimate: input tokens ≤ the prompt's +**UTF-8 byte count** + 16 per message (byte-level tokenizers never produce more tokens than bytes; chars/4 is +only an average and is never used for enforcement) at the target's input price + the **enforced** output bound (request `max_tokens`, capped by the application +default `maxOutputTokens`, default 1024 — the bound is sent to the provider so it is real) at the output +price. If reported usage exceeds the reservation (a provider ignoring the bound, tokenizer overhead), the full +reported cost is settled anyway — spend is never truncated to the reservation — and the overrun is flagged in +evidence; enforcement is therefore described as an **estimated** bound. Under one ledger lock, check every +applicable hard budget (`spent + reserved + estimate ≤ cap` for +global, team, application in the current period) and reserve in all or none. Refusal ⇒ governed denial at +stage `budget`. **Settle** exactly once per attempt with the actual cost (reported usage) or the +conservative estimate when usage is unavailable/failed (`estimated_*` basis), then **release** the +remainder exactly once (idempotent by key). Cancellation and fallback settle each attempt independently. +**Unpriced paid targets are ineligible** under any hard budget (validation error at apply). Local +targets with an explicit zero price reserve $0 ("zero marginal provider charge", infrastructure excluded). + +Warnings at configured fractions are reported (status, evidence) and do not block; `warn-only` budgets +never block. Lowering a cap below spend blocks new paid work and keeps spend; raising/lowering is a +configuration activation (audited with before/after). Legacy migration: if no ledger exists, the current +audit segment's recorded spend is imported once as a `legacy-import` settle into the current period of the +global and team budgets. Precision: amounts are stored as decimal and displayed with significant digits +for sub-cent charges. + +**Savings** ("Estimated provider charge avoided") are computed only when `Savings:Baseline` names a priced +connection/model; cache reuse and route selection are reported separately; otherwise hidden. + +## Consequences +- (+) Concurrent requests cannot jointly overrun a hard cap beyond estimation error; the cap is an + **estimated** enforcement bound, not an invoice ceiling, whenever usage is unreported. +- (−) A journal file is one more durable artifact to back up alongside the audit log. diff --git a/docs/console-v2-acceptance.md b/docs/console-v2-acceptance.md new file mode 100644 index 0000000..b812dd4 --- /dev/null +++ b/docs/console-v2-acceptance.md @@ -0,0 +1,89 @@ +# Console v2 — handoff and acceptance record (spec §9) + +Branch `feat/console-v2` from `main` 9371dbe. Not merged. **The author's environment cannot run `dotnet`.** Every +"Observed" entry below was executed by the independent verifier (Codex) on macOS arm64 against the commit named, +with logs/screenshots in the git-excluded `docs/verification-2026-10-16/v2/` folder. "Claimed" = implemented, not +yet independently observed. Final source checkpoint: `9e71d66`; subsequent verifier changes affect only the +launcher and documentation and have their own executed checks below. No source patches were required for the +780-test run. + +## 1. Commits by task + +| Task | Commits | +|---|---| +| T01 architecture | f1ebd12 (ADR-0011..0014, v2 contract, migration notes, config model), 79ec4b0 (review corrections) | +| T10 CI | 2f2a28a (single `test` check; docs-only vs code decided in one job) | +| T02/T03 config, profiles, policies | a929d84, 8bb8923 (review round 1 incl. torn journal) | +| T04/T05/T06 budgets, console inference + trace, fallback/cache | a16bed8, 1ad07c4 (review round 2) | +| T07/T08 UI | 3d579fe, 96deed5, 959ce13 (UI round 2), 2a7d5e5 (UI round 3) | +| T09 demo | 45760e9 (launcher, explicit hybrid seed prices, runbook) | + +Docs: ADR-0011..0014 (+ ADR-0001 status update), `docs/ui-api-contract.md` (v2), `docs/migration-v2.md`, +`docs/demo-runbook.md`, `docs/console-v2-progress.md` (per-round defect → fix → test), this file. + +## 2. Executed verification (observed by the verifier) + +| Commit | Observation | +|---|---| +| 2f2a28a | Release build 0 warnings/errors; 310 tests pass (baseline) | +| 8bb8923 | Release build + 491 tests pass incl. torn-journal regression; osx-arm64 self-contained single-file publish; `/ui`→302 `/ui/`; `/ui/`, nested route, Blazor JS → 200 | +| 1ad07c4 (+2 test-only name fixes, applied in 959ce13) | Release build + 723 tests pass; HTTP stream suite: partial-then-error ⇒ Deny/no fallback; length finish relayed + Truncated; post-content stall ⇒ timeout, partial kept, no fallback; empty completion ⇒ 200/Allow. Cache collision probes (delimiter, output-bound) ⇒ calls=2, no false hit. 503/429/timeout fallback with two charged attempts. Ledger migration crash window ⇒ refuses start; clean import preserves spend. Stable pagination; early trace (provider Running before first token) | +| 959ce13 | Release build + **761 tests pass**, no verifier patches; osx-arm64 single-file publish pass; coverage measured at an earlier checkpoint: line 95.57 % / branch 83.24 % | +| browser (959ce13 era) | connect once; budget edit → preview → apply (v10) with spend preserved; policy split/save (v31); pause primary + approved slow fixture (v32); cache TTL edit (v33) + repeated request = cache hit, no provider call, $0, skipped stages; live provider Running before first token; Ollama discovery → select `qwen2.5-coder:7b` → save → real synthetic sensitive request: Pii (US SSN pattern), served by local Qwen, zero configured provider charge, evidence found; presentation fits 1280×720; Escape restores focus; header local health correct. Screenshots: `qwen-real-{1280,1920}-{dark,light}.png`, `dashboard-1280-dark.png`, `presentation-1280-dark.png`, `round2-*.png`, `budget-applied-v10.png` | +| 9e71d66 + verifier launcher corrections | Full solution Release build: **0 warnings, 0 errors**. Embedded-console test run: **780 passed, 0 failed/skipped**; coverage **95.59% line / 83.65% branch**. Fresh-output `SkipConsolePublish=true`: **780 passed**. Self-contained single-file publishes: **osx-arm64 and linux-x64 passed** (Linux cross-publish only, not executed). Published Mac routes: `/ui/`, nested route and Blazor JS all 200. Launcher Local-only starts, real Qwen synthetic request returns 200, restart retains audit/config; no credentials in normal stdout, private files 0600. Spaced JSON catalog, exact model matching, occupied-port and missing hybrid key/price guards pass. | +| UI round 3 (2a7d5e5, included in 9e71d66) | Created Public profile, granted existing application, previewed and saved v34; real Public and PII Qwen requests succeed. Final classification/escalation visible; previous-result marker and cache original-model provenance verified. Presentation screenshots at 1280×720 and 1920×1080 in light/dark; all trace stages and timings visible. At 900×700 no horizontal page overflow. Evidence: `round3-presentation-*.png`, `final-cache-presentation.png`. | +| security probes | invalid enums / null settings ⇒ validation errors (no 500); removed application's key ⇒ 403; app key cannot read admin APIs; admin token cannot authorize inference; browser disconnect ⇒ Cancelled, one estimated charged attempt, no fallback, reservation released | +| NativeAOT | **Fails**: IL2104/IL3053 from Anthropic 12.8.0 and Neo4j.Driver 6.2.1 — documented, not suppressed (ADR-0001 status update, runbook §1a). Supported artifact: self-contained single file | + +## 3. Status by task (claims vs observations) + +| Task | Implemented (claimed) | Executed verification | Remaining gap | +|---|---|---|---| +| T01 | ADRs 0011–0014, contract, migration | reviewed by verifier | — | +| T02 | repository, journal, validation, impact, rollback, legacy import | tests + HTTP | — | +| T03 | profiles, baseline escalation, policy engine v2, simulator, modes | tests + browser split/save | — | +| T04 | ledger, reservations, periods, settle/release, migration | tests + HTTP (concurrency 1×200/5×403, archive preserves spend) | — | +| T05 | console endpoint, submissions, trace hub/stream | tests + browser live trace | — | +| T06 | fallback, attempt evidence, cache identity, savings, archive/export | tests + HTTP fixture | real cloud fallback not exercised (see §5) | +| T07 | shell, composer, Playground, presentation | browser (both themes, 1280/1920) | round 3 independently verified (see above) | +| T08 | editors, requests archive, evidence export | browser (budget/policy/settings/connections) | profile/grant editor independently verified | +| T09 | launcher, seeds, runbook | seed tests pass; actual Local-only launcher/restart + Qwen request; credential/model/port guards verified | real cloud smoke remains opt-in and not run | +| T10 | single CI check; this record | final full build/test/coverage, clean skip-console tests, Mac publish/run, Linux cross-publish | GitHub CI and Linux runtime execution not run (branch not pushed) | + +## 4. Verifier commands for HEAD + +``` +dotnet build Covenant.sln -c Release --disable-build-servers +dotnet test tests/Covenant.Tests -c Release --disable-build-servers --collect:"XPlat Code Coverage" --settings tests/coverlet.runsettings +dotnet test tests/Covenant.Tests -c Release -p:SkipConsolePublish=true --artifacts-path +dotnet publish src/Covenant.Host -c Release -r osx-arm64 --self-contained -p:PublishSingleFile=true -o +scripts/run-local-demo.sh # isolated port 5210, own state; then runbook §2–§3 in the browser +``` +Route checks with GET (not HEAD): `curl -sS -D - -o /dev/null http://localhost:5210/ui` → 302 `/ui/`; `/ui/` and +`/ui/requests/x` → 200 text/html. + +## 5. Known limitations (stated, not hidden) + +- **Detector coverage:** `RegexDataClassifier` recognises a US-SSN pattern and MRN/diagnosis/patient-id keywords only. + It is a demonstration detector, not DLP; Public is reachable only through a trusted, granted Public profile, and + detection can only escalate. It cannot prove content is non-sensitive. +- **Price and usage uncertainty:** costs are configured-price × provider-reported usage. Unreported usage and + failed attempts are charged a conservative estimate (UTF-8 byte bound); a hard budget is an *estimated* + enforcement bound, not an invoice ceiling. Local "$0" is zero configured provider charge, infrastructure excluded. + Savings are shown only with a configured priced baseline and are not evidence of equal answer quality. +- **Answer quality:** Covenant governs routing, cost and evidence; it does not evaluate answers. "Audit integrity + verified" means the hash chain is internally consistent, nothing about correctness. +- **Identity:** console actions are attributed to the shared admin credential (`OperatorRef = shared-admin-token`); + no individual operator attribution until real IAM. +- **Real cloud smoke:** BLOCKED / NOT RUN — needs owner-supplied credentials, synthetic prompts and a small cap. +- **NativeAOT:** blocked by dependencies (above). **Linux-x64:** cross-publish passed on macOS; the artifact has not been executed on Linux. + +## 6. Final verifier handoff + +Claude completed through `9e71d66`. While the Mac was locked and Claude was idle, Codex corrected the launcher +and runbook directly, then exercised those changes. Launch with `scripts/run-local-demo.sh` (port 5210); +`OPEN_BROWSER=0` keeps it headless. The existing instance on port 5201 was not changed. + +Local implementation and verification are complete within the stated limits. This is a reviewable feature branch, +not a production certification: no merge/push, real paid cloud call, Linux runtime run or NativeAOT success is claimed. +The scope does not include semantic caching, prompt rewriting, answer-quality evaluation or individual-admin IAM. diff --git a/docs/console-v2-progress.md b/docs/console-v2-progress.md new file mode 100644 index 0000000..0193d14 --- /dev/null +++ b/docs/console-v2-progress.md @@ -0,0 +1,991 @@ +# Console v2 — progress record + +Spec: `docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md`. Contract: `docs/ui-api-contract.md` (v2 section). One section per task. + +--- + +## T07 UI — shell and request workspace + +**Status: NOT EXECUTED.** Written without a .NET SDK (the authoring sandbox has none and cannot download one), so +nothing below has been compiled, unit-tested or opened in a browser. Backend endpoints were being implemented +concurrently by another agent; every UI call to a v2 endpoint is **integration pending until the backend lands** +and the verifier steps below pass. Do not cite T07 as complete before then (spec §7). + +### Files + +``` +src/Covenant.Ui/Models/ConfigContracts.cs new v2 DTOs (config envelope/config mirror of Core/Configuration.cs, + validate/put/versions/rollback, applications, playground request, + trace event/snapshot, budget state, simulator). All "…Dto" names + (no clash with Covenant.Core types); enums kept as strings. +src/Covenant.Ui/Models/Contracts.cs audit v3 fields on AuditEntryView (+ AuditAttemptView; Trace[] kept as + JsonElement so object or "stage:state:ms" shapes both read); + ChatRequestDto removed; UiJsonContext lists every new DTO +src/Covenant.Ui/Logic/SafeMarkdown.cs new encode-first Markdown renderer (the console's only MarkupString source) +src/Covenant.Ui/Logic/TraceModel.cs new trace reduction (dedupe by seq, seq ordering, attempts, skipped, + not-reported), TraceAccumulator (Last-Event-ID), SseParser, + audit Trace[] fallback +src/Covenant.Ui/Logic/ShellStatus.cs new mode badge mapping, Live / "Stale · n s" label, single announcement +src/Covenant.Ui/Logic/RequestSnapshot.cs PlaygroundForm gains ApplicationId/ProfileId (streaming default on); + snapshot gains ApplicationId/ProfileId/ClientRequestId (GUID per Run); + new ComposerRules (selectable apps, granted profiles, run validation, + eligible model overrides from the active config) +src/Covenant.Ui/Logic/ScenarioPresets.cs presets A–D rewritten to spec §8 (ticket-priority JSON task; B/C carry + the synthetic SSN 078-05-1120; D fresh nonce); populate-only, picks a + granted Public-baseline profile; IsReady for "Run preset" +src/Covenant.Ui/Logic/OutcomeModel.cs fallback-aware texts, partial-cancel title, 404 (endpoint missing), 409 + DuplicateSubmission; "there is no fallback model" wording removed +src/Covenant.Ui/Logic/ModelFacts.cs Destination (serving attempt + Local/Cloud from config), AttemptFacts +src/Covenant.Ui/Logic/CostText.cs BasisCost for per-attempt cost +src/Covenant.Ui/Logic/LaunchLink.cs admin token only; appkey= ignored +src/Covenant.Ui/Services/ConsoleInferenceApi.cs new POST /admin/playground/requests on the admin HttpClient (+ InferenceResult) +src/Covenant.Ui/Services/InferenceApi.cs DELETED (no remaining references) +src/Covenant.Ui/Services/TraceClient.cs new trace SSE follower (Last-Event-ID resume, bounded reconnect, 404/410 → + snapshot → expired) +src/Covenant.Ui/Services/WorkspaceConfig.cs new GET /admin/applications, /admin/config, /admin/budgets (shared, per connection) +src/Covenant.Ui/Services/RunText.cs new run display text (duration/tokens/cost/evidence/announcement) +src/Covenant.Ui/Services/PlaygroundState.cs rewritten: shared composer state, runs + per-run trace + evidence, history (≤30) +src/Covenant.Ui/Services/AdminApi.cs + applications/config/budgets/trace snapshot/trace stream, ReportUnauthorized +src/Covenant.Ui/Services/AppState.cs application key removed +src/Covenant.Ui/Services/Interop.cs, wwwroot/js/interop.js comment only (copy = operator-chosen text) +src/Covenant.Ui/Program.cs admin HttpClient timeout 5 min; ConsoleInferenceApi/TraceClient/WorkspaceConfig +src/Covenant.Ui/Components/Icon.razor new original inline SVG icons (no icon set) +src/Covenant.Ui/Components/RequestComposer.razor new shared composer (Playground + Overview) +src/Covenant.Ui/Components/TraceBar.razor new horizontal trace + stage popover +src/Covenant.Ui/Components/RunSummary.razor new compact outcome line +src/Covenant.Ui/Components/RunDetails.razor new drawer content: request, outcome, baseline vs final class, attempts, cost, evidence +src/Covenant.Ui/Components/BoundaryTag.razor new Local / Cloud / "Boundary not reported" tag (text + icon + colour) +src/Covenant.Ui/Layout/SideNav.razor icons, active bar, "Audit & evidence", theme moved to header +src/Covenant.Ui/Layout/StatusHeader.razor env, mode badge, freshness, health chip, pause + scope popover, theme, live region +src/Covenant.Ui/Layout/MainLayout.razor pause banner wording +src/Covenant.Ui/Pages/Playground.razor rewritten (two panes, action bar, response/raw/copy, outcome line, trace, + drawer, history, presentation mode) +src/Covenant.Ui/Pages/Overview.razor rewritten (setup checks, composer, metrics, recent outcomes, small chart) +src/Covenant.Ui/Pages/Evidence.razor title "Audit & evidence", + @page "/audit" +src/Covenant.Ui/Pages/Connect.razor no application key; copy updated +src/Covenant.Ui/Pages/Settings.razor "Application key: never held" +src/Covenant.Ui/Pages/Connections.razor governed test runs as a chosen test application via console inference + (minimal change; the editor is T08) +src/Covenant.Ui/wwwroot/css/tokens.css + --local/--cloud (+bg), --shadow (both themes) +src/Covenant.Ui/wwwroot/css/app.css nav/header, composer, trace, response, outcome line, Playground, Overview, + presentation grid, responsive rules; old Playground CSS removed +tests/Covenant.Tests/Covenant.Tests.csproj links Models/*.cs (was Contracts.cs only) +tests/Covenant.Tests/ConsoleLogicTests.cs preset/snapshot tests rewritten; + ComposerRulesTests, SafeMarkdownTests, + TraceModelTests, ShellStatusTests, AttemptAndDestinationTests; + launch-link test now asserts appkey is ignored +``` + +### What is wired to which endpoint + +| UI | Endpoint | Status | +|---|---|---| +| Run (Playground, Overview composer, Connections governed test) | `POST /admin/playground/requests` (admin token, buffered or SSE, `X-Covenant-Request-Id`, `client_request_id`) | integration pending until backend lands | +| "Run as" select, profile select, Overview "Test applications" check | `GET /admin/applications` | integration pending | +| Profile names/baselines, eligible model overrides, Local/Cloud boundary of destinations | `GET /admin/config` (redacted) | integration pending; without it the UI shows profile ids, falls back to the legacy catalog for overrides and says "Boundary not reported" | +| Overview budget check | `GET /admin/budgets` (falls back to `status.budget`) | integration pending | +| TraceBar (live) | `GET /admin/requests/{id}/trace/stream` (SSE, `Last-Event-ID`, `event: end`) | integration pending | +| TraceBar (fallback) | `GET /admin/requests/{id}/trace`, then audit v3 `Trace[]` | integration pending | +| Evidence Pending → Verified (record found) / Unavailable | `GET /admin/requests/{id}` (existing EvidenceTracker, bounded) | existing endpoint; v3 fields integration pending | +| Header mode badge | `GET /admin/status` `mode` (accepts local-only/LocalOnly, hybrid, legacy-cloud/LegacyCloud, cloud) | existing field; v2 values pending | +| Pause / resume | `POST /admin/kill-switch` (unchanged) | existing | + +A 404 from any v2 endpoint is shown as "not available on this Host yet (endpoint missing — integration pending)", +never as an empty success. + +### Decisions + +- **No application key anywhere in the console.** `AppState.ApplicationKey`, the Playground key field and the + `#appkey=` launch parameter are gone; `InferenceApi` is deleted. The Connections governed test was switched to + console inference ("Run as" select) so the page keeps working without a key. +- **One composer, one state.** `RequestComposer` + `PlaygroundState` back both Playground and the Overview compact + composer. Presets only populate; the action bar label becomes "Run preset X" only while the form still holds a + READY preset. Opening a page, `/playground/{A-D}`, applying a preset or picking a history entry never submits. +- **Model override value** is `connectionId/modelId` (the backend's `PolicyV2` override matcher accepts + `{AdapterKey}/{ModelId}` or a bare model id). Free text is labelled "test input; does not grant permission". +- **Trace** starts as soon as the request id is known (streaming: at the response headers; buffered: when the + response arrives, i.e. replay). Unreported stages stay "Pending" while open and "Not reported" once complete — + never inferred as passed/skipped. Provider attempts are grouped by `attempt_id`. +- **Markdown**: the whole input is HTML-encoded first; only the renderer's own tags are emitted; links must be + absolute http(s) and get `target="_blank" rel="noopener noreferrer"`. Server/provider error text is never + rendered as markup. +- **Live/stale**: "Live" (green dot) while fresh; "Stale · 12 s" only when stale; exact time in the tooltip. The header + re-renders each second only while stale. One visually hidden polite region announces connected/paused/stale; the + Playground has one for run state changes (running → outcome), not for streamed text. +- **Presentation mode** (`?present=1`): prompt + Run/Cancel, response, outcome facts, trace. A fixed layer with + `overflow:auto` (one scroll at most) and a grid that collapses to one column under 1100 px; the response scrolls + intentionally. Esc exits and focus returns to the "Presentation mode" button. +- **Icons**: original inline SVG paths written for this repo (`Components/Icon.razor`), no third-party asset — no + PROVENANCE entry needed beyond noting they are original (docs/PROVENANCE.md not edited by this task). + +### Risks / known gaps + +1. Not compiled. Highest-risk spots: Razor templates in `@code` (`ResponseBody`), pattern variables inside + `@switch` cases (`RunDetails`), `@bind:after` on inputs, `Nav.GetUriWithQueryParameter("present", (string?)null)`, + source-generated names `UiJsonContext.Default.ListApplicationSummaryDto` / `ListBudgetStateDto`. +2. Wire-name assumptions: the Host's `ConfigJsonContext` uses `SnakeCaseLower`, which may name + `PriceConfig.InputPer1M` `input_per1_m` rather than `input_per_1m` (not used by T07; T08 must check). + Enums are expected as C# names (`LocalOnly`, `Local`, `Public`) — the UI also accepts kebab/snake spellings. +3. Audit v3 `Trace[]` shape is read leniently (objects or `stage:state:ms`); `Attempts[].Outcome` success words + assumed: served/success/succeeded/ok/passed/completed. +4. Trace SSE in the browser relies on fetch streaming (`SetBrowserResponseStreamingEnabled`) like the status + feed; if the browser buffers, events arrive at the end (snapshot fallback still applies). +5. Buffered runs have no request id until the response arrives, so their trace is a replay, not live. +6. 401 from console inference is treated as an admin-token rejection (disconnect), per contract. + +### Verifier steps (not executed) + +``` +dotnet build Covenant.sln -c Release --disable-build-servers +dotnet test tests/Covenant.Tests -c Release --disable-build-servers --filter "FullyQualifiedName~Covenant.Tests.SafeMarkdownTests|FullyQualifiedName~Covenant.Tests.TraceModelTests|FullyQualifiedName~Covenant.Tests.ComposerRulesTests|FullyQualifiedName~Covenant.Tests.ShellStatusTests|FullyQualifiedName~Covenant.Tests.SnapshotAndPresetTests|FullyQualifiedName~Covenant.Tests.AttemptAndDestinationTests" +dotnet test tests/Covenant.Tests -c Release --disable-build-servers # full suite +``` + +Browser (isolated port, demo profile; both themes; 1280×720 and 1920×1080; then a ~900 px width): +- [ ] Sidebar: 8 items with icons; active bar on the current page; `/audit` and `/evidence` both highlight "Audit & evidence". +- [ ] Header: environment, mode badge (Local-only / Hybrid / Legacy cloud; "Mode not reported" against an old Host), + health chip, "Live" with exact time in the tooltip; stop the Host → "Stale · n s" counts, screen reader hears + "Status is stale" once; pause/resume labels and the ⓘ popover (Esc closes); theme button label flips. +- [ ] Playground: no key field anywhere; "Run as" shows disabled/non-test apps greyed with reason; profile list = + granted profiles only; Run disabled with the reason until valid; nothing runs on page open, on `/playground/B`, + on preset click, on reload or on history selection (check the Host log / Requests list). +- [ ] A/B/C/D per spec §8 from the Playground; each Run has a distinct `client_request_id` (DevTools → Network). +- [ ] Streaming: text appears in the right pane, TraceBar chips change as events arrive, provider ×2 on fallback, + skipped stages dashed; click a chip → popover with state/reason/duration/attempts; Esc closes it. +- [ ] Kill the trace connection mid-run (DevTools offline toggle) → "reconnecting", no duplicated chips afterwards. +- [ ] Cancel mid-stream → partial text kept, "Cancelled — partial response", explanation mentions possible charge. +- [ ] Details drawer: baseline vs final classification, attempts with Local/Cloud tags and costs, evidence + Pending → "Verified — record found" (or Unavailable + Retry); Tab trapped, Esc closes, focus returns. +- [ ] Markdown: a reply containing `")] + [InlineData("hello ")] + [InlineData("x")] + [InlineData("")] + [InlineData("****")] + [InlineData("`item")] + public void Raw_html_is_always_encoded(string input) + { + var html = SafeMarkdown.ToHtml(input); + Assert.DoesNotContain("docs", html, StringComparison.Ordinal); + + var tricky = SafeMarkdown.ToHtml("[x](https://e.com/\"onmouseover=\"alert(1))"); + Assert.DoesNotContain("\"onmouseover", tricky, StringComparison.Ordinal); + Assert.DoesNotContain(" onmouseover=\"", tricky, StringComparison.Ordinal); + AssertOnlyAllowedTags(tricky); + } + + [Fact] + public void Supported_formatting_renders() + { + Assert.Equal("

Title

", SafeMarkdown.ToHtml("# Title")); + Assert.Equal("

Sub

", SafeMarkdown.ToHtml("## Sub")); + Assert.Equal("
Small
", SafeMarkdown.ToHtml("### Small")); + Assert.Equal("

#### four

", SafeMarkdown.ToHtml("#### four")); + Assert.Equal("

bold and it and b2 and i2

", + SafeMarkdown.ToHtml("**bold** and *it* and __b2__ and _i2_")); + Assert.Equal("

use a*b*c here

", SafeMarkdown.ToHtml("use `a*b*c` here")); + Assert.Equal("
  • one
  • two
", SafeMarkdown.ToHtml("- one\n* two")); + Assert.Equal("
  1. first
  2. second
", SafeMarkdown.ToHtml("1. first\n2) second")); + Assert.Equal("

line one
line two

para two

", SafeMarkdown.ToHtml("line one\r\nline two\n\npara two")); + Assert.Equal("
x < 1\n**not bold**
", SafeMarkdown.ToHtml("```csharp\nx < 1\n**not bold**\n```")); + Assert.Equal("

snake_case_name stays

", SafeMarkdown.ToHtml("snake_case_name stays")); + Assert.Equal("{"priority":"low"}", StripP(SafeMarkdown.ToHtml("{\"priority\":\"low\"}"))); + Assert.Equal("", SafeMarkdown.ToHtml(null)); + Assert.Equal("", SafeMarkdown.ToHtml("")); + } + + [Fact] + public void Unclosed_fence_while_streaming_renders_as_code() + => Assert.Equal("
partial <b>
", SafeMarkdown.ToHtml("```\npartial ")); + + private static string StripP(string html) => html.StartsWith("

", StringComparison.Ordinal) ? html[3..^4] : html; + + ///

Every tag in the output is one the renderer itself writes. + private static void AssertOnlyAllowedTags(string html) + { + var allowed = new HashSet(StringComparer.Ordinal) { "p", "br", "h3", "h4", "h5", "strong", "em", "code", "pre", "ul", "ol", "li", "a" }; + foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(html, "<\\/?([a-zA-Z0-9]+)")) + Assert.Contains(m.Groups[1].Value, allowed); + foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(html, "]*)>")) + Assert.Matches("^href=\"https?://[^\"<>]*\" target=\"_blank\" rel=\"noopener noreferrer\"$", m.Groups[1].Value); + } +} + +public sealed class TraceModelTests +{ + private static TraceEventDto E(long seq, string stage, string state, double? ms = null, string? attempt = null, string? reason = null, string? target = null) + => new() { Seq = seq, Stage = stage, State = state, DurationMs = ms, AttemptId = attempt, ReasonCode = reason, Target = target }; + + private static TraceStepView Step(TraceView v, string stage) => v.Steps.Single(s => s.Stage == stage); + + [Fact] + public void Steps_follow_the_canonical_order_and_unreported_stages_are_pending_until_complete() + { + var open = TraceModel.Reduce([E(1, "auth", "passed", 2)], complete: false); + Assert.Equal(TraceModel.Stages, open.Steps.Select(s => s.Stage)); + Assert.Equal(TraceStepState.Passed, Step(open, "auth").State); + Assert.Equal(2, Step(open, "auth").DurationMs); + Assert.Equal(TraceStepState.Pending, Step(open, "policy").State); + + var done = TraceModel.Reduce([E(1, "auth", "passed", 2)], complete: true); + Assert.Equal(TraceStepState.NotReported, Step(done, "policy").State); // never invented as passed/skipped + } + + [Fact] + public void Duplicates_are_dropped_by_seq_and_out_of_order_delivery_cannot_regress_a_state() + { + var events = new[] + { + E(3, "policy", "passed", 4, reason: "allowed"), + E(1, "auth", "running"), + E(2, "auth", "passed", 1.5), + E(2, "auth", "failed"), // duplicate seq (replay): ignored, first copy wins + E(3, "policy", "refused"), // duplicate seq + E(4, "policy", "running"), // stray later event wins only because its seq is higher + }; + var v = TraceModel.Reduce(events, complete: false); + Assert.Equal(TraceStepState.Passed, Step(v, "auth").State); + Assert.Equal(1.5, Step(v, "auth").DurationMs); + Assert.Equal(TraceStepState.Running, Step(v, "policy").State); + Assert.Equal("allowed", Step(v, "policy").ReasonCode); + Assert.Equal(4, v.LastSeq); + } + + [Fact] + public void Skipped_stages_are_reported_as_skipped_with_their_reason() + { + var v = TraceModel.Reduce( + [ + E(1, "cache", "passed", 1, reason: "cache_hit"), + E(2, "rate_limit", "skipped", reason: "cache_hit"), + E(3, "pause", "skipped", reason: "cache_hit"), + E(4, "provider", "skipped", reason: "cache_hit"), + ], complete: true); + Assert.Equal(TraceStepState.Skipped, Step(v, "rate_limit").State); + Assert.Equal(TraceStepState.Skipped, Step(v, "provider").State); + Assert.Empty(Step(v, "provider").Attempts); + Assert.Equal("cache_hit", Step(v, "provider").ReasonCode); + Assert.Null(Step(v, "rate_limit").DurationMs); + } + + [Fact] + public void Provider_events_are_grouped_into_attempts_in_order_of_first_appearance() + { + var v = TraceModel.Reduce( + [ + E(10, "provider", "running", attempt: "a1", target: "openai/gpt-x"), + E(12, "provider", "running", attempt: "a2", target: "ollama/qwen"), + E(11, "provider", "failed", 5000, attempt: "a1", reason: "timeout"), + E(13, "provider", "passed", 800, attempt: "a2"), + ], complete: true); + var p = Step(v, "provider"); + Assert.Equal(2, p.Attempts.Count); + Assert.Equal("a1", p.Attempts[0].AttemptId); + Assert.Equal(TraceStepState.Failed, p.Attempts[0].State); + Assert.Equal("openai/gpt-x", p.Attempts[0].Target); + Assert.Equal("timeout", p.Attempts[0].ReasonCode); + Assert.Equal(5000, p.Attempts[0].DurationMs); + Assert.Equal("a2", p.Attempts[1].AttemptId); + Assert.Equal(TraceStepState.Passed, p.Attempts[1].State); + Assert.Equal("ollama/qwen", p.Attempts[1].Target); + Assert.Equal(TraceStepState.Passed, p.State); // last attempt decides + Assert.Equal(5800, p.DurationMs); // sum of reported attempt durations + Assert.Equal(new[] { 1, 2 }, p.Attempts.Select(a => a.Number)); + } + + [Fact] + public void Provider_is_running_while_any_attempt_runs() + { + var v = TraceModel.Reduce([E(1, "provider", "running", attempt: "a1")], complete: false); + Assert.Equal(TraceStepState.Running, Step(v, "provider").State); + } + + [Fact] + public void Accumulator_dedupes_tracks_last_seq_and_merges_snapshots() + { + var acc = new TraceAccumulator(); + Assert.True(acc.Add(E(1, "auth", "passed"))); + Assert.False(acc.Add(E(1, "auth", "passed"))); + Assert.True(acc.Add(E(5, "policy", "passed"))); + Assert.Equal(5, acc.LastSeq); + + acc.ApplySnapshot(new TraceSnapshotDto { Complete = true, ConfigVersion = 7, Events = [E(1, "auth", "passed"), E(6, "attribution", "passed")] }); + Assert.Equal(3, acc.Count); + Assert.True(acc.Complete); + var view = acc.View(); + Assert.Equal(7, view.ConfigVersion); + Assert.Equal(TraceStepState.NotReported, Step(view, "budget").State); + } + + [Fact] + public void Unknown_states_and_stages_are_kept_honestly() + { + var v = TraceModel.Reduce([E(1, "auth", "weird"), E(2, "future_stage", "passed")], complete: true); + Assert.Equal(TraceStepState.NotReported, Step(v, "auth").State); + Assert.Equal("future_stage", v.Steps[^1].Stage); + } + + [Fact] + public void Audit_summary_fallback_reads_the_typed_compact_trace() + { + // Core AuditTraceStep shape only ({Stage, State, DurationMs, AttemptId?, ReasonCode?}); provider steps are matched + // to Attempts[] by AttemptId. + var summary = new List + { + new() { Stage = "auth", State = "passed", DurationMs = 1 }, + new() { Stage = "policy", State = "passed", DurationMs = 3 }, + new() { Stage = "provider", State = "failed", DurationMs = 900, AttemptId = "a1", ReasonCode = "timeout" }, + new() { Stage = "provider", State = "passed", DurationMs = 400, AttemptId = "a2" }, + new() { Stage = "", State = "passed" }, + }; + var attempts = new List + { + new() { AttemptId = "a1", ConnectionId = "openai", ModelId = "gpt-x", Outcome = "failed" }, + new() { AttemptId = "a2", ConnectionId = "ollama", ModelId = "qwen", Outcome = "served" }, + }; + var v = TraceModel.FromAuditSummary(summary, attempts, 3)!; + Assert.Equal("audit summary", v.Source); + Assert.True(v.Complete); + Assert.Equal(TraceStepState.Passed, Step(v, "auth").State); + Assert.Equal(3, Step(v, "policy").DurationMs); + var p = Step(v, "provider"); + Assert.Equal(2, p.Attempts.Count); + Assert.Equal("openai/gpt-x", p.Attempts[0].Target); + Assert.Equal(TraceStepState.Failed, p.Attempts[0].State); + Assert.Equal("timeout", p.Attempts[0].ReasonCode); + Assert.Equal("ollama/qwen", p.Attempts[1].Target); + Assert.Equal(TraceStepState.Passed, p.State); + Assert.Null(TraceModel.FromAuditSummary(null)); + Assert.Null(TraceModel.FromAuditSummary([])); + } + + [Fact] + public void Sse_parser_dispatches_on_blank_lines_and_joins_data() + { + var p = new SseParser(); + Assert.Null(p.Feed(": comment")); + Assert.Null(p.Feed("id: 7")); + Assert.Null(p.Feed("data: {\"a\":")); + Assert.Null(p.Feed("data: 1}")); + var ev = p.Feed(""); + Assert.NotNull(ev); + Assert.Equal("7", ev!.Id); + Assert.Equal("message", ev.Event); + Assert.Equal("{\"a\":\n1}", ev.Data); + + Assert.Null(p.Feed("event: end")); + var end = p.Feed(""); + Assert.Equal("end", end!.Event); + Assert.Null(p.Feed("")); // nothing pending + } +} + +public sealed class ShellStatusTests +{ + [Theory] + [InlineData("local-only", "Local-only", "local")] + [InlineData("hybrid", "Hybrid", "hybrid")] + [InlineData("legacy-cloud", "Legacy cloud", "legacy")] + // One explicit contract (docs/ui-api-contract.md "Wire spellings"): other spellings are not guessed. + [InlineData("LocalOnly", "Mode not reported", "unknown")] + [InlineData("Hybrid", "Mode not reported", "unknown")] + [InlineData("LegacyCloud", "Mode not reported", "unknown")] + [InlineData("cloud", "Mode not reported", "unknown")] + [InlineData(null, "Mode not reported", "unknown")] + [InlineData("", "Mode not reported", "unknown")] + [InlineData("quantum", "Mode not reported", "unknown")] + public void Mode_badge_mapping(string? mode, string label, string tone) + { + var b = ShellStatus.Mode(mode); + Assert.Equal(label, b.Label); + Assert.Equal(tone, b.Tone); + } + + private static readonly DateTimeOffset Now = new(2026, 10, 16, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public void Live_shows_no_counter_and_the_exact_time_goes_in_the_title() + { + var f = ShellStatus.Freshness(true, false, Now.AddSeconds(-1), Now, null); + Assert.Equal("Live", f.Label); + Assert.Equal("ok", f.Tone); + Assert.False(f.Stale); + Assert.Equal("Last status update 2026-10-16 11:59:59 UTC", f.Title); + Assert.DoesNotMatch("\\d+ s", f.Label); + } + + [Fact] + public void Stale_shows_age_and_the_feed_problem() + { + var f = ShellStatus.Freshness(true, true, Now.AddSeconds(-12), Now, "Connection lost — retrying"); + Assert.Equal("Stale · 12 s", f.Label); + Assert.Equal("warn", f.Tone); + Assert.Contains("Connection lost", f.Title, StringComparison.Ordinal); + Assert.Equal("Stale · 3 min", ShellStatus.Freshness(true, true, Now.AddSeconds(-200), Now, null).Label); + Assert.Equal("Stale · no update", ShellStatus.Freshness(true, true, null, Now, null).Label); + Assert.Equal("Disconnected", ShellStatus.Freshness(false, false, null, Now, null).Label); + } + + [Fact] + public void Announcement_depends_on_state_changes_only() + { + var a = ShellStatus.Announcement(true, false, false); + Assert.Equal("Console connected. New provider calls accepted.", a); + Assert.Equal("Console connected. New provider calls paused. Status is stale.", ShellStatus.Announcement(true, true, true)); + Assert.Equal("Console disconnected.", ShellStatus.Announcement(false, true, true)); + // Same state, any time → same text: nothing to re-announce while the clock ticks. + Assert.Equal(a, ShellStatus.Announcement(true, false, false)); + } +} + +public sealed class AttemptAndDestinationTests +{ + private static AuditEntryView Fallback() => Set(Rec.V2(selected: "openai/gpt-x", attempted: "ollama/qwen", served: "ollama/qwen"), + [ + new AuditAttemptView { AttemptId = "a1", ConnectionId = "openai", ModelId = "gpt-x", Outcome = "failed", ErrorClass = "timeout", DurationMs = 5000, CostUsd = 0.0001m, CostBasis = "estimated_failed_call" }, + new AuditAttemptView { AttemptId = "a2", ConnectionId = "ollama", ModelId = "qwen", Outcome = "served", DurationMs = 800, CostUsd = 0m, CostBasis = "zero_priced" }, + ]); + + private static AuditEntryView Set(AuditEntryView r, List attempts) { r.Attempts = attempts; return r; } + + private static readonly List Connections = + [ + new() { Id = "openai", Boundary = "Cloud", Enabled = true }, + new() { Id = "ollama", Boundary = "Local", Enabled = true }, + ]; + + [Fact] + public void Fallback_is_explained_attempt_by_attempt() + { + var r = Fallback(); + var v = OutcomeModel.FromRecord(r); + Assert.Equal(DisplayOutcome.Served, v.Outcome); + Assert.Equal("Served by approved fallback", v.Title); + Assert.Contains("Attempt 1 (openai/gpt-x) failed: timeout; attempt 2 (ollama/qwen) served.", v.Explanation, StringComparison.Ordinal); + + var lines = AttemptFacts.Lines(r, Connections); + Assert.Equal(2, lines.Count); + Assert.Equal("openai/gpt-x", lines[0].Target); + Assert.Equal("Cloud", lines[0].Boundary); + Assert.Equal("timeout", lines[0].ErrorClass); + Assert.Equal("≈ $0.0001 estimated", lines[0].Cost); + Assert.Equal("ollama/qwen", lines[1].Target); + Assert.Equal("Local", lines[1].Boundary); + } + + [Fact] + public void Destination_is_the_serving_attempt_with_its_boundary() + { + var d = ModelFacts.Destination(Fallback(), Connections); + Assert.Equal("ollama/qwen", d.Text); + Assert.Equal("Local", d.Boundary); + Assert.True(d.Served); + + var unknown = ModelFacts.Destination(Fallback(), null); + Assert.Null(unknown.Boundary); // never guessed from the name + + var refused = ModelFacts.Destination(Rec.PolicyDeny()); + Assert.Equal(ModelFacts.NoProviderCall, refused.Text); + Assert.False(refused.Served); + + var cache = ModelFacts.Destination(Rec.V2(cacheHit: true, attempted: null, served: "ollama/qwen"), Connections); + Assert.StartsWith("Cache — no provider call", cache.Text, StringComparison.Ordinal); + } + + [Fact] + public void Single_attempt_is_not_called_a_fallback() + { + var r = Set(Rec.V2(), [new AuditAttemptView { AttemptId = "a1", ConnectionId = "openai", ModelId = "gpt-x", Outcome = "served" }]); + Assert.Null(AttemptFacts.FallbackSentence(r)); + Assert.Equal("Served", OutcomeModel.FromRecord(r).Title); + } + + [Fact] + public void Cancel_with_partial_text_says_so_truthfully() + { + var v = OutcomeModel.Compute(new OutcomeInput(200, Cancelled: true, HasPartialText: true)); + Assert.Equal(DisplayOutcome.Cancelled, v.Outcome); + Assert.Equal("Cancelled — partial response", v.Title); + Assert.Contains("the provider may have charged for work done", v.Explanation, StringComparison.Ordinal); + Assert.Equal("Cancelled — no response received", OutcomeModel.Compute(new OutcomeInput(Cancelled: true)).Title); + } + + [Fact] + public void Duplicate_submission_is_not_a_success() + { + var v = OutcomeModel.Compute(new OutcomeInput(409, "duplicate_submission")); + Assert.Equal(DisplayOutcome.DuplicateSubmission, v.Outcome); + Assert.Equal("unknown", v.PillKind); } } @@ -583,60 +1179,1412 @@ public void Normalize_matches_the_catalog_shape(string raw, string expected) public void Authority_is_host_and_port() => Assert.Equal("ollama-host:11434", ConnectionLogic.Authority("http://ollama-host:11434/v1")); - private static CatalogResponse Catalog(string? endpoint, string? model, bool registered, bool configured = true) => new() + [Fact] + public void Governed_connection_test_prompt_is_fresh_every_run_so_it_cannot_hit_the_cache() + => Assert.NotEqual(ConnectionLogic.GovernedTestPrompt(), ConnectionLogic.GovernedTestPrompt()); + + [Fact] + public void Launch_link_reads_only_the_admin_token_from_the_fragment_and_ignores_appkey() + { + var c = LaunchLink.Parse("http://localhost:5201/ui/connect#token=abc%2B1&appkey=k-2"); + Assert.NotNull(c); + Assert.Equal("abc+1", c!.AdminToken); + + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#appkey=k-2")); // application keys are never accepted + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect?token=abc")); // query is sent to the server: never accepted + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect")); + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#")); + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#other=1")); + } + + [Fact] + public void Launch_link_token_rides_only_in_the_fragment() + { + Assert.Equal("t-1", LaunchLink.Parse("http://localhost:5201/ui/connect#token=t-1")!.AdminToken); + Assert.Equal("t-2", LaunchLink.Parse("http://localhost:5201/ui/connect#appkey=k&token=t-2")!.AdminToken); + Assert.Equal("t-3", LaunchLink.Parse("http://localhost:5201/ui/connect#token=%20t-3%20")!.AdminToken); + + // Query-string tokens are sent to the server (and its logs): never accepted, even beside a fragment. + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect?token=abc")); + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect?token=abc#appkey=k")); + Assert.Equal("frag", LaunchLink.Parse("http://localhost:5201/ui/connect?token=query#token=frag")!.AdminToken); + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#token=")); + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#token=" + new string('x', 513))); + Assert.Null(LaunchLink.Parse(null)); + } + + [Fact] + public void Launch_link_credentials_expose_no_application_key() + { + // Console v2 (ADR-0012): the console never holds an application key — the parsed credentials carry the + // admin token and nothing else, whatever the launcher put in the fragment. + var props = typeof(LaunchLink.Credentials).GetProperties().Select(p => p.Name).ToList(); + Assert.Equal(new[] { "AdminToken" }, props); + + var c = LaunchLink.Parse("http://localhost:5201/ui/connect#appkey=secret-app-key&token=adm"); + Assert.NotNull(c); + Assert.DoesNotContain("secret-app-key", c!.ToString(), StringComparison.Ordinal); + } +} + +// ---- T08: editable admin pages and evidence workflows ---- + +internal static class Cfg +{ + /// A small hybrid configuration: local Ollama + cloud OpenAI, Public → cloud with local fallback, + /// Internal → local, PII/PHI → local. + public static CovenantConfigDto Hybrid() => new() { - Mode = "cloud", - Local = new LocalRouteInfo { Configured = configured, Endpoint = endpoint, ModelId = model, Registered = registered }, + Version = 3, + Origin = "console", + CreatedUtc = new DateTimeOffset(2026, 10, 16, 9, 0, 0, TimeSpan.Zero), + Mode = "hybrid", + Connections = + [ + new ConnectionDto + { + Id = "ollama", DisplayName = "Ollama", Kind = "Ollama", Boundary = "Local", Endpoint = "http://ollama-host:11434/v1", Enabled = true, + Models = [new ModelDto { ModelId = "qwen2.5-coder:7b", Price = new PriceDto { InputPer1M = 0m, OutputPer1M = 0m, Basis = "zero-marginal-local" } }], + }, + new ConnectionDto + { + Id = "openai", DisplayName = "OpenAI", Kind = "OpenAi", Boundary = "Cloud", Enabled = true, SecretRef = "Secrets:openai", + Models = [new ModelDto { ModelId = "gpt-4o-mini", Price = new PriceDto { InputPer1M = 0.15m, OutputPer1M = 0.60m, Basis = "provider-list" } }], + }, + ], + Policies = + [ + new PolicyDto + { + Id = "public", Name = "Public", Enabled = true, Classifications = ["Public"], Strategy = "fixed", + Targets = [new PolicyTargetDto { ConnectionId = "openai", ModelId = "gpt-4o-mini" }, new PolicyTargetDto { ConnectionId = "ollama", ModelId = "qwen2.5-coder:7b" }], + }, + new PolicyDto + { + Id = "internal", Name = "Internal", Enabled = true, Classifications = ["Internal"], Strategy = "fixed", + Targets = [new PolicyTargetDto { ConnectionId = "ollama", ModelId = "qwen2.5-coder:7b" }], + }, + new PolicyDto + { + Id = "sensitive", Name = "PII/PHI", Enabled = true, Classifications = ["Pii", "Phi"], Strategy = "fixed", + Targets = [new PolicyTargetDto { ConnectionId = "ollama", ModelId = "qwen2.5-coder:7b" }], + }, + ], + Budgets = [new BudgetConfigDto { Id = "global", Scope = "global", CapUsd = 25m, Period = "monthly", WarnAt = [0.8m, 0.95m], Enforcement = "hard" }], + Settings = new OperationalSettingsDto { CacheTtlSeconds = 300, CacheMaxEntries = 1000, PromptPreviewChars = 0, TraceRetentionMinutes = 10 }, }; +} + +public sealed class MoneyTests +{ + [Theory] + [InlineData("0.000184", "$0.000184")] + [InlineData("0.0012", "$0.0012")] + [InlineData("0.003", "$0.003")] + [InlineData("0.00012345", "$0.000123")] + [InlineData("0.0123", "$0.0123")] + [InlineData("0.5", "$0.50")] + [InlineData("1.234", "$1.23")] + [InlineData("1234.5", "$1,234.50")] + [InlineData("0", "$0.00")] + [InlineData("-1.23", "-$1.23")] + [InlineData("-0.000184", "-$0.000184")] + [InlineData("0.0000001", "<$0.000001")] + public void Usd_uses_significant_digits_for_tiny_amounts(string value, string expected) + => Assert.Equal(expected, Money.Usd(decimal.Parse(value, System.Globalization.CultureInfo.InvariantCulture))); + + [Theory] + [InlineData("0.000184")] + [InlineData("0.0000049")] + [InlineData("0.004999")] + [InlineData("0.0000000001")] + public void A_non_zero_charge_is_never_rendered_as_zero(string value) + { + var text = Money.Usd(decimal.Parse(value, System.Globalization.CultureInfo.InvariantCulture)); + Assert.NotEqual("$0.00", text); + Assert.NotEqual("$0", text); + Assert.DoesNotContain("$0.00 ", text + " ", StringComparison.Ordinal); + } [Fact] - public void Applied_check_needs_same_endpoint_exact_tag_and_server_registration() + public void Null_is_not_reported_and_never_zero() { - const string draft = "http://ollama-host:11434/v1/"; - Assert.True(ConnectionLogic.CheckApplied(Catalog("http://ollama-host:11434/v1", "qwen3:8b", true), draft, "qwen3:8b").Pass); - Assert.False(ConnectionLogic.CheckApplied(Catalog("http://other:11434/v1", "qwen3:8b", true), draft, "qwen3:8b").Pass); - Assert.False(ConnectionLogic.CheckApplied(Catalog("http://ollama-host:11434/v1", "qwen3:4b", true), draft, "qwen3:8b").Pass); - Assert.False(ConnectionLogic.CheckApplied(Catalog("http://ollama-host:11434/v1", "qwen3:8b", false), draft, "qwen3:8b").Pass); - Assert.False(ConnectionLogic.CheckApplied(Catalog(null, null, false, configured: false), draft, "qwen3:8b").Pass); - Assert.False(ConnectionLogic.CheckApplied(null, draft, "qwen3:8b").Pass); + Assert.Equal("Not reported", Money.Usd((decimal?)null)); + Assert.Equal("$0.15", Money.Usd((decimal?)0.15m)); + Assert.Equal("Unpriced", Money.PerMillion(null)); + Assert.Equal("$0.15 / 1M", Money.PerMillion(0.15m)); + Assert.Equal("Unpriced — cost unknown, not zero", Money.Price(0.15m, null)); + Assert.Equal("$0 provider charge (infrastructure excluded)", Money.Price(0m, 0m)); + Assert.Equal("in $0.15 · out $0.60 per 1M tokens", Money.Price(0.15m, 0.60m)); } [Fact] - public void Config_block_has_names_and_values_but_no_secret() + public void Caps_have_two_decimals_and_tiny_caps_stay_visible() { - var block = ConnectionLogic.ConfigBlock("http://ollama-host:11434/v1", "qwen3:8b", localOnly: true); - Assert.Contains("Providers__Mode=local-only", block, StringComparison.Ordinal); - Assert.Contains("Local__Endpoint=http://ollama-host:11434/v1", block, StringComparison.Ordinal); - Assert.Contains("Local__ModelId=qwen3:8b", block, StringComparison.Ordinal); - Assert.Contains("dotnet user-secrets set \"Local:ModelId\" \"qwen3:8b\"", block, StringComparison.Ordinal); - Assert.DoesNotContain("ApiKey=", block, StringComparison.Ordinal); + Assert.Equal("$250.00", Money.Cap(250m)); + Assert.Equal("$0.00", Money.Cap(0m)); + Assert.Equal("$0.005", Money.Cap(0.005m)); + Assert.Equal("62%", Money.Share(6.2m, 10m)); + Assert.Equal("n/a", Money.Share(1m, 0m)); + } + + [Fact] + public void Cost_text_now_uses_significant_digits() + => Assert.Equal("$0.000184 (estimated provider charge)", CostText.Cost(Rec.V2(costBasis: "reported", cost: 0.000184m))); +} - var cloud = ConnectionLogic.ConfigBlock("http://ollama-host:11434/v1", "qwen3:8b", localOnly: false); - Assert.DoesNotContain("\nProviders__Mode=local-only", "\n" + cloud, StringComparison.Ordinal); +public sealed class ConfigDraftTests +{ + [Fact] + public void Draft_is_a_deep_copy_and_never_aliases_the_applied_configuration() + { + var applied = Cfg.Hybrid(); + var session = new ConfigDraft(3, "\"v3\"", applied); + + session.Draft.Policies[0].Targets.Add(new PolicyTargetDto { ConnectionId = "x", ModelId = "y" }); + session.Draft.Connections[0].Models[0].Price!.InputPer1M = 9m; + session.Draft.Settings!.CacheTtlSeconds = 1; + + Assert.Equal(2, applied.Policies[0].Targets.Count); + Assert.Equal(0m, applied.Connections[0].Models[0].Price!.InputPer1M); + Assert.Equal(300, applied.Settings!.CacheTtlSeconds); + Assert.Equal(2, session.Base.Policies[0].Targets.Count); + Assert.NotSame(applied.Policies[0].Targets, session.Draft.Policies[0].Targets); } [Fact] - public void Route_review_text_depends_on_mode() + public void Dirty_tracking_follows_content_not_touches() { - Assert.Contains("PII and PHI requests route to local:qwen3:8b", ConnectionLogic.RouteReview("cloud", "qwen3:8b"), StringComparison.Ordinal); - Assert.Contains("every classification", ConnectionLogic.RouteReview("local-only", "qwen3:8b"), StringComparison.Ordinal); + var session = new ConfigDraft(3, null, Cfg.Hybrid()); + Assert.False(session.IsDirty); + Assert.Equal("\"v3\"", session.BaseEtag); + + session.Draft.Policies[0].Paused = true; + Assert.True(session.IsDirty); + session.Draft.Policies[0].Paused = false; + Assert.False(session.IsDirty); // toggled back: nothing to save + + Assert.True(PolicyRoutes.MoveDown(session.Draft.Policies[0].Targets, 0)); + Assert.True(session.IsDirty); // order is content + session.Reset(); + Assert.False(session.IsDirty); + Assert.Equal("openai", session.Draft.Policies[0].Targets[0].ConnectionId); } [Fact] - public void Governed_connection_test_prompt_is_fresh_every_run_so_it_cannot_hit_the_cache() - => Assert.NotEqual(ConnectionLogic.GovernedTestPrompt(), ConnectionLogic.GovernedTestPrompt()); + public void Change_summary_names_what_changed_without_values() + { + var before = Cfg.Hybrid(); + var after = ConfigCopy.Deep(before); + after.Mode = "local-only"; + after.Connections[1].Enabled = false; + after.Budgets.Add(new BudgetConfigDto { Id = "team-risk", Scope = "team:risk", CapUsd = 5m }); + after.Policies.RemoveAt(2); + PolicyRoutes.MoveDown(after.Policies[0].Targets, 0); + + var lines = ChangeSummary.Lines(before, after); + Assert.Contains("mode hybrid → local-only", lines); + Assert.Contains("connection openai changed", lines); + Assert.Contains("budget team-risk added", lines); + Assert.Contains("policy sensitive removed", lines); + Assert.Contains("policy public changed", lines); + Assert.DoesNotContain(lines, l => l.Contains("Secrets:", StringComparison.Ordinal)); + Assert.StartsWith("Console: ", ChangeSummary.Text(before, after), StringComparison.Ordinal); + Assert.Equal("Console: no effective change", ChangeSummary.Text(before, ConfigCopy.Deep(before))); + } +} +public sealed class EditOutcomeTests +{ [Fact] - public void Launch_link_reads_credentials_only_from_the_fragment() + public void Only_a_2xx_with_a_version_is_success() { - var c = LaunchLink.Parse("http://localhost:5201/ui/connect#token=abc%2B1&appkey=k-2"); - Assert.NotNull(c); - Assert.Equal("abc+1", c!.AdminToken); - Assert.Equal("k-2", c.ApplicationKey); + var ok = EditOutcomes.FromResponse(200, "{\"version\":8,\"etag\":\"\\\"v8\\\"\"}"); + Assert.Equal(EditOutcomeKind.Applied, ok.Kind); + Assert.True(ok.Succeeded); + Assert.Equal(8, ok.Version); + Assert.Equal("Applied version v8", ok.Message); + + Assert.Equal("Rollback applied as new version v9", EditOutcomes.FromResponse(200, "{\"version\":9}", rollback: true).Message); + + var noVersion = EditOutcomes.FromResponse(200, "{}"); + Assert.Equal(EditOutcomeKind.Failed, noVersion.Kind); + Assert.False(noVersion.Succeeded); + Assert.False(EditOutcomes.FromResponse(200, "not json").Succeeded); + } - Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect?token=abc")); // query is sent to the server: never accepted - Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect")); - Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#")); - Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#other=1")); + [Fact] + public void Stale_edit_412_keeps_the_draft_and_names_the_new_version() + { + var stale = EditOutcomes.FromResponse(412, "{\"error\":\"stale\",\"reason\":\"the active configuration is v8\",\"active_version\":8}"); + Assert.Equal(EditOutcomeKind.Stale, stale.Kind); + Assert.Equal(8, stale.Version); + Assert.StartsWith("Configuration changed since you started editing (now v8).", stale.Message, StringComparison.Ordinal); + Assert.Contains("kept", stale.Message, StringComparison.Ordinal); + Assert.False(stale.Succeeded); + + Assert.Equal(EditOutcomeKind.Stale, EditOutcomes.FromResponse(409, "").Kind); + Assert.Equal("Configuration changed since you started editing. Your draft was not applied and is kept.", EditOutcomes.StaleMessage(null)); + } + + [Fact] + public void Validation_422_maps_errors_to_fields_and_reports_the_active_version_unchanged() + { + var body = "{\"error\":\"invalid_configuration\",\"active_version\":7,\"errors\":[{\"path\":\"connections[1].secret_ref\",\"code\":\"secret_unavailable\",\"message\":\"secret not set\"},{\"path\":\"policies[0].targets[1]\",\"code\":\"sensitive_cloud_target\",\"message\":\"cloud target for PII\"}],\"warnings\":[{\"path\":\"policies\",\"code\":\"no_route_for_classification\",\"message\":\"Phi has no route\"}]}"; + var invalid = EditOutcomes.FromResponse(422, body); + Assert.Equal(EditOutcomeKind.Invalid, invalid.Kind); + Assert.Equal(7, invalid.Version); + Assert.Equal(2, invalid.Errors!.Count); + Assert.Single(invalid.Warnings!); + Assert.Contains("active version is unchanged", invalid.Message, StringComparison.Ordinal); + + var index = new IssueIndex(invalid.Errors, invalid.Warnings!); + Assert.Single(index.ErrorsAt("connections[1]")); + Assert.Single(index.ErrorsAt("connections[1].secret_ref")); + Assert.Empty(index.ErrorsAt("connections[0]")); + Assert.True(index.HasErrorAt("policies[0]")); + Assert.Single(index.WarningsAt("policies")); + Assert.Single(index.Unclaimed(["connections[1]"])); + Assert.NotNull(IssueHelp.For("secret_unavailable")); + } + + [Theory] + [InlineData(428, EditOutcomeKind.PreconditionRequired)] + [InlineData(401, EditOutcomeKind.Unauthorized)] + [InlineData(404, EditOutcomeKind.NotFound)] + [InlineData(400, EditOutcomeKind.Failed)] + [InlineData(500, EditOutcomeKind.Failed)] + public void Other_answers_are_never_success(int status, EditOutcomeKind kind) + { + var o = EditOutcomes.FromResponse(status, "{\"error\":\"x\",\"reason\":\"y\"}"); + Assert.Equal(kind, o.Kind); + Assert.False(o.Succeeded); + Assert.Null(o.Errors); + } + + [Fact] + public void Issue_paths_match_on_member_and_element_boundaries_only() + { + Assert.True(IssueIndex.Under("connections[1]", "connections[1]")); + Assert.True(IssueIndex.Under("connections[1].endpoint", "connections[1]")); + Assert.True(IssueIndex.Under("connections[1].models[0].price", "connections[1].models[0]")); + Assert.False(IssueIndex.Under("connections[10].endpoint", "connections[1")); + Assert.False(IssueIndex.Under("connections[10]", "connections[1]")); + Assert.False(IssueIndex.Under("settings.cache_ttl_seconds_x", "settings.cache_ttl_seconds_")); + Assert.False(IssueIndex.Under(null, "settings")); + Assert.Equal("policies[2].targets[0]", IssueIndex.Target(2, 0)); + Assert.Equal("connections[0].models[1]", IssueIndex.Model(0, 1)); + Assert.Equal("settings.prompt_preview_chars", IssueIndex.Setting("prompt_preview_chars")); + } +} + +public sealed class ImpactTextTests +{ + private static ConfigImpactDto Impact() => new() + { + Classifications = + [ + new ConfigImpactRowDto { Classification = "Public", Profile = "*", Before = "openai/gpt-4o-mini", After = "ollama/qwen", Changed = true }, + new ConfigImpactRowDto { Classification = "Internal", Profile = "", Before = "ollama/qwen", After = "ollama/qwen", Changed = false }, + new ConfigImpactRowDto { Classification = "Pii", Profile = "customer", Before = "ollama/qwen", After = "refused: no eligible target" }, // no flag, text differs + ], + NewlyRefused = ["Pii/customer"], + PricingGaps = ["vllm/llama"], + }; + + [Fact] + public void Only_changed_routes_are_listed_with_refusals_marked() + { + var lines = ImpactText.ChangedRoutes(Impact()); + Assert.Equal(2, lines.Count); + Assert.Equal("Public", lines[0].Scope); + Assert.Equal("openai/gpt-4o-mini", lines[0].Before); + Assert.Equal("PII · profile customer", lines[1].Scope); + Assert.True(lines[1].NowRefused); + Assert.False(lines[1].WasRefused); + Assert.Empty(ImpactText.ChangedRoutes(null)); + } + + [Fact] + public void Headline_counts_each_kind_of_impact() + { + Assert.Equal("2 routes change · 1 newly refused · 1 pricing gap", ImpactText.Headline(Impact())); + Assert.Equal("No routing change for any classification or profile.", ImpactText.Headline(new ConfigImpactDto())); + Assert.StartsWith("Impact not computed", ImpactText.Headline(null), StringComparison.Ordinal); + Assert.True(ImpactText.NeedsAttention(Impact())); + Assert.False(ImpactText.NeedsAttention(new ConfigImpactDto())); + } +} + +public sealed class PolicyRoutesTests +{ + [Fact] + public void Summary_lines_state_the_effective_route_never_may_use() + { + var cfg = Cfg.Hybrid(); + Assert.Equal("Public → openai/gpt-4o-mini · fallback: ollama/qwen2.5-coder:7b", PolicyRoutes.SummaryLine(cfg.Policies[0], cfg)); + Assert.Equal("Internal → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[1], cfg)); + Assert.Equal("PII + PHI → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[2], cfg)); + foreach (var p in cfg.Policies) + Assert.DoesNotContain("may use", PolicyRoutes.SummaryLine(p, cfg), StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Paused_route_is_skipped_and_paused_policy_refuses() + { + var cfg = Cfg.Hybrid(); + cfg.Policies[0].Targets[0].Paused = true; + Assert.Equal("Public → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[0], cfg)); + Assert.Equal("route paused — skipped", PolicyRoutes.Targets(cfg.Policies[0], cfg)[0].ExcludedReason); + + cfg.Policies[0].Targets[1].Paused = true; + Assert.Equal("Public → refused (no eligible target)", PolicyRoutes.SummaryLine(cfg.Policies[0], cfg)); + + cfg.Policies[1].Paused = true; + Assert.Equal("Internal → refused (policy paused)", PolicyRoutes.SummaryLine(cfg.Policies[1], cfg)); + Assert.Equal("Paused — refuses its traffic", PolicyText.StateText(cfg.Policies[1])); + Assert.Contains(PolicyRoutes.RefusalConditions(cfg.Policies[1], cfg), l => l.Contains("paused", StringComparison.Ordinal)); + } + + [Fact] + public void Cloud_targets_are_never_eligible_or_offered_for_sensitive_policies_or_local_only() + { + var cfg = Cfg.Hybrid(); + cfg.Policies[2].Targets.Add(new PolicyTargetDto { ConnectionId = "openai", ModelId = "gpt-4o-mini" }); + var states = PolicyRoutes.Targets(cfg.Policies[2], cfg); + Assert.False(states[1].Eligible); + Assert.Contains("PII/PHI", states[1].ExcludedReason!, StringComparison.Ordinal); + + cfg.Policies[2].Targets.RemoveAt(1); + var options = PolicyRoutes.Options(cfg.Policies[2], cfg); + var cloud = Assert.Single(options); + Assert.Equal("openai/gpt-4o-mini", cloud.Value); + Assert.Equal(PolicyText.SensitiveNeverCloud, cloud.DisabledReason); + + cfg.Mode = "local-only"; + Assert.Equal("Internal → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[1], cfg)); + Assert.Equal("Public → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[0], cfg)); + Assert.NotNull(Assert.Single(PolicyRoutes.Options(cfg.Policies[1], cfg)).DisabledReason); + } + + [Fact] + public void Disabled_or_unknown_connections_and_unpermitted_models_are_excluded() + { + var cfg = Cfg.Hybrid(); + cfg.Connections[1].Enabled = false; + cfg.Policies[1].Targets.Add(new PolicyTargetDto { ConnectionId = "ghost", ModelId = "m" }); + cfg.Policies[1].Targets.Add(new PolicyTargetDto { ConnectionId = "ollama", ModelId = "not-permitted" }); + Assert.Equal("Public → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[0], cfg)); + var states = PolicyRoutes.Targets(cfg.Policies[1], cfg); + Assert.Contains("not configured", states[1].ExcludedReason!, StringComparison.Ordinal); + Assert.Contains("not permitted", states[2].ExcludedReason!, StringComparison.Ordinal); + Assert.Empty(PolicyRoutes.Options(cfg.Policies[0], cfg)); // disabled connection offers nothing; ollama already listed + } + + [Fact] + public void Length_heuristic_is_named_honestly_with_its_threshold() + { + var cfg = Cfg.Hybrid(); + var p = cfg.Policies[0]; + p.Strategy = "length-heuristic"; + p.ThresholdTokens = 750; + Assert.Equal("Length-based heuristic (threshold 750 tokens)", PolicyText.StrategyName(p)); + Assert.Equal("Public → ≤ 750 tokens: openai/gpt-4o-mini · above: ollama/qwen2.5-coder:7b", PolicyRoutes.SummaryLine(p, cfg)); + Assert.Equal("Fixed + fallback", PolicyText.StrategyName(cfg.Policies[1])); + } + + [Fact] + public void Fallback_reorder_moves_one_place_and_stops_at_the_ends() + { + var list = new List + { + new() { ConnectionId = "a", ModelId = "1" }, new() { ConnectionId = "b", ModelId = "2" }, new() { ConnectionId = "c", ModelId = "3" }, + }; + Assert.False(PolicyRoutes.MoveUp(list, 0)); + Assert.False(PolicyRoutes.MoveDown(list, 2)); + Assert.False(PolicyRoutes.MoveUp(list, 7)); + Assert.True(PolicyRoutes.MoveUp(list, 2)); + Assert.Equal(new[] { "a", "c", "b" }, list.Select(t => t.ConnectionId)); + Assert.True(PolicyRoutes.MoveDown(list, 0)); + Assert.Equal(new[] { "c", "a", "b" }, list.Select(t => t.ConnectionId)); + Assert.Equal("Primary", PolicyRoutes.RoleLabel(0)); + Assert.Equal("Fallback 2", PolicyRoutes.RoleLabel(2)); + } + + [Fact] + public void Hybrid_defaults_build_a_restrictive_draft_and_need_a_local_model() + { + var cfg = Cfg.Hybrid(); + cfg.Mode = "legacy-cloud"; + cfg.Policies = [new PolicyDto { Id = "legacy-general", Enabled = true, Classifications = ["Public", "Internal"], Targets = [new PolicyTargetDto { ConnectionId = "openai", ModelId = "gpt-4o-mini" }] }]; + Assert.True(PolicyRoutes.IsLegacy(cfg.Mode)); + + Assert.Null(HybridDefaults.ApplyTo(cfg)); + Assert.Equal("hybrid", cfg.Mode); + Assert.Equal(new[] { "public", "internal", "sensitive" }, cfg.Policies.Select(p => p.Id)); + Assert.Equal(new[] { "openai/gpt-4o-mini", "ollama/qwen2.5-coder:7b" }, cfg.Policies[0].Targets.Select(PolicyRoutes.Key)); + Assert.All(cfg.Policies.Skip(1), p => Assert.Equal(new[] { "ollama/qwen2.5-coder:7b" }, p.Targets.Select(PolicyRoutes.Key))); + Assert.Equal(new[] { "Pii", "Phi" }, cfg.Policies[2].Classifications); + + var noLocal = Cfg.Hybrid(); + noLocal.Connections.RemoveAt(0); + var before = ConfigCopy.Canonical(noLocal); + Assert.NotNull(HybridDefaults.ApplyTo(noLocal)); + Assert.Equal(before, ConfigCopy.Canonical(noLocal)); // untouched when it cannot comply + } +} + +public sealed class SegmentScopeTests +{ + [Fact] + public void Current_segment_is_the_hosts_explicit_flag_only() + { + Assert.True(SegmentScope.IsCurrent(new AuditSegmentDto { Id = "seg-2", Current = true })); + // Never inferred from the id or from the list order. + Assert.False(SegmentScope.IsCurrent(new AuditSegmentDto { Id = "current", Current = false })); + Assert.False(SegmentScope.IsCurrent(new AuditSegmentDto { Id = "a-0123456789abcdef" })); + } + + [Fact] + public void Page_scope_comes_from_the_segment_descriptor() + { + var first = new DateTimeOffset(2026, 10, 16, 9, 0, 0, TimeSpan.Zero); + Assert.Equal("Current segment · since 2026-10-16 09:00:00 UTC", + SegmentScope.Label(new SegmentInfo { Id = "current", Label = "Current segment", IsCurrent = true, FirstUtc = first })); + Assert.Equal("Archived segment Archived 2026-10-01 09:00:00 UTC · read-only", + SegmentScope.Label(new SegmentInfo { Id = "a-0123456789abcdef", Label = "Archived 2026-10-01 09:00:00 UTC", IsCurrent = false })); + // An archived page whose id happens to be "current" is still archived: the flag decides. + Assert.StartsWith("Archived segment", SegmentScope.Label(new SegmentInfo { Id = "current", IsCurrent = false }), StringComparison.Ordinal); + } + + [Fact] + public void Labels_say_which_segment_and_that_filters_cover_only_loaded_records() + { + var first = new DateTimeOffset(2026, 10, 16, 9, 0, 0, TimeSpan.Zero); + Assert.Equal("Current segment · since 2026-10-16 09:00:00 UTC", SegmentScope.Label(new AuditSegmentDto { Id = "current", Current = true, FirstUtc = first })); + Assert.Equal("Archived segment Oct 1 · read-only", SegmentScope.Label(new AuditSegmentDto { Id = "a1", Label = "Oct 1" })); + Assert.Equal("Archived · a1 (1,200 records)", SegmentScope.Option(new AuditSegmentDto { Id = "a1", Entries = 1200 })); + + var cov = SegmentScope.Coverage("Current segment", 200, 1500, moreAvailable: true, filtersActive: true); + Assert.Contains("200 of 1,500 records loaded", cov, StringComparison.Ordinal); + Assert.Contains("Load older", cov, StringComparison.Ordinal); + Assert.Contains("only to these loaded records", cov, StringComparison.Ordinal); + Assert.DoesNotContain("all history", cov, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Load older", SegmentScope.Coverage("Current segment", 200, 1500, moreAvailable: false, filtersActive: false), StringComparison.Ordinal); + } + + [Theory] + [InlineData(false, null, true, EvidenceCompletenessState.Pending)] + [InlineData(false, true, false, EvidenceCompletenessState.Unavailable)] + [InlineData(true, true, false, EvidenceCompletenessState.Verified)] + [InlineData(true, false, false, EvidenceCompletenessState.Unverifiable)] + [InlineData(true, null, true, EvidenceCompletenessState.Recorded)] + public void Evidence_is_verified_only_when_present_in_a_verified_chain(bool found, bool? chainValid, bool pending, EvidenceCompletenessState expected) + { + var s = EvidenceCompleteness.State(found, chainValid, pending); + Assert.Equal(expected, s); + var (label, tone) = EvidenceCompleteness.Text(s); + Assert.Equal(expected == EvidenceCompletenessState.Verified, label.StartsWith("Audit integrity verified", StringComparison.Ordinal)); + Assert.Equal(expected == EvidenceCompletenessState.Verified, tone == "ok"); + } +} + +public sealed class BudgetTextTests +{ + [Fact] + public void Thresholds_parse_as_percentages_and_reject_garbage() + { + Assert.Equal(new[] { 0.8m, 0.95m }, BudgetText.ParseThresholds("95, 80")); + Assert.Equal(new[] { 0.5m }, BudgetText.ParseThresholds("50%")); + Assert.Empty(BudgetText.ParseThresholds("")!); + Assert.Null(BudgetText.ParseThresholds("0")); + Assert.Null(BudgetText.ParseThresholds("120")); + Assert.Null(BudgetText.ParseThresholds("eighty")); + Assert.Equal("80, 95", BudgetText.FormatThresholds([0.8m, 0.95m])); + Assert.Equal("80%, 95%", BudgetText.Thresholds([0.8m, 0.95m])); + } + + [Fact] + public void Server_states_are_worded_and_overrun_is_never_truncated() + { + Assert.Equal(("Cap reached — new paid work blocked", "bad"), BudgetText.Warning("exceeded")); + Assert.Equal("warn", BudgetText.Warning("critical").Tone); + Assert.Equal("Exceeded by $0.000184", BudgetText.Remaining(-0.000184m)); + Assert.Equal("$1.50", BudgetText.Remaining(1.5m)); + Assert.Equal("Monthly (UTC) · 2026-10", BudgetText.Period("monthly", "2026-10")); + Assert.Equal("Team risk", BudgetText.Scope("team:risk")); + Assert.Equal("Application demo-app", BudgetText.Scope("application:demo-app")); + Assert.Equal(100, BudgetText.MeterPercent(5m, 1m, 4m)); + Assert.Equal(100, BudgetText.MeterPercent(0.01m, 0m, 0m)); + Assert.Equal(25, BudgetText.MeterPercent(0.5m, 0.5m, 4m)); + Assert.StartsWith("Warn only", BudgetText.Enforcement("warn-only"), StringComparison.Ordinal); + } + + [Fact] + public void Local_only_zero_spend_is_detected_for_the_explanatory_empty_state() + { + Assert.True(BudgetText.NoSpendAnywhere([new BudgetStateDto { Id = "g", CapUsd = 10m }])); + Assert.False(BudgetText.NoSpendAnywhere([new BudgetStateDto { Id = "g", CapUsd = 10m, ReservedUsd = 0.0001m }])); + Assert.False(BudgetText.NoSpendAnywhere(null)); + } +} + +public sealed class ConnectionFormTests +{ + private static readonly Dictionary Secrets = new() + { + ["Secrets:openai"] = new SecretAvailabilityDto { Available = true }, + ["Secrets:anthropic"] = new SecretAvailabilityDto { Available = false }, + }; + + [Fact] + public void Discovery_never_approves_and_local_prices_default_to_explicit_zero_marginal() + { + var f = ConnectionForm.NewOllama(["ollama"]); + Assert.Equal("ollama-2", f.Id); + f.Endpoint = "http://ollama-host:11434/v1"; + f.ApplyDiscovery(["qwen2.5-coder:7b", "llama3:8b"]); + Assert.Equal(2, f.Models.Count); + Assert.All(f.Models, m => Assert.False(m.Selected)); + Assert.All(f.Models, m => Assert.Equal(ConnectionForm.BasisLocal, m.Basis)); + Assert.All(f.Models, m => Assert.Equal(0m, m.InputPer1M)); + + Assert.Contains(f.Problems([], null), p => p.StartsWith("Select at least one", StringComparison.Ordinal)); + f.Models[1].Selected = true; + Assert.Empty(f.Problems(["ollama"], null)); + + var dto = f.ToConnection(); + var model = Assert.Single(dto.Models); // unselected tags are not saved + Assert.Equal("qwen2.5-coder:7b", model.ModelId); + Assert.Equal("zero-marginal-local", model.Price!.Basis); + Assert.Equal("Local", dto.Boundary); + Assert.Null(dto.SecretRef); + } + + [Fact] + public void Editing_prefills_actual_values_and_marks_what_the_endpoint_no_longer_reports() + { + var conn = Cfg.Hybrid().Connections[0]; + var f = ConnectionForm.FromConnection(conn); + Assert.False(f.IsNew); + Assert.Equal("http://ollama-host:11434/v1", f.Endpoint); + var row = Assert.Single(f.Models); + Assert.True(row.Selected); + Assert.True(row.Configured); + + f.ApplyDiscovery(["other:1b"]); + Assert.False(f.Models[0].ReportedByEndpoint); + Assert.False(f.Models[1].Selected); + Assert.Equal(0, f.SentIndex(f.Models[0])); + Assert.Null(f.SentIndex(f.Models[1])); + } + + [Fact] + public void Cloud_needs_prices_and_an_available_secret_reference() + { + var f = ConnectionForm.NewCloud("Anthropic", []); + Assert.Equal("Cloud", f.Boundary); + f.SetKind("OpenAi"); + Assert.Equal("Cloud", f.Boundary); + var m = f.AddModel("gpt-4o-mini"); + Assert.True(m.Selected); + Assert.False(m.Priced); + Assert.Null(m.InputPer1M); // cloud prices are never assumed + + var problems = f.Problems([], Secrets); + Assert.Contains(problems, p => p.Contains("never treated as $0", StringComparison.Ordinal)); + Assert.Contains(problems, p => p.StartsWith("Choose the server-side secret", StringComparison.Ordinal)); + + m.Priced = true; + Assert.Contains(f.Problems([], Secrets), p => p.Contains("enter both input and output prices", StringComparison.Ordinal)); + + m.InputPer1M = 0.15m; + m.OutputPer1M = 0.6m; + f.SecretRef = "Secrets:anthropic"; + Assert.Contains(f.Problems([], Secrets), p => p.Contains("not available on the server", StringComparison.Ordinal)); + f.SecretRef = "Secrets:openai"; + Assert.Empty(f.Problems([], Secrets)); + + m.Priced = false; + Assert.Contains(f.Problems([], Secrets), p => p.Contains("never treated as $0", StringComparison.Ordinal)); + Assert.Null(f.ToConnection().Models[0].Price); // unpriced stays unknown, never $0 + } + + [Fact] + public void Apply_to_draft_replaces_its_own_earlier_copy_even_after_an_id_change() + { + var draft = Cfg.Hybrid(); + var f = ConnectionForm.NewOllama(draft.Connections.Select(c => c.Id)); + f.Endpoint = "http://second:11434/v1"; + f.AddModel("phi3:mini"); + int i = f.ApplyTo(draft); + Assert.Equal(2, i); + f.Id = "ollama-b"; + Assert.Equal(2, f.ApplyTo(draft)); + Assert.Equal(new[] { "ollama", "openai", "ollama-b" }, draft.Connections.Select(c => c.Id)); + + var edit = ConnectionForm.FromConnection(draft.Connections[0]); + edit.Enabled = false; + Assert.Equal(0, edit.ApplyTo(draft)); + Assert.False(draft.Connections[0].Enabled); + Assert.Equal(3, draft.Connections.Count); + } + + [Fact] + public void Removing_a_routed_model_is_called_out_before_preview() + { + var cfg = Cfg.Hybrid(); + var f = ConnectionForm.FromConnection(cfg.Connections[0]); + f.Models[0].Selected = false; + Assert.Equal(new[] { "ollama/qwen2.5-coder:7b" }, f.RemovedModelsStillRouted(cfg)); + } + + [Theory] + [InlineData("Secrets:openai", true)] + [InlineData("OpenAI:ApiKey", true)] + [InlineData("Secrets:", false)] + [InlineData("Env:OPENAI", false)] + [InlineData("Secrets:bad name", false)] + public void Secret_references_are_restricted(string r, bool ok) => Assert.Equal(ok, ConnectionRules.IsValidSecretRef(r)); + + [Fact] + public void Connection_rules_helpers() + { + Assert.Equal("Secrets__openai", ConnectionRules.EnvVarFor("Secrets:openai")); + Assert.Equal("api.openai.com:443", ConnectionRules.AuthorityOf("OpenAi", null)); + Assert.Equal("host:8000", ConnectionRules.AuthorityOf("OpenAiCompatible", "http://host:8000/v1")); + Assert.False(ConnectionRules.IsValidId("has space")); + Assert.True(ConnectionRules.EndpointRequired("Ollama")); + Assert.False(ConnectionRules.EndpointRequired("Anthropic")); + } +} + +public sealed class ConnectionHealthTests +{ + private static readonly DateTimeOffset Now = new(2026, 10, 16, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public void A_newer_failure_wins_and_both_facts_are_stated() + { + var h = new ModelHealth { State = "failed", LastSuccessUtc = Now.AddMinutes(-30), LastFailureUtc = Now.AddMinutes(-2), LastError = "timeout" }; + var v = ConnectionHealth.Summarize(true, [h], null, null, null, Now); + Assert.Equal("bad", v.Tone); + Assert.Equal("Last governed call failed 2 min ago · last success 30 min ago", v.Summary); + Assert.Contains(v.Details, d => d.Label == "Last failed governed call" && d.Value.Contains("timeout", StringComparison.Ordinal)); + } + + [Fact] + public void A_reachable_probe_is_not_called_ready_when_no_call_succeeded() + { + var probe = new ProbeResponse { Allowed = true, Reachable = true, CheckedUtc = Now.AddSeconds(-5) }; + var v = ConnectionHealth.Summarize(true, [new ModelHealth { State = "unknown" }], probe, null, null, Now); + Assert.Equal("Endpoint reachable (probe 5 s ago) · no governed call observed yet", v.Summary); + Assert.DoesNotContain("ready", v.Summary, StringComparison.OrdinalIgnoreCase); + Assert.Equal("hollow", v.Tone); + Assert.Contains(v.Details, d => d.Label == "Last successful governed call" && d.Value == "None observed"); + } + + [Fact] + public void Probe_failure_disabled_and_unobserved_states() + { + var refused = new ProbeResponse { Allowed = false, Reachable = false }; + var v = ConnectionHealth.Summarize(true, [], refused, Now.AddMinutes(-1), null, Now); + Assert.Equal("bad", v.Tone); + Assert.Contains(v.Details, d => d.Value.Contains("not on the probe allow-list", StringComparison.Ordinal)); + + Assert.StartsWith("Disabled", ConnectionHealth.Summarize(false, [], null, null, null, Now).Summary, StringComparison.Ordinal); + Assert.StartsWith("Not observed yet", ConnectionHealth.Summarize(true, [], null, null, null, Now).Summary, StringComparison.Ordinal); + + var ok = ConnectionHealth.Summarize(true, [new ModelHealth { State = "ok", LastSuccessUtc = Now.AddHours(-3) }], null, null, + new ModelHealth { LastFailureUtc = Now.AddHours(-1), LastError = "refused" }, Now); + Assert.Equal("Last successful governed call 3 h ago", ok.Summary); // inference fact first; probe is a separate detail + Assert.Contains(ok.Details, d => d.Label == "Last endpoint probe" && d.Value.StartsWith("Failed", StringComparison.Ordinal)); + } +} + +public sealed class RequestFilterApplicationTests +{ + [Fact] + public void Application_filter_matches_v3_application_id_only() + { + var a = Rec.V2(); + a.ApplicationId = "demo-app"; + var legacy = Rec.Legacy(); + var c = RequestFilterCriteria.None with { Application = "DEMO-APP" }; + Assert.True(c.IsActive); + Assert.True(RequestFilter.Matches(a, c, DateTimeOffset.UtcNow)); + Assert.False(RequestFilter.Matches(legacy, c, DateTimeOffset.UtcNow)); + Assert.Equal(new[] { "demo-app" }, RequestFilter.Applications([a, legacy])); + } +} + +// ---- Review round 2 (UI): pure logic behind U2/U4/U6/U7/U8/U9/U10 ---- + +public sealed class SubmissionPollTests +{ + private const string Client = "0123456789abcdef0123456789abcdef"; + private const string Req = "req_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + + private static PlaygroundSubmissionDto Found(string state = "running") => new() { ClientRequestId = Client, RequestId = Req, State = state }; + + [Fact] + public void Not_registered_yet_polls_again_then_subscribes_exactly_once() + { + var p = new SubmissionPoll(Client); + Assert.True(p.ShouldPoll); + Assert.Equal(SubmissionPollAction.PollAgain, p.OnPollResult(404, null)); + Assert.Equal(SubmissionPollAction.PollAgain, p.OnPollResult(null, null)); // transport hiccup: bounded retry + Assert.Equal(SubmissionPollAction.Subscribe, p.OnPollResult(200, Found())); + Assert.Equal(Req, p.RequestId); + Assert.Equal("submission lookup", p.Source); + Assert.False(p.ShouldPoll); + Assert.Equal(3, p.Polls); + + // Later answers and the finished POST never start a second subscription. + Assert.Equal(SubmissionPollAction.Stop, p.OnPollResult(200, Found("completed"))); + Assert.Equal(SubmissionPollAction.Stop, p.OnSendCompleted(Req)); + Assert.True(p.Stopped); + } + + [Fact] + public void A_body_for_another_submission_is_not_accepted() + { + var p = new SubmissionPoll(Client); + var other = new PlaygroundSubmissionDto { ClientRequestId = "ffff", RequestId = "req_x", State = "running" }; + Assert.Equal(SubmissionPollAction.PollAgain, p.OnPollResult(200, other)); + Assert.Null(p.RequestId); + } + + [Fact] + public void Response_id_is_the_backstop_when_polling_found_nothing() + { + var p = new SubmissionPoll(Client); + Assert.Equal(SubmissionPollAction.PollAgain, p.OnPollResult(404, null)); + Assert.Equal(SubmissionPollAction.Subscribe, p.OnSendCompleted(Req)); + Assert.Equal("response", p.Source); + Assert.False(p.ShouldPoll); + + var none = new SubmissionPoll(Client); + Assert.Equal(SubmissionPollAction.Stop, none.OnSendCompleted(null)); // 400 before governance: no id, no trace + Assert.Null(none.RequestId); + } + + [Fact] + public void Unauthorized_and_the_bound_stop_polling() + { + var p = new SubmissionPoll(Client); + Assert.Equal(SubmissionPollAction.Stop, p.OnPollResult(401, null)); + Assert.False(p.ShouldPoll); + + var b = new SubmissionPoll(Client); + for (int i = 1; i < SubmissionPoll.MaxPolls; i++) Assert.Equal(SubmissionPollAction.PollAgain, b.OnPollResult(404, null)); + Assert.Equal(SubmissionPollAction.Stop, b.OnPollResult(404, null)); + Assert.False(b.ShouldPoll); + Assert.Equal(TimeSpan.FromMilliseconds(250), SubmissionPoll.Interval); + } + + [Fact] + public void Client_request_ids_are_guid_n() + { + var id = RequestSnapshot.NewClientRequestId(); + Assert.Matches("^[0-9a-f]{32}$", id); + } +} + +public sealed class LiveTraceStartTests +{ + private static TraceEventDto E(long seq, string stage, string state, string? attempt = null, double? ms = null) + => new() { Seq = seq, Stage = stage, State = state, AttemptId = attempt, DurationMs = ms, RequestId = "req_1" }; + + [Fact] + public void Provider_shows_running_while_waiting_with_its_output_bounds() + { + var acc = new TraceAccumulator(); + acc.AddRange([E(1, "auth", "passed", ms: 0.4), E(2, "budget", "passed", ms: 0.2), + new TraceEventDto { Seq = 3, Stage = "provider", State = "running", AttemptId = "att_1", Target = "ollama/qwen", + RequestedMaxOutputTokens = 256, EffectiveMaxOutputTokens = 64 }]); + var v = acc.View(); + var provider = v.Steps.Single(s => s.Stage == "provider"); + Assert.Equal(TraceStepState.Running, provider.State); + Assert.Null(provider.DurationMs); // no invented timing while it runs + var a = Assert.Single(provider.Attempts); + Assert.Equal(256, a.RequestedMaxOutputTokens); + Assert.Equal(64, a.EffectiveMaxOutputTokens); + Assert.True(v.HasEvents); + Assert.Equal(TraceStepState.Pending, v.Steps.Single(s => s.Stage == "attribution").State); + } + + [Fact] + public void Unknown_state_spellings_are_not_guessed() + => Assert.Equal(TraceStepState.NotReported, TraceModel.ParseState("canceled")); +} + +public sealed class PolicyEditingTests +{ + private static CovenantConfigDto AllClasses() + { + var cfg = Cfg.Hybrid(); + cfg.Mode = "legacy-cloud"; + cfg.Profiles = [new WorkloadProfileDto { Id = "internal", Name = "Internal", Baseline = "Internal" }]; + cfg.Policies = + [ + new PolicyDto + { + Id = "legacy", Name = "Imported", Enabled = true, Classifications = ["Public", "Internal", "Pii", "Phi"], Strategy = "fixed", + Targets = [new PolicyTargetDto { ConnectionId = "openai", ModelId = "gpt-4o-mini" }, new PolicyTargetDto { ConnectionId = "ollama", ModelId = "qwen2.5-coder:7b" }], + Retry = new RetrySettingsDto { MaxAttempts = 2, DeadlineMs = 60_000, On = ["timeout"] }, + }, + ]; + return cfg; + } + + [Fact] + public void Split_makes_public_cloud_with_local_fallback_and_never_cloud_for_sensitive() + { + var cfg = AllClasses(); + Assert.True(PolicyEditing.CanSplit(cfg.Policies[0])); + Assert.Null(PolicyEditing.ApplySplit(cfg, "legacy")); + Assert.Equal(2, cfg.Policies.Count); + + var pub = cfg.Policies[0]; + Assert.Equal(new[] { "Public" }, pub.Classifications); + Assert.Equal(new[] { "openai/gpt-4o-mini", "ollama/qwen2.5-coder:7b" }, pub.Targets.Select(PolicyRoutes.Key)); + Assert.Equal(60_000, pub.Retry!.DeadlineMs); + + var restricted = cfg.Policies[1]; + Assert.Equal(new[] { "Internal", "Pii", "Phi" }, restricted.Classifications); + Assert.Equal(new[] { "ollama/qwen2.5-coder:7b" }, restricted.Targets.Select(PolicyRoutes.Key)); + Assert.DoesNotContain(restricted.Targets, t => t.ConnectionId == "openai"); + Assert.All(PolicyRoutes.Targets(restricted, cfg), t => Assert.Equal("Local", t.Boundary)); + Assert.NotEqual(pub.Id, restricted.Id); + Assert.DoesNotContain(cfg.Policies, p => p.Id == "legacy"); + } + + [Fact] + public void Split_without_a_cloud_target_proposes_a_priced_cloud_model_and_local_only_mode_keeps_public_local() + { + var cfg = AllClasses(); + cfg.Policies[0].Targets = [new PolicyTargetDto { ConnectionId = "ollama", ModelId = "qwen2.5-coder:7b" }]; + var plan = PolicyEditing.PlanSplit(cfg.Policies[0], cfg); + Assert.Null(plan.Problem); + Assert.Equal("openai/gpt-4o-mini", PolicyRoutes.Key(plan.PublicPolicy!.Targets[0])); + Assert.Contains(plan.Notes, n => n.Contains("first enabled, priced cloud model", StringComparison.Ordinal)); + + cfg.Mode = "local-only"; + var local = PolicyEditing.PlanSplit(cfg.Policies[0], cfg); + Assert.Equal(new[] { "ollama/qwen2.5-coder:7b" }, local.PublicPolicy!.Targets.Select(PolicyRoutes.Key)); + Assert.DoesNotContain(local.RestrictedPolicy!.Targets, t => t.ConnectionId == "openai"); + } + + [Fact] + public void Split_needs_a_local_model_and_a_mixed_policy() + { + var cfg = AllClasses(); + cfg.Connections.RemoveAll(c => c.Boundary == "Local"); + var before = ConfigCopy.Canonical(cfg); + Assert.NotNull(PolicyEditing.ApplySplit(cfg, "legacy")); + Assert.Equal(before, ConfigCopy.Canonical(cfg)); // untouched + + Assert.False(PolicyEditing.CanSplit(Cfg.Hybrid().Policies[0])); // Public only + } + + [Fact] + public void Create_policy_never_accepts_a_cloud_target_for_pii_or_phi() + { + var cfg = Cfg.Hybrid(); + var form = new NewPolicyForm { Id = "pii-cloud", Name = "PII", Classifications = ["Pii"], Targets = ["openai/gpt-4o-mini"] }; + var problems = PolicyEditing.Problems(form, cfg); + Assert.Contains(problems, p => p.Contains(PolicyText.SensitiveNeverCloud, StringComparison.Ordinal)); + Assert.Contains(PolicyEditing.TargetOptions(["Pii"], cfg), o => o.Value == "openai/gpt-4o-mini" && o.DisabledReason is not null); + Assert.NotEmpty(PolicyEditing.Add(cfg, form)); + Assert.Equal(3, cfg.Policies.Count); + + var ok = new NewPolicyForm { Id = "public-2", Name = "Public tickets", Classifications = ["Public"], Profiles = [], Targets = ["openai/gpt-4o-mini", "ollama/qwen2.5-coder:7b"] }; + Assert.Empty(PolicyEditing.Add(cfg, ok)); + var added = cfg.Policies[^1]; + Assert.Equal("public-2", added.Id); + Assert.True(added.Enabled); + Assert.Equal("fixed", added.Strategy); + Assert.Equal(new[] { "openai/gpt-4o-mini", "ollama/qwen2.5-coder:7b" }, added.Targets.Select(PolicyRoutes.Key)); + + Assert.Contains(PolicyEditing.Problems(new NewPolicyForm { Id = "public-2", Name = "x", Classifications = ["Public"], Targets = ["ollama/qwen2.5-coder:7b"] }, cfg), + p => p.Contains("already exists", StringComparison.Ordinal)); + Assert.Contains(PolicyEditing.Problems(new NewPolicyForm { Id = "p", Name = "x", Classifications = ["Public"], Profiles = ["nope"], Targets = ["ollama/qwen2.5-coder:7b"] }, cfg), + p => p.Contains("does not exist", StringComparison.Ordinal)); + } + + [Fact] + public void Applicability_edits_refuse_sensitive_classes_behind_a_cloud_target() + { + var cfg = Cfg.Hybrid(); + var pub = cfg.Policies[0]; // openai first + Assert.NotNull(PolicyEditing.SetClassifications(pub, ["Public", "Pii"], cfg)); + Assert.Equal(new[] { "Public" }, pub.Classifications); + Assert.NotNull(PolicyEditing.SetClassifications(pub, [], cfg)); + Assert.Null(PolicyEditing.SetClassifications(cfg.Policies[1], ["Internal", "Public"], cfg)); + Assert.Equal(new[] { "Public", "Internal" }, cfg.Policies[1].Classifications); // contract order + + cfg.Profiles = [new WorkloadProfileDto { Id = "internal", Name = "Internal", Baseline = "Internal" }]; + Assert.Null(PolicyEditing.SetProfiles(cfg.Policies[1], ["internal"], cfg)); + Assert.Equal(new[] { "internal" }, cfg.Policies[1].Profiles); + Assert.NotNull(PolicyEditing.SetProfiles(cfg.Policies[1], ["ghost"], cfg)); + } + + [Fact] + public void Removing_the_only_policy_for_a_class_says_it_will_be_refused() + { + var cfg = Cfg.Hybrid(); + var lines = PolicyEditing.RemovalImpact(cfg.Policies[2], cfg); + Assert.Equal(2, lines.Count); + Assert.All(lines, l => Assert.Contains("REFUSED", l, StringComparison.Ordinal)); + Assert.True(PolicyEditing.Remove(cfg, "sensitive")); + Assert.Equal(new[] { "public", "internal" }, cfg.Policies.Select(p => p.Id)); + Assert.False(PolicyEditing.Remove(cfg, "sensitive")); + } +} + +public sealed class RoundTwoCostAndFactsTests +{ + [Fact] + public void Mixed_cost_basis_is_labelled_as_including_estimates() + { + var r = Rec.V2(costBasis: "mixed", cost: 0.0021m); + Assert.Equal("≈ $0.0021 · Mixed (includes estimates)", CostText.Cost(r)); + Assert.Equal("≈ $0.0021 mixed", CostText.CostShort(r)); + Assert.Contains("includes estimates", CostText.BasisDescription("mixed"), StringComparison.Ordinal); + Assert.Equal("≈ $0.0021 Mixed (includes estimates)", CostText.BasisCost("mixed", 0.0021m)); + Assert.DoesNotContain("reported", CostText.Cost(r), StringComparison.Ordinal); + } + + [Fact] + public void Requested_and_effective_output_bounds_are_labelled_separately() + { + var r = Rec.V2(); + r.RequestedMaxOutputTokens = 256; + r.EffectiveMaxOutputTokens = 64; + r.ServedConnectionId = "ollama"; + Assert.Equal("256", RecordFacts.RequestedMaxOutputTokens(r)); + Assert.Equal("64", RecordFacts.EffectiveMaxOutputTokens(r)); + Assert.Equal("Requested 256 · enforced 64", RecordFacts.BoundsLine(r)); + Assert.Equal("ollama", RecordFacts.ServedConnection(r)); + + var none = Rec.V2(); + none.EffectiveMaxOutputTokens = 1024; + Assert.StartsWith("None requested", RecordFacts.RequestedMaxOutputTokens(none), StringComparison.Ordinal); + + var old = Rec.V2(); // older record: neither field + Assert.Equal("Not recorded", RecordFacts.RequestedMaxOutputTokens(old)); + Assert.Equal("Not recorded", RecordFacts.EffectiveMaxOutputTokens(old)); + Assert.Equal("Not recorded", RecordFacts.ServedConnection(old)); + Assert.Equal("Not recorded", RecordFacts.TruncatedText(old)); + } + + [Fact] + public void Truncation_and_incomplete_streams_are_stated_clearly() + { + var t = Rec.V2(); + t.EffectiveMaxOutputTokens = 64; + t.Attempts = [new AuditAttemptView { AttemptId = "att_1", ConnectionId = "ollama", ModelId = "qwen", Outcome = "served", EffectiveMaxOutputTokens = 64, Truncated = true }]; + Assert.True(RecordFacts.Truncated(t)); + Assert.StartsWith("Yes", RecordFacts.TruncatedText(t), StringComparison.Ordinal); + var line = Assert.Single(AttemptFacts.Lines(t)); + Assert.True(line.Truncated); + Assert.Equal(64, line.EffectiveMaxOutputTokens); + Assert.EndsWith("· bound 64 · truncated (length)", AttemptFacts.Detail(line), StringComparison.Ordinal); + + var inc = Rec.Upstream(); + inc.PartialOutputChars = 120; + inc.Attempts = [new AuditAttemptView { AttemptId = "att_1", ConnectionId = "openai", ModelId = "gpt-x", Outcome = "failed", ErrorClass = "incomplete_stream", EffectiveMaxOutputTokens = 256 }]; + Assert.True(RecordFacts.IsIncompleteStream(inc)); + var text = RecordFacts.IncompleteStreamText(inc)!; + Assert.Contains("NOT served", text, StringComparison.Ordinal); + Assert.Contains("120 characters", text, StringComparison.Ordinal); + Assert.Equal("256 (last attempt — not served)", RecordFacts.EffectiveMaxOutputTokens(inc)); + Assert.Null(RecordFacts.IncompleteStreamText(t)); + } + + [Fact] + public void Attempt_success_is_the_contract_word_served_only() + { + Assert.True(AttemptFacts.IsSuccess(new AuditAttemptView { Outcome = "served" })); + Assert.False(AttemptFacts.IsSuccess(new AuditAttemptView { Outcome = "ok" })); + Assert.False(AttemptFacts.IsSuccess(new AuditAttemptView { Outcome = "succeeded" })); + } + + [Theory] + [InlineData("Ollama")] + [InlineData("OpenAi")] + [InlineData("Anthropic")] + [InlineData("OpenAiCompatible")] + public void New_connections_start_with_a_120_second_timeout(string kind) + { + var f = kind == "Ollama" ? ConnectionForm.NewOllama([]) : ConnectionForm.NewCloud(kind, []); + Assert.Equal(120, f.TimeoutSeconds); + Assert.Equal(ConnectionForm.DefaultTimeoutSeconds, f.TimeoutSeconds); + Assert.Equal(120, f.ToConnection().TimeoutSeconds); + Assert.DoesNotContain(f.Problems([], null), p => p.Contains("Timeout", StringComparison.Ordinal)); + } +} + +public sealed class RequestPagingTests +{ + private static RequestsResponse Page(string id, bool current, string? cursor, int items = 2) + => new() + { + Segment = new SegmentInfo { Id = id, Label = current ? "Current segment" : "Archived 2026-10-01 09:00:00 UTC", IsCurrent = current, Entries = 10, ChainValid = true }, + Items = Enumerable.Range(0, items).Select(i => Rec.V2(id: "req_" + id + i.ToString(System.Globalization.CultureInfo.InvariantCulture))).ToList(), + NextCursor = cursor, + }; + + [Fact] + public void Current_pages_follow_next_cursor_until_the_last_page() + { + var p = new RequestPaging(); + p.Reset(null); + Assert.False(p.CanLoadOlder); + Assert.Equal(PageResult.Accepted, p.ApplyPage(Page("current", true, "c2-a"), older: false)); + Assert.True(p.CanLoadOlder); + Assert.Equal("c2-a", p.NextCursor); + Assert.Equal("Current segment", p.Segment!.Label); + Assert.Equal(PageResult.Accepted, p.ApplyPage(Page("current", true, null), older: true)); + Assert.False(p.CanLoadOlder); + Assert.True(p.Loaded); + } + + [Fact] + public void Scope_is_the_descriptor_never_the_request() + { + var p = new RequestPaging(); + p.Reset(null); + // Asked for the current segment, but the Host says this page is archived: refused, nothing shown. + Assert.Equal(PageResult.SegmentMismatch, p.ApplyPage(Page("a-0123456789abcdef", false, "x"), older: false)); + Assert.False(p.Loaded); + Assert.NotNull(p.Problem); + + var a = new RequestPaging(); + a.Reset("a-0123456789abcdef"); + Assert.Equal(PageResult.SegmentMismatch, a.ApplyPage(Page("current", true, "x"), older: false)); + Assert.Equal(PageResult.Accepted, a.ApplyPage(Page("a-0123456789abcdef", false, "y"), older: false)); + Assert.Equal(PageResult.SegmentMismatch, a.ApplyPage(Page("a-ffffffffffffffff", false, null), older: true)); // older page of another segment + Assert.Null(a.NextCursor); + } + + [Fact] + public void Cursor_expired_410_stops_paging_and_asks_for_a_reload() + { + var p = new RequestPaging(); + p.Reset(null); + p.ApplyPage(Page("current", true, "c2-a"), older: false); + Assert.Equal(PageResult.CursorExpired, p.ApplyError(410, "cursor_expired", "410: the segment was rotated")); + Assert.True(p.Expired); + Assert.False(p.CanLoadOlder); + Assert.Null(p.NextCursor); + Assert.Equal("The audit segment changed (archived) — reload the list.", p.Problem); + + Assert.Equal(PageResult.Failed, p.ApplyError(400, "invalid_cursor", "400: bad")); + Assert.Contains("invalid_cursor", p.Problem, StringComparison.Ordinal); + Assert.Equal(PageResult.Failed, p.ApplyError(410, "expired", "410: other")); // only cursor_expired means "reload" + + p.Reset(null); + Assert.False(p.Expired); + Assert.Null(p.Problem); + Assert.Equal(PageResult.Accepted, p.ApplyPage(Page("current", true, "c2-b"), older: false)); + Assert.True(p.CanLoadOlder); + } + + [Fact] + public void An_empty_page_has_no_older_cursor() + { + var p = new RequestPaging(); + p.Reset(null); + Assert.Equal(PageResult.Accepted, p.ApplyPage(Page("current", true, "c2-a", items: 0), older: false)); + Assert.False(p.CanLoadOlder); + } +} + +public sealed class HeaderLocalHealthTests +{ + private static readonly DateTimeOffset Now = new(2026, 10, 17, 12, 0, 0, TimeSpan.Zero); + + private static CatalogResponse Catalog(ModelHealth? health, ModelHealth? endpoint = null) => new() + { + Mode = "hybrid", + Local = new LocalRouteInfo + { + Configured = true, Registered = true, ConnectionId = "ollama-2", ModelId = "qwen2.5-coder:7b", Endpoint = "http://localhost:11434/v1", + Health = health, EndpointHealth = endpoint ?? new ModelHealth(), + }, + // A stale legacy connection literally named "local" must never be consulted. + Models = [new CatalogModel { Adapter = "local", ModelId = "qwen2.5-coder:7b", Registered = true, Health = new ModelHealth { State = "failed", LastFailureUtc = Now } }], + }; + + private static ConnectionHealthDto Row(string key, ModelHealth h) => new() + { + Key = key, ConnectionId = key.Split(':')[0], ModelId = key[(key.IndexOf(':') + 1)..], Boundary = "Local", Enabled = true, Health = h, + }; + + [Fact] + public void A_successful_governed_local_call_is_ready_from_status_connection_health() + { + var v = LocalHealth.Derive(Catalog(new ModelHealth()), [Row("ollama-2:qwen2.5-coder:7b", new ModelHealth { State = "ok", LastSuccessUtc = Now })]); + Assert.Equal(LocalRouteState.Ready, v.State); + Assert.Equal("status connection_health", v.Source); + Assert.Equal("ollama-2", v.ConnectionId); + } + + [Fact] + public void Catalog_local_health_is_used_when_status_has_no_row_and_the_legacy_local_adapter_is_ignored() + { + var v = LocalHealth.Derive(Catalog(new ModelHealth { State = "ok", LastSuccessUtc = Now }), null); + Assert.Equal(LocalRouteState.Ready, v.State); + Assert.Equal("catalog local.health", v.Source); + + var unobserved = LocalHealth.Derive(Catalog(new ModelHealth()), [Row("local:qwen2.5-coder:7b", new ModelHealth { State = "failed", LastFailureUtc = Now })]); + Assert.Equal(LocalRouteState.NotObserved, unobserved.State); // another connection's row is not this one's health + } + + [Fact] + public void Endpoint_health_only_when_runtime_health_is_unknown_and_newer_failures_degrade() + { + var probe = LocalHealth.Derive(Catalog(new ModelHealth { State = "unknown" }, new ModelHealth { State = "ok", LastSuccessUtc = Now }), []); + Assert.Equal(LocalRouteState.Ready, probe.State); + Assert.Equal("catalog local.endpoint_health", probe.Source); + + var degraded = LocalHealth.Derive(Catalog(new ModelHealth { State = "failed", LastSuccessUtc = Now.AddMinutes(-5), LastFailureUtc = Now, LastError = "timeout" }, + new ModelHealth { State = "ok", LastSuccessUtc = Now }), null); + Assert.Equal(LocalRouteState.Degraded, degraded.State); + Assert.Equal("timeout", degraded.Health!.LastError); + } + + [Fact] + public void Not_configured_not_registered_and_unknown() + { + Assert.Equal(LocalRouteState.Unknown, LocalHealth.Derive(null, null).State); + Assert.Equal(LocalRouteState.NotConfigured, LocalHealth.Derive(new CatalogResponse { Local = new LocalRouteInfo { Configured = false } }, null).State); + Assert.Equal(LocalRouteState.NotRegistered, + LocalHealth.Derive(new CatalogResponse { Local = new LocalRouteInfo { Configured = true, Registered = false, ConnectionId = "ollama" } }, null).State); + } +} + +// ---- Review round 3 (UI) ---- + +public sealed class ClassificationFactTests +{ + private static AuditEntryView With(string classification, string? baseline, string? signal) + { + var r = Rec.V2(classification: classification, signal: signal); + r.BaselineClassification = baseline; + return r; + } + + [Fact] + public void Escalation_names_baseline_and_detector() + => Assert.Equal("PII (baseline Public, escalated: US SSN pattern)", ModelFacts.ClassificationFact(With("Pii", "Public", "US SSN pattern"))); + + [Fact] + public void Escalation_without_a_recorded_signal_still_says_escalated() + => Assert.Equal("PHI (baseline Internal, escalated)", ModelFacts.ClassificationFact(With("Phi", "Internal", null))); + + [Fact] + public void Same_as_baseline_is_not_escalated() + { + Assert.Equal("Internal (baseline Internal, not escalated)", ModelFacts.ClassificationFact(With("Internal", "Internal", null))); + Assert.Equal("PII (baseline PII, not escalated; detector: US SSN pattern)", ModelFacts.ClassificationFact(With("Pii", "Pii", "US SSN pattern"))); + } + + [Fact] + public void Missing_baseline_is_said_not_guessed() + { + Assert.Equal("PII (detector: US SSN pattern; baseline not recorded)", ModelFacts.ClassificationFact(With("Pii", null, "US SSN pattern"))); + Assert.Equal("Internal (no detector rule matched; baseline not recorded)", ModelFacts.ClassificationFact(With("Internal", null, null))); + } + + [Fact] + public void Not_evaluated_and_legacy_records_never_show_the_restrictive_default_as_a_detection() + { + Assert.StartsWith("Not evaluated — stopped at", ModelFacts.ClassificationFact(Rec.AuthFail()), StringComparison.Ordinal); + Assert.DoesNotContain("PHI", ModelFacts.ClassificationFact(Rec.AuthFail()), StringComparison.Ordinal); + Assert.Equal(ModelFacts.NotRecorded, ModelFacts.ClassificationFact(Rec.Legacy())); + } + + [Fact] + public void Cache_provenance_uses_the_served_connection_when_the_model_lacks_it() + { + var r = Rec.V2(cacheHit: true, attempted: null, served: "stub-slow"); + r.ServedConnectionId = "local"; + Assert.Equal("local/stub-slow", ModelFacts.CacheOrigin(r)); + Assert.Equal("Cache — no provider call (originally local/stub-slow)", ModelFacts.Destination(r).Text); + Assert.Equal("Served from cache (no provider call) · local/stub-slow", ModelFacts.Served(r)); + + var full = Rec.V2(cacheHit: true, attempted: null, served: "ollama/qwen"); + full.ServedConnectionId = "ollama"; + Assert.Equal("ollama/qwen", ModelFacts.CacheOrigin(full)); + Assert.Null(ModelFacts.CacheOrigin(Rec.V2(cacheHit: true, attempted: null, served: null))); + } +} + +public sealed class ProfileEditingTests +{ + /// Hybrid config + two profiles and two existing applications (demo grants both, default internal). + private static CovenantConfigDto WithProfiles() + { + var cfg = Cfg.Hybrid(); + cfg.Profiles = + [ + new WorkloadProfileDto { Id = "public-demo", Name = "Public demo", Baseline = "Public" }, + new WorkloadProfileDto { Id = "internal-default", Name = "Internal", Baseline = "Internal" }, + ]; + cfg.Applications = + [ + new ApplicationDto { Id = "demo", Team = "payments", Enabled = true, ConsoleTesting = true, GrantedProfiles = ["public-demo", "internal-default"], DefaultProfile = "internal-default", MaxOutputTokens = 256 }, + new ApplicationDto { Id = "batch", Team = "risk", Enabled = true, ConsoleTesting = false, GrantedProfiles = ["internal-default"], DefaultProfile = "internal-default" }, + ]; + return cfg; + } + + [Fact] + public void Create_profile_validates_id_name_baseline_and_is_granted_to_nobody() + { + var cfg = WithProfiles(); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = "bad id!", Name = "x", Baseline = "Public" }, cfg), p => p.Contains("Profile id", StringComparison.Ordinal)); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = "public-demo", Name = "x", Baseline = "Public" }, cfg), p => p.Contains("already exists", StringComparison.Ordinal)); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = ProfileEditing.LegacyInternal, Name = "x", Baseline = "Internal" }, cfg), p => p.Contains("built-in", StringComparison.Ordinal)); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = "p", Name = " ", Baseline = "Public" }, cfg), p => p.Contains("name", StringComparison.Ordinal)); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = "p", Name = "x", Baseline = "Secret" }, cfg), p => p.Contains("baseline", StringComparison.Ordinal)); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = "p", Name = "x", Baseline = "pii" }, cfg), p => p.Contains("baseline", StringComparison.Ordinal)); // contract spelling only + + var before = ConfigCopy.Canonical(cfg); + Assert.NotEmpty(ProfileEditing.Add(cfg, new NewProfileForm { Id = "", Name = "x" })); + Assert.Equal(before, ConfigCopy.Canonical(cfg)); // refused ⇒ draft untouched + + Assert.Empty(ProfileEditing.Add(cfg, new NewProfileForm { Id = " customer-pii ", Name = " Customer PII ", Baseline = "Pii", Description = " " })); + var added = cfg.Profiles[^1]; + Assert.Equal("customer-pii", added.Id); + Assert.Equal("Customer PII", added.Name); + Assert.Equal("Pii", added.Baseline); + Assert.Null(added.Description); + Assert.Empty(ProfileEditing.Usage(cfg, "customer-pii").GrantedTo); + Assert.NotEqual("customer-pii", ProfileEditing.UniqueId("customer-pii", cfg)); + } + + [Fact] + public void Edit_name_and_baseline_refuse_blank_or_unknown_values() + { + var cfg = WithProfiles(); + var p = cfg.Profiles[0]; + Assert.NotNull(ProfileEditing.SetName(p, " ")); + Assert.Equal("Public demo", p.Name); + Assert.Null(ProfileEditing.SetName(p, " Public tickets ")); + Assert.Equal("Public tickets", p.Name); + Assert.NotNull(ProfileEditing.SetBaseline(p, "Confidential")); + Assert.Equal("Public", p.Baseline); + Assert.Null(ProfileEditing.SetBaseline(p, "Internal")); + Assert.Equal("Internal", p.Baseline); + ProfileEditing.SetDescription(p, " "); + Assert.Null(p.Description); + } + + [Fact] + public void Removing_a_default_profile_is_refused_client_side_with_the_reason() + { + var cfg = WithProfiles(); + var blockers = ProfileEditing.RemovalBlockers(cfg, "internal-default"); + Assert.Equal(2, blockers.Count); // default of demo and of batch + Assert.All(blockers, b => Assert.Contains("default profile", b, StringComparison.Ordinal)); + var before = ConfigCopy.Canonical(cfg); + Assert.NotNull(ProfileEditing.Remove(cfg, "internal-default")); + Assert.Equal(before, ConfigCopy.Canonical(cfg)); + Assert.NotEmpty(ProfileEditing.RemovalBlockers(cfg, ProfileEditing.LegacyInternal)); + Assert.NotEmpty(ProfileEditing.RemovalBlockers(cfg, "ghost")); + } + + [Fact] + public void Removing_the_only_profile_of_a_policy_is_refused_because_it_would_widen_the_policy() + { + var cfg = WithProfiles(); + cfg.Policies[0].Profiles = ["public-demo"]; + Assert.Contains(ProfileEditing.RemovalBlockers(cfg, "public-demo"), b => b.Contains("widen", StringComparison.Ordinal)); + Assert.NotNull(ProfileEditing.Remove(cfg, "public-demo")); + Assert.Equal(new[] { "public-demo" }, cfg.Policies[0].Profiles); + } + + [Fact] + public void Removal_impact_lists_grants_and_multi_profile_policies_then_remove_cleans_every_reference() + { + var cfg = WithProfiles(); + cfg.Policies[0].Profiles = ["public-demo", "internal-default"]; + var impact = ProfileEditing.RemovalImpact(cfg, "public-demo"); + Assert.Contains(impact, l => l.Contains("'demo' loses the grant", StringComparison.Ordinal)); + Assert.Contains(impact, l => l.Contains("Policy 'public' stops listing", StringComparison.Ordinal)); + Assert.Empty(ProfileEditing.RemovalBlockers(cfg, "public-demo")); + + Assert.Null(ProfileEditing.Remove(cfg, "public-demo")); + Assert.DoesNotContain(cfg.Profiles, p => p.Id == "public-demo"); + Assert.Equal(new[] { "internal-default" }, cfg.Applications[0].GrantedProfiles); + Assert.Equal(new[] { "internal-default" }, cfg.Policies[0].Profiles); + Assert.All(cfg.Applications, a => Assert.Empty(ProfileEditing.ApplicationProblems(a, cfg))); + + var unused = WithProfiles(); + unused.Profiles.Add(new WorkloadProfileDto { Id = "spare", Name = "Spare", Baseline = "Phi" }); + Assert.Contains(ProfileEditing.RemovalImpact(unused, "spare"), l => l.Contains("changes no route", StringComparison.Ordinal)); + } + + [Fact] + public void Grants_and_default_profile_stay_consistent() + { + var cfg = WithProfiles(); + var demo = cfg.Applications[0]; + + // The default cannot be revoked; another default first. + Assert.NotNull(ProfileEditing.SetGrant(demo, "internal-default", false, cfg)); + Assert.Contains("internal-default", demo.GrantedProfiles); + Assert.NotNull(ProfileEditing.SetDefault(cfg.Applications[1], "public-demo")); // not granted to batch + Assert.Equal("internal-default", cfg.Applications[1].DefaultProfile); + Assert.Null(ProfileEditing.SetDefault(demo, "public-demo")); + Assert.Null(ProfileEditing.SetGrant(demo, "internal-default", false, cfg)); + Assert.Equal(new[] { "public-demo" }, demo.GrantedProfiles); + + // Unknown profiles are never granted; the built-in one may be. + Assert.NotNull(ProfileEditing.SetGrant(demo, "ghost", true, cfg)); + Assert.Null(ProfileEditing.SetGrant(demo, ProfileEditing.LegacyInternal, true, cfg)); + Assert.Contains(ProfileEditing.LegacyInternal, ProfileEditing.GrantOptions(cfg, demo)); + + // No default ⇒ the built-in legacy-internal (baseline Internal) applies. + Assert.Null(ProfileEditing.SetDefault(demo, "")); + Assert.Null(demo.DefaultProfile); + Assert.Contains(ProfileEditing.LegacyInternal, ProfileEditing.DefaultText(cfg, demo), StringComparison.Ordinal); + Assert.Empty(ProfileEditing.ApplicationProblems(demo, cfg)); + + // What the Host rejects is reported. + demo.DefaultProfile = "internal-default"; + Assert.Contains(ProfileEditing.ApplicationProblems(demo, cfg), p => p.Contains("not granted", StringComparison.Ordinal)); + demo.GrantedProfiles.Add("ghost"); + Assert.Contains(ProfileEditing.ApplicationProblems(demo, cfg), p => p.Contains("does not exist", StringComparison.Ordinal)); + } + + [Fact] + public void Team_and_output_bound_are_validated() + { + var app = WithProfiles().Applications[0]; + Assert.NotNull(ProfileEditing.SetTeam(app, " ")); + Assert.Equal("payments", app.Team); + Assert.Null(ProfileEditing.SetTeam(app, " risk ")); + Assert.Equal("risk", app.Team); + Assert.NotNull(ProfileEditing.SetMaxOutputTokens(app, 0)); + Assert.NotNull(ProfileEditing.SetMaxOutputTokens(app, null)); + Assert.Equal(256, app.MaxOutputTokens); + Assert.Null(ProfileEditing.SetMaxOutputTokens(app, 64)); + Assert.Equal(64, app.MaxOutputTokens); + } + + [Fact] + public void Labels_name_the_baseline_and_the_built_in_profile() + { + var cfg = WithProfiles(); + Assert.Equal("Public demo (baseline Public)", ProfileEditing.Label(cfg, "public-demo")); + Assert.Equal("legacy-internal (built-in, baseline Internal)", ProfileEditing.Label(cfg, ProfileEditing.LegacyInternal)); + Assert.Equal("ghost (not configured)", ProfileEditing.Label(cfg, "ghost")); + Assert.True(ProfileEditing.Exists(cfg, ProfileEditing.LegacyInternal)); + Assert.False(ProfileEditing.IsDeclared(cfg, ProfileEditing.LegacyInternal)); } } diff --git a/tests/Covenant.Tests/ConsolePlaygroundTests.cs b/tests/Covenant.Tests/ConsolePlaygroundTests.cs new file mode 100644 index 0000000..c41a90e --- /dev/null +++ b/tests/Covenant.Tests/ConsolePlaygroundTests.cs @@ -0,0 +1,208 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using Covenant.Core; +using Covenant.Host; +using Xunit; + +namespace Covenant.Tests; + +internal static class Playground +{ + public static string Body(string applicationId, string prompt, string? profile = null, bool stream = false, + string? clientRequestId = null, int? maxTokens = null, string? model = null) + { + var sb = new StringBuilder(); + sb.Append("{\"application_id\":").Append(JsonSerializer.Serialize(applicationId, CovenantJsonContext.Default.String)); + if (profile is not null) sb.Append(",\"profile_id\":").Append(JsonSerializer.Serialize(profile, CovenantJsonContext.Default.String)); + sb.Append(",\"messages\":[{\"role\":\"user\",\"content\":").Append(JsonSerializer.Serialize(prompt, CovenantJsonContext.Default.String)).Append("}]"); + sb.Append(",\"stream\":").Append(stream ? "true" : "false"); + // Review round 2 (B7): client_request_id is required by the console endpoint — generated when the test names none. + clientRequestId ??= "t-" + Guid.NewGuid().ToString("n"); + sb.Append(",\"client_request_id\":\"").Append(clientRequestId).Append('"'); + if (maxTokens is not null) sb.Append(",\"max_tokens\":").Append(maxTokens.Value); + if (model is not null) sb.Append(",\"model\":").Append(JsonSerializer.Serialize(model, CovenantJsonContext.Default.String)); + return sb.Append('}').ToString(); + } + + public static async Task PostAsync(HttpClient client, string json, bool admin = true) + { + using var req = admin + ? CorrelationTestKit.Admin(HttpMethod.Post, "/admin/playground/requests") + : new HttpRequestMessage(HttpMethod.Post, "/admin/playground/requests"); + req.Content = new StringContent(json, Encoding.UTF8, "application/json"); + return await client.SendAsync(req); + } + + /// Adds a disabled application and an application that is not console-testable (validated apply). + public static async Task AddTestApplicationsAsync(HttpClient admin) + { + var (version, cfg, _) = await V2Admin.GetConfigAsync(admin); + var apps = cfg.Applications.ToList(); + apps.Add(new ApplicationConfig { Id = "off-app", Team = "data", Enabled = false, ConsoleTesting = true, GrantedProfiles = ["public-demo"], DefaultProfile = "public-demo" }); + apps.Add(new ApplicationConfig { Id = "batch-app", Team = "data", Enabled = true, ConsoleTesting = false, GrantedProfiles = ["internal-default"], DefaultProfile = "internal-default" }); + return await V2Admin.ApplyAsync(admin, cfg with { Applications = apps }, version, "test applications"); + } +} + +/// ADR-0012 console inference: POST /admin/playground/requests runs the SAME governed pipeline as /v1 with an +/// application resolved server-side; 400 before governance (no audit), governed 403 with audit, 409 on a repeated +/// client_request_id, no application credential anywhere in the browser-facing payloads. +public sealed class ConsolePlaygroundTests : IDisposable +{ + private readonly HybridSeedFactory _factory = new(); + private readonly HttpClient _client; + + public ConsolePlaygroundTests() => _client = _factory.CreateClient(); + + public void Dispose() => _factory.Dispose(); + + [Fact] + public async Task Console_request_runs_the_governed_pipeline_as_the_application_with_honest_operator_attribution() + { + using var resp = await Playground.PostAsync(_client, Playground.Body("demo-app", "Summarize this public announcement.", profile: "public-demo")); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + var text = await resp.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(text); + Assert.Equal(id, doc.RootElement.GetProperty("id").GetString()); // same response contract as /v1 + Assert.Equal(V2.CloudModel, doc.RootElement.GetProperty("model").GetString()); + Assert.Equal("cloud reply", doc.RootElement.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString()); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal("console", e.EntryPoint); + Assert.Equal("shared-admin-token", e.OperatorRef); + Assert.Equal("demo-app", e.ApplicationId); + Assert.Equal("platform", e.Tags.Team); + Assert.Equal("public-demo", e.ProfileId); + Assert.Equal(1, e.ConfigVersion); + Assert.NotNull(e.Trace); + Assert.Single(e.Attempts!); + Assert.True(e.ReservedUsd > 0m); + Assert.Equal(e.Usage.CostUsd, e.SettledUsd); + + // Credentials never cross to the browser: no application key, admin token or provider secret in the payload. + Assert.DoesNotContain("demo-key", text, StringComparison.Ordinal); + Assert.DoesNotContain(CorrelationTestKit.AdminToken, text, StringComparison.Ordinal); + Assert.DoesNotContain(HybridSeedFactory.Secret, text, StringComparison.Ordinal); + } + + [Fact] + public async Task Streaming_console_request_speaks_the_same_SSE_contract() + { + using var resp = await Playground.PostAsync(_client, Playground.Body("demo-app", "an internal question", stream: true)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + Assert.Equal("text/event-stream", resp.Content.Headers.ContentType?.MediaType); + var id = CorrelationTestKit.HeaderId(resp); + var body = await resp.Content.ReadAsStringAsync(); + Assert.Contains("local reply", body, StringComparison.Ordinal); + Assert.Contains($"\"id\":\"{id}\"", body, StringComparison.Ordinal); + Assert.EndsWith("data: [DONE]\n\n", body, StringComparison.Ordinal); + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal("console", e.EntryPoint); + Assert.True(e.Stream); + } + + [Theory] + [InlineData("off-app", null, "disabled")] + [InlineData("batch-app", null, "not enabled for console testing")] + [InlineData("demo-app", "phi-workload", "not granted")] + [InlineData("ghost-app", null, "is not configured")] + public async Task Refused_identities_are_governed_403_with_an_audit_record_and_no_provider_call(string app, string? profile, string reason) + { + await Playground.AddTestApplicationsAsync(_client); + int calls = _factory.Cloud.Calls + _factory.Local.Calls; + using var resp = await Playground.PostAsync(_client, Playground.Body(app, "hello", profile: profile)); + Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal("denied", doc.RootElement.GetProperty("error").GetString()); + Assert.Equal(id, doc.RootElement.GetProperty("request_id").GetString()); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal("auth", e.StoppedAtStage); + Assert.Equal("Governance", e.DenialKind); + Assert.Equal("console", e.EntryPoint); + Assert.Contains(reason, e.Reason, StringComparison.Ordinal); + Assert.Equal(calls, _factory.Cloud.Calls + _factory.Local.Calls); + } + + [Theory] + [InlineData("{not json")] + [InlineData("""{"profile_id":"public-demo","messages":[{"role":"user","content":"x"}]}""")] + [InlineData("""{"application_id":"demo-app","messages":[]}""")] + [InlineData("""{"application_id":"demo-app","messages":[{"role":"wizard","content":"x"}]}""")] + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":null}]}""")] + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}],"max_tokens":0}""")] + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}],"client_request_id":"bad id with spaces"}""")] + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}]}""")] // B7: client_request_id required + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}],"client_request_id":"a.b:c"}""")] // B7: [A-Za-z0-9_-] only + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}],"client_request_id":"0123456789012345678901234567890123456789012345678901234567890123x"}""")] // 65 chars + public async Task Invalid_body_is_400_before_governance_with_no_audit_record(string json) + { + await V2Admin.AuditAsync(_factory.AuditPath, l => l.Count >= 1); // bootstrap event is on disk + using var bad = await Playground.PostAsync(_client, json); + Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); + var badId = CorrelationTestKit.HeaderId(bad); + using var doc = JsonDocument.Parse(await bad.Content.ReadAsStringAsync()); + Assert.Equal("invalid_request", doc.RootElement.GetProperty("error").GetString()); + + // FIFO proof (single-reader sink): a later request's record exists ⇒ nothing was ever enqueued for the 400. + using var ok = await Playground.PostAsync(_client, Playground.Body("demo-app", "after the bad one")); + await CorrelationTestKit.LookupAsync(_client, CorrelationTestKit.HeaderId(ok)); + using var lookup = await _client.SendAsync(CorrelationTestKit.Admin(HttpMethod.Get, $"/admin/requests/{badId}")); + Assert.Equal(HttpStatusCode.NotFound, lookup.StatusCode); + Assert.Equal(1, _factory.Local.Calls); + } + + [Fact] + public async Task Repeated_client_request_id_is_409_with_the_original_request_id_and_never_runs_again() + { + using var first = await Playground.PostAsync(_client, Playground.Body("demo-app", "run once", clientRequestId: "run-7f3a")); + Assert.Equal(HttpStatusCode.OK, first.StatusCode); + var originalId = CorrelationTestKit.HeaderId(first); + int calls = _factory.Local.Calls; + + using var again = await Playground.PostAsync(_client, Playground.Body("demo-app", "run once", clientRequestId: "run-7f3a")); + Assert.Equal(HttpStatusCode.Conflict, again.StatusCode); + using var doc = JsonDocument.Parse(await again.Content.ReadAsStringAsync()); + Assert.Equal("duplicate_submission", doc.RootElement.GetProperty("error").GetString()); + Assert.Equal(originalId, doc.RootElement.GetProperty("request_id").GetString()); + Assert.Equal(calls, _factory.Local.Calls); // a reload never replays inference + } + + [Fact] + public async Task Admin_token_is_required_and_v1_is_unchanged() + { + using var noToken = await Playground.PostAsync(_client, Playground.Body("demo-app", "hi"), admin: false); + Assert.Equal(HttpStatusCode.Unauthorized, noToken.StatusCode); + + // /v1 still requires an application key: the admin token is not one. + using var v1 = new HttpRequestMessage(HttpMethod.Post, "/v1/chat/completions") { Content = CorrelationTestKit.Chat("hi") }; + v1.Headers.Add("X-Covenant-Admin-Token", CorrelationTestKit.AdminToken); + using var v1Resp = await _client.SendAsync(v1); + Assert.Equal(HttpStatusCode.Unauthorized, v1Resp.StatusCode); + + using var app = _factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + using var keyed = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("hi from v1")); + Assert.Equal(HttpStatusCode.OK, keyed.StatusCode); + var e = await CorrelationTestKit.LookupAsync(_client, CorrelationTestKit.HeaderId(keyed)); + Assert.Equal("v1", e.EntryPoint); + Assert.Null(e.OperatorRef); + } + + [Fact] + public void Submissions_window_expires_and_is_bounded() + { + var clock = new SettableClock(DateTimeOffset.Parse("2026-10-17T10:00:00Z")); + var s = new ConsoleSubmissions(clock, TimeSpan.FromMinutes(10), maxEntries: 4); + Assert.True(s.TryClaim("a", "req_1", out _)); + Assert.False(s.TryClaim("a", "req_2", out var original)); + Assert.Equal("req_1", original); + clock.Advance(TimeSpan.FromMinutes(11)); + Assert.True(s.TryClaim("a", "req_3", out _)); // outside the 10-minute window + for (int i = 0; i < 10; i++) Assert.True(s.TryClaim($"k{i}", $"req_k{i}", out _)); + } +} diff --git a/tests/Covenant.Tests/ContractRoundTripTests.cs b/tests/Covenant.Tests/ContractRoundTripTests.cs new file mode 100644 index 0000000..56e2855 --- /dev/null +++ b/tests/Covenant.Tests/ContractRoundTripTests.cs @@ -0,0 +1,1306 @@ +using System.Text.Json; +using Covenant.Core; +using Covenant.Host; +using Xunit; +// Aliased, not imported: Core/Host and the console both have config shapes. Not "Ui": inside namespace +// Covenant.Tests that simple name would bind to the Covenant.Ui namespace before any compilation-unit alias. +using UiModels = Covenant.Ui.Models; + +namespace Covenant.Tests; + +// Proof that a configuration the console saves round-trips through the Host (console v2, ADR-0011): +// Host GET body (ConfigJsonContext.ConfigGetResponse) +// → console reads it (UiJsonContext.ConfigEnvelopeDto) +// → console writes the PUT body (UiJsonContext.ConfigPutRequestDto) +// → Host reads it (ConfigJsonContext.ConfigPutRequest) +// and the configuration that comes out is the one that went in. The UI DTOs are compiled in by link +// (Covenant.Tests.csproj), so a field the console drops or misspells fails here, not in production. +// +// Review round 2 (U1): ONE explicit contract. Every admin DTO the console consumes is pinned Host → UI here: the Host +// object is serialized with the SAME context its endpoint uses (CovenantJsonContext: status, catalog, probe, evidence, +// errors, budgets; ConfigJsonContext: config, validate, versions, rollback, applications, simulate; AuditJsonContext: +// requests page, request, segments, export; TraceJsonContext: trace snapshot/event, playground submission) and read with +// UiJsonContext, then asserted field by field. The console has no alternative-shape fallback parser left. +public sealed class ContractRoundTripTests +{ + private static readonly DateTimeOffset Created = new(2026, 10, 16, 9, 30, 0, TimeSpan.Zero); + + /// A representative v2 configuration that uses every enum value at least once. + private static CovenantConfig Representative(ProviderMode mode) => new() + { + Version = 7, + BaseVersion = 6, + RolledBackFrom = null, + Origin = "console", + CreatedUtc = Created, + ChangeSummary = "round-trip fixture", + Mode = mode, + Connections = + [ + new ConnectionConfig + { + Id = "ollama", DisplayName = "Ollama (in perimeter)", Kind = ProviderKind.Ollama, Boundary = Boundary.Local, + Endpoint = "http://ollama-host:11434/v1", Enabled = true, SecretRef = null, TimeoutSeconds = 90, + Models = + [ + new ModelConfig + { + ModelId = "qwen3:8b", DisplayName = "Qwen 3 8B", ContextTokens = 32768, MaxOutputTokens = 4096, + Price = new PriceConfig { InputPer1M = 0m, OutputPer1M = 0m, Basis = "zero-marginal-local", EffectiveDate = new DateOnly(2026, 10, 1) }, + }, + ], + }, + new ConnectionConfig + { + Id = "vllm", DisplayName = "vLLM", Kind = ProviderKind.OpenAiCompatible, Boundary = Boundary.Local, + Endpoint = "http://vllm-host:8000/v1", Enabled = false, SecretRef = "Secrets:vllm", + Models = [new ModelConfig { ModelId = "llama-3.1-8b", Price = null }], // unknown price stays unknown + }, + new ConnectionConfig + { + Id = "openai", DisplayName = "OpenAI", Kind = ProviderKind.OpenAi, Boundary = Boundary.Cloud, + Endpoint = null, Enabled = true, SecretRef = "Secrets:openai", TimeoutSeconds = 30, + Models = + [ + new ModelConfig + { + ModelId = "gpt-x-mini", DisplayName = "GPT-X mini", + Price = new PriceConfig { InputPer1M = 0.15m, OutputPer1M = 0.60m, Basis = "provider-list", EffectiveDate = new DateOnly(2026, 9, 15) }, + }, + new ModelConfig + { + ModelId = "gpt-x", + Price = new PriceConfig { InputPer1M = 2.50m, OutputPer1M = 10.00m, Basis = "contract" }, + }, + ], + }, + new ConnectionConfig + { + Id = "anthropic", DisplayName = "Anthropic", Kind = ProviderKind.Anthropic, Boundary = Boundary.Cloud, + Enabled = true, SecretRef = "Secrets:anthropic", + Models = + [ + new ModelConfig + { + ModelId = "claude-x", MaxOutputTokens = 8192, + Price = new PriceConfig { InputPer1M = 3.0m, OutputPer1M = 15.0m, Basis = "provider-list" }, + }, + ], + }, + ], + Applications = + [ + new ApplicationConfig + { + Id = "demo-app", Team = "payments", Enabled = true, ConsoleTesting = true, + GrantedProfiles = ["public-tickets", "internal", "customer-pii", "clinical"], DefaultProfile = "internal", MaxOutputTokens = 512, + }, + new ApplicationConfig + { + Id = "prod-app", Team = "risk", Enabled = false, ConsoleTesting = false, GrantedProfiles = ["internal"], + }, + ], + Profiles = + [ + new WorkloadProfileConfig { Id = "public-tickets", Name = "Public tickets", Baseline = DataClassification.Public, Description = "Synthetic public text" }, + new WorkloadProfileConfig { Id = "internal", Name = "Internal", Baseline = DataClassification.Internal }, + new WorkloadProfileConfig { Id = "customer-pii", Name = "Customer PII", Baseline = DataClassification.Pii }, + new WorkloadProfileConfig { Id = "clinical", Name = "Clinical", Baseline = DataClassification.Phi }, + ], + Policies = + [ + new PolicyConfigV2 + { + Id = "public", Name = "Public: economical cloud, local fallback", Enabled = true, + Classifications = [DataClassification.Public], + Profiles = ["public-tickets"], + // Order is precedence: primary first, then approved fallbacks. + Targets = + [ + new PolicyTarget { ConnectionId = "openai", ModelId = "gpt-x-mini" }, + new PolicyTarget { ConnectionId = "anthropic", ModelId = "claude-x", Paused = true }, + new PolicyTarget { ConnectionId = "ollama", ModelId = "qwen3:8b" }, + ], + Strategy = RoutingStrategy.Fixed, + Retry = new RetrySettings { MaxAttempts = 3, DeadlineMs = 45_000, On = ["timeout", "5xx"] }, + Explanation = "Public text may use the approved cloud model.", + }, + new PolicyConfigV2 + { + Id = "internal", Name = "Internal: length heuristic", Enabled = true, Paused = true, + Classifications = [DataClassification.Internal], + Targets = + [ + new PolicyTarget { ConnectionId = "ollama", ModelId = "qwen3:8b" }, + new PolicyTarget { ConnectionId = "openai", ModelId = "gpt-x" }, + ], + Strategy = RoutingStrategy.LengthHeuristic, + ThresholdTokens = 750, + }, + new PolicyConfigV2 + { + Id = "sensitive", Name = "PII/PHI: local only", Enabled = false, + Classifications = [DataClassification.Pii, DataClassification.Phi], + Targets = [new PolicyTarget { ConnectionId = "ollama", ModelId = "qwen3:8b" }, new PolicyTarget { ConnectionId = "vllm", ModelId = "llama-3.1-8b" }], + Retry = new RetrySettings { MaxAttempts = 1, DeadlineMs = 10_000, On = ["connect"] }, + }, + ], + Budgets = + [ + new BudgetConfigV2 { Id = "global", Scope = "global", CapUsd = 250.00m, Period = BudgetPeriod.Monthly, WarnAt = [0.5m, 0.9m], Enforcement = BudgetEnforcement.Hard }, + new BudgetConfigV2 { Id = "team-risk", Scope = "team:risk", CapUsd = 12.5m, Period = BudgetPeriod.Daily, Enforcement = BudgetEnforcement.WarnOnly }, + new BudgetConfigV2 { Id = "app-demo", Scope = "application:demo-app", CapUsd = 1m, Period = BudgetPeriod.None, WarnAt = [], Enforcement = BudgetEnforcement.Hard }, + ], + Settings = new OperationalSettings + { + CacheTtlSeconds = 300, CacheMaxEntries = 2_000, PromptPreviewChars = 80, TraceRetentionMinutes = 15, + RateLimitGlobalPerMinute = 600, RateLimitPerTeamPerMinute = 60, + }, + SavingsBaseline = new ModelRef("openai", "gpt-x"), + }; + + private static string HostGetBody(CovenantConfig cfg) => JsonSerializer.Serialize(new ConfigGetResponse + { + Version = cfg.Version, + Etag = "\"v" + cfg.Version + "\"", + Config = cfg, + Secrets = new Dictionary + { + ["Secrets:openai"] = new() { Available = true }, + ["Secrets:anthropic"] = new() { Available = false }, + ["Secrets:vllm"] = new() { Available = false }, + }, + AllowList = ["api.openai.com:443", "ollama-host:11434"], + }, ConfigJsonContext.Default.ConfigGetResponse); + + /// GET body → console envelope → console PUT body → Host PUT request. + private static (string GetBody, UiModels.ConfigEnvelopeDto Envelope, string PutBody, ConfigPutRequest Put) RoundTrip(CovenantConfig cfg) + { + var getBody = HostGetBody(cfg); + var envelope = JsonSerializer.Deserialize(getBody, UiModels.UiJsonContext.Default.ConfigEnvelopeDto); + Assert.NotNull(envelope); + Assert.NotNull(envelope!.Config); + + var putBody = JsonSerializer.Serialize( + new UiModels.ConfigPutRequestDto { Config = envelope.Config, ChangeSummary = "saved by the console" }, + UiModels.UiJsonContext.Default.ConfigPutRequestDto); + var put = JsonSerializer.Deserialize(putBody, ConfigJsonContext.Default.ConfigPutRequest); + Assert.NotNull(put); + Assert.NotNull(put!.Config); + return (getBody, envelope, putBody, put); + } + + [Theory] + [InlineData(ProviderMode.LocalOnly, "local-only")] + [InlineData(ProviderMode.Hybrid, "hybrid")] + [InlineData(ProviderMode.LegacyCloud, "legacy-cloud")] + public void Console_saved_config_round_trips_through_the_host_unchanged(ProviderMode mode, string wireMode) + { + var original = Representative(mode); + var (_, envelope, putBody, put) = RoundTrip(original); + + // The console saw the wire spelling verbatim. + Assert.Equal(wireMode, envelope.Config!.Mode); + Assert.Equal(wireMode, Wire(putBody).GetProperty("config").GetProperty("mode").GetString()); + Assert.Equal("saved by the console", put.ChangeSummary); + + // Deep equality: the Host's own serialization of what came back is byte-identical to what went out. + // (Records with IReadOnlyList members compare lists by reference, so compare canonical JSON instead.) + var before = JsonSerializer.Serialize(original, ConfigJsonContext.Default.CovenantConfig); + var after = JsonSerializer.Serialize(put.Config!, ConfigJsonContext.Default.CovenantConfig); + Assert.Equal(before, after); + + AssertMeaningfulFieldsEqual(original, put.Config!); + } + + private static void AssertMeaningfulFieldsEqual(CovenantConfig a, CovenantConfig b) + { + Assert.Equal(a.Version, b.Version); + Assert.Equal(a.BaseVersion, b.BaseVersion); + Assert.Equal(a.Origin, b.Origin); + Assert.Equal(a.CreatedUtc, b.CreatedUtc); + Assert.Equal(a.ChangeSummary, b.ChangeSummary); + Assert.Equal(a.Mode, b.Mode); + Assert.Equal(a.SavingsBaseline, b.SavingsBaseline); + + Assert.Equal(a.Connections.Select(c => c.Id), b.Connections.Select(c => c.Id)); + foreach (var (x, y) in a.Connections.Zip(b.Connections)) + { + Assert.Equal(x.Kind, y.Kind); + Assert.Equal(x.Boundary, y.Boundary); + Assert.Equal(x.DisplayName, y.DisplayName); + Assert.Equal(x.Endpoint, y.Endpoint); + Assert.Equal(x.Enabled, y.Enabled); + Assert.Equal(x.SecretRef, y.SecretRef); + Assert.Equal(x.TimeoutSeconds, y.TimeoutSeconds); + Assert.Equal(x.Models.Select(m => m.ModelId), y.Models.Select(m => m.ModelId)); + foreach (var (mx, my) in x.Models.Zip(y.Models)) + { + Assert.Equal(mx.DisplayName, my.DisplayName); + Assert.Equal(mx.ContextTokens, my.ContextTokens); + Assert.Equal(mx.MaxOutputTokens, my.MaxOutputTokens); + Assert.Equal(mx.Price, my.Price); // PriceConfig has only scalar members: record equality is deep + } + } + + Assert.Equal(a.Applications.Count, b.Applications.Count); + foreach (var (x, y) in a.Applications.Zip(b.Applications)) + { + Assert.Equal(x.Id, y.Id); + Assert.Equal(x.Team, y.Team); + Assert.Equal(x.Enabled, y.Enabled); + Assert.Equal(x.ConsoleTesting, y.ConsoleTesting); + Assert.Equal(x.GrantedProfiles, y.GrantedProfiles); + Assert.Equal(x.DefaultProfile, y.DefaultProfile); + Assert.Equal(x.MaxOutputTokens, y.MaxOutputTokens); + } + + Assert.Equal(a.Profiles, b.Profiles); // scalar-only records: deep + + Assert.Equal(a.Policies.Count, b.Policies.Count); + foreach (var (x, y) in a.Policies.Zip(b.Policies)) + { + Assert.Equal(x.Id, y.Id); + Assert.Equal(x.Name, y.Name); + Assert.Equal(x.Enabled, y.Enabled); + Assert.Equal(x.Paused, y.Paused); + Assert.Equal(x.Classifications, y.Classifications); + Assert.Equal(x.Profiles, y.Profiles); + Assert.Equal(x.Targets, y.Targets); // order, connection, model and paused flag + Assert.Equal(x.Strategy, y.Strategy); + Assert.Equal(x.ThresholdTokens, y.ThresholdTokens); + Assert.Equal(x.Retry.MaxAttempts, y.Retry.MaxAttempts); + Assert.Equal(x.Retry.DeadlineMs, y.Retry.DeadlineMs); + Assert.Equal(x.Retry.On, y.Retry.On); + Assert.Equal(x.Explanation, y.Explanation); + } + + Assert.Equal(a.Budgets.Count, b.Budgets.Count); + foreach (var (x, y) in a.Budgets.Zip(b.Budgets)) + { + Assert.Equal(x.Id, y.Id); + Assert.Equal(x.Scope, y.Scope); + Assert.Equal(x.CapUsd, y.CapUsd); + Assert.Equal(x.Period, y.Period); + Assert.Equal(x.WarnAt, y.WarnAt); + Assert.Equal(x.Enforcement, y.Enforcement); + } + + Assert.Equal(a.Settings, b.Settings); + } + + [Fact] + public void Host_wire_spellings_are_the_contract_vocabulary_and_the_console_reads_them_verbatim() + { + var (getBody, envelope, putBody, _) = RoundTrip(Representative(ProviderMode.Hybrid)); + + foreach (var body in new[] { getBody, putBody }) + { + var cfg = Wire(body).GetProperty("config"); + Assert.Equal("hybrid", cfg.GetProperty("mode").GetString()); + + var conns = cfg.GetProperty("connections").EnumerateArray().ToList(); + Assert.Equal(new[] { "Ollama", "OpenAiCompatible", "OpenAi", "Anthropic" }, conns.Select(c => c.GetProperty("kind").GetString())); + Assert.Equal(new[] { "Local", "Local", "Cloud", "Cloud" }, conns.Select(c => c.GetProperty("boundary").GetString())); + + var price = conns[2].GetProperty("models")[0].GetProperty("price"); + Assert.Equal(0.15m, price.GetProperty("input_per_1m").GetDecimal()); + Assert.Equal(0.60m, price.GetProperty("output_per_1m").GetDecimal()); + Assert.False(price.TryGetProperty("input_per1_m", out _)); + + var policies = cfg.GetProperty("policies").EnumerateArray().ToList(); + Assert.Equal(new[] { "fixed", "length-heuristic", "fixed" }, policies.Select(p => p.GetProperty("strategy").GetString())); + Assert.Equal(new[] { "Public", "Internal", "Pii", "Phi" }, + policies.SelectMany(p => p.GetProperty("classifications").EnumerateArray().Select(c => c.GetString()))); + Assert.Equal(new[] { "openai/gpt-x-mini", "anthropic/claude-x", "ollama/qwen3:8b" }, + policies[0].GetProperty("targets").EnumerateArray().Select(t => t.GetProperty("connection_id").GetString() + "/" + t.GetProperty("model_id").GetString())); + + Assert.Equal(new[] { "Public", "Internal", "Pii", "Phi" }, + cfg.GetProperty("profiles").EnumerateArray().Select(p => p.GetProperty("baseline").GetString())); + + var budgets = cfg.GetProperty("budgets").EnumerateArray().ToList(); + Assert.Equal(new[] { "monthly", "daily", "none" }, budgets.Select(b => b.GetProperty("period").GetString())); + Assert.Equal(new[] { "hard", "warn-only", "hard" }, budgets.Select(b => b.GetProperty("enforcement").GetString())); + } + + // The console DTOs hold the same strings (enums travel as strings; nothing re-spelled client-side). + var dto = envelope.Config!; + Assert.Equal(new[] { "Ollama", "OpenAiCompatible", "OpenAi", "Anthropic" }, dto.Connections.Select(x => x.Kind)); + Assert.Equal(new[] { "Local", "Local", "Cloud", "Cloud" }, dto.Connections.Select(x => x.Boundary)); + Assert.Equal(new[] { "fixed", "length-heuristic", "fixed" }, dto.Policies.Select(p => p.Strategy)); + Assert.Equal(new[] { "monthly", "daily", "none" }, dto.Budgets.Select(b => b.Period)); + Assert.Equal(new[] { "hard", "warn-only", "hard" }, dto.Budgets.Select(b => b.Enforcement)); + Assert.Equal(new[] { "Public", "Internal", "Pii", "Phi" }, dto.Profiles.Select(p => p.Baseline)); + Assert.Equal(new[] { "Pii", "Phi" }, dto.Policies[2].Classifications); + Assert.Equal(0.15m, dto.Connections[2].Models[0].Price!.InputPer1M); + Assert.Equal(0.60m, dto.Connections[2].Models[0].Price!.OutputPer1M); + Assert.Equal("2026-09-15", dto.Connections[2].Models[0].Price!.EffectiveDate); + Assert.Null(dto.Connections[1].Models[0].Price); // unknown price is not $0 + Assert.Equal(new[] { false, true, false }, dto.Policies[0].Targets.Select(t => t.Paused)); + Assert.Equal(new[] { false, true, false }, dto.Policies.Select(p => p.Paused)); + Assert.Equal(3, dto.Policies[0].Retry!.MaxAttempts); + Assert.Equal(45_000, dto.Policies[0].Retry!.DeadlineMs); + Assert.Equal(new[] { "timeout", "5xx" }, dto.Policies[0].Retry!.On); + + // Envelope metadata survives too. + Assert.Equal(7, envelope.Version); + Assert.Equal("\"v7\"", envelope.Etag); + Assert.True(envelope.Secrets!["Secrets:openai"].Available); + Assert.False(envelope.Secrets!["Secrets:anthropic"].Available); + Assert.Equal(new[] { "api.openai.com:443", "ollama-host:11434" }, envelope.AllowList); + } + + [Fact] + public void Console_put_body_never_carries_an_allow_sensitive_cloud_switch() + { + // PII/PHI never route to cloud destinations: there is no console-side override to send. + var (_, _, putBody, _) = RoundTrip(Representative(ProviderMode.Hybrid)); + foreach (var p in Wire(putBody).GetProperty("config").GetProperty("policies").EnumerateArray()) + Assert.False(p.TryGetProperty("allow_sensitive_cloud", out _)); + } + + // ---- T08 editors: every other DTO the console reads or writes on the config/simulate/catalog/archive paths ---- + + [Fact] + public void Validate_request_and_response_round_trip_with_impact_and_field_paths() + { + var cfg = Representative(ProviderMode.Hybrid); + var envelope = RoundTrip(cfg).Envelope; + + // console → Host: POST /admin/config/validate + var reqBody = JsonSerializer.Serialize(new UiModels.ConfigValidateRequestDto { BaseVersion = 7, Config = envelope.Config }, + UiModels.UiJsonContext.Default.ConfigValidateRequestDto); + var hostReq = JsonSerializer.Deserialize(reqBody, ConfigJsonContext.Default.ConfigValidateRequest); + Assert.Equal(7, hostReq!.BaseVersion); + Assert.Equal(JsonSerializer.Serialize(cfg, ConfigJsonContext.Default.CovenantConfig), + JsonSerializer.Serialize(hostReq.Config!, ConfigJsonContext.Default.CovenantConfig)); + + // Host → console: the validation result + var respBody = JsonSerializer.Serialize(new ConfigValidateResponse + { + Valid = false, + ActiveVersion = 7, + Errors = [new ConfigIssueView { Path = "connections[2].secret_ref", Code = "secret_unavailable", Message = "secret not set" }], + Warnings = [new ConfigIssueView { Path = "base_version", Code = "stale_base_version", Message = "edited from v6" }], + Impact = new ImpactView + { + Classifications = [new ImpactRowView { Classification = "Public", Profile = "public-tickets", Before = "openai/gpt-x-mini", After = "refused: no eligible target", Changed = true }], + ApplicationsAffected = ["demo-app"], + UnavailableDestinations = ["openai/gpt-x-mini"], + PricingGaps = ["vllm/llama-3.1-8b"], + NewlyRefused = ["Public/public-tickets"], + }, + }, ConfigJsonContext.Default.ConfigValidateResponse); + var ui = JsonSerializer.Deserialize(respBody, UiModels.UiJsonContext.Default.ConfigValidationResultDto)!; + Assert.False(ui.Valid); + Assert.Equal(7, ui.ActiveVersion); + Assert.Equal("connections[2].secret_ref", Assert.Single(ui.Errors).Path); + Assert.Equal("secret_unavailable", ui.Errors[0].Code); + Assert.Equal("stale_base_version", Assert.Single(ui.Warnings).Code); + var row = Assert.Single(ui.Impact!.Classifications); + Assert.True(row.Changed); + Assert.Equal("refused: no eligible target", row.After); + Assert.Equal(new[] { "demo-app" }, ui.Impact.ApplicationsAffected); + Assert.Equal(new[] { "openai/gpt-x-mini" }, ui.Impact.UnavailableDestinations); + Assert.Equal(new[] { "vllm/llama-3.1-8b" }, ui.Impact.PricingGaps); + Assert.Equal(new[] { "Public/public-tickets" }, ui.Impact.NewlyRefused); + Assert.Single(Covenant.Ui.Logic.ImpactText.ChangedRoutes(ui.Impact)); + } + + [Fact] + public void Host_write_answers_map_onto_console_outcomes() + { + string Error(int? active, bool withIssues) => JsonSerializer.Serialize(new ConfigErrorResponse + { + Error = withIssues ? "invalid_configuration" : "stale", + Reason = "x", + ActiveVersion = active, + Errors = withIssues ? [new ConfigIssueView { Path = "policies[0].targets[1]", Code = "sensitive_cloud_target", Message = "no" }] : null, + Warnings = withIssues ? [] : null, + }, ConfigJsonContext.Default.ConfigErrorResponse); + + var stale = Covenant.Ui.Logic.EditOutcomes.FromResponse(412, Error(8, withIssues: false)); + Assert.Equal(Covenant.Ui.Logic.EditOutcomeKind.Stale, stale.Kind); + Assert.Equal(8, stale.Version); + + var invalid = Covenant.Ui.Logic.EditOutcomes.FromResponse(422, Error(7, withIssues: true)); + Assert.Equal(Covenant.Ui.Logic.EditOutcomeKind.Invalid, invalid.Kind); + Assert.Equal("policies[0].targets[1]", Assert.Single(invalid.Errors!).Path); + + var ok = Covenant.Ui.Logic.EditOutcomes.FromResponse(200, + JsonSerializer.Serialize(new ConfigPutResponse { Version = 9, Etag = "\"v9\"" }, ConfigJsonContext.Default.ConfigPutResponse)); + Assert.True(ok.Succeeded); + Assert.Equal(9, ok.Version); + + var err = JsonSerializer.Deserialize(Error(8, withIssues: false), UiModels.UiJsonContext.Default.ConfigErrorResponseDto)!; + Assert.Equal("stale", err.Error); + Assert.Equal(8, err.ActiveVersion); + } + + [Fact] + public void Version_history_and_rollback_request_round_trip() + { + var history = JsonSerializer.Serialize(new List + { + new() { Version = 8, CreatedUtc = Created, Origin = "rollback", BaseVersion = 7, RolledBackFrom = 3, ChangeSummary = "rollback to v3", Active = true }, + new() { Version = 7, CreatedUtc = Created.AddMinutes(-5), Origin = "console", BaseVersion = 6, Active = false }, + }, ConfigJsonContext.Default.ListConfigVersionSummary); + var ui = JsonSerializer.Deserialize(history, UiModels.UiJsonContext.Default.ListConfigVersionDto)!; + Assert.Equal(new[] { 8, 7 }, ui.Select(v => v.Version)); + Assert.True(ui[0].Active); + Assert.Equal(3, ui[0].RolledBackFrom); + Assert.Equal("rollback", ui[0].Origin); + Assert.Equal(Created, ui[0].CreatedUtc); + Assert.Null(ui[1].RolledBackFrom); + + var body = JsonSerializer.Serialize(new UiModels.ConfigRollbackRequestDto { TargetVersion = 3, ExpectedActiveVersion = 8 }, + UiModels.UiJsonContext.Default.ConfigRollbackRequestDto); + var host = JsonSerializer.Deserialize(body, ConfigJsonContext.Default.ConfigRollbackRequest)!; + Assert.Equal(3, host.TargetVersion); + Assert.Equal(8, host.ExpectedActiveVersion); + } + + [Fact] + public void Simulator_request_with_a_draft_candidate_and_dry_run_response_round_trip() + { + var cfg = Representative(ProviderMode.Hybrid); + var envelope = RoundTrip(cfg).Envelope; + var body = JsonSerializer.Serialize(new UiModels.SimulateRequestDto + { + ApplicationId = "demo-app", ProfileId = "public-tickets", Prompt = "Priority: low", Model = "openai/gpt-x-mini", Config = envelope.Config, + }, UiModels.UiJsonContext.Default.SimulateRequestDto); + var host = JsonSerializer.Deserialize(body, ConfigJsonContext.Default.SimulateRequest)!; + Assert.Equal("demo-app", host.ApplicationId); + Assert.Equal("public-tickets", host.ProfileId); + Assert.Equal("openai/gpt-x-mini", host.Model); + Assert.Equal(JsonSerializer.Serialize(cfg, ConfigJsonContext.Default.CovenantConfig), + JsonSerializer.Serialize(host.Config!, ConfigJsonContext.Default.CovenantConfig)); + + // Without a draft the candidate is omitted (the Host simulates the active version). + var noDraft = JsonSerializer.Serialize(new UiModels.SimulateRequestDto { ApplicationId = "demo-app", Prompt = "x" }, UiModels.UiJsonContext.Default.SimulateRequestDto); + Assert.False(Wire(noDraft).TryGetProperty("config", out _)); + Assert.Null(JsonSerializer.Deserialize(noDraft, ConfigJsonContext.Default.SimulateRequest)!.Config); + + var resp = JsonSerializer.Serialize(new SimulateResponse + { + DryRun = true, ConfigVersion = 7, ApplicationId = "demo-app", Profile = "public-tickets", + Classification = "Pii", Baseline = "Public", DetectedSignal = "US SSN pattern", PolicyId = "sensitive", + Eligible = + [ + new SimulatedTarget { Target = "ollama/qwen3:8b", Boundary = "Local" }, + new SimulatedTarget { Target = "openai/gpt-x-mini", Boundary = "Cloud", ExcludedReason = "cloud destination for PII" }, + ], + Decision = "route", Primary = "ollama/qwen3:8b", Fallbacks = [], Reason = "allowed", Explanation = "PII → ollama/qwen3:8b", + }, ConfigJsonContext.Default.SimulateResponse); + var ui = JsonSerializer.Deserialize(resp, UiModels.UiJsonContext.Default.SimulateResponseDto)!; + Assert.True(ui.DryRun); + Assert.Equal(7, ui.ConfigVersion); + Assert.Equal("Pii", ui.Classification); + Assert.Equal("Public", ui.Baseline); + Assert.Equal("US SSN pattern", ui.DetectedSignal); + Assert.Equal("route", ui.Decision); + Assert.Equal("ollama/qwen3:8b", ui.Primary); + Assert.Equal(new[] { "Local", "Cloud" }, ui.Eligible.Select(e => e.Boundary)); + Assert.Null(ui.Eligible[0].ExcludedReason); + Assert.Equal("cloud destination for PII", ui.Eligible[1].ExcludedReason); + Assert.Equal("PII → ollama/qwen3:8b", ui.Explanation); + } + + [Fact] + public void Catalog_connections_carry_health_registration_and_allow_listing_to_the_console() + { + var ok = new HealthView { State = "ok", LastSuccessUtc = Created }; + var body = JsonSerializer.Serialize(new CatalogReport + { + Mode = "hybrid", + Models = [new CatalogModel { Adapter = "ollama", ModelId = "qwen3:8b", Classifications = ["Internal"], Registered = true, PriceBasis = "zero", Health = ok, ConnectionId = "ollama", Boundary = "Local", Key = "ollama:qwen3:8b" }], + Local = new LocalConfigView + { + Configured = true, Endpoint = "http://ollama-host:11434/v1", ModelId = "qwen3:8b", Registered = true, + EndpointHealth = new HealthView { State = "failed", LastFailureUtc = Created, LastError = "refused" }, + ConnectionId = "ollama", Health = new HealthView { State = "ok", LastSuccessUtc = Created.AddMinutes(1) }, + }, + ProbeAllowList = ["ollama-host:11434"], + ConfigVersion = 7, + EgressAllowList = ["api.openai.com:443", "ollama-host:11434"], + Connections = + [ + new CatalogConnection + { + Id = "openai", DisplayName = "OpenAI", Kind = "OpenAi", Boundary = "Cloud", Enabled = true, Endpoint = null, EndpointAllowListed = true, + SecretRef = "Secrets:openai", SecretAvailable = false, + Models = [new CatalogConnectionModel { Key = "openai:gpt-x-mini", ModelId = "gpt-x-mini", Registered = false, PriceBasis = "configured", InPer1M = 0.15m, OutPer1M = 0.60m, Health = new HealthView { State = "unknown" } }], + }, + ], + }, CovenantJsonContext.Default.CatalogReport); + + var ui = JsonSerializer.Deserialize(body, UiModels.UiJsonContext.Default.CatalogResponse)!; + Assert.Equal(7, ui.ConfigVersion); + Assert.Equal(new[] { "api.openai.com:443", "ollama-host:11434" }, ui.EgressAllowList); + Assert.Equal("Local", ui.Models[0].Boundary); + Assert.Equal("ollama", ui.Models[0].ConnectionId); + Assert.Equal("ollama:qwen3:8b", ui.Models[0].Key); + Assert.Equal("hybrid", ui.Mode); + Assert.Equal(new[] { "ollama-host:11434" }, ui.ProbeAllowList); + var m0 = Assert.Single(ui.Models); + Assert.Equal("ollama", m0.Adapter); + Assert.Equal("qwen3:8b", m0.ModelId); + Assert.Equal(new[] { "Internal" }, m0.Classifications); + Assert.True(m0.Registered); + Assert.Equal("zero", m0.PriceBasis); + Assert.Equal("ok", m0.Health!.State); + Assert.Equal(Created, m0.Health!.LastSuccessUtc); + var local = ui.Local!; + Assert.True(local.Configured); + Assert.True(local.Registered); + Assert.Equal("http://ollama-host:11434/v1", local.Endpoint); + Assert.Equal("qwen3:8b", local.ModelId); + Assert.Equal("failed", local.EndpointHealth.State); + Assert.Equal("refused", local.EndpointHealth.LastError); + Assert.Equal(Created, local.EndpointHealth.LastFailureUtc); + // Review round 2 (B11): the CURRENT runtime connection and its health. + Assert.Equal("ollama", local.ConnectionId); + Assert.Equal("ok", local.Health!.State); + Assert.Equal(Created.AddMinutes(1), local.Health!.LastSuccessUtc); + Assert.Equal(Covenant.Ui.Logic.LocalRouteState.Ready, Covenant.Ui.Logic.LocalHealth.Derive(ui, null).State); + var c = Assert.Single(ui.Connections!); + Assert.Equal("openai", c.Id); + Assert.Equal("OpenAI", c.DisplayName); + Assert.True(c.Enabled); + Assert.Null(c.Endpoint); + Assert.Equal("OpenAi", c.Kind); + Assert.Equal("Cloud", c.Boundary); + Assert.True(c.EndpointAllowListed); + Assert.False(c.SecretAvailable); + Assert.Equal("Secrets:openai", c.SecretRef); + var m = Assert.Single(c.Models); + Assert.Equal("openai:gpt-x-mini", m.Key); + Assert.Equal("gpt-x-mini", m.ModelId); + Assert.False(m.Registered); + Assert.Equal("configured", m.PriceBasis); + Assert.Equal(0.15m, m.InPer1M); + Assert.Equal(0.60m, m.OutPer1M); + Assert.Equal("unknown", m.Health!.State); + } + + // T04/T06 read paths. These pin the backend's budget-ledger and audit-archive views (implemented concurrently with + // the console; see docs/console-v2-progress.md "T08 UI" — integration pending until those land and pass). + + [Fact] + public void Budget_state_and_contributions_reach_the_console() + { + var states = JsonSerializer.Serialize(new List + { + new() + { + Id = "global", Scope = "global", Period = "monthly", PeriodId = "2026-10", PeriodStartUtc = Created, PeriodEndUtc = Created.AddDays(16), + CapUsd = 25m, SpentUsd = 0.000184m, ReservedUsd = 0.0021m, RemainingUsd = 24.997716m, WarnAt = [0.8m, 0.95m], Warning = "none", Enforcement = "hard", + }, + }, CovenantJsonContext.Default.ListBudgetStateView); + var ui = Assert.Single(JsonSerializer.Deserialize(states, UiModels.UiJsonContext.Default.ListBudgetStateDto)!); + Assert.Equal("global", ui.Id); + Assert.Equal("global", ui.Scope); + Assert.Equal("monthly", ui.Period); + Assert.Equal(25m, ui.CapUsd); + Assert.Equal(24.997716m, ui.RemainingUsd); + Assert.Equal("none", ui.Warning); + Assert.Equal("hard", ui.Enforcement); + Assert.Equal(Created.AddDays(16), ui.PeriodEndUtc); + Assert.Equal("2026-10", ui.PeriodId); + Assert.Equal(0.000184m, ui.SpentUsd); + Assert.Equal(0.0021m, ui.ReservedUsd); + Assert.Equal(Created, ui.PeriodStartUtc); + Assert.Equal(new[] { 0.8m, 0.95m }, ui.WarnAt); + Assert.Equal("$0.000184", Covenant.Ui.Logic.Money.Usd(ui.SpentUsd)); + + var contributions = JsonSerializer.Serialize(new BudgetRequestsView + { + BudgetId = "global", Scope = "global", PeriodId = "2026-10", + Items = + [ + new BudgetContributionView { RequestId = "req_a", AttemptId = "att_2", Kind = "settle", AmountUsd = 0.000184m, TsUtc = Created, Overrun = true }, + new BudgetContributionView { RequestId = "req_b", AttemptId = "att_1", Kind = "settle-recovered", AmountUsd = 0.0021m, TsUtc = Created }, + ], + }, CovenantJsonContext.Default.BudgetRequestsView); + var page = JsonSerializer.Deserialize(contributions, UiModels.UiJsonContext.Default.BudgetRequestsDto)!; + Assert.Equal("global", page.BudgetId); + Assert.Equal("global", page.Scope); + Assert.Equal("2026-10", page.PeriodId); + var rows = page.Items; + Assert.Equal(new[] { "req_a", "req_b" }, rows.Select(r => r.RequestId)); + Assert.Equal(0.000184m, rows[0].AmountUsd); + Assert.Equal("att_2", rows[0].AttemptId); + Assert.Equal("settle", rows[0].Kind); + Assert.True(rows[0].Overrun); + Assert.False(rows[1].Overrun); + Assert.Equal("settle-recovered", rows[1].Kind); + Assert.Equal(Created, rows[0].TsUtc); + } + + [Fact] + public void Audit_segments_and_cursor_pages_reach_the_console() + { + var segs = JsonSerializer.Serialize(new List + { + new() { Id = "current", Label = "Current", Current = true, Entries = 12, ChainValid = true, FirstUtc = Created }, + new() { Id = "a-0123456789abcdef", Label = "Archived 2026-10-01 09:00", Current = false, Entries = 40, Events = 2, ChainValid = true, ArchivedUtc = Created.AddDays(-15) }, + }, AuditJsonContext.Default.ListSegmentView); + var ui = JsonSerializer.Deserialize(segs, UiModels.UiJsonContext.Default.ListAuditSegmentDto)!; + Assert.True(Covenant.Ui.Logic.SegmentScope.IsCurrent(ui[0])); + Assert.False(Covenant.Ui.Logic.SegmentScope.IsCurrent(ui[1])); + Assert.Equal("current", ui[0].Id); + Assert.Equal("Current", ui[0].Label); + Assert.Equal(12, ui[0].Entries); + Assert.Equal(Created, ui[0].FirstUtc); + Assert.True(ui[0].ChainValid); + Assert.Equal("a-0123456789abcdef", ui[1].Id); + Assert.Equal("Archived 2026-10-01 09:00", ui[1].Label); + Assert.Equal(40, ui[1].Entries); + Assert.Equal(2, ui[1].Events); + Assert.Equal(Created.AddDays(-15), ui[1].ArchivedUtc); + + var cursor = AuditSegments.Cursor("a-0123456789abcdef", "0123456789abcdef", 40); + var page = JsonSerializer.Serialize(new RequestsPage + { + Segment = new SegmentInfo + { + Path = "/var/covenant/audit.jsonl", Entries = 80, Events = 3, ChainValid = true, FirstUtc = Created, LastUtc = Created.AddHours(1), + Id = "a-0123456789abcdef", Label = "Archived 2026-10-01 09:00", IsCurrent = false, + }, + Items = [], + NextCursor = cursor, + }, AuditJsonContext.Default.RequestsPage); + var uiPage = JsonSerializer.Deserialize(page, UiModels.UiJsonContext.Default.RequestsResponse)!; + // The segment descriptor — never inferred from a row. + Assert.Equal("a-0123456789abcdef", uiPage.Segment.Id); + Assert.Equal("Archived 2026-10-01 09:00", uiPage.Segment.Label); + Assert.False(uiPage.Segment.IsCurrent); + Assert.Equal("/var/covenant/audit.jsonl", uiPage.Segment.Path); + Assert.Equal(80, uiPage.Segment.Entries); + Assert.Equal(3, uiPage.Segment.Events); + Assert.True(uiPage.Segment.ChainValid); + Assert.Equal(Created, uiPage.Segment.FirstUtc); + Assert.Equal(Created.AddHours(1), uiPage.Segment.LastUtc); + Assert.Equal(cursor, uiPage.NextCursor); // opaque: passed back verbatim + Assert.Equal("Archived segment Archived 2026-10-01 09:00 · read-only", Covenant.Ui.Logic.SegmentScope.Label(uiPage.Segment)); + + var paging = new Covenant.Ui.Logic.RequestPaging(); + paging.Reset("a-0123456789abcdef"); + Assert.Equal(Covenant.Ui.Logic.PageResult.Accepted, paging.ApplyPage(uiPage, older: false)); + + // is_current is ALWAYS on the wire, even when false. + Assert.False(Wire(page).GetProperty("segment").GetProperty("is_current").GetBoolean()); + var last = JsonSerializer.Serialize(new RequestsPage + { + Segment = new SegmentInfo { Path = "/var/covenant/audit.jsonl", Entries = 0, ChainValid = true, Id = "current", Label = "Current segment", IsCurrent = true }, + Items = [], + NextCursor = null, + }, AuditJsonContext.Default.RequestsPage); + var uiLast = JsonSerializer.Deserialize(last, UiModels.UiJsonContext.Default.RequestsResponse)!; + Assert.True(uiLast.Segment.IsCurrent); + Assert.Null(uiLast.NextCursor); + } + + // ---- Review round 2 (U1): the remaining Host → UI contracts, field by field ---- + + private static AuditEntry RoundTwoRecord() => new( + Id: "req_0123456789abcdef0123456789abcdef", + TimestampUtc: Created, + Principal: "console:demo-app", + Tags: new AttributionTags("payments", "console", "playground"), + Classification: DataClassification.Pii, + Effect: PolicyEffect.Allow, + Reason: "allowed", + ServedByModel: "ollama/qwen3:8b", + Usage: new Usage(84, 10, 0.0021m), + DurationMs: 812.5, + PromptChars: 120, + PromptSha256: new string('a', 64), + Signal: "US SSN pattern", + PromptPreview: null, + CacheHit: false, + SchemaVersion: 2, + CorrelationId: "req_0123456789abcdef0123456789abcdef", + ClassificationEvaluated: true, + DenialKind: "None", + StoppedAtStage: null, + SelectedModel: "openai/gpt-x-mini", + AttemptedModel: "ollama/qwen3:8b", + Stream: true, + UsageReported: true, + CostBasis: "mixed", + EventType: "request", + ConfigVersion: 13, + EntryPoint: "console", + OperatorRef: "shared-admin-token", + ApplicationId: "demo-app", + ProfileId: "public-tickets", + BaselineClassification: DataClassification.Public, + Attempts: + [ + new AuditAttempt("att_1", "openai", "gpt-x-mini", "failed", "incomplete_stream", 1500.25, 0.0021m, "estimated_failed_call", + ReservedUsd: 0.0021m, Overrun: false, EffectiveMaxOutputTokens: 256, Truncated: null), + new AuditAttempt("att_2", "ollama", "qwen3:8b", "served", null, 640.5, 0m, "zero_priced", + ReservedUsd: 0m, Overrun: false, EffectiveMaxOutputTokens: 64, Truncated: true), + ], + Trace: + [ + new AuditTraceStep("auth", "passed", 0.4), + new AuditTraceStep("provider", "failed", 1500.25, "att_1", "incomplete_stream"), + new AuditTraceStep("provider", "passed", 640.5, "att_2"), + ], + ReservedUsd: 0.0021m, + SettledUsd: 0.0021m, + RequestedMaxOutputTokens: 256, + EffectiveMaxOutputTokens: 64, + PartialOutputChars: null, + ServedConnectionId: "ollama"); + + private static void AssertRecord(AuditEntry h, UiModels.AuditEntryView u) + { + Assert.Equal(h.Id, u.Id); + Assert.Equal(h.TimestampUtc, u.TimestampUtc); + Assert.Equal(h.Principal, u.Principal); + Assert.Equal(h.Tags.Team, u.Tags.Team); + Assert.Equal(h.Tags.Workflow, u.Tags.Workflow); + Assert.Equal(h.Tags.UseCase, u.Tags.UseCase); + Assert.Equal("Pii", u.Classification); + Assert.Equal("Allow", u.Effect); + Assert.Equal(h.Reason, u.Reason); + Assert.Equal(h.ServedByModel, u.ServedByModel); + Assert.Equal(h.Usage.InputTokens, u.Usage.InputTokens); + Assert.Equal(h.Usage.OutputTokens, u.Usage.OutputTokens); + Assert.Equal(h.Usage.TotalTokens, u.Usage.TotalTokens); + Assert.Equal(h.Usage.CostUsd, u.Usage.CostUsd); + Assert.Equal(h.DurationMs, u.DurationMs); + Assert.Equal(h.PromptChars, u.PromptChars); + Assert.Equal(h.PromptSha256, u.PromptSha256); + Assert.Equal(h.Signal, u.Signal); + Assert.Null(u.PromptPreview); + Assert.Equal(h.CacheHit, u.CacheHit); + Assert.Equal(h.SchemaVersion, u.SchemaVersion); + Assert.Equal(h.CorrelationId, u.CorrelationId); + Assert.Equal(h.ClassificationEvaluated, u.ClassificationEvaluated); + Assert.Equal(h.DenialKind, u.DenialKind); + Assert.Equal(h.StoppedAtStage, u.StoppedAtStage); + Assert.Equal(h.SelectedModel, u.SelectedModel); + Assert.Equal(h.AttemptedModel, u.AttemptedModel); + Assert.Equal(h.Stream, u.Stream); + Assert.Equal(h.UsageReported, u.UsageReported); + Assert.Equal(h.CostBasis, u.CostBasis); + Assert.Equal(h.EventType, u.EventType); + Assert.Equal(h.ConfigVersion, u.ConfigVersion); + Assert.Equal(h.EntryPoint, u.EntryPoint); + Assert.Equal(h.OperatorRef, u.OperatorRef); + Assert.Equal(h.ApplicationId, u.ApplicationId); + Assert.Equal(h.ProfileId, u.ProfileId); + Assert.Equal("Public", u.BaselineClassification); + Assert.Equal(h.ReservedUsd, u.ReservedUsd); + Assert.Equal(h.SettledUsd, u.SettledUsd); + Assert.Equal(h.RequestedMaxOutputTokens, u.RequestedMaxOutputTokens); + Assert.Equal(h.EffectiveMaxOutputTokens, u.EffectiveMaxOutputTokens); + Assert.Equal(h.PartialOutputChars, u.PartialOutputChars); + Assert.Equal(h.ServedConnectionId, u.ServedConnectionId); + + Assert.Equal(h.Attempts!.Count, u.Attempts!.Count); + foreach (var (ha, ua) in h.Attempts!.Zip(u.Attempts!)) + { + Assert.Equal(ha.AttemptId, ua.AttemptId); + Assert.Equal(ha.ConnectionId, ua.ConnectionId); + Assert.Equal(ha.ModelId, ua.ModelId); + Assert.Equal(ha.Outcome, ua.Outcome); + Assert.Equal(ha.ErrorClass, ua.ErrorClass); + Assert.Equal(ha.DurationMs, ua.DurationMs); + Assert.Equal(ha.CostUsd, ua.CostUsd); + Assert.Equal(ha.CostBasis, ua.CostBasis); + Assert.Equal(ha.ReservedUsd, ua.ReservedUsd); + Assert.Equal(ha.Overrun, ua.Overrun); + Assert.Equal(ha.EffectiveMaxOutputTokens, ua.EffectiveMaxOutputTokens); + Assert.Equal(ha.Truncated, ua.Truncated); + } + Assert.Equal(h.Trace!.Count, u.Trace!.Count); + foreach (var (ht, ut) in h.Trace!.Zip(u.Trace!)) + { + Assert.Equal(ht.Stage, ut.Stage); + Assert.Equal(ht.State, ut.State); + Assert.Equal(ht.DurationMs, ut.DurationMs); + Assert.Equal(ht.AttemptId, ut.AttemptId); + Assert.Equal(ht.ReasonCode, ut.ReasonCode); + } + } + + [Fact] + public void Audit_record_v3_round_two_fields_reach_the_console_from_the_requests_page_and_the_by_id_lookup() + { + var record = RoundTwoRecord(); + var page = JsonSerializer.Serialize(new RequestsPage + { + Segment = new SegmentInfo { Path = "/var/covenant/audit.jsonl", Entries = 1, ChainValid = true, Id = "current", Label = "Current segment", IsCurrent = true }, + Items = [record], + NextCursor = null, + }, AuditJsonContext.Default.RequestsPage); + var ui = JsonSerializer.Deserialize(page, UiModels.UiJsonContext.Default.RequestsResponse)!; + AssertRecord(record, Assert.Single(ui.Items)); + + var byId = JsonSerializer.Deserialize(JsonSerializer.Serialize(record, AuditJsonContext.Default.AuditEntry), UiModels.UiJsonContext.Default.AuditEntryView)!; + AssertRecord(record, byId); + + // What the drawer shows from those fields. + Assert.Equal("256", Covenant.Ui.Logic.RecordFacts.RequestedMaxOutputTokens(byId)); + Assert.Equal("64", Covenant.Ui.Logic.RecordFacts.EffectiveMaxOutputTokens(byId)); + Assert.True(Covenant.Ui.Logic.RecordFacts.Truncated(byId)); + Assert.True(Covenant.Ui.Logic.RecordFacts.IsIncompleteStream(byId)); + Assert.Equal("ollama", Covenant.Ui.Logic.RecordFacts.ServedConnection(byId)); + Assert.Contains("Mixed (includes estimates)", Covenant.Ui.Logic.CostText.Cost(byId), StringComparison.Ordinal); + var trace = Covenant.Ui.Logic.TraceModel.FromAuditSummary(byId.Trace, byId.Attempts, byId.ConfigVersion)!; + var provider = trace.Steps.Single(st => st.Stage == "provider"); + Assert.Equal(2, provider.Attempts.Count); + Assert.Equal("openai/gpt-x-mini", provider.Attempts[0].Target); + Assert.Equal("incomplete_stream", provider.Attempts[0].ReasonCode); + } + + [Fact] + public void Status_report_with_connection_health_reaches_the_console() + { + var recent = new RecentRequest + { + Id = "req_1", T = Created, Principal = "console:demo-app", Team = "payments", Workflow = "console", UseCase = "playground", + Classification = "Pii", Effect = "Allow", Model = "ollama/qwen3:8b", Tokens = 94, TokensIn = 84, TokensOut = 10, CostUsd = 0.0021m, + Ms = 812.5, Reason = "allowed", PromptChars = 120, PromptSha256 = "abc", Signal = "US SSN pattern", PromptPreview = null, CacheHit = false, CostBasis = "mixed", + }; + var host = new StatusReport + { + GeneratedUtc = Created, StartedUtc = Created.AddHours(-1), + KillSwitch = new KillSwitchState { Engaged = true, Reason = "demo" }, + Budget = new BudgetStatus { GlobalCapUsd = 25m, GlobalSpendUsd = 0.5m, Teams = [new TeamBudgetStatus { Team = "payments", CapUsd = null, SpendUsd = 0.5m }] }, + Routes = [new RouteView { Classification = "Pii", Adapter = "ollama", Model = "qwen3:8b" }], + FinOps = new FinOpsSummary + { + Requests = 3, Allowed = 2, Denied = 1, TotalCostUsd = 0.0021m, LocalRequests = 1, LocalTokens = 94, + EstimatedSavingsUsd = 0m, SavingsLocalUsd = 0m, SavingsRouterUsd = 0m, SavingsCacheUsd = 0m, CacheHits = 0, + UnknownCostRequests = 1, EstimatedCostRequests = 1, + CostByTeamUsd = new() { ["payments"] = 0.0021m }, DenialsByReason = new() { ["paused"] = 1 }, + Activity = [new ActivityBucket { T = Created, Requests = 3, Denied = 1, CostUsd = 0.0021m, AvgMs = 400.5 }], + RequestsByModel = new() { ["ollama/qwen3:8b"] = 2 }, + Recent = [recent], + Savings = new SavingsSummary { Baseline = "openai/gpt-x", RouteAvoidedUsd = 0.01m, CacheAvoidedUsd = 0.002m, TotalUsd = 0.012m, ExcludedRecords = 1 }, + }, + ChainValid = true, AuditEntries = 3, Auth = new AuthStatus { AllowAnonymous = false, KeyCount = 2 }, OtelEnabled = false, RoutingThresholdTokens = 400, + Environment = "local", Mode = "local-only", AuditPath = "/var/covenant/audit.jsonl", CacheTtlSeconds = 300, PromptPreviewChars = 0, + Anchor = new AnchorStatus { Configured = true, Every = 100, AnchorsWritten = 2, LastAnchorUtc = Created }, + Version = "2.0.0", ConfigVersion = 13, + ConnectionHealth = + [ + new ConnectionHealthView + { + Key = "ollama:qwen3:8b", ConnectionId = "ollama", ModelId = "qwen3:8b", Boundary = "Local", Enabled = true, + Health = new HealthView { State = "ok", LastSuccessUtc = Created, LastFailureUtc = Created.AddMinutes(-5), LastError = "timeout" }, + }, + ], + }; + var ui = JsonSerializer.Deserialize(JsonSerializer.Serialize(host, CovenantJsonContext.Default.StatusReport), UiModels.UiJsonContext.Default.StatusReport)!; + + Assert.Equal(Created, ui.GeneratedUtc); + Assert.Equal(Created.AddHours(-1), ui.StartedUtc); + Assert.True(ui.KillSwitch.Engaged); + Assert.Equal("demo", ui.KillSwitch.Reason); + Assert.Equal(25m, ui.Budget.GlobalCapUsd); + Assert.Equal(0.5m, ui.Budget.GlobalSpendUsd); + Assert.Equal("payments", Assert.Single(ui.Budget.Teams).Team); + Assert.Null(ui.Budget.Teams[0].CapUsd); + Covenant.Ui.Models.RouteView route = Assert.Single(ui.Routes); + Assert.Equal("Pii", route.Classification); + Assert.Equal("ollama", route.Adapter); + Assert.Equal("qwen3:8b", route.Model); + Assert.True(ui.ChainValid); + Assert.Equal(3, ui.AuditEntries); + Assert.False(ui.Auth.AllowAnonymous); + Assert.Equal(2, ui.Auth.KeyCount); + Assert.False(ui.OtelEnabled); + Assert.Equal(400, ui.RoutingThresholdTokens); + Assert.Equal("local", ui.Environment); + Assert.Equal("local-only", ui.Mode); + Assert.Equal("Local-only", Covenant.Ui.Logic.ShellStatus.Mode(ui.Mode).Label); + Assert.Equal("/var/covenant/audit.jsonl", ui.AuditPath); + Assert.Equal(300, ui.CacheTtlSeconds); + Assert.Equal(0, ui.PromptPreviewChars); + Assert.True(ui.Anchor!.Configured); + Assert.Equal(100, ui.Anchor!.Every); + Assert.Equal(2, ui.Anchor!.AnchorsWritten); + Assert.Equal(Created, ui.Anchor!.LastAnchorUtc); + Assert.Equal("2.0.0", ui.Version); + Assert.Equal(13, ui.ConfigVersion); + + var f = ui.FinOps; + Assert.Equal(3, f.Requests); + Assert.Equal(2, f.Allowed); + Assert.Equal(1, f.Denied); + Assert.Equal(0.0021m, f.TotalCostUsd); + Assert.Equal(1, f.LocalRequests); + Assert.Equal(94, f.LocalTokens); + Assert.Equal(1, f.UnknownCostRequests); + Assert.Equal(1, f.EstimatedCostRequests); + Assert.Equal(0.0021m, f.CostByTeamUsd["payments"]); + Assert.Equal(1, f.DenialsByReason["paused"]); + Assert.Equal(2, f.RequestsByModel["ollama/qwen3:8b"]); + var b = Assert.Single(f.Activity); + Assert.Equal(Created, b.T); + Assert.Equal(400.5, b.AvgMs); + Assert.Equal("Estimated provider charge avoided", f.Savings!.Label); + Assert.Equal("openai/gpt-x", f.Savings!.Baseline); + Assert.Equal(0.01m, f.Savings!.RouteAvoidedUsd); + Assert.Equal(0.002m, f.Savings!.CacheAvoidedUsd); + Assert.Equal(0.012m, f.Savings!.TotalUsd); + Assert.Equal(1, f.Savings!.ExcludedRecords); + var r = Assert.Single(f.Recent); + Assert.Equal("req_1", r.Id); + Assert.Equal(Created, r.T); + Assert.Equal("Pii", r.Classification); + Assert.Equal("Allow", r.Effect); + Assert.Equal("ollama/qwen3:8b", r.Model); + Assert.Equal(94, r.Tokens); + Assert.Equal(84, r.TokensIn); + Assert.Equal(10, r.TokensOut); + Assert.Equal(0.0021m, r.CostUsd); + Assert.Equal(812.5, r.Ms); + Assert.Equal(120, r.PromptChars); + Assert.Equal("US SSN pattern", r.Signal); + Assert.False(r.CacheHit); + Assert.Equal("mixed", r.CostBasis); + + // Review round 2 (B11): connection_health — the header's source for the CURRENT runtime connection. + var h = Assert.Single(ui.ConnectionHealth!); + Assert.Equal("ollama:qwen3:8b", h.Key); + Assert.Equal("ollama", h.ConnectionId); + Assert.Equal("qwen3:8b", h.ModelId); + Assert.Equal("Local", h.Boundary); + Assert.True(h.Enabled); + Assert.Equal("ok", h.Health.State); + Assert.Equal(Created, h.Health.LastSuccessUtc); + Assert.Equal(Created.AddMinutes(-5), h.Health.LastFailureUtc); + Assert.Equal("timeout", h.Health.LastError); + + var catalog = new UiModels.CatalogResponse + { + Local = new UiModels.LocalRouteInfo { Configured = true, Registered = true, ConnectionId = "ollama", ModelId = "qwen3:8b" }, + }; + Assert.Equal(Covenant.Ui.Logic.LocalRouteState.Ready, Covenant.Ui.Logic.LocalHealth.Derive(catalog, ui.ConnectionHealth).State); + } + + [Fact] + public void Applications_reach_the_console_without_credentials() + { + var body = JsonSerializer.Serialize(new List + { + new() { Id = "demo-app", Team = "payments", Enabled = true, ConsoleTesting = true, GrantedProfiles = ["public-tickets", "internal"], DefaultProfile = "internal" }, + new() { Id = "prod-app", Team = "risk", Enabled = false, ConsoleTesting = false, GrantedProfiles = [], DefaultProfile = null }, + }, ConfigJsonContext.Default.ListApplicationView); + var ui = JsonSerializer.Deserialize(body, UiModels.UiJsonContext.Default.ListApplicationSummaryDto)!; + Assert.Equal(2, ui.Count); + Assert.Equal("demo-app", ui[0].Id); + Assert.Equal("payments", ui[0].Team); + Assert.True(ui[0].Enabled); + Assert.True(ui[0].ConsoleTesting); + Assert.Equal(new[] { "public-tickets", "internal" }, ui[0].GrantedProfiles); + Assert.Equal("internal", ui[0].DefaultProfile); + Assert.False(ui[1].Enabled); + Assert.False(ui[1].ConsoleTesting); + Assert.Empty(ui[1].GrantedProfiles); + Assert.Null(ui[1].DefaultProfile); + Assert.DoesNotContain("key", body, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Rollback_answer_and_config_errors_reach_the_console() + { + // POST /admin/config/rollback answers like a PUT: {version, etag} (ConfigJsonContext.ConfigPutResponse). + var ok = JsonSerializer.Deserialize(JsonSerializer.Serialize(new ConfigPutResponse { Version = 14, Etag = "\"v14\"" }, ConfigJsonContext.Default.ConfigPutResponse), + UiModels.UiJsonContext.Default.ConfigPutResponseDto)!; + Assert.Equal(14, ok.Version); + Assert.Equal("\"v14\"", ok.Etag); + + var notFound = JsonSerializer.Deserialize(JsonSerializer.Serialize(new ConfigErrorResponse { Error = "not_found", Reason = "no activated configuration version 99", ActiveVersion = 13 }, + ConfigJsonContext.Default.ConfigErrorResponse), UiModels.UiJsonContext.Default.ConfigErrorResponseDto)!; + Assert.Equal("not_found", notFound.Error); + Assert.Equal("no activated configuration version 99", notFound.Reason); + Assert.Equal(13, notFound.ActiveVersion); + Assert.Null(notFound.Errors); + + var rolledBack = Covenant.Ui.Logic.EditOutcomes.FromResponse(200, + JsonSerializer.Serialize(new ConfigPutResponse { Version = 14, Etag = "\"v14\"" }, ConfigJsonContext.Default.ConfigPutResponse), rollback: true); + Assert.True(rolledBack.Succeeded); + Assert.Equal(14, rolledBack.Version); + + // A historical snapshot (GET /admin/config/versions/{n}) is a plain CovenantConfig. + var snap = JsonSerializer.Deserialize(JsonSerializer.Serialize(Representative(ProviderMode.LocalOnly), ConfigJsonContext.Default.CovenantConfig), + UiModels.UiJsonContext.Default.CovenantConfigDto)!; + Assert.Equal(7, snap.Version); + Assert.Equal("local-only", snap.Mode); + Assert.Equal(4, snap.Connections.Count); + Assert.Equal(90, snap.Connections[0].TimeoutSeconds); + } + + [Fact] + public void Common_admin_error_body_carries_the_error_code_the_console_branches_on() + { + foreach (var (error, reason) in new[] { ("cursor_expired", "the segment was rotated"), ("invalid_cursor", "malformed"), ("not_found", "no record") }) + { + var ui = JsonSerializer.Deserialize(JsonSerializer.Serialize(new ErrorResponse { Error = error, Reason = reason, RequestId = "req_1", Scanned = 3 }, CovenantJsonContext.Default.ErrorResponse), + UiModels.UiJsonContext.Default.ErrorResponse)!; + Assert.Equal(error, ui.Error); + Assert.Equal(reason, ui.Reason); + Assert.Equal("req_1", ui.RequestId); + Assert.Equal(3, ui.Scanned); + } + var p = new Covenant.Ui.Logic.RequestPaging(); + p.Reset(null); + Assert.Equal(Covenant.Ui.Logic.PageResult.CursorExpired, p.ApplyError(410, "cursor_expired", "410")); + } + + [Fact] + public void Request_export_reaches_the_console_without_content() + { + var record = RoundTwoRecord() with { PromptPreview = null }; + var host = new RequestExport + { + ExportedUtc = Created.AddDays(1), + RequestId = record.Id, + Segment = new SegmentView { Id = "a-0123456789abcdef", Label = "Archived 2026-10-01 09:00:00 UTC", Current = false, Entries = 40, Events = 2, FirstUtc = Created, LastUtc = Created.AddHours(2), ChainValid = true, ArchivedUtc = Created.AddDays(1) }, + ConfigVersion = 13, + Record = record, + Attempts = record.Attempts, + Trace = record.Trace, + Integrity = new ExportIntegrity + { + SegmentId = "a-0123456789abcdef", ChainValid = true, ChainFailure = null, Line = 17, PreviousHash = new string('b', 64), EntryHash = new string('c', 64), + AnchorConfigured = true, Status = "verified", + }, + ContentIncluded = false, + }; + var ui = JsonSerializer.Deserialize(JsonSerializer.Serialize(host, AuditJsonContext.Default.RequestExport), UiModels.UiJsonContext.Default.RequestExportDto)!; + Assert.Equal(Created.AddDays(1), ui.ExportedUtc); + Assert.Equal(record.Id, ui.RequestId); + Assert.Equal("a-0123456789abcdef", ui.Segment.Id); + Assert.Equal("Archived 2026-10-01 09:00:00 UTC", ui.Segment.Label); + Assert.False(ui.Segment.Current); + Assert.Equal(40, ui.Segment.Entries); + Assert.Equal(2, ui.Segment.Events); + Assert.Equal(Created, ui.Segment.FirstUtc); + Assert.Equal(Created.AddHours(2), ui.Segment.LastUtc); + Assert.True(ui.Segment.ChainValid); + Assert.Equal(Created.AddDays(1), ui.Segment.ArchivedUtc); + Assert.Equal(13, ui.ConfigVersion); + AssertRecord(record, ui.Record); + Assert.Equal(new[] { "att_1", "att_2" }, ui.Attempts!.Select(a => a.AttemptId)); + Assert.Equal(new[] { "auth", "provider", "provider" }, ui.Trace!.Select(t => t.Stage)); + Assert.Equal("a-0123456789abcdef", ui.Integrity.SegmentId); + Assert.True(ui.Integrity.ChainValid); + Assert.Null(ui.Integrity.ChainFailure); + Assert.Equal(17, ui.Integrity.Line); + Assert.Equal(new string('b', 64), ui.Integrity.PreviousHash); + Assert.Equal(new string('c', 64), ui.Integrity.EntryHash); + Assert.True(ui.Integrity.AnchorConfigured); + Assert.Equal("verified", ui.Integrity.Status); + Assert.False(ui.ContentIncluded); + } + + [Fact] + public void Trace_snapshot_event_and_playground_submission_reach_the_console() + { + var ev = new TraceEventView + { + Seq = 9, RequestId = "req_1", ConfigVersion = 13, Stage = "provider", AttemptId = "att_1", State = "running", TsUtc = Created, + DurationMs = null, ReasonCode = null, Target = "ollama/qwen3:8b", RequestedMaxOutputTokens = 256, EffectiveMaxOutputTokens = 64, + }; + var uiEv = JsonSerializer.Deserialize(JsonSerializer.Serialize(ev, TraceJsonContext.Default.TraceEventView), UiModels.UiJsonContext.Default.TraceEventDto)!; + Assert.Equal(9, uiEv.Seq); + Assert.Equal("req_1", uiEv.RequestId); + Assert.Equal(13, uiEv.ConfigVersion); + Assert.Equal("provider", uiEv.Stage); + Assert.Equal("att_1", uiEv.AttemptId); + Assert.Equal("running", uiEv.State); + Assert.Equal(Created, uiEv.TsUtc); + Assert.Null(uiEv.DurationMs); + Assert.Null(uiEv.ReasonCode); + Assert.Equal("ollama/qwen3:8b", uiEv.Target); + Assert.Equal(256, uiEv.RequestedMaxOutputTokens); + Assert.Equal(64, uiEv.EffectiveMaxOutputTokens); + + var snap = new TraceSnapshotView + { + RequestId = "req_1", ConfigVersion = 13, Complete = true, Truncated = true, + Events = [ev, new TraceEventView { Seq = 10, RequestId = "req_1", ConfigVersion = 13, Stage = "provider", AttemptId = "att_1", State = "passed", TsUtc = Created.AddSeconds(1), DurationMs = 812.25 }], + }; + var uiSnap = JsonSerializer.Deserialize(JsonSerializer.Serialize(snap, TraceJsonContext.Default.TraceSnapshotView), UiModels.UiJsonContext.Default.TraceSnapshotDto)!; + Assert.Equal("req_1", uiSnap.RequestId); + Assert.Equal(13, uiSnap.ConfigVersion); + Assert.True(uiSnap.Complete); + Assert.True(uiSnap.Truncated); + Assert.Equal(new long[] { 9, 10 }, uiSnap.Events.Select(e => e.Seq)); + Assert.Equal(812.25, uiSnap.Events[1].DurationMs); + var acc = new Covenant.Ui.Logic.TraceAccumulator(); + acc.ApplySnapshot(uiSnap); + var attempt = Assert.Single(acc.View().Steps.Single(st => st.Stage == "provider").Attempts); + Assert.Equal(Covenant.Ui.Logic.TraceStepState.Passed, attempt.State); + Assert.Equal(64, attempt.EffectiveMaxOutputTokens); + + foreach (var state in new[] { "running", "completed" }) + { + var sub = new PlaygroundSubmissionView { ClientRequestId = "0123456789abcdef0123456789abcdef", RequestId = "req_1", State = state }; + var uiSub = JsonSerializer.Deserialize(JsonSerializer.Serialize(sub, TraceJsonContext.Default.PlaygroundSubmissionView), UiModels.UiJsonContext.Default.PlaygroundSubmissionDto)!; + Assert.Equal("0123456789abcdef0123456789abcdef", uiSub.ClientRequestId); + Assert.Equal("req_1", uiSub.RequestId); + Assert.Equal(state, uiSub.State); + var poll = new Covenant.Ui.Logic.SubmissionPoll("0123456789abcdef0123456789abcdef"); + Assert.Equal(Covenant.Ui.Logic.SubmissionPollAction.Subscribe, poll.OnPollResult(200, uiSub)); + Assert.Equal("req_1", poll.RequestId); + } + } + + [Fact] + public void Console_inference_body_always_carries_a_client_request_id_the_host_accepts() + { + var snapshot = Covenant.Ui.Logic.RequestSnapshot.Freeze(1, new Covenant.Ui.Logic.PlaygroundForm { ApplicationId = "demo-app", Prompt = "Reply OK." }, Created); + var body = JsonSerializer.Serialize(new UiModels.PlaygroundRequestDto + { + ApplicationId = "demo-app", Messages = [new UiModels.ChatMessageDto { Role = "user", Content = "Reply OK." }], MaxTokens = 256, Stream = true, + ClientRequestId = snapshot.ClientRequestId, + }, UiModels.UiJsonContext.Default.PlaygroundRequestDto); + var host = JsonSerializer.Deserialize(body, CovenantJsonContext.Default.PlaygroundRequest)!; + Assert.Null(PlaygroundApi.Validate(host)); // required since review round 2 (B7) + Assert.Equal(snapshot.ClientRequestId, host.ClientRequestId); + Assert.True(PlaygroundApi.IsValidClientRequestId(host.ClientRequestId)); + Assert.Equal(256, host.MaxTokens); + Assert.True(host.Stream); + } + + [Fact] + public void Probe_evidence_and_kill_switch_reach_the_console() + { + var probe = JsonSerializer.Deserialize(JsonSerializer.Serialize(new ProbeResult + { + Allowed = true, Reachable = true, HttpStatus = 200, Models = ["qwen2.5-coder:7b"], Error = null, DurationMs = 12.5, Endpoint = "http://localhost:11434/v1/", CheckedUtc = Created, + }, CovenantJsonContext.Default.ProbeResult), UiModels.UiJsonContext.Default.ProbeResponse)!; + Assert.True(probe.Allowed); + Assert.True(probe.Reachable); + Assert.Equal(200, probe.HttpStatus); + Assert.Equal(new[] { "qwen2.5-coder:7b" }, probe.Models); + Assert.Equal(12.5, probe.DurationMs); + Assert.Equal("http://localhost:11434/v1/", probe.Endpoint); + Assert.Equal(Created, probe.CheckedUtc); + + var ev = JsonSerializer.Deserialize(JsonSerializer.Serialize(new EvidenceReport + { + GeneratedUtc = Created, AuditLogPath = "/var/covenant/audit.jsonl", ChainValid = false, ChainFailure = "hash mismatch", FirstInvalidLine = 4, + Entries = 10, Events = 2, Allowed = 7, Denied = 3, FirstEntryUtc = Created, LastEntryUtc = Created.AddHours(1), TotalCostUsd = 0.5m, + CostByTeamUsd = new() { ["payments"] = 0.5m }, RequestsByClassification = new() { ["Pii"] = 4 }, AnchorConfigured = true, AnchorCount = 3, LastAnchorUtc = Created, + }, CovenantJsonContext.Default.EvidenceReport), UiModels.UiJsonContext.Default.EvidenceReport)!; + Assert.Equal(Created, ev.GeneratedUtc); + Assert.Equal("/var/covenant/audit.jsonl", ev.AuditLogPath); + Assert.False(ev.ChainValid); + Assert.Equal("hash mismatch", ev.ChainFailure); + Assert.Equal(4, ev.FirstInvalidLine); + Assert.Equal(10, ev.Entries); + Assert.Equal(2, ev.Events); + Assert.Equal(7, ev.Allowed); + Assert.Equal(3, ev.Denied); + Assert.Equal(0.5m, ev.TotalCostUsd); + Assert.Equal(0.5m, ev.CostByTeamUsd["payments"]); + Assert.Equal(4, ev.RequestsByClassification["Pii"]); + Assert.True(ev.AnchorConfigured); + Assert.Equal(3, ev.AnchorCount); + Assert.Equal(Created, ev.LastAnchorUtc); + + var ks = JsonSerializer.Deserialize(JsonSerializer.Serialize(new KillSwitchState { Engaged = true, Reason = "paused from console" }, CovenantJsonContext.Default.KillSwitchState), + UiModels.UiJsonContext.Default.KillSwitchState)!; + Assert.True(ks.Engaged); + Assert.Equal("paused from console", ks.Reason); + var reset = JsonSerializer.Deserialize(JsonSerializer.Serialize(new ResetResponse { ArchivedTo = "/var/covenant/audit.jsonl.20261017-120000.archived" }, CovenantJsonContext.Default.ResetResponse), + UiModels.UiJsonContext.Default.ResetResponse)!; + Assert.Equal("/var/covenant/audit.jsonl.20261017-120000.archived", reset.ArchivedTo); + } + + private static JsonElement Wire(string json) + { + using var doc = JsonDocument.Parse(json); + return doc.RootElement.Clone(); + } + + // ---- Review round 3 (UI): the profile/grant editor builds drafts the Host's validation accepts ---- + + private static Covenant.Governance.ValidationEnvironment PermissiveEnvironment() => new() + { + EgressAllowList = new HashSet(StringComparer.OrdinalIgnoreCase) { "ollama-host:11434", "vllm-host:8000", "api.openai.com:443", "api.anthropic.com:443" }, + SecretAvailable = _ => true, + LocalEndpoints = new HashSet(StringComparer.OrdinalIgnoreCase) { "ollama-host:11434", "vllm-host:8000" }, + }; + + /// Console draft → PUT body (UiJsonContext) → Host ConfigPutRequest → ConfigValidator. + private static (CovenantConfig Host, Covenant.Governance.ConfigValidationResult Result) HostValidates(UiModels.CovenantConfigDto draft) + { + var body = JsonSerializer.Serialize(new UiModels.ConfigPutRequestDto { Config = draft, ChangeSummary = "profiles" }, UiModels.UiJsonContext.Default.ConfigPutRequestDto); + var put = JsonSerializer.Deserialize(body, ConfigJsonContext.Default.ConfigPutRequest); + Assert.NotNull(put?.Config); + var config = put!.Config!; + var result = Covenant.Governance.ConfigValidator.Validate(config, PermissiveEnvironment()); + Assert.True(result.StructurallySound, string.Join("; ", result.Errors.Select(e => e.Path + ": " + e.Code))); + return (config, result); + } + + private static bool ProfileOrGrantPath(string path) + => path.StartsWith("profiles", StringComparison.Ordinal) || path.StartsWith("applications", StringComparison.Ordinal) || path.Contains(".profiles", StringComparison.Ordinal); + + [Fact] + public void Profile_and_grant_edits_made_by_the_console_pass_host_validation() + { + var (_, envelope, _, _) = RoundTrip(Representative(ProviderMode.Hybrid)); + var draft = envelope.Config!; + + Assert.Empty(Covenant.Ui.Logic.ProfileEditing.Add(draft, new Covenant.Ui.Logic.NewProfileForm { Id = "support", Name = "Support tickets", Baseline = "Public", Description = "Synthetic" })); + var demo = Covenant.Ui.Logic.ProfileEditing.FindApplication(draft, "demo-app")!; + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetGrant(demo, "support", true, draft)); + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetDefault(demo, "support")); + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetMaxOutputTokens(demo, 128)); + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetTeam(demo, "payments-ops")); + var prod = Covenant.Ui.Logic.ProfileEditing.FindApplication(draft, "prod-app")!; + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetGrant(prod, "support", true, draft)); + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetDefault(prod, "internal")); + prod.Enabled = true; + prod.ConsoleTesting = true; + + // "clinical" is only granted (no default, no policy) → removable; "public-tickets" is policy 'public''s only + // profile → refused client-side (removing it would widen that policy). + Assert.Null(Covenant.Ui.Logic.ProfileEditing.Remove(draft, "clinical")); + Assert.NotNull(Covenant.Ui.Logic.ProfileEditing.Remove(draft, "public-tickets")); + Assert.All(draft.Applications, a => Assert.Empty(Covenant.Ui.Logic.ProfileEditing.ApplicationProblems(a, draft))); + + var (host, result) = HostValidates(draft); + Assert.DoesNotContain(result.Errors, e => ProfileOrGrantPath(e.Path)); + var support = host.Profiles.Single(p => p.Id == "support"); + Assert.Equal(DataClassification.Public, support.Baseline); + Assert.Equal("Synthetic", support.Description); + Assert.DoesNotContain(host.Profiles, p => p.Id == "clinical"); + var hostDemo = host.Applications.Single(a => a.Id == "demo-app"); + Assert.Equal("support", hostDemo.DefaultProfile); + Assert.Equal(128, hostDemo.MaxOutputTokens); + Assert.Equal("payments-ops", hostDemo.Team); + Assert.DoesNotContain("clinical", hostDemo.GrantedProfiles); + var hostProd = host.Applications.Single(a => a.Id == "prod-app"); + Assert.True(hostProd.Enabled); + Assert.True(hostProd.ConsoleTesting); + Assert.Equal(new[] { "internal", "support" }, hostProd.GrantedProfiles); + } + + [Fact] + public void Console_and_host_agree_that_a_default_profile_must_be_granted() + { + var (_, envelope, _, _) = RoundTrip(Representative(ProviderMode.Hybrid)); + var draft = envelope.Config!; + var prod = Covenant.Ui.Logic.ProfileEditing.FindApplication(draft, "prod-app")!; + Assert.NotNull(Covenant.Ui.Logic.ProfileEditing.SetDefault(prod, "customer-pii")); // the editor refuses + prod.DefaultProfile = "customer-pii"; // forced, to compare + Assert.NotEmpty(Covenant.Ui.Logic.ProfileEditing.ApplicationProblems(prod, draft)); + var (_, result) = HostValidates(draft); + Assert.Contains(result.Errors, e => e.Code == "default_profile_not_granted"); + } +} diff --git a/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs b/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs index 834bffa..d84e4da 100644 --- a/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs +++ b/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs @@ -68,10 +68,25 @@ public static string ReadShared(string path) return reader.ReadToEnd(); } + /// Every per-instance durable path derives from ONE unique audit path (no shared /tmp default): the audit + /// log, the configuration repository (Config:Path) and the budget ledger (Budget:LedgerPath). + public static void IsolatePaths(IWebHostBuilder builder, string auditPath) + { + builder.UseSetting("Audit:Path", auditPath); + builder.UseSetting("Config:Path", ConfigDirFor(auditPath)); + builder.UseSetting("Budget:LedgerPath", auditPath + ".ledger.jsonl"); + } + + public static string ConfigDirFor(string auditPath) => auditPath + ".config"; + + /// Deletes the audit file and every sibling derived from it (archives, anchors, ledger, config repository). public static void DeleteWithSiblings(string path) { - foreach (var f in Directory.GetFiles(Path.GetDirectoryName(path)!, Path.GetFileName(path) + "*")) + var dir = Path.GetDirectoryName(path)!; + foreach (var f in Directory.GetFiles(dir, Path.GetFileName(path) + "*")) File.Delete(f); + foreach (var d in Directory.GetDirectories(dir, Path.GetFileName(path) + "*")) + try { Directory.Delete(d, recursive: true); } catch (IOException) { } } } @@ -102,6 +117,7 @@ internal sealed class ScriptedChatClient : MEAI.IChatClient if (fail) throw new HttpRequestException("connection reset mid-stream"); yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, "rest"); yield return new MEAI.ChatResponseUpdate { Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 7, OutputTokenCount = 3 })] }; + yield return new MEAI.ChatResponseUpdate { FinishReason = MEAI.ChatFinishReason.Stop }; // terminal completion (real providers send one) } public object? GetService(Type serviceType, object? serviceKey = null) => null; @@ -126,7 +142,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("Auth:Keys:0:Key", "k"); builder.UseSetting("Auth:Keys:0:Principal", "p"); builder.UseSetting("Auth:Keys:0:Team", "t"); - builder.UseSetting("Audit:Path", AuditPath); + CorrelationTestKit.IsolatePaths(builder, AuditPath); // No Local:* → PII routes to the unconfigured local placeholder and fails closed. builder.ConfigureTestServices(services => services.AddSingleton(new ChatClientRegistry( @@ -271,9 +287,13 @@ public async Task Pause_403_stops_at_pause_without_calling_the_provider() } } + /// Review fix 4 (stricter than pre-v2, same intent): with no Local:* the legacy import's PII/PHI route + /// names the explicitly DISABLED placeholder connection, so the request is refused at POLICY — no model is + /// selected, none attempted, no provider and no cloud call. (Pre-v2: selected the placeholder, refused at provider.) [Fact] - public async Task Missing_local_adapter_403_selected_but_never_attempted() + public async Task Missing_local_model_403_refused_at_policy_never_selected_or_attempted() { + int callsBefore = _factory.Provider.Calls; var resp = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("my ssn is 123-45-6789")); Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); var id = CorrelationTestKit.HeaderId(resp); @@ -283,11 +303,14 @@ public async Task Missing_local_adapter_403_selected_but_never_attempted() var e = await CorrelationTestKit.LookupAsync(_client, id); Assert.Equal(DataClassification.Pii, e.Classification); Assert.Equal("Governance", e.DenialKind); - Assert.Equal("provider", e.StoppedAtStage); - Assert.Equal("local-model-not-configured", e.SelectedModel); + Assert.Equal("policy", e.StoppedAtStage); + Assert.Contains("no eligible destination", e.Reason, StringComparison.Ordinal); + Assert.Contains("connection 'local' is disabled (not configured)", e.Reason, StringComparison.Ordinal); + Assert.Null(e.SelectedModel); Assert.Null(e.AttemptedModel); Assert.Null(e.ServedByModel); Assert.Equal("no_call", e.CostBasis); + Assert.Equal(callsBefore, _factory.Provider.Calls); // no provider (and so no cloud) call } [Fact] @@ -471,7 +494,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("Auth:Keys:0:Key", "k"); builder.UseSetting("Auth:Keys:0:Principal", "p"); builder.UseSetting("Auth:Keys:0:Team", "t"); - builder.UseSetting("Audit:Path", AuditPath); + CorrelationTestKit.IsolatePaths(builder, AuditPath); builder.UseSetting("RateLimit:GlobalPerMinute", "1"); builder.ConfigureTestServices(services => services.AddSingleton(new ChatClientRegistry( @@ -710,7 +733,7 @@ await sink.EnqueueAsync(new AuditEntry("req_v2b", DateTimeOffset.Parse("2026-10- Assert.Equal("estimated_failed_call", entries[2].CostBasis); var ledger = new InMemorySpendLedger(); - LedgerReplay.Rebuild(entries, ledger); + Covenant.Host.LedgerReplay.Rebuild(entries, ledger); Assert.Equal(0.002m + 0.01m + 0.0005m, ledger.GlobalSpendUsd); Assert.Equal(0.002m, ledger.TeamSpendUsd("legacy-team")); Assert.Equal(0.0105m, ledger.TeamSpendUsd("v2-team")); // the estimated failed-call charge replays diff --git a/tests/Covenant.Tests/Covenant.Tests.csproj b/tests/Covenant.Tests/Covenant.Tests.csproj index 6ca31a8..a9975c4 100644 --- a/tests/Covenant.Tests/Covenant.Tests.csproj +++ b/tests/Covenant.Tests/Covenant.Tests.csproj @@ -30,7 +30,7 @@ without referencing the Blazor WebAssembly project. Ui types live in Covenant.Ui.* namespaces — qualify them in tests where Covenant.Host has a same-named type (ErrorResponse, StatusReport, …). --> - + diff --git a/tests/Covenant.Tests/FallbackTests.cs b/tests/Covenant.Tests/FallbackTests.cs new file mode 100644 index 0000000..c4f3e70 --- /dev/null +++ b/tests/Covenant.Tests/FallbackTests.cs @@ -0,0 +1,314 @@ +using System.Net; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// ADR-0013 bounded approved fallback through the REAL stages (stub IChatClients, never a paid provider): +/// fallback only for the policy's retry classes, within maxAttempts and deadlineMs, never after content was emitted, +/// never on caller cancellation, pause or non-retryable errors; every attempt evidenced and charged (ADR-0014). +public sealed class FallbackTests +{ + private readonly StubChatClient _mini = new("mini reply"); + private readonly StubChatClient _strong = new("strong reply"); + private readonly StubChatClient _local = new("local reply"); + + private V2Rig Rig(RetrySettings? retry = null, Func? tweak = null) + => V2Rig.Build(V2Rig.FallbackConfig(retry, tweak: tweak), new Dictionary + { + [$"openai:{V2.CloudModel}"] = _mini, + ["openai:gpt-4o"] = _strong, + [$"ollama:{V2.LocalTag}"] = _local, + }); + + public static TheoryData RetryableFailures => new() { "429", "timeout", "5xx-500", "5xx-502", "5xx-503", "5xx-504", "connect" }; + + private static Exception Make(string kind) => kind switch + { + "429" => Failures.Status(HttpStatusCode.TooManyRequests), + "timeout" => Failures.ProviderTimeout(), + "5xx-500" => Failures.Status(HttpStatusCode.InternalServerError), + "5xx-502" => Failures.Status(HttpStatusCode.BadGateway), + "5xx-503" => Failures.Status(HttpStatusCode.ServiceUnavailable), + "5xx-504" => Failures.Status(HttpStatusCode.GatewayTimeout), + "connect" => Failures.Connect(), + _ => throw new ArgumentOutOfRangeException(nameof(kind)), + }; + + [Theory] + [MemberData(nameof(RetryableFailures))] + public async Task Retryable_failure_before_output_falls_back_to_the_next_approved_target(string kind) + { + _mini.Then(StubChatClient.Mode.Throw, () => Make(kind)); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal(1, _mini.Calls); + Assert.Equal(1, _strong.Calls); + Assert.Equal("strong reply", ctx.Response!.Message.Content); + Assert.Equal("gpt-4o", e.ServedByModel); + Assert.Equal(V2.CloudModel, e.SelectedModel); // policy's primary + Assert.Equal("gpt-4o", e.AttemptedModel); // last attempt started + + var attempts = Assert.IsAssignableFrom>(e.Attempts); + Assert.Equal(2, attempts.Count); + Assert.Equal(("att_1", "openai", V2.CloudModel, "failed"), (attempts[0].AttemptId, attempts[0].ConnectionId, attempts[0].ModelId, attempts[0].Outcome)); + Assert.Equal(kind.StartsWith("5xx", StringComparison.Ordinal) ? "5xx" : kind, attempts[0].ErrorClass); + Assert.Equal(("att_2", "gpt-4o", "served"), (attempts[1].AttemptId, attempts[1].ModelId, attempts[1].Outcome)); + + // Both attempts charged: the failed one at its reservation-bound estimate (possibly billed, never $0). + Assert.Equal("estimated_failed_call", attempts[0].CostBasis); + Assert.True(attempts[0].CostUsd > 0m); + Assert.Equal(attempts[0].ReservedUsd, attempts[0].CostUsd); + Assert.Equal("reported", attempts[1].CostBasis); + Assert.Equal(attempts[0].CostUsd + attempts[1].CostUsd, e.SettledUsd); + Assert.Equal(e.SettledUsd, e.Usage.CostUsd); // the request's charge includes the failed attempt + Assert.Equal(e.SettledUsd, rig.Ledger.Spent("global", BudgetPeriod.Monthly)); + Assert.Equal(0, rig.Ledger.OpenReservations); + Assert.Equal(0m, rig.Ledger.Reserved("global")); + + // Observed health per connection:model from the real attempts. + Assert.Equal("failed", rig.Health.Get($"openai:{V2.CloudModel}").State); + Assert.Equal("ok", rig.Health.Get("openai:gpt-4o").State); + + // Trace: two provider attempts; the fallback's pause + budget re-checks are recorded with its attempt id. + Assert.Contains(ctx.TraceEvents, t => t.Stage == "provider" && t.AttemptId == "att_1" && t.State == TraceStates.Failed); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "pause" && t.AttemptId == "att_2" && t.State == TraceStates.Passed); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "budget" && t.AttemptId == "att_2" && t.State == TraceStates.Passed); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "provider" && t.AttemptId == "att_2" && t.State == TraceStates.Passed); + } + + public static TheoryData NonRetryableStatuses => new() { 400, 401, 403, 404, 422 }; + + [Theory] + [MemberData(nameof(NonRetryableStatuses))] + public async Task Non_retryable_provider_error_never_falls_back(int status) + { + _mini.Then(StubChatClient.Mode.Throw, () => Failures.Status((HttpStatusCode)status)); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(0, _strong.Calls + _local.Calls); + var a = Assert.Single(e.Attempts!); + Assert.Equal("non_retryable", a.ErrorClass); + Assert.Equal("estimated_failed_call", e.CostBasis); + Assert.True(e.Usage.CostUsd > 0m); + } + + [Fact] + public async Task Failure_class_not_in_retry_on_is_terminal() + { + _mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.TooManyRequests)); + var rig = Rig(new RetrySettings { MaxAttempts = 3, DeadlineMs = 60_000, On = ["5xx"] }); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal("429", Assert.Single(e.Attempts!).ErrorClass); + Assert.Equal(0, _strong.Calls); + } + + [Fact] + public async Task Max_attempts_is_respected() + { + var fail = () => Failures.Status(HttpStatusCode.ServiceUnavailable); + _mini.Then(StubChatClient.Mode.Throw, fail); + _strong.Then(StubChatClient.Mode.Throw, fail); + var rig = Rig(new RetrySettings { MaxAttempts = 2, DeadlineMs = 60_000 }); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(2, e.Attempts!.Count); + Assert.Equal(0, _local.Calls); // a third approved target exists but maxAttempts = 2 + Assert.All(e.Attempts!, a => Assert.True(a.CostUsd > 0m)); + Assert.Equal(e.Attempts!.Sum(a => a.CostUsd), e.SettledUsd); + } + + [Fact] + public async Task Deadline_cancels_a_hanging_attempt_as_timeout_and_starts_no_further_attempt() + { + _mini.Then(StubChatClient.Mode.Hang); + var rig = Rig(new RetrySettings { MaxAttempts = 3, DeadlineMs = 50 }); // pure rig: below the validator minimum on purpose + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + var a = Assert.Single(e.Attempts!); + Assert.Equal("timeout", a.ErrorClass); + Assert.Equal(0, _strong.Calls + _local.Calls); + } + + [Fact] + public async Task Streaming_failure_after_the_first_chunk_never_continues_on_a_second_provider() + { + _mini.Then(StubChatClient.Mode.StreamThenThrow); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(0, _strong.Calls + _local.Calls); // 503 is retryable, but content was already emitted + Assert.Equal("partial ".Length, ctx.PartialOutputChars); // partial output preserved as a fact + var a = Assert.Single(e.Attempts!); + Assert.Equal("failed", a.Outcome); + Assert.Equal("5xx", a.ErrorClass); + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.Equal("estimated_failed_call", e.CostBasis); + } + + [Fact] + public async Task Streaming_failure_before_any_chunk_may_fall_back() + { + _mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.BadGateway)); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal("gpt-4o", e.ServedByModel); + Assert.Equal(2, e.Attempts!.Count); + } + + [Fact] + public async Task Pause_tripped_between_attempts_refuses_the_second_attempt_at_pause() + { + var rig = Rig(); + _mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)); + _mini.OnCall = () => rig.Kill.Trip("operator pause mid-request"); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + + Assert.True(ctx.IsDenied); + Assert.Equal("pause", e.StoppedAtStage); + Assert.Equal("Governance", e.DenialKind); + Assert.Contains("kill switch engaged", e.Reason, StringComparison.Ordinal); + Assert.Equal(0, _strong.Calls); + Assert.Single(e.Attempts!); // the refused fallback never started + Assert.Contains(ctx.TraceEvents, t => t.Stage == "pause" && t.AttemptId == "att_2" && t.State == TraceStates.Refused); + Assert.True(e.Usage.CostUsd > 0m); // the failed first attempt is still charged + Assert.Equal(0, rig.Ledger.OpenReservations); + } + + [Fact] + public async Task Pause_before_the_request_refuses_with_no_attempt() + { + var rig = Rig(); + rig.Kill.Trip("maintenance"); + var (_, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal("pause", e.StoppedAtStage); + Assert.Empty(e.Attempts!); + Assert.Equal(0, _mini.Calls + _strong.Calls + _local.Calls); + } + + [Fact] + public async Task Policy_denial_makes_no_attempt() + { + var rig = Rig(); + var (_, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", model: "openai/not-a-target"); + Assert.Equal("policy", e.StoppedAtStage); + Assert.Empty(e.Attempts!); + Assert.Equal(0, _mini.Calls + _strong.Calls + _local.Calls); + } + + [Fact] + public async Task Caller_cancellation_is_not_a_provider_failure_and_never_falls_back() + { + _mini.Then(StubChatClient.Mode.Hang); + var rig = Rig(); + using var cts = new CancellationTokenSource(); + var run = rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", ct: cts.Token); + await _mini.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + cts.Cancel(); + var (ctx, e) = await run; + + Assert.Equal(DenialKind.Cancelled, ctx.DenialKind); + Assert.Equal("Cancelled", e.DenialKind); + Assert.Equal(0, _strong.Calls + _local.Calls); + var a = Assert.Single(e.Attempts!); + Assert.Equal("cancelled", a.Outcome); + Assert.Equal("client_cancelled", a.ErrorClass); + Assert.NotEqual("failed", rig.Health.Get($"openai:{V2.CloudModel}").State); // no health penalty for the provider + // Cancellation settles the (possibly billed) attempt at its estimate and releases the reservation. + Assert.Equal(a.ReservedUsd, a.CostUsd); + Assert.Equal(0, rig.Ledger.OpenReservations); + Assert.Equal(0m, rig.Ledger.Reserved("global")); + Assert.Equal(a.CostUsd, rig.Ledger.Spent("global", BudgetPeriod.Monthly)); + } + + [Fact] + public async Task Model_override_pins_one_target_with_no_fallback() + { + _mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", model: $"openai/{V2.CloudModel}"); + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Single(e.Attempts!); + Assert.Equal(0, _strong.Calls + _local.Calls); + } + + [Fact] + public async Task Sensitive_request_whose_local_primary_fails_never_reaches_a_cloud_target() + { + // Even a (validation-invalid) sensitive policy that lists a cloud fallback cannot make it eligible: the engine + // excludes cloud destinations for PII/PHI, so the failing local primary is terminal. + _local.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)); + var rig = Rig(tweak: c => c with + { + Policies = c.Policies.Select(p => p.Id != "sensitive" ? p : p with + { + Targets = [V2.T("ollama", V2.LocalTag), V2.T("openai", V2.CloudModel), V2.T("openai", "gpt-4o")], + Retry = new RetrySettings { MaxAttempts = 3, DeadlineMs = 60_000 }, + }).ToList(), + }); + var (ctx, e) = await rig.RunAsync("Customer SSN 078-05-1120 needs a summary.", profile: "public-demo"); + + Assert.Equal(DataClassification.Pii, e.Classification); + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(1, _local.Calls); + Assert.Equal(0, _mini.Calls + _strong.Calls); + Assert.Equal("ollama", Assert.Single(e.Attempts!).ConnectionId); + Assert.All(ctx.Policy!.Candidates, c => Assert.Equal("ollama", c.AdapterKey)); + } + + [Fact] + public async Task The_enforced_output_bound_is_sent_to_the_provider() + { + var rig = Rig(); + await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal(RequestBounds.DefaultOutputTokens, _mini.LastOptions?.MaxOutputTokens); // application default 1024 + + await rig.RunAsync(V2Rig.PublicPrompt + " again", profile: "public-demo", maxTokens: 64); + Assert.Equal(64, _mini.LastOptions?.MaxOutputTokens); // min(request, application) + + await rig.RunAsync(V2Rig.PublicPrompt + " once more", profile: "public-demo", maxTokens: 100_000); + Assert.Equal(RequestBounds.DefaultOutputTokens, _mini.LastOptions?.MaxOutputTokens); // capped by the application + } +} + +/// SDK-aware failure classification (ADR-0013) — BCL shapes the stub providers raise. +public sealed class ProviderFailureClassifierTests +{ + [Theory] + [InlineData(429, "429")] + [InlineData(500, "5xx")] + [InlineData(502, "5xx")] + [InlineData(503, "5xx")] + [InlineData(504, "5xx")] + [InlineData(501, "non_retryable")] + [InlineData(400, "non_retryable")] + [InlineData(401, "non_retryable")] + [InlineData(404, "non_retryable")] + public void Http_status_maps_to_the_bounded_class(int status, string expected) + => Assert.Equal(expected, SdkProviderFailureClassifier.Shared.Classify(Failures.Status((HttpStatusCode)status))); + + [Fact] + public void Transport_and_timeout_failures_are_classified() + { + var c = SdkProviderFailureClassifier.Shared; + Assert.Equal("connect", c.Classify(Failures.Connect())); + Assert.Equal("connect", c.Classify(new System.Net.Sockets.SocketException(10061))); + Assert.Equal("timeout", c.Classify(new TimeoutException())); + Assert.Equal("timeout", c.Classify(Failures.ProviderTimeout())); + Assert.Equal("5xx", c.Classify(new InvalidOperationException("wrapped", Failures.Status(HttpStatusCode.BadGateway)))); + Assert.Equal("connect", c.Classify(new System.ClientModel.ClientResultException("no response", null, null))); + Assert.Equal("non_retryable", c.Classify(new InvalidOperationException("anything else"))); + } +} diff --git a/tests/Covenant.Tests/HttpMappingTests.cs b/tests/Covenant.Tests/HttpMappingTests.cs index fbbd2bf..614d9d6 100644 --- a/tests/Covenant.Tests/HttpMappingTests.cs +++ b/tests/Covenant.Tests/HttpMappingTests.cs @@ -27,7 +27,7 @@ public HttpMappingTests(WebApplicationFactory factory) b.UseSetting("Auth:Keys:0:Principal", "itest"); b.UseSetting("Auth:Keys:0:Team", "itest-team"); b.UseSetting("RateLimit:PerTeamPerMinute", "1"); - b.UseSetting("Audit:Path", _auditPath); + CorrelationTestKit.IsolatePaths(b, _auditPath); }); _client = _factory.CreateClient(); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "test-api-key"); @@ -36,7 +36,7 @@ public HttpMappingTests(WebApplicationFactory factory) public void Dispose() { _factory.Dispose(); - if (File.Exists(_auditPath)) File.Delete(_auditPath); + CorrelationTestKit.DeleteWithSiblings(_auditPath); } private static StringContent Chat(string content, bool stream = false) => diff --git a/tests/Covenant.Tests/LegacyImportTests.cs b/tests/Covenant.Tests/LegacyImportTests.cs new file mode 100644 index 0000000..060587a --- /dev/null +++ b/tests/Covenant.Tests/LegacyImportTests.cs @@ -0,0 +1,296 @@ +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Microsoft.Extensions.Configuration; +using Xunit; + +namespace Covenant.Tests; + +/// docs/migration-v2.md: each legacy startup-key shape imports into a v1 configuration that routes +/// EXACTLY as the pre-v2 composition did (the main proof is that every pre-existing Host test still passes on the +/// imported configuration; this suite compares the two engines decision by decision). +public sealed class LegacyImportTests +{ + private static IConfiguration Config(params (string Key, string? Value)[] pairs) + => new ConfigurationBuilder().AddInMemoryCollection(pairs.Select(p => new KeyValuePair(p.Key, p.Value))).Build(); + + /// Verbatim pre-v2 Program.cs policy construction (the reference behaviour). + private static (PolicyConfig Policy, long Threshold) LegacyPolicy(IConfiguration cfg) + { + bool localOnly = StartupValidation.ProviderMode(cfg) == StartupValidation.LocalOnlyMode; + string publicModelId = cfg["OpenAI:ModelId"] ?? "gpt-4o-mini"; + string strongModelId = cfg["OpenAI:StrongModelId"] ?? "gpt-4o"; + string localModelId = StartupValidation.Trimmed(cfg["Local:ModelId"]) ?? "local-model-not-configured"; + string anthropicModelId = cfg["Anthropic:ModelId"] ?? "claude-haiku-4-5"; + bool anthropicEnabled = !localOnly && cfg["Anthropic:ApiKey"] is { Length: > 0 }; + List general = localOnly ? [new("local", localModelId)] : [new("openai", publicModelId)]; + if (!localOnly && anthropicEnabled) general.Add(new("anthropic", anthropicModelId)); + if (!localOnly) general.Add(new("openai", strongModelId)); + var policy = new PolicyConfig + { + AllowedRoutes = new Dictionary> + { + [DataClassification.Public] = general, + [DataClassification.Internal] = general, + [DataClassification.Pii] = [new("local", localModelId)], + [DataClassification.Phi] = [new("local", localModelId)], + }, + }; + long threshold = long.TryParse(cfg["Routing:ComplexityTokenThreshold"], out var t) ? t : 400; + return (policy, threshold); + } + + public static TheoryData Shapes => new() { "cloud", "cloud+anthropic", "cloud+local", "cloud+custom", "local-only" }; + + private static IConfiguration Shape(string shape) => shape switch + { + "cloud" => Config(("OpenAI:ApiKey", "sk"), ("Budget:GlobalCapUsd", "5")), + "cloud+anthropic" => Config(("OpenAI:ApiKey", "sk"), ("Anthropic:ApiKey", "ak"), ("Budget:GlobalCapUsd", "5")), + "cloud+local" => Config(("OpenAI:ApiKey", "sk"), ("Local:Endpoint", "http://localhost:11434/v1"), ("Local:ModelId", "qwen3:8b"), ("Budget:GlobalCapUsd", "5")), + "cloud+custom" => Config(("OpenAI:ApiKey", "sk"), ("OpenAI:ModelId", "cheap-1"), ("OpenAI:StrongModelId", "strong-1"), + ("Routing:ComplexityTokenThreshold", "25"), ("Pricing:cheap-1:InPer1M", "0.1"), ("Pricing:cheap-1:OutPer1M", "0.2"), + ("Pricing:strong-1:InPer1M", "3"), ("Pricing:strong-1:OutPer1M", "9"), ("Budget:GlobalCapUsd", "5")), + "local-only" => Config(("Providers:Mode", "local-only"), ("Local:Endpoint", "http://localhost:11434/v1"), ("Local:ModelId", "qwen3:8b"), ("Budget:GlobalCapUsd", "5")), + _ => throw new ArgumentOutOfRangeException(nameof(shape)), + }; + + private static CovenantConfig Import(IConfiguration cfg) + { + var errors = new List(); + var v1 = LegacyImport.Build(cfg, DateTimeOffset.UtcNow, errors); + Assert.Empty(errors); + return v1; + } + + [Theory] + [MemberData(nameof(Shapes))] + public void Imported_configuration_routes_exactly_like_the_pre_v2_policy(string shape) + { + var cfg = Shape(shape); + var (legacyPolicy, threshold) = LegacyPolicy(cfg); + var legacy = new PolicyEngine(legacyPolicy, new RoutingOptions { ComplexityTokenThreshold = threshold }); + var snapshot = new RuntimeSnapshot(Import(cfg)); + bool localConfigured = StartupValidation.Trimmed(cfg["Local:ModelId"]) is { Length: > 0 }; + + var prompts = new[] { "hi", new string('x', 99), new string('x', 101), new string('x', 1601), new string('x', 1605) }; + var models = new string?[] { null, "gpt-4o-mini", "GPT-4O", "gpt-4o", "claude-haiku-4-5", "qwen3:8b", "cheap-1", "strong-1", + "local-model-not-configured", "not-a-model" }; + int compared = 0; + foreach (var cls in Enum.GetValues()) + foreach (var prompt in prompts) + foreach (var model in models) + { + var ctx = new InferenceContext(new InferenceRequest("p", [new ChatMessage(ChatRole.User, prompt)], model, AttributionTags.Unattributed)) + { Classification = cls }; + var before = legacy.Evaluate(ctx); + var after = PolicyEngineV2.Evaluate(snapshot, cls, PolicyEngineV2.LegacyInternalProfile, model, ctx.Request.Messages); + var label = $"{shape} {cls} len={prompt.Length} model={model ?? "(none)"}"; + if (!localConfigured && cls >= DataClassification.Pii) + { + // Review fix 4 (deliberately STRICTER than pre-v2): without Local:* the PII/PHI route points + // at the explicitly DISABLED placeholder, so it is refused at POLICY. Pre-v2 "allowed" it to + // the placeholder and refused at the provider stage — never served either way. + if (after.Effect != PolicyEffect.Deny) throw new Xunit.Sdk.XunitException($"{label}: expected a policy refusal, got {after.Effect}"); + if (before.Effect == PolicyEffect.Allow) + Assert.Contains("connection 'local' is disabled (not configured)", after.Reason, StringComparison.Ordinal); + else + Assert.Equal(before.Reason, after.Reason); + compared++; + continue; + } + if (before.Effect != after.Effect) throw new Xunit.Sdk.XunitException($"{label}: effect {before.Effect} → {after.Effect} ({after.Reason})"); + if (before.Route != after.Route) throw new Xunit.Sdk.XunitException($"{label}: route {before.Route} → {after.Route}"); + if (before.Effect == PolicyEffect.Deny) Assert.Equal(before.Reason, after.Reason); + compared++; + } + Assert.Equal(4 * prompts.Length * models.Length, compared); + } + + [Theory] + [MemberData(nameof(Shapes))] + public void Imported_configuration_validates_against_the_startup_environment(string shape) + { + var cfg = Shape(shape); + var v1 = Import(cfg); + var result = ConfigValidator.Validate(v1, new ValidationEnvironment + { + EgressAllowList = StartupEgress.BuildAllowList(cfg), + SecretAvailable = StartupEgress.SecretAvailability(cfg), + LocalEndpoints = StartupEgress.LocalEndpoints(cfg), + }); + Assert.True(result.IsValid, string.Join("; ", result.Errors.Select(e => $"{e.Path} {e.Code} {e.Message}"))); + Assert.DoesNotContain(result.Warnings, w => w.Code == "unknown_connection"); // every target names a real connection + } + + [Fact] + public void Prices_match_the_pre_v2_price_map_per_connection_model() + { + var snap = new RuntimeSnapshot(Import(Shape("cloud+anthropic"))); + Assert.True(ConfigPrices.TryGet(snap, "openai", "gpt-4o-mini", out var mini)); + Assert.Equal((0.00015m, 0.0006m), mini); + Assert.True(ConfigPrices.TryGet(snap, "openai", "gpt-4o", out var strong)); + Assert.Equal((0.0025m, 0.01m), strong); + Assert.True(ConfigPrices.TryGet(snap, "anthropic", "claude-haiku-4-5", out var haiku)); + Assert.Equal((0.001m, 0.005m), haiku); + + var custom = new RuntimeSnapshot(Import(Shape("cloud+custom"))); + Assert.True(ConfigPrices.TryGet(custom, "openai", "strong-1", out var s1)); + Assert.Equal((3m / 1000m, 9m / 1000m), s1); + + var local = new RuntimeSnapshot(Import(Shape("local-only"))); + Assert.True(ConfigPrices.TryGet(local, "local", "qwen3:8b", out var zero)); + Assert.Equal((0m, 0m), zero); + } + + [Fact] + public void Modes_connections_and_the_unconfigured_local_placeholder_are_explicit() + { + var cloud = Import(Shape("cloud")); + Assert.Equal(ProviderMode.LegacyCloud, cloud.Mode); + Assert.Equal("legacy-import", cloud.Origin); + Assert.Equal(new[] { "openai", "local" }, cloud.Connections.Select(c => c.Id).ToArray()); + var sensitive = cloud.Policies.Single(p => p.Id == "legacy-sensitive"); + Assert.Equal(new[] { DataClassification.Pii, DataClassification.Phi }, sensitive.Classifications); + Assert.Equal("local", sensitive.Targets.Single().ConnectionId); + Assert.Equal(LegacyImport.UnconfiguredLocalModel, sensitive.Targets.Single().ModelId); + Assert.Equal(new ModelRef("openai", "gpt-4o"), cloud.SavingsBaseline); + + // Review fix 4: the explicitly DISABLED placeholder, and PII/PHI refused at policy because of it. + var placeholder = cloud.Connections.Single(c => c.Id == "local"); + Assert.False(placeholder.Enabled); + Assert.Null(placeholder.Endpoint); + Assert.Equal(Boundary.Local, placeholder.Boundary); + Assert.Equal(ProviderKind.OpenAiCompatible, placeholder.Kind); + Assert.Equal("Local model — not configured (import placeholder)", placeholder.DisplayName); + var pm = Assert.Single(placeholder.Models); + Assert.Equal(LegacyImport.UnconfiguredLocalModel, pm.ModelId); + Assert.Equal("zero-marginal-local", pm.Price!.Basis); + var refused = PolicyEngineV2.Evaluate(new RuntimeSnapshot(cloud), DataClassification.Pii, PolicyEngineV2.LegacyInternalProfile, null, + [new ChatMessage(ChatRole.User, "x")]); + Assert.Equal(PolicyEffect.Deny, refused.Effect); + Assert.Contains("no eligible destination", refused.Reason, StringComparison.Ordinal); + Assert.Contains("connection 'local' is disabled (not configured)", refused.Reason, StringComparison.Ordinal); + Assert.Equal(new[] { "openai", "local" }, Import(Shape("cloud+anthropic")).Connections.Where(c => c.Id != "anthropic").Select(c => c.Id).ToArray()); + Assert.True(Import(Shape("cloud+local")).Connections.Single(c => c.Id == "local").Enabled); + + var localOnly = Import(Shape("local-only")); + Assert.Equal(ProviderMode.LocalOnly, localOnly.Mode); + var conn = Assert.Single(localOnly.Connections); + Assert.Equal("local", conn.Id); + Assert.Equal(Boundary.Local, conn.Boundary); + Assert.Null(localOnly.SavingsBaseline); + Assert.Equal("local-only", StartupEgress.ModeString(localOnly.Mode)); + Assert.Equal("legacy-cloud", StartupEgress.ModeString(cloud.Mode)); + } + + [Fact] + public void Identities_budgets_and_operational_settings_are_imported() + { + var cfg = Config(("OpenAI:ApiKey", "sk"), ("Budget:GlobalCapUsd", "7.5"), ("Budget:TeamCapsUsd:payments", "2"), + ("Auth:Keys:0:Key", "k0"), ("Auth:Keys:0:Principal", "svc-a"), ("Auth:Keys:0:Team", "payments"), + ("Auth:Keys:1:Key", "k1"), ("Auth:Keys:1:Principal", "svc-b"), ("Auth:Keys:1:Team", "risk"), ("Auth:Keys:1:Application", "risk-app"), + ("Auth:Keys:2:Key", "k2"), ("Auth:Keys:2:Principal", "alice@example.com"), ("Auth:Keys:2:Team", "ops"), // not a valid id → normalized + ("Cache:TtlSeconds", "30"), ("RateLimit:PerTeamPerMinute", "9"), ("Audit:PromptPreviewChars", "40")); + var v1 = Import(cfg); + + // Review fix 7: one application per key at v1 — including a principal that is not a valid id (normalized + // deterministically, exactly as the auth stage normalizes it), so no key is left unbound. + var alice = ApplicationIds.FromKey("alice@example.com"); + Assert.StartsWith("alice-example.com-", alice, StringComparison.Ordinal); + Assert.True(ConfigValidator.IsValidId(alice)); + Assert.Equal(alice, new ApiKeyRecord("k2", "alice@example.com", "ops").Application); + Assert.Equal(new[] { "svc-a", "risk-app", alice }, v1.Applications.Select(a => a.Id).ToArray()); + Assert.Equal("ops", v1.Applications.Single(a => a.Id == alice).Team); + Assert.All(v1.Applications, a => + { + Assert.False(a.ConsoleTesting); + Assert.Equal(PolicyEngineV2.LegacyInternalProfile, a.DefaultProfile); + }); + var global = v1.Budgets.Single(b => b.Scope == "global"); + Assert.Equal(7.5m, global.CapUsd); + Assert.Equal(BudgetPeriod.None, global.Period); + Assert.Equal(2m, v1.Budgets.Single(b => b.Scope == "team:payments").CapUsd); + Assert.Equal(30, v1.Settings.CacheTtlSeconds); + Assert.Equal(9, v1.Settings.RateLimitPerTeamPerMinute); + Assert.Equal(40, v1.Settings.PromptPreviewChars); + } + + [Fact] + public void Invalid_legacy_values_are_reported_not_ignored() + { + var errors = new List(); + LegacyImport.Build(Config(("OpenAI:ApiKey", "sk"), ("Budget:GlobalCapUsd", "lots"), ("Pricing:gpt-4o:InPer1M", "x"), + ("Cache:TtlSeconds", "-1")), DateTimeOffset.UtcNow, errors); + Assert.Contains(errors, e => e.StartsWith("Budget:GlobalCapUsd", StringComparison.Ordinal)); + Assert.Contains(errors, e => e.StartsWith("Pricing:gpt-4o", StringComparison.Ordinal)); + Assert.Contains(errors, e => e.StartsWith("Cache:TtlSeconds", StringComparison.Ordinal)); + } + + [Fact] + public void Demo_seeds_use_the_restrictive_defaults() + { + var cfg = Config(("OpenAI:ApiKey", "sk"), ("Local:Endpoint", "http://localhost:11434/v1"), ("Local:ModelId", "qwen3:8b"), ("Budget:GlobalCapUsd", "3"), + ("Pricing:gpt-4o-mini:InPer1M", "0.15"), ("Pricing:gpt-4o-mini:OutPer1M", "0.60")); + var errors = new List(); + var hybrid = DemoSeeds.Build(DemoSeeds.Hybrid, cfg, DateTimeOffset.UtcNow, errors); + var local = DemoSeeds.Build(DemoSeeds.LocalOnly, cfg, DateTimeOffset.UtcNow, errors); + Assert.Empty(errors); + var env = new ValidationEnvironment + { + EgressAllowList = StartupEgress.BuildAllowList(cfg), SecretAvailable = StartupEgress.SecretAvailability(cfg), + LocalEndpoints = StartupEgress.LocalEndpoints(cfg), + }; + Assert.True(ConfigValidator.Validate(hybrid, env).IsValid); + Assert.True(ConfigValidator.Validate(local, env).IsValid); + + var h = new RuntimeSnapshot(hybrid); + Assert.Equal("openai/gpt-4o-mini (fallback: ollama/qwen3:8b)", PolicyEngineV2.Summary(h, DataClassification.Public, "public-demo")); + foreach (var cls in new[] { DataClassification.Internal, DataClassification.Pii, DataClassification.Phi }) + Assert.Equal("ollama/qwen3:8b", PolicyEngineV2.Summary(h, cls, "public-demo")); + Assert.Equal("ollama/qwen3:8b", PolicyEngineV2.Summary(new RuntimeSnapshot(local), DataClassification.Public, "public-demo")); + Assert.Equal(BudgetPeriod.Monthly, hybrid.Budgets.Single().Period); + Assert.Equal(3m, hybrid.Budgets.Single().CapUsd); + } + + // Reviewer finding (T09): the hybrid seed accepted any OpenAI:ModelId but always seeded gpt-4o-mini's 0.15/0.60 + // "provider-list" rates — a custom model silently inherited another model's price, corrupting budget claims. + [Fact] + public void Hybrid_seed_refuses_a_cloud_model_without_explicit_model_bound_prices() + { + var cfg = Config(("OpenAI:ApiKey", "sk"), ("OpenAI:ModelId", "my-custom-model"), ("Local:Endpoint", "http://localhost:11434/v1"), + ("Local:ModelId", "qwen3:8b"), ("Budget:GlobalCapUsd", "3")); + var errors = new List(); + var seeded = DemoSeeds.Build(DemoSeeds.Hybrid, cfg, DateTimeOffset.UtcNow, errors); + + Assert.Contains(errors, e => e.StartsWith("Pricing:my-custom-model:InPer1M", StringComparison.Ordinal)); + var model = seeded.Connections.Single(c => c.Id == "openai").Models.Single(); + Assert.Null(model.Price); // never 0.15/0.60 inherited + } + + [Fact] + public void Hybrid_seed_retains_supplied_prices_basis_and_date_for_a_custom_model() + { + var cfg = Config(("OpenAI:ApiKey", "sk"), ("OpenAI:ModelId", "my-custom-model"), ("Local:Endpoint", "http://localhost:11434/v1"), + ("Local:ModelId", "qwen3:8b"), ("Budget:GlobalCapUsd", "3"), + ("Pricing:my-custom-model:InPer1M", "1.25"), ("Pricing:my-custom-model:OutPer1M", "5.5"), + ("Pricing:my-custom-model:Basis", "provider list price"), ("Pricing:my-custom-model:EffectiveDate", "2026-10-01")); + var errors = new List(); + var seeded = DemoSeeds.Build(DemoSeeds.Hybrid, cfg, DateTimeOffset.UtcNow, errors); + + Assert.Empty(errors); + var price = seeded.Connections.Single(c => c.Id == "openai").Models.Single().Price!; + Assert.Equal(1.25m, price.InputPer1M); + Assert.Equal(5.5m, price.OutputPer1M); + Assert.Equal("provider list price", price.Basis); + Assert.Equal(new DateOnly(2026, 10, 1), price.EffectiveDate); + } + + [Fact] + public void Local_only_seed_needs_no_cloud_price() + { + var cfg = Config(("Local:Endpoint", "http://localhost:11434/v1"), ("Local:ModelId", "qwen3:8b"), ("Budget:GlobalCapUsd", "3")); + var errors = new List(); + DemoSeeds.Build(DemoSeeds.LocalOnly, cfg, DateTimeOffset.UtcNow, errors); + Assert.Empty(errors); + } +} diff --git a/tests/Covenant.Tests/LocalOnlyModeTests.cs b/tests/Covenant.Tests/LocalOnlyModeTests.cs index 3cc5200..0897f0f 100644 --- a/tests/Covenant.Tests/LocalOnlyModeTests.cs +++ b/tests/Covenant.Tests/LocalOnlyModeTests.cs @@ -39,7 +39,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("Auth:Keys:0:Key", "k"); builder.UseSetting("Auth:Keys:0:Principal", "p"); builder.UseSetting("Auth:Keys:0:Team", "t"); - builder.UseSetting("Audit:Path", AuditPath); + CorrelationTestKit.IsolatePaths(builder, AuditPath); // Stub the local endpoint in-process; register cloud keys too, as tripwires that must stay at 0 calls. builder.ConfigureTestServices(services => services.AddSingleton(new ChatClientRegistry( diff --git a/tests/Covenant.Tests/PipelineSliceTests.cs b/tests/Covenant.Tests/PipelineSliceTests.cs index 774729d..2a7a95a 100644 --- a/tests/Covenant.Tests/PipelineSliceTests.cs +++ b/tests/Covenant.Tests/PipelineSliceTests.cs @@ -27,7 +27,8 @@ private sealed class StubChatClient(string reply) : MEAI.IChatClient yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply[half..]); yield return new MEAI.ChatResponseUpdate { - Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 })] + Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 })], + FinishReason = MEAI.ChatFinishReason.Stop, // terminal completion (review round 2: required for "served") }; } diff --git a/tests/Covenant.Tests/PolicyEngineV2Tests.cs b/tests/Covenant.Tests/PolicyEngineV2Tests.cs new file mode 100644 index 0000000..3e33924 --- /dev/null +++ b/tests/Covenant.Tests/PolicyEngineV2Tests.cs @@ -0,0 +1,343 @@ +using Covenant.Core; +using Covenant.Governance; +using Xunit; + +namespace Covenant.Tests; + +/// ADR-0013 policy engine v2 and the configuration validator: precedence, ambiguity, pause semantics, +/// eligibility (mode boundary, sensitive-cloud rule, pricing), override pinning, the honestly named length heuristic. +public sealed class PolicyEngineV2Tests +{ + private static PolicyOutcome Eval(CovenantConfig c, DataClassification cls, string? profile = null, string? model = null, string prompt = "hi") + => PolicyEngineV2.Evaluate(V2.Snap(c), cls, profile, model, [new ChatMessage(ChatRole.User, prompt)]); + + private static CovenantConfig WithPolicies(params PolicyConfigV2[] policies) => V2.Hybrid() with { Policies = policies }; + + private static ConfigValidationResult Validate(CovenantConfig c, bool secrets = true) + => ConfigValidator.Validate(c, V2.Env(secrets)); + + [Fact] + public void Demo_defaults_validate_cleanly_and_route_as_specified() + { + var c = V2.Hybrid(); + Assert.Empty(Validate(c).Errors); + + var pub = Eval(c, DataClassification.Public, "public-demo"); + Assert.Equal(new RouteTarget("openai", V2.CloudModel), pub.Route); + Assert.Equal(new[] { new RouteTarget("openai", V2.CloudModel), new RouteTarget("ollama", V2.LocalTag) }, pub.Candidates); + Assert.Equal("public", pub.PolicyId); + Assert.Equal($"Public → openai/{V2.CloudModel} (fallback: ollama/{V2.LocalTag}) · policy public v1", pub.Explanation); + + foreach (var sensitive in new[] { DataClassification.Internal, DataClassification.Pii, DataClassification.Phi }) + { + var o = Eval(c, sensitive); + Assert.Equal(PolicyEffect.Allow, o.Effect); + Assert.All(o.Candidates, t => Assert.Equal("ollama", t.AdapterKey)); // never a cloud fallback + } + } + + [Fact] + public void Profile_specific_policy_takes_precedence_over_a_classification_only_policy() + { + var c = WithPolicies( + V2.Policy("public", [DataClassification.Public], [V2.T("openai", V2.CloudModel)]), + V2.Policy("public-demo-local", [DataClassification.Public], [V2.T("ollama", V2.LocalTag)], profiles: ["public-demo"]), + V2.Policy("rest", [DataClassification.Internal, DataClassification.Pii, DataClassification.Phi], [V2.T("ollama", V2.LocalTag)])); + Assert.Empty(Validate(c).Errors); // defined precedence, not an overlap + Assert.Equal("public-demo-local", Eval(c, DataClassification.Public, "public-demo").PolicyId); + Assert.Equal("public", Eval(c, DataClassification.Public, "other-profile").PolicyId); + } + + [Fact] + public void Ambiguous_overlap_is_a_validation_error_and_a_runtime_refusal() + { + var c = WithPolicies( + V2.Policy("a", [DataClassification.Internal, DataClassification.Pii], [V2.T("ollama", V2.LocalTag)]), + V2.Policy("b", [DataClassification.Internal], [V2.T("ollama", V2.LocalTag)]), + V2.Policy("phi", [DataClassification.Phi], [V2.T("ollama", V2.LocalTag)])); + Assert.Contains(Validate(c).Errors, e => e.Code == "ambiguous_policy_overlap"); + var o = Eval(c, DataClassification.Internal); + Assert.Equal(PolicyEffect.Deny, o.Effect); + Assert.Contains("ambiguous", o.Reason, StringComparison.Ordinal); + Assert.Equal(PolicyEffect.Allow, Eval(c, DataClassification.Pii).Effect); // only one matches Pii + } + + [Fact] + public void Profile_specific_policies_with_disjoint_profiles_do_not_overlap() + { + var c = WithPolicies( + V2.Policy("p1", [DataClassification.Public], [V2.T("ollama", V2.LocalTag)], profiles: ["public-demo"]), + V2.Policy("p2", [DataClassification.Public], [V2.T("openai", V2.CloudModel)], profiles: ["internal-default"]), + V2.Policy("rest", [DataClassification.Internal, DataClassification.Pii, DataClassification.Phi], [V2.T("ollama", V2.LocalTag)])); + Assert.DoesNotContain(Validate(c).Errors, e => e.Code == "ambiguous_policy_overlap"); + var same = c with { Policies = [.. c.Policies, V2.Policy("p3", [DataClassification.Public], [V2.T("ollama", V2.LocalTag)], profiles: ["public-demo"])] }; + Assert.Contains(Validate(same).Errors, e => e.Code == "ambiguous_policy_overlap"); + } + + [Fact] + public void Paused_policy_denies_its_matching_traffic() + { + var c = V2.Hybrid(tweak: x => x with { Policies = x.Policies.Select(p => p.Id == "internal" ? p with { Paused = true } : p).ToList() }); + var o = Eval(c, DataClassification.Internal); + Assert.Equal(PolicyEffect.Deny, o.Effect); + Assert.Equal("policy 'internal' is paused", o.Reason); + Assert.Equal("internal", o.PolicyId); + } + + [Fact] + public void Disabled_policy_does_not_match_and_falls_through_to_refusal() + { + var c = V2.Hybrid(tweak: x => x with { Policies = x.Policies.Select(p => p.Id == "internal" ? p with { Enabled = false } : p).ToList() }); + Assert.Contains("no permitted route", Eval(c, DataClassification.Internal).Reason, StringComparison.Ordinal); + Assert.Contains(Validate(c).Warnings, w => w.Code == "no_route_for_classification"); + } + + [Fact] + public void Paused_route_is_skipped_and_the_next_approved_target_serves() + { + var c = WithPolicies( + V2.Policy("public", [DataClassification.Public], [V2.T("openai", V2.CloudModel, paused: true), V2.T("ollama", V2.LocalTag)]), + V2.Policy("rest", [DataClassification.Internal, DataClassification.Pii, DataClassification.Phi], [V2.T("ollama", V2.LocalTag)])); + var o = Eval(c, DataClassification.Public, "public-demo"); + Assert.Equal(new RouteTarget("ollama", V2.LocalTag), o.Route); + var excluded = Assert.Single(o.Excluded); + Assert.Equal("route paused", excluded.Reason); + + var allPaused = WithPolicies( + V2.Policy("public", [DataClassification.Public], [V2.T("openai", V2.CloudModel, paused: true), V2.T("ollama", V2.LocalTag, paused: true)]), + V2.Policy("rest", [DataClassification.Internal, DataClassification.Pii, DataClassification.Phi], [V2.T("ollama", V2.LocalTag)])); + var refused = Eval(allPaused, DataClassification.Public, "public-demo"); + Assert.Equal(PolicyEffect.Deny, refused.Effect); + Assert.Contains("no eligible destination", refused.Reason, StringComparison.Ordinal); + } + + [Fact] + public void Local_only_mode_excludes_cloud_targets_even_if_a_cloud_connection_is_enabled() + { + var c = V2.Hybrid() with { Mode = ProviderMode.LocalOnly }; + Assert.Contains(Validate(c).Errors, e => e.Code == "cloud_in_local_only"); // validation refuses it … + var o = Eval(c, DataClassification.Public, "public-demo"); // … and the engine never selects it + Assert.Equal(new RouteTarget("ollama", V2.LocalTag), o.Route); + Assert.Contains(o.Excluded, x => x.Target.AdapterKey == "openai" && x.Reason.Contains("local-only", StringComparison.Ordinal)); + } + + /// Review fix 5: no AllowSensitiveCloud escape hatch. A PII/PHI policy listing a cloud target is a + /// validation ERROR (sensitive_cloud_target), and the engine still excludes cloud targets for PII/PHI. + [Fact] + public void Sensitive_data_never_reaches_cloud_and_a_sensitive_policy_with_a_cloud_target_is_invalid() + { + var c = WithPolicies( + V2.Policy("public", [DataClassification.Public, DataClassification.Internal], [V2.T("ollama", V2.LocalTag)]), + V2.Policy("sensitive", [DataClassification.Pii, DataClassification.Phi], [V2.T("openai", V2.CloudModel), V2.T("ollama", V2.LocalTag)])); + var error = Assert.Single(Validate(c).Errors, e => e.Code == "sensitive_cloud_target"); + Assert.Equal("policies[1].targets[0]", error.Path); + var o = Eval(c, DataClassification.Pii); // defensive: engine excludes it anyway + Assert.Equal(new[] { new RouteTarget("ollama", V2.LocalTag) }, o.Candidates); + Assert.Contains(o.Excluded, x => x.Target.AdapterKey == "openai" && x.Reason.Contains("never routed to a cloud", StringComparison.Ordinal)); + + var onlyCloud = WithPolicies( + V2.Policy("public", [DataClassification.Public, DataClassification.Internal], [V2.T("ollama", V2.LocalTag)]), + V2.Policy("sensitive", [DataClassification.Pii, DataClassification.Phi], [V2.T("openai", V2.CloudModel)])); + Assert.Contains(Validate(onlyCloud).Errors, e => e.Code == "sensitive_cloud_target"); + Assert.Equal(PolicyEffect.Deny, Eval(onlyCloud, DataClassification.Phi).Effect); // refused, never sent to cloud + Assert.Equal(PolicyEffect.Deny, Eval(onlyCloud, DataClassification.Pii, model: V2.CloudModel).Effect); + Assert.Equal(PolicyEffect.Deny, Eval(onlyCloud with { Mode = ProviderMode.LegacyCloud }, DataClassification.Pii).Effect); + Assert.Null(typeof(PolicyConfigV2).GetProperty("AllowSensitiveCloud")); // the escape hatch is gone + } + + /// Review fix 9: a paused profile-specific policy refuses its traffic; it never falls through to the + /// less specific (classification-only) policy that would otherwise serve it. + [Fact] + public void Paused_specific_policy_never_falls_through_to_a_less_specific_policy() + { + var c = WithPolicies( + V2.Policy("public-generic", [DataClassification.Public], [V2.T("openai", V2.CloudModel)]), + V2.Policy("public-demo-only", [DataClassification.Public], [V2.T("ollama", V2.LocalTag)], profiles: ["public-demo"], paused: true), + V2.Policy("rest", [DataClassification.Internal, DataClassification.Pii, DataClassification.Phi], [V2.T("ollama", V2.LocalTag)])); + Assert.Empty(Validate(c).Errors); + var o = Eval(c, DataClassification.Public, "public-demo"); + Assert.Equal(PolicyEffect.Deny, o.Effect); + Assert.Equal("public-demo-only", o.PolicyId); + Assert.Equal("policy 'public-demo-only' is paused", o.Reason); + Assert.Null(o.Route); + // With an override naming the generic policy's target, still refused (the paused policy decided). + Assert.Equal(PolicyEffect.Deny, Eval(c, DataClassification.Public, "public-demo", model: V2.CloudModel).Effect); + // Other profiles are unaffected: the generic policy serves them. + Assert.Equal("public-generic", Eval(c, DataClassification.Public, "internal-default").PolicyId); + } + + /// Review fix 2: a bare model id eligible on two connections is REFUSED (never first-wins); + /// connection/model resolves exactly; a bare id eligible on exactly one connection still pins. + [Fact] + public void Ambiguous_bare_model_override_is_refused_and_connection_slash_model_resolves_exactly() + { + var c = V2.Hybrid() with + { + Connections = [V2.Ollama(id: "local-a"), V2.Ollama(id: "local-b"), V2.OpenAi()], + Policies = + [ + V2.Policy("public", [DataClassification.Public], [V2.T("openai", V2.CloudModel), V2.T("local-a", V2.LocalTag)]), + V2.Policy("internal", [DataClassification.Internal, DataClassification.Pii, DataClassification.Phi], + [V2.T("local-a", V2.LocalTag), V2.T("local-b", V2.LocalTag)]), + ], + }; + Assert.Empty(Validate(c).Errors); + + var ambiguous = Eval(c, DataClassification.Internal, model: V2.LocalTag); + Assert.Equal(PolicyEffect.Deny, ambiguous.Effect); + Assert.Equal($"model id '{V2.LocalTag}' is ambiguous across connections local-a, local-b — use connection/model", ambiguous.Reason); + Assert.Null(ambiguous.Route); + + var exactB = Eval(c, DataClassification.Internal, model: $"local-b/{V2.LocalTag}"); + Assert.Equal(new[] { new RouteTarget("local-b", V2.LocalTag) }, exactB.Candidates); // pinned, no fallback + var exactA = Eval(c, DataClassification.Internal, model: $"LOCAL-A/{V2.LocalTag}"); + Assert.Equal(new RouteTarget("local-a", V2.LocalTag), exactA.Route); + + // Only ONE eligible target carries the bare id under the Public policy ⇒ it resolves. + Assert.Equal(new RouteTarget("local-a", V2.LocalTag), Eval(c, DataClassification.Public, "public-demo", model: V2.LocalTag).Route); + + // Ambiguity is about ELIGIBLE targets: pause local-b and the bare id resolves to local-a. + var paused = c with { Policies = c.Policies.Select(p => p.Id != "internal" ? p : p with { Targets = [V2.T("local-a", V2.LocalTag), V2.T("local-b", V2.LocalTag, paused: true)] }).ToList() }; + Assert.Equal(new RouteTarget("local-a", V2.LocalTag), Eval(paused, DataClassification.Internal, model: V2.LocalTag).Route); + } + + [Fact] + public void Model_override_must_be_an_eligible_target_and_pins_it() + { + var c = V2.Hybrid(); + var pinned = Eval(c, DataClassification.Public, "public-demo", model: V2.LocalTag); + Assert.Equal(new[] { new RouteTarget("ollama", V2.LocalTag) }, pinned.Candidates); // no fallback after a pin + Assert.Equal(new RouteTarget("ollama", V2.LocalTag), Eval(c, DataClassification.Public, "public-demo", model: $"ollama/{V2.LocalTag}").Route); + + var notInPolicy = Eval(c, DataClassification.Internal, model: V2.CloudModel); + Assert.Equal(PolicyEffect.Deny, notInPolicy.Effect); + Assert.Equal($"model '{V2.CloudModel}' not permitted for classification 'Internal'", notInPolicy.Reason); + + var paused = c with { Policies = c.Policies.Select(p => p.Id != "public" ? p : p with { Targets = [V2.T("openai", V2.CloudModel, paused: true), V2.T("ollama", V2.LocalTag)] }).ToList() }; + var excludedPin = Eval(paused, DataClassification.Public, "public-demo", model: V2.CloudModel); + Assert.Equal(PolicyEffect.Deny, excludedPin.Effect); + Assert.Contains("route paused", excludedPin.Reason, StringComparison.Ordinal); + } + + [Fact] + public void Length_heuristic_is_named_honestly_and_uses_the_configured_threshold() + { + var c = WithPolicies( + V2.Policy("general", [DataClassification.Public, DataClassification.Internal], + [V2.T("openai", V2.CloudModel), V2.T("openai", "gpt-4o")], strategy: RoutingStrategy.LengthHeuristic, threshold: 10), + V2.Policy("sensitive", [DataClassification.Pii, DataClassification.Phi], [V2.T("ollama", V2.LocalTag)])); + + var shortO = Eval(c, DataClassification.Internal, prompt: new string('a', 40)); // 10 tokens: not above 10 + Assert.Equal(V2.CloudModel, shortO.Route!.ModelId); + var longO = Eval(c, DataClassification.Internal, prompt: new string('a', 44)); // 11 tokens: above 10 + Assert.Equal("gpt-4o", longO.Route!.ModelId); + Assert.Contains("length-based heuristic", longO.Reason, StringComparison.Ordinal); + Assert.Contains("threshold 10", longO.Reason, StringComparison.Ordinal); + Assert.Equal(new[] { "gpt-4o", V2.CloudModel }, longO.Candidates.Select(t => t.ModelId).ToArray()); + } + + [Fact] + public void Unpriced_paid_target_under_a_hard_budget_is_ineligible_and_invalid() + { + var c = V2.Hybrid() with { Connections = [V2.Ollama(), V2.OpenAi(priced: false)] }; + Assert.Contains(Validate(c).Errors, e => e.Code == "unpriced_paid_target_under_hard_budget"); + var o = Eval(c, DataClassification.Public, "public-demo"); + Assert.Equal(new RouteTarget("ollama", V2.LocalTag), o.Route); + Assert.Contains(o.Excluded, x => x.Reason.Contains("unpriced", StringComparison.Ordinal)); + } + + /// Review fix 4: no mode bypass. Unknown and disabled connections are never eligible — legacy-cloud + /// included — and unknown_connection is always a validation error. + [Fact] + public void Disabled_or_unknown_connection_targets_are_ineligible_in_every_mode() + { + foreach (var mode in new[] { ProviderMode.Hybrid, ProviderMode.LegacyCloud, ProviderMode.LocalOnly }) + { + var disabled = V2.Hybrid() with { Mode = mode, Connections = [V2.Ollama(enabled: false), V2.OpenAi(enabled: false)] }; + var d = Eval(disabled, DataClassification.Internal); + Assert.Equal(PolicyEffect.Deny, d.Effect); + Assert.Contains(d.Excluded, x => x.Reason.Contains("is disabled", StringComparison.Ordinal)); + + var unknown = V2.Hybrid() with { Mode = mode, Connections = [V2.OpenAi(enabled: mode != ProviderMode.LocalOnly)] }; // ollama removed + var u = Eval(unknown, DataClassification.Internal); + Assert.Equal(PolicyEffect.Deny, u.Effect); + Assert.Contains("unknown connection 'ollama'", u.Reason, StringComparison.Ordinal); + Assert.Contains(Validate(unknown).Errors, e => e.Code == "unknown_connection"); + Assert.DoesNotContain(Validate(unknown).Warnings, w => w.Code == "unknown_connection"); + } + } + + /// Review fix 6: Boundary.Local must be bound to a startup-approved local endpoint; cloud SDK kinds are + /// always Cloud. A cloud host relabelled Local (to reach PII/PHI) is boundary_not_approved. + [Fact] + public void Local_boundary_requires_a_startup_approved_endpoint() + { + var relabelled = new ConnectionConfig + { + Id = "sneaky", DisplayName = "Cloud host labelled local", Kind = ProviderKind.OpenAiCompatible, Boundary = Boundary.Local, + Endpoint = "https://api.openai.com/v1", Enabled = true, SecretRef = "OpenAI:ApiKey", + Models = [new ModelConfig { ModelId = "gpt-4o-mini", Price = new PriceConfig { InputPer1M = 0m, OutputPer1M = 0m, Basis = "zero-marginal-local" } }], + }; + var c = V2.Hybrid() with + { + Connections = [V2.Ollama(), V2.OpenAi(), relabelled], + Policies = [.. V2.Hybrid().Policies.Where(p => p.Id != "sensitive"), + V2.Policy("sensitive", [DataClassification.Pii, DataClassification.Phi], [V2.T("sneaky", "gpt-4o-mini")])], + }; + var errors = Validate(c).Errors; + var e = Assert.Single(errors, x => x.Code == "boundary_not_approved"); + Assert.Equal("connections[2].boundary", e.Path); + Assert.DoesNotContain(errors, x => x.Code == "endpoint_not_allow_listed"); // the host IS allow-listed — only the label is refused + + // The same endpoint labelled Cloud is fine (and then a PII/PHI policy cannot use it). + var honest = c with { Connections = [V2.Ollama(), V2.OpenAi(), relabelled with { Boundary = Boundary.Cloud }] }; + Assert.DoesNotContain(Validate(honest).Errors, x => x.Code == "boundary_not_approved"); + Assert.Contains(Validate(honest).Errors, x => x.Code == "sensitive_cloud_target"); + + // Cloud SDK kinds are always Cloud. + var openAiLocal = V2.Hybrid() with { Connections = [V2.Ollama(), V2.OpenAi() with { Boundary = Boundary.Local }] }; + Assert.Contains(Validate(openAiLocal).Errors, x => x.Code == "boundary_not_approved" && x.Path == "connections[1].boundary"); + + // An approved local endpoint passes; the same Ollama on an unapproved host does not. + Assert.DoesNotContain(Validate(V2.Hybrid()).Errors, x => x.Code == "boundary_not_approved"); + var otherHost = V2.Hybrid() with { Connections = [V2.Ollama() with { Endpoint = "http://10.1.2.3:11434/v1" }, V2.OpenAi()] }; + Assert.Contains(ConfigValidator.Validate(otherHost, V2.Env(true, "10.1.2.3:11434")).Errors, x => x.Code == "boundary_not_approved"); + } + + [Fact] + public void Validator_reports_contract_codes() + { + var bad = V2.Hybrid() with + { + Connections = + [ + V2.Ollama() with { Endpoint = "http://10.9.9.9:11434/v1" }, // not allow-listed + V2.OpenAi() with { Models = [new ModelConfig { ModelId = V2.CloudModel, Price = new PriceConfig { InputPer1M = 1, OutputPer1M = 1, Basis = "x" } }] }, + ], + Applications = + [ + new ApplicationConfig { Id = "a1", Team = "t", Enabled = true, ConsoleTesting = true, GrantedProfiles = ["nope"], DefaultProfile = "public-demo" }, + new ApplicationConfig { Id = "a1", Team = "t", Enabled = true, ConsoleTesting = true, GrantedProfiles = [] }, + ], + Policies = + [ + V2.Policy("public", [DataClassification.Public], [V2.T("openai", "gpt-4o")]), // model not on the connection + V2.Policy("rest", [DataClassification.Internal, DataClassification.Pii, DataClassification.Phi], [V2.T("ollama", V2.LocalTag)]), + ], + Budgets = [new BudgetConfigV2 { Id = "b", Scope = "teams:x", CapUsd = 1 }], + }; + var codes = Validate(bad, secrets: false).Errors.Select(e => e.Code).ToHashSet(); + foreach (var expected in new[] { "endpoint_not_allow_listed", "secret_unavailable", "profile_not_found", "default_profile_not_granted", + "duplicate_id", "unknown_model", "invalid_budget_scope", "missing_global_budget" }) + Assert.Contains(expected, codes); + } + + [Fact] + public void Summary_states_the_effective_route_or_refusal() + { + var c = V2.Hybrid(); + Assert.Equal($"openai/{V2.CloudModel} (fallback: ollama/{V2.LocalTag})", PolicyEngineV2.Summary(V2.Snap(c), DataClassification.Public, "public-demo")); + var noLocal = c with { Connections = [V2.Ollama(enabled: false), V2.OpenAi()] }; + Assert.StartsWith("refused:", PolicyEngineV2.Summary(V2.Snap(noLocal), DataClassification.Phi, null), StringComparison.Ordinal); + } +} diff --git a/tests/Covenant.Tests/ProviderClientConstructionTests.cs b/tests/Covenant.Tests/ProviderClientConstructionTests.cs new file mode 100644 index 0000000..03cfe96 --- /dev/null +++ b/tests/Covenant.Tests/ProviderClientConstructionTests.cs @@ -0,0 +1,134 @@ +using System.Diagnostics; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Microsoft.Extensions.Configuration; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// Review fix 11 (ADR-0011 "Provider clients"): SDK clients are built with automatic redirects OFF, +/// SDK-internal retries OFF and the connection's timeout as the network timeout — exercised against real loopback +/// sockets through the real OpenAI and Anthropic SDK clients. And a client that cannot be built for an enabled, +/// referenced connection is a validation error (client_unbuildable), never a silently skipped target. +public sealed class ProviderClientConstructionTests +{ + private static IConfiguration Secrets() => new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["Anthropic:ApiKey"] = "ak-test-not-real", + ["OpenAI:ApiKey"] = "sk-test-not-real", + }).Build(); + + private static ConnectionConfig Compat(string endpoint, int timeoutSeconds = 30) => new() + { + Id = "compat", DisplayName = "loopback", Kind = ProviderKind.OpenAiCompatible, Boundary = Boundary.Local, + Endpoint = endpoint, Enabled = true, TimeoutSeconds = timeoutSeconds, + Models = [new ModelConfig { ModelId = "m1", Price = new PriceConfig { InputPer1M = 0, OutputPer1M = 0, Basis = "zero-marginal-local" } }], + }; + + private static ConnectionConfig Claude(string baseUrl, int timeoutSeconds = 30) => new() + { + Id = "claude", DisplayName = "loopback anthropic", Kind = ProviderKind.Anthropic, Boundary = Boundary.Cloud, + Endpoint = baseUrl, Enabled = true, SecretRef = "Anthropic:ApiKey", TimeoutSeconds = timeoutSeconds, + Models = [new ModelConfig { ModelId = "claude-test", Price = new PriceConfig { InputPer1M = 1, OutputPer1M = 1, Basis = "x" } }], + }; + + private static CovenantConfig With(params ConnectionConfig[] connections) => V2.Hybrid() with + { + Connections = connections, + Policies = [V2.Policy("all", [DataClassification.Public, DataClassification.Internal], + connections.Select(c => V2.T(c.Id, c.Models[0].ModelId)).ToArray())], + }; + + private static MEAI.IChatClient Build(ConnectionConfig conn, params string[] egress) + { + var set = new SdkProviderClientFactory(Secrets(), new HashSet(egress, StringComparer.OrdinalIgnoreCase)).Build(With(conn)); + Assert.Empty(set.Skipped); + Assert.True(set.TryResolve(conn.Id, conn.Models[0].ModelId, out var client)); + return client; + } + + private static Task Call(MEAI.IChatClient client) + => client.GetResponseAsync([new MEAI.ChatMessage(MEAI.ChatRole.User, "hi")]); + + [Fact] + public void Handler_never_follows_redirects() + { + using var handler = SdkProviderClientFactory.CreateHandler(Compat("http://127.0.0.1:1/v1")); + Assert.False(handler.AllowAutoRedirect); + using var http = SdkProviderClientFactory.CreateHttpClient(Compat("http://127.0.0.1:1/v1")); + Assert.Equal(Timeout.InfiniteTimeSpan, http.Timeout); // the SDK option (connection timeout) governs + } + + [Fact] + public async Task OpenAi_compatible_client_does_not_retry_a_503_internally() + { + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(503, """{"error":{"message":"busy"}}""")); + var client = Build(Compat(server.V1), server.Authority); + await Assert.ThrowsAnyAsync(() => Call(client)); + await Task.Delay(300); // a default SDK retry would arrive well within this + Assert.Single(server.Requests); // exactly one attempt: retries are Covenant's own + } + + [Fact] + public async Task OpenAi_compatible_client_does_not_follow_a_redirect_off_the_approved_endpoint() + { + using var elsewhere = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(200, """{"id":"x","choices":[]}""")); + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(302, "", + extraHeaders: $"Location: http://127.0.0.1:{elsewhere.Port}/v1/chat/completions\r\n")); + var client = Build(Compat(server.V1), server.Authority); + await Assert.ThrowsAnyAsync(() => Call(client)); + Assert.Single(server.Requests); + Assert.Equal(0, elsewhere.Connections); // the redirect target was never contacted + } + + [Fact] + public async Task OpenAi_compatible_client_enforces_the_connection_timeout() + { + using var server = new LoopbackHttpServer(_ => null); // accepts, never answers + var client = Build(Compat(server.V1, timeoutSeconds: 1), server.Authority); + var sw = Stopwatch.StartNew(); + await Assert.ThrowsAnyAsync(() => Call(client)); + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(15), $"took {sw.Elapsed}"); + Assert.Single(server.Requests); // and no retry after the timeout + } + + [Fact] + public async Task Anthropic_client_does_not_retry_and_does_not_follow_redirects() + { + using var busy = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(503, """{"type":"error","error":{"type":"overloaded_error","message":"busy"}}""")); + var c1 = Build(Claude($"http://127.0.0.1:{busy.Port}"), busy.Authority); + await Assert.ThrowsAnyAsync(() => Call(c1)); + await Task.Delay(300); + Assert.Single(busy.Requests); + + using var elsewhere = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(200, "{}")); + using var redirecting = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(307, "", + extraHeaders: $"Location: http://127.0.0.1:{elsewhere.Port}/v1/messages\r\n")); + var c2 = Build(Claude($"http://127.0.0.1:{redirecting.Port}"), redirecting.Authority); + await Assert.ThrowsAnyAsync(() => Call(c2)); + Assert.Single(redirecting.Requests); + Assert.Equal(0, elsewhere.Connections); + } + + /// An enabled connection referenced by an enabled policy that gets no client (here: its endpoint is not + /// on the execution-time egress list) makes the candidate invalid — client_unbuildable — instead of being skipped. + [Fact] + public void Unbuildable_referenced_connection_is_a_validation_error_not_a_silent_skip() + { + var conn = Compat("http://127.0.0.1:11434/v1"); + var cfg = With(conn, V2.Ollama(id: "spare") with { Enabled = false }); + var set = new SdkProviderClientFactory(Secrets(), new HashSet(StringComparer.OrdinalIgnoreCase)).Build(cfg); + Assert.Contains(set.Skipped, s => s.ConnectionId == "compat"); + var issue = Assert.Single(ProviderClientSet.UnbuildableIssues(cfg, set)); + Assert.Equal("client_unbuildable", issue.Code); + Assert.Equal("connections[0]", issue.Path); + + // Disabled or unreferenced connections are not errors; a fully built set has none. + var ok = new SdkProviderClientFactory(Secrets(), new HashSet(StringComparer.OrdinalIgnoreCase) { "127.0.0.1:11434" }).Build(cfg); + Assert.Empty(ProviderClientSet.UnbuildableIssues(cfg, ok)); + ok.Dispose(); + set.Dispose(); + } +} diff --git a/tests/Covenant.Tests/ProviderProbeTests.cs b/tests/Covenant.Tests/ProviderProbeTests.cs index e78c13c..d107727 100644 --- a/tests/Covenant.Tests/ProviderProbeTests.cs +++ b/tests/Covenant.Tests/ProviderProbeTests.cs @@ -292,7 +292,7 @@ public async Task Applied_endpoint_probe_success_then_failure_updates_catalog_he b.UseSetting("Admin:Token", CorrelationTestKit.AdminToken); b.UseSetting("Budget:GlobalCapUsd", "10"); b.UseSetting("Auth:AllowAnonymous", "true"); - b.UseSetting("Audit:Path", audit); + CorrelationTestKit.IsolatePaths(b, audit); b.UseSetting("Local:Endpoint", server.V1); b.UseSetting("Local:ModelId", "qwen3:8b"); }); diff --git a/tests/Covenant.Tests/ReviewRound2Tests.cs b/tests/Covenant.Tests/ReviewRound2Tests.cs new file mode 100644 index 0000000..3ecf11c --- /dev/null +++ b/tests/Covenant.Tests/ReviewRound2Tests.cs @@ -0,0 +1,950 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using Covenant.Adapters; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +// Review round 2 (backend) regressions — docs/verification-2026-10-16/v2/CODEX-REVIEW.txt. Every test here FAILS on +// 96deed5 (behaviourally, or because the evidence field it asserts did not exist) and passes with the fix. + +/// Ledger store whose appends can be made to fail (injected IOException) — B4. +internal sealed class FlakyLedgerStore : ILedgerStore +{ + public InMemoryLedgerStore Inner { get; } = new(); + public Func, bool> Fail { get; set; } = _ => false; + public int Failures { get; private set; } + + public IReadOnlyList Records => Inner.Records; + + public void Append(IReadOnlyList records) + { + if (Fail(records)) + { + Failures++; + throw new IOException("injected ledger write failure"); + } + Inner.Append(records); + } + + /// Fails the next appends that contain a record with . + public void FailNext(string op, int count = 1) + { + int left = count; + Fail = recs => recs.Any(r => r.Op == op) && left-- > 0; + } +} + +internal sealed class ThrowingStage : IPipelineStage +{ + public Task InvokeAsync(InferenceContext context, PipelineDelegate next, CancellationToken cancellationToken) + => throw new InvalidOperationException("downstream stage failure (injected)"); +} + +internal static class Round2 +{ + public static StubChatClient Mini() => new("mini reply"); + + /// Hybrid fallback config (Public → openai/gpt-4o-mini, openai/gpt-4o, ollama/qwen3:8b), cache optional. + public static CovenantConfig Config(int maxAttempts = 3, int deadlineMs = 60_000, int cacheTtl = 0, Func? tweak = null) + => V2Rig.FallbackConfig(new RetrySettings { MaxAttempts = maxAttempts, DeadlineMs = deadlineMs }, tweak: c => + { + var x = c with { Settings = new OperationalSettings { CacheTtlSeconds = cacheTtl } }; + return tweak is null ? x : tweak(x); + }); + + /// The Host's stage order with optional extra stages appended after attribution. + public static (InferencePipeline Pipeline, V2Rig.ListSink Sink) Pipeline(BudgetLedger ledger, IReadOnlyDictionary clients, + params IPipelineStage[] after) + { + var sink = new V2Rig.ListSink(); + var kill = new KillSwitch(); + var stages = new List + { + new AuditStage(sink), + new AuthStage(new AuthConfig { AllowAnonymous = false, Keys = [new ApiKeyRecord("demo-key", "demo-service", "platform", "demo-app")] }), + new ShapeStage(), + new ClassifyStage(new RegexDataClassifier()), + new PolicyStage(new PolicyEngine(new PolicyConfig { AllowedRoutes = new Dictionary>() })), + new CacheStage(new ResponseCache(), new CacheConfig()), + new RateLimitStage(new RateCounter(), new RateCounter(), new RateLimitConfig()), + new PauseStage(kill), + new BudgetStage(kill, ledger), + new ProviderCallStage(new Covenant.Adapters.ChatClientRegistry(clients), new ProviderHealth(), classifier: SdkProviderFailureClassifier.Shared), + new AttributionStage(new PriceBook(new Dictionary())), + }; + stages.AddRange(after); + return (new InferencePipeline(stages), sink); + } + + public static InferenceContext Ctx(RuntimeSnapshot snapshot, string prompt, string profile = "public-demo", bool stream = false) + { + var ctx = new InferenceContext(new InferenceRequest("caller", [new ChatMessage(ChatRole.User, prompt)], null, + new AttributionTags("self-declared", "wf", "uc"), Stream: stream, Credential: "demo-key", + RequestId: $"req_{Guid.NewGuid():n}", RequestedProfile: profile)); + ctx.Configuration = snapshot; + ctx.ConfigVersion = snapshot.Version; + return ctx; + } +} + +/// B1 — a stream counts as served ONLY with a terminal finish reason and no error. +public sealed class StreamCompletionTests +{ + private readonly StubChatClient _mini = new("mini reply"); + private readonly StubChatClient _strong = new("strong reply"); + private readonly StubChatClient _local = new("local reply"); + private readonly ResponseCache _cache = new(); + + private V2Rig Rig() => V2Rig.Build(Round2.Config(cacheTtl: 300), new Dictionary + { + [$"openai:{V2.CloudModel}"] = _mini, + ["openai:gpt-4o"] = _strong, + [$"ollama:{V2.LocalTag}"] = _local, + }, cache: _cache); + + [Fact] + public async Task Stream_ending_without_a_finish_reason_is_an_incomplete_stream_provider_failure_never_served_cached_or_continued() + { + _mini.Then(StubChatClient.Mode.StreamNoFinish).Then(StubChatClient.Mode.Serve); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + + Assert.True(ctx.IsDenied); + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(TraceReasons.IncompleteStream, ctx.DenialCode); + Assert.Null(ctx.Response); + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.Equal("UpstreamFailure", e.DenialKind); + Assert.Null(e.ServedByModel); + Assert.Equal(0, _strong.Calls + _local.Calls); // no fallback: content was emitted + Assert.Equal("partial mini reply".Length, ctx.PartialOutputChars); + Assert.Equal("partial mini reply".Length, e.PartialOutputChars); // partial output recorded + var a = Assert.Single(e.Attempts!); + Assert.Equal("failed", a.Outcome); + Assert.Equal("incomplete_stream", a.ErrorClass); + Assert.Equal("estimated_failed_call", a.CostBasis); // charged its estimate + Assert.True(a.CostUsd > 0m); + Assert.Equal(a.ReservedUsd, a.CostUsd); + Assert.Equal(0, rig.Ledger.OpenReservations); + Assert.Equal("failed", rig.Health.Get($"openai:{V2.CloudModel}").State); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "provider" && t.AttemptId == "att_1" && t.State == TraceStates.Failed + && t.ReasonCode == TraceReasons.IncompleteStream); + + // Never cached: the identical request calls the provider again. + var (again, e2) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + Assert.False(again.IsDenied, again.DenialReason); + Assert.False(e2.CacheHit); + Assert.Equal(2, _mini.Calls); + } + + [Fact] + public async Task Stream_throwing_mid_stream_is_terminal_partial_recorded_and_never_cached() + { + _mini.Then(StubChatClient.Mode.StreamThenThrow).Then(StubChatClient.Mode.Serve); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(0, _strong.Calls + _local.Calls); + Assert.Equal("partial ".Length, e.PartialOutputChars); + Assert.Equal("5xx", Assert.Single(e.Attempts!).ErrorClass); + var (_, e2) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + Assert.False(e2.CacheHit); + Assert.Equal(2, _mini.Calls); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Finish_reason_length_is_served_and_recorded_as_truncated(bool stream) + { + _mini.Then(StubChatClient.Mode.ServeLength); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: stream); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal("length", ctx.Response!.FinishReason); + Assert.True(Assert.Single(e.Attempts!).Truncated); + Assert.Null(e.PartialOutputChars); + } + + [Fact] + public async Task Host_SSE_relays_the_incomplete_stream_as_upstream_error_and_never_finish_reason_stop() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + factory.Cloud.Then(StubChatClient.Mode.StreamNoFinish).Then(StubChatClient.Mode.Serve); + using var app = factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + app.DefaultRequestHeaders.Add("X-Covenant-Profile", "public-demo"); + + using var resp = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this public announcement.", stream: true)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); // headers committed with the first delta + var body = await resp.Content.ReadAsStringAsync(); + Assert.Contains("partial ", body, StringComparison.Ordinal); + Assert.Contains("\"upstream_error\"", body, StringComparison.Ordinal); + Assert.DoesNotContain("\"finish_reason\":\"stop\"", body, StringComparison.Ordinal); + Assert.EndsWith("data: [DONE]\n\n", body, StringComparison.Ordinal); + var e = await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(resp)); + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.Equal("UpstreamFailure", e.DenialKind); + Assert.Equal(0, factory.Local.Calls); // no fallback after content + + // The completed stream still ends with the provider's own finish reason. + using var ok = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this public announcement.", stream: true)); + var okBody = await ok.Content.ReadAsStringAsync(); + Assert.Contains("\"finish_reason\":\"stop\"", okBody, StringComparison.Ordinal); + Assert.DoesNotContain("upstream_error", okBody, StringComparison.Ordinal); + } + + // Reviewer HTTP finding: a legitimately completed EMPTY stream was audited Allow/served but answered 403 "no response", + // because the endpoint treated "no delta written" as "denied". It must be a 200 SSE with the terminal chunk + [DONE]. + [Fact] + public async Task Host_SSE_completed_empty_stream_is_a_successful_200_not_a_denial() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + factory.Cloud.Then(StubChatClient.Mode.StreamEmptyComplete); + using var app = factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + app.DefaultRequestHeaders.Add("X-Covenant-Profile", "public-demo"); + + using var resp = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this public announcement.", stream: true)); + var body = await resp.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + Assert.Equal("text/event-stream", resp.Content.Headers.ContentType?.MediaType); + Assert.Contains("\"finish_reason\":\"stop\"", body, StringComparison.Ordinal); + Assert.DoesNotContain("upstream_error", body, StringComparison.Ordinal); + Assert.EndsWith("data: [DONE]\n\n", body, StringComparison.Ordinal); + var e = await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(resp)); + Assert.Equal(PolicyEffect.Allow, e.Effect); // evidence and HTTP outcome agree + } +} + +/// B2 — request-level CostBasis over the charged attempts. +public sealed class AggregateCostBasisTests +{ + private static AttemptRecord A(string basis, decimal cost) => new() { AttemptId = "a", ConnectionId = "c", ModelId = "m", CostBasis = basis, CostUsd = cost }; + + [Fact] + public void Reported_only_when_every_charged_attempt_is_reported_else_the_shared_basis_else_mixed() + { + Assert.Equal("reported", CostBases.Aggregate([A("reported", 0.1m)], "reported")); + Assert.Equal("estimated_failed_call", CostBases.Aggregate([A("estimated_failed_call", 0.1m), A("estimated_failed_call", 0.2m)], "estimated_failed_call")); + Assert.Equal("mixed", CostBases.Aggregate([A("estimated_failed_call", 0.1m), A("reported", 0.2m)], "reported")); + Assert.Equal("reported", CostBases.Aggregate([A("estimated_failed_call", 0m), A("reported", 0.2m)], "reported")); // $0 is not a charge + Assert.Equal("zero_priced", CostBases.Aggregate([A("zero_priced", 0m)], "zero_priced")); // nothing charged + } + + [Fact] + public async Task Failed_estimated_attempt_plus_reported_fallback_is_mixed_in_the_audit_record() + { + var mini = new StubChatClient("mini reply"); + var strong = new StubChatClient("strong reply"); + mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)); + var rig = V2Rig.Build(Round2.Config(), new Dictionary + { + [$"openai:{V2.CloudModel}"] = mini, + ["openai:gpt-4o"] = strong, + }); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal("estimated_failed_call", e.Attempts![0].CostBasis); + Assert.Equal("reported", e.Attempts[1].CostBasis); + Assert.Equal("mixed", e.CostBasis); // was "reported" for a total containing an estimate + + // FinOps counts it as an estimated-cost request and keeps it out of savings claims. + var f = FinOps.Build([e], V2.LocalTag, V2.LocalTag, new Dictionary(), null); + Assert.Equal(1, f.EstimatedCostRequests); + } +} + +/// B3 — one finite deadline for the whole execution, also after content. +public sealed class DeadlineAfterContentTests +{ + [Fact] + public async Task Deadline_after_streamed_content_is_a_timeout_with_partial_output_and_no_fallback() + { + var mini = new StubChatClient("mini reply") { Gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) }; // never released + var strong = new StubChatClient("strong reply"); + mini.Then(StubChatClient.Mode.StreamGated); + var rig = V2Rig.Build(Round2.Config(deadlineMs: 300), new Dictionary + { + [$"openai:{V2.CloudModel}"] = mini, + ["openai:gpt-4o"] = strong, + }); + using var safety = new CancellationTokenSource(TimeSpan.FromSeconds(5)); // pre-fix: the stream hangs until this fires + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true, ct: safety.Token); + + Assert.False(safety.IsCancellationRequested); + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + var a = Assert.Single(e.Attempts!); + Assert.Equal("failed", a.Outcome); + Assert.Equal("timeout", a.ErrorClass); + Assert.Equal("partial ".Length, e.PartialOutputChars); + Assert.Equal(0, strong.Calls); + Assert.True(a.CostUsd > 0m); + Assert.Contains("deadline", e.Reason, StringComparison.Ordinal); + Assert.Equal(0, rig.Ledger.OpenReservations); + } +} + +/// B4 — every admitted attempt settled/released exactly once; a slot closes only after the durable write. +public sealed class SettlementRobustnessTests +{ + private static readonly RouteTarget Mini = new("openai", V2.CloudModel); + + [Fact] + public void A_failed_settle_write_leaves_the_slot_open_and_a_retry_settles_exactly_once() + { + var store = new FlakyLedgerStore(); + var ledger = new BudgetLedger(store); + var snapshot = new RuntimeSnapshot(Round2.Config()); + var ctx = Round2.Ctx(snapshot, V2Rig.PublicPrompt); + var gate = new BudgetAttemptGate(ledger, new KillSwitch(), snapshot, ctx); + Assert.True(gate.ReserveFirst(ctx, Mini).Admitted); + Assert.Equal(1, ledger.OpenReservations); + + store.FailNext(LedgerOps.Settle); + Assert.Throws(() => gate.Settle(ctx, "att_1", null)); + Assert.Equal(1, gate.OpenSlots); // NOT marked closed before the durable write succeeded + Assert.Equal(1, ledger.OpenReservations); // reservation still held (never silently lost) + Assert.Null(ctx.SettledUsd); + + var charge = gate.Settle(ctx, "att_1", null); + Assert.True(charge.Settled); + Assert.Equal(0, gate.OpenSlots); + Assert.Equal(0, ledger.OpenReservations); + Assert.False(gate.Settle(ctx, "att_1", null).Settled); // idempotent afterwards + Assert.Equal(new[] { LedgerOps.Reserve, LedgerOps.Settle, LedgerOps.Release }, store.Records.Select(r => r.Op)); + Assert.Equal(charge.CostUsd, ctx.SettledUsd); + } + + [Fact] + public void A_failed_release_write_leaves_the_slot_open_and_a_retry_releases_once() + { + var store = new FlakyLedgerStore(); + var ledger = new BudgetLedger(store); + var snapshot = new RuntimeSnapshot(Round2.Config()); + var ctx = Round2.Ctx(snapshot, V2Rig.PublicPrompt); + var gate = new BudgetAttemptGate(ledger, new KillSwitch(), snapshot, ctx); + gate.ReserveFirst(ctx, Mini); + store.FailNext(LedgerOps.Release); + Assert.Throws(() => gate.Release(ctx, "att_1")); + Assert.Equal(1, gate.OpenSlots); + gate.Finish(ctx); // the unwind backstop releases it + Assert.Equal(0, gate.OpenSlots); + Assert.Equal(0, ledger.OpenReservations); + Assert.Equal(new[] { LedgerOps.Reserve, LedgerOps.Release }, store.Records.Select(r => r.Op)); + } + + [Fact] + public async Task Pipeline_settle_failure_is_retried_by_the_unwind_and_settles_exactly_once() + { + var store = new FlakyLedgerStore(); + var ledger = new BudgetLedger(store); + var (pipeline, sink) = Round2.Pipeline(ledger, new Dictionary { [$"openai:{V2.CloudModel}"] = new StubChatClient("mini") }); + var ctx = Round2.Ctx(new RuntimeSnapshot(Round2.Config()), V2Rig.PublicPrompt); + store.FailNext(LedgerOps.Settle); + + await Assert.ThrowsAsync(() => pipeline.ExecuteAsync(ctx, CancellationToken.None)); + Assert.Equal(1, store.Failures); + Assert.Equal(0, ledger.OpenReservations); // pre-fix: the slot was closed before the failed write ⇒ stuck open + Assert.Equal(0m, ledger.Reserved("global")); + Assert.Single(store.Records, r => r.Op == LedgerOps.Settle); + Assert.Single(sink.Entries); // the request is still evidenced + } + + [Fact] + public async Task Persistent_write_failure_keeps_state_consistent_and_boot_recovery_settles_once() + { + var store = new FlakyLedgerStore(); + var ledger = new BudgetLedger(store); + var (pipeline, _) = Round2.Pipeline(ledger, new Dictionary { [$"openai:{V2.CloudModel}"] = new StubChatClient("mini") }); + var ctx = Round2.Ctx(new RuntimeSnapshot(Round2.Config()), V2Rig.PublicPrompt); + store.FailNext(LedgerOps.Settle, count: int.MaxValue); + + await Assert.ThrowsAsync(() => pipeline.ExecuteAsync(ctx, CancellationToken.None)); + Assert.Equal(1, ledger.OpenReservations); // held, uncharged: the durable state the next boot sees + var reserved = store.Records.Single(r => r.Op == LedgerOps.Reserve).AmountUsd; + + // "Restart": replay what was durably written; recovery settles the open reservation exactly once. + var after = new BudgetLedger(new InMemoryLedgerStore(), store.Records); + var recovered = Assert.Single(after.RecoverUnsettled()); + Assert.Equal(LedgerOps.SettleRecovered, recovered.Op); + Assert.Equal(reserved, after.Spent("global", BudgetPeriod.Monthly)); + Assert.Empty(after.RecoverUnsettled()); + } + + [Fact] + public async Task Exception_after_attribution_still_settles_the_served_attempt_exactly_once_at_its_priced_cost() + { + var store = new FlakyLedgerStore(); + var ledger = new BudgetLedger(store); + var (pipeline, sink) = Round2.Pipeline(ledger, new Dictionary { [$"openai:{V2.CloudModel}"] = new StubChatClient("mini") }, + new ThrowingStage()); + var ctx = Round2.Ctx(new RuntimeSnapshot(Round2.Config()), V2Rig.PublicPrompt); + + await Assert.ThrowsAsync(() => pipeline.ExecuteAsync(ctx, CancellationToken.None)); + Assert.Equal(new[] { LedgerOps.Reserve, LedgerOps.Settle, LedgerOps.Release }, store.Records.Select(r => r.Op)); + Assert.Equal(0, ledger.OpenReservations); + var a = Assert.Single(ctx.Attempts); + Assert.Equal("reported", a.CostBasis); // settled by the provider stage's finally with the priced cost + Assert.Equal(10 / 1_000_000m * 0.15m + 5 / 1_000_000m * 0.60m, a.CostUsd); + Assert.Single(sink.Entries); // still exactly one evidence record + } +} + +/// B5 — unambiguous cache keys and served provenance (reviewer probe cache-collision-probe.cs.txt). +public sealed class CacheKeyCollisionTests +{ + private static async Task<(int Calls, bool SecondHit)> TwoRunsAsync(Func first, Func second) + { + var cache = new CacheStage(new ResponseCache(), new CacheConfig { TtlSeconds = 60 }); + int calls = 0; + Task Next(InferenceContext c, CancellationToken t) + { + calls++; + c.Response = new(new(ChatRole.Assistant, "response-" + calls), Usage.Empty, "model"); + return Task.CompletedTask; + } + await cache.InvokeAsync(first(), Next, default); + var b = second(); + await cache.InvokeAsync(b, Next, default); + return (calls, b.ServedFromCache); + } + + private static InferenceContext Legacy(params ChatMessage[] messages) + => new(new InferenceRequest("app", messages, "model", new("team", "flow", "case"))) { Policy = PolicyOutcome.Allow(new("connection", "model")) }; + + private static readonly RuntimeSnapshot Snapshot = new(V2.Hybrid(tweak: c => c with { Settings = new OperationalSettings { CacheTtlSeconds = 60 } })); + + private static InferenceContext Configured(params ChatMessage[] messages) + { + var ctx = new InferenceContext(new InferenceRequest("app", messages, null, new("platform", "flow", "case"))) { Configuration = Snapshot, ApplicationId = "demo-app" }; + ctx.Policy = PolicyOutcome.Allow(new("openai", V2.CloudModel)) with { Candidates = [new("openai", V2.CloudModel), new("ollama", V2.LocalTag)] }; + return ctx; + } + + public static TheoryData Shapes => new() { "delimiter-in-content", "boundary-shift", "control-chars", "role", "empty-vs-absent" }; + + private static ChatMessage U(string content) => new(ChatRole.User, content); + + private static (ChatMessage[] A, ChatMessage[] B) Pair(string shape) + { + switch (shape) + { + case "delimiter-in-content": return (new[] { U("x\u001fAssistant:y") }, new[] { U("x"), new ChatMessage(ChatRole.Assistant, "y") }); + case "boundary-shift": return (new[] { U("ab"), U("c") }, new[] { U("a"), U("bc") }); + case "control-chars": return (new[] { U("a\u001e"), U("b") }, new[] { U("a"), U("\u001eb") }); + case "role": return (new[] { new ChatMessage(ChatRole.System, "x") }, new[] { U("x") }); + case "empty-vs-absent": return (new[] { U("x"), U("") }, new[] { U("x") }); + default: throw new ArgumentOutOfRangeException(nameof(shape)); + } + } + + [Theory] + [MemberData(nameof(Shapes))] + public async Task Different_message_structures_never_collide_legacy_key(string shape) + { + var (a, b) = Pair(shape); + var (calls, hit) = await TwoRunsAsync(() => Legacy(a), () => Legacy(b)); + Assert.Equal(2, calls); + Assert.False(hit); + } + + [Theory] + [MemberData(nameof(Shapes))] + public async Task Different_message_structures_never_collide_configured_key(string shape) + { + var (a, b) = Pair(shape); + var (calls, hit) = await TwoRunsAsync(() => Configured(a), () => Configured(b)); + Assert.Equal(2, calls); + Assert.False(hit); + } + + [Fact] + public async Task Exact_repeat_still_hits() + { + var (calls, hit) = await TwoRunsAsync(() => Configured(new ChatMessage(ChatRole.User, "same")), () => Configured(new ChatMessage(ChatRole.User, "same"))); + Assert.Equal(1, calls); + Assert.True(hit); + } + + [Fact] + public async Task Reviewer_probe_capped_primary_and_less_capped_fallback_with_max_tokens_20_then_10_are_two_calls() + { + var config = new CovenantConfig + { + Version = 1, Origin = "probe", CreatedUtc = DateTimeOffset.UtcNow, Mode = ProviderMode.LocalOnly, + Connections = [new ConnectionConfig { Id = "local", DisplayName = "Fixture", Kind = ProviderKind.Ollama, Boundary = Boundary.Local, Enabled = true, + Models = [new ModelConfig { ModelId = "primary", MaxOutputTokens = 2 }, new ModelConfig { ModelId = "fallback", MaxOutputTokens = 100 }] }], + Applications = [new ApplicationConfig { Id = "app", Team = "team", Enabled = true, ConsoleTesting = true, GrantedProfiles = [], MaxOutputTokens = 100 }], + Profiles = [], Policies = [], Budgets = [], Settings = new OperationalSettings { CacheTtlSeconds = 60 }, + }; + var snapshot = new RuntimeSnapshot(config); + InferenceContext B(int max) => new(new InferenceRequest("app", [new(ChatRole.User, "test")], null, new("team", "flow", "case"), MaxOutputTokens: max)) + { + Configuration = snapshot, ApplicationId = "app", + Policy = PolicyOutcome.Allow(new("local", "primary")) with { Candidates = [new("local", "primary"), new("local", "fallback")] }, + }; + var (calls, hit) = await TwoRunsAsync(() => B(20), () => B(10)); + Assert.Equal(2, calls); + Assert.False(hit); + } + + [Fact] + public async Task A_hit_reports_the_connection_and_model_that_actually_served_not_the_primary() + { + var mini = new StubChatClient("mini reply"); + var strong = new StubChatClient("strong reply"); + var local = new StubChatClient("local reply"); + mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)).Then(StubChatClient.Mode.Serve); + strong.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)).Then(StubChatClient.Mode.Serve); + var rig = V2Rig.Build(Round2.Config(cacheTtl: 300), new Dictionary + { + [$"openai:{V2.CloudModel}"] = mini, + ["openai:gpt-4o"] = strong, + [$"ollama:{V2.LocalTag}"] = local, + }); + var (_, first) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal("ollama", first.ServedConnectionId); + Assert.Equal(V2.LocalTag, first.ServedByModel); + + var (hitCtx, hit) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.True(hit.CacheHit); + Assert.Equal(1, local.Calls); + Assert.Equal(new RouteTarget("ollama", V2.LocalTag), hitCtx.ServedTarget); + Assert.Equal("ollama", hit.ServedConnectionId); + Assert.Equal(V2.LocalTag, hit.ServedByModel); + Assert.Equal(V2.CloudModel, hit.SelectedModel); // the policy's primary stays visible as "selected" + } +} + +/// B6 — identity team = the ACTIVE application's team on both entry points. +public sealed class TeamConsistencyTests +{ + private const decimal OneRequest = 10 / 1_000_000m * 0.15m + 5 / 1_000_000m * 0.60m; + + [Fact] + public async Task Team_change_applied_through_configuration_governs_new_v1_and_console_charges_and_history_stays() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + using var app = factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); // key's startup team: platform + app.DefaultRequestHeaders.Add("X-Covenant-Profile", "public-demo"); + + using (var before = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this public announcement."))) + Assert.Equal("platform", (await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(before))).Tags.Team); + + var (version, cfg, _) = await V2Admin.GetConfigAsync(admin); + await V2Admin.ApplyAsync(admin, cfg with + { + Applications = cfg.Applications.Select(a => a.Id == "demo-app" ? a with { Team = "payments" } : a).ToList(), + }, version, "move demo-app to payments"); + + using var v1 = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this other public announcement.")); + Assert.Equal(HttpStatusCode.OK, v1.StatusCode); + Assert.Equal("payments", (await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(v1))).Tags.Team); // pre-fix: platform + + using var console = await Playground.PostAsync(admin, Playground.Body("demo-app", "Summarize a third public announcement.", profile: "public-demo")); + Assert.Equal(HttpStatusCode.OK, console.StatusCode); + Assert.Equal("payments", (await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(console))).Tags.Team); + + var (_, status, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/status"); + var teams = status.GetProperty("budget").GetProperty("teams").EnumerateArray() + .ToDictionary(t => t.GetProperty("team").GetString()!, t => t.GetProperty("spend_usd").GetDecimal(), StringComparer.OrdinalIgnoreCase); + Assert.Equal(OneRequest, teams["platform"]); // historical charge stays where it was recorded + Assert.Equal(2 * OneRequest, teams["payments"]); // both entry points charge the new team + } +} + +/// B7 — console request id available before the first response byte. +public sealed class EarlyRequestIdTests +{ + [Fact] + public async Task Submission_lookup_returns_the_request_id_while_the_provider_blocks_and_the_trace_shows_provider_running() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + factory.Cloud.Gate = gate; + factory.Cloud.Then(StubChatClient.Mode.Gated).Then(StubChatClient.Mode.Serve); + const string crid = "crid-early-7f3a"; + + var post = Playground.PostAsync(admin, Playground.Body("demo-app", "Summarize this public announcement.", profile: "public-demo", + clientRequestId: crid, maxTokens: 256)); + await factory.Cloud.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + + var (status, sub, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, $"/admin/playground/submissions/{crid}"); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(crid, sub.GetProperty("client_request_id").GetString()); + Assert.Equal("running", sub.GetProperty("state").GetString()); + var requestId = sub.GetProperty("request_id").GetString()!; + Assert.True(RequestCorrelation.IsWellFormed(requestId)); + + var (traceStatus, trace, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, $"/admin/requests/{requestId}/trace"); + Assert.Equal(HttpStatusCode.OK, traceStatus); + Assert.False(trace.GetProperty("complete").GetBoolean()); + var events = trace.GetProperty("events").EnumerateArray().ToList(); + var running = events.Last(e => e.GetProperty("stage").GetString() == "provider"); + Assert.Equal("running", running.GetProperty("state").GetString()); + Assert.Equal("att_1", running.GetProperty("attempt_id").GetString()); + Assert.Equal(256, running.GetProperty("requested_max_output_tokens").GetInt32()); // B12 on trace attempt events + Assert.Equal(256, running.GetProperty("effective_max_output_tokens").GetInt32()); + + gate.SetResult(); + using var resp = await post; + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + Assert.Equal(requestId, CorrelationTestKit.HeaderId(resp)); + var (_, done, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, $"/admin/playground/submissions/{crid}"); + Assert.Equal("completed", done.GetProperty("state").GetString()); + + var (missing, missingBody, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/playground/submissions/never-submitted"); + Assert.Equal(HttpStatusCode.NotFound, missing); + Assert.Equal("not_found", missingBody.GetProperty("error").GetString()); + using var noToken = await admin.GetAsync($"/admin/playground/submissions/{crid}"); + Assert.Equal(HttpStatusCode.Unauthorized, noToken.StatusCode); + } + + [Fact] + public void Client_request_id_is_required_and_bounded() + { + PlaygroundRequest Body(string? crid) => new() + { + ApplicationId = "demo-app", Messages = [new PlaygroundMessage { Role = "user", Content = "x" }], ClientRequestId = crid, + }; + Assert.NotNull(PlaygroundApi.Validate(Body(null))); + Assert.NotNull(PlaygroundApi.Validate(Body(""))); + Assert.NotNull(PlaygroundApi.Validate(Body(new string('a', 65)))); + Assert.NotNull(PlaygroundApi.Validate(Body("a.b"))); + Assert.Null(PlaygroundApi.Validate(Body(new string('a', 64)))); + Assert.Null(PlaygroundApi.Validate(Body("run_7f3a-B"))); + } +} + +/// B8 — stable newest-first paging anchored by absolute index; rotation ⇒ 410. +public sealed class StablePaginationTests : IDisposable +{ + private readonly RestartableHybridFactory _factory = new(RestartableHybridFactory.NewAuditPath()); + private readonly HttpClient _admin; + + public StablePaginationTests() => _admin = _factory.CreateClient(); + + public void Dispose() => _factory.Dispose(); + + private async Task RunAsync(string prompt) + { + using var resp = await Playground.PostAsync(_admin, Playground.Body("demo-app", prompt)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + await CorrelationTestKit.LookupAsync(_admin, id); + return id; + } + + private async Task<(HttpStatusCode Status, JsonElement Body)> GetAsync(string path) + { + var (status, body, _) = await V2Admin.SendAsync(_admin, HttpMethod.Get, path); + return (status, body); + } + + private static List Ids(JsonElement page) => page.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("Id").GetString()!).ToList(); + + [Fact] + public async Task Insert_between_pages_causes_no_duplicates_and_no_gaps() + { + var r1 = await RunAsync("first internal question"); + var r2 = await RunAsync("second internal question"); + var r3 = await RunAsync("third internal question"); + + var (_, page1) = await GetAsync("/admin/requests?limit=2"); + Assert.Equal(new[] { r3, r2 }, Ids(page1)); + var segment = page1.GetProperty("segment"); + Assert.Equal("current", segment.GetProperty("id").GetString()); + Assert.True(segment.GetProperty("is_current").GetBoolean()); + Assert.False(string.IsNullOrEmpty(segment.GetProperty("label").GetString())); + var cursor = page1.GetProperty("next_cursor").GetString()!; + + var r4 = await RunAsync("a newer internal question arrives between pages"); + + var (status, page2) = await GetAsync($"/admin/requests?limit=2&cursor={Uri.EscapeDataString(cursor)}"); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(new[] { r1 }, Ids(page2)); // pre-fix: r2 again (offset shifted by the insert) + Assert.Equal(JsonValueKind.Null, page2.GetProperty("next_cursor").ValueKind); + Assert.True(page2.GetProperty("segment").GetProperty("is_current").GetBoolean()); + + var (_, fresh) = await GetAsync("/admin/requests?limit=2"); + Assert.Equal(new[] { r4, r3 }, Ids(fresh)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task A_cursor_issued_before_a_rotation_is_410_cursor_expired_never_redirected(bool newRecordAfterRotation) + { + await RunAsync("first internal question"); + await RunAsync("second internal question"); + var (_, page1) = await GetAsync("/admin/requests?limit=1"); + var cursor = page1.GetProperty("next_cursor").GetString()!; + + var (resetStatus, _, _) = await V2Admin.SendAsync(_admin, HttpMethod.Post, "/admin/reset"); + Assert.Equal(HttpStatusCode.OK, resetStatus); + if (newRecordAfterRotation) await RunAsync("after the rotation"); + + var (status, body) = await GetAsync($"/admin/requests?limit=1&cursor={Uri.EscapeDataString(cursor)}"); + Assert.Equal(HttpStatusCode.Gone, status); + Assert.Equal("cursor_expired", body.GetProperty("error").GetString()); + } + + [Fact] + public async Task Archived_segment_pages_carry_their_descriptor() + { + await RunAsync("first internal question"); + await RunAsync("second internal question"); + await V2Admin.SendAsync(_admin, HttpMethod.Post, "/admin/reset"); + var (_, segments) = await GetAsync("/admin/audit/segments"); + var archivedId = segments.EnumerateArray().Single(s => !s.GetProperty("current").GetBoolean()).GetProperty("id").GetString()!; + var (_, page1) = await GetAsync($"/admin/requests?segment={archivedId}&limit=1"); + Assert.False(page1.GetProperty("segment").GetProperty("is_current").GetBoolean()); + Assert.Equal(archivedId, page1.GetProperty("segment").GetProperty("id").GetString()); + var (status, page2) = await GetAsync($"/admin/requests?cursor={Uri.EscapeDataString(page1.GetProperty("next_cursor").GetString()!)}"); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Single(Ids(page2)); + } +} + +/// B9 — atomic ledger bootstrap with a completion marker; B10 — replay validation. +public sealed class LedgerBootstrapAndReplayTests : IDisposable +{ + private readonly string _path = Path.Combine(Path.GetTempPath(), $"covenant-ledger-r2-{Guid.NewGuid():n}.jsonl"); + + public void Dispose() => CorrelationTestKit.DeleteWithSiblings(_path); + + private static readonly DateTimeOffset Now = DateTimeOffset.Parse("2026-10-17T12:00:00Z"); + private static readonly (string, decimal)[] TwoTeams = [("payments", 1.5m), ("data", 0.5m)]; + + private static string Line(string op, string req, string att, string scopes, string amount = "0.1", string ts = "2026-10-17T10:00:00+00:00", bool overrun = false) + => $"{{\"op\":\"{op}\",\"request_id\":\"{req}\",\"attempt_id\":\"{att}\",\"scopes\":[{scopes}],\"amount_usd\":{amount},\"ts_utc\":\"{ts}\"{(overrun ? ",\"overrun\":true" : "")}}}"; + + private const string G = "\"global\",\"team:platform\""; + private static readonly string Marker = Line("bootstrap-complete", "bootstrap", "bootstrap-complete", "", "0"); + + [Fact] + public void Fresh_bootstrap_imports_every_team_once_atomically_with_the_marker_and_is_never_repeated() + { + int calls = 0; + var opened = LedgerBootstrap.OpenOrBootstrap(new FileLedgerStore(_path), () => { calls++; return TwoTeams; }, Now); + Assert.Empty(opened.Errors); + Assert.False(opened.Existed); + Assert.Equal(new[] { LedgerOps.LegacyImport, LedgerOps.LegacyImport, LedgerOps.BootstrapComplete }, opened.Records.Select(r => r.Op)); + Assert.False(File.Exists(_path + ".bootstrap.tmp")); + var ledger = new BudgetLedger(new FileLedgerStore(_path), opened.Records, new SettableClock(Now)); + Assert.Equal(2m, ledger.Spent("global", BudgetPeriod.Monthly)); + + var again = LedgerBootstrap.OpenOrBootstrap(new FileLedgerStore(_path), () => { calls++; return TwoTeams; }, Now); + Assert.Empty(again.Errors); + Assert.True(again.Existed); + Assert.Equal(1, calls); // the import never runs twice + Assert.Equal(2m, new BudgetLedger(new InMemoryLedgerStore(), again.Records, new SettableClock(Now)).Spent("global", BudgetPeriod.Monthly)); + } + + [Fact] + public void Interruption_after_create_before_import_refuses_start_and_never_restores_capacity() + { + File.WriteAllText(_path, ""); // what the pre-fix EnsureCreated left behind + Assert.NotEmpty(new FileLedgerStore(_path).Open().Errors); // pre-fix: accepted silently ⇒ legacy spend lost + int calls = 0; + var opened = LedgerBootstrap.OpenOrBootstrap(new FileLedgerStore(_path), () => { calls++; return TwoTeams; }, Now); + Assert.Contains(opened.Errors, e => e.Contains("bootstrap-complete", StringComparison.Ordinal)); + Assert.Equal(0, calls); + Assert.Equal("", File.ReadAllText(_path)); // evidence untouched + } + + [Fact] + public void Partway_through_a_multi_team_import_refuses_start() + { + var oneOfTwo = Line("legacy-import", "legacy-import", "team:payments", "\"global\",\"team:payments\"", "1.5"); + File.WriteAllText(_path, oneOfTwo + "\n"); + Assert.NotEmpty(new FileLedgerStore(_path).Open().Errors); + + // Same with the second team's line torn mid-write: never quarantine-and-continue on a half import. + File.WriteAllText(_path, oneOfTwo + "\n{\"op\":\"legacy-import\",\"request_id\":\"legacy-imp"); + Assert.NotEmpty(new FileLedgerStore(_path).Open().Errors); + } + + [Fact] + public void Interruption_before_the_rename_leaves_no_ledger_and_the_next_boot_bootstraps_once() + { + File.WriteAllText(_path + ".bootstrap.tmp", Line("legacy-import", "legacy-import", "team:payments", "\"global\",\"team:payments\"", "1.5") + "\n"); + var opened = LedgerBootstrap.OpenOrBootstrap(new FileLedgerStore(_path), () => TwoTeams, Now); + Assert.Empty(opened.Errors); + Assert.Equal(2m, new BudgetLedger(new InMemoryLedgerStore(), opened.Records, new SettableClock(Now)).Spent("global", BudgetPeriod.Monthly)); + } + + [Fact] + public void Duplicate_legacy_import_lines_are_idempotent_per_scope() + { + var imp = Line("legacy-import", "legacy-import", "team:payments", "\"global\",\"team:payments\"", "1.5", "2026-10-17T10:00:00+00:00"); + File.WriteAllText(_path, imp + "\n" + imp + "\n" + Marker + "\n"); + var opened = new FileLedgerStore(_path).Open(); + Assert.Empty(opened.Errors); + var ledger = new BudgetLedger(new InMemoryLedgerStore(), opened.Records, new SettableClock(Now)); + Assert.Equal(1.5m, ledger.Spent("team:payments", BudgetPeriod.Monthly)); + Assert.Empty(ledger.ImportLegacy([("payments", 1.5m)])); // a replayed import adds nothing + } + + [Fact] + public void Pre_marker_journal_with_recorded_operations_is_accepted_once_with_the_marker_appended() + { + File.WriteAllText(_path, Line("reserve", "r1", "att_1", G) + "\n" + Line("settle", "r1", "att_1", G) + "\n" + Line("release", "r1", "att_1", G, "0") + "\n"); + var first = new FileLedgerStore(_path).Open(); + Assert.Empty(first.Errors); + Assert.NotEmpty(first.Warnings); + var second = new FileLedgerStore(_path).Open(); + Assert.Empty(second.Errors); + Assert.Empty(second.Warnings); + Assert.Single(second.Records, r => r.Op == LedgerOps.BootstrapComplete); + } + + public static TheoryData Violations => new() + { + { "unknown-op", Line("refund", "r1", "att_1", G), "unknown op" }, + { "negative", Line("reserve", "r1", "att_1", G, "-1"), "negative amount" }, + { "empty-request", Line("reserve", "", "att_1", G), "empty request_id" }, + { "empty-attempt", Line("reserve", "r1", "", G), "empty attempt_id" }, + { "bad-scope", Line("reserve", "r1", "att_1", "\"teamx\""), "invalid scope" }, + { "empty-team", Line("reserve", "r1", "att_1", "\"global\",\"team:\""), "invalid scope" }, + { "no-scopes", Line("reserve", "r1", "att_1", ""), "without scopes" }, + { "min-ts", Line("reserve", "r1", "att_1", G, ts: "0001-01-01T00:00:00+00:00"), "ts_utc" }, + { "settle-unreserved", Line("settle", "r9", "att_1", G), "settle without a reservation" }, + { "release-unreserved", Line("release", "r9", "att_1", G), "release without a reservation" }, + { "recover-unreserved", Line("settle-recovered", "r9", "att_1", G), "settle-recovered without a reservation" }, + { "double-settle", Line("settle", "r0", "att_1", G), "second settle" }, + { "double-reserve", Line("reserve", "r0", "att_1", G), "second reserve" }, + { "release-after-close", Line("release", "rc", "att_1", G, "0"), "release after the attempt was closed" }, + { "import-after-marker", Line("legacy-import", "legacy-import", "team:x", "\"global\",\"team:x\"", "1"), "after the bootstrap-complete marker" }, + { "second-marker", Marker, "duplicate bootstrap-complete" }, + }; + + [Theory] + [MemberData(nameof(Violations))] + public void A_violation_in_a_non_tail_line_refuses_start_with_a_precise_diagnostic(string name, string bad, string expected) + { + Assert.NotNull(name); + var prefix = new[] + { + Marker, + Line("reserve", "r0", "att_1", G), Line("settle", "r0", "att_1", G), // r0 settled + Line("reserve", "rc", "att_1", G), Line("settle-recovered", "rc", "att_1", G), // rc closed + }; + var lines = prefix.Append(bad).Append(Line("reserve", "tail", "att_1", G)).ToArray(); // valid tail after it + File.WriteAllText(_path, string.Join("\n", lines) + "\n"); + var opened = new FileLedgerStore(_path).Open(); + var error = Assert.Single(opened.Errors); + Assert.Contains($"line {prefix.Length + 1} ", error, StringComparison.Ordinal); + Assert.Contains(expected, error, StringComparison.Ordinal); + } + + [Fact] + public void Non_iso_timestamp_is_a_corrupt_line() + { + File.WriteAllText(_path, Marker + "\n" + Line("reserve", "r1", "att_1", G, ts: "yesterday") + "\n" + Line("reserve", "r2", "att_1", G) + "\n"); + Assert.Contains(new FileLedgerStore(_path).Open().Errors, e => e.Contains("line 2 ", StringComparison.Ordinal)); + } + + [Fact] + public void A_valid_full_lifecycle_replays_cleanly_and_an_unknown_op_never_silently_disappears_in_memory() + { + File.WriteAllText(_path, string.Join("\n", + Marker, + Line("reserve", "r1", "att_1", G), Line("settle", "r1", "att_1", G, "0.05"), Line("release", "r1", "att_1", G, "0.05"), + Line("reserve", "r2", "att_1", G), Line("release", "r2", "att_1", G), + Line("settle", "r3", "att_1", G, "0.2", overrun: true), + Line("reserve", "r4", "att_1", G), Line("settle-recovered", "r4", "att_1", G)) + "\n"); + var opened = new FileLedgerStore(_path).Open(); + Assert.Empty(opened.Errors); + Assert.Equal(0.05m + 0.2m + 0.1m, new BudgetLedger(new InMemoryLedgerStore(), opened.Records, new SettableClock(Now)).Spent("global", BudgetPeriod.None)); + + var bogus = new LedgerRecord { Op = "refund", RequestId = "r", AttemptId = "a", Scopes = ["global"], AmountUsd = 1m, TsUtc = Now }; + Assert.Throws(() => new BudgetLedger(new InMemoryLedgerStore(), [bogus])); + } +} + +/// B11 — header local health from CURRENT runtime connection health. +public sealed class LocalHealthTests +{ + [Fact] + public async Task After_a_successful_governed_local_call_catalog_and_status_show_that_connection_model_ok_and_a_legacy_local_connection_does_not_shadow_it() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + + // A stale legacy-style connection literally named "local" (pre-fix: catalog.local always picked it). + var (version, cfg, _) = await V2Admin.GetConfigAsync(admin); + await V2Admin.ApplyAsync(admin, cfg with + { + Connections = cfg.Connections.Append(new ConnectionConfig + { + Id = "local", DisplayName = "Legacy local", Kind = ProviderKind.Ollama, Boundary = Boundary.Local, + Endpoint = "http://127.0.0.1:11434/v1", Enabled = true, + Models = [new ModelConfig { ModelId = "legacy-model", Price = new PriceConfig { InputPer1M = 0m, OutputPer1M = 0m, Basis = "zero-marginal-local" } }], + }).ToList(), + }, version, "legacy local connection"); + + using var app = factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + using var resp = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("an internal question")); // Internal → ollama + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + Assert.Equal(1, factory.Local.Calls); + + var (_, catalog, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/catalog"); + var local = catalog.GetProperty("local"); + Assert.Equal("ollama", local.GetProperty("connection_id").GetString()); + Assert.Equal(V2.LocalTag, local.GetProperty("model_id").GetString()); + Assert.Equal("ok", local.GetProperty("health").GetProperty("state").GetString()); + var conn = catalog.GetProperty("connections").EnumerateArray().Single(c => c.GetProperty("id").GetString() == "ollama"); + Assert.Equal("ok", conn.GetProperty("models")[0].GetProperty("health").GetProperty("state").GetString()); + + var (_, status, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/status"); + var health = status.GetProperty("connection_health").EnumerateArray().ToList(); + Assert.Equal("ok", health.Single(h => h.GetProperty("key").GetString() == $"ollama:{V2.LocalTag}").GetProperty("health").GetProperty("state").GetString()); + Assert.Equal("unknown", health.Single(h => h.GetProperty("key").GetString() == "local:legacy-model").GetProperty("health").GetProperty("state").GetString()); + } +} + +/// B12 — requested vs effective output bound in audit v3 and on attempts. +public sealed class OutputBoundEvidenceTests +{ + [Fact] + public async Task Audit_records_requested_and_effective_bounds_per_attempt_and_on_the_record() + { + var mini = new StubChatClient("mini reply"); + var rig = V2Rig.Build(Round2.Config(tweak: c => c with + { + Connections = c.Connections.Select(x => x.Id != "openai" ? x : x with + { + Models = x.Models.Select(m => m.ModelId == V2.CloudModel ? m with { MaxOutputTokens = 64 } : m).ToList(), + }).ToList(), + }), new Dictionary { [$"openai:{V2.CloudModel}"] = mini }); + + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", maxTokens: 256); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal(256, e.RequestedMaxOutputTokens); + Assert.Equal(64, e.EffectiveMaxOutputTokens); + Assert.Equal(64, Assert.Single(e.Attempts!).EffectiveMaxOutputTokens); + Assert.Equal(64, mini.LastOptions?.MaxOutputTokens); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "provider" && t.AttemptId == "att_1" && t.RequestedMaxOutputTokens == 256 && t.EffectiveMaxOutputTokens == 64); + + var (_, noMax) = await rig.RunAsync(V2Rig.PublicPrompt + " again", profile: "public-demo"); + Assert.Null(noMax.RequestedMaxOutputTokens); + Assert.Equal(64, noMax.EffectiveMaxOutputTokens); + } +} diff --git a/tests/Covenant.Tests/RuntimeV2TestKit.cs b/tests/Covenant.Tests/RuntimeV2TestKit.cs new file mode 100644 index 0000000..18c1bf3 --- /dev/null +++ b/tests/Covenant.Tests/RuntimeV2TestKit.cs @@ -0,0 +1,286 @@ +using System.Net; +using System.Runtime.CompilerServices; +using Covenant.Adapters; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// Settable clock (no sleeps): budget periods, trace retention. +internal sealed class SettableClock(DateTimeOffset start) : TimeProvider +{ + private DateTimeOffset _now = start; + public override DateTimeOffset GetUtcNow() => _now; + public void Set(DateTimeOffset now) => _now = now; + public void Advance(TimeSpan by) => _now += by; +} + +/// Stub provider whose behaviour per call is scripted (never a paid provider). Each call dequeues the next +/// behaviour (the last one repeats). Records the ChatOptions it saw. +internal sealed class StubChatClient(string reply = "stub reply") : MEAI.IChatClient +{ + public enum Mode + { + Serve, ServeNoUsage, Throw, Hang, StreamThenThrow, ServeHugeUsage, StreamGated, + /// Streams text, then ends WITHOUT a terminal update carrying a finish reason (review round 2, B1). + StreamNoFinish, + /// Buffered/streamed: served with finish reason "length" (truncated at the output bound). + ServeLength, + /// Buffered: waits for before serving (B7 early request id). + Gated, + /// Streamed: a legitimately COMPLETED stream with no text at all (terminal update only). + StreamEmptyComplete, + } + + /// StreamGated: the first chunk is sent, then the stream waits for this gate before finishing. + public TaskCompletionSource? Gate { get; set; } + + private readonly Queue<(Mode Mode, Func? Error)> _script = new(); + private (Mode Mode, Func? Error) _last = (Mode.Serve, null); + private int _calls; + + public int Calls => Volatile.Read(ref _calls); + public MEAI.ChatOptions? LastOptions { get; private set; } + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + /// Invoked when a call starts (before its behaviour), e.g. to trip the pause between attempts. + public Action? OnCall { get; set; } + + public StubChatClient Then(Mode mode, Func? error = null) + { + lock (_script) _script.Enqueue((mode, error)); + return this; + } + + private (Mode Mode, Func? Error) Next() + { + lock (_script) + { + if (_script.Count > 0) _last = _script.Dequeue(); + return _last; + } + } + + public async Task GetResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _calls); + LastOptions = options; + OnCall?.Invoke(); + Entered.TrySetResult(); + var (mode, error) = Next(); + switch (mode) + { + case Mode.Throw: + throw error?.Invoke() ?? new HttpRequestException("stub failure"); + case Mode.Hang: + await Task.Delay(Timeout.Infinite, cancellationToken); + break; + case Mode.Gated when Gate is { } g: + await g.Task.WaitAsync(cancellationToken); + break; + } + var usage = mode switch + { + Mode.ServeNoUsage => null, + Mode.ServeHugeUsage => new MEAI.UsageDetails { InputTokenCount = 1_000_000, OutputTokenCount = 1_000_000 }, + _ => new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 }, + }; + return new MEAI.ChatResponse(new MEAI.ChatMessage(MEAI.ChatRole.Assistant, reply)) + { + Usage = usage, + FinishReason = mode == Mode.ServeLength ? MEAI.ChatFinishReason.Length : MEAI.ChatFinishReason.Stop, + }; + } + + public async IAsyncEnumerable GetStreamingResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _calls); + LastOptions = options; + OnCall?.Invoke(); + Entered.TrySetResult(); + var (mode, error) = Next(); + await Task.Yield(); + if (mode == Mode.Throw) throw error?.Invoke() ?? new HttpRequestException("stub failure"); + if (mode == Mode.Hang) await Task.Delay(Timeout.Infinite, cancellationToken); + if (mode == Mode.StreamEmptyComplete) + { + yield return new MEAI.ChatResponseUpdate + { + Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 0 })], + FinishReason = MEAI.ChatFinishReason.Stop, + }; + yield break; + } + yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, "partial "); + if (mode == Mode.StreamGated && Gate is { } gate) await gate.Task.WaitAsync(cancellationToken); + if (mode == Mode.StreamThenThrow) throw error?.Invoke() ?? new HttpRequestException("connection reset mid-stream", null, HttpStatusCode.ServiceUnavailable); + yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply); + if (mode == Mode.StreamNoFinish) yield break; // EOF with no terminal completion (e.g. a swallowed SSE error) + yield return new MEAI.ChatResponseUpdate + { + Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 })], + FinishReason = mode == Mode.ServeLength ? MEAI.ChatFinishReason.Length : MEAI.ChatFinishReason.Stop, + }; + } + + public object? GetService(Type serviceType, object? serviceKey = null) => null; + public void Dispose() { } +} + +internal static class Failures +{ + public static Exception Status(HttpStatusCode code) => new HttpRequestException($"stub HTTP {(int)code}", null, code); + public static Exception Connect() => new HttpRequestException("stub connection refused", new System.Net.Sockets.SocketException(10061)); + public static Exception ProviderTimeout() => new TaskCanceledException("stub provider-side timeout"); +} + +/// Pure v2 pipeline (no Host): the Host's stage order with a bound configuration snapshot, the persistent-ledger +/// budget stage over an in-memory store, the SDK-aware classifier and observed health. +internal sealed class V2Rig +{ + public sealed class ListSink : IAuditSink + { + public List Entries { get; } = []; + public ValueTask EnqueueAsync(AuditEntry entry, CancellationToken cancellationToken = default) + { + lock (Entries) Entries.Add(entry); + return ValueTask.CompletedTask; + } + } + + public required InferencePipeline Pipeline { get; init; } + public required ListSink Sink { get; init; } + public required InMemoryLedgerStore Store { get; init; } + public required BudgetLedger Ledger { get; init; } + public required KillSwitch Kill { get; init; } + public required ProviderHealth Health { get; init; } + public RuntimeSnapshot Snapshot { get; set; } = null!; + + public static V2Rig Build(CovenantConfig config, IReadOnlyDictionary clients, TimeProvider? clock = null, + ResponseCache? cache = null, BudgetLedger? ledger = null, InMemoryLedgerStore? store = null) + { + store ??= new InMemoryLedgerStore(); + ledger ??= new BudgetLedger(store, clock: clock); + var sink = new ListSink(); + var kill = new KillSwitch(); + var health = new ProviderHealth(); + var pipeline = new InferencePipeline( + [ + new AuditStage(sink), + new AuthStage(new AuthConfig + { + AllowAnonymous = false, + Keys = + [ + new ApiKeyRecord("demo-key", "demo-service", "platform", "demo-app"), + new ApiKeyRecord("batch-key", "batch-app", "data"), + ], + }), + new ShapeStage(), + new ClassifyStage(new RegexDataClassifier()), + new PolicyStage(new PolicyEngine(new PolicyConfig { AllowedRoutes = new Dictionary>() })), + new CacheStage(cache ?? new ResponseCache(clock), new CacheConfig()), + new RateLimitStage(new RateCounter(), new RateCounter(), new RateLimitConfig()), + new PauseStage(kill), + new BudgetStage(kill, ledger), + new ProviderCallStage(new ChatClientRegistry(clients), health, classifier: SdkProviderFailureClassifier.Shared), + new AttributionStage(new PriceBook(new Dictionary())), + ]); + return new V2Rig { Pipeline = pipeline, Sink = sink, Store = store, Ledger = ledger, Kill = kill, Health = health, Snapshot = new RuntimeSnapshot(config) }; + } + + public async Task<(InferenceContext Ctx, AuditEntry Entry)> RunAsync(string prompt, string? profile = null, string key = "demo-key", + bool stream = false, int? maxTokens = null, string? model = null, CancellationToken ct = default) + { + var ctx = new InferenceContext(new InferenceRequest("caller", [new ChatMessage(ChatRole.User, prompt)], model, + new AttributionTags("self-declared", "wf", "uc"), Stream: stream, Credential: key, MaxOutputTokens: maxTokens, + RequestId: $"req_{Guid.NewGuid():n}", RequestedProfile: profile)); + ctx.Configuration = Snapshot; + ctx.ConfigVersion = Snapshot.Version; + var deltas = new System.Text.StringBuilder(); + if (stream) ctx.DeltaSink = (d, _) => { deltas.Append(d.Content); return ValueTask.CompletedTask; }; + int before; + lock (Sink.Entries) before = Sink.Entries.Count; + try + { + await Pipeline.ExecuteAsync(ctx, ct); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + // the caller cancelled: the record is still written (asserted by the caller) + } + lock (Sink.Entries) + { + if (Sink.Entries.Count != before + 1) throw new Xunit.Sdk.XunitException($"expected exactly one audit record, got {Sink.Entries.Count - before}"); + return (ctx, Sink.Entries[^1]); + } + } + + /// Hybrid demo config with a priced cloud primary and a priced second cloud fallback so fallback charges are + /// visible; Public → [openai/gpt-4o-mini, openai/gpt-4o, ollama/qwen3:8b] with the given retry settings. + public static CovenantConfig FallbackConfig(RetrySettings? retry = null, decimal cap = 100m, Func? tweak = null) + => V2.Hybrid(tweak: c => + { + var x = c with + { + Policies = c.Policies.Select(p => p.Id != "public" ? p : p with + { + Targets = [V2.T("openai", V2.CloudModel), V2.T("openai", "gpt-4o"), V2.T("ollama", V2.LocalTag)], + Retry = retry ?? new RetrySettings { MaxAttempts = 3, DeadlineMs = 60_000 }, + }).ToList(), + Budgets = [new BudgetConfigV2 { Id = "global", Scope = "global", CapUsd = cap, Period = BudgetPeriod.Monthly }], + }; + return tweak is null ? x : tweak(x); + }); + + public const string PublicPrompt = "Rewrite this public product announcement in one sentence."; +} + +/// A Host booted from the demo-hybrid seed with stub providers on a caller-chosen audit path, optionally NOT +/// deleting its files on dispose — so a second instance can boot on the same audit log, configuration and ledger +/// (restart tests). Cloud price from the seed: $0.15 / $0.60 per 1M. +public sealed class RestartableHybridFactory(string auditPath, bool cleanup = true) : WebApplicationFactory +{ + public string AuditPath { get; } = auditPath; + public string LedgerPath => AuditPath + ".ledger.jsonl"; + internal StubChatClient Local { get; } = new("local reply"); + internal StubChatClient Cloud { get; } = new("cloud reply"); + + public static string NewAuditPath() => Path.Combine(Path.GetTempPath(), $"covenant-t04-{Guid.NewGuid():n}.log"); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Production"); + builder.UseSetting("Config:Seed", "demo-hybrid"); + builder.UseSetting($"Pricing:{V2.CloudModel}:InPer1M", "0.15"); // explicit, model-bound (seed never assumes) + builder.UseSetting($"Pricing:{V2.CloudModel}:OutPer1M", "0.60"); + builder.UseSetting("OpenAI:ApiKey", HybridSeedFactory.Secret); + builder.UseSetting("Anthropic:ApiKey", ""); + builder.UseSetting("Local:Endpoint", "http://127.0.0.1:11434/v1"); + builder.UseSetting("Local:ModelId", V2.LocalTag); + builder.UseSetting("Admin:Token", CorrelationTestKit.AdminToken); + builder.UseSetting("Budget:GlobalCapUsd", "100"); + builder.UseSetting("Auth:Keys:0:Key", "demo-key"); + builder.UseSetting("Auth:Keys:0:Principal", "demo-service"); + builder.UseSetting("Auth:Keys:0:Team", "platform"); + builder.UseSetting("Auth:Keys:0:Application", "demo-app"); + CorrelationTestKit.IsolatePaths(builder, AuditPath); + builder.ConfigureTestServices(services => + services.AddSingleton(new ChatClientRegistry(new Dictionary + { + [$"ollama:{V2.LocalTag}"] = Local, + [$"openai:{V2.CloudModel}"] = Cloud, + }))); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (cleanup) CorrelationTestKit.DeleteWithSiblings(AuditPath); + } +} diff --git a/tests/Covenant.Tests/ServedPathTests.cs b/tests/Covenant.Tests/ServedPathTests.cs index 41336ca..3b3f980 100644 --- a/tests/Covenant.Tests/ServedPathTests.cs +++ b/tests/Covenant.Tests/ServedPathTests.cs @@ -31,7 +31,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("Auth:Keys:0:Key", "k"); builder.UseSetting("Auth:Keys:0:Principal", "p"); builder.UseSetting("Auth:Keys:0:Team", "t"); - builder.UseSetting("Audit:Path", AuditPath); + CorrelationTestKit.IsolatePaths(builder, AuditPath); // Replace the provider registry with in-memory stubs for the policy's OpenAI routes. // ConfigureTestServices runs AFTER the app's registrations, so this override wins; the @@ -51,8 +51,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) protected override void Dispose(bool disposing) { base.Dispose(disposing); - foreach (var f in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(AuditPath) + "*")) - File.Delete(f); + CorrelationTestKit.DeleteWithSiblings(AuditPath); } } @@ -68,6 +67,7 @@ private sealed class StubChatClient(string reply) : MEAI.IChatClient yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply[..6]); yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply[6..]); yield return new MEAI.ChatResponseUpdate { Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 7, OutputTokenCount = 4 })] }; + yield return new MEAI.ChatResponseUpdate { FinishReason = MEAI.ChatFinishReason.Stop }; // terminal completion (real providers send one) } public object? GetService(Type t, object? key = null) => null; diff --git a/tests/Covenant.Tests/SimulatorTests.cs b/tests/Covenant.Tests/SimulatorTests.cs new file mode 100644 index 0000000..4640fa3 --- /dev/null +++ b/tests/Covenant.Tests/SimulatorTests.cs @@ -0,0 +1,114 @@ +using System.Net; +using System.Text.Json; +using Covenant.Core; +using Covenant.Host; +using Xunit; + +namespace Covenant.Tests; + +/// POST /admin/policies/simulate is a labelled dry run on the REAL classifier and policy engine: it never +/// calls a provider (tripwire clients), never writes audit, never records spend. +public sealed class SimulatorTests : IDisposable +{ + private readonly HybridSeedFactory _factory = new(); + private readonly HttpClient _client; + + public SimulatorTests() => _client = _factory.CreateClient(); + + public void Dispose() => _factory.Dispose(); + + private async Task Simulate(string json) + { + var (status, body, _) = await V2Admin.SendAsync(_client, HttpMethod.Post, "/admin/policies/simulate", json); + if (status != HttpStatusCode.OK) throw new Xunit.Sdk.XunitException($"simulate → {(int)status}: {body}"); + Assert.True(body.GetProperty("dry_run").GetBoolean()); + return body; + } + + private async Task AuditLinesAsync() + { + // The bootstrap config.activated event is the first line; wait for it so the baseline is stable. + var entries = await V2Admin.AuditAsync(_factory.AuditPath, l => l.Count >= 1); + return entries.Count; + } + + [Fact] + public async Task Dry_run_routes_public_to_cloud_without_calling_any_provider_or_writing_evidence() + { + int before = await AuditLinesAsync(); + var body = await Simulate("""{"application_id":"demo-app","profile_id":"public-demo","prompt":"Rewrite this public announcement."}"""); + + Assert.Equal("route", body.GetProperty("decision").GetString()); + Assert.Equal("Public", body.GetProperty("classification").GetString()); + Assert.Equal("Public", body.GetProperty("baseline").GetString()); + Assert.Equal("public", body.GetProperty("policy_id").GetString()); + Assert.Equal($"openai/{V2.CloudModel}", body.GetProperty("primary").GetString()); + Assert.Equal($"ollama/{V2.LocalTag}", body.GetProperty("fallbacks")[0].GetString()); + Assert.Equal(1, body.GetProperty("config_version").GetInt32()); + + Assert.Equal(0, _factory.Cloud.Calls + _factory.Local.Calls); // tripwires untouched + var (_, status, _) = await V2Admin.SendAsync(_client, HttpMethod.Get, "/admin/status"); + Assert.Equal(0m, status.GetProperty("budget").GetProperty("global_spend_usd").GetDecimal()); + Assert.Equal(0, status.GetProperty("finops").GetProperty("requests").GetInt32()); + + // FIFO proof (single-reader sink): once a later real request's record is on disk, anything the simulation + // had enqueued would be too. Exactly one new line ⇒ the simulation wrote nothing. + using var app = _factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "demo-key"); + using var real = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("after the dry run")); + var id = CorrelationTestKit.HeaderId(real); + await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal(before + 1, AuditChainVerifier.VerifyAndRead(_factory.AuditPath).Entries.Count); + } + + [Fact] + public async Task Dry_run_shows_detector_escalation_and_cloud_exclusion() + { + var body = await Simulate("""{"application_id":"demo-app","profile_id":"public-demo","prompt":"Public notice, SSN 123-45-6789"}"""); + Assert.Equal("Pii", body.GetProperty("classification").GetString()); + Assert.Equal("Public", body.GetProperty("baseline").GetString()); + Assert.Equal("US SSN pattern", body.GetProperty("detected_signal").GetString()); + Assert.Equal($"ollama/{V2.LocalTag}", body.GetProperty("primary").GetString()); + + var refused = await Simulate($$"""{"application_id":"demo-app","profile_id":"public-demo","prompt":"Public notice, SSN 123-45-6789","model":"{{V2.CloudModel}}"}"""); + Assert.Equal("refuse", refused.GetProperty("decision").GetString()); + Assert.Equal(0, _factory.Cloud.Calls + _factory.Local.Calls); + } + + [Fact] + public async Task Dry_run_refuses_ungranted_profiles_and_unknown_applications() + { + var ungranted = await Simulate("""{"application_id":"demo-app","profile_id":"phi-anything","prompt":"x"}"""); + Assert.Equal("refuse", ungranted.GetProperty("decision").GetString()); + Assert.Contains("not granted", ungranted.GetProperty("reason").GetString(), StringComparison.Ordinal); + + var unknown = await Simulate("""{"application_id":"ghost","prompt":"x"}"""); + Assert.Equal("refuse", unknown.GetProperty("decision").GetString()); + } + + [Fact] + public async Task Dry_run_against_a_candidate_uses_it_without_applying_it() + { + var (_, cfg, _) = await V2Admin.GetConfigAsync(_client); + var paused = cfg with { Policies = cfg.Policies.Select(p => p.Id == "public" ? p with { Paused = true } : p).ToList() }; + var json = JsonSerializer.Serialize(new SimulateRequest + { + ApplicationId = "demo-app", ProfileId = "public-demo", Prompt = "Rewrite this public announcement.", Config = paused, + }, ConfigJsonContext.Default.SimulateRequest); + + var body = await Simulate(json); + Assert.Equal("refuse", body.GetProperty("decision").GetString()); + Assert.Contains("paused", body.GetProperty("reason").GetString(), StringComparison.Ordinal); + Assert.Equal(1, (await V2Admin.GetConfigAsync(_client)).Version); // never applied + Assert.Equal(0, _factory.Cloud.Calls + _factory.Local.Calls); + } + + [Fact] + public async Task Simulator_is_admin_only() + { + using var anon = _factory.CreateClient(); + var resp = await anon.PostAsync("/admin/policies/simulate", + new StringContent("""{"application_id":"demo-app","prompt":"x"}""", System.Text.Encoding.UTF8, "application/json")); + Assert.Equal(HttpStatusCode.Unauthorized, resp.StatusCode); + } +} diff --git a/tests/Covenant.Tests/SnapshotIsolationTests.cs b/tests/Covenant.Tests/SnapshotIsolationTests.cs new file mode 100644 index 0000000..d611f2a --- /dev/null +++ b/tests/Covenant.Tests/SnapshotIsolationTests.cs @@ -0,0 +1,114 @@ +using System.Net; +using System.Net.Http.Headers; +using Covenant.Adapters; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// ADR-0011 isolation: every request binds to ONE configuration version. A request in flight on v1 keeps +/// v1's policy and prices while v2 is applied; the next request sees v2. Retired snapshots dispose their provider +/// clients only after their last in-flight request releases them. +public sealed class SnapshotIsolationTests : IDisposable +{ + private readonly HybridSeedFactory _factory = new(); + + public void Dispose() => _factory.Dispose(); + + [Fact] + public async Task In_flight_request_keeps_v1_policy_and_prices_while_v2_is_applied() + { + var admin = _factory.CreateClient(); + using var app = _factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + app.DefaultRequestHeaders.Add("X-Covenant-Profile", "public-demo"); + + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _factory.Cloud.Gate = gate; + var first = app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this public product announcement.")); + await _factory.Cloud.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); // provider call genuinely in flight on v1 + + // v2: cloud price ×100 AND the Public policy paused. + var (_, v1, _) = await V2Admin.GetConfigAsync(admin); + var v2 = v1 with + { + Connections = v1.Connections.Select(c => c.Id != "openai" ? c : c with + { + Models = c.Models.Select(m => m.ModelId != V2.CloudModel ? m : m with + { + Price = new PriceConfig { InputPer1M = 15m, OutputPer1M = 60m, Basis = "contract" }, + }).ToList(), + }).ToList(), + Policies = v1.Policies.Select(p => p.Id == "public" ? p with { Paused = true } : p).ToList(), + }; + Assert.Equal(2, await V2Admin.ApplyAsync(admin, v2, 1, "reprice + pause public")); + + gate.SetResult(); + using var firstResp = await first; + Assert.Equal(HttpStatusCode.OK, firstResp.StatusCode); + var firstEntry = await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(firstResp)); + Assert.Equal(1, firstEntry.ConfigVersion); + Assert.Equal(V2.CloudModel, firstEntry.ServedByModel); + Assert.Equal(1000 / 1_000_000m * 0.15m + 1000 / 1_000_000m * 0.60m, firstEntry.Usage.CostUsd); // v1 price, not v2's + + using var second = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this public product announcement.")); + Assert.Equal(HttpStatusCode.Forbidden, second.StatusCode); + var secondEntry = await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(second)); + Assert.Equal(2, secondEntry.ConfigVersion); + Assert.Contains("paused", secondEntry.Reason, StringComparison.Ordinal); + Assert.Equal(1, _factory.Cloud.Calls); + } + + [Fact] + public void Retired_snapshot_disposes_its_clients_only_after_the_last_request_releases_it() + { + var oldClient = new GatedChatClient(); + var v1 = new RuntimeSnapshot(V2.Hybrid(), new ProviderClientSet(new Dictionary { ["ollama:" + V2.LocalTag] = oldClient })); + var holder = new SnapshotHolder(v1); + + var inFlight = holder.Acquire(); + Assert.Same(v1, inFlight); + Assert.Equal(2, v1.RefCount); + + var v2 = new RuntimeSnapshot(V2.Hybrid(version: 2)); + holder.Swap(v2); + Assert.Same(v2, holder.Current); + Assert.False(v1.IsDisposed); // still used by the in-flight request + Assert.False(oldClient.Disposed); + Assert.True(inFlight.GetResource()!.TryResolve("ollama", V2.LocalTag, out _)); + + inFlight.Release(); + Assert.True(v1.IsDisposed); + Assert.True(oldClient.Disposed); + + var next = holder.Acquire(); + Assert.Same(v2, next); + next.Release(); + Assert.False(v2.IsDisposed); // the holder still owns the current snapshot + } + + [Fact] + public async Task Concurrent_acquire_and_swap_never_hand_out_a_disposed_snapshot() + { + var holder = new SnapshotHolder(new RuntimeSnapshot(V2.Hybrid())); + using var stop = new CancellationTokenSource(TimeSpan.FromMilliseconds(300)); + int handedOutDisposed = 0; + var readers = Enumerable.Range(0, 4).Select(_ => Task.Run(() => + { + while (!stop.IsCancellationRequested) + { + var s = holder.Acquire(); + if (s.IsDisposed) Interlocked.Increment(ref handedOutDisposed); + s.Release(); + } + })).ToList(); + int version = 1; + while (!stop.IsCancellationRequested) + holder.Swap(new RuntimeSnapshot(V2.Hybrid(version: ++version))); + await Task.WhenAll(readers); + Assert.Equal(0, handedOutDisposed); + } +} diff --git a/tests/Covenant.Tests/TraceTests.cs b/tests/Covenant.Tests/TraceTests.cs new file mode 100644 index 0000000..e9b155f --- /dev/null +++ b/tests/Covenant.Tests/TraceTests.cs @@ -0,0 +1,240 @@ +using System.Net; +using System.Text.Json; +using Covenant.Core; +using Covenant.Host; +using Xunit; + +namespace Covenant.Tests; + +/// ADR-0013 real request trace: emitted by the pipeline itself (server UTC time, Stopwatch durations, bounded +/// reason codes), buffered BEFORE the pipeline starts, served as snapshot and SSE (replay-then-live, Last-Event-ID), +/// skipped stages explicit, compact summary persisted in the audit record. +public sealed class TraceTests : IDisposable +{ + private static readonly string[] Stages = ["auth", "shape", "classify", "policy", "cache", "rate_limit", "pause", "budget", "provider", "attribution"]; + + private readonly HybridSeedFactory _factory = new(); + private readonly HttpClient _client; + + public TraceTests() => _client = _factory.CreateClient(); + + public void Dispose() => _factory.Dispose(); + + private static List<(long Id, string? Event, JsonElement Data)> ParseSse(string body) + { + var list = new List<(long, string?, JsonElement)>(); + foreach (var block in body.Split("\n\n", StringSplitOptions.RemoveEmptyEntries)) + { + long id = 0; + string? evt = null; + string? data = null; + foreach (var line in block.Split('\n')) + { + if (line.StartsWith("id: ", StringComparison.Ordinal)) id = long.Parse(line[4..], System.Globalization.CultureInfo.InvariantCulture); + else if (line.StartsWith("event: ", StringComparison.Ordinal)) evt = line[7..]; + else if (line.StartsWith("data: ", StringComparison.Ordinal)) data = line[6..]; + } + if (data is null) continue; + list.Add((id, evt, JsonDocument.Parse(data).RootElement.Clone())); + } + return list; + } + + private async Task RunConsoleAsync(string json) + { + using var resp = await Playground.PostAsync(_client, json); + return CorrelationTestKit.HeaderId(resp); + } + + private async Task<(HttpStatusCode Status, string Body)> GetAsync(string path, string? lastEventId = null) + { + using var req = CorrelationTestKit.Admin(HttpMethod.Get, path); + if (lastEventId is not null) req.Headers.TryAddWithoutValidation("Last-Event-ID", lastEventId); + using var resp = await _client.SendAsync(req); + return (resp.StatusCode, await resp.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task Subscribing_after_completion_replays_every_event_then_ends() + { + var id = await RunConsoleAsync(Playground.Body("demo-app", "Summarize this public announcement.", profile: "public-demo")); + var (status, body) = await GetAsync($"/admin/requests/{id}/trace/stream"); + Assert.Equal(HttpStatusCode.OK, status); + var events = ParseSse(body); + Assert.Equal("end", events[^1].Event); + var data = events.Where(e => e.Event is null).ToList(); + Assert.Equal(Enumerable.Range(1, data.Count).Select(i => (long)i), data.Select(e => e.Id)); // monotonic seq from 1 + Assert.All(data, e => Assert.Equal(id, e.Data.GetProperty("request_id").GetString())); + Assert.All(data, e => Assert.Equal(1, e.Data.GetProperty("config_version").GetInt32())); + + foreach (var stage in Stages) + { + Assert.Contains(data, e => e.Data.GetProperty("stage").GetString() == stage && e.Data.GetProperty("state").GetString() == "running"); + var terminal = data.Last(e => e.Data.GetProperty("stage").GetString() == stage && e.Data.GetProperty("state").GetString() != "running"); + Assert.Equal("passed", terminal.Data.GetProperty("state").GetString()); + Assert.True(terminal.Data.GetProperty("duration_ms").GetDouble() >= 0); + } + var attempt = data.First(e => e.Data.TryGetProperty("attempt_id", out _)); + Assert.Equal("att_1", attempt.Data.GetProperty("attempt_id").GetString()); + Assert.Equal($"openai/{V2.CloudModel}", attempt.Data.GetProperty("target").GetString()); + Assert.DoesNotContain("public announcement", body, StringComparison.Ordinal); // never content + Assert.DoesNotContain("cloud reply", body, StringComparison.Ordinal); + + // Snapshot: same events, complete. + var (snapStatus, snap) = await GetAsync($"/admin/requests/{id}/trace"); + Assert.Equal(HttpStatusCode.OK, snapStatus); + using var doc = JsonDocument.Parse(snap); + Assert.True(doc.RootElement.GetProperty("complete").GetBoolean()); + Assert.Equal(data.Count, doc.RootElement.GetProperty("events").GetArrayLength()); + + // Durable compact summary in the audit record. + var audit = await CorrelationTestKit.LookupAsync(_client, id); + Assert.NotNull(audit.Trace); + Assert.All(Stages.Where(s => s != "provider"), s => Assert.Contains(audit.Trace!, t => t.Stage == s && t.State == "passed")); + Assert.Contains(audit.Trace!, t => t.Stage == "provider" && t.AttemptId == "att_1" && t.State == "passed"); + } + + [Fact] + public async Task Last_Event_ID_resumes_after_the_given_sequence() + { + var id = await RunConsoleAsync(Playground.Body("demo-app", "an internal question")); + var (_, all) = await GetAsync($"/admin/requests/{id}/trace/stream"); + int total = ParseSse(all).Count(e => e.Event is null); + var (_, resumed) = await GetAsync($"/admin/requests/{id}/trace/stream", lastEventId: "5"); + var events = ParseSse(resumed).Where(e => e.Event is null).ToList(); + Assert.Equal(total - 5, events.Count); + Assert.Equal(6, events[0].Id); + Assert.Equal("end", ParseSse(resumed)[^1].Event); + } + + [Fact] + public async Task Refusal_marks_every_stage_not_entered_as_skipped_not_reached() + { + var id = await RunConsoleAsync(Playground.Body("demo-app", "hello", profile: "not-granted")); + var (_, snap) = await GetAsync($"/admin/requests/{id}/trace"); + using var doc = JsonDocument.Parse(snap); + var events = doc.RootElement.GetProperty("events").EnumerateArray().ToList(); + var auth = events.Last(e => e.GetProperty("stage").GetString() == "auth"); + Assert.Equal("refused", auth.GetProperty("state").GetString()); + Assert.Equal("governance_denied", auth.GetProperty("reason_code").GetString()); + foreach (var stage in Stages.Skip(1)) + { + var ev = Assert.Single(events, e => e.GetProperty("stage").GetString() == stage); + Assert.Equal("skipped", ev.GetProperty("state").GetString()); + Assert.Equal("not_reached", ev.GetProperty("reason_code").GetString()); + } + var entry = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Contains(entry.Trace!, t => t.Stage == "provider" && t.State == "skipped" && t.ReasonCode == "not_reached"); + Assert.Empty(entry.Attempts!); + } + + [Fact] + public async Task A_subscriber_joining_mid_request_gets_the_early_events_then_live_ones_until_the_end() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var client = factory.CreateClient(); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + factory.Cloud.Gate = gate; + factory.Cloud.Then(StubChatClient.Mode.StreamGated); + + // Streaming console request: headers (with the request id) commit on the first delta; the provider then waits. + using var req = CorrelationTestKit.Admin(HttpMethod.Post, "/admin/playground/requests"); + req.Content = new StringContent(Playground.Body("demo-app", "Summarize this public announcement.", profile: "public-demo", stream: true), + System.Text.Encoding.UTF8, "application/json"); + using var resp = await client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + + using var streamReq = CorrelationTestKit.Admin(HttpMethod.Get, $"/admin/requests/{id}/trace/stream"); + using var stream = await client.SendAsync(streamReq, HttpCompletionOption.ResponseHeadersRead); + Assert.Equal(HttpStatusCode.OK, stream.StatusCode); + + using var snapReq = CorrelationTestKit.Admin(HttpMethod.Get, $"/admin/requests/{id}/trace"); + using var snapResp = await client.SendAsync(snapReq); + using (var snap = JsonDocument.Parse(await snapResp.Content.ReadAsStringAsync())) + { + Assert.False(snap.RootElement.GetProperty("complete").GetBoolean()); // still in flight + var first = snap.RootElement.GetProperty("events")[0]; + Assert.Equal(1, first.GetProperty("seq").GetInt64()); + Assert.Equal("auth", first.GetProperty("stage").GetString()); // the very first event was retained + Assert.Equal("running", first.GetProperty("state").GetString()); + } + + gate.SetResult(); + var body = await stream.Content.ReadAsStringAsync(); // completes when the server writes event: end + await resp.Content.ReadAsStringAsync(); + var events = ParseSse(body); + Assert.Equal("end", events[^1].Event); + var data = events.Where(e => e.Event is null).ToList(); + Assert.Equal(1, data[0].Id); + Assert.Equal(Enumerable.Range(1, data.Count).Select(i => (long)i), data.Select(e => e.Id)); + Assert.Contains(data, e => e.Data.GetProperty("stage").GetString() == "attribution" && e.Data.GetProperty("state").GetString() == "passed"); + } + + [Fact] + public async Task Unknown_trace_is_404_and_malformed_id_is_400() + { + var (status, _) = await GetAsync("/admin/requests/req_00000000000000000000000000000000/trace"); + Assert.Equal(HttpStatusCode.NotFound, status); + var (streamStatus, _) = await GetAsync("/admin/requests/req_00000000000000000000000000000000/trace/stream"); + Assert.Equal(HttpStatusCode.NotFound, streamStatus); + var (bad, _) = await GetAsync("/admin/requests/bad%20id/trace"); + Assert.Equal(HttpStatusCode.BadRequest, bad); + using var noToken = await _client.GetAsync("/admin/requests/req_00000000000000000000000000000000/trace"); + Assert.Equal(HttpStatusCode.Unauthorized, noToken.StatusCode); + } +} + +/// TraceHub bounds and retention (no Host). +public sealed class TraceHubTests +{ + private static PipelineTraceEvent Ev(string stage, string state) => new(stage, state, DateTimeOffset.UtcNow); + + [Fact] + public void Expired_traces_are_410_not_404_and_unknown_ids_are_404() + { + var clock = new SettableClock(DateTimeOffset.Parse("2026-10-17T10:00:00Z")); + var hub = new TraceHub(clock); + var b = hub.Begin("req_a", 1, retentionMinutes: 10); + b.Append(Ev("auth", "running")); + b.Complete(clock.GetUtcNow()); + clock.Advance(TimeSpan.FromMinutes(9)); + Assert.Equal(TraceHub.Lookup.Found, hub.TryGet("req_a", out _)); + clock.Advance(TimeSpan.FromMinutes(2)); + Assert.Equal(TraceHub.Lookup.Expired, hub.TryGet("req_a", out _)); + Assert.Equal(TraceHub.Lookup.Unknown, hub.TryGet("req_never", out _)); + } + + [Fact] + public void Events_and_requests_are_bounded() + { + var hub = new TraceHub(maxRequests: 3, maxEventsPerRequest: 4); + var b = hub.Begin("req_0", 1, 10); + for (int i = 0; i < 10; i++) b.Append(Ev("auth", "running")); + var snap = b.Snapshot(); + Assert.Equal(4, snap.Events.Count); + Assert.True(snap.Truncated); + b.Complete(DateTimeOffset.UtcNow); + + for (int i = 1; i <= 3; i++) hub.Begin($"req_{i}", 1, 10); // a 4th buffer evicts the oldest COMPLETED one + Assert.Equal(TraceHub.Lookup.Expired, hub.TryGet("req_0", out _)); + Assert.Equal(TraceHub.Lookup.Found, hub.TryGet("req_3", out _)); + } + + [Fact] + public void A_completed_buffer_accepts_no_more_events_and_wakes_waiters() + { + var hub = new TraceHub(); + var b = hub.Begin("req_x", 2, 10); + var (_, complete, changed) = b.Since(0); + Assert.False(complete); + b.Append(Ev("auth", "running")); + Assert.True(changed.IsCompleted); + var (_, _, next) = b.Since(1); + b.Complete(DateTimeOffset.UtcNow); + Assert.True(next.IsCompleted); + b.Append(Ev("shape", "running")); + Assert.Single(b.Snapshot().Events); + Assert.Equal(2, b.Snapshot().ConfigVersion); + } +} diff --git a/tests/Covenant.Tests/WireShapeTests.cs b/tests/Covenant.Tests/WireShapeTests.cs index 2531f42..f5c9fbe 100644 --- a/tests/Covenant.Tests/WireShapeTests.cs +++ b/tests/Covenant.Tests/WireShapeTests.cs @@ -167,7 +167,7 @@ private sealed class CapturingClient : MEAI.IChatClient public Task GetResponseAsync(IEnumerable m, MEAI.ChatOptions? o = null, CancellationToken ct = default) { Seen = o; return Task.FromResult(new MEAI.ChatResponse(new MEAI.ChatMessage(MEAI.ChatRole.Assistant, "ok")) { Usage = new MEAI.UsageDetails { InputTokenCount = 1, OutputTokenCount = 1 } }); } public async IAsyncEnumerable GetStreamingResponseAsync(IEnumerable m, MEAI.ChatOptions? o = null, [EnumeratorCancellation] CancellationToken ct = default) - { Seen = o; await Task.Yield(); yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, "ok"); } + { Seen = o; await Task.Yield(); yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, "ok"); yield return new MEAI.ChatResponseUpdate { FinishReason = MEAI.ChatFinishReason.Stop }; } public object? GetService(Type t, object? k = null) => null; public void Dispose() { } } @@ -205,14 +205,14 @@ public Ingress(WebApplicationFactory factory) b.UseSetting("Auth:Keys:0:Key", "k"); b.UseSetting("Auth:Keys:0:Principal", "shape-tester"); b.UseSetting("Auth:Keys:0:Team", "t"); - b.UseSetting("Audit:Path", _auditPath); + CorrelationTestKit.IsolatePaths(b, _auditPath); }); _client = _factory.CreateClient(); _client.DefaultRequestHeaders.Add("x-api-key", "k"); _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "k"); } - public void Dispose() { _factory.Dispose(); if (File.Exists(_auditPath)) File.Delete(_auditPath); } + public void Dispose() { _factory.Dispose(); CorrelationTestKit.DeleteWithSiblings(_auditPath); } private static StringContent Body(string json) => new(json, Encoding.UTF8, "application/json");