diff --git a/Covenant.sln b/Covenant.sln index 7cd2f53..9de1879 100644 --- a/Covenant.sln +++ b/Covenant.sln @@ -14,6 +14,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Covenant.Governance", "src\ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Covenant.Host", "src\Covenant.Host\Covenant.Host.csproj", "{13CD101B-CB05-4632-966E-8DAAD7DB34DD}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Covenant.Ui", "src\Covenant.Ui\Covenant.Ui.csproj", "{4F1C2B7E-9D3A-4B86-A2E5-6C0D8F7B1E42}" +EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Covenant.Tests", "tests\Covenant.Tests\Covenant.Tests.csproj", "{8C7AC33C-9BF8-413E-9227-D179A0245892}" EndProject Global @@ -38,6 +40,10 @@ Global {13CD101B-CB05-4632-966E-8DAAD7DB34DD}.Debug|Any CPU.Build.0 = Debug|Any CPU {13CD101B-CB05-4632-966E-8DAAD7DB34DD}.Release|Any CPU.ActiveCfg = Release|Any CPU {13CD101B-CB05-4632-966E-8DAAD7DB34DD}.Release|Any CPU.Build.0 = Release|Any CPU + {4F1C2B7E-9D3A-4B86-A2E5-6C0D8F7B1E42}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4F1C2B7E-9D3A-4B86-A2E5-6C0D8F7B1E42}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4F1C2B7E-9D3A-4B86-A2E5-6C0D8F7B1E42}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4F1C2B7E-9D3A-4B86-A2E5-6C0D8F7B1E42}.Release|Any CPU.Build.0 = Release|Any CPU {8C7AC33C-9BF8-413E-9227-D179A0245892}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8C7AC33C-9BF8-413E-9227-D179A0245892}.Debug|Any CPU.Build.0 = Debug|Any CPU {8C7AC33C-9BF8-413E-9227-D179A0245892}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -51,6 +57,7 @@ Global {E28BD9F8-FBB1-4D29-BC1D-97F6E3AA59DF} = {7DBFEF37-7328-4DE7-B219-1B311679A9F1} {A83FBCC1-65D4-4604-BA54-46DEF55E3B0C} = {7DBFEF37-7328-4DE7-B219-1B311679A9F1} {13CD101B-CB05-4632-966E-8DAAD7DB34DD} = {7DBFEF37-7328-4DE7-B219-1B311679A9F1} + {4F1C2B7E-9D3A-4B86-A2E5-6C0D8F7B1E42} = {7DBFEF37-7328-4DE7-B219-1B311679A9F1} {8C7AC33C-9BF8-413E-9227-D179A0245892} = {1AFC3317-7EBB-410A-9065-0CE302297F63} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution diff --git a/docs/PROVENANCE.md b/docs/PROVENANCE.md index f30c22e..eb03b48 100644 --- a/docs/PROVENANCE.md +++ b/docs/PROVENANCE.md @@ -22,5 +22,9 @@ No third-party source code has been copied into this repository. Everything belo - `OpenTelemetry.Extensions.Hosting` / `OpenTelemetry.Exporter.OpenTelemetryProtocol` 1.17.0 — Apache-2.0. Host-only, activated only when `Otel:Endpoint` is configured (ADR-0003). Core instruments via BCL `ActivitySource` and takes no OTel dependency. - `Neo4j.Driver` 6.2.1 — Apache-2.0, official Bolt driver. Host-only, activated only when `Neo4j:Uri` is configured (ADR-0006 evidence graph projection). - `Anthropic` 12.8.0 — MIT, official Anthropic SDK (IChatClient integration). Host-only, activated only when `Anthropic:ApiKey` is configured (ADR-0001 provider start set). +- Console (`src/Covenant.Ui`, ADR-0004 standalone Blazor WebAssembly; compiled to static assets and embedded in the Host — never loaded into the Host process): `Microsoft.AspNetCore.Components.WebAssembly` 10.0.11 — MIT; `Microsoft.AspNetCore.Components.WebAssembly.DevServer` 10.0.11 — MIT, build/dev-time only (`PrivateAssets=all`), not in the published bundle. Pinned against nuget.org 2026-10-16. + +## Bundled assets (not code) +- **IBM Plex Sans** (400/500/600, latin subset) and **IBM Plex Mono** (400/500, latin subset) — Copyright 2018 IBM Corp., **SIL Open Font License 1.1**. Copied from `covenant-prototype/fonts/` into `src/Covenant.Ui/wwwroot/fonts/` as `.woff2` together with both licence texts (`LICENSE-ibm-plex-sans.txt`, `LICENSE-ibm-plex-mono.txt`) and the `@font-face` declarations in `fonts/fonts.css`. Served only from the appliance (`/ui/fonts/*`); nothing is fetched from a CDN. The OFL permits bundling and redistribution with the licence; the fonts are not sold on their own and are not renamed (Reserved Font Name "Plex" is kept). _Update this file in the same change as any code that introduces a new influence or dependency._ diff --git a/docs/UI-implementation-tasks.txt b/docs/UI-implementation-tasks.txt new file mode 100644 index 0000000..b44746b --- /dev/null +++ b/docs/UI-implementation-tasks.txt @@ -0,0 +1,305 @@ +COVENANT UI + BACKEND IMPLEMENTATION TASKS +Implementation brief for Claude — 16 October 2026 + +START HERE + +Implement the revised Covenant design in the existing .NET repository. This is +an implementation assignment, not another design exercise. Preserve its visual +direction and make the controls operate the real governed pipeline. + +Design reference: +/Users/commandor/Library/CloudStorage/OneDrive-Personal/Projects/My docs/Topics/VSLive!/2026/covenant-prototype + +Read README.md, Handoff.dc.html, the relevant page sources and tokens.css there. +Read the repository CLAUDE.md files and accepted ADRs first. ADR-0004 already +selects standalone Blazor WebAssembly embedded as assets in the minimal-API host. +The request/evidence browser triggers that migration. Do not introduce React, +Blazor Server, a second production server, or ship the prototype runtime. + +Work through the numbered tasks in dependency order. Use small reviewable +changes with meaningful tests. Do not commit or publish unless separately asked. +Do not overwrite unrelated local work. The existing UI-redesign-brief.txt is +user work to preserve. Significant contract/storage decisions need an ADR before +code, as required by the repository. Routine choices do not need another round +of user approval. Keep a short progress record with task status and test results. + +The source code is authoritative about existing behaviour. Handoff is useful +but not a complete API specification. Do not copy fixture claims into real UI. +The existing audit already contains Signal; don't declare it universally absent. + +DELIVERY SCOPE + +First deliver a working vertical slice: real sign-in, real request, real result, +matching audit evidence, and one working Ollama/Qwen route. Then complete the +remaining read-only pages and harden the demo. No policy/budget editor, multiple +local models, full archive search, model downloading, or provider proliferation +in this slice. Open WebUI is an optional client of Covenant, not a new backend. + +TASK 01 — UI shell and appliance packaging +Dependencies: none. + +Create a standalone Blazor WASM UI project. Build and embed its production assets +in Covenant.Host using ADR-0004. Serve the UI through the existing appliance; +retain the inference and admin APIs. Provide reliable nested-route reloads, +correct MIME types and WASM loading from the published artifact. + +Port the shared shell, navigation, colour/type tokens, dark/light themes and +locally bundled fonts. Record font licences/provenance. Use shared components +for statuses, buttons, drawers, request facts and errors. No external CDNs. + +Implement Connect/disconnect against the real admin API. Keep admin credentials +separate from application credentials. An application key stays in UI memory; +never persist it, prompts or responses in localStorage. Preserve the established +tab-scoped admin-token behaviour, clear it on disconnect, and never display/log +secrets. Remove seeded keys and identity claims. Identity is server-resolved. + +Use one application state service for status, pause state and freshness across +navigation. Read real status updates, handle reconnect/401/staleness, and render +mutation failures without falsely claiming success. Disconnecting the console +does not pause Covenant. Data pages must not remain falsely authenticated. + +Acceptance: +- Published single appliance serves the UI and assets without a separate server. +- Invalid token, disconnect, API outage and reconnect have correct visible states. +- Pause/resume uses POST /admin/kill-switch and stays consistent across pages. +- No fixture runtime, canned results or external font requests ship. +- Keyboard focus, labels, drawer close/Escape and focus restoration work. + +TASK 02 — Stable request identity and exact evidence lookup +Dependencies: none; finish before wiring Playground evidence. + +Choose and document one server-generated request correlation ID, created before +pipeline execution and returned even for governed refusals. Propagate it through +the canonical context, buffered responses, streaming response headers and audit. +Keep the existing audit-record identity if useful; define the mapping explicitly. +Do not trust a caller-supplied ID as unique or use timestamps to join records. + +Add an admin-authenticated exact lookup API. The UI needs pending/not-yet-found, +found, unavailable/error and retry behaviour. Do not claim an audit write failed +merely because a bounded lookup timed out. Define lookup retention/snapshot +limits explicitly; full historical search is outside this task. + +Add explicit audit metadata needed by these screens: classification evaluated +state, structured final outcome/denial kind, selected versus attempted versus +served model, and stopping stage where actually known. Keep measured stage +timings deferred. Never infer a complete measured trace from a reason string. +Preserve the restrictive default classification used for enforcement. + +IMPORTANT: adding fields can change serialized bytes used by audit hashing. +Document a versioned/backward-compatible approach before implementation. Existing +logs and anchors must still verify without rewriting history. Legacy missing +fields display 'Not recorded', not fabricated facts. Check audit enqueue on client +cancellation: cancellation must not silently prevent the required audit record. +Define what happens to malformed requests rejected before canonical execution. + +Acceptance: +- Concurrent requests, identical prompts and equal timestamps resolve correctly. +- Allow, auth denial, policy denial, pause, missing adapter, rate limit, upstream + failure and cancellation carry the right identity/outcome wherever supported. +- Mid-stream failure retains transport HTTP 200 but final outcome is failure. +- Existing audit fixtures, anchors and ledger replay still verify correctly. +- Lookup is admin-only, bounded and never exposes unconfigured prompt content. + +TASK 03 — Honest usage and estimated cost +Dependencies: coordinate audit schema with 02. + +Preserve the distinction between unreported token usage and a real zero through +adapter, attribution, audit, API and UI. The current provider adapter replaces +missing counts with zero. Do not copy that ambiguity into the new screens. +Use explicit availability metadata or a compatible nullable representation. + +Show 'Estimated provider cost' using configured prices and reported usage. +Show 'Not reported' for unknown billable usage. A refused request with no call +can legitimately show zero; a failed or cancelled provider call may not. +Local zero-priced inference is not free infrastructure. + +Define and document a fail-closed accounting response to unpriced/unknown usage; +do not silently let unknown billable calls escape budget enforcement. Keep the +decision narrow, test it, and expose any resulting uncertainty or blocking state. +Maintain pre-call threshold semantics and explain concurrent overshoot. Do not +claim that this budget is a guaranteed provider invoice ceiling. + +Acceptance: +- Tests cover complete, partial and missing usage, local zero price, no call, + cache hit, interrupted stream and provider failure. +- Unknown cost cannot become a false $0 or false saving in any aggregate. +- Ledger replay and old records remain compatible with the chosen representation. + +TASK 04 — Real Playground and presentation mode +Dependencies: 01, 02, 03. + +Reproduce Main.dc.html's normal and presentation layouts with real API calls. +Presets A–D populate inputs only. The actual pipeline decides the outcome. +Use an application key with POST /v1/chat/completions, never the admin token or +a direct provider call. Support buffered and streaming responses. + +Start empty; freeze a submitted request snapshot. Editing the form cannot +relabel its result. Prevent overlapping runs for this first version. Use the +server correlation ID, show asynchronous audit arrival with bounded retries, +and open the exact request in Requests. Add that same navigation action to the +presentation-mode evidence drawer, not just normal mode. + +Capture errors from both transport and stream termination. Cancellation means +'stopped waiting/incomplete' where appropriate, never a guarantee of rollback +or zero charge. Use the real model catalog and allow explicit test overrides +without suggesting that selecting a model grants permission. + +Correct a residual design issue: a route selected before a pause refusal or a +cache hit is not a model actually attempted. Display Selected model separately +from Provider attempted/Served model using observed backend facts. + +Scenario D needs a fresh value on every run or verified disabled caching. The +system's pause scope remains new provider calls; cache hits and in-flight work +are not retroactively stopped. No invented pipeline timings or checks. + +Acceptance: +- A succeeds; B refuses the unapproved model without a provider call. +- C fails closed without local registration and succeeds locally when configured. +- D refuses while paused, then succeeds after resume, repeatedly. +- Empty key yields real auth failure and 'classification not evaluated'. +- At 1280x720 and 1920x1080, prompt, Run, result, model, cost and evidence action + fit presentation mode without page scrolling; long output scrolls inside it. +- No prompts/responses or application keys persist after reload/disconnect. + +TASK 05 — Requests browser and evidence detail +Dependencies: 01, 02, 03; use the same view models as 04. + +Implement the full-width recent list and detail drawer from Requests.dc.html. +Filter the actual available snapshot; label its coverage and never imply full +audit history. Use stable IDs and retain filters/selection on navigation. +Exact deep links must open their record even when the current filter excludes +it: explain that condition rather than silently opening another request. + +Display recorded historical facts. Today's pause, policy or model health must +not recolour a past decision. Separate optional console-only response content +from persisted audit evidence. Show the existing Signal when present; legacy +missing classification-evaluated/stage data stays unknown. + +Acceptance: +- Open from Playground selects the same correlation/audit record every time. +- Filters, empty results, clear filters, row selection, close and keyboard work. +- Long model names/IDs remain readable at 1280px, without squeezing the table. +- Raw JSON agrees with visible facts and follows prompt-retention configuration. +- Removing a row from the recent window produces a clear unavailable state. + +TASK 06 — One real Ollama/Qwen connection +Dependencies: 02, 04; 01 for wizard UI. + +Extend the existing Local:Endpoint/Local:ModelId OpenAI-compatible adapter rather +than introducing another inference path. Support one exact installed Qwen tag. +Do not guess the user's host or tag, pull models automatically or change Ollama's +network exposure. Keep endpoint/tag inputs explicit and configurable. + +Add admin-authenticated, host-side probe and model discovery operations with +timeouts, response-size limits and an explicit operator-configured destination +allow-list. Validate scheme/host/port and redirects/resolution; this must not +become an arbitrary server-side URL fetcher. Allow intentionally approved local +addresses; localhost refers to Covenant's host/container, not the browser. +Never forward the Covenant admin/application token to Ollama. Provider secrets +remain server-side and are never returned to the browser. + +Expose applied configuration and an operational model catalog distinguishing +configured, registered, permitted, last successful observation, latest failure +and stale/unknown reachability. GET /v1/models alone is not a health check. + +Port the wizard gates: valid endpoint → successful probe → discovery → exact +single tag → route review → manual config/restart → read back applied config → +governed inference test. Generate safe configuration guidance without embedding +secrets. Runtime apply/edit is deferred. Make it explicit in the UI. + +The governed test must use an application key through the same pipeline as +Playground. The current design lacks that key flow: reuse the in-memory key or +ask for one; never treat admin sign-in as inference authorization. Link its real +request/evidence just like any other Playground request. + +Fix the residual stale-success problem: after a successful test, a later failed +test must update shared health to failed/degraded. Preserve last success time, +but don't leave the header green. A paused test is not proof the provider is +unreachable. Draft endpoint changes invalidate draft probe results; they must +not silently change or erase the applied running configuration. + +Provide explicit local-only startup configuration without requiring a cloud +key. Define routes deliberately; do not quietly reroute configured cloud traffic +or relax sensitive-data policy. Missing/invalid required configuration remains +fail-closed. Record an ADR for new startup/routing mode semantics before code. + +Acceptance: +- Mock contract tests cover reachable/refused/timeout/empty discovery/tag mismatch, + unauthorized destinations, redirects, stale results and response failures. +- A real smoke test with Alex's actual Ollama/tag proves buffered and streaming + inference, audit correlation, and no cloud fallback for protected content. +- Failed probe blocks progression; changing endpoint invalidates its draft checks. +- Applied config is read back; a checkbox is never proof of registration. +- Successful test followed by failure updates all pages consistently. +- Local-only mode starts without cloud secrets; incomplete mode configuration fails. +- Optional Open WebUI instructions use Covenant /v1 and an application key. + +TASK 07 — Overview, read-only controls and evidence pages +Dependencies: 01–03, 06 catalog/status. + +Implement Overview, Policies, Budgets, Evidence and Settings against real data. +Do not port the fixture store, hardcoded times, chart bars, default green statuses, +sample counters or fabricated hashes. If data is unavailable, show that state. +Charts must state their actual retained window; no synthetic history. + +Policies: show applied routes and actual processing order; no disabled editor +teasers. Budgets: cap, recorded spend, remaining, team attribution and uncertainty. +Keep savings secondary and show the baseline only if it is computable. + +Evidence: use existing chain verification and anchoring. Expose actual anchor +configuration/coverage/status without secrets. 'Configured' is not 'verified'. +Use the revised internal-consistency wording. Do not invent an independent anchor +or archived-segment browser. Export real verification data. + +Settings: read-only applied values; isolate archive/reset in Maintenance with +explicit confirmation of environment, segment and budget reopening. Do not use +reset as the fix for a reached budget or silently clear evidence for the demo. + +Acceptance: +- Pages agree on current environment, pause, health, counts and accounting scope. +- Failed verification, stale data, unknown usage and missing configuration are + represented accurately, not as normal green states. +- Archive/reset retains old evidence and behaves exactly as described. +- No destructive maintenance is invoked by normal navigation or scenario selection. + +TASK 08 — Automated validation, publish checks and conference handoff +Dependencies: all above. + +Run the repository test suite and targeted new integration tests. Automated tests +use fake adapters, never live paid providers. Run a real Ollama smoke separately +with supplied deployment inputs and synthetic data. Record it as blocked if the +endpoint/tag is unavailable; do not substitute fixtures and call it passed. + +Publish using the repo's supported deployment path. Check the NativeAOT path +explicitly and report any pre-existing limitations separately from regressions. +Prove the actual published binary serves UI/WASM/fonts and reloads nested routes. +Do not mark packaging done because dotnet run works. + +Prepare a short demo runbook: startup, preflight, A/B/C/D sequence, expected +outcomes, model warm-up, prompt retention, connectivity checks, and recovery from +provider outage. Keep demo.sh as an optional diagnostic/smoke tool; the normal +demo must be operable from the browser after startup. + +Provide the reviewer with: +- Baseline and final commit IDs plus uncommitted-file summary; no secrets. +- Completed task list and any explicit deferrals. +- Commands run, exit status and meaningful test output summaries. +- Run/publish instructions and required configuration NAMES only. +- Screenshots at 1280x720 and 1920x1080, light and dark; no visible credentials. +- Evidence IDs from the synthetic live smoke and whether it was truly live. +- Known limitations and any architecture decisions added. + +CODEX VERIFICATION ORDER AFTER CLAUDE IMPLEMENTS + +1. Inspect diff/ADRs for scope, dependency/provenance and audit compatibility. +2. Run unit/integration tests, especially fail-closed and audit-history tests. +3. Verify admin/app credential separation and authorized provider-probe boundary. +4. Run the published appliance; check navigation, no external assets and staleness. +5. Exercise real A/B/C/D, auth failure, provider outage, stream failure and cancel. +6. Match responses to exact audit records, including concurrent requests. +7. Check unknown usage, budget threshold, cache/pause and restart behaviour. +8. Check Ollama failure after success, draft versus applied config and key flow. +9. Review projection screenshots and rehearse without a terminal interaction. + +The reviewer independently verifies the implementation. Claude's 'done' summary +and passing fixture UI alone are not evidence of a working governed system. diff --git a/docs/UI-redesign-brief.txt b/docs/UI-redesign-brief.txt new file mode 100644 index 0000000..e773c1f --- /dev/null +++ b/docs/UI-redesign-brief.txt @@ -0,0 +1,187 @@ +Covenant UI redesign brief for Claude + +Purpose + +Redesign Covenant as an AI governance workspace that an operator can use and a presenter can demonstrate without switching to a terminal. Make the main journey obvious: configure an approved connection, run a request, understand its result, inspect its evidence, and stop or resume new provider calls. + +This is a design brief, not authorization to replace the application stack or invent completed backend capabilities. First deliver a clickable design prototype and implementation handoff. Keep design fixtures clearly separate from live results. Do not change the product code in the design pass. + +1. Product and design direction + +Covenant is a .NET application for governing model requests, attributing usage, and recording evidence. It is not another general-purpose chat application. A focused request playground belongs inside the product because it makes the controls observable. + +Keep the Covenant name. Use “AI governance workspace” as the short descriptor. Avoid the current long promise that every request is classified, routed, budgeted, attributed, and audited: early refusals and cache hits do not execute every stage. + +Use a restrained enterprise application style. Dark mode is the initial target, with a light-mode design variant for projection. Use neutral surfaces, one blue action accent, and semantic green/amber/red only for status. Remove glowing decorations, oversized metric cards, excessive uppercase headings, and empty space above navigation. Use a locally bundled sans-serif font and monospace only for identifiers, model names, and numbers where alignment helps. + +Desktop layout: a compact left navigation, a slim status header, and a useful working area. Optimize first for 1440×900 and 1920×1080; remain usable at 1280×720. Normal body text 16px, secondary text at least 14px. Presentation mode uses approximately 20–24px for key request results. Do not squeeze every field into one screen. + +Use tables where people need to scan many requests or compare models. Use a detail drawer or full detail view for one request. Do not turn every setting into a card or display a wall of raw JSON as the main experience. + +2. Navigation and global states + +Main navigation: Overview, Playground, Requests, Models & connections, Policies, Budgets, Evidence. Settings and the connection/account control sit at the bottom. “Pipeline” becomes a contextual request-flow view and a small explanation inside Policies, rather than a primary destination competing with actual work. + +Header: environment name, service condition, data freshness, and a persistent “Pause new model calls” control. Never show a green “Serving” badge based only on an open status stream or an unengaged stop switch. Distinguish “Console connected,” “Provider available,” and “Requests paused.” A missing local route should produce a visible degraded-state alert with “Review connection.” + +Current authentication is a shared admin token, not a named-user identity system. Show “Connected with admin token,” the environment, and Disconnect. Do not invent an avatar, named account, role picker, SSO, or tenant switcher. Design a dedicated connection screen with a masked token field, Connect, validation feedback, and clear disconnected/invalid-token/connection-lost states. Preserve navigation when reconnecting where safe. + +Authentication for administration and authentication for sending model requests are separate. Connecting to the console must not silently grant an application unlimited inference access. + +3. Overview + +Answer “What needs attention?” before showing historical statistics. + +Top: one concise alert for a missing connection, stopped calls, invalid audit chain, or stale data. Each alert links to an appropriate action. Then a compact summary row: served requests, refused/failed requests, provider charges, and budget used. Show the time range or audit segment for every total. A new screen visit does not reset accounting. + +Below: a modest request activity chart and a list of recent notable outcomes. Keep cost and request-count charts separate, or provide clearly labeled units and axes; do not overlay money and counts on an unlabeled scale. Provide a 15-minute, 1-hour, or available-history selector only if the data supports it. + +Move estimated savings into Budgets as a secondary analysis with its baseline explained. Rename it “Estimated provider charge avoided” if that is what the calculation measures. Local inference is not economically free: $0 provider token charges excludes hardware, electricity, and operations. + +“Run a request” is the primary action. “View requests” is secondary. Audit verification is a concise status linked to Evidence, not a large duplicate request-count card. + +4. Playground — the priority screen + +This is the conference demo workspace and the operator’s diagnostic starting point. + +Use two main columns: request setup on the left, result on the right. At the bottom, a collapsible evidence area follows the selected request. On smaller screens, stack setup above result. Keep the last result visible while preparing the next request. + +Request setup: +- Application credential context: display the server-resolved application/team. For the first implementation, accept a separate application key, masked and held only in memory. A subsequent server-managed test-identity selector needs an explicit authorized backend contract; it must not impersonate arbitrary callers. +- Routing choice: “Let policy choose” or a requested model from the allowed catalog. Provide an advanced explicit model field for testing a rejection; label it as a test input, not a permission grant. +- Prompt editor with a short synthetic default, output-token limit, and streaming toggle. +- Workflow/use-case labels, clearly distinguished from the key-bound identity and team. +- Run request, Cancel, and Clear output. Explain that cancellation may leave work or charges already incurred; it is not rollback. + +Result: +- Large outcome: Served, Reused from cache, Policy denied, Authentication failed, Rate limited, Provider unavailable, or Cancelled/incomplete. Distinguish HTTP failure from a governance refusal. +- A plain-language reason and the actual HTTP status when available. +- Response text for the request the operator just submitted; no automatic response archive. +- Requested model versus actual model, provider/connection, measured duration, tokens when reported, and provider charges. Unknown values show “Not reported,” not fabricated zeroes. +- “View request evidence” links to the exact audit record once it arrives. Show “Awaiting audit record” while the asynchronous sink catches up. Never guess the matching record by the most recent timestamp. + +Request flow: +Show Authentication → Input validation → Classification → Policy and route selection → Cache → Rate limit → Operator stop and budget → Provider → Cost attribution. Audit wraps the request. This is the order assembled in Program.cs; do not copy a stale diagram from prose. + +A stage can be completed, denied, failed, skipped, not reached, or unknown. Show timings only when measured. The current API does not supply a full trace; until instrumentation exists, label this as “Configured processing order,” not an animated trace pretending to show actual execution. + +Scenario presets are useful, but they must make real requests: +A. Normal permitted request. +B. Valid application, unapproved requested model. +C. Synthetic sensitive-data fixture routed to an approved local Qwen model, or refused if no usable local route exists. +D. Pause new calls, then submit a fresh uncached request; resume and submit another. +Presets populate the request. Only Run sends it. Selecting a scenario must not silently change policy or global stop state. Compare the expected outcome with the actual outcome and show a mismatch honestly. + +5. Requests and request detail + +Keep a compact, filterable list with time, application/team, outcome, model, duration, and charge. Classification can be a secondary column. Search by request ID; filter by application, outcome, model, and time. Offer page-size and pagination controls based on the actual data scope. Client filtering of a recent snapshot must say “Recent requests,” not imply a full audit-log search. + +Selecting a row opens a detail drawer with this order: +1. Result and plain-language explanation. +2. Request ID, time, identity, requested/served model, and routing evidence. +3. Classification result and matched signal, if classification actually ran. +4. Usage, charges, cache result, and measured duration. +5. Audit evidence and optional raw JSON. + +Fix the misleading “hi”/PHI example in the supplied screenshot. The source initializes classification to PHI as a restrictive internal default. An authentication refusal occurs before classification. Display “Not evaluated — authentication failed,” not a detected-PHI badge. Preserve the restrictive enforcement default; add explicit evaluation state to the API instead of weakening the classifier. + +Keep historical results tied to the configuration at processing time. Never repaint old rows as though today’s policy applied then. Configuration version is a proposed backend field, not an existing fact. + +Content privacy: prompt previews remain opt-in. Show whether content is retained and what the retention scope is. The ordinary Requests page must not suddenly expose full prompts and responses. Hiding content in presentation mode does not erase stored content. + +6. Models & connections — Ollama and Qwen + +Separate the connection from its models. A connection has a display name, server-side base URL, provider type, credential reference if needed, approved boundary, and last-check state. Its model list shows exact IDs/tags, registered status, policy permission, and tested availability separately. + +Connection flow: choose Ollama → enter endpoint → Test connection → Discover installed models → select exact model tags → review proposed permitted routes → save/apply using the supported configuration workflow → run a governed test request. Discovery must not automatically approve every model. + +Do not guess the user’s Qwen tag, host address, or quantization. Do not substitute the current hard-coded llama model name. “Installed,” “registered,” “permitted,” and “reachable” are different states. + +The intended inference path is: +Covenant Playground → Covenant request pipeline → Ollama → installed Qwen model. + +Optional separate chat-client path: +Open WebUI → Covenant /v1 → Covenant request pipeline → Ollama → installed Qwen model. + +Open WebUI is a client in this design, not the local model runtime. Configuring Open WebUI to call Ollama directly bypasses Covenant. Its connection to Covenant needs a Covenant application key, never the admin token. Restrict validation initially to text chat and supported streaming; do not promise that all Open WebUI tools, images, background tasks, or other APIs are supported. + +Ollama’s documented local OpenAI-compatible base is http://localhost:11434/v1/. Here “localhost” means the machine/container running Covenant, not the presenter’s browser. A workstation or container deployment needs an address reachable from the Covenant host. Do not assume an Ollama endpoint or model is local-only merely because the provider type says Ollama; approval must verify the actual endpoint/model and egress behavior. + +First release: connect to an existing Ollama installation and use selected installed models. Model downloads, deletion, loading/unloading, GPU telemetry, and remote machine administration are later scope, not decorative buttons in the initial UI. No silent model pull or cloud fallback. If the local model fails, refuse the protected request and explain why. + +Display local provider charge as $0 only when that is the configured provider-charge basis. Label infrastructure costs as excluded or unconfigured. Never present an unknown cost as free. + +7. Policies, budgets, evidence, settings + +Policies: show current classification-to-route rules with a readable rule summary, configured models, and unresolved routes. For now this is read-only configuration. Add “Try in Playground.” Do not invent per-application model grants: current keys bind identity/team, while the routing policy is classification-based. A future editor needs validation, versioning, authorization, review/apply behavior, and rollback semantics before it is enabled. + +Budgets: global cap and team caps, spend basis, remaining budget, and applicable accounting period/segment. Explain that the current ledger is reconstructed from the audit log; it is not automatically a monthly billing cycle. Show threshold checks separately from an exact invoice cap. Keep the allocation example from the talk out of the product unless allocation functionality is actually implemented. + +Evidence: last verification time, chain status and scope, entry count, export, and independent anchor status when supported. “Chain verified” does not mean regulatory compliance, every event is present, or an independent anchor exists. Verification failures must remain prominent. + +Settings: environment and configuration source, active/applied configuration state, cache behavior, telemetry, content-preview retention, and connection/session details. Use “Managed by configuration; restart required” for current read-only values. Do not show a fake Save button. + +Put archive/reset behind a clearly separated maintenance action. Explain both effects: archive the audit segment and reset spend counters, potentially reopening budgets. Require confirmation showing the affected environment. Never delete the audit trail or use reset as the default way to start a demo. + +8. Pause control and presentation mode + +Replace “All inference stops instantly” with “Pause new provider calls.” Explain current scope: cache hits bypass this stage, in-flight work is not cancelled, and downstream actions are outside Covenant. The active banner reads “New provider calls paused” with reason and an explicit Resume action. Broader stopping behavior requires a backend change and tests. + +Presentation mode enlarges the Playground result and key evidence, hides navigation noise and sensitive fields, and keeps the active environment plus live/test-adapter mode visible. It does not change policy, credentials, or request handling. Include Exit presentation mode and keyboard-accessible controls. Fullscreen is optional. + +A successful five-minute demonstration stays in this workspace: run allowed → inspect evidence → run unapproved model → inspect denial → pause → demonstrate refusal → resume → demonstrate recovery. Model setup is completed before the talk. + +9. Backend reality and implementation handoff + +Existing surfaces: +GET /admin/status and /admin/status/stream — authenticated snapshots. +POST /admin/kill-switch — engage/resume. +GET /admin/evidence — verification report. +POST /admin/reset — archive/reset. +GET /v1/models and POST /v1/chat/completions — application authentication and governed inference. + +Known gaps that the design must mark as proposed: +- Stable request correlation: AuditStage generates its own record ID; the response ID is separate. Add one server-issued correlation ID spanning response headers/body and audit, including refusal paths, before enabling “View exact evidence.” +- Execution state: classification evaluated/not reached, denial kind, selected route, configuration version, and any stage trace need explicit data. Preserve existing audit records; version new fields and render legacy unknowns honestly. +- Provider health/discovery and selected model registration need backend endpoints. Probe only authorized configured hosts, enforce endpoint validation/timeouts, and keep provider credentials on the server. +- The current local integration registers one exact Local:ModelId using Local:Endpoint and optional Local:ApiKey. Multiple Qwen models need a deliberate registry/config extension. +- Startup currently requires OpenAI:ApiKey. Genuine local-only mode must start with no cloud credentials, validate configured providers independently, and keep missing approved routes fail-closed. +- Public/Internal currently use cloud generalRoutes; PII/PHI use the local route. General local Qwen use requires an explicit policy change, not just a model dropdown. +- /v1/models currently lists policy models even if an adapter is missing. The console needs an operational catalog with separate permission/registration/availability status. +- Historical query/filtering and mutable policy/budget/provider configuration are not supplied by the current status endpoint. + +Architecture constraint: the accepted ADR-0004 specifies embedded standalone Blazor WebAssembly when richer editing or evidence browsing is introduced. Keep the .NET host minimal-API and NativeAOT-compatible; the current project does not prove a completed AOT publish. No Blazor Server or silent React migration. A Claude design prototype may use its own tooling in an isolated prototype, but that is not the production architecture decision. No CDN fonts, external analytics, or remote assets in the shipped appliance. + +10. Delivery sequence and acceptance + +Design pass first: deliver the shell, Playground, request detail, and Ollama connection flow before polishing secondary pages. Include normal, empty, loading, invalid-token, disconnected, stale, denied, missing-model, provider-timeout, stopped, and recovered states. Provide component styles, responsive behavior, and concise copy. Identify every mocked API response and every backend dependency. + +First functional slice: browser request submission through the existing governed path; useful result and refusal display; truthful statuses; exact evidence correlation; stop/resume; one approved local Qwen route. Preserve the existing shell script as a secondary integration-test tool. + +Next slice: model discovery/health, local-only startup, multiple selected local models, richer evidence queries. Configuration editors and named-user sessions/RBAC are separate later work. + +Acceptance examples: +- A presenter can complete the main demo without a terminal or token pasted on screen. +- Admin authentication never substitutes for an application key or bypasses policy. +- “hi” rejected before authentication does not claim a PHI detection. +- A missing local adapter never appears as a healthy local model. +- Discovered models remain unavailable to inference until explicitly permitted and registered. +- A configured local-only deployment makes real requests to the chosen installed Qwen model without a cloud credential or cloud fallback. +- Both buffered and streamed text requests return honest outcome/usage data; provider failure and cancellation do not show success. +- Request evidence links by correlation ID, survives asynchronous arrival, and does not depend on timestamp matching. +- Cache and stop behavior match the actual pipeline; no animation invents stages that did not run. +- Archive/reset never happens implicitly during a presentation and does not delete evidence. + +Source anchors inspected on 2026-10-15 + +src/Covenant.Host/AdminUi.cs — embedded UI, sessionStorage admin token, status stream, request details. +src/Covenant.Host/Program.cs — startup, local registration, routes, pipeline assembly, endpoints. +src/Covenant.Core/InferenceContext.cs — restrictive default classification and denial kinds. +src/Covenant.Governance/Auth.cs — key-bound identity and team. +src/Covenant.Governance/Audit.cs — separate audit ID, optional previews, asynchronous evidence. +src/Covenant.Governance/Budget.cs and Cache.cs — scope of stop and cache bypass. +docs/adr/ADR-0004-admin-ui-blazor-wasm-when-triggered.md — accepted UI architecture. +https://docs.ollama.com/api/openai-compatibility — local OpenAI-compatible endpoint and subset support. +https://docs.openwebui.com/getting-started/quick-start/connect-a-provider/starting-with-openai-compatible/ — Open WebUI as an OpenAI-compatible client. + +Still to confirm before integration testing: which machine runs Ollama, its address from Covenant, the installed Qwen model tags, and whether the conference demo will use that machine locally or across a network. These do not block the UI design. diff --git a/docs/adr/ADR-0009-request-correlation-evidence-v2-and-honest-accounting.md b/docs/adr/ADR-0009-request-correlation-evidence-v2-and-honest-accounting.md new file mode 100644 index 0000000..2516cd6 --- /dev/null +++ b/docs/adr/ADR-0009-request-correlation-evidence-v2-and-honest-accounting.md @@ -0,0 +1,58 @@ +# ADR-0009 — Request correlation, audit record v2, and honest usage accounting + +**Status:** Accepted +**Date:** 2026-10-16 + +## Context +The console must open the *exact* evidence record for a request it just sent, show what actually +happened (which stage stopped it, whether classification ran, which model was selected / attempted / +served), and never present unknown usage as a real $0. Before this ADR: the audit stage minted its own +id unrelated to any response id; the provider adapter replaced missing token counts with 0; a cancelled +request could lose its audit record (the sink write used the cancelled token); and the audit record +had no structured outcome beyond Effect + a reason string. + +## Decision +1. **One correlation id.** Host middleware creates `req_<32 hex>` for every `/v1/*` request *before* + body binding, sets `X-Covenant-Request-Id`, and passes it into the canonical request. It is the + buffered OpenAI `id`, the Anthropic message `id`, the SSE chunk id, `request_id` on error bodies, and + the audit record `Id` (duplicated in `CorrelationId` for explicitness). Caller-supplied ids are never + used. Requests rejected by the JSON binder never reach the pipeline: they carry the header but have no + audit record — the console states this instead of searching. +2. **Audit record v2 — additive, hash-compatible.** New nullable fields appended to `AuditEntry`: + `SchemaVersion=2, CorrelationId, ClassificationEvaluated, DenialKind, StoppedAtStage, SelectedModel, + AttemptedModel, Stream, UsageReported, CostBasis`. The chain hashes the *stored* line bytes and the + verifier re-hashes stored content, so legacy lines verify unchanged and are never rewritten; on + deserialize missing fields are null and the console renders **Not recorded**. Facts are observed, not + inferred: the pipeline sets `CurrentStage` on entry to each stage and `Deny` captures it (the budget + stage names the finer "pause" for the kill switch); `AttemptedModel` is set immediately before a + provider call starts; `ClassificationEvaluated` only by the classify stage. The restrictive default + classification is unchanged for enforcement. No measured per-stage timings yet. +3. **Cancellation is evidence.** The audit stage records a cancelled request as `DenialKind=Cancelled` + and writes with `CancellationToken.None`, so the client going away can never suppress the record. + HTTP 499 if anything is still listening. +4. **Usage honesty.** `InferenceResponse.UsageReported` is false when the provider omitted either token + count. `CostBasis` ∈ `reported | zero_priced | estimated_from_text | estimated_failed_call | + unknown_failed_call | unpriced | no_call`. +5. **Fail-closed accounting.** (a) Startup refuses any routable model without a price (0 is an explicit, + valid price for in-perimeter compute — "provider charge $0", infrastructure excluded). (b) A served + call on a priced model with no reported usage is charged from a chars/4 estimate of prompt + output + (`estimated_from_text`); token counts stay "not reported". (c) A call that was *started* but produced no + response (upstream failure, mid-stream failure, cancellation) is charged an estimate of input + any + streamed output (`estimated_failed_call`) — never a silent zero. (d) Savings aggregates exclude + estimated/unknown records and expose their counts. The budget remains a **pre-call threshold** check: + concurrent requests admitted under the cap can overshoot it by their own cost; it is not an invoice + ceiling. + +## Consequences +- (+) Exact evidence lookup by id (`GET /admin/requests/{id}`), robust to identical prompts, equal + timestamps and concurrency; no timestamp joins anywhere. +- (+) Unknown cost cannot become a false $0 or a false saving; ledger replay reproduces estimated charges + because they are recorded in `Usage.CostUsd` of the audit line. +- (−) Lookups re-read the current segment (bounded to it; archived segments are out of scope). +- (−) Estimates can over- or under-charge relative to the provider invoice; they are labelled estimates. + +## Alternatives considered +- Rewrite legacy lines into v2 — rejected: rewriting history is exactly what the chain forbids. +- Nullable token fields inside `Usage` — rejected: changes the nested shape every consumer and the + ledger replay read; an entry-level flag is additive. +- Charge nothing for failed calls — rejected: providers bill input tokens on many failures; fail-closed. diff --git a/docs/adr/ADR-0010-local-only-provider-mode.md b/docs/adr/ADR-0010-local-only-provider-mode.md new file mode 100644 index 0000000..1a8d15f --- /dev/null +++ b/docs/adr/ADR-0010-local-only-provider-mode.md @@ -0,0 +1,35 @@ +# ADR-0010 — Local-only provider mode and the governed local route + +**Status:** Accepted +**Date:** 2026-10-16 + +## Context +The demo and many regulated deployments run a single in-perimeter model (Ollama serving one exact Qwen +tag) with no cloud credential. Startup required `OpenAI:ApiKey`; the local model id defaulted to a +hard-coded `llama-3.1-8b-instruct`; and the console needs to probe/discover an Ollama endpoint without +becoming an arbitrary server-side URL fetcher. + +## Decision +- `Providers:Mode` = `cloud` (default, unchanged behaviour: cloud key required; Public/Internal on cloud + routes; PII/PHI on the local route) or `local-only`. +- **local-only** requires `Local:Endpoint` (absolute http/https) and `Local:ModelId` (exact tag); it + registers **no** cloud provider and **refuses to start** if `OpenAI:ApiKey` or `Anthropic:ApiKey` is + configured — no silent fallback, no quiet rerouting. Every classification routes to `local:`: an + explicit mode choice recorded in status/catalog, not a model dropdown. +- In both modes the local model id is never guessed: `Local:Endpoint` without `Local:ModelId` refuses to + start; with no local config the route reads `local-model-not-configured` and fails closed at the + provider stage. +- Probing (`POST /admin/providers/probe`, admin-only): destinations must be on + `Providers:ProbeAllowList` (host:port list) or be the applied `Local:Endpoint` authority; http/https; + no userinfo/query/fragment; redirects not followed; connection only to the validated host; 5 s + timeout; 64 KiB response cap; no Covenant credential forwarded. `localhost` means Covenant's host. +- Applying configuration remains manual (config + restart). The console reads back the applied + configuration (`GET /admin/catalog`); draft probe results never alter applied state. Observed health + comes from real pipeline calls and probes of the applied endpoint; a later failure supersedes an + earlier success while preserving the last-success time. A paused (refused) request records no health. + +## Consequences +- (+) A no-cloud appliance starts and serves the local model through the full governed pipeline. +- (+) The probe cannot be aimed at arbitrary hosts by a console user. +- (−) One local model only; multiple local models need a registry extension (later ADR). +- (−) Runtime apply is deferred; the wizard ends with configuration guidance and a restart. diff --git a/docs/console-progress.md b/docs/console-progress.md new file mode 100644 index 0000000..4567cec --- /dev/null +++ b/docs/console-progress.md @@ -0,0 +1,494 @@ +# Console progress — status record + +## Current status (2026-10-16, working-branch recheck) + +**Who ran what.** The authoring environment has no .NET SDK: the author has executed nothing. Every result in +this table was produced by an independent reviewer on macOS arm64, SDK 10.0.107. Evidence lives in the +git-excluded `docs/verification-2026-10-16/` folder (`recheck/CLAUDE-RECHECK.txt` for the run below). + +**Source fingerprint of what was checked:** staged code subtrees `src` = `dd087f907b000d0fdb2070842527f2d69e758988`, `tests` = `79e65c587c846f70044fa82bc4efb6e216eb5d94` (on top of +`main` 0624887). Recompute with `T=$(git write-tree); git rev-parse $T:src $T:tests`. If either hash differs, +code has changed since this check, and the results below must be re-run before they're cited. Docs-only changes +don't affect these hashes. + +### Executed on the working branch `feat/console` (after the three fixes below) +| Check | Result | +|---|---| +| `dotnet build Covenant.sln -c Release --disable-build-servers` | PASS — 0 warnings, 0 errors | +| `dotnet test tests/Covenant.Tests -c Release --collect:"XPlat Code Coverage" --settings tests/coverlet.runsettings` (console embedded) | 309 passed, 0 failed, 0 skipped · line coverage **0.9362** (CI gate 0.80) | +| Same tests with `-p:SkipConsolePublish=true` and isolated `--artifacts-path` | 309 passed, 0 failed, 0 skipped | +| `dotnet publish src/Covenant.Host -c Release -r osx-arm64 --self-contained true -p:PublishSingleFile=true` | PASS | +| Published binary, GET `/ui` | 302 → `/ui/` | +| Published binary, GET `/ui/` | 200 text/html, ``, CSP header present | +| Published binary, GET `/ui/requests/x` (nested-route reload) | 200 text/html | +| Framework loader, `.wasm`, CSS, local font | 200 with correct MIME types; missing framework asset → 404; conditional GET with ETag → 304 | +| API demo against real Ollama `qwen2.5-coder:7b`, `Providers:Mode=local-only`, no cloud credentials, isolated port/audit file | A served locally · B 403 policy, no provider attempted · C classified Pii, served locally · no key 401, classification not evaluated (stopped at auth) · paused 403, no attempt · resumed: streaming 200 ending `[DONE]` · application key cannot read `/admin/status` (401) · admin token cannot authorize inference (401) · every response resolves to its exact audit record by id · 5 concurrent identical prompts → 5 unique ids, 5 exact lookups · chain_valid true · local cost basis `zero_priced` | + +Route checks use GET, not HEAD: these are `MapGet` endpoints, so `curl -I` (HEAD) returns 405, which proves +nothing about GET. Use `curl -sS -D - -o /dev/null http://localhost:5100/ui` (don't follow redirects; inspect +`Location`), and the same for `/ui/` and `/ui/requests/x`. + +### NOT executed — not covered by any sign-off +- **Browser acceptance:** signed-in rehearsal; reload; presentation mode at 1280×720 and 1920×1080 in both themes; + A–D from the UI; the Requests drawer with keyboard and focus restoration; disconnect/reconnect; stale state; + screenshots. +- **Failure paths in a real browser:** real cancellation from the browser, and a controlled provider failure + after a success (use an isolated mock endpoint, not the shared Ollama service). +- **Other publish targets:** linux-x64 and NativeAOT. +- **Overall conference-demo readiness.** A passing build plus an API demo does not establish that the browser + presentation is ready. + +### Fixes applied after the first (diagnostic-copy) review +1. `src/Covenant.Ui/Pages/Policies.razor` — `AdapterStatus(Covenant.Ui.Models.RouteView r)` (CS0104; Blazor's + `RouteView` component in App.razor untouched). +2. `src/Covenant.Host/Covenant.Host.csproj` — EmbeddedResource `Include` then `Update` assigning `LogicalName` + per file (CS1508). +3. `src/Covenant.Host/ConsoleAssets.cs` — a single `/ui/{**path}` endpoint that redirects only when the path is + exactly `/ui`, so `/ui/` serves `index.html`. The literal `/ui` route had also matched `/ui/`, causing a + redirect loop. No test assertion was weakened. + +Superseded below: the packaging description mentioning `dotnet publish … -o obj/console-publish` (replaced by the +in-build `MSBuild` task plus `CleanConsolePublishDir`) and every "Not verified (no compiler)" section; those are +history. The tables above are the record of what has been executed. + +--- + +# History — TASK 01 (shell & packaging), TASK 07 read-only pages, TASKS 04/05 + UI half of 06 + +Status as of 2026-10-16. Written without a .NET SDK on the authoring machine: **nothing below has been compiled +or run yet** — see "Not verified" before trusting any of it. + +## What was built + +**Packaging (ADR-0004).** `src/Covenant.Ui` is a standalone Blazor WebAssembly project. `Covenant.Host` does not +reference it; instead the `PublishConsole` MSBuild target in `Covenant.Host.csproj` runs +`dotnet publish src/Covenant.Ui -c $(Configuration) -o src/Covenant.Host/obj/console-publish` before +`PrepareForBuild` and adds every file under `obj/console-publish/wwwroot/ui/**` as an `EmbeddedResource` with +`LogicalName=console/` (published Blazor output lands under `wwwroot//`, +i.e. `wwwroot/ui/`). `ConsoleAssets.MapConsole()` loads those resources once at startup and serves them under +`/ui/`: `/ui` → 302 `/ui/`; known file → bytes with the right MIME type, ETag (304 on `If-None-Match`), +`Cache-Control` (`no-cache` for `index.html` and the loader entry points, `immutable` for fingerprinted +`_framework/*` and the woff2 fonts); anything without a file extension → `index.html` (nested-route reload); +file-like path that does not exist → 404 (so a missing asset fails loudly instead of returning HTML to the +loader). Every console response carries a `self`-only CSP, `X-Content-Type-Options: nosniff` and +`Referrer-Policy: same-origin`. With `-p:SkipConsolePublish=true` nothing is embedded and `/ui/` answers 503 +with a plain-text explanation. The Host stays minimal-API + RDG; no reflection, no MVC, no static-files +middleware. `Program.cs` gained exactly one line: `app.MapConsole();`. + +**Shell.** Compact left nav (Overview, Playground, Requests, Models & connections, Policies, Budgets, Evidence; +Settings + connection control + theme toggle at the bottom), slim status header (environment, "Console +connected/disconnected", "Updated n s ago" / "Stale" / "Connection lost — retrying", "New provider calls +paused/accepted", Pause/Resume button), amber "New provider calls paused" banner with reason and scope text. +Dark/light via `data-theme` on ``; only the theme is persisted (localStorage `covenant.theme`). + +**Services** (`Services/`): `AppState` (pure state + `Changed` event; admin token in memory, application key in +memory only, `Connected`, `LastStatus`, `LastUpdatedUtc`, `IsStale` (>8 s), `Paused`, `Environment`, catalog, +feed mode/error, `Restoring`), `AdminApi` (typed `/admin/*` calls with `X-Covenant-Admin-Token`; 401 → +`Unauthorized` event → disconnect + `/connect` "Token rejected"; error bodies parsed into readable messages), +`StatusFeed` (SSE via `HttpClient` + `SetBrowserResponseStreamingEnabled` + `ResponseHeadersRead`, `data:` line +parsing, backoff reconnect, polling fallback after two stream failures, 1 s staleness tick), +`ConsoleSession` (connect/validate/restore/disconnect, sessionStorage mirror of the token under +`covenant.admin-token`, pause/resume with server re-sync, catalog load), `Interop` (typed wrapper over +`wwwroot/js/interop.js`), `Fmt` (invariant formatting), `RouteHealth` (unresolved / missing local route from +`status.routes` × `catalog`). + +**Components** (`Components/`): `StatusPill` (served/refused/failed/paused/unknown; `KindFor(effect, denialKind)` +never defaults to green), `Button`, `Drawer` (drawer or dialog; Escape/scrim close, JS focus trap, focus restored +to `OpenerId`), `FactList`, `ErrorBanner`, `EmptyState`, `Skeleton`, `AlertCard`, `RequiresConnection` (gate: +restoring → skeleton, disconnected → "Connect to the console", else content). + +**Pages** (`Pages/`): `/connect`, `/` Overview, `/policies`, `/budgets`, `/evidence`, `/settings` as specified in +the task (alerts first on Overview; segment label on totals; activity labelled with its real window; chain +status with "Internal consistency verified…" wording; Configured ≠ Verified for anchors; Export downloads the +server's JSON byte-for-byte via a Blob; Settings read-only values + separate Maintenance with a typed +environment-name confirmation that names both effects and is blocked while chain verification fails). +`Playground.razor`, `Requests.razor` and `Connections.razor` were placeholders after TASK 01; they are now +implemented — see "TASKS 04 / 05 / 06 (UI)" below. + +No fixtures, canned values, fake hashes or default-green states were ported from `covenant-prototype/`; only +`tokens.css`, the fonts (SIL OFL 1.1, recorded in `docs/PROVENANCE.md`) and layout/copy. + +## Files + +``` +Covenant.sln + Covenant.Ui project (GUID 4F1C2B7E-9D3A-4B86-A2E5-6C0D8F7B1E42), src folder +src/Covenant.Host/Covenant.Host.csproj + PublishConsole target, EmbeddedResource glob +src/Covenant.Host/ConsoleAssets.cs new — MapConsole, MIME map, NormalizePath, CacheControlFor, Load +src/Covenant.Host/Program.cs + app.MapConsole(); (one line before app.Run()) +src/Covenant.Ui/Covenant.Ui.csproj new +src/Covenant.Ui/Program.cs, App.razor, _Imports.razor +src/Covenant.Ui/Layout/{MainLayout,BareLayout,SideNav,StatusHeader}.razor +src/Covenant.Ui/Components/{StatusPill,Button,Drawer,FactList,ErrorBanner,EmptyState,Skeleton,AlertCard,RequiresConnection}.razor +src/Covenant.Ui/Services/{AppState,AdminApi,StatusFeed,ConsoleSession,Interop,Fmt,RouteHealth}.cs +src/Covenant.Ui/Models/Contracts.cs DTOs + UiJsonContext (source-generated) +src/Covenant.Ui/Pages/{Connect,Overview,Policies,Budgets,Evidence,Settings,Playground,Requests,Connections}.razor +src/Covenant.Ui/wwwroot/index.html, css/tokens.css, css/app.css, js/interop.js +src/Covenant.Ui/wwwroot/fonts/*.woff2, fonts.css, LICENSE-ibm-plex-{sans,mono}.txt +tests/Covenant.Tests/ConsoleAssetsTests.cs new — unit (MIME/normalize/cache/CSP) + integration via WebApplicationFactory +docs/PROVENANCE.md + two NuGet packages, bundled fonts +docs/console-progress.md this file +``` + +## How to build + +- `dotnet build` (solution or `src/Covenant.Host`) — triggers `dotnet publish` of `Covenant.Ui` and embeds the + bundle. First build restores the Blazor packages; the `wasm-tools` workload is **not** required (no WASM AOT, + no relinking). +- `dotnet test -p:SkipConsolePublish=true` — fast tests; `ConsoleAssetsTests` detects the absence of the bundle + and asserts the 503 branch instead. +- `dotnet test` (without the flag) — also exercises the embedded bundle: 200 `text/html` for `/ui/`, nested + route reload, `font/woff2`, `text/javascript`, ETag/304. +- `dotnet run --project src/Covenant.Host` then open `http://localhost:5100/ui/`. The UI calls the same origin + (`/admin/*`), so no dev-server/proxy is involved; the DevServer package is only a dev-time dependency. + +## Not verified (no compiler here) — check these first + +1. **Razor/C# compiles under warnings-as-errors.** Written conservatively, but the obvious risk spots are: + nested `if` inside C# blocks vs `@if` inside markup (checked by hand), pattern variables in `@if (... is not { } s)`, + collection expressions targeting `IReadOnlyList` / `List` with target-typed `new(...)`, + `EventCallback` bound to `Task`-returning method groups, `@bind-Open` on `Drawer`. +2. **MSBuild embedding.** `%(RecursiveDir)` inside a target-scoped `ItemGroup`, `WithCulture="false"`, and the + `BeforeTargets` list (`PrepareForBuild;AssignTargetPaths;PrepareResourceNames;PrepareEmbeddedResources` — + the last is a no-op if that target does not exist). If `CoreCompile` sees no resources, move the target to + `BeforeTargets="BeforeBuild"` and confirm `_GenerateCompileInputs` runs after it. Verify the publish layout is + `obj/console-publish/wwwroot/ui/...` (docs say so for `StaticWebAssetBasePath`); if it is `wwwroot/...`, + change the glob. +3. **Package versions.** `Microsoft.AspNetCore.Components.WebAssembly[.DevServer]` 10.0.11 exist on nuget.org + (checked 2026-10-16 via the flat-container index). `CompressionEnabled=false` is the .NET 8+ property name. +4. **SSE over `HttpClient` in the browser** (`SetBrowserResponseStreamingEnabled(true)` + + `HttpCompletionOption.ResponseHeadersRead` + `StreamReader.ReadLineAsync(ct)`). Polling fallback kicks in + after two failures if the browser buffers the response. +5. **Blazor + CSP.** `script-src 'self' 'wasm-unsafe-eval'`, `style-src 'self' 'unsafe-inline'` should satisfy the + .NET 10 loader (`dotnet.js` is imported from `_framework/`, no inline script). If the loader needs + `blazor.boot.json`/`dotnet.boot.js` revalidation, both are already `no-cache`. +6. **Freshness UX**: the 1 s `System.Threading.Timer` in `StatusHeader` + `AppState.Tick` in `StatusFeed` — confirm + no double re-render storms in the browser. +7. **Environment name in confirmations.** Until Task 07's `environment` lands in `/admin/status`, the Settings + confirmation asks you to type `Environment not reported`. Expected to resolve when the field ships. +8. **Drawer focus trap** (`interop.js trapFocus`) — exercise with keyboard: Tab cycles inside, Escape closes, + focus returns to the opener. + +## Decisions worth knowing + +- Disconnect never calls `/admin/kill-switch`; pause/resume always re-fetch `/admin/status` after the POST and + render the server's answer, never the optimistic one. +- "Current audit segment since …" on Overview/Settings uses the oldest activity bucket (status has no + `first_utc`); Budgets uses `segment.first_utc` from `/admin/requests` when that endpoint exists. +- Evidence anchor status reads `anchor_*` from `/admin/evidence` first, then `status.anchor`; any missing field + renders "Not reported", never "Verified". +- The legacy `/admin/ui` vanilla page is untouched; retire it in a later change once the console is proven. + +## Backend (Tasks 02/03/06) + +Design: ADR-0009 (correlation, audit v2, honest accounting), ADR-0010 (local-only mode); wire shapes in +`docs/ui-api-contract.md`. Nothing here was compiled or run in the authoring environment (no SDK) — the +first `dotnet build && dotnet test` is the real gate. + +### Endpoints +- Every `/v1/*` response carries `X-Covenant-Request-Id: req_<32 hex>` (middleware, set before body binding). + Same value = OpenAI `id` / Anthropic message `id` / SSE chunk `id` / `request_id` on error bodies / audit `Id` + (+ `CorrelationId`). Malformed JSON → 400 with the header and **no** audit record (never reached the pipeline). +- `GET /admin/requests?limit=N` — current segment, newest first, `limit` clamped to 1..1000 (default 200). +- `GET /admin/requests/{id}` — exact lookup; 400 malformed id, 404 `{error:"not_found", scanned}` (sink is async: + poll before concluding "unavailable"). +- `GET /admin/catalog` — mode, per-route registered / price basis / observed health, local config, probe allow-list. +- `POST /admin/providers/probe` — allow-listed, http(s) only, no userinfo/query/fragment, redirects refused, + 5 s overall deadline (connect + headers + body), 64 KiB cap, no credentials forwarded. Probing the applied + `Local:Endpoint` updates its endpoint health (failure supersedes success; last success kept). +- `/admin/status` adds `environment, mode, audit_path, cache_ttl_seconds, prompt_preview_chars, anchor, version`; + FinOps adds `unknown_cost_requests, estimated_cost_requests`, recent rows add `cost_basis`; + `/admin/evidence` adds `anchor_configured, anchor_count, last_anchor_utc`. + +### Review fixes (this pass) +- `ProviderCallStage`: only a *caller* cancellation (`ct.IsCancellationRequested`) is rethrown; a provider-side + `OperationCanceledException` (HttpClient timeout) is now a governed `UpstreamFailure` (502, charged estimate) + instead of escaping as an unhandled exception recorded as "Cancelled". +- `ProviderProbe`: overall deadline now also bounds the body read (a server that sent headers then stalled could + hold the admin request open); `IOException` mid-body is a probe failure, not a 500; overload + `RunAsync(raw, allowList, timeout, ct)` for tests. +- `/admin/catalog` resolves `IChatClientRegistry` from `RequestServices` instead of relying on RDG parameter + inference for an interface type on a GET; `/admin/requests` uses `Enumerable.Reverse(entries)` explicitly. +- Provider-mode startup rules extracted into `StartupValidation.ValidateProviders(IConfiguration)` (pure, + behaviour-preserving) so refusal cases are unit-tested without `Environment.Exit`. +- `StartupValidation` additionally refuses a whitespace-only `Local:ModelId` (previously it would register `local:` with an empty tag). +- `CanonicalModel.cs`: duplicate `` on `InferenceResponse` and a merged trailing comment on + `InferenceRequest` cleaned up. + +### Tests added (tests/Covenant.Tests) +- `CorrelationAndEvidenceTests.cs` + - `CorrelationAndEvidenceTests` (host, stub registry): header == body id == audit record for buffered 200, + Anthropic 200, 401 (stage `auth`, `ClassificationEvaluated=false`, classification still `Phi`), policy 403, + pause 403 (stage `pause`, provider not called), missing local adapter 403 (stage `provider`, selected + `local-model-not-configured`, attempted null), upstream 502 (attempted set, `estimated_failed_call` > 0), + mid-stream failure (HTTP 200, SSE error line with `request_id`, record Deny/UpstreamFailure), malformed JSON + (400 + header, no record — proven after a later record lands); 20 concurrent identical prompts → 20 distinct + ids each resolving to its own record; lookup/list admin-only; bad id 400; unknown id 404 + `scanned`; list + newest-first + limit clamping; no prompt text in records/log/list without `Audit:PromptPreviewChars`. + - `CorrelationRateLimitTests` (own host, `RateLimit:GlobalPerMinute=1`): 429 correlated, stage `rate_limit`. + - `CancellationEvidenceTests` (pipeline): cancelled in-flight call → exactly one record, `Cancelled`, attempted + model, `estimated_failed_call`, cost > 0 and charged, enqueued via a sink that rejects any cancellable token + (proves `CancellationToken.None`); provider-side timeout → `UpstreamFailure`, not `Cancelled`. + - `LegacyAuditCompatibilityTests`: hand-written v1 lines (no v2 keys) + v2 lines via `FileAuditSink` with + anchors → chain + anchors verify, legacy bytes unchanged, legacy v2 fields read as null, ledger replay + includes the estimated failed-call charge, evidence export reports anchors. +- `AccountingTests.cs` (real stages, stub clients): reported / missing usage (`estimated_from_text`, charged, + buffered + streamed) / partial usage (not reported) / local `zero_priced` / refusal `no_call` / cache hit + `no_call` charged once / upstream failure `estimated_failed_call` exact estimate charged / interrupted stream + estimate includes partial output / unpriced → `unpriced` + FinOps unknown count + no saving / failed call on + unpriced → `unknown_failed_call`; FinOps: unpriced/estimated never produce savings while the same record as + `reported` does; legacy (null basis) keeps old treatment; `TokenEstimate` ceiling. +- `ProviderProbeTests.cs` (TcpListener loopback server): valid discovery, no credential headers forwarded, empty + discovery, refused port, silent server timeout (400 ms overload), non-JSON / wrong shapes, non-2xx, 302 not + followed (Location never requested), oversized body with and without Content-Length, not-allow-listed and + unsafe shapes (userinfo, query, fragment, ftp, file, relative, empty) refused with zero connections, allow-list + building, `ProviderHealth` success→failure→success, and host-level: applied-endpoint probe ok → failed updates + `/admin/catalog` `endpoint_health` while keeping `last_success_utc`; probe is admin-only. +- `LocalOnlyModeTests.cs`: host in `local-only` with no cloud key starts; status mode `local-only`, all routes + local; Internal/PII/PHI served by `local:qwen3:8b` with cloud tripwire clients at 0 calls; explicit cloud model + request is denied at policy (not rerouted); catalog mode/local registered/no openai models/price `zero`; + `/v1/models` lists only the tag. `StartupValidationTests`: cloud needs key; local-only needs endpoint + tag, + refuses OpenAI/Anthropic keys; endpoint without tag refused in any mode; non-http/invalid/blank endpoint + refused; unknown mode refused; mode normalization. + +### Unverified / remaining risks +- Not compiled here. Watch especially: xunit analyzer severities, RDG handling of `int? limit`, and the + `ConnectCallback` dual-mode socket on the CI OS. +- In the **Development** environment minimal APIs throw on bad JSON and the developer exception page clears + response headers, so the 400 loses `X-Covenant-Request-Id` there (Production — the shipped mode and all + tests — keeps it). +- Exceptions thrown by the Host's SSE writer (client disconnect surfacing as `IOException`) are inside the + provider stream `try` and would be recorded as an upstream failure and mark provider health failed. +- ADR-0009 §5(a) "startup refuses an unpriced routable model": the built-in price map always contains every + routable model, so that gate cannot currently fire; the runtime `unpriced` flag is the effective protection. +- In local-only mode FinOps still computes "savings" against the (unrouted) cloud strong model as baseline. +- Probe allow-list entries are host names; the connect callback re-resolves DNS, so a hostname entry trusts DNS + (rebinding) — prefer IP entries for strict deployments. +- The `TcpListener`-based timeout/refused tests depend on loopback behaviour (refused port relies on nothing + rebinding the just-released ephemeral port). + + +--- + +# TASKS 04 / 05 / 06 (UI half) — Playground, Requests, Models & connections + +Status 2026-10-16. Same caveat: **written without a .NET SDK — not compiled, not run.** Backend files were not touched +(another engineer owns Core/Governance/Adapters/Host/tests except the new test file). + +## What was built + +**Pure view-model logic — `src/Covenant.Ui/Logic/`** (plain C#, only `System.*` + `Covenant.Ui.Models`; linked into +`tests/Covenant.Tests` via `` together with `Models/Contracts.cs`): +- `OutcomeModel.cs` — `DisplayOutcome` {Served, ServedFromCache, PolicyDenied, Paused, AuthenticationFailed, RateLimited, + ProviderUnavailable, ProviderFailedMidStream, Unsupported, RejectedBeforeGovernance, Cancelled, Unknown}; + `OutcomeModel.Compute(OutcomeInput)` → title, plain explanation, status line, `TransportDiffers` (HTTP 200 but not a + success → "Transport 200, final outcome: failed/incomplete"), pill kind, `AwaitingRecord`. Before the record: transport + only (403 → "Refused (HTTP 403) — awaiting evidence for the stage", never a guessed stage). With the record: + `DenialKind` first, then `StoppedAtStage` ("pause" → Paused; "provider" with `AttemptedModel==null` → missing adapter; + "budget"/"policy" → governance denial); legacy deny without kind/stage → "Refused (legacy record)". Reason text is + never parsed. Also `PipelineStages` (configured order; pause+budget share one row). +- `ModelFacts.cs` — Selected / Provider attempted / Served (cache → "Served from cache (no provider call)"), legacy nulls + → "Not recorded", classification "Not evaluated — stopped at {stage}" / "Not recorded" / class + signal. +- `CostText.cs` — CostBasis wording exactly as specified; unknown/unrecognised basis → "Not reported" (never "$0"); + tokens "Not reported" whenever a provider call was attempted and `UsageReported != true`. +- `RequestFilter.cs` — immutable `RequestFilterCriteria` (outcome, model matching selected/attempted/served, team, id + substring, time window) + option lists. +- `RequestSnapshot.cs` — `PlaygroundForm` (mutable inputs) and the immutable `RequestSnapshot` frozen at Run + (sequence, "Scenario X · title" or "Custom", sent prompt incl. nonce, base prompt, requested model or null = "Let + policy choose", streaming, max tokens, labels, time); `MatchesForm` drives "Previous request — the form has changed since". +- `ScenarioPresets.cs` — A permitted; B explicit `gpt-4-unapproved-test` (test input); C synthetic sensitive fixture + (published sample SSN 078-05-1120 — matches `RegexDataClassifier`'s PII rule, verified by test); D normal prompt + + `" [run {Guid:N}]"` appended at every Freeze. Presets only fill inputs. +- `ConnectionLogic.cs` — endpoint validation/normalisation (catalog shape `scheme://host:port/path`), host:port, applied- + config read-back check, route review text, generated configuration block (names + values, no secrets), governed + test prompt (contains the sample SSN so cloud mode routes it to the local model). + +**Services** +- `InferenceApi` — own `HttpClient` (same origin, 5 min timeout), `Authorization: Bearer ` only when a + key is set (empty → no header → real 401), never the admin token; `X-Covenant-Workflow/UseCase` labels (printable ASCII + only). Buffered and SSE streaming (`SetBrowserResponseStreamingEnabled` + `ResponseHeadersRead`, `data:` lines, deltas, + the mid-stream `{"error":…}` line, `[DONE]`; missing `[DONE]` = incomplete). Request id from `X-Covenant-Request-Id`, + falling back to the body/chunk id or `request_id`. Cancellation → `Cancelled` ("Stopped waiting … not a rollback"). +- `EvidenceTracker` — polls `GET /admin/requests/{id}` after 0.5,1,1.5,2,3,3,3 s; 404 → Pending → "Not in the current + audit segment yet — retry."; 401 handled by ConsoleSession; other errors → Error + Retry. Never says the write failed. +- `PlaygroundState` (scoped) — form, runs, selection, in-flight run (one at a time), evidence tracking; refreshes the + catalog after each run; cleared by `AppState.Disconnected`. +- `RequestsViewState` (scoped) — snapshot, filters, selection; cleared on disconnect. +- `CatalogState` (scoped) — 30 s refresh loop while connected + `RefreshAsync()` after governed tests/probes; reuses + `ConsoleSession.LoadCatalogAsync` / `AppState.Catalog`. `RouteHealth.LocalRoute()` (extended, not duplicated) gives one + "Local route: ready / degraded (last success …) / not configured / not registered / not yet observed" summary used by + the header, Overview (new "degraded" alert) and Models & connections. A failure newer than the last success is degraded. +- `AppState.Disconnected` event (raised in `Disconnect` before `Changed`). +- `Interop.CopyTextAsync` + `copyText` in `interop.js` (request ids only). + +**Pages** +- `/playground/{Scenario?}` (+ `?present=1`): two columns (setup | result), bottom row "Configured processing order" + (recorded `StoppedAtStage` highlighted, cache-hit row marked, no timings/animation) | collapsible Evidence for the + selected run with "Open in Requests". Application key masked, memory-only. Routing: policy / permitted catalog model + (GET /admin/catalog, classifications > 0) / "Advanced: explicit model id (test input — does not grant permission)". + Run disabled while in flight, Cancel, Clear output, session history (#n). Presentation mode: fixed full-viewport layer + (nav/header hidden), own header with environment, provider mode, pause state, Pause/Resume + scope note, Setup drawer, + Inspect-evidence drawer with "Open in Requests", "Exit presentation mode". Sizes use `--text-outcome-present` / + `--text-facts-present`; long output scrolls inside `.response-box`. +- `/requests`, `/requests/{Id}`: coverage label from `segment`, filters persisted in `RequestsViewState`, Clear filters, + empty / no-match states, full-width fixed-layout table (min-width 1120 px, horizontal scroll inside its container, + ellipsis + `title` cells), row click or the id button (Enter) opens the drawer, URL becomes `/requests/{id}`. Deep link + always fetches `GET /admin/requests/{id}`; notes "hidden by the current filters" / "not in the loaded recent list"; + 404 → "Not in the current audit segment (may be archived or not yet written)" + Retry. Drawer sections 1–5 in the + specified order; prompt preview only when the record has `PromptPreview`; raw JSON is a re-serialisation of the same + `AuditEntryView` via `UiJsonContext` (indented, nulls omitted). +- `/connections`: running configuration (mode, local configured/endpoint/model/registered from the server flag only, + endpoint health, probe allow-list, per-model routes/registered/permitted/price basis/health with last success/failure/ + error, "unknown" when never observed). Wizard as gated `
`s: 1 endpoint (edit → clears all later draft results + with a notice; applied config untouched) → 2 probe (allowed/reachable/status/duration/error; not-allow-listed → add + host:port to `Providers:ProbeAllowList`) → 3 discovered tags (empty state) → 4 exactly one tag (radio) → 5 route review + + generated config + "Runtime apply is not available in this version…" → 6 check applied config (re-GET catalog; pass only + if endpoint, tag and `registered` match) → 7 governed test through `InferenceApi` with the application key (asks for one + if empty), requested model = tag, outcome + request id + "Open evidence"; paused → "Paused — not a reachability result"; + catalog refreshed after the test and after probes. Optional Open WebUI section (`/v1`, application key). +- Header: "Local route: …" indicator linking to Models & connections. +- CSS: desktop shell is now app-height (`.shell {height:100vh}`; `#main` scrolls) so Playground can size to the viewport. + +## Files (this round) + +``` +src/Covenant.Ui/Logic/{OutcomeModel,ModelFacts,CostText,RequestFilter,RequestSnapshot,ScenarioPresets,ConnectionLogic}.cs new +src/Covenant.Ui/Services/{InferenceApi,EvidenceTracker,PlaygroundState,RequestsViewState,CatalogState}.cs new +src/Covenant.Ui/Services/AppState.cs + Disconnected event +src/Covenant.Ui/Services/RouteHealth.cs + LocalRouteState / LocalRouteSummary / LocalRoute() +src/Covenant.Ui/Services/Interop.cs + CopyTextAsync +src/Covenant.Ui/Models/Contracts.cs + catalog endpoint_health / probe_allow_list / probe checked_utc; chat DTOs; UiJsonContext entries +src/Covenant.Ui/Program.cs + service registrations (InferenceApi with its own HttpClient) +src/Covenant.Ui/_Imports.razor + @using Covenant.Ui.Logic +src/Covenant.Ui/Pages/{Playground,Requests,Connections}.razor implemented; Pages/Overview.razor + degraded-local-route alert +src/Covenant.Ui/Layout/StatusHeader.razor + local route indicator (instantiates CatalogState) +src/Covenant.Ui/wwwroot/css/app.css + app-height shell, Playground/presentation/Requests/Connections styles +src/Covenant.Ui/wwwroot/js/interop.js + copyText +tests/Covenant.Tests/ConsoleLogicTests.cs new (outcome branches, model facts, cost text, filters, snapshots, presets, connection logic) +tests/Covenant.Tests/Covenant.Tests.csproj + links to Ui Logic/*.cs and Models/Contracts.cs +``` + +## Manual QA checklist + +Setup: Host running with at least one application key, cloud mode with a fake/real cloud adapter, optionally Ollama. + +A — Playground basics +- [ ] Fresh load: Playground is empty ("No request yet"); nothing in localStorage/sessionStorage except `covenant.theme` + and `covenant.admin-token` (DevTools → Application). +- [ ] Empty key, Run A → "Authentication failed", HTTP 401; evidence arrives; classification "Not evaluated — stopped at + authentication" (never PHI). +- [ ] With key, A buffered → Served; selected/attempted/served models, tokens or "Not reported", cost per CostBasis, + duration "(recorded by Covenant)" once the record arrives, client-measured before; request id copy works. +- [ ] A streamed → text appears incrementally; final usage/cost from the record. +- [ ] B → Policy denied, Provider attempted "None — no provider call", stage "policy" highlighted. +- [ ] C without a local route → refused; with Ollama configured → served by `local:`; never a cloud model. +- [ ] D: pause (header or presentation) → Run D → "Paused — new provider calls refused", stage pause/budget highlighted; + resume → Run D again → Served (not from cache: prompt carries a new `[run …]` nonce each time). +- [ ] Run twice identical A without nonce → second is "Served from cache"; cache row highlighted; cost "$0.00 — no provider call". +- [ ] Edit the prompt after a run → "Previous request — the form has changed since"; result title unchanged. +- [ ] Run is disabled while in flight; Cancel → "Cancelled / incomplete … not a rollback". +- [ ] Mid-stream provider failure (fake adapter) → "Transport 200, final outcome: failed", partial text kept. +- [ ] Malformed request (not reachable from the UI; use curl) is shown in Requests as absent — no record. +- [ ] "Open in Requests" (normal + presentation drawer) opens exactly `/requests/`. +- [ ] Disconnect → reconnect: key, runs, responses and form are gone; reload does the same. + +B — Presentation mode +- [ ] Button and `?present=1` both enter it; nav/status header hidden; environment, pause state and Pause/Resume visible + with the scope note; Exit returns to the normal layout. +- [ ] 1280×720 and 1920×1080 (light + dark): prompt, Run, outcome, model, cost and "Inspect evidence" visible without page + scroll; a long response scrolls inside its box. +- [ ] Setup and Inspect drawers: Tab trapped, Escape closes, focus returns to the opener. + +C — Requests +- [ ] Coverage label shows segment start and record count; "not a full audit history search". +- [ ] Each filter narrows the table; combinations; Clear filters; "No requests match" state; filters survive navigating + away and back; cleared on disconnect. +- [ ] Row click and Enter on the id button open the drawer; URL becomes `/requests/`; Close/Escape returns to `/requests`. +- [ ] Deep link to an id excluded by filters → record shown + "hidden by the current filters"; unknown id → "Not in the + current audit segment…"; after archive/reset the old id → same unavailable state. +- [ ] Legacy record → "Not recorded" for v2 facts; raw JSON matches the visible facts; prompt preview only when retained. +- [ ] Long model ids/ids readable at 1280 px (drawer wraps; table ellipsis + title; table scrolls horizontally). + +D — Models & connections +- [ ] Running configuration matches `GET /admin/catalog`; "Registered" only from the server flag; unknown health shown as such. +- [ ] Endpoint not on the allow-list → probe "Allowed: No" + Providers:ProbeAllowList guidance; later steps stay disabled. +- [ ] Reachable endpoint → tags listed; no tags → empty state; choose one tag; config block shows names/values, no secrets. +- [ ] Edit the endpoint after a probe → all later steps cleared with the notice; running config unchanged. +- [ ] Before restart, "Check applied configuration" fails with the mismatch; after config + restart it passes. +- [ ] Governed test: asks for a key if none; served by `local:`; "Open evidence" opens the record. Stop Ollama → run + again → failed; header shows "Local route: degraded (last success …)" on every page; Overview shows the alert. +- [ ] Paused test → "Paused — not a reachability result"; health unchanged. + +## Not verified without a compiler — check first + +1. **Razor templates in `@code`** (`RenderFragment` / `RenderFragment` properties with `@
…
`) containing + `@switch` with `case … when … is { } rec:` and components — valid Razor, but the most complex markup here. +2. **`@page "/playground/{Scenario?}"`** (optional parameter) also matching `/playground`; `[SupplyParameterFromQuery]` + on a public property without `[Parameter]` (.NET 8+ style). +3. **Pattern variables in markup** (`@if (x is { } y)`) leaking into the enclosing render lambda — names were kept unique + per lambda by hand; a CS0128/CS0136 here is a rename. +4. **Linked compile in the test project**: `Contracts.cs` + Logic compile in a non-Blazor project (they reference only + System.Text.Json); `UiJsonContext` source generation runs there too. No `using Covenant.Host` in ConsoleLogicTests, so + no ambiguity with Host's `ErrorResponse`/`StatusReport`. +5. **xunit analyzers under warnings-as-errors** (e.g. xUnit2013 style rules) in ConsoleLogicTests. +6. **SSE in the browser**: as for StatusFeed — if `fetch` buffers, streaming still completes but text arrives at once. +7. **App-height shell CSS** (`.shell {height:100vh}`, `#main` scrolling) changes scrolling for every page on desktop; + check Overview/Policies still scroll and drawers still overlay correctly. +8. **`InputType=number` bound to `int?`** and ` + @Help + + + } + + +
+ This is a shared admin token, not a personal account. It administers the console only — it never authorizes model requests. Applications send their own keys. + Kept in this tab’s session storage; closing the tab disconnects. +
+ + + +@code { + private sealed record BannerInfo(string Tone, string Title, string Body); + + private string _token = ""; + private bool _busy; + private bool _invalid; + private string? _error; + + private string Help => _invalid && _error is not null + ? _error + : "Validated against GET /admin/status. Nothing is stored until the Host accepts it."; + + private BannerInfo? Banner + { + get + { + if (State.Connected) return null; + if (_invalid && _error is not null) return new("bad", "Could not connect", _error); + var m = State.ConnectMessage; + if (m is null) return null; + if (m.StartsWith("Token rejected", StringComparison.Ordinal)) + return new("bad", "Token rejected", "The Host refused the admin token. Enter the current token to reconnect."); + if (m.StartsWith("Connection lost", StringComparison.Ordinal)) + return new("warn", "Connection lost", m + ". The Host did not answer; try again when it is reachable."); + return new("info", "Disconnected", "The token and any application key were cleared from this tab. Covenant itself keeps running — disconnecting never pauses it."); + } + } + + protected override void OnInitialized() => State.Changed += OnChanged; + + // One-click launch from scripts/run-local-demo.sh: read credentials from the URL fragment once, wipe the + // fragment from the address bar/history immediately, then connect exactly as if they had been typed. + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender || LaunchLink.Parse(Nav.Uri) is not { } launch) return; + Nav.NavigateTo("connect", forceLoad: false, replace: true); + if (launch.ApplicationKey is { } key) State.SetApplicationKey(key); + if (launch.AdminToken is { } token && !State.Connected) + { + _token = token; + await ConnectAsync(); + StateHasChanged(); + } + } + + private async Task ConnectAsync() + { + if (_busy || string.IsNullOrWhiteSpace(_token)) return; + _busy = true; _invalid = false; _error = null; + try + { + await Session.ConnectAsync(_token.Trim()); + _token = ""; + Nav.NavigateTo(""); + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + _invalid = true; + _error = "Token rejected by the Host. Check the Admin:Token value in the appliance configuration."; + } + catch (Exception ex) + { + _invalid = true; + _error = "The Host did not answer: " + ex.Message; + } + finally + { + _busy = false; + } + } + + private async Task DisconnectAsync() + { + await Session.DisconnectAsync("Disconnected"); + _token = ""; + } + + private void OnChanged() => _ = InvokeAsync(StateHasChanged); + public void Dispose() => State.Changed -= OnChanged; +} diff --git a/src/Covenant.Ui/Pages/Connections.razor b/src/Covenant.Ui/Pages/Connections.razor new file mode 100644 index 0000000..752d35e --- /dev/null +++ b/src/Covenant.Ui/Pages/Connections.razor @@ -0,0 +1,498 @@ +@page "/connections" +@inject AppState State +@inject AdminApi Api +@inject CatalogState Catalog +@inject InferenceApi Inference +@inject EvidenceTracker Evidence +@inject NavigationManager Nav +@implements IDisposable + +Models & connections · Covenant + +@* + TASK 06 (UI half). Top: the APPLIED configuration as the server reports it (GET /admin/catalog) — "Registered" + only ever comes from the server's flag. Bottom: the Ollama wizard. Draft values live only in this page; probing + a draft never changes the running configuration, and runtime apply is not available (config + restart). + The governed test goes through /v1 with an APPLICATION key, never the admin token. +*@ + +
+ +
+
+

Models & connections

+ Where Covenant sends calls. Registration, permission and observed reachability are separate facts. +
+ Managed by configuration; restart required + +
+ + @{ var cat = State.Catalog; var localRoute = RouteHealth.LocalRoute(cat, DateTimeOffset.UtcNow); } + + @if (cat is null) + { + if (State.CatalogError is { } ce) + { + + } + else + { + + } + } + else + { +
+
+

Running configuration

+ + Mode @Fmt.OrNotRecorded(cat.Mode) · read @Fmt.Ago(State.CatalogUpdatedUtc, DateTimeOffset.UtcNow) + +
+
+ @localRoute.Text +
+
Local route configured
@(cat.Local?.Configured == true ? "Yes" : "No")
+
Local:Endpoint (running)
@Fmt.OrNotRecorded(cat.Local?.Endpoint)
+
Local:ModelId (running)
@Fmt.OrNotRecorded(cat.Local?.ModelId)
+
Local model registered
@(cat.Local is null ? "Not reported" : cat.Local.Registered ? "Yes (server-reported)" : "No (server-reported)")
+
Endpoint health
@HealthText(cat.Local?.EndpointHealth)
+
Probe allow-list
@(cat.ProbeAllowList is { Count: > 0 } al ? string.Join(", ", al) : "Not reported")
+
+
+ @if (cat.Models.Count == 0) + { +
+ } + else + { +
+ + + + + + + + + + + + + + @foreach (var m in cat.Models) + { + + + + + + + + + + } + +
AdapterModel idRoute classificationsRegisteredPermittedPrice basisObserved health
@m.Adapter@(m.EndpointHost is { Length: > 0 } eh ? " · " + eh : "")@m.ModelId@(m.Classifications.Count > 0 ? string.Join(", ", m.Classifications) : "None")@(m.Registered ? "Yes" : "No — matching requests are refused at the provider stage")@(m.Classifications.Count > 0 ? "Yes, for " + string.Join(", ", m.Classifications) : "No")@PriceText(m)@HealthText(m.Health)
+
+ } +
Health is observed from real governed calls and probes of the applied endpoint; “unknown” means never observed. GET /v1/models is not a health check.
+
+ } + +
+
+

Connect an existing Ollama

+ One exact model tag · nothing is applied from here +
+
+
+ 1 · Endpoint +
+ + + @(EndpointProblem ?? "Looks valid. Test it next.") + “localhost” means the machine or container running Covenant — not this browser. +
+ @if (_invalidated) + { + The endpoint changed, so the earlier probe, model choice and checks were cleared. The running configuration is unchanged. + } +
+ +
+ 2 · Test connection @StepText(ProbePassed, _probe is not null) + Covenant probes the endpoint from its own host (GET …/models, 5 s timeout, 64 KiB cap, no redirects, allow-listed destinations only). No Covenant credential is forwarded. +
+ +
+ + @if (_probe is { } pr) + { +
+
Allowed destination
@(pr.Allowed ? "Yes" : "No")
+
Reachable
@(pr.Reachable ? "Yes" : "No")
+
HTTP status
@(pr.HttpStatus?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "None")
+
Duration
@(pr.DurationMs is { } ms ? Fmt.Ms(ms) : "Not reported")
+
Normalised endpoint
@Fmt.OrNotRecorded(pr.Endpoint)
+
Error
@(pr.Error ?? "None")
+
+ @if (!pr.Allowed) + { + This destination is not on the operator allow-list. Add @(ConnectionLogic.Authority(_endpoint) ?? "host:port") to Providers:ProbeAllowList (e.g. Providers__ProbeAllowList=@(ConnectionLogic.Authority(_endpoint) ?? "host:port")) and restart Covenant, then test again. + } + else if (!pr.Reachable) + { + The probe failed, so the wizard stops here. Check the address from the Covenant host’s point of view, then edit the endpoint or test again. + } + Observed @(pr.CheckedUtc is { } cu ? Fmt.Utc(cu) : Fmt.Utc(_probeAtUtc)). Reachability is a point-in-time observation. + } +
+ +
+ 3 · Installed models @StepText(DiscoveryPassed, ProbePassed) + What the endpoint reports as installed. Discovery never registers or permits a model. + @if (ProbePassed && _probe is { } dp) + { + if (dp.Models.Count == 0) + { + + } + else + { +
    + @foreach (var t in dp.Models) + { +
  • @t
  • + } +
+ } + } +
+ +
+ 4 · Choose exactly one tag @StepText(TagPassed, DiscoveryPassed) + Covenant registers exactly one local model (Local:ModelId). The tag must match exactly — it is never guessed. + @if (DiscoveryPassed && _probe is { } tp) + { +
+ @foreach (var t in tp.Models) + { + var tag = t; + + } +
+ } +
+ +
+ 5 · Review the route and configuration + @if (TagPassed && _tag is { } rt) + { + @ConnectionLogic.RouteReview(cat?.Mode, rt) +
+ + +
+ @if (_localOnly) + { + @ConnectionLogic.RouteReview("local-only", rt) + } +
@ConnectionLogic.ConfigBlock(_endpoint, rt, _localOnly)
+ Runtime apply is not available in this version: apply the configuration and restart Covenant. Then check what the running instance actually loaded. + } +
+ +
+ 6 · Check applied configuration @StepText(AppliedPassed, _appliedChecked) + Re-reads GET /admin/catalog. Passes only if the running instance loaded this endpoint and tag and reports the model as registered. +
+ +
+ @if (_appliedChecked) + { + @_appliedMessage + } +
+ +
+ 7 · Governed test @TestStepText + Sends a short synthetic prompt to Covenant /v1 with an application key and requested model @(_tag ?? "—"). It passes through the full pipeline to Ollama — never directly. The prompt carries the published sample SSN so that cloud mode routes it to the local model. + @if (string.IsNullOrEmpty(State.ApplicationKey)) + { +
+ + + Held in this tab's memory only; never stored. Shared with the Playground. +
+ } + else + { + Using the application key held in memory for this tab. + } +
+ +
+ @if (_testOutcome is { } to) + { +
+ @(to.Outcome == DisplayOutcome.Paused ? "Paused — not a reachability result" : to.Title) + +
+ @to.Explanation +
+
Request id
@(_testResult?.RequestId ?? "None received")
+ @if (_testEvidence.Record is { } trec) + { +
Selected / attempted / served
@ModelFacts.Selected(trec) · @ModelFacts.Attempted(trec) · @ModelFacts.Served(trec)
+
Classification
@ModelFacts.Classification(trec)
+ } + else + { +
Evidence
@EvidenceText
+ } +
+ @if (_testResult?.RequestId is { Length: > 0 } tid) + { + Open evidence + } + } +
+
+
+ +
+

Optional: use Open WebUI as a client

+
+ Open WebUI + Covenant /v1 + Covenant request pipeline + Ollama +
+
+
OpenAI-compatible base URL
@CovenantV1
+
API key
A Covenant application key — never the admin token.
+
Supported
Text chat, buffered and streamed. Tools, images and other APIs are not supported and are refused.
+
+ Pointing Open WebUI at Ollama directly bypasses Covenant: no policy, budget, pause or audit. +
+
+
+ +@code { + private string _endpoint = ""; + private bool _invalidated; + + private ProbeResponse? _probe; + private DateTimeOffset _probeAtUtc; + private bool _probing; + private string? _probeError; + + private string? _tag; + private bool _localOnly; + + private bool _checking; + private bool _appliedChecked; + private bool _appliedPass; + private string? _appliedMessage; + + private bool _testing; + private InferenceResult? _testResult; + private OutcomeView? _testOutcome; + private EvidenceStatus _testEvidence = EvidenceStatus.Idle; + private CancellationTokenSource? _cts; + + private string? EndpointProblem => ConnectionLogic.EndpointProblem(_endpoint); + private bool ProbePassed => _probe is { Allowed: true, Reachable: true }; + private bool DiscoveryPassed => ProbePassed && _probe is { Models.Count: > 0 }; + private bool TagPassed => DiscoveryPassed && _tag is not null && _probe is { } p && p.Models.Contains(_tag); + private bool AppliedPassed => TagPassed && _appliedChecked && _appliedPass; + + private string CovenantV1 => new Uri(new Uri(Nav.BaseUri).GetLeftPart(UriPartial.Authority)).ToString().TrimEnd('/') + "/v1"; + + private string TestTone => _testOutcome is null ? "" : _testOutcome.PillKind switch { "served" => "ok", "failed" => "bad", _ => "warn" }; + private string TestStepText => _testOutcome is null ? (AppliedPassed ? "Ready" : "Locked") : OutcomeModel.Label(_testOutcome.Outcome); + + private string EvidenceText => _testEvidence.State switch + { + EvidenceState.Pending => "Awaiting audit record…", + EvidenceState.Unavailable => _testEvidence.Message ?? EvidenceTracker.UnavailableMessage, + EvidenceState.Error => _testEvidence.Message ?? "Evidence lookup failed", + _ => _testResult?.RequestId is null ? "No request id received" : "Not looked up", + }; + + protected override void OnInitialized() => State.Changed += OnChanged; + + private static string StepText(bool passed, bool attempted) => passed ? "Passed" : attempted ? "Not passed" : ""; + private static string StepTone(bool passed, bool attempted) => passed ? "ok" : attempted ? "bad" : ""; + + private static string HealthText(ModelHealth? h) + { + if (h is null) return "Not reported"; + var state = string.IsNullOrWhiteSpace(h.State) ? "unknown" : h.State; + var now = DateTimeOffset.UtcNow; + var parts = new List { state }; + parts.Add("last success " + (h.LastSuccessUtc is null ? "never" : Fmt.Ago(h.LastSuccessUtc, now))); + if (h.LastFailureUtc is not null) parts.Add("last failure " + Fmt.Ago(h.LastFailureUtc, now)); + if (!string.IsNullOrWhiteSpace(h.LastError)) parts.Add("error: " + h.LastError); + return string.Join(" · ", parts); + } + + private static string PriceText(CatalogModel m) => m.PriceBasis switch + { + "zero" => "$0 configured provider price (infrastructure excluded)", + "configured" => $"{(m.InPer1M is { } i ? Fmt.Usd(i, 2) : "?")} in / {(m.OutPer1M is { } o ? Fmt.Usd(o, 2) : "?")} out per 1M tokens", + "unpriced" => "Unpriced — cost unknown, not zero", + _ => "Not reported", + }; + + private void OnEndpointInput(ChangeEventArgs e) + { + var next = e.Value?.ToString() ?? ""; + if (string.Equals(next, _endpoint, StringComparison.Ordinal)) return; + bool hadDraftResults = _probe is not null || _tag is not null || _appliedChecked || _testOutcome is not null; + _endpoint = next; + InvalidateFromProbe(); + _invalidated = hadDraftResults; + } + + /// Editing the endpoint invalidates every later DRAFT result. The running configuration is untouched. + private void InvalidateFromProbe() + { + _cts?.Cancel(); + _probe = null; + _probeError = null; + _tag = null; + InvalidateFromApplied(); + } + + private void InvalidateFromApplied() + { + _appliedChecked = false; + _appliedPass = false; + _appliedMessage = null; + _testResult = null; + _testOutcome = null; + _testEvidence = EvidenceStatus.Idle; + } + + private void ChooseTag(string tag) + { + if (string.Equals(_tag, tag, StringComparison.Ordinal)) return; + _tag = tag; + InvalidateFromApplied(); + } + + private async Task ProbeAsync() + { + if (EndpointProblem is not null || _probing) return; + var endpoint = _endpoint.Trim(); + _probing = true; + _probeError = null; + _invalidated = false; + _probe = null; + _tag = null; + InvalidateFromApplied(); + try + { + var result = await Api.ProbeAsync(endpoint); + // Ignore a stale answer if the endpoint was edited while the probe was running. + if (string.Equals(_endpoint.Trim(), endpoint, StringComparison.Ordinal)) + { + _probe = result; + _probeAtUtc = DateTimeOffset.UtcNow; + } + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // handled by ConsoleSession + } + catch (Exception ex) + { + _probeError = ex.Message; + } + finally + { + _probing = false; + } + // A probe of the APPLIED endpoint updates its observed health on the server. + await Catalog.RefreshAsync(); + } + + private async Task CheckAppliedAsync() + { + if (!TagPassed || _tag is not { } tag) return; + _checking = true; + try + { + await Catalog.RefreshAsync(); + var (pass, message) = ConnectionLogic.CheckApplied(State.Catalog, _endpoint, tag); + _appliedPass = pass; + _appliedMessage = message + " Read " + Fmt.Utc(State.CatalogUpdatedUtc) + "."; + _appliedChecked = true; + } + finally + { + _checking = false; + } + } + + private void OnKeyInput(ChangeEventArgs e) => State.SetApplicationKey(e.Value?.ToString()); + + private async Task RunTestAsync() + { + if (!AppliedPassed || _testing || _tag is not { } tag) return; + _testing = true; + _testResult = null; + _testOutcome = null; + _testEvidence = EvidenceStatus.Idle; + _cts?.Cancel(); + var cts = new CancellationTokenSource(); + _cts = cts; + try + { + var form = new PlaygroundForm + { + Prompt = ConnectionLogic.GovernedTestPrompt(), + Mode = RouteMode.Explicit, + ExplicitModel = tag, + MaxTokens = 16, + Workflow = "connection-test", + UseCase = "local-route-check", + }; + var snapshot = RequestSnapshot.Freeze(1, form, DateTimeOffset.UtcNow); + var result = await Inference.SendAsync(snapshot, null, cts.Token); + _testResult = result; + _testOutcome = OutcomeModel.Compute(result.ToOutcomeInput(null)); + StateHasChanged(); + + if (result.RequestId is { Length: > 0 } id && result.HttpStatus is not null) + { + var final = await Evidence.TrackAsync(id, s => { _testEvidence = s; _ = InvokeAsync(StateHasChanged); }, cts.Token); + if (final.State != EvidenceState.Idle) _testEvidence = final; + _testOutcome = OutcomeModel.Compute(result.ToOutcomeInput(_testEvidence.Record)); + } + } + finally + { + _testing = false; + if (ReferenceEquals(_cts, cts)) _cts = null; + cts.Dispose(); + } + // The backend records success/failure from this real call; re-read shared health so the header and catalog + // show a later failure even after an earlier success (last success time is kept by the server). + await Catalog.RefreshAsync(); + } + + private void OnChanged() => _ = InvokeAsync(StateHasChanged); + + public void Dispose() + { + State.Changed -= OnChanged; + _cts?.Cancel(); + } +} diff --git a/src/Covenant.Ui/Pages/Evidence.razor b/src/Covenant.Ui/Pages/Evidence.razor new file mode 100644 index 0000000..6917742 --- /dev/null +++ b/src/Covenant.Ui/Pages/Evidence.razor @@ -0,0 +1,219 @@ +@page "/evidence" +@inject AppState State +@inject AdminApi Api +@inject Interop Interop +@implements IDisposable + +Evidence · Covenant + +
+ +
+
+

Evidence

+ Hash-chained audit log for this environment. Every allow and every refusal is an entry. +
+ + +
+ + @if (_error is not null) + { + + } + @if (_exportError is not null) + { + + } + + @if (_report is null && _error is null) + { +
+ } + else if (_report is { } r) + { +
+
+

+ @(r.ChainValid ? "Internal consistency verified" : "Chain verification FAILED") +

+ @if (r.ChainValid) + { + Internal consistency verified: every stored record hashes to the next; this does not prove completeness or independent anchoring. + } + else + { + @Fmt.OrNotRecorded(r.ChainFailure)@(r.FirstInvalidLine is { } line ? $" — first invalid line {line}." : "") Entries after the break are not trusted; the count below is the verified prefix. + } +
+ + @if (!r.ChainValid) + { + + } +
+ +
+
+

A passing verification shows

+
    +
  • The current entries and their hash links are internally consistent: every stored record hashes to the next.
  • +
  • When anchors exist: the history they cover matches those separately protected comparison points.
  • +
+
+
+

It does not show

+
    +
  • That history was never rewritten: anyone able to rewrite the log can recompute an unanchored chain.
  • +
  • That every event was captured, or anything about traffic that bypassed Covenant.
  • +
  • Regulatory compliance of any kind.
  • +
+
+
+ +
+
+

Anchor

+ @AnchorStatusText(r) +
+

An anchor written to separately protected storage gives verification a trusted comparison point for the history it covers. It is only as strong as the protection of that storage. “Configured” means the Host will write anchors; “Verified” means this verification compared the log against anchors that exist.

+ +
+ +
+
+

Segments

+ Archived segments are kept on the appliance and remain verifiable outside the console +
+
+ + + + + + + + + + +
SegmentPeriodEntriesStatus
Current@(r.FirstEntryUtc is null ? "No entries yet" : Fmt.Utc(r.FirstEntryUtc) + " → " + Fmt.Utc(r.LastEntryUtc))@Fmt.Int(r.Entries)@(r.ChainValid ? "Verified" : "FAILED")
+
+

Archived segments are not browsable from the console in this release; verify them from the appliance with the exported report as reference.

+
+ } +
+
+ +@code { + private EvidenceReport? _report; + private bool _loading; + private bool _exporting; + private string? _error; + private string? _exportError; + private DateTimeOffset? _verifiedAt; + private bool _started; + + protected override void OnInitialized() => State.Changed += OnChanged; + + protected override async Task OnParametersSetAsync() + { + if (State.Connected && !_started) await LoadAsync(); + } + + private async Task LoadAsync() + { + if (_loading) return; + _started = true; + _loading = true; _error = null; + StateHasChanged(); + try + { + _report = await Api.GetEvidenceAsync(); + _verifiedAt = DateTimeOffset.UtcNow; + } + catch (Exception ex) + { + _error = ex.Message; + _report = null; // never show a previous green state against a failed check + } + finally + { + _loading = false; + StateHasChanged(); + } + } + + private async Task ExportAsync() + { + _exporting = true; _exportError = null; + try + { + var json = await Api.GetEvidenceJsonAsync(); + var name = $"covenant-evidence-{DateTimeOffset.UtcNow:yyyyMMdd-HHmmss}Z.json"; + await Interop.DownloadTextAsync(name, "application/json", json); + } + catch (Exception ex) + { + _exportError = ex.Message; + } + finally + { + _exporting = false; + } + } + + private IReadOnlyList StatusFacts(EvidenceReport r) => + [ + new("Last verification", _verifiedAt is { } v ? Fmt.Utc(v) : "—", true), + new("Scope", "Current segment"), + new("Entries checked", Fmt.Int(r.Entries), true), + new("Allowed / refused", $"{Fmt.Int(r.Allowed)} / {Fmt.Int(r.Denied)}", true), + new("First entry", Fmt.Utc(r.FirstEntryUtc), true), + new("Last entry", Fmt.Utc(r.LastEntryUtc), true), + new("Source", "GET /admin/evidence", true), + ]; + + private bool? AnchorConfigured(EvidenceReport r) => r.AnchorConfigured ?? State.LastStatus?.Anchor?.Configured; + private long? AnchorCount(EvidenceReport r) => r.AnchorCount ?? State.LastStatus?.Anchor?.AnchorsWritten; + private DateTimeOffset? LastAnchor(EvidenceReport r) => r.LastAnchorUtc ?? State.LastStatus?.Anchor?.LastAnchorUtc; + + private string AnchorStatusText(EvidenceReport r) + { + var configured = AnchorConfigured(r); + if (configured is null) return "Not reported by this Host"; + if (configured == false) return "Not configured"; + var count = AnchorCount(r); + if (count is null) return "Configured · coverage not reported"; + if (count == 0) return "Configured · no anchor written yet"; + return r.ChainValid ? $"Configured · {Fmt.Int(count.Value)} anchors compared" : $"Configured · {Fmt.Int(count.Value)} anchors"; + } + + private string AnchorPillKind(EvidenceReport r) + { + var configured = AnchorConfigured(r); + if (configured != true) return "unknown"; + var count = AnchorCount(r); + return count is > 0 && r.ChainValid ? "served" : "refused"; + } + + private IReadOnlyList AnchorFacts(EvidenceReport r) => + [ + new("Audit:AnchorPath", AnchorConfigured(r) switch { true => "Configured (path not exposed)", false => "Not set", null => "Not reported" }), + new("Audit:AnchorEvery", State.LastStatus?.Anchor?.Every is { } every ? $"every {Fmt.Int(every)} entries" : "Not reported", true), + new("Anchors written", AnchorCount(r) is { } n ? Fmt.Int(n) : "Not reported", true), + new("Last anchor written", LastAnchor(r) is { } t ? Fmt.Utc(t) : "Not reported", true), + ]; + + private void OnChanged() + { + if (State.Connected && !_started) _ = InvokeAsync(LoadAsync); + _ = InvokeAsync(StateHasChanged); + } + + public void Dispose() => State.Changed -= OnChanged; +} diff --git a/src/Covenant.Ui/Pages/NotFound.razor b/src/Covenant.Ui/Pages/NotFound.razor new file mode 100644 index 0000000..d64b8ed --- /dev/null +++ b/src/Covenant.Ui/Pages/NotFound.razor @@ -0,0 +1,10 @@ +@page "/not-found" +@* Router.NotFoundPage (.NET 10; the render fragment is obsolete). Rendered inside MainLayout. *@ + +Not found · Covenant + + diff --git a/src/Covenant.Ui/Pages/Overview.razor b/src/Covenant.Ui/Pages/Overview.razor new file mode 100644 index 0000000..021e00f --- /dev/null +++ b/src/Covenant.Ui/Pages/Overview.razor @@ -0,0 +1,273 @@ +@page "/" +@inject AppState State +@inject ConsoleSession Session +@implements IDisposable + +Overview · Covenant + +
+ + @if (State.LastStatus is not { } s) + { + + } + else + { + var f = s.FinOps; + + @* ---- What needs attention (first) ---- *@ + if (State.Paused) + { + + } + if (!s.ChainValid) + { + + } + if (State.IsStale) + { + + } + if (RouteHealth.LocalRouteMissing(s, State.Catalog)) + { + + } + var localRoute = RouteHealth.LocalRoute(State.Catalog, DateTimeOffset.UtcNow); + if (localRoute.State == LocalRouteState.Degraded) + { + 0 } le ? " (" + le + ")" : "") + ". Requests routed to it fail closed; they are never sent elsewhere.")" + ActionText="Review connection" ActionHref="connections" /> + } + if (State.Catalog is null && State.CatalogError is not null) + { + + } + if (!State.Paused && s.ChainValid && !State.IsStale && !RouteHealth.LocalRouteMissing(s, State.Catalog) && localRoute.State != LocalRouteState.Degraded && State.Catalog is not null) + { +
+
+ Nothing needs attention + New provider calls are accepted, the audit chain verifies, and every configured route has a registered adapter. +
+
+ } + +
+
+

Overview

+ @SegmentLabel(s). Opening this page never resets accounting. +
+ View requests + Run a request +
+ + @* ---- Summary row ---- *@ +
+
+
Served
+
@Fmt.Int(f.Allowed)
+
@(f.CacheHits > 0 ? $"Including {Fmt.Int(f.CacheHits)} served from cache" : "Allowed by policy and answered")
+
+
+
Refused or failed
+
@Fmt.Int(f.Denied)
+
Every refusal is an audit entry · reasons below
+
+
+
Estimated provider charges
+
@Fmt.Usd(f.TotalCostUsd)
+
Reported tokens × configured prices · infrastructure excluded
+
+
+
Global budget used
+
@Fmt.Percent(s.Budget.GlobalSpendUsd, s.Budget.GlobalCapUsd)
+
@Fmt.Usd(s.Budget.GlobalSpendUsd) of @Fmt.UsdTotal(s.Budget.GlobalCapUsd) cap
+
+ + + +
+
+
+ +
+ + + @(s.ChainValid ? "Audit chain verifies" : "Audit chain verification FAILED") + + Checked @Fmt.Ago(State.LastUpdatedUtc, DateTimeOffset.UtcNow) · @Fmt.Int(s.AuditEntries) entries in this segment + Open evidence +
+ + @* ---- Activity ---- *@ +
+
+

Activity

+ @ActivityWindow(f) +
+ @if (f.Activity.Count == 0) + { + + } + else + { + var peakReq = Math.Max(1, f.Activity.Max(b => b.Requests)); + var peakCost = f.Activity.Max(b => b.CostUsd); +
+
+ Requests per minute + Served + Refused or failed + peak @peakReq / min +
+ +
@Fmt.UtcShort(f.Activity[0].T) UTC@Fmt.UtcShort(f.Activity[^1].T) UTC
+
+
+
+ Estimated provider charges per minute (USD) + peak @Fmt.Usd(peakCost) / min +
+ +
@Fmt.UtcShort(f.Activity[0].T) UTC@Fmt.UtcShort(f.Activity[^1].T) UTC
+
+ } +
+ +
+
+
+

Recent notable outcomes

+ All requests +
+ @if (Notable(f).Count == 0) + { +
+ } + else + { +
    + @foreach (var r in Notable(f)) + { +
  • + @Fmt.UtcShort(r.T) + + + @r.Reason + @if (r.Model is { Length: > 0 }) + { + · @r.Model + } + · @r.Team + + @r.Id +
  • + } +
+ } +
+ +
+
+

Refusals by reason

+ This segment, grouped from the audit reason text +
+ @if (f.DenialsByReason.Count == 0) + { +
No refusals in this segment.
+ } + else + { +
+ + + @foreach (var kv in f.DenialsByReason.OrderByDescending(k => k.Value)) + { + + } + +
@kv.Key@Fmt.Int(kv.Value)
+
+ } +
+
+ } +
+
+ +@code { + private bool _busy; + private bool _refreshing; + + protected override void OnInitialized() => State.Changed += OnChanged; + + private static int Pct(int value, int peak) => peak <= 0 ? 0 : (int)Math.Round(value * 100.0 / peak); + + private static string MeterTone(StatusReport s) + { + var pct = Fmt.PercentClamped(s.Budget.GlobalSpendUsd, s.Budget.GlobalCapUsd); + return pct >= 100 ? "bad" : pct >= 80 ? "warn" : ""; + } + + /// Totals cover the current audit segment. Its start is the oldest activity bucket when there is any + /// (the Host's segment first_utc is not in /admin/status); otherwise we say so rather than guess. + private static string SegmentLabel(StatusReport s) + { + var oldest = s.FinOps.Activity.Count > 0 ? s.FinOps.Activity[0].T : (DateTimeOffset?)null; + return oldest is null + ? "Totals cover the current audit segment (no entries yet)" + : "Current audit segment since " + Fmt.Utc(oldest); + } + + private static string ActivityWindow(FinOpsSummary f) + { + if (f.Activity.Count == 0) return "Per-minute buckets · nothing recorded"; + var span = f.Activity[^1].T - f.Activity[0].T + TimeSpan.FromMinutes(1); + return $"Per-minute buckets · {Fmt.Duration(span)} ending {Fmt.UtcShort(f.Activity[^1].T)} UTC (most recent hour retained)"; + } + + private static List Notable(FinOpsSummary f) + => f.Recent.Where(r => !string.Equals(r.Effect, "Allow", StringComparison.OrdinalIgnoreCase)).Take(8).ToList(); + + private async Task ResumeAsync() + { + _busy = true; + await Session.SetPausedAsync(false, null); + _busy = false; + } + + private async Task RefreshAsync() + { + _refreshing = true; + await Session.TryRefreshAsync(); + _refreshing = false; + } + + private void OnChanged() => _ = InvokeAsync(StateHasChanged); + public void Dispose() => State.Changed -= OnChanged; +} diff --git a/src/Covenant.Ui/Pages/Playground.razor b/src/Covenant.Ui/Pages/Playground.razor new file mode 100644 index 0000000..ec7163c --- /dev/null +++ b/src/Covenant.Ui/Pages/Playground.razor @@ -0,0 +1,661 @@ +@page "/playground/{Scenario?}" +@inject AppState State +@inject PlaygroundState Pg +@inject ConsoleSession Session +@inject Interop Interop +@inject NavigationManager Nav +@implements IDisposable + +Playground · Covenant + +@* + TASK 04. Every Run sends a real POST /v1/chat/completions with the APPLICATION key (never the admin token); + the governed pipeline decides the outcome. Presets only fill the form. Each run freezes a RequestSnapshot, and + its result/evidence stay tied to that snapshot. Evidence is looked up by the server's correlation id + (X-Covenant-Request-Id == audit Id) — never by timestamp. Response text is console-only and memory-only. +*@ + +@if (_present) +{ + +
+
+ Covenant + @State.EnvironmentLabel + @if (State.LastStatus?.Mode is { Length: > 0 } mode) + { + Provider mode: @mode + } + + + @(State.Paused ? "New provider calls paused" : "New provider calls accepted") + + + Pauses NEW provider calls. Cache hits and in-flight calls are not stopped. + @if (_pauseError is not null) + { + @_pauseError + } + @if (State.Paused) + { + + } + else + { + + } + + +
+ +
+ @foreach (var p in ScenarioPresets.All) + { + var preset = p; + + } +
+ +
+
+ + + @SetupLine() + @if (Pg.Form.Problem is { } problem && Pg.Form.Prompt.Length > 0) + { + @problem + } +
+ + +
+ Cancel stops waiting; it is not a rollback. +
+ +
+ @if (Pg.Selected is not { } run) + { + Ready + Pick a scenario and press Run request. + } + else + { + + @run.Snapshot.Title · @Fmt.UtcShort(run.Snapshot.SubmittedUtc) UTC + @if (!run.Snapshot.MatchesForm(Pg.Form)) + { + · previous request + } + + @if (run.InFlight) + { + Sending request #@run.Snapshot.Sequence… + } + else if (run.Outcome is { } o) + { +
+ @o.Title + @o.StatusLine +
+ @o.Explanation + } +
@(run.Text.Length == 0 ? (run.InFlight ? "Waiting for the first token…" : "No response text.") : run.Text)
+
+
Model
@PresentModel(run)
+
Estimated provider cost
@CostFor(run)
+
Duration
@DurationFor(run)
+
+
+ + @if (RequestIdOf(run) is { } rid) + { + + } + @EvidenceShort(run) +
+ } +
+
+
+ + + @SetupFields + + + @if (Pg.Selected is { } ir) + { + @FactsBlock(ir) + @EvidenceBlock(ir) + @FlowBlock(ir) + } + +
+} +else +{ +
+ +
+
+

Playground

+ Send a request through the governed pipeline and inspect exactly what happened to it. +
+ The header’s Pause control pauses NEW provider calls. Cache hits and in-flight calls are not stopped. + +
+ +
+
+

New request

+
+ Scenario preset — fills the form; only Run sends +
+ @foreach (var p in ScenarioPresets.All) + { + var preset = p; + + } +
+ @if (ScenarioPresets.Find(Pg.Form.Scenario) is { } cur) + { + @cur.Note + } + @if (Pg.Form.Scenario == 'C' && RouteHealth.LocalRoute(State.Catalog, DateTimeOffset.UtcNow).State is LocalRouteState.NotConfigured or LocalRouteState.NotRegistered) + { + No usable local route is registered, so policy will refuse C (fail-closed). Set up the connection + } +
+ +
+ + + @if (Pg.Form.FreshNonce) + { + A fresh nonce ([run …]) is appended on every run, so this request is never served from cache. + } +
+ + @SetupFields + +
+ + + +
+ @if (Pg.Form.Problem is { } problem && Pg.Form.Prompt.Length > 0) + { + @problem + } + Cancel stops waiting; it is not a rollback. Work or provider cost already incurred remains. +
+ +
+

Result

+ @if (Pg.Selected is not { } run) + { + + } + else + { +
+ @run.Snapshot.Title + submitted @Fmt.UtcShort(run.Snapshot.SubmittedUtc) UTC · @run.Snapshot.RoutingLabel · @(run.Snapshot.Streaming ? "streamed" : "buffered") + @if (!run.InFlight && !run.Snapshot.MatchesForm(Pg.Form)) + { + Previous request — the form has changed since + } +
+ + @if (run.InFlight) + { + Sending request #@run.Snapshot.Sequence… + Waiting for Covenant. Cancel stops waiting; it does not roll anything back. + } + else if (run.Outcome is { } o) + { +
+ @o.Title + +
+ @o.Explanation + @if (run.Result?.ErrorReason is { Length: > 0 } why) + { + Server reason: @why + } + @if (run.Result?.TransportError is { Length: > 0 } te) + { + @te + } + @if (run.Evidence.Record is { StoppedAtStage: "provider", AttemptedModel: null }) + { + Review the connection for this route + } + } + +
+ Response — console-only; not persisted; cleared on disconnect or reload +
@(run.Text.Length == 0 ? (run.InFlight ? "Waiting for the first token…" : "No response text.") : run.Text)
+
+ + @FactsBlock(run) + +
+ @if (RequestIdOf(run) is { } rid) + { + + } + @EvidenceShort(run) +
+ + @if (Pg.Runs.Count > 1) + { +
+ This session + @foreach (var h in Pg.Runs) + { + var hr = h; + + } +
+ } + } +
+
+ +
+
+ @if (Pg.Selected is { } fr) + { + @FlowBlock(fr) + } + else + { + @FlowBlock(null) + } +
+
+

+ +

+ @if (_evOpen) + { + if (Pg.Selected is { } evr) + { + @EvidenceBlock(evr) + } + else + { + Run a request to see its audit evidence here. + } + } +
+
+
+
+} + +@code { + [Parameter] public string? Scenario { get; set; } + [SupplyParameterFromQuery(Name = "present")] public string? Present { get; set; } + + private bool _present; + private string? _appliedScenario; + private bool _setupOpen; + private bool _inspectOpen; + private bool _evOpen = true; + private bool _pauseBusy; + private string? _pauseError; + private string? _copyNote; + + private bool CanRun => !Pg.Running && Pg.Form.Problem is null; + + private IReadOnlyList PermittedModels + => State.Catalog is { } c ? c.Models.Where(m => m.Classifications.Count > 0).ToList() : []; + + protected override void OnInitialized() + { + State.Changed += OnChanged; + Pg.Changed += OnChanged; + } + + protected override void OnParametersSet() + { + _present = string.Equals(Present, "1", StringComparison.Ordinal); + if (!string.Equals(Scenario, _appliedScenario, StringComparison.OrdinalIgnoreCase)) + { + _appliedScenario = Scenario; + // A scenario in the URL only fills the form, like clicking the preset. Never while a run is in flight. + if (!Pg.Running && ScenarioPresets.Find(Scenario) is { } preset) Pg.ApplyPreset(preset); + } + } + + private Task RunAsync() => Pg.RunAsync(); + + private void Cancel() => Pg.Cancel(); + + private void TogglePresent() + { + _setupOpen = false; + _inspectOpen = false; + Nav.NavigateTo(Nav.GetUriWithQueryParameter("present", _present ? null : "1")); + } + + private void OpenSetup() => _setupOpen = true; + private void OpenInspect() => _inspectOpen = true; + + private void OpenInRequests(string id) + { + _inspectOpen = false; + Nav.NavigateTo("requests/" + Uri.EscapeDataString(id)); + } + + private void SetMode(RouteMode mode) + { + Pg.Form.Mode = mode; + if (mode == RouteMode.Catalog && string.IsNullOrWhiteSpace(Pg.Form.CatalogModel) && PermittedModels.Count > 0) + Pg.Form.CatalogModel = PermittedModels[0].ModelId; + } + + private void OnKeyInput(ChangeEventArgs e) => State.SetApplicationKey(e.Value?.ToString()); + + private void ForgetKey() => State.SetApplicationKey(null); + + private async Task CopyIdAsync(string id) + { + bool ok; + try { ok = await Interop.CopyTextAsync(id); } + catch (JSException) { ok = false; } + _copyNote = ok ? "Copied" : "Copy failed — select the id and copy it manually"; + } + + private async Task PauseAsync() + { + _pauseBusy = true; _pauseError = null; + var err = await Session.SetPausedAsync(true, "paused from console (presentation)"); + _pauseBusy = false; + _pauseError = err is null ? null : "Pause failed — " + err; + } + + private async Task ResumeAsync() + { + _pauseBusy = true; _pauseError = null; + var err = await Session.SetPausedAsync(false, null); + _pauseBusy = false; + _pauseError = err is null ? null : "Resume failed — " + err; + } + + // ---- Text helpers (all derived from the run's own snapshot / result / audit record) ---- + + private static string? RequestIdOf(PlaygroundRun run) => run.Result?.RequestId is { Length: > 0 } id ? id : null; + + private string SetupLine() + { + var key = string.IsNullOrEmpty(State.ApplicationKey) ? "no application key (the server will answer 401)" : "application key set (memory only)"; + var route = Pg.Form.RequestedModel ?? RequestSnapshot.PolicyChooses; + return $"{key} · {route} · {(Pg.Form.Streaming ? "streamed" : "buffered")}"; + } + + private static string AwaitingText(PlaygroundRun run) => run.InFlight ? "Awaiting response" : run.Evidence.State switch + { + EvidenceState.Pending => "Awaiting audit record…", + EvidenceState.Unavailable => "Not available — no audit record found yet", + EvidenceState.Error => "Not available — evidence lookup failed", + _ => RequestIdOf(run) is null ? "Not available — no request id received" : "Not available — no audit record", + }; + + private static string DurationFor(PlaygroundRun run) + { + if (run.Evidence.Record is { } rec) return Fmt.Ms(rec.DurationMs) + " (recorded by Covenant)"; + if (run.InFlight) return Fmt.Ms(run.Clock.Elapsed.TotalMilliseconds) + " so far (client-measured)"; + return run.Result is { } r ? Fmt.Ms(r.ClientMs) + " (client-measured)" : "Not reported"; + } + + private static string CostFor(PlaygroundRun run) + => run.Evidence.Record is { } rec ? CostText.Cost(rec) : AwaitingText(run); + + private static string TokensFor(PlaygroundRun run) + => run.Evidence.Record is { } rec ? CostText.Tokens(rec) : AwaitingText(run); + + private static string PresentModel(PlaygroundRun run) + { + if (run.Evidence.Record is not { } rec) return AwaitingText(run); + var f = ModelFacts.From(rec); + return rec.CacheHit || !string.IsNullOrWhiteSpace(rec.ServedByModel) ? f.Served : "Selected: " + f.Selected + " · attempted: " + f.Attempted; + } + + private static string EvidenceShort(PlaygroundRun run) + { + if (run.InFlight) return ""; + return run.Evidence.State switch + { + EvidenceState.Pending => $"Awaiting audit record… (lookup {run.Evidence.Attempts + 1})", + EvidenceState.Found => "Audit record found", + EvidenceState.Unavailable => run.Evidence.Message ?? EvidenceTracker.UnavailableMessage, + EvidenceState.Error => run.Evidence.Message ?? "Evidence lookup failed", + _ => run.Outcome?.Outcome == DisplayOutcome.RejectedBeforeGovernance + ? "Rejected before governance (400); no evidence record" + : RequestIdOf(run) is null ? "No request id was received, so there is no exact record to open" : "", + }; + } + + // ---- Shared fragments (normal layout and presentation drawers) ---- + + private RenderFragment SetupFields => @
+
+ +
+ + @if (!string.IsNullOrEmpty(State.ApplicationKey)) + { + + } +
+ @if (string.IsNullOrEmpty(State.ApplicationKey)) + { + No application key set — Run will be refused with HTTP 401 (useful only for the authentication-failure demo). Paste an application key, e.g. the App key printed by scripts/run-local-demo.sh. The admin token does not work here. + } + Held in this tab's memory only; never stored — a page reload clears it. Identity and team are resolved by Covenant from this key — never from the admin token. +
+ +
+ Model routing +
+ + + +
+ @if (Pg.Form.Mode == RouteMode.Policy) + { + Classification picks the route (see Policies). No model is requested. + } + else if (Pg.Form.Mode == RouteMode.Catalog) + { + + + From GET /admin/catalog. Policy still checks the request’s classification: a listed model is not a permission grant. + } + else + { + + + } + @if (State.Catalog is null) + { + @(State.CatalogError is { } ce ? "Catalog unavailable: " + ce : "Catalog not loaded yet.") + } +
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ Labels are attribution text only (X-Covenant-Workflow / X-Covenant-UseCase); they do not change identity, team or permission. + +
; + + private RenderFragment FactsBlock => run => @
+ @if (run.Evidence.Record is { } rec) + { + var f = ModelFacts.From(rec); +
Selected model
@f.Selected
+
Provider attempted
@f.Attempted
+
Served model
@f.Served
+
Classification
@f.Classification
+
Identity
@rec.Principal · team @Fmt.OrNotRecorded(rec.Tags.Team)
+ } + else + { +
Selected / attempted / served
@AwaitingText(run)
+ } +
Duration
@DurationFor(run)
+
Tokens
@TokensFor(run)
+
Estimated cost
@CostFor(run)
+
Request id
+
+ @if (RequestIdOf(run) is { } id) + { + + @id + + @if (_copyNote is not null) + { + @_copyNote + } + + } + else + { + @(run.InFlight ? "Awaiting response" : "None — no response with a request id was received") + } +
+
; + + private RenderFragment EvidenceBlock => run => @
+ @switch (run.Evidence.State) + { + case EvidenceState.Found when run.Evidence.Record is { } rec: + var o = OutcomeModel.FromRecord(rec); +
+
Audit record
@rec.Id
+
Recorded
@Fmt.Utc(rec.TimestampUtc)
+
Recorded outcome
+
Effect / denial kind
@rec.Effect · @Fmt.OrNotRecorded(rec.DenialKind)
+
Stopped at
@(rec.StoppedAtStage is { } st ? PipelineStages.Label(st) : string.Equals(rec.Effect, "Allow", StringComparison.OrdinalIgnoreCase) ? "Completed" : "Not recorded")
+
Reason
@rec.Reason
+
Cost basis
@CostText.BasisDescription(rec.CostBasis)
+
Prompt fingerprint
sha256 @Fmt.OrNotRecorded(rec.PromptSha256) · @rec.PromptChars chars
+
+
+ +
+ break; + case EvidenceState.Pending: + Awaiting audit record… The audit sink writes asynchronously; looking up @RequestIdOf(run) (attempt @(run.Evidence.Attempts + 1)). + break; + case EvidenceState.Unavailable: + + This does not mean the audit write failed — the record may still be on its way. + break; + case EvidenceState.Error: + + break; + default: + if (run.InFlight) + { + The request is still in flight. + } + else if (run.Outcome?.Outcome == DisplayOutcome.RejectedBeforeGovernance) + { + Rejected before governance (400); no evidence record — the request never reached the pipeline. + } + else if (RequestIdOf(run) is null) + { + No request id was received (stopped waiting before the response headers, or Covenant was unreachable), so there is no exact record to look up. Search Requests by time instead — never assume the newest record is this one. + } + break; + } +
; + + private RenderFragment FlowBlock => run => @
+
+

Configured processing order

+
+ The order assembled at startup — not a measured trace. Only the stage recorded as stopping this request is highlighted; no timings are shown. +
    + @{ var rec = run?.Evidence.Record; var stopKey = PipelineStages.RowKey(rec?.StoppedAtStage); var n = 0; } + @foreach (var st in PipelineStages.Configured) + { + n++; + var stopped = stopKey == st.Key; + var cacheHit = rec is { CacheHit: true } && st.Key == "cache"; +
  1. + @n + @st.Name + @st.Detail + @if (stopped) + { + · stopped here (recorded) + } + else if (cacheHit) + { + · served from cache here; later stages skipped + } +
  2. + } +
+ + Audit wraps every request, including refusals. + @if (rec is { } r && string.Equals(r.Effect, "Allow", StringComparison.OrdinalIgnoreCase) && !r.CacheHit) + { + This request completed: no stage stopped it. + } + else if (rec is { StoppedAtStage: null, DenialKind: null } lr && string.Equals(lr.Effect, "Deny", StringComparison.OrdinalIgnoreCase)) + { + Stopping stage not recorded (legacy record). + } + else if (run is { InFlight: false } && rec is null) + { + The stopping stage is shown once the audit record arrives. + } + +
; + + private void OnChanged() => _ = InvokeAsync(StateHasChanged); + + public void Dispose() + { + State.Changed -= OnChanged; + Pg.Changed -= OnChanged; + } +} diff --git a/src/Covenant.Ui/Pages/Policies.razor b/src/Covenant.Ui/Pages/Policies.razor new file mode 100644 index 0000000..3ce4384 --- /dev/null +++ b/src/Covenant.Ui/Pages/Policies.razor @@ -0,0 +1,163 @@ +@page "/policies" +@inject AppState State +@implements IDisposable + +Policies · Covenant + +
+ + @if (State.LastStatus is not { } s) + { + + } + else + { + var groups = s.Routes.GroupBy(r => r.Classification).OrderBy(g => ClassificationOrder(g.Key)).ToList(); + var unresolved = RouteHealth.UnresolvedRoutes(s, State.Catalog); + +
+
+

Policies

+ Routing is decided by classification. Application keys set identity and team; they do not grant models. +
+ Managed by configuration; restart required + Try in Playground +
+ +
+

In plain words

+
    + @foreach (var g in groups) + { +
  • + @g.Key requests may use + @foreach (var (r, i) in g.Select((x, idx) => (x, idx))) + { + if (i > 0) { , } + @r.Adapter:@r.Model + } + @if (g.Count() > 1 && s.RoutingThresholdTokens > 0) + { + ; requests estimated under ~@Fmt.Int(s.RoutingThresholdTokens) tokens take the cheapest route and larger ones escalate. + } + else + { + . + } +
  • + } +
  • A caller may ask for a specific model only if it is in the route set for the request’s classification.
  • +
  • Each request starts with the restrictive default for enforcement. That default is never reported as a detection — when a stage before Classify refuses, the record shows “Not evaluated”.
  • + @if (s.Routes.Count == 0) + { +
  • No routes are configured. Every request is refused by policy (fail-closed).
  • + } +
+
+ +
+
+

Classification routes

+ Read-only · as loaded at start · @(Fmt.Int(s.Routes.Count) + (s.Routes.Count == 1 ? " route" : " routes")) +
+ @if (s.Routes.Count == 0) + { +
+ } + else + { +
+ + + + + + + + + + + @foreach (var g in groups) + { + var first = true; + foreach (var r in g) + { + + + + + + + first = false; + } + } + +
ClassificationAdapterModelAdapter status
@(first ? g.Key : "")@r.Adapter@r.Model@AdapterStatus(r)
+
+ } + @if (unresolved.Count > 0) + { +
+ +
+ } +
+ +
+
+

Configured processing order

+ A request stops at the first stage that refuses it; a cache hit skips every stage after Cache. Audit wraps the whole pipeline and records every outcome, including refusals. +
+

auth → shape → classify → policy → cache → rate limit → pause/budget → provider → attribution (audit wraps)

+
    + @foreach (var (name, desc, i) in Stages.Select((st, idx) => (st.Name, st.Desc, idx + 1))) + { +
  1. @i@name — @desc
  2. + } +
+
+ +
+

Editing policies in the console is not available

+ An editor needs validation, versioned configuration, authorization, a review-then-apply step and defined rollback first. Per-application model grants do not exist today. +
+ } +
+
+ +@code { + private static readonly (string Name, string Desc)[] Stages = + [ + ("Auth", "Application key → principal and team. Unknown key: refused (Unauthenticated)."), + ("Shape", "Only plain text chat is governed; tools, images and audio are refused (Unsupported)."), + ("Classify", "Public / Internal / PII / PHI from the prompt text; the restrictive default applies until evaluated."), + ("Policy", "Allowed route set for the classification; a requested model outside it is refused."), + ("Cache", "An identical governed request within the TTL is answered from cache — no provider call, no charge."), + ("Rate limit", "Per-principal limits; over the limit: refused (RateLimited)."), + ("Pause / budget", "Paused: refused. Estimated spend at or over the cap: refused (checked before the call)."), + ("Provider", "The adapter call; a permitted route with no registered adapter is refused here, never redirected."), + ("Attribution", "Reported usage × configured price, attributed to the team; written to the audit chain."), + ]; + + private static int ClassificationOrder(string c) => c.ToLowerInvariant() switch + { + "public" => 0, "internal" => 1, "pii" => 2, "phi" => 3, _ => 9, + }; + + private static string UnresolvedTitle(int n) + => n == 1 ? "1 route permitted by policy but not served by any registered adapter" + : n + " routes permitted by policy but not served by any registered adapter"; + + private string AdapterStatus(Covenant.Ui.Models.RouteView r) + { + if (State.Catalog is null) + return State.CatalogError is null ? "Checking…" : "Unknown (catalog unavailable)"; + return RouteHealth.IsRegistered(r, State.Catalog) ? "Registered" : "Not registered — refused at Provider"; + } + + protected override void OnInitialized() => State.Changed += OnChanged; + private void OnChanged() => _ = InvokeAsync(StateHasChanged); + public void Dispose() => State.Changed -= OnChanged; +} diff --git a/src/Covenant.Ui/Pages/Requests.razor b/src/Covenant.Ui/Pages/Requests.razor new file mode 100644 index 0000000..d863e3a --- /dev/null +++ b/src/Covenant.Ui/Pages/Requests.razor @@ -0,0 +1,496 @@ +@page "/requests" +@page "/requests/{Id}" +@using System.Text.Json +@using System.Text.Json.Serialization +@inject AdminApi Api +@inject AppState State +@inject RequestsViewState View +@inject NavigationManager Nav +@implements IDisposable + +Requests · Covenant + +@* + TASK 05. A recent snapshot of the CURRENT audit segment (GET /admin/requests?limit=500), filtered client-side, + labelled as such. Rows show the facts recorded at processing time only — today's pause, policy or health never + recolours them. Deep links (/requests/{id}) always fetch the exact record by correlation id. +*@ + +
+ +
+
+

Requests

+ @CoverageLabel +
+ +
+ + + + + Filters apply to the recent snapshot loaded here (newest @RequestsViewState.SnapshotLimit records of the current audit segment), not to the full audit log or archived segments. + +
+
+

Recent requests

+ @CountLabel +
+ @if (View.Snapshot is null) + { + if (_loading) + { +
+ } + } + else if (View.Snapshot.Items.Count == 0) + { +
+ } + else if (Filtered.Count == 0) + { +
+ + + +
+ } + else + { +
+ + + + + + + + + + + + + + + + + + + + + + + @foreach (var item in Filtered) + { + var r = item; + var o = OutcomeModel.FromRecord(r); + var model = ModelFacts.SelectedToServed(r); + var cost = CostText.CostShort(r); + + + + + + + + + + } + +
Time (UTC)Identity / teamOutcomeSelected → served modelDurationEst. costRequest id
@(r.TimestampUtc.UtcDateTime.ToString("MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture))@r.Principal / @r.Tags.Team@model@Fmt.Ms(r.DurationMs)@cost + +
+
+ } +
+ + + @if (_detailLoading) + { + + } + else if (_notFound) + { + + + + } + else if (_detailError is not null) + { + + } + else if (View.SelectedRecord is { } rec) + { + if (HiddenNote(rec) is { } note) + { +
@note
+ } + var o = OutcomeModel.FromRecord(rec); + var mf = ModelFacts.From(rec); + +
+

1 · Result

+
+ @o.Title +
+ @o.Explanation + Recorded when the request was processed. Today’s pause, policy or model health does not change this result. +
+ +
+

2 · Request, identity and routing

+
+
Request id
@rec.Id
+
Time
@Fmt.Utc(rec.TimestampUtc)
+
Identity
@Fmt.OrNotRecorded(rec.Principal)
+
Team
@Fmt.OrNotRecorded(rec.Tags.Team)
+
Workflow / use case
@Fmt.OrNotRecorded(rec.Tags.Workflow) · @Fmt.OrNotRecorded(rec.Tags.UseCase)
+
Selected model
@mf.Selected
+
Provider attempted
@mf.Attempted
+
Served model
@mf.Served
+
Streamed
@(rec.Stream is { } st ? (st ? "Yes" : "No") : "Not recorded")
+
Stopped at
@StoppedText(rec)
+
Recorded reason
@Fmt.OrNotRecorded(rec.Reason)
+
+
+ +
+

3 · Classification

+ @mf.Classification + @if (rec.ClassificationEvaluated == false) + { + The pipeline starts from the restrictive default (@rec.Classification) for enforcement. It is not a detection: the classifier never ran for this request. + } + else if (rec.ClassificationEvaluated is null) + { + Legacy record: whether classification ran was not recorded. Stored class: @Fmt.OrNotRecorded(rec.Classification)@(rec.Signal is { Length: > 0 } sg ? " · signal " + sg : ""). + } +
+ +
+

4 · Usage, estimated cost and timing

+
+
Tokens
@CostText.Tokens(rec)
+
Estimated cost
@CostText.Cost(rec)
+
Cost basis
@CostText.BasisDescription(rec.CostBasis)
+
Cache
@(rec.CacheHit ? "Hit — response reused, no provider call" : "Not served from cache")
+
Duration
@Fmt.Ms(rec.DurationMs) (recorded by Covenant)
+
+
+ +
+

5 · Audit evidence

+
+
Prompt SHA-256
@Fmt.OrNotRecorded(rec.PromptSha256)
+
Prompt length
@rec.PromptChars chars
+
Matched signal
@(rec.Signal is { Length: > 0 } sig ? sig : rec.ClassificationEvaluated == true ? "None" : "Not evaluated or not recorded")
+
Schema version
@(rec.SchemaVersion?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "1 (legacy)")
+
+ @if (rec.PromptPreview is { } preview) + { + Prompt preview +
@preview
+ Preview retained because Audit:PromptPreviewChars > 0 when this record was written. + } + else + { + No prompt content is retained in this record — only its fingerprint and length. + } + Response text is never audit evidence; the Playground shows it only to the operator who sent the request. +
+ Raw audit record (JSON) +
@RawJson(rec)
+
+
+ } +
+
+
+ +@code { + [Parameter] public string? Id { get; set; } + + private static readonly UiJsonContext Indented = new(new JsonSerializerOptions + { + WriteIndented = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }); + + private bool _loading; + private string? _loadError; + private bool _detailLoading; + private string? _detailError; + private bool _notFound; + private string? _paramId; + + private IReadOnlyList Items => View.Snapshot?.Items ?? []; + private IReadOnlyList Filtered => RequestFilter.Apply(Items, View.Criteria, DateTimeOffset.UtcNow); + + private IReadOnlyList OutcomeOptions + { + get + { + var list = RequestFilter.Outcomes(Items).ToList(); + if (View.Criteria.Outcome is { } sel && !list.Contains(sel)) list.Add(sel); + return list; + } + } + + private IReadOnlyList ModelOptions => WithSelected(RequestFilter.Models(Items), View.Criteria.Model); + private IReadOnlyList TeamOptions => WithSelected(RequestFilter.Teams(Items), View.Criteria.Team); + + private bool DrawerOpen => Id is not null; + + private string DrawerTitle => Id is null ? "Request" : "Request " + Truncate(Id); + + private string CoverageLabel + { + get + { + if (View.Snapshot is not { } snap) return "Recent requests — current audit segment; not a full audit history search"; + var since = snap.Segment.FirstUtc is { } f ? Fmt.Utc(f) : "(no records yet)"; + return $"Recent requests — current audit segment since {since} ({Fmt.Int(snap.Segment.Entries)} records); not a full audit history search"; + } + } + + private string CountLabel + { + get + { + if (View.Snapshot is not { } snap) return ""; + var loaded = snap.Items.Count; + var shown = Filtered.Count; + var loadedAt = View.LoadedUtc is { } t ? " · loaded " + Fmt.UtcShort(t) + " UTC" : ""; + var cap = snap.Segment.Entries > loaded ? $" (newest {Fmt.Int(loaded)} of {Fmt.Int(snap.Segment.Entries)})" : ""; + return $"Showing {Fmt.Int(shown)} of {Fmt.Int(loaded)} loaded{cap}{loadedAt}"; + } + } + + protected override async Task OnInitializedAsync() + { + State.Changed += OnStateChanged; + if (State.Connected && View.Snapshot is null) await LoadAsync(); + } + + protected override async Task OnParametersSetAsync() + { + if (string.Equals(Id, _paramId, StringComparison.Ordinal)) return; + _paramId = Id; + _notFound = false; + _detailError = null; + if (Id is null) + { + View.SelectedId = null; + View.SelectedRecord = null; + return; + } + View.SelectedId = Id; + await EnsureDetailAsync(); + } + + private void OnStateChanged() + { + _ = InvokeAsync(async () => + { + if (State.Connected) + { + if (View.Snapshot is null && !_loading && _loadError is null) await LoadAsync(); + if (Id is not null && View.SelectedRecord is null && !_detailLoading && !_notFound && _detailError is null) + await EnsureDetailAsync(); + } + StateHasChanged(); + }); + } + + private async Task LoadAsync() + { + if (!State.Connected || _loading) return; + _loading = true; + _loadError = null; + StateHasChanged(); + try + { + View.Snapshot = await Api.GetRequestsAsync(RequestsViewState.SnapshotLimit); + View.LoadedUtc = DateTimeOffset.UtcNow; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // ConsoleSession disconnects and routes to /connect. + } + catch (Exception ex) + { + _loadError = ex.Message; + } + finally + { + _loading = false; + } + } + + /// Deep link / selection: always the exact record for this id, even if the filters exclude it. + private async Task EnsureDetailAsync() + { + if (Id is not { } id || !State.Connected) return; + if (View.SelectedRecord is { } have && string.Equals(have.Id, id, StringComparison.Ordinal)) return; + _detailLoading = true; + _notFound = false; + _detailError = null; + View.SelectedRecord = null; + try + { + var rec = await Api.GetRequestAsync(id); + if (string.Equals(Id, id, StringComparison.Ordinal)) View.SelectedRecord = rec; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.NotFound) + { + _notFound = true; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.BadRequest) + { + _detailError = "Not a valid request id (expected req_ followed by letters, digits, '-' or '_')."; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // handled by ConsoleSession + } + catch (Exception ex) + { + _detailError = ex.Message; + } + finally + { + _detailLoading = false; + } + } + + private async Task RetryDetailAsync() + { + _notFound = false; + _detailError = null; + View.SelectedRecord = null; + await EnsureDetailAsync(); + } + + private void Open(AuditEntryView r) + { + View.SelectedId = r.Id; + View.SelectedRecord = r; + Nav.NavigateTo("requests/" + Uri.EscapeDataString(r.Id)); + } + + private void OnDrawerOpenChanged(bool open) + { + if (open) return; + Nav.NavigateTo("requests"); + } + + private string? HiddenNote(AuditEntryView rec) + { + if (View.Snapshot is null) return null; + bool inSnapshot = Items.Any(i => string.Equals(i.Id, rec.Id, StringComparison.Ordinal)); + if (!inSnapshot) + return "This request is not in the loaded recent list (it is newer than the snapshot, or older than the newest " + + RequestsViewState.SnapshotLimit + " records). Shown from an exact lookup by id."; + if (!RequestFilter.Matches(rec, View.Criteria, DateTimeOffset.UtcNow)) + return "This request is hidden by the current filters. It is shown because it was opened by id."; + return null; + } + + private static string StoppedText(AuditEntryView r) + { + if (r.StoppedAtStage is { } s) return PipelineStages.Label(s); + if (string.Equals(r.Effect, "Allow", StringComparison.OrdinalIgnoreCase)) return "Completed — no stage stopped it"; + return ModelFacts.IsV2(r) ? "Not recorded" : "Not recorded (legacy record)"; + } + + private static string RawJson(AuditEntryView r) => JsonSerializer.Serialize(r, Indented.AuditEntryView); + + private static string RowId(string id) => "req-row-" + id; + + private static string Truncate(string id) => id.Length <= 16 ? id : id[..12] + "…" + id[^4..]; + + private static IReadOnlyList WithSelected(IReadOnlyList options, string? selected) + { + if (string.IsNullOrWhiteSpace(selected) || options.Contains(selected, StringComparer.OrdinalIgnoreCase)) return options; + return [.. options, selected]; + } + + // ---- Filter handlers: the criteria record is immutable; each change replaces it. ---- + + private void OnIdSearch(ChangeEventArgs e) + => View.Criteria = View.Criteria with { IdSearch = e.Value?.ToString() }; + + private void OnOutcome(ChangeEventArgs e) + => View.Criteria = View.Criteria with + { + Outcome = Enum.TryParse(e.Value?.ToString(), out var o) ? o : null, + }; + + private void OnModel(ChangeEventArgs e) + => View.Criteria = View.Criteria with { Model = Blank(e.Value?.ToString()) }; + + private void OnTeam(ChangeEventArgs e) + => View.Criteria = View.Criteria with { Team = Blank(e.Value?.ToString()) }; + + private void OnWindow(ChangeEventArgs e) + => View.Criteria = View.Criteria with + { + Window = Enum.TryParse(e.Value?.ToString(), out var w) ? w : TimeWindow.All, + }; + + private void ClearFilters() => View.Criteria = RequestFilterCriteria.None; + + private static string? Blank(string? s) => string.IsNullOrWhiteSpace(s) ? null : s; + + public void Dispose() => State.Changed -= OnStateChanged; +} diff --git a/src/Covenant.Ui/Pages/Settings.razor b/src/Covenant.Ui/Pages/Settings.razor new file mode 100644 index 0000000..ccf9395 --- /dev/null +++ b/src/Covenant.Ui/Pages/Settings.razor @@ -0,0 +1,213 @@ +@page "/settings" +@inject AppState State +@inject AdminApi Api +@inject ConsoleSession Session +@inject NavigationManager Nav +@implements IDisposable + +Settings · Covenant + +
+ + @if (State.LastStatus is not { } s) + { + + } + else + { +
+
+

Settings

+ Values in effect since the last start (@Fmt.Utc(s.StartedUtc)). Change them in configuration and restart — there is nothing to save here. +
+
+ +
+
+

Environment and configuration

+ Managed by configuration; restart required +
+
+ + + @foreach (var row in Rows(s)) + { + + + + + } + +
@row.Key +
+ @row.Value + @if (row.Note is not null) + { + @row.Note + } +
+
+
+
+ +
+
+

This console session

+ Connected with the shared admin token, kept in this tab’s session storage. It administers the console only and never sends model requests. Disconnecting does not pause Covenant. +
+ +
+ +
+
+ +
+
+

Maintenance

+ Separate from day-to-day settings. Not a way to start a demo, and not a fix for an exhausted budget. +
+
+ Archive audit segment and reset spend accounting +
    +
  • The current audit segment is closed and archived with a timestamp. Nothing is deleted; the archive stays independently verifiable.
  • +
  • Spend counters reset to $0. Any reached budget reopens because accounting restarts, not because spend went away.
  • +
  • Overview, Budgets and Requests then show only the new segment.
  • +
+
+ + @if (_resetError is not null) + { + + } + @if (_resetResult is { } done) + { +
+
+ Segment archived · accounting reset + + @(done.ArchivedTo is { Length: > 0 } ? "Archived to " : "Nothing to archive (the segment was empty); ") + @if (done.ArchivedTo is { Length: > 0 }) + { + @done.ArchivedTo. + } + A new segment has started. + +
+ View in Evidence +
+ } + + @if (!s.ChainValid) + { + + } + else + { +
+ +
+ } +
+ + +

This will archive the current audit segment (@Fmt.Int(s.AuditEntries) entries, since @SegmentStart(s)) and reset spend counters (@Fmt.Usd(s.Budget.GlobalSpendUsd) recorded against a @Fmt.UsdTotal(s.Budget.GlobalCapUsd) cap) — budgets reopen. The archived segment is kept and stays verifiable. Nothing is deleted.

+ @if (State.Paused) + { +

New provider calls are currently paused; resetting accounting does not resume them.

+ } +
+ + +
+
+ + +
+
+ } +
+
+ +@code { + private sealed record Row(string Key, string Value, string? Note = null, bool Mono = false); + + private bool _confirmOpen; + private string _typed = ""; + private bool _resetting; + private string? _resetError; + private ResetResponse? _resetResult; + + private bool CanConfirm => !_resetting && string.Equals(_typed.Trim(), State.EnvironmentLabel, StringComparison.Ordinal); + + protected override void OnInitialized() => State.Changed += OnChanged; + + private static string NotReported => "Not reported by this Host"; + + private static List Rows(StatusReport s) => + [ + new("Environment", s.Environment ?? NotReported, "Shown in the header and in every confirmation", true), + new("Provider mode", s.Mode ?? NotReported, "Providers:Mode — cloud or local-only (ADR-0010)", true), + new("Covenant version", s.Version ?? NotReported, null, true), + new("Started", Fmt.Utc(s.StartedUtc), "Configuration is read once at start", true), + new("Audit log path", s.AuditPath ?? NotReported, "Audit:Path — the current segment; archives sit beside it", true), + new("Anchor", AnchorText(s), "Audit:AnchorPath / Audit:AnchorEvery — see Evidence for coverage"), + new("Cache TTL", s.CacheTtlSeconds is { } ttl ? (ttl == 0 ? "Disabled" : Fmt.Int(ttl) + " s") : NotReported, "Cache:TtlSeconds — identical governed requests are answered without a provider call", true), + new("Content-preview retention", s.PromptPreviewChars is { } pc ? (pc == 0 ? "No prompt preview stored" : Fmt.Int(pc) + " characters of each prompt") : NotReported, "Audit:PromptPreviewChars — the only prompt content the audit record holds", true), + new("Telemetry (OpenTelemetry)", s.OtelEnabled ? "Enabled — exporting to the configured in-perimeter collector" : "Disabled", "Otel:Endpoint; active only when configured (ADR-0003)"), + new("Routing threshold", Fmt.Int(s.RoutingThresholdTokens) + " estimated tokens", "Routing:ComplexityThresholdTokens — below: cheapest permitted route; above: escalate", true), + new("Application keys", Fmt.Int(s.Auth.KeyCount) + (s.Auth.KeyCount == 1 ? " key" : " keys") + (s.Auth.AllowAnonymous ? " · anonymous requests ALLOWED" : " · anonymous requests refused"), "Auth:Keys — count only; key values never leave the configuration", true), + new("Global budget cap", Fmt.UsdTotal(s.Budget.GlobalCapUsd), "Budget:GlobalCapUsd — team caps are listed under Budgets", true), + ]; + + private static string AnchorText(StatusReport s) => s.Anchor switch + { + null => NotReported, + { Configured: false } => "Not configured", + { Configured: true, Every: { } every } => $"Configured · every {Fmt.Int(every)} entries", + _ => "Configured", + }; + + private static string SegmentStart(StatusReport s) + => s.FinOps.Activity.Count > 0 ? Fmt.Utc(s.FinOps.Activity[0].T) : "start of segment (no entries yet)"; + + private IReadOnlyList SessionFacts() => + [ + new("Credential", "Shared admin token (X-Covenant-Admin-Token)", true), + new("Stored in", "This tab’s sessionStorage only; cleared on disconnect or when the tab closes"), + new("Status feed", State.FeedMode switch { FeedMode.Stream => "Live stream (/admin/status/stream)", FeedMode.Polling => "Polling every 3 s (stream unavailable)", _ => "Not running" }, true), + new("Application key", State.ApplicationKey is null ? "None held" : "Held in memory for the Playground; never persisted"), + new("Theme", "Stored in localStorage (the only value this console persists there)"), + ]; + + private async Task ResetAsync() + { + if (!CanConfirm) return; + _resetting = true; _resetError = null; _resetResult = null; + try + { + _resetResult = await Api.ResetAsync(); + _confirmOpen = false; + } + catch (Exception ex) + { + _resetError = ex.Message; + _confirmOpen = false; + } + finally + { + _resetting = false; + _typed = ""; + } + // Never assume the outcome: re-sync the counters from the server either way. + await Session.TryRefreshAsync(); + } + + private async Task DisconnectAsync() + { + await Session.DisconnectAsync("Disconnected"); + Nav.NavigateTo("connect"); + } + + private void OnChanged() => _ = InvokeAsync(StateHasChanged); + public void Dispose() => State.Changed -= OnChanged; +} diff --git a/src/Covenant.Ui/Program.cs b/src/Covenant.Ui/Program.cs new file mode 100644 index 0000000..118f3af --- /dev/null +++ b/src/Covenant.Ui/Program.cs @@ -0,0 +1,29 @@ +using Covenant.Ui; +using Covenant.Ui.Services; +using Microsoft.AspNetCore.Components.Web; +using Microsoft.AspNetCore.Components.WebAssembly.Hosting; + +var builder = WebAssemblyHostBuilder.CreateDefault(args); +builder.RootComponents.Add("#app"); +builder.RootComponents.Add("head::after"); + +// The console is served from /ui/ but talks to the Host's root (/admin/*), so the HttpClient is rooted at the +// origin, never at the base href. Same origin only — CSP connect-src 'self' enforces it in the browser too. +var origin = new Uri(new Uri(builder.HostEnvironment.BaseAddress).GetLeftPart(UriPartial.Authority)); +builder.Services.AddScoped(_ => new HttpClient { BaseAddress = origin }); + +// In Blazor WebAssembly a scoped service lives for the page: these are the console's singletons. +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +// Governed inference uses its OWN HttpClient (same origin) so the admin client's headers can never leak into +// an application call, and vice versa. Only the application key is ever attached here. +builder.Services.AddScoped(sp => new InferenceApi(new HttpClient { BaseAddress = origin, Timeout = TimeSpan.FromMinutes(5) }, sp.GetRequiredService())); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +await builder.Build().RunAsync(); diff --git a/src/Covenant.Ui/Services/AdminApi.cs b/src/Covenant.Ui/Services/AdminApi.cs new file mode 100644 index 0000000..afca2d0 --- /dev/null +++ b/src/Covenant.Ui/Services/AdminApi.cs @@ -0,0 +1,141 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Services; + +/// A failed admin call, with the HTTP status and the server's reason when it sent one. The message is +/// safe to render: it never includes the token or the request body. +public sealed class ApiException(HttpStatusCode? status, string message) : Exception(message) +{ + public HttpStatusCode? Status { get; } = status; +} + +/// Typed client for /admin/*. Every call carries X-Covenant-Admin-Token from AppState; a 401 raises +/// Unauthorized (ConsoleSession then disconnects and routes to /connect with "Token rejected") and throws. +/// Admin and application credentials are never mixed: this class knows nothing about application keys. +public sealed class AdminApi(HttpClient http, AppState state) +{ + public const string TokenHeader = "X-Covenant-Admin-Token"; + + public event Action? Unauthorized; + + public Task GetStatusAsync(CancellationToken ct = default) + => GetAsync("/admin/status", UiJsonContext.Default.StatusReport, ct); + + public Task GetEvidenceAsync(CancellationToken ct = default) + => GetAsync("/admin/evidence", UiJsonContext.Default.EvidenceReport, ct); + + public Task GetRequestsAsync(int limit = 200, CancellationToken ct = default) + => GetAsync($"/admin/requests?limit={limit}", UiJsonContext.Default.RequestsResponse, ct); + + public Task GetRequestAsync(string id, CancellationToken ct = default) + => GetAsync("/admin/requests/" + Uri.EscapeDataString(id), UiJsonContext.Default.AuditEntryView, ct); + + public Task GetCatalogAsync(CancellationToken ct = default) + => GetAsync("/admin/catalog", UiJsonContext.Default.CatalogResponse, ct); + + public Task SetKillSwitchAsync(bool engaged, string? reason, CancellationToken ct = default) + => PostAsync("/admin/kill-switch", new KillSwitchRequest { Engaged = engaged, Reason = reason }, + UiJsonContext.Default.KillSwitchRequest, UiJsonContext.Default.KillSwitchState, ct); + + public Task ResetAsync(CancellationToken ct = default) + => PostAsync("/admin/reset", null, null, UiJsonContext.Default.ResetResponse, ct); + + public Task ProbeAsync(string endpoint, CancellationToken ct = default) + => PostAsync("/admin/providers/probe", new ProbeRequest { Endpoint = endpoint }, + UiJsonContext.Default.ProbeRequest, UiJsonContext.Default.ProbeResponse, ct); + + /// Raw GET returning the body text — used by Evidence export so the downloaded file is byte-for-byte + /// what the server produced, not a re-serialization. + public async Task GetEvidenceJsonAsync(CancellationToken ct = default) + { + using var request = NewRequest(HttpMethod.Get, "/admin/evidence"); + using var response = await http.SendAsync(request, ct); + await EnsureSuccessAsync(response, ct); + return await response.Content.ReadAsStringAsync(ct); + } + + /// Opens the SSE status stream. The caller owns the response and reads lines from it. + public async Task OpenStatusStreamAsync(CancellationToken ct) + { + var request = NewRequest(HttpMethod.Get, "/admin/status/stream"); + request.Headers.Accept.ParseAdd("text/event-stream"); + Microsoft.AspNetCore.Components.WebAssembly.Http.WebAssemblyHttpRequestMessageExtensions + .SetBrowserResponseStreamingEnabled(request, true); + var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct); + try + { + await EnsureSuccessAsync(response, ct); + } + catch + { + response.Dispose(); + throw; + } + return response; + } + + public HttpRequestMessage NewRequest(HttpMethod method, string path) + { + var request = new HttpRequestMessage(method, path); + if (state.AdminToken is { Length: > 0 } token) + request.Headers.TryAddWithoutValidation(TokenHeader, token); + return request; + } + + private async Task GetAsync(string path, System.Text.Json.Serialization.Metadata.JsonTypeInfo typeInfo, CancellationToken ct) + { + using var request = NewRequest(HttpMethod.Get, path); + using var response = await http.SendAsync(request, ct); + await EnsureSuccessAsync(response, ct); + var body = await response.Content.ReadFromJsonAsync(typeInfo, ct); + return body ?? throw new ApiException(response.StatusCode, "Empty response from " + path); + } + + private async Task PostAsync( + string path, TIn? body, + System.Text.Json.Serialization.Metadata.JsonTypeInfo? inType, + System.Text.Json.Serialization.Metadata.JsonTypeInfo outType, + CancellationToken ct) + { + using var request = NewRequest(HttpMethod.Post, path); + if (body is not null && inType is not null) + request.Content = JsonContent.Create(body, inType); + else + request.Content = new StringContent("{}", System.Text.Encoding.UTF8, "application/json"); + using var response = await http.SendAsync(request, ct); + await EnsureSuccessAsync(response, ct); + var result = await response.Content.ReadFromJsonAsync(outType, ct); + return result ?? throw new ApiException(response.StatusCode, "Empty response from " + path); + } + + private async Task EnsureSuccessAsync(HttpResponseMessage response, CancellationToken ct) + { + if (response.IsSuccessStatusCode) return; + + if (response.StatusCode == HttpStatusCode.Unauthorized) + { + Unauthorized?.Invoke(); + throw new ApiException(response.StatusCode, "Token rejected"); + } + + string? reason = null; + try + { + var text = await response.Content.ReadAsStringAsync(ct); + if (text.Length > 0) + { + var err = JsonSerializer.Deserialize(text, UiJsonContext.Default.ErrorResponse); + reason = err?.Reason ?? err?.Error; + if (err?.Error == "not_found" && err.Scanned is { } scanned) + reason = $"not found (scanned {scanned} records)"; + } + } + catch (JsonException) { /* non-JSON error body: fall through to the status line */ } + + throw new ApiException(response.StatusCode, + reason is { Length: > 0 } ? $"{(int)response.StatusCode}: {reason}" : $"HTTP {(int)response.StatusCode} {response.ReasonPhrase}"); + } +} diff --git a/src/Covenant.Ui/Services/AppState.cs b/src/Covenant.Ui/Services/AppState.cs new file mode 100644 index 0000000..a06f9ac --- /dev/null +++ b/src/Covenant.Ui/Services/AppState.cs @@ -0,0 +1,154 @@ +using Covenant.Ui.Models; + +namespace Covenant.Ui.Services; + +public enum FeedMode { None, Stream, Polling } + +/// The one place the console keeps state across navigation: connection, the last status snapshot and +/// its freshness, pause state, and the two credentials — which are handled differently on purpose. +/// The admin token is mirrored to tab-scoped sessionStorage by ConsoleSession; the application key exists +/// ONLY in this object's memory: never persisted, never logged, cleared on disconnect. +/// Pure state: no HTTP, no JS. Raises Changed; components re-render via InvokeAsync(StateHasChanged). +public sealed class AppState +{ + public static readonly TimeSpan StaleAfter = TimeSpan.FromSeconds(8); + + public event Action? Changed; + + /// Raised by before Changed. Session-bound services (PlaygroundState, + /// RequestsViewState, CatalogState) subscribe and drop everything they hold: prompts, responses, + /// selections, the catalog. Nothing of that is ever persisted, so reload clears it too. + public event Action? Disconnected; + + public string? AdminToken { get; private set; } + public bool Connected { get; private set; } + + /// True until the startup check of sessionStorage has finished; pages show a skeleton instead of + /// flashing "not connected" at a user who is about to be reconnected. + public bool Restoring { get; private set; } = true; + + public void RestoreComplete() + { + if (!Restoring) return; + Restoring = false; + Notify(); + } + + public StatusReport? LastStatus { get; private set; } + public DateTimeOffset? LastUpdatedUtc { get; private set; } + public bool IsStale { get; private set; } + + public FeedMode FeedMode { get; private set; } + /// Human-readable feed problem ("Connection lost — retrying"), null while healthy. + public string? FeedError { get; private set; } + + public CatalogResponse? Catalog { get; private set; } + public DateTimeOffset? CatalogUpdatedUtc { get; private set; } + public string? CatalogError { get; private set; } + + /// Why the user is on /connect (e.g. "Token rejected", "Disconnected"); cleared on connect. + public string? ConnectMessage { get; private set; } + + /// Application key for the Playground — in memory only (see class remarks). + public string? ApplicationKey { get; private set; } + + public bool Paused => LastStatus?.KillSwitch.Engaged == true; + public string? PauseReason => LastStatus?.KillSwitch.Reason; + public string? Environment => LastStatus?.Environment; + public string EnvironmentLabel => string.IsNullOrWhiteSpace(Environment) ? "Environment not reported" : Environment; + + public void SetToken(string token) + { + AdminToken = token; + Notify(); + } + + public void Connect(StatusReport status) + { + Connected = true; + ConnectMessage = null; + FeedError = null; + ApplyStatus(status); + } + + public void ApplyStatus(StatusReport status) + { + LastStatus = status; + LastUpdatedUtc = DateTimeOffset.UtcNow; + IsStale = false; + FeedError = null; + Notify(); + } + + public void SetFeedMode(FeedMode mode) + { + if (FeedMode == mode) return; + FeedMode = mode; + Notify(); + } + + public void MarkFeedFailure(string message) + { + FeedError = message; + IsStale = true; + Notify(); + } + + public void SetCatalog(CatalogResponse catalog) + { + Catalog = catalog; + CatalogUpdatedUtc = DateTimeOffset.UtcNow; + CatalogError = null; + Notify(); + } + + public void SetCatalogError(string message) + { + CatalogError = message; + Notify(); + } + + public void SetApplicationKey(string? key) + { + ApplicationKey = string.IsNullOrWhiteSpace(key) ? null : key; + Notify(); + } + + /// Called once a second by the feed; flips IsStale when the last snapshot ages past StaleAfter. + /// Only notifies on a change so the shell does not re-render every tick for nothing. + public void Tick(DateTimeOffset nowUtc) + { + if (!Connected) return; + var stale = LastUpdatedUtc is null || nowUtc - LastUpdatedUtc.Value > StaleAfter; + if (stale != IsStale) + { + IsStale = stale; + Notify(); + } + } + + /// Forgets everything that belongs to this connection. Does NOT touch the kill switch: + /// disconnecting the console never pauses Covenant. + public void Disconnect(string? message) + { + AdminToken = null; + ApplicationKey = null; + Connected = false; + LastStatus = null; + LastUpdatedUtc = null; + IsStale = false; + FeedMode = FeedMode.None; + FeedError = null; + Catalog = null; + CatalogUpdatedUtc = null; + CatalogError = null; + ConnectMessage = message; + Disconnected?.Invoke(); + Notify(); + } + + public int SecondsSinceUpdate(DateTimeOffset nowUtc) + => LastUpdatedUtc is null ? -1 : (int)Math.Max(0, (nowUtc - LastUpdatedUtc.Value).TotalSeconds); + + private void Notify() => Changed?.Invoke(); +} diff --git a/src/Covenant.Ui/Services/CatalogState.cs b/src/Covenant.Ui/Services/CatalogState.cs new file mode 100644 index 0000000..3d7380e --- /dev/null +++ b/src/Covenant.Ui/Services/CatalogState.cs @@ -0,0 +1,73 @@ +namespace Covenant.Ui.Services; + +/// Keeps the shared provider catalog (AppState.Catalog) fresh: loaded on connect by ConsoleSession, +/// refreshed every 30 s while connected and on demand after a governed test — so the header, Overview and +/// Models & connections all show the same observed health. A later failure supersedes an earlier success +/// (the server keeps last_success_utc). Stops and forgets on disconnect. +public sealed class CatalogState : IDisposable +{ + public static readonly TimeSpan RefreshInterval = TimeSpan.FromSeconds(30); + + private readonly AppState _state; + private readonly ConsoleSession _session; + private CancellationTokenSource? _loop; + + public CatalogState(AppState state, ConsoleSession session) + { + _state = state; + _session = session; + _state.Changed += OnChanged; + _state.Disconnected += StopLoop; + OnChanged(); + } + + public bool Refreshing { get; private set; } + + public async Task RefreshAsync() + { + if (!_state.Connected || Refreshing) return; + Refreshing = true; + try { await _session.LoadCatalogAsync(); } + finally { Refreshing = false; } + } + + private void OnChanged() + { + if (_state.Connected && _loop is null) + { + _loop = new CancellationTokenSource(); + _ = LoopAsync(_loop.Token); + } + else if (!_state.Connected && _loop is not null) + { + StopLoop(); + } + } + + private async Task LoopAsync(CancellationToken ct) + { + try + { + using var timer = new PeriodicTimer(RefreshInterval); + while (await timer.WaitForNextTickAsync(ct)) + await RefreshAsync(); + } + catch (OperationCanceledException) { /* stopped */ } + } + + private void StopLoop() + { + var cts = _loop; + _loop = null; + if (cts is null) return; + cts.Cancel(); + cts.Dispose(); + } + + public void Dispose() + { + _state.Changed -= OnChanged; + _state.Disconnected -= StopLoop; + StopLoop(); + } +} diff --git a/src/Covenant.Ui/Services/ConsoleSession.cs b/src/Covenant.Ui/Services/ConsoleSession.cs new file mode 100644 index 0000000..593aa78 --- /dev/null +++ b/src/Covenant.Ui/Services/ConsoleSession.cs @@ -0,0 +1,168 @@ +using Covenant.Ui.Models; +using Microsoft.AspNetCore.Components; + +namespace Covenant.Ui.Services; + +/// Connect / disconnect / restore for the console session. Owns the only two side effects of a +/// connection — mirroring the admin token to tab-scoped sessionStorage and running the status feed — and the +/// 401 handling that every page relies on: the token is dropped, the feed stops, and the user lands on +/// /connect with "Token rejected". Disconnecting never calls the kill switch. +public sealed class ConsoleSession : IDisposable +{ + public const string TokenStorageKey = "covenant.admin-token"; + + private readonly AppState _state; + private readonly AdminApi _api; + private readonly StatusFeed _feed; + private readonly Interop _interop; + private readonly NavigationManager _nav; + private bool _restored; + + public ConsoleSession(AppState state, AdminApi api, StatusFeed feed, Interop interop, NavigationManager nav) + { + _state = state; + _api = api; + _feed = feed; + _interop = interop; + _nav = nav; + _api.Unauthorized += OnUnauthorized; + } + + /// At startup: if this tab still holds a token, validate it against GET /admin/status and resume. + /// A rejected token is removed so the console cannot sit on a page looking authenticated. + public async Task RestoreAsync() + { + if (_restored) return; + _restored = true; + try + { + string? token; + try { token = await _interop.SessionGetAsync(TokenStorageKey); } + catch (Exception) { token = null; } + if (string.IsNullOrWhiteSpace(token)) return; + + _state.SetToken(token); + try + { + var status = await _api.GetStatusAsync(); + _state.Connect(status); + _feed.Start(); + _ = LoadCatalogAsync(); + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // OnUnauthorized already disconnected and routed; nothing else to do. + } + catch (Exception ex) + { + // Host unreachable right now: keep the token (the tab is still ours) but show the honest state. + _state.Disconnect("Connection lost — " + ex.Message); + _state.SetToken(token); + } + } + finally + { + _state.RestoreComplete(); + } + } + + /// Validates the token with GET /admin/status. On success the token is kept for this tab and the + /// feed starts. Throws ApiException("Token rejected") on 401; other failures throw with the reason. + public async Task ConnectAsync(string token) + { + _state.SetToken(token); + StatusReport status; + try + { + status = await _api.GetStatusAsync(); + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + throw; // state already cleared by OnUnauthorized + } + catch (Exception) + { + _state.Disconnect(null); + throw; + } + + try { await _interop.SessionSetAsync(TokenStorageKey, token); } + catch (Exception) { /* storage unavailable: the session still works for this page load */ } + + _state.Connect(status); + _feed.Start(); + _ = LoadCatalogAsync(); + } + + /// Clears the token (memory + sessionStorage) and the in-memory application key, stops the feed. + /// Nothing is sent to the Host — in particular the kill switch is untouched. + public async Task DisconnectAsync(string? message = "Disconnected") + { + _feed.Stop(); + _state.Disconnect(message); + try { await _interop.SessionRemoveAsync(TokenStorageKey); } + catch (Exception) { /* nothing to remove */ } + } + + public async Task LoadCatalogAsync() + { + if (!_state.Connected) return; + try + { + var catalog = await _api.GetCatalogAsync(); + _state.SetCatalog(catalog); + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.NotFound) + { + _state.SetCatalogError("Catalog endpoint not available on this Host"); + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // handled by OnUnauthorized + } + catch (Exception ex) + { + _state.SetCatalogError(ex.Message); + } + } + + /// Pause/resume via POST /admin/kill-switch, then re-sync from the server. Returns the error text + /// to show, or null on success; the caller never assumes success from the absence of an exception alone — + /// the refreshed status is what the shell renders. + public async Task SetPausedAsync(bool paused, string? reason) + { + try + { + await _api.SetKillSwitchAsync(paused, reason); + } + catch (Exception ex) + { + await TryRefreshAsync(); + return ex.Message; + } + await TryRefreshAsync(); + return null; + } + + public async Task TryRefreshAsync() + { + try { await _feed.RefreshNowAsync(); } + catch (Exception ex) { _state.MarkFeedFailure("Could not refresh status — " + ex.Message); } + } + + private void OnUnauthorized() + { + _feed.Stop(); + _state.Disconnect("Token rejected"); + _ = RemoveStoredTokenAsync(); + _nav.NavigateTo("connect"); + } + + private async Task RemoveStoredTokenAsync() + { + try { await _interop.SessionRemoveAsync(TokenStorageKey); } + catch (Exception) { /* best effort */ } + } + + public void Dispose() => _api.Unauthorized -= OnUnauthorized; +} diff --git a/src/Covenant.Ui/Services/EvidenceTracker.cs b/src/Covenant.Ui/Services/EvidenceTracker.cs new file mode 100644 index 0000000..69a0317 --- /dev/null +++ b/src/Covenant.Ui/Services/EvidenceTracker.cs @@ -0,0 +1,67 @@ +using System.Net; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Services; + +public enum EvidenceState { Idle, Pending, Found, Unavailable, Error } + +/// Lookup state for one request's audit record. Never claims the audit write failed: a bounded +/// lookup that finds nothing reports "not in the current audit segment yet". +public sealed record EvidenceStatus(EvidenceState State, AuditEntryView? Record = null, string? Message = null, int Attempts = 0) +{ + public static readonly EvidenceStatus Idle = new(EvidenceState.Idle); +} + +/// Polls GET /admin/requests/{id} (admin token, via AdminApi) after a governed request. The audit sink +/// is asynchronous, so 404 means "pending" for a bounded time (≈15 s), then "unavailable — retry". +public sealed class EvidenceTracker(AdminApi api, AppState state) +{ + public const string UnavailableMessage = "Not in the current audit segment yet — retry."; + + /// Waits before each attempt, in seconds (sum ≈ 14 s). + public static readonly double[] RetryDelaysSeconds = [0.5, 1, 1.5, 2, 3, 3, 3]; + + public async Task TrackAsync(string id, Action? progress, CancellationToken ct) + { + int attempts = 0; + foreach (var delay in RetryDelaysSeconds) + { + progress?.Invoke(new EvidenceStatus(EvidenceState.Pending, Attempts: attempts)); + try { await Task.Delay(TimeSpan.FromSeconds(delay), ct); } + catch (OperationCanceledException) { return new EvidenceStatus(EvidenceState.Idle, Attempts: attempts); } + + attempts++; + var r = await LookupOnceAsync(id, ct); + if (r.State != EvidenceState.Pending) return r with { Attempts = attempts }; + } + return new EvidenceStatus(EvidenceState.Unavailable, Message: UnavailableMessage, Attempts: attempts); + } + + /// One lookup. 404 → Pending (caller decides whether to keep waiting). + public async Task LookupOnceAsync(string id, CancellationToken ct) + { + if (!state.Connected) + return new EvidenceStatus(EvidenceState.Error, Message: "Connect the console (admin token) to look up evidence."); + try + { + var record = await api.GetRequestAsync(id, ct); + return new EvidenceStatus(EvidenceState.Found, record); + } + catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) + { + return new EvidenceStatus(EvidenceState.Pending); + } + catch (ApiException ex) when (ex.Status == HttpStatusCode.Unauthorized) + { + return new EvidenceStatus(EvidenceState.Error, Message: "Admin token rejected — reconnect to look up evidence."); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return new EvidenceStatus(EvidenceState.Idle); + } + catch (Exception ex) + { + return new EvidenceStatus(EvidenceState.Error, Message: "Evidence lookup failed: " + ex.Message); + } + } +} diff --git a/src/Covenant.Ui/Services/Fmt.cs b/src/Covenant.Ui/Services/Fmt.cs new file mode 100644 index 0000000..81a94e7 --- /dev/null +++ b/src/Covenant.Ui/Services/Fmt.cs @@ -0,0 +1,53 @@ +using System.Globalization; + +namespace Covenant.Ui.Services; + +/// Invariant-culture formatting (the bundle ships no globalization data). Money is shown to four +/// decimals because per-request provider charges are fractions of a cent; totals use two. +public static class Fmt +{ + private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; + + public static string Usd(decimal value, int decimals = 4) + => "$" + value.ToString("F" + decimals.ToString(Inv), Inv); + + public static string UsdTotal(decimal value) => Usd(value, value == decimal.Truncate(value) ? 2 : 4); + + public static string Int(long value) => value.ToString("N0", Inv); + + public static string Percent(decimal numerator, decimal denominator) + { + if (denominator <= 0) return "n/a"; + var pct = numerator / denominator * 100m; + return pct.ToString(pct >= 10 ? "F0" : "F1", Inv) + "%"; + } + + public static int PercentClamped(decimal numerator, decimal denominator) + => denominator <= 0 ? 0 : (int)Math.Clamp(numerator / denominator * 100m, 0m, 100m); + + public static string Utc(DateTimeOffset? t) + => t is null ? "Not recorded" : t.Value.UtcDateTime.ToString("yyyy-MM-dd HH:mm:ss", Inv) + " UTC"; + + public static string UtcShort(DateTimeOffset t) => t.UtcDateTime.ToString("HH:mm:ss", Inv); + + public static string Ms(double ms) => ms < 1000 ? ms.ToString("F0", Inv) + " ms" : (ms / 1000).ToString("F2", Inv) + " s"; + + public static string Ago(DateTimeOffset? t, DateTimeOffset now) + { + if (t is null) return "never"; + var s = (int)Math.Max(0, (now - t.Value).TotalSeconds); + if (s < 60) return s + " s ago"; + if (s < 3600) return (s / 60) + " min ago"; + return (s / 3600) + " h ago"; + } + + public static string Duration(TimeSpan d) + { + if (d.TotalMinutes < 1) return d.Seconds + " s"; + if (d.TotalHours < 1) return (int)d.TotalMinutes + " min"; + if (d.TotalDays < 1) return $"{(int)d.TotalHours} h {d.Minutes} min"; + return $"{(int)d.TotalDays} d {d.Hours} h"; + } + + public static string OrNotRecorded(string? s) => string.IsNullOrWhiteSpace(s) ? "Not recorded" : s; +} diff --git a/src/Covenant.Ui/Services/InferenceApi.cs b/src/Covenant.Ui/Services/InferenceApi.cs new file mode 100644 index 0000000..bec4fbd --- /dev/null +++ b/src/Covenant.Ui/Services/InferenceApi.cs @@ -0,0 +1,248 @@ +using System.Diagnostics; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using Covenant.Ui.Logic; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Services; + +/// What the console observed for one governed request. Response text is console-only: it lives in +/// memory for the operator who submitted it and is never persisted. +public sealed class InferenceResult +{ + public int? HttpStatus { get; set; } + /// X-Covenant-Request-Id (or request_id from an error body as a fallback). Null only when no + /// response arrived at all. + public string? RequestId { get; set; } + public string? ErrorCode { get; set; } + public string? ErrorReason { get; set; } + public string Text { get; set; } = ""; + public string? Model { get; set; } + public bool StreamTerminatedWithError { get; set; } + /// Stream ended without [DONE] and without an error line (connection dropped). + public bool StreamIncomplete { get; set; } + public bool Cancelled { get; set; } + /// Network-level failure text (no HTTP response). + public string? TransportError { get; set; } + /// Wall time measured in the browser — labelled "client-measured" wherever shown. + public double ClientMs { get; set; } + + public OutcomeInput ToOutcomeInput(AuditEntryView? record) => new( + HttpStatus, ErrorCode, StreamTerminatedWithError || StreamIncomplete, Cancelled, record); +} + +/// POST /v1/chat/completions through the governed pipeline with an APPLICATION key. Uses its own +/// HttpClient and never sees the admin token. An empty key sends no Authorization header at all, so the server +/// answers with its real 401 (and the record says classification was not evaluated). Identity and team are +/// resolved by the server from the key; the console only sends workflow/use-case labels. +public sealed class InferenceApi(HttpClient http, AppState state) +{ + public const string RequestIdHeader = "X-Covenant-Request-Id"; + + public Task SendAsync(RequestSnapshot snapshot, Action? onDelta, CancellationToken ct) + => snapshot.Streaming ? StreamAsync(snapshot, onDelta, ct) : BufferedAsync(snapshot, ct); + + private HttpRequestMessage Build(RequestSnapshot s, bool stream) + { + var body = new ChatRequestDto + { + Model = s.RequestedModel, + Messages = [new ChatMessageDto { Role = "user", Content = s.Prompt }], + Stream = stream, + MaxTokens = s.MaxTokens, + }; + var request = new HttpRequestMessage(HttpMethod.Post, "/v1/chat/completions") + { + Content = JsonContent.Create(body, UiJsonContext.Default.ChatRequestDto), + }; + if (state.ApplicationKey is { Length: > 0 } key) + request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + key.Trim()); + AddLabel(request, "X-Covenant-Workflow", s.Workflow); + AddLabel(request, "X-Covenant-UseCase", s.UseCase); + return request; + } + + /// Labels are plain attribution text; anything outside printable ASCII is dropped so the browser's + /// fetch never rejects the header. + private static void AddLabel(HttpRequestMessage request, string header, string? value) + { + if (string.IsNullOrWhiteSpace(value)) return; + var sb = new StringBuilder(value.Length); + foreach (var c in value.Trim()) + if (c >= 0x20 && c < 0x7F) sb.Append(c); + if (sb.Length > 0 && sb.Length <= 128) request.Headers.TryAddWithoutValidation(header, sb.ToString()); + } + + private async Task BufferedAsync(RequestSnapshot s, CancellationToken ct) + { + var result = new InferenceResult(); + var sw = Stopwatch.StartNew(); + try + { + using var request = Build(s, stream: false); + using var response = await http.SendAsync(request, ct); + Capture(result, response); + var text = await response.Content.ReadAsStringAsync(ct); + if (response.IsSuccessStatusCode) + ReadChatResponse(result, text); + else + ReadError(result, text); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + result.Cancelled = true; + } + catch (HttpRequestException ex) + { + result.TransportError = "Could not reach Covenant: " + ex.Message; + } + catch (OperationCanceledException) + { + // Not our token: the client-side timeout elapsed. The request may still complete on the server. + result.TransportError = "Stopped waiting after the console's " + http.Timeout.TotalMinutes.ToString("0", System.Globalization.CultureInfo.InvariantCulture) + + "-minute timeout — the request may have completed or been charged."; + } + finally + { + result.ClientMs = sw.Elapsed.TotalMilliseconds; + } + return result; + } + + private async Task StreamAsync(RequestSnapshot s, Action? onDelta, CancellationToken ct) + { + var result = new InferenceResult(); + var sw = Stopwatch.StartNew(); + var text = new StringBuilder(); + try + { + using var request = Build(s, stream: true); + request.Headers.Accept.ParseAdd("text/event-stream"); + Microsoft.AspNetCore.Components.WebAssembly.Http.WebAssemblyHttpRequestMessageExtensions + .SetBrowserResponseStreamingEnabled(request, true); + using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct); + Capture(result, response); + + var mediaType = response.Content.Headers.ContentType?.MediaType; + if (!response.IsSuccessStatusCode || !string.Equals(mediaType, "text/event-stream", StringComparison.OrdinalIgnoreCase)) + { + // Refused before the first byte: the same JSON error contract as buffered mode. + var body = await response.Content.ReadAsStringAsync(ct); + if (response.IsSuccessStatusCode) ReadChatResponse(result, body); + else ReadError(result, body); + return result; + } + + using var stream = await response.Content.ReadAsStreamAsync(ct); + using var reader = new StreamReader(stream); + bool done = false; + while (!done) + { + var line = await reader.ReadLineAsync(ct); + if (line is null) break; + if (!line.StartsWith("data:", StringComparison.Ordinal)) continue; + var payload = line.AsSpan(5).Trim(); + if (payload.IsEmpty) continue; + if (payload is "[DONE]") { done = true; break; } + + StreamFrameDto? frame; + try { frame = JsonSerializer.Deserialize(payload, UiJsonContext.Default.StreamFrameDto); } + catch (JsonException) { continue; } + if (frame is null) continue; + + if (frame.Error is { Length: > 0 }) + { + result.StreamTerminatedWithError = true; + result.ErrorCode = frame.Error; + result.ErrorReason = frame.Reason; + result.RequestId ??= frame.RequestId; + continue; // [DONE] follows + } + + result.RequestId ??= frame.Id; + if (frame.Model is { Length: > 0 } m) result.Model = m; + if (frame.Choices is { Count: > 0 } choices && choices[0].Delta?.Content is { Length: > 0 } delta) + { + text.Append(delta); + result.Text = text.ToString(); + onDelta?.Invoke(delta); + } + } + if (!done && !result.StreamTerminatedWithError) result.StreamIncomplete = true; + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + result.Cancelled = true; + } + catch (HttpRequestException ex) + { + if (result.HttpStatus is null) result.TransportError = "Could not reach Covenant: " + ex.Message; + else result.StreamIncomplete = true; + } + catch (IOException) + { + result.StreamIncomplete = true; + } + catch (OperationCanceledException) + { + // Client-side timeout (not our token). + if (result.HttpStatus is null) result.TransportError = "Stopped waiting for response headers (console timeout)."; + else result.StreamIncomplete = true; + } + finally + { + result.Text = text.Length > 0 ? text.ToString() : result.Text; + result.ClientMs = sw.Elapsed.TotalMilliseconds; + } + return result; + } + + private static void Capture(InferenceResult result, HttpResponseMessage response) + { + result.HttpStatus = (int)response.StatusCode; + if (response.Headers.TryGetValues(RequestIdHeader, out var values)) + foreach (var v in values) + if (!string.IsNullOrWhiteSpace(v)) { result.RequestId = v.Trim(); break; } + } + + private static void ReadChatResponse(InferenceResult result, string body) + { + ChatResponseDto? dto; + try { dto = JsonSerializer.Deserialize(body, UiJsonContext.Default.ChatResponseDto); } + catch (JsonException) { return; } + if (dto is null) return; + result.RequestId ??= dto.Id; + result.Model = dto.Model; + if (dto.Choices.Count > 0 && dto.Choices[0].Message?.Content is { } content) + result.Text = ContentText(content); + } + + private static string ContentText(JsonElement content) + { + if (content.ValueKind == JsonValueKind.String) return content.GetString() ?? ""; + if (content.ValueKind != JsonValueKind.Array) return ""; + var sb = new StringBuilder(); + foreach (var part in content.EnumerateArray()) + if (part.ValueKind == JsonValueKind.Object && part.TryGetProperty("text", out var t) && t.ValueKind == JsonValueKind.String) + sb.Append(t.GetString()); + return sb.ToString(); + } + + private static void ReadError(InferenceResult result, string body) + { + if (string.IsNullOrWhiteSpace(body)) return; + try + { + var err = JsonSerializer.Deserialize(body, UiJsonContext.Default.ErrorResponse); + if (err is null) return; + result.ErrorCode = err.Error; + result.ErrorReason = err.Reason; + result.RequestId ??= err.RequestId; + } + catch (JsonException) + { + // Not our error contract (e.g. the binder's 400): keep the status, no reason. + } + } +} diff --git a/src/Covenant.Ui/Services/Interop.cs b/src/Covenant.Ui/Services/Interop.cs new file mode 100644 index 0000000..5000361 --- /dev/null +++ b/src/Covenant.Ui/Services/Interop.cs @@ -0,0 +1,28 @@ +using Microsoft.JSInterop; + +namespace Covenant.Ui.Services; + +/// Typed wrapper over wwwroot/js/interop.js. Everything the console asks the browser for goes through +/// here, so the storage rules are auditable in one place: sessionStorage for the admin token only, +/// localStorage for the theme only, nothing else is ever persisted. +public sealed class Interop(IJSRuntime js) +{ + private const string Prefix = "covenantInterop."; + + public ValueTask SessionGetAsync(string key) => js.InvokeAsync(Prefix + "sessionGet", key); + public ValueTask SessionSetAsync(string key, string value) => js.InvokeVoidAsync(Prefix + "sessionSet", key, value); + public ValueTask SessionRemoveAsync(string key) => js.InvokeVoidAsync(Prefix + "sessionRemove", key); + + public ValueTask GetThemeAsync() => js.InvokeAsync(Prefix + "getTheme"); + public ValueTask SetThemeAsync(string theme) => js.InvokeAsync(Prefix + "setTheme", theme); + + public ValueTask FocusElementAsync(string id) => js.InvokeAsync(Prefix + "focusElement", id); + public ValueTask TrapFocusAsync(string containerId) => js.InvokeVoidAsync(Prefix + "trapFocus", containerId); + public ValueTask ReleaseFocusAsync(string containerId) => js.InvokeVoidAsync(Prefix + "releaseFocus", containerId); + + /// Copies a non-secret identifier (request id) to the clipboard. Returns false if the browser refused. + public ValueTask CopyTextAsync(string text) => js.InvokeAsync(Prefix + "copyText", text); + + public ValueTask DownloadTextAsync(string fileName, string contentType, string text) + => js.InvokeVoidAsync(Prefix + "downloadText", fileName, contentType, text); +} diff --git a/src/Covenant.Ui/Services/PlaygroundState.cs b/src/Covenant.Ui/Services/PlaygroundState.cs new file mode 100644 index 0000000..b9ecdc5 --- /dev/null +++ b/src/Covenant.Ui/Services/PlaygroundState.cs @@ -0,0 +1,173 @@ +using System.Diagnostics; +using System.Text; +using Covenant.Ui.Logic; + +namespace Covenant.Ui.Services; + +/// One submitted Playground request: its frozen snapshot, what the transport showed, the streamed text +/// (console-only, memory-only) and the evidence lookup for its correlation id. +public sealed class PlaygroundRun(RequestSnapshot snapshot) +{ + private readonly StringBuilder _text = new(); + + public RequestSnapshot Snapshot { get; } = snapshot; + public bool InFlight { get; internal set; } = true; + public InferenceResult? Result { get; internal set; } + public EvidenceStatus Evidence { get; internal set; } = EvidenceStatus.Idle; + /// Elapsed client wall time while in flight (for the "Sending…" line), final once done. + public Stopwatch Clock { get; } = Stopwatch.StartNew(); + + public string Text => Result is { Text.Length: > 0 } r && !InFlight ? r.Text : _text.ToString(); + + internal void Append(string delta) => _text.Append(delta); + + public OutcomeView? Outcome => InFlight || Result is null ? null : OutcomeModel.Compute(Result.ToOutcomeInput(Evidence.Record)); +} + +/// Playground session state, kept across navigation (scoped = the page lifetime in WASM) so an in-flight +/// run, its result and its evidence survive a visit to Requests. Nothing here is persisted; AppState.Disconnected +/// clears all of it (and the application key lives in AppState, cleared there). One run at a time. +public sealed class PlaygroundState : IDisposable +{ + private readonly AppState _state; + private readonly InferenceApi _inference; + private readonly EvidenceTracker _evidence; + private readonly CatalogState _catalog; + private readonly List _runs = []; + private CancellationTokenSource? _runCts; + private CancellationTokenSource? _evidenceCts; + private int _sequence; + + public PlaygroundState(AppState state, InferenceApi inference, EvidenceTracker evidence, CatalogState catalog) + { + _state = state; + _inference = inference; + _evidence = evidence; + _catalog = catalog; + _state.Disconnected += Clear; + } + + public event Action? Changed; + + public PlaygroundForm Form { get; } = new(); + public IReadOnlyList Runs => _runs; + public PlaygroundRun? Selected { get; private set; } + public bool Running => _runCts is not null; + + public void Select(PlaygroundRun run) + { + if (!_runs.Contains(run)) return; + Selected = run; + Notify(); + } + + public void ApplyPreset(ScenarioPreset preset) + { + ScenarioPresets.ApplyTo(preset, Form); + Notify(); + } + + /// Freezes the form and sends it. Refuses to start while another run is in flight. + public async Task RunAsync() + { + if (Running || Form.Problem is not null) return; + + var snapshot = RequestSnapshot.Freeze(++_sequence, Form, DateTimeOffset.UtcNow); + var run = new PlaygroundRun(snapshot); + _runs.Add(run); + Selected = run; + var cts = new CancellationTokenSource(); + _runCts = cts; + Notify(); + + InferenceResult result; + try + { + result = await _inference.SendAsync(snapshot, delta => { run.Append(delta); Notify(); }, cts.Token); + } + finally + { + _runCts = null; + cts.Dispose(); + } + run.Clock.Stop(); + run.Result = result; + run.InFlight = false; + Notify(); + + // Only drop this run's results if a disconnect cleared the list while it was in flight. + if (!_runs.Contains(run)) return; + + if (result.RequestId is { Length: > 0 } && result.HttpStatus is not null && !IsPreGovernance(result)) + await TrackEvidenceAsync(run); + + // The backend records success/failure from real calls: re-read shared health after any provider attempt. + _ = _catalog.RefreshAsync(); + } + + /// Stops waiting for the in-flight run. Not a rollback. + public void Cancel() + { + try { _runCts?.Cancel(); } + catch (ObjectDisposedException) { /* finished meanwhile */ } + } + + public async Task RetryEvidenceAsync(PlaygroundRun run) + { + if (run.Result?.RequestId is not { Length: > 0 }) return; + await TrackEvidenceAsync(run); + } + + /// Clear output: forgets every run and response (not the form, not the key). + public void ClearOutput() + { + if (Running) return; + _evidenceCts?.Cancel(); + _runs.Clear(); + Selected = null; + Notify(); + } + + private static bool IsPreGovernance(InferenceResult r) + => r.HttpStatus == 400 && !string.Equals(r.ErrorCode, "unsupported", StringComparison.Ordinal); + + private async Task TrackEvidenceAsync(PlaygroundRun run) + { + var id = run.Result?.RequestId; + if (id is null) return; + _evidenceCts?.Cancel(); + var cts = new CancellationTokenSource(); + _evidenceCts = cts; + run.Evidence = new EvidenceStatus(EvidenceState.Pending); + Notify(); + var final = await _evidence.TrackAsync(id, s => { run.Evidence = s; Notify(); }, cts.Token); + if (final.State != EvidenceState.Idle || run.Evidence.State == EvidenceState.Pending) + run.Evidence = final.State == EvidenceState.Idle + ? new EvidenceStatus(EvidenceState.Unavailable, Message: "Lookup stopped — retry.") + : final; + if (ReferenceEquals(_evidenceCts, cts)) _evidenceCts = null; + cts.Dispose(); + Notify(); + } + + /// Disconnect: cancel the in-flight run and forget prompts, responses, snapshots and selection. + private void Clear() + { + Cancel(); + _evidenceCts?.Cancel(); + _runs.Clear(); + Selected = null; + Form.Clear(); + _sequence = 0; + Notify(); + } + + private void Notify() => Changed?.Invoke(); + + public void Dispose() + { + _state.Disconnected -= Clear; + Cancel(); + _evidenceCts?.Cancel(); + } +} diff --git a/src/Covenant.Ui/Services/RequestsViewState.cs b/src/Covenant.Ui/Services/RequestsViewState.cs new file mode 100644 index 0000000..cc01ae1 --- /dev/null +++ b/src/Covenant.Ui/Services/RequestsViewState.cs @@ -0,0 +1,38 @@ +using Covenant.Ui.Logic; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Services; + +/// Requests browser state that survives navigation: the loaded snapshot of the current audit segment, +/// the filters and the selected request. Cleared on disconnect. Holds audit records only (no response text). +public sealed class RequestsViewState : IDisposable +{ + public const int SnapshotLimit = 500; + + private readonly AppState _state; + + public RequestsViewState(AppState state) + { + _state = state; + _state.Disconnected += Clear; + } + + public RequestsResponse? Snapshot { get; set; } + public DateTimeOffset? LoadedUtc { get; set; } + public RequestFilterCriteria Criteria { get; set; } = RequestFilterCriteria.None; + + /// The request open in the detail drawer (by correlation id), with its exact record when fetched. + public string? SelectedId { get; set; } + public AuditEntryView? SelectedRecord { get; set; } + + private void Clear() + { + Snapshot = null; + LoadedUtc = null; + Criteria = RequestFilterCriteria.None; + SelectedId = null; + SelectedRecord = null; + } + + public void Dispose() => _state.Disconnected -= Clear; +} diff --git a/src/Covenant.Ui/Services/RouteHealth.cs b/src/Covenant.Ui/Services/RouteHealth.cs new file mode 100644 index 0000000..661848b --- /dev/null +++ b/src/Covenant.Ui/Services/RouteHealth.cs @@ -0,0 +1,88 @@ +using Covenant.Ui.Models; + +namespace Covenant.Ui.Services; + +public enum LocalRouteState { Unknown, NotConfigured, NotRegistered, NotObserved, Ready, Degraded } + +/// One shared answer to "is the local route usable?" for the header, Overview and Models & +/// connections. Built from the server's catalog only — never from a client checkbox. +public sealed record LocalRouteSummary(LocalRouteState State, string Text, string Tone, DateTimeOffset? LastSuccessUtc, + DateTimeOffset? LastFailureUtc, string? LastError); + +/// Cross-checks the policy's routes (status.routes) against the provider catalog (catalog.models / +/// catalog.local). A route the policy permits but no adapter serves is "unresolved": matching requests pass +/// routing and are refused at the Provider stage. Unknown when the catalog has not loaded — never assumed healthy. +public static class RouteHealth +{ + /// Local route status. Health comes from the local model's observed health (real pipeline calls), + /// falling back to the applied endpoint's probe health when the model has not been observed. + /// A failure newer than the last success is "degraded" even if an older success exists. + public static LocalRouteSummary LocalRoute(CatalogResponse? catalog, DateTimeOffset nowUtc) + { + if (catalog is null) + return new(LocalRouteState.Unknown, "Local route: unknown (catalog not loaded)", "hollow", null, null, null); + var local = catalog.Local; + if (local is null || !local.Configured) + return new(LocalRouteState.NotConfigured, "Local route: not configured", "hollow", null, null, null); + if (!local.Registered) + return new(LocalRouteState.NotRegistered, "Local route: configured but not registered", "bad", null, null, null); + + ModelHealth? health = null; + foreach (var m in catalog.Models) + if (IsLocalAdapter(m.Adapter) && string.Equals(m.ModelId, local.ModelId, StringComparison.Ordinal)) + { + health = m.Health; + break; + } + if (health is null || string.Equals(health.State, "unknown", StringComparison.OrdinalIgnoreCase) || health.State is null) + health = local.EndpointHealth ?? health; + + var success = health?.LastSuccessUtc; + var failure = health?.LastFailureUtc; + var state = health?.State; + if (string.Equals(state, "failed", StringComparison.OrdinalIgnoreCase) + || (failure is not null && (success is null || failure > success))) + { + var lastOk = success is null ? "never succeeded" : "last success " + Fmt.Ago(success, nowUtc); + return new(LocalRouteState.Degraded, $"Local route: degraded ({lastOk})", "warn", success, failure, health?.LastError); + } + if (string.Equals(state, "ok", StringComparison.OrdinalIgnoreCase) || success is not null) + return new(LocalRouteState.Ready, $"Local route: ready (last success {Fmt.Ago(success, nowUtc)})", "ok", success, failure, health?.LastError); + return new(LocalRouteState.NotObserved, "Local route: registered, not yet observed", "hollow", null, null, null); + } + + public static bool IsLocalAdapter(string adapter) => string.Equals(adapter, "local", StringComparison.OrdinalIgnoreCase); + + public static IReadOnlyList UnresolvedRoutes(StatusReport? status, CatalogResponse? catalog) + { + if (status is null || catalog is null) return []; + var registered = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var m in catalog.Models) + if (m.Registered) registered.Add(m.Adapter + ":" + m.ModelId); + + var unresolved = new List(); + foreach (var r in status.Routes) + if (!registered.Contains(r.Adapter + ":" + r.Model)) unresolved.Add(r); + return unresolved; + } + + public static bool LocalRouteMissing(StatusReport? status, CatalogResponse? catalog) + { + if (status is null || catalog is null) return false; + if (catalog.Local is { Configured: true, Registered: false }) return true; + foreach (var r in UnresolvedRoutes(status, catalog)) + if (IsLocalAdapter(r.Adapter)) return true; + return false; + } + + public static bool IsRegistered(RouteView route, CatalogResponse? catalog) + { + if (catalog is null) return false; + foreach (var m in catalog.Models) + if (m.Registered + && string.Equals(m.Adapter, route.Adapter, StringComparison.OrdinalIgnoreCase) + && string.Equals(m.ModelId, route.Model, StringComparison.OrdinalIgnoreCase)) + return true; + return false; + } +} diff --git a/src/Covenant.Ui/Services/StatusFeed.cs b/src/Covenant.Ui/Services/StatusFeed.cs new file mode 100644 index 0000000..c5bb2a4 --- /dev/null +++ b/src/Covenant.Ui/Services/StatusFeed.cs @@ -0,0 +1,149 @@ +using System.Text.Json; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Services; + +/// Keeps AppState.LastStatus current while connected. Primary: the SSE stream at /admin/status/stream +/// (read through HttpClient so the admin token travels in a header — EventSource cannot). On failure it +/// reconnects with backoff and marks the state stale ("Connection lost — retrying"); after two streaming +/// failures it falls back to polling GET /admin/status every 3 s. A second loop ticks AppState once a second +/// so freshness flips to Stale on time even when nothing arrives. +public sealed class StatusFeed(AdminApi api, AppState state) : IDisposable +{ + public static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(3); + private const int StreamFailuresBeforePolling = 2; + + private CancellationTokenSource? _cts; + + public bool Running => _cts is { IsCancellationRequested: false }; + + public void Start() + { + if (Running) return; + _cts = new CancellationTokenSource(); + _ = RunAsync(_cts.Token); + _ = TickAsync(_cts.Token); + } + + public void Stop() + { + var cts = _cts; + _cts = null; + if (cts is null) return; + cts.Cancel(); + cts.Dispose(); + state.SetFeedMode(FeedMode.None); + } + + /// One immediate GET /admin/status; used after a mutation so the UI re-syncs from the server + /// instead of assuming the mutation succeeded. + public async Task RefreshNowAsync(CancellationToken ct = default) + { + var status = await api.GetStatusAsync(ct); + state.ApplyStatus(status); + } + + private async Task TickAsync(CancellationToken ct) + { + try + { + using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1)); + while (await timer.WaitForNextTickAsync(ct)) + state.Tick(DateTimeOffset.UtcNow); + } + catch (OperationCanceledException) { /* stopped */ } + } + + private async Task RunAsync(CancellationToken ct) + { + int streamFailures = 0; + int attempt = 0; + + while (!ct.IsCancellationRequested) + { + try + { + if (streamFailures < StreamFailuresBeforePolling) + { + state.SetFeedMode(FeedMode.Stream); + await ReadStreamAsync(ct); + // A clean end of stream (server closed) is treated like a failure for backoff purposes. + streamFailures++; + } + else + { + state.SetFeedMode(FeedMode.Polling); + await PollAsync(ct); + return; // PollAsync only returns on cancellation + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + return; // AdminApi already raised Unauthorized; ConsoleSession disconnects and stops us. + } + catch (Exception) + { + streamFailures++; + } + + if (ct.IsCancellationRequested) return; + attempt++; + state.MarkFeedFailure("Connection lost — retrying"); + var delay = TimeSpan.FromSeconds(Math.Min(10, 1 << Math.Min(attempt, 3))); + try { await Task.Delay(delay, ct); } catch (OperationCanceledException) { return; } + } + } + + private async Task ReadStreamAsync(CancellationToken ct) + { + using var response = await api.OpenStatusStreamAsync(ct); + using var stream = await response.Content.ReadAsStreamAsync(ct); + using var reader = new StreamReader(stream); + + while (!ct.IsCancellationRequested) + { + var line = await reader.ReadLineAsync(ct); + if (line is null) return; // end of stream + if (!line.StartsWith("data:", StringComparison.Ordinal)) continue; + + var json = line.AsSpan(5).Trim(); + if (json.IsEmpty) continue; + StatusReport? status; + try + { + status = JsonSerializer.Deserialize(json, UiJsonContext.Default.StatusReport); + } + catch (JsonException) + { + continue; // a malformed frame is skipped; the next one re-syncs + } + if (status is not null) state.ApplyStatus(status); + } + } + + private async Task PollAsync(CancellationToken ct) + { + using var timer = new PeriodicTimer(PollInterval); + while (!ct.IsCancellationRequested) + { + try + { + var status = await api.GetStatusAsync(ct); + state.ApplyStatus(status); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) { return; } + catch (Exception) + { + state.MarkFeedFailure("Connection lost — retrying"); + } + if (!await timer.WaitForNextTickAsync(ct)) return; + } + } + + public void Dispose() => Stop(); +} diff --git a/src/Covenant.Ui/_Imports.razor b/src/Covenant.Ui/_Imports.razor new file mode 100644 index 0000000..49e5282 --- /dev/null +++ b/src/Covenant.Ui/_Imports.razor @@ -0,0 +1,11 @@ +@using System.Net.Http +@using Microsoft.AspNetCore.Components.Forms +@using Microsoft.AspNetCore.Components.Routing +@using Microsoft.AspNetCore.Components.Web +@using Microsoft.JSInterop +@using Covenant.Ui +@using Covenant.Ui.Components +@using Covenant.Ui.Layout +@using Covenant.Ui.Logic +@using Covenant.Ui.Models +@using Covenant.Ui.Services diff --git a/src/Covenant.Ui/wwwroot/css/app.css b/src/Covenant.Ui/wwwroot/css/app.css new file mode 100644 index 0000000..ceddc0c --- /dev/null +++ b/src/Covenant.Ui/wwwroot/css/app.css @@ -0,0 +1,357 @@ +/* Covenant console — application styles. Tokens live in tokens.css; only semantic colours are used here. */ + +*, *::before, *::after { box-sizing: border-box; } +html, body { margin: 0; padding: 0; } +html { background: var(--bg); color: var(--text); } +body { + font-family: var(--font-sans); + font-size: var(--text-body); + line-height: 1.5; + -webkit-font-smoothing: antialiased; +} +a { color: var(--accent); } +a:hover { text-decoration-thickness: 2px; } +h1, h2, h3 { margin: 0; font-weight: 600; line-height: 1.3; } +h1 { font-size: var(--text-page-title); } +h2 { font-size: var(--text-section); } +h3 { font-size: var(--text-body); } +p { margin: 0; } +ul, ol { margin: 0; } +dl { margin: 0; } +dd { margin: 0; } +table { border-collapse: collapse; width: 100%; } +th, td { text-align: left; padding: 10px 14px; border-bottom: 1px solid var(--border); vertical-align: top; } +th { font-weight: 500; color: var(--muted); font-size: var(--text-secondary); } +td.num, th.num { text-align: right; } +code, .mono { font-family: var(--font-mono); font-variant-numeric: tabular-nums; } +.muted { color: var(--muted); } +.subtle { color: var(--subtle); } +.secondary { font-size: var(--text-secondary); } +.visually-hidden { position: absolute !important; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } + +/* Focus: one visible ring everywhere, in the accent colour. */ +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: var(--radius-control); } +button:focus:not(:focus-visible), a:focus:not(:focus-visible) { outline: none; } + +/* ---- Boot placeholder (replaced when the runtime mounts) ---- */ +.boot { min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; color: var(--muted); } +.boot-mark { font-weight: 600; font-size: 22px; color: var(--text); } +.boot-sub { font-size: var(--text-secondary); } + +#blazor-error-ui { + display: none; position: fixed; bottom: 0; left: 0; right: 0; z-index: 1000; + background: var(--amber-bg); color: var(--text); border-top: 1px solid var(--amber); + padding: 12px 20px; font-size: var(--text-secondary); +} +#blazor-error-ui .reload { margin-left: 12px; } +#blazor-error-ui .dismiss { float: right; background: none; border: 0; color: var(--text); font-size: 18px; cursor: pointer; } + +/* ---- Shell ---- */ +.shell { min-height: 100vh; display: flex; align-items: stretch; } +.shell-nav { + flex: 0 0 220px; background: var(--surface); border-right: 1px solid var(--border); + padding: 20px 12px; display: flex; flex-direction: column; gap: 4px; +} +.shell-brand { display: flex; flex-direction: column; padding: 0 12px 20px; } +.shell-brand .name { font-weight: 600; font-size: 18px; } +.shell-brand .descriptor { font-size: var(--text-secondary); color: var(--subtle); } +.nav-link { + display: flex; justify-content: space-between; align-items: center; gap: 8px; + text-decoration: none; color: var(--muted); padding: 8px 12px; border-radius: var(--radius-control); + min-height: var(--target-min); +} +.nav-link:hover { color: var(--text); background: var(--surface2); } +.nav-link.active { color: var(--text); background: var(--blue-bg); font-weight: 500; } +.nav-spacer { flex-grow: 1; min-height: 24px; } +.nav-session { + border-top: 1px solid var(--border); margin-top: 8px; padding: 12px; + display: flex; flex-direction: column; gap: 4px; font-size: var(--text-secondary); +} +.nav-session .theme-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 8px; } + +.shell-main { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; } +.status-header { + display: flex; flex-wrap: wrap; align-items: center; gap: 10px 18px; padding: 10px 28px; + border-bottom: 1px solid var(--border); background: var(--surface); font-size: var(--text-secondary); +} +.status-header .env { font-family: var(--font-mono); padding: 2px 8px; border: 1px solid var(--border); border-radius: 4px; } +.status-header .grow { flex-grow: 1; } +.indicator { display: inline-flex; align-items: center; gap: 6px; } +.dot { width: 8px; height: 8px; border-radius: 4px; background: var(--subtle); flex: 0 0 auto; } +.dot.ok { background: var(--green); } +.dot.warn { background: var(--amber); } +.dot.bad { background: var(--red); } +.dot.hollow { background: transparent; border: 1px solid var(--subtle); } + +.pause-banner { + display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; padding: 10px 28px; + background: var(--amber-bg); border-bottom: 1px solid var(--amber); font-size: var(--text-secondary); +} +.pause-banner strong { color: var(--amber); } + +.page { padding: 22px 28px 48px; display: flex; flex-direction: column; gap: 18px; max-width: 1400px; width: 100%; } +.page-head { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 16px; } +.page-head .titles { display: flex; flex-direction: column; flex: 1 1 320px; min-width: 0; } +.page-head .lede { font-size: var(--text-secondary); color: var(--muted); } +.page-note { font-size: var(--text-secondary); color: var(--subtle); padding: 6px 10px; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface); } + +/* ---- Panels, grids ---- */ +.panel { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-panel); padding: 18px 20px; display: flex; flex-direction: column; gap: 14px; } +.panel.flush { padding: 0; overflow: hidden; gap: 0; } +.panel-head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 8px 16px; } +.panel.flush .panel-head { padding: 14px 18px; border-bottom: 1px solid var(--border); } +.panel-sub { font-size: var(--text-secondary); color: var(--subtle); } +.two-col { display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start; } +.two-col > * { flex: 1 1 380px; min-width: 0; } +.summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; } +.summary-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-panel); padding: 14px 16px; display: flex; flex-direction: column; gap: 2px; } +.summary-card dt { font-size: var(--text-secondary); color: var(--muted); } +.summary-card .value { font-size: 24px; font-weight: 600; font-family: var(--font-mono); font-variant-numeric: tabular-nums; } +.summary-card .hint { font-size: var(--text-secondary); color: var(--subtle); } +.meter { height: 6px; border-radius: 3px; background: var(--surface2); display: block; overflow: hidden; } +.meter > span { display: block; height: 6px; border-radius: 3px; background: var(--accent); min-width: 2px; } +.meter.warn > span { background: var(--amber); } +.meter.bad > span { background: var(--red); } +.table-wrap { overflow-x: auto; } +.plain-list { padding-left: 20px; display: flex; flex-direction: column; gap: 6px; } +.row-list { list-style: none; margin: 0; padding: 0; } +.row-list li { display: flex; flex-wrap: wrap; gap: 4px 14px; align-items: baseline; padding: 12px 18px; border-bottom: 1px solid var(--border); } +.row-list li:last-child { border-bottom: 0; } +.stages { padding-left: 0; list-style: none; display: flex; flex-direction: column; gap: 8px; counter-reset: stage; } +.stages li { display: flex; gap: 12px; align-items: baseline; } +.stages .n { font-family: var(--font-mono); color: var(--subtle); min-width: 1.5em; } +.stages .name { font-weight: 500; } + +/* ---- Alerts & banners ---- */ +.alert { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; border: 1px solid var(--border); border-radius: var(--radius-inner); padding: 12px 16px; background: var(--surface); } +.alert .alert-text { display: flex; flex-direction: column; flex: 1 1 360px; min-width: 0; } +.alert .alert-body { font-size: var(--text-secondary); color: var(--muted); } +.alert strong { font-weight: 600; } +.alert.warn { border-color: var(--amber); background: var(--amber-bg); } +.alert.warn strong { color: var(--amber); } +.alert.bad { border-color: var(--red); background: var(--red-bg); } +.alert.bad strong { color: var(--red); } +.alert.ok { border-color: var(--border); } +.alert.ok strong { color: var(--green); } +.alert.info strong { color: var(--accent); } + +/* ---- Status pill ---- */ +.pill { display: inline-flex; align-items: center; gap: 6px; padding: 2px 10px; border-radius: 999px; font-size: var(--text-secondary); font-weight: 500; border: 1px solid var(--border); background: var(--surface2); color: var(--text); white-space: nowrap; } +.pill .dot { width: 7px; height: 7px; } +.pill.served { background: var(--green-bg); color: var(--green); border-color: transparent; } +.pill.refused { background: var(--amber-bg); color: var(--amber); border-color: transparent; } +.pill.failed { background: var(--red-bg); color: var(--red); border-color: transparent; } +.pill.paused { background: var(--amber-bg); color: var(--amber); border-color: transparent; } +.pill.unknown { color: var(--muted); } + +/* ---- Buttons ---- */ +.btn { + display: inline-flex; align-items: center; justify-content: center; gap: 8px; + min-height: var(--target-min); padding: 0 16px; border-radius: var(--radius-control); + border: 1px solid var(--border); background: var(--surface2); color: var(--text); + font: inherit; font-size: var(--text-secondary); font-weight: 500; cursor: pointer; text-decoration: none; +} +.btn:hover:not(:disabled) { border-color: var(--accent); } +.btn:disabled { opacity: .55; cursor: not-allowed; } +.btn.primary { background: var(--accent-fill); border-color: var(--accent-fill); color: var(--on-accent); font-weight: 600; } +.btn.danger { background: var(--danger-fill); border-color: var(--danger-fill); color: var(--on-accent); font-weight: 600; } +.btn.ghost { background: transparent; } +.btn.form { min-height: var(--target-form); font-size: var(--text-body); } +.btn.sm { min-height: 32px; padding: 0 10px; } +.btn-row { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; } + +/* ---- Forms ---- */ +.field { display: flex; flex-direction: column; gap: 6px; } +.field label { font-size: var(--text-secondary); font-weight: 500; } +.field .help { font-size: var(--text-secondary); color: var(--subtle); } +.field .help.bad { color: var(--red); } +.input { + height: var(--target-form); padding: 0 12px; border-radius: var(--radius-control); + border: 1px solid var(--border); background: var(--bg); color: var(--text); font: inherit; width: 100%; +} +.input.mono { font-family: var(--font-mono); } +.input[aria-invalid="true"] { border-color: var(--red); } +.input:focus { outline: 2px solid var(--accent); outline-offset: 1px; border-color: var(--accent); } +.switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; font-size: var(--text-secondary); color: var(--muted); } + +/* ---- Fact list ---- */ +.facts { display: grid; grid-template-columns: max-content 1fr; gap: 8px 18px; font-size: var(--text-secondary); } +.facts dt { color: var(--muted); } +.facts dd { color: var(--text); overflow-wrap: anywhere; } +.facts dd.mono { font-family: var(--font-mono); } +.facts.inline { grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; } +.facts.inline > div { display: flex; flex-direction: column; gap: 2px; } +.facts.inline dd { font-size: var(--text-body); } + +/* ---- Error banner, empty state, skeleton ---- */ +.error-banner { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; border: 1px solid var(--red); background: var(--red-bg); border-radius: var(--radius-inner); padding: 12px 16px; } +.error-banner .error-text { display: flex; flex-direction: column; flex: 1 1 320px; } +.error-banner strong { color: var(--red); } +.error-banner .detail { font-size: var(--text-secondary); color: var(--muted); font-family: var(--font-mono); overflow-wrap: anywhere; } +.empty { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; padding: 24px; border: 1px dashed var(--border); border-radius: var(--radius-panel); color: var(--muted); } +.empty h2 { color: var(--text); } +.skeleton { display: block; height: 1em; border-radius: 4px; background: linear-gradient(90deg, var(--surface2), var(--border), var(--surface2)); background-size: 200% 100%; animation: shimmer 1.4s infinite linear; } +@keyframes shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } } +@media (prefers-reduced-motion: reduce) { .skeleton { animation: none; } } + +/* ---- Drawer / dialog ---- */ +.scrim { position: fixed; inset: 0; background: var(--scrim); z-index: 100; } +.drawer { + position: fixed; top: 0; right: 0; bottom: 0; width: min(560px, 100vw); z-index: 101; + background: var(--surface); border-left: 1px solid var(--border); display: flex; flex-direction: column; + box-shadow: -8px 0 24px rgba(0,0,0,.25); +} +.drawer-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 16px 20px; border-bottom: 1px solid var(--border); } +.drawer-body { padding: 20px; overflow: auto; display: flex; flex-direction: column; gap: 16px; } +.dialog { position: fixed; inset: 0; z-index: 101; display: flex; align-items: center; justify-content: center; padding: 24px; } +.dialog-box { width: min(560px, 100%); background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-panel); padding: 22px 24px; display: flex; flex-direction: column; gap: 14px; } + +/* ---- Connect ---- */ +.connect-wrap { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 48px 16px; } +.connect { width: 100%; max-width: 440px; display: flex; flex-direction: column; gap: 20px; } +.connect .brand { display: flex; flex-direction: column; gap: 2px; } +.connect .brand .name { font-weight: 600; font-size: 22px; } +.connect form { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-panel); padding: 24px; display: flex; flex-direction: column; gap: 16px; } + +/* ---- Activity chart ---- */ +.chart { display: flex; flex-direction: column; gap: 6px; } +.chart .legend { display: flex; flex-wrap: wrap; gap: 6px 16px; align-items: baseline; font-size: var(--text-secondary); color: var(--muted); } +.chart .legend .title { font-weight: 500; color: var(--text); } +.chart .swatch { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 6px; vertical-align: middle; } +.chart .bars { height: 140px; display: flex; align-items: flex-end; gap: 2px; border-bottom: 1px solid var(--border); } +.chart .bars.short { height: 80px; } +.chart .bar { flex: 1 1 0; min-width: 0; display: flex; flex-direction: column; justify-content: flex-end; height: 100%; } +.chart .bar .refused { background: var(--amber); border-radius: 2px 2px 0 0; } +.chart .bar .served { background: var(--accent); margin-top: 1px; } +.chart .bar .cost { background: var(--muted); border-radius: 2px 2px 0 0; } +.chart .axis { display: flex; justify-content: space-between; font-size: var(--text-secondary); color: var(--subtle); font-family: var(--font-mono); } + +/* ---- App-height shell (desktop): the page scrolls inside
, so work screens (Playground) can size + themselves to the viewport and keep long output scrolling inside its own box. ---- */ +@media (min-width: 901px) { + .shell { height: 100vh; min-height: 0; } + .shell-nav { overflow-y: auto; } + .shell-main { min-height: 0; } + #main { flex: 1 1 auto; min-height: 0; overflow: auto; display: flex; flex-direction: column; } +} +.header-link { color: inherit; text-decoration: none; } +.header-link:hover { text-decoration: underline; } + +/* ---- Shared small pieces ---- */ +.textarea { min-height: 96px; padding: 10px 12px; height: auto; resize: vertical; line-height: 1.45; } +select.input { padding-right: 8px; } +.field-row { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; } +.field-row > .field { flex: 1 1 140px; min-width: 0; } +.seg { display: inline-flex; flex-wrap: wrap; gap: 0; border: 1px solid var(--border); border-radius: var(--radius-control); overflow: hidden; } +.seg button { border: 0; border-right: 1px solid var(--border); background: transparent; color: var(--muted); font: inherit; font-size: var(--text-secondary); padding: 8px 12px; min-height: var(--target-min); cursor: pointer; } +.seg button:last-child { border-right: 0; } +.seg button[aria-checked="true"], .seg button[aria-pressed="true"] { background: var(--blue-bg); color: var(--text); font-weight: 500; } +.wrap-any { overflow-wrap: anywhere; word-break: break-word; } +.ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.code-block { margin: 0; padding: 12px 14px; background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius-inner); font-family: var(--font-mono); font-size: var(--text-secondary); white-space: pre-wrap; overflow-wrap: anywhere; max-height: 360px; overflow: auto; } +.note { font-size: var(--text-secondary); color: var(--subtle); } +.note.warn { color: var(--amber); } +.note.bad { color: var(--red); } +.copy-row { display: inline-flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; } +details.raw > summary { cursor: pointer; font-size: var(--text-secondary); color: var(--accent); min-height: 32px; display: flex; align-items: center; } + +/* ---- Playground (normal) ---- */ +.pg-page { flex: 1 1 auto; min-height: 0; max-width: none; padding-bottom: 16px; display: grid; grid-template-rows: auto minmax(0, 1fr) auto; gap: 14px; } +.pg-cols { display: grid; grid-template-columns: minmax(340px, 5fr) minmax(420px, 7fr); gap: 16px; min-height: 0; } +.pg-cols > section { min-height: 0; overflow: auto; } +.pg-bottom { display: grid; grid-template-columns: minmax(300px, 5fr) minmax(420px, 7fr); gap: 16px; min-height: 0; max-height: 34vh; } +.pg-bottom > section { min-height: 0; overflow: auto; padding: 14px 18px; gap: 10px; } +.presets { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; } +.preset { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; text-align: left; padding: 8px 12px; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface2); color: var(--text); font: inherit; cursor: pointer; min-height: var(--target-min); } +.preset .hint { font-size: var(--text-secondary); color: var(--subtle); } +.preset[aria-pressed="true"] { border-color: var(--accent); background: var(--blue-bg); } +.preset:disabled { opacity: .55; cursor: not-allowed; } +.outcome { font-size: var(--text-outcome); font-weight: 600; line-height: 1.2; } +.outcome.served { color: var(--green); } +.outcome.refused, .outcome.paused { color: var(--amber); } +.outcome.failed { color: var(--red); } +.outcome.unknown { color: var(--muted); } +.result-head { display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: baseline; } +.result-head .title { font-weight: 600; } +.changed-flag { font-size: var(--text-secondary); color: var(--amber); border: 1px solid var(--amber); border-radius: 999px; padding: 0 8px; } +.response-box { background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius-inner); padding: 12px 14px; white-space: pre-wrap; overflow-wrap: anywhere; overflow: auto; max-height: 40vh; min-height: 48px; } +.response-box.empty { color: var(--subtle); font-style: italic; } +.stage-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; } +.stage-list li { display: flex; gap: 10px; align-items: baseline; padding: 4px 8px; border-radius: var(--radius-control); font-size: var(--text-secondary); } +.stage-list .n { font-family: var(--font-mono); color: var(--subtle); min-width: 1.4em; } +.stage-list .name { font-weight: 500; } +.stage-list .detail { color: var(--subtle); } +.stage-list li.stopped { background: var(--amber-bg); outline: 1px solid var(--amber); } +.stage-list li.stopped .mark { color: var(--amber); font-weight: 600; } +.stage-list li.cache-hit { background: var(--green-bg); } +.history { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.ev-toggle { display: flex; justify-content: space-between; align-items: center; width: 100%; background: none; border: 0; color: var(--text); font: inherit; padding: 0; cursor: pointer; min-height: 32px; text-align: left; } +.pause-scope { font-size: var(--text-secondary); color: var(--subtle); } + +/* ---- Playground (presentation) — fixed full-viewport layer over the shell. ---- */ +.present-root { position: fixed; inset: 0; z-index: 60; background: var(--bg); display: grid; grid-template-rows: auto auto minmax(0, 1fr); overflow: hidden; } +.present-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; padding: 10px 24px; border-bottom: 1px solid var(--border); background: var(--surface); font-size: var(--text-secondary); } +.present-head .brand { font-weight: 600; font-size: 18px; } +.present-head .env { font-family: var(--font-mono); padding: 2px 8px; border: 1px solid var(--border); border-radius: 4px; } +.present-head .grow { flex-grow: 1; } +.present-scen { display: flex; flex-wrap: wrap; gap: 8px; padding: 12px 24px 0; } +.present-scen .preset { flex-direction: row; font-size: var(--text-facts-present); } +.present-main { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: 20px; padding: 14px 24px 18px; min-height: 0; } +.present-main > section { min-height: 0; display: flex; flex-direction: column; gap: 12px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-panel); padding: 18px 20px; overflow: hidden; } +.present-main textarea { flex: 1 1 auto; min-height: 80px; font-size: var(--text-facts-present); resize: none; } +.present-main .outcome { font-size: var(--text-outcome-present); } +.present-main .reason { font-size: var(--text-facts-present); color: var(--muted); } +.present-main .response-box { flex: 1 1 auto; max-height: none; font-size: var(--text-facts-present); min-height: 60px; } +.present-facts { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; font-size: var(--text-facts-present); } +.present-facts dt { font-size: var(--text-secondary); color: var(--muted); } +.present-facts dd { overflow-wrap: anywhere; } +.present-main .btn { font-size: var(--text-facts-present); min-height: 52px; } + +/* ---- Requests ---- */ +.filters { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; } +.filters .field { flex: 1 1 160px; min-width: 140px; } +.filters .field.search { flex: 2 1 240px; } +.req-table { min-width: 1120px; table-layout: fixed; } +.req-table td, .req-table th { padding: 8px 12px; } +.req-table td { font-size: var(--text-secondary); } +.req-table tbody tr { cursor: pointer; } +.req-table tbody tr:hover { background: var(--surface2); } +.req-table tbody tr.selected { background: var(--blue-bg); } +.req-table tbody tr:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.req-table .cell { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.table-scroll { overflow-x: auto; } +.drawer-section { display: flex; flex-direction: column; gap: 8px; border-top: 1px solid var(--border); padding-top: 14px; } +.drawer-section:first-child { border-top: 0; padding-top: 0; } +.drawer-section h3 { font-size: var(--text-secondary); color: var(--muted); font-weight: 600; } +.drawer .facts dd { overflow-wrap: anywhere; } +.drawer { width: min(640px, 100vw); } + +/* ---- Connections ---- */ +.wizard { display: flex; flex-direction: column; gap: 14px; } +.wizard fieldset { border: 1px solid var(--border); border-radius: var(--radius-inner); padding: 14px 16px; margin: 0; display: flex; flex-direction: column; gap: 10px; min-width: 0; } +.wizard fieldset:disabled { opacity: .55; } +.wizard legend { font-weight: 600; padding: 0 6px; } +.step-state { font-size: var(--text-secondary); font-weight: 500; } +.step-state.ok { color: var(--green); } +.step-state.bad { color: var(--red); } +.step-state.warn { color: var(--amber); } +.tag-list { display: flex; flex-direction: column; gap: 6px; } +.tag-list label { display: flex; gap: 8px; align-items: center; font-family: var(--font-mono); min-height: 32px; overflow-wrap: anywhere; } +.path-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; font-size: var(--text-secondary); } +.path-row .hop { border: 1px solid var(--border); border-radius: var(--radius-control); padding: 2px 8px; background: var(--surface2); } + +@media (max-height: 760px) and (min-width: 901px) { + .pg-bottom { max-height: 30vh; } + .present-main { padding-top: 10px; gap: 14px; } +} +@media (max-width: 1100px) { + .pg-cols, .pg-bottom { grid-template-columns: 1fr; } + .pg-page { display: flex; flex-direction: column; } + .pg-bottom { max-height: none; } +} + +@media (max-width: 900px) { + .shell { flex-direction: column; } + .shell-nav { flex: none; border-right: 0; border-bottom: 1px solid var(--border); } + .page, .status-header, .pause-banner { padding-left: 16px; padding-right: 16px; } +} diff --git a/src/Covenant.Ui/wwwroot/css/tokens.css b/src/Covenant.Ui/wwwroot/css/tokens.css new file mode 100644 index 0000000..185f64a --- /dev/null +++ b/src/Covenant.Ui/wwwroot/css/tokens.css @@ -0,0 +1,75 @@ +/* + * Covenant design tokens — ported from covenant-prototype/tokens.css (design reference, revision 2). + * Apply data-theme="dark" (default) or data-theme="light" (projection) on . + * Fonts: IBM Plex Sans / Mono are bundled in wwwroot/fonts (SIL OFL 1.1; see docs/PROVENANCE.md). No CDN. + */ +:root, +:root[data-theme="dark"] { + --bg: #0D1015; + --surface: #141920; + --surface2: #1A2029; + --border: #2A323D; + --text: #E7EAEE; + --muted: #A9B1BD; + --subtle: #8C96A4; /* lowest text tier; >= 4.5:1 on --surface */ + --accent: #6FA3F7; /* links, focus ring, outlines */ + --accent-fill: #2E6BD6; /* primary button fill */ + --on-accent: #FFFFFF; + --green: #4CC38A; /* served, verified */ + --amber: #E5A84B; /* paused, degraded, near limit */ + --red: #F27A70; /* denied, failed */ + --green-bg: #13291F; + --amber-bg: #2E2414; + --red-bg: #321A19; + --blue-bg: #15233A; /* current nav item, selected row */ + --danger-fill: #B8322A; /* destructive confirm only */ + --scrim: rgba(0,0,0,.55); /* behind drawers */ +} + +:root[data-theme="light"] { + --bg: #F4F5F7; + --surface: #FFFFFF; + --surface2: #F0F2F5; + --border: #D5D9E0; + --text: #161A20; + --muted: #4A5361; + --subtle: #5B6472; + --accent: #1F5FC9; + --accent-fill: #1F5FC9; + --on-accent: #FFFFFF; + --green: #17794A; + --amber: #8A5A00; + --red: #B42318; + --green-bg: #E3F4EA; + --amber-bg: #FBF0DB; + --red-bg: #FCE6E3; + --blue-bg: #E3ECFB; + --danger-fill: #B42318; +} + +:root { + --font-sans: 'IBM Plex Sans', system-ui, sans-serif; + --font-mono: 'IBM Plex Mono', ui-monospace, monospace; + + /* type scale (px) */ + --text-page-title: 24px; /* 600 */ + --text-section: 18px; /* 600 */ + --text-body: 16px; /* 400, line-height 1.5 */ + --text-secondary: 14px; /* minimum size */ + --text-outcome: 28px; /* Playground outcome */ + --text-outcome-present: 40px; + --text-facts-present: 20px; + + /* spacing, 4px base */ + --space-1: 4px; --space-2: 8px; --space-3: 12px; --space-4: 16px; + --space-5: 20px; --space-6: 24px; --space-7: 28px; + + /* radii */ + --radius-control: 6px; + --radius-inner: 8px; + --radius-panel: 10px; + + /* targets */ + --target-min: 40px; + --target-form: 44px; +} diff --git a/src/Covenant.Ui/wwwroot/fonts/LICENSE-ibm-plex-mono.txt b/src/Covenant.Ui/wwwroot/fonts/LICENSE-ibm-plex-mono.txt new file mode 100644 index 0000000..70687df --- /dev/null +++ b/src/Covenant.Ui/wwwroot/fonts/LICENSE-ibm-plex-mono.txt @@ -0,0 +1,93 @@ +Copyright 2017 IBM Corp. All rights reserved. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/Covenant.Ui/wwwroot/fonts/LICENSE-ibm-plex-sans.txt b/src/Covenant.Ui/wwwroot/fonts/LICENSE-ibm-plex-sans.txt new file mode 100644 index 0000000..e89cc25 --- /dev/null +++ b/src/Covenant.Ui/wwwroot/fonts/LICENSE-ibm-plex-sans.txt @@ -0,0 +1,93 @@ +Copyright 2018 IBM Corp. All rights reserved. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/Covenant.Ui/wwwroot/fonts/fonts.css b/src/Covenant.Ui/wwwroot/fonts/fonts.css new file mode 100644 index 0000000..6eb9488 --- /dev/null +++ b/src/Covenant.Ui/wwwroot/fonts/fonts.css @@ -0,0 +1,5 @@ +@font-face{font-family:'IBM Plex Sans';font-style:normal;font-weight:400;font-display:swap;src:url('ibm-plex-sans-latin-400-normal.woff2') format('woff2')} +@font-face{font-family:'IBM Plex Sans';font-style:normal;font-weight:500;font-display:swap;src:url('ibm-plex-sans-latin-500-normal.woff2') format('woff2')} +@font-face{font-family:'IBM Plex Sans';font-style:normal;font-weight:600;font-display:swap;src:url('ibm-plex-sans-latin-600-normal.woff2') format('woff2')} +@font-face{font-family:'IBM Plex Mono';font-style:normal;font-weight:400;font-display:swap;src:url('ibm-plex-mono-latin-400-normal.woff2') format('woff2')} +@font-face{font-family:'IBM Plex Mono';font-style:normal;font-weight:500;font-display:swap;src:url('ibm-plex-mono-latin-500-normal.woff2') format('woff2')} diff --git a/src/Covenant.Ui/wwwroot/fonts/ibm-plex-mono-latin-400-normal.woff2 b/src/Covenant.Ui/wwwroot/fonts/ibm-plex-mono-latin-400-normal.woff2 new file mode 100644 index 0000000..a6c77d6 Binary files /dev/null and b/src/Covenant.Ui/wwwroot/fonts/ibm-plex-mono-latin-400-normal.woff2 differ diff --git a/src/Covenant.Ui/wwwroot/fonts/ibm-plex-mono-latin-500-normal.woff2 b/src/Covenant.Ui/wwwroot/fonts/ibm-plex-mono-latin-500-normal.woff2 new file mode 100644 index 0000000..99c2610 Binary files /dev/null and b/src/Covenant.Ui/wwwroot/fonts/ibm-plex-mono-latin-500-normal.woff2 differ diff --git a/src/Covenant.Ui/wwwroot/fonts/ibm-plex-sans-latin-400-normal.woff2 b/src/Covenant.Ui/wwwroot/fonts/ibm-plex-sans-latin-400-normal.woff2 new file mode 100644 index 0000000..93bcd64 Binary files /dev/null and b/src/Covenant.Ui/wwwroot/fonts/ibm-plex-sans-latin-400-normal.woff2 differ diff --git a/src/Covenant.Ui/wwwroot/fonts/ibm-plex-sans-latin-500-normal.woff2 b/src/Covenant.Ui/wwwroot/fonts/ibm-plex-sans-latin-500-normal.woff2 new file mode 100644 index 0000000..adbbd4c Binary files /dev/null and b/src/Covenant.Ui/wwwroot/fonts/ibm-plex-sans-latin-500-normal.woff2 differ diff --git a/src/Covenant.Ui/wwwroot/fonts/ibm-plex-sans-latin-600-normal.woff2 b/src/Covenant.Ui/wwwroot/fonts/ibm-plex-sans-latin-600-normal.woff2 new file mode 100644 index 0000000..0ac91d6 Binary files /dev/null and b/src/Covenant.Ui/wwwroot/fonts/ibm-plex-sans-latin-600-normal.woff2 differ diff --git a/src/Covenant.Ui/wwwroot/index.html b/src/Covenant.Ui/wwwroot/index.html new file mode 100644 index 0000000..b33a259 --- /dev/null +++ b/src/Covenant.Ui/wwwroot/index.html @@ -0,0 +1,32 @@ + + + + + + + Covenant + + + + + + + + + +
+
+ Covenant + Loading the console… +
+
+ + + + + diff --git a/src/Covenant.Ui/wwwroot/js/interop.js b/src/Covenant.Ui/wwwroot/js/interop.js new file mode 100644 index 0000000..d409271 --- /dev/null +++ b/src/Covenant.Ui/wwwroot/js/interop.js @@ -0,0 +1,111 @@ +// Covenant console — the entire JS surface. No libraries, no network, no logging. +// +// Storage rules (TASK 01): localStorage holds ONLY the theme choice. The admin token lives in +// sessionStorage (tab-scoped; closing the tab disconnects). Application keys, prompts and responses are +// never persisted anywhere by this file — they stay in WASM memory. +(function () { + "use strict"; + + var THEME_KEY = "covenant.theme"; + + function applyTheme(theme) { + var t = theme === "light" ? "light" : "dark"; + document.documentElement.setAttribute("data-theme", t); + return t; + } + + // Apply the persisted theme immediately (before the runtime boots) to avoid a flash. + try { applyTheme(window.localStorage.getItem(THEME_KEY)); } catch (e) { applyTheme("dark"); } + + var traps = {}; // containerId -> keydown handler (focus trap for drawers/dialogs) + + function focusables(container) { + var sel = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'; + return Array.prototype.filter.call(container.querySelectorAll(sel), function (el) { + return el.offsetParent !== null || el === document.activeElement; + }); + } + + window.covenantInterop = { + sessionGet: function (key) { + try { return window.sessionStorage.getItem(key); } catch (e) { return null; } + }, + sessionSet: function (key, value) { + try { window.sessionStorage.setItem(key, value); } catch (e) { /* storage unavailable: stays in memory */ } + }, + sessionRemove: function (key) { + try { window.sessionStorage.removeItem(key); } catch (e) { /* nothing to remove */ } + }, + + getTheme: function () { + return document.documentElement.getAttribute("data-theme") || "dark"; + }, + setTheme: function (theme) { + var t = applyTheme(theme); + try { window.localStorage.setItem(THEME_KEY, t); } catch (e) { /* preference simply won't persist */ } + return t; + }, + + focusElement: function (id) { + var el = document.getElementById(id); + if (el && typeof el.focus === "function") { el.focus(); return true; } + return false; + }, + + // Keep Tab/Shift+Tab inside the container while a drawer or dialog is open. + trapFocus: function (containerId) { + var container = document.getElementById(containerId); + if (!container || traps[containerId]) return; + var handler = function (ev) { + if (ev.key !== "Tab") return; + var items = focusables(container); + if (items.length === 0) { ev.preventDefault(); container.focus(); return; } + var first = items[0], last = items[items.length - 1]; + if (ev.shiftKey && (document.activeElement === first || document.activeElement === container)) { + ev.preventDefault(); last.focus(); + } else if (!ev.shiftKey && document.activeElement === last) { + ev.preventDefault(); first.focus(); + } + }; + traps[containerId] = handler; + document.addEventListener("keydown", handler, true); + }, + releaseFocus: function (containerId) { + var handler = traps[containerId]; + if (!handler) return; + document.removeEventListener("keydown", handler, true); + delete traps[containerId]; + }, + + // Copy a request id (never a secret) to the clipboard. Resolves true on success. + copyText: function (text) { + try { + if (navigator.clipboard && navigator.clipboard.writeText) { + return navigator.clipboard.writeText(text).then(function () { return true; }, function () { return false; }); + } + } catch (e) { /* fall through */ } + return false; + }, + + // Evidence export: the JSON report, exactly as the server returned it, as a download. + downloadText: function (fileName, contentType, text) { + var blob = new Blob([text], { type: contentType || "application/octet-stream" }); + var url = URL.createObjectURL(blob); + var a = document.createElement("a"); + a.href = url; + a.download = fileName; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + setTimeout(function () { URL.revokeObjectURL(url); }, 1000); + } + }; + + // The framework's error banner has no built-in dismiss handler. + document.addEventListener("DOMContentLoaded", function () { + var ui = document.getElementById("blazor-error-ui"); + if (!ui) return; + var dismiss = ui.querySelector(".dismiss"); + if (dismiss) dismiss.addEventListener("click", function () { ui.style.display = "none"; }); + }); +})(); diff --git a/tests/Covenant.Tests/AccountingTests.cs b/tests/Covenant.Tests/AccountingTests.cs new file mode 100644 index 0000000..a397a8a --- /dev/null +++ b/tests/Covenant.Tests/AccountingTests.cs @@ -0,0 +1,323 @@ +using System.Runtime.CompilerServices; +using Covenant.Adapters; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// ADR-0009 §4–5 / Task 03: honest usage and fail-closed accounting through the REAL stages. +/// Unreported usage is never a real zero; a started-but-failed call is never $0; unknown cost never +/// becomes a false saving. +public sealed class AccountingTests +{ + private const string Cloud = "gpt-4o-mini"; + private const string Strong = "gpt-4o"; + private const string Local = "qwen3:8b"; + private const decimal InPer1K = 0.01m; + private const decimal OutPer1K = 0.03m; + + private enum UsageMode { Full, None, InputOnly } + + private sealed class AccountingClient(string reply, UsageMode usage = UsageMode.Full, bool fail = false, string? streamPartialThenFail = null) : MEAI.IChatClient + { + public int Calls; + + private MEAI.UsageDetails? Usage() => usage switch + { + UsageMode.Full => new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 }, + UsageMode.InputOnly => new MEAI.UsageDetails { InputTokenCount = 10 }, + _ => null, + }; + + public Task GetResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref Calls); + if (fail) throw new HttpRequestException("simulated provider 500"); + return Task.FromResult(new MEAI.ChatResponse(new MEAI.ChatMessage(MEAI.ChatRole.Assistant, reply)) { Usage = Usage() }); + } + + public async IAsyncEnumerable GetStreamingResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref Calls); + await Task.Yield(); + if (streamPartialThenFail is { } partial) + { + yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, partial); + throw new HttpRequestException("stream interrupted"); + } + yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply); + if (Usage() is { } u) yield return new MEAI.ChatResponseUpdate { Contents = [new MEAI.UsageContent(u)] }; + } + + public object? GetService(Type serviceType, object? serviceKey = null) => null; + public void Dispose() { } + } + + private sealed class CollectingSink : IAuditSink + { + public List Entries { get; } = []; + public ValueTask EnqueueAsync(AuditEntry entry, CancellationToken cancellationToken = default) + { + lock (Entries) Entries.Add(entry); + return ValueTask.CompletedTask; + } + } + + private static Dictionary DefaultPrices() => new() + { + [Cloud] = (InPer1K, OutPer1K), + [Strong] = (0.1m, 0.3m), + [Local] = (0m, 0m), + }; + + private sealed record Rig(InferencePipeline Pipeline, CollectingSink Sink, InMemorySpendLedger Ledger); + + private static Rig Build(MEAI.IChatClient cloud, MEAI.IChatClient? local = null, + Dictionary? prices = null, int cacheTtlSeconds = 0) + { + var sink = new CollectingSink(); + var ledger = new InMemorySpendLedger(); + var priceBook = new PriceBook(prices ?? DefaultPrices()); + var clients = new Dictionary { [$"openai:{Cloud}"] = cloud }; + if (local is not null) clients[$"local:{Local}"] = local; + var policy = new PolicyConfig + { + AllowedRoutes = new Dictionary> + { + [DataClassification.Public] = [new("openai", Cloud)], + [DataClassification.Internal] = [new("openai", Cloud)], + [DataClassification.Pii] = [new("local", Local)], + [DataClassification.Phi] = [new("local", Local)], + } + }; + var pipeline = new InferencePipeline( + [ + new AuditStage(sink), + new AuthStage(new AuthConfig { AllowAnonymous = true, Keys = [] }), + new ClassifyStage(new RegexDataClassifier()), + new PolicyStage(new PolicyEngine(policy)), + new CacheStage(new ResponseCache(), new CacheConfig { TtlSeconds = cacheTtlSeconds }), + new BudgetStage(new KillSwitch(), ledger, new BudgetConfig { GlobalCapUsd = 1_000m }, priceBook), + new ProviderCallStage(new ChatClientRegistry(clients)), + new AttributionStage(priceBook), + ]); + return new Rig(pipeline, sink, ledger); + } + + private static async Task<(InferenceContext Ctx, AuditEntry Entry)> RunAsync(Rig rig, string prompt, bool stream = false, string? model = null) + { + var ctx = new InferenceContext(new InferenceRequest("tester", [new ChatMessage(ChatRole.User, prompt)], model, + new AttributionTags("acct", "wf", "uc"), Stream: stream, RequestId: $"req_{Guid.NewGuid():n}")); + if (stream) ctx.DeltaSink = (_, _) => ValueTask.CompletedTask; + int before = rig.Sink.Entries.Count; + await rig.Pipeline.ExecuteAsync(ctx, CancellationToken.None); + Assert.Equal(before + 1, rig.Sink.Entries.Count); + return (ctx, rig.Sink.Entries[^1]); + } + + private static decimal Estimate(long inChars, long outChars) + => TokenEstimate.FromChars(inChars) / 1000m * InPer1K + TokenEstimate.FromChars(outChars) / 1000m * OutPer1K; + + [Fact] + public async Task Complete_usage_is_reported_and_priced_from_tokens() + { + var rig = Build(new AccountingClient("reply")); + var (_, e) = await RunAsync(rig, "a normal question"); + + Assert.Equal("reported", e.CostBasis); + Assert.True(e.UsageReported); + Assert.Equal(10, e.Usage.InputTokens); + Assert.Equal(5, e.Usage.OutputTokens); + Assert.Equal(10 / 1000m * InPer1K + 5 / 1000m * OutPer1K, e.Usage.CostUsd); + Assert.Equal(e.Usage.CostUsd, rig.Ledger.GlobalSpendUsd); + } + + [Fact] + public async Task Missing_usage_on_priced_model_is_estimated_from_text_and_charged() + { + const string prompt = "a question with no usage reported back"; + const string reply = "an answer of some length here"; + var rig = Build(new AccountingClient(reply, UsageMode.None)); + var (_, e) = await RunAsync(rig, prompt); + + Assert.Equal(PolicyEffect.Allow, e.Effect); + Assert.Equal("estimated_from_text", e.CostBasis); + Assert.False(e.UsageReported); + Assert.Equal(0, e.Usage.InputTokens); // not reported — not invented either + Assert.Equal(Estimate(prompt.Length, reply.Length), e.Usage.CostUsd); + Assert.True(e.Usage.CostUsd > 0m); + Assert.Equal(e.Usage.CostUsd, rig.Ledger.GlobalSpendUsd); // cannot escape the budget + } + + [Fact] + public async Task Missing_usage_on_a_streamed_call_is_also_estimated() + { + var rig = Build(new AccountingClient("streamed answer", UsageMode.None)); + var (_, e) = await RunAsync(rig, "stream without usage", stream: true); + + Assert.Equal("estimated_from_text", e.CostBasis); + Assert.False(e.UsageReported); + Assert.True(e.Usage.CostUsd > 0m); + } + + [Fact] + public async Task Partial_usage_is_not_reported_usage() + { + var rig = Build(new AccountingClient("reply", UsageMode.InputOnly)); + var (ctx, e) = await RunAsync(rig, "partial usage please"); + + Assert.False(ctx.Response!.UsageReported); + Assert.False(e.UsageReported); + Assert.Equal("estimated_from_text", e.CostBasis); + } + + [Fact] + public async Task Local_zero_price_is_zero_priced_not_reported_free() + { + var local = new AccountingClient("local reply"); + var rig = Build(new AccountingClient("never"), local); + var (_, e) = await RunAsync(rig, "ssn 123-45-6789"); + + Assert.Equal(Local, e.ServedByModel); + Assert.Equal("zero_priced", e.CostBasis); + Assert.Equal(0m, e.Usage.CostUsd); + Assert.Equal(1, local.Calls); + } + + [Fact] + public async Task Refusal_with_no_call_is_no_call_and_zero() + { + var cloud = new AccountingClient("never"); + var rig = Build(cloud); + var (_, e) = await RunAsync(rig, "hello", model: "unapproved-model"); + + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.Equal("no_call", e.CostBasis); + Assert.Null(e.AttemptedModel); + Assert.Null(e.UsageReported); + Assert.Equal(0m, e.Usage.CostUsd); + Assert.Equal(0, cloud.Calls); + } + + [Fact] + public async Task Cache_hit_is_no_call_and_zero_and_charged_once() + { + var cloud = new AccountingClient("cached reply"); + var rig = Build(cloud, cacheTtlSeconds: 60); + var (_, first) = await RunAsync(rig, "same question twice"); + var spentAfterFirst = rig.Ledger.GlobalSpendUsd; + var (_, second) = await RunAsync(rig, "same question twice"); + + Assert.Equal("reported", first.CostBasis); + Assert.True(second.CacheHit); + Assert.Equal("no_call", second.CostBasis); + Assert.Null(second.AttemptedModel); + Assert.Equal(0m, second.Usage.CostUsd); + Assert.Equal(1, cloud.Calls); + Assert.Equal(spentAfterFirst, rig.Ledger.GlobalSpendUsd); + } + + [Fact] + public async Task Upstream_failure_on_priced_model_is_charged_an_estimate() + { + const string prompt = "this call will fail upstream"; + var rig = Build(new AccountingClient("never", fail: true)); + var (ctx, e) = await RunAsync(rig, prompt); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(Cloud, e.AttemptedModel); + Assert.Equal("estimated_failed_call", e.CostBasis); + Assert.False(e.UsageReported); + Assert.Equal(Estimate(prompt.Length, 0), e.Usage.CostUsd); + Assert.True(e.Usage.CostUsd > 0m); + Assert.Equal(e.Usage.CostUsd, rig.Ledger.GlobalSpendUsd); + } + + [Fact] + public async Task Interrupted_stream_estimate_includes_partial_output() + { + const string prompt = "stream then die"; + const string partial = "twenty chars of text"; // 20 chars → 5 estimated output tokens + var rig = Build(new AccountingClient("never", streamPartialThenFail: partial)); + var (ctx, e) = await RunAsync(rig, prompt, stream: true); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(partial.Length, ctx.PartialOutputChars); + Assert.Equal("estimated_failed_call", e.CostBasis); + Assert.Equal(Estimate(prompt.Length, partial.Length), e.Usage.CostUsd); + Assert.True(e.Usage.CostUsd > Estimate(prompt.Length, 0)); // output was counted, not dropped + Assert.Equal(e.Usage.CostUsd, rig.Ledger.GlobalSpendUsd); + } + + [Fact] + public async Task Unpriced_model_is_flagged_unpriced_and_counted_unknown() + { + var prices = DefaultPrices(); + prices.Remove(Cloud); + var rig = Build(new AccountingClient("reply"), prices: prices); + var (_, e) = await RunAsync(rig, "price me if you can"); + + Assert.Equal("unpriced", e.CostBasis); + Assert.Equal(0m, e.Usage.CostUsd); + + var finops = FinOps.Build([e], Local, Strong, prices); + Assert.Equal(1, finops.UnknownCostRequests); + Assert.Equal(0m, finops.EstimatedSavingsUsd); + } + + [Fact] + public async Task Failed_call_on_unpriced_model_is_unknown_not_zero() + { + var prices = DefaultPrices(); + prices.Remove(Cloud); + var rig = Build(new AccountingClient("never", fail: true), prices: prices); + var (_, e) = await RunAsync(rig, "fail on an unpriced model"); + + Assert.Equal("unknown_failed_call", e.CostBasis); + Assert.Equal(Cloud, e.AttemptedModel); + Assert.Equal(1, FinOps.Build([e], Local, Strong, prices).UnknownCostRequests); + } + + private static AuditEntry Served(string? costBasis, string model = Cloud) => new( + $"req_{Guid.NewGuid():n}", DateTimeOffset.UtcNow, "p", new AttributionTags("t", "w", "u"), + DataClassification.Internal, PolicyEffect.Allow, "allowed", model, new Usage(1000, 1000, 0.04m), + SchemaVersion: 2, CostBasis: costBasis); + + [Theory] + [InlineData("unpriced")] + [InlineData("estimated_from_text")] + public void Unknown_or_estimated_cost_never_becomes_a_saving(string basis) + { + var prices = DefaultPrices(); + var control = FinOps.Build([Served("reported")], Local, Strong, prices); + Assert.True(control.EstimatedSavingsUsd > 0m); // same record, reported → a real saving vs strong + + var flagged = FinOps.Build([Served(basis)], Local, Strong, prices); + Assert.Equal(0m, flagged.EstimatedSavingsUsd); + Assert.Equal(0m, flagged.SavingsRouterUsd); + Assert.Equal(1, flagged.Allowed); + Assert.Equal(0.04m, flagged.TotalCostUsd); // the charge still counts toward spend + Assert.Equal(basis == "unpriced" ? 1 : 0, flagged.UnknownCostRequests); + Assert.Equal(basis == "estimated_from_text" ? 1 : 0, flagged.EstimatedCostRequests); + } + + [Fact] + public void Legacy_records_without_cost_basis_keep_their_savings_treatment() + { + var legacy = FinOps.Build([Served(null)], Local, Strong, DefaultPrices()); + Assert.True(legacy.EstimatedSavingsUsd > 0m); + Assert.Equal(0, legacy.UnknownCostRequests); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(1, 1)] + [InlineData(4, 1)] + [InlineData(5, 2)] + [InlineData(400, 100)] + public void Token_estimate_is_ceiling_chars_over_four(int chars, int tokens) + => Assert.Equal((long)tokens, TokenEstimate.FromChars(chars)); +} diff --git a/tests/Covenant.Tests/ConsoleAssetsTests.cs b/tests/Covenant.Tests/ConsoleAssetsTests.cs new file mode 100644 index 0000000..71ebd2d --- /dev/null +++ b/tests/Covenant.Tests/ConsoleAssetsTests.cs @@ -0,0 +1,231 @@ +using System.Net; +using Covenant.Host; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Xunit; + +namespace Covenant.Tests; + +/// Pure tests for the console asset helpers: MIME map, path normalization, cache policy. These run +/// whether or not the WASM bundle was embedded (SkipConsolePublish). +public sealed class ConsoleAssetsUnitTests +{ + [Theory] + [InlineData("index.html", "text/html; charset=utf-8")] + [InlineData("_framework/blazor.webassembly.js", "text/javascript; charset=utf-8")] + [InlineData("_framework/dotnet.native.abc123.wasm", "application/wasm")] + [InlineData("_framework/blazor.boot.json", "application/json; charset=utf-8")] + [InlineData("_framework/icudt.dat", "application/octet-stream")] + [InlineData("_framework/Covenant.Ui.pdb", "application/octet-stream")] + [InlineData("fonts/ibm-plex-sans-latin-400-normal.woff2", "font/woff2")] + [InlineData("css/app.css", "text/css; charset=utf-8")] + [InlineData("js/interop.mjs", "text/javascript; charset=utf-8")] + [InlineData("favicon.ico", "image/x-icon")] + [InlineData("logo.svg", "image/svg+xml")] + [InlineData("logo.png", "image/png")] + [InlineData("README.md", "text/markdown; charset=utf-8")] + [InlineData("notes.txt", "text/plain; charset=utf-8")] + [InlineData("INDEX.HTML", "text/html; charset=utf-8")] + public void Content_type_map_covers_the_bundle(string path, string expected) + => Assert.Equal(expected, ConsoleAssets.ContentTypeFor(path)); + + [Theory] + [InlineData("thing.unknownext")] + [InlineData("noextension")] + public void Unknown_extensions_are_octet_stream(string path) + => Assert.Equal("application/octet-stream", ConsoleAssets.ContentTypeFor(path)); + + [Theory] + [InlineData(null, "")] + [InlineData("", "")] + [InlineData("index.html", "index.html")] + [InlineData("/index.html", "index.html")] + [InlineData("_framework\\blazor.boot.json", "_framework/blazor.boot.json")] + [InlineData("_framework//dotnet.js", "_framework/dotnet.js")] + [InlineData("./css/app.css", "css/app.css")] + [InlineData("css/../index.html", "index.html")] + [InlineData("../../etc/passwd", "etc/passwd")] + [InlineData("requests/req_abc/", "requests/req_abc")] + public void Paths_normalize_to_forward_slashes_without_traversal(string? input, string expected) + => Assert.Equal(expected, ConsoleAssets.NormalizePath(input)); + + [Theory] + [InlineData("index.html", "no-cache")] + [InlineData("_framework/blazor.boot.json", "no-cache")] + [InlineData("_framework/blazor.webassembly.js", "no-cache")] + [InlineData("_framework/dotnet.boot.js", "no-cache")] + [InlineData("_framework/dotnet.ab12cd34.js", "public,max-age=31536000,immutable")] + [InlineData("_framework/Covenant.Ui.ab12cd34.wasm", "public,max-age=31536000,immutable")] + [InlineData("fonts/ibm-plex-mono-latin-400-normal.woff2", "public,max-age=31536000,immutable")] + [InlineData("css/app.css", "no-cache")] + [InlineData("_framework/System.Runtime.wasm", "no-cache")] // unfingerprinted → revalidate, never pinned for a year + public void Cache_policy_revalidates_entry_points_and_pins_fingerprinted_files(string path, string expected) + => Assert.Equal(expected, ConsoleAssets.CacheControlFor(path)); + + [Fact] + public void Csp_never_allows_remote_origins() + { + Assert.Contains("default-src 'self'", ConsoleAssets.ContentSecurityPolicy); + Assert.Contains("'wasm-unsafe-eval'", ConsoleAssets.ContentSecurityPolicy); + Assert.Contains("frame-ancestors 'none'", ConsoleAssets.ContentSecurityPolicy); + Assert.DoesNotContain("http", ConsoleAssets.ContentSecurityPolicy); + Assert.DoesNotContain("*", ConsoleAssets.ContentSecurityPolicy); + } +} + +/// The console through the real Host. The bundle may or may not be embedded in this test build +/// (SkipConsolePublish); each test asserts the branch the manifest says applies, so the suite is deterministic +/// either way. +public sealed class ConsoleAssetsTests : IClassFixture +{ + public sealed class Factory : WebApplicationFactory + { + public readonly string AuditPath = Path.Combine(Path.GetTempPath(), $"covenant-console-{Guid.NewGuid():n}.log"); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Production"); + builder.UseSetting("OpenAI:ApiKey", "unused-stubbed"); + builder.UseSetting("Admin:Token", "test-admin"); + builder.UseSetting("Budget:GlobalCapUsd", "100"); + 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); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + foreach (var f in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(AuditPath) + "*")) + File.Delete(f); + } + } + + private static readonly bool Embedded = ConsoleAssets.HasEmbeddedConsole(typeof(ConsoleAssets).Assembly); + private readonly HttpClient _client; + + public ConsoleAssetsTests(Factory factory) + { + _client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + } + + [Fact] + public async Task Ui_root_serves_the_shell_or_an_honest_503() + { + var resp = await _client.GetAsync("/ui/"); + if (Embedded) + { + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + Assert.Equal("text/html", resp.Content.Headers.ContentType?.MediaType); + var html = await resp.Content.ReadAsStringAsync(); + Assert.Contains(" new() + { + Id = id, + CorrelationId = id, + TimestampUtc = at ?? new DateTimeOffset(2026, 10, 16, 12, 0, 0, TimeSpan.Zero), + Principal = "svc-" + team, + Tags = new AttributionTagsView { Team = team, Workflow = "playground", UseCase = "console-test" }, + Classification = classification, + Effect = effect, + Reason = reason, + ServedByModel = served, + Usage = new UsageView { InputTokens = inTok, OutputTokens = outTok, TotalTokens = inTok + outTok, CostUsd = cost }, + DurationMs = 123, + PromptChars = 42, + PromptSha256 = new string('a', 64), + Signal = signal, + CacheHit = cacheHit, + SchemaVersion = 2, + ClassificationEvaluated = classificationEvaluated, + DenialKind = denialKind, + StoppedAtStage = stage, + SelectedModel = selected, + AttemptedModel = attempted, + Stream = false, + UsageReported = usageReported, + CostBasis = costBasis, + }; + + public static AuditEntryView Pause() => V2("Deny", "Governance", "pause", attempted: null, served: null, + costBasis: "no_call", cost: 0m, usageReported: null, inTok: 0, outTok: 0, reason: "kill switch engaged: demo"); + + public static AuditEntryView PolicyDeny() => V2("Deny", "Governance", "policy", selected: null, attempted: null, served: null, + costBasis: "no_call", cost: 0m, usageReported: null, inTok: 0, outTok: 0, + reason: "model 'gpt-4-unapproved-test' not permitted for classification 'Internal'"); + + public static AuditEntryView MissingAdapter() => V2("Deny", "Governance", "provider", selected: "qwen3:8b", attempted: null, served: null, + classification: "Pii", signal: "US SSN pattern", costBasis: "no_call", cost: 0m, usageReported: null, inTok: 0, outTok: 0, + reason: "no adapter registered for 'local:qwen3:8b'"); + + public static AuditEntryView AuthFail() => V2("Deny", "Unauthenticated", "auth", selected: null, attempted: null, served: null, + classificationEvaluated: false, classification: "Phi", costBasis: "no_call", cost: 0m, usageReported: null, inTok: 0, outTok: 0, + reason: "authentication required: no API key presented"); + + public static AuditEntryView Upstream() => V2("Deny", "UpstreamFailure", "provider", served: null, + costBasis: "estimated_failed_call", cost: 0.0004m, usageReported: false, inTok: 0, outTok: 0, + reason: "provider 'openai' stream failed: boom"); + + /// A pre-v2 line: none of the v2 fields exist. + public static AuditEntryView Legacy(string effect = "Allow") => new() + { + Id = "a1b2c3", + TimestampUtc = new DateTimeOffset(2026, 9, 1, 8, 0, 0, TimeSpan.Zero), + Principal = "svc-legacy", + Tags = new AttributionTagsView { Team = "legacy" }, + Classification = "Phi", + Effect = effect, + Reason = effect == "Allow" ? "allowed" : "denied", + ServedByModel = effect == "Allow" ? "gpt-4o-mini" : null, + Usage = new UsageView { InputTokens = 5, OutputTokens = 7, TotalTokens = 12, CostUsd = 0.0001m }, + }; +} + +public sealed class OutcomeModelTests +{ + [Fact] + public void Served_record_is_served() + { + var v = OutcomeModel.Compute(new OutcomeInput(200, Record: Rec.V2())); + Assert.Equal(DisplayOutcome.Served, v.Outcome); + Assert.Equal("served", v.PillKind); + Assert.False(v.TransportDiffers); + Assert.Equal("HTTP 200", v.StatusLine); + } + + [Fact] + public void Http_200_before_the_record_is_served_but_awaiting_evidence() + { + var v = OutcomeModel.Compute(new OutcomeInput(200)); + Assert.Equal(DisplayOutcome.Served, v.Outcome); + Assert.True(v.AwaitingRecord); + } + + [Fact] + public void Cache_hit_is_served_from_cache() + { + var v = OutcomeModel.FromRecord(Rec.V2(cacheHit: true, attempted: null, costBasis: "no_call")); + Assert.Equal(DisplayOutcome.ServedFromCache, v.Outcome); + Assert.Equal("served", v.PillKind); + } + + [Fact] + public void Mid_stream_failure_is_transport_200_but_failed_before_the_record() + { + var v = OutcomeModel.Compute(new OutcomeInput(200, "upstream_error", StreamTerminatedWithError: true)); + Assert.Equal(DisplayOutcome.ProviderFailedMidStream, v.Outcome); + Assert.True(v.TransportDiffers); + Assert.Equal("Transport 200, final outcome: failed", v.StatusLine); + Assert.Equal("failed", v.PillKind); + } + + [Fact] + public void Mid_stream_failure_with_its_record_stays_failed_and_differs() + { + var v = OutcomeModel.Compute(new OutcomeInput(200, "upstream_error", true, Record: Rec.Upstream())); + Assert.Equal(DisplayOutcome.ProviderFailedMidStream, v.Outcome); + Assert.True(v.TransportDiffers); + Assert.Equal("Transport 200, final outcome: failed", v.StatusLine); + } + + [Fact] + public void Upstream_failure_without_a_committed_stream_is_provider_unavailable() + { + Assert.Equal(DisplayOutcome.ProviderUnavailable, OutcomeModel.Compute(new OutcomeInput(502, "upstream_error", Record: Rec.Upstream())).Outcome); + Assert.Equal(DisplayOutcome.ProviderUnavailable, OutcomeModel.Compute(new OutcomeInput(502, "upstream_error")).Outcome); + Assert.Equal(DisplayOutcome.ProviderUnavailable, OutcomeModel.FromRecord(Rec.Upstream()).Outcome); + } + + [Fact] + public void Auth_failure_before_and_after_the_record() + { + var before = OutcomeModel.Compute(new OutcomeInput(401, "unauthenticated")); + Assert.Equal(DisplayOutcome.AuthenticationFailed, before.Outcome); + Assert.Contains("not evaluated", before.Explanation, StringComparison.OrdinalIgnoreCase); + + var after = OutcomeModel.Compute(new OutcomeInput(401, "unauthenticated", Record: Rec.AuthFail())); + Assert.Equal(DisplayOutcome.AuthenticationFailed, after.Outcome); + Assert.Equal("refused", after.PillKind); + } + + [Fact] + public void Auth_failure_classification_is_not_evaluated_never_the_restrictive_default() + { + var text = ModelFacts.Classification(Rec.AuthFail()); + Assert.Equal("Not evaluated — stopped at authentication", text); + Assert.DoesNotContain("Phi", text, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Http_403_before_the_record_does_not_guess_the_stage() + { + var v = OutcomeModel.Compute(new OutcomeInput(403, "denied")); + Assert.Equal(DisplayOutcome.Unknown, v.Outcome); + Assert.Equal("Refused (HTTP 403) — awaiting evidence for the stage", v.Title); + Assert.True(v.AwaitingRecord); + Assert.Equal("refused", v.PillKind); + } + + [Fact] + public void Pause_vs_policy_vs_missing_adapter_come_from_the_recorded_stage() + { + Assert.Equal(DisplayOutcome.Paused, OutcomeModel.FromRecord(Rec.Pause()).Outcome); + Assert.Equal("paused", OutcomeModel.FromRecord(Rec.Pause()).PillKind); + Assert.Equal(DisplayOutcome.PolicyDenied, OutcomeModel.FromRecord(Rec.PolicyDeny()).Outcome); + + var missing = OutcomeModel.FromRecord(Rec.MissingAdapter()); + Assert.Equal(DisplayOutcome.ProviderUnavailable, missing.Outcome); + Assert.Contains("no registered adapter", missing.Title, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Pause_is_never_inferred_from_the_reason_text() + { + var looksPaused = Rec.V2("Deny", "Governance", "policy", attempted: null, served: null, costBasis: "no_call", + reason: "kill switch engaged: demo"); + Assert.Equal(DisplayOutcome.PolicyDenied, OutcomeModel.FromRecord(looksPaused).Outcome); + + var paused = Rec.V2("Deny", "Governance", "pause", attempted: null, served: null, costBasis: "no_call", reason: "anything"); + Assert.Equal(DisplayOutcome.Paused, OutcomeModel.FromRecord(paused).Outcome); + } + + [Fact] + public void Provider_stage_with_an_attempted_model_is_not_a_missing_adapter() + { + var r = Rec.V2("Deny", "Governance", "provider", served: null, costBasis: "unknown_failed_call"); + var v = OutcomeModel.FromRecord(r); + Assert.NotEqual(DisplayOutcome.ProviderUnavailable, v.Outcome); + Assert.DoesNotContain("no registered adapter", v.Title, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Budget_refusal_is_a_governance_denial() + { + var v = OutcomeModel.FromRecord(Rec.V2("Deny", "Governance", "budget", attempted: null, served: null, costBasis: "no_call", + reason: "global budget exhausted (cap 5 USD)")); + Assert.Equal(DisplayOutcome.PolicyDenied, v.Outcome); + Assert.Contains("budget", v.Title, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Rate_limited_unsupported_and_rejected_before_governance() + { + Assert.Equal(DisplayOutcome.RateLimited, OutcomeModel.Compute(new OutcomeInput(429, "rate_limited")).Outcome); + Assert.Equal(DisplayOutcome.RateLimited, OutcomeModel.FromRecord(Rec.V2("Deny", "RateLimited", "rate_limit", attempted: null, served: null)).Outcome); + + Assert.Equal(DisplayOutcome.Unsupported, OutcomeModel.Compute(new OutcomeInput(400, "unsupported")).Outcome); + Assert.Equal(DisplayOutcome.Unsupported, OutcomeModel.FromRecord(Rec.V2("Deny", "Unsupported", "shape", attempted: null, served: null)).Outcome); + + var binder = OutcomeModel.Compute(new OutcomeInput(400)); + Assert.Equal(DisplayOutcome.RejectedBeforeGovernance, binder.Outcome); + Assert.Contains("no evidence record", binder.Explanation, StringComparison.Ordinal); + } + + [Fact] + public void Cancellation_is_stopped_waiting_never_a_rollback() + { + var client = OutcomeModel.Compute(new OutcomeInput(Cancelled: true)); + Assert.Equal(DisplayOutcome.Cancelled, client.Outcome); + Assert.Contains("not a rollback", client.Explanation, StringComparison.Ordinal); + Assert.Contains("may have completed or been charged", client.Explanation, StringComparison.Ordinal); + + Assert.Equal(DisplayOutcome.Cancelled, OutcomeModel.Compute(new OutcomeInput(499, "cancelled")).Outcome); + Assert.Equal(DisplayOutcome.Cancelled, OutcomeModel.FromRecord(Rec.V2("Deny", "Cancelled", "provider", served: null, + costBasis: "estimated_failed_call")).Outcome); + } + + [Fact] + public void Cancelled_stream_after_200_is_transport_200_final_incomplete() + { + var v = OutcomeModel.Compute(new OutcomeInput(200, Cancelled: true)); + Assert.Equal(DisplayOutcome.Cancelled, v.Outcome); + Assert.True(v.TransportDiffers); + Assert.Equal("Transport 200, final outcome: incomplete", v.StatusLine); + } + + [Fact] + public void Record_wins_over_client_cancel_when_the_server_completed() + { + var v = OutcomeModel.Compute(new OutcomeInput(Cancelled: true, Record: Rec.V2())); + Assert.Equal(DisplayOutcome.Served, v.Outcome); + Assert.Contains("stopped waiting", v.Explanation, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void No_response_and_unknown_effect_are_unknown() + { + var net = OutcomeModel.Compute(new OutcomeInput()); + Assert.Equal(DisplayOutcome.Unknown, net.Outcome); + Assert.Equal("No HTTP response", net.StatusLine); + Assert.Equal("unknown", net.PillKind); + + Assert.Equal(DisplayOutcome.Unknown, OutcomeModel.FromRecord(Rec.V2(effect: "Maybe")).Outcome); + } + + [Fact] + public void Legacy_denial_without_kind_or_stage_is_not_attributed_to_a_stage() + { + var v = OutcomeModel.FromRecord(Rec.Legacy("Deny")); + Assert.Equal(DisplayOutcome.Unknown, v.Outcome); + Assert.Equal("Refused (legacy record)", v.Title); + Assert.Equal("refused", v.PillKind); + } + + [Fact] + public void Pipeline_stage_rows_map_pause_and_budget_to_one_row() + { + Assert.Equal("pause_budget", PipelineStages.RowKey("pause")); + Assert.Equal("pause_budget", PipelineStages.RowKey("budget")); + Assert.Equal("auth", PipelineStages.RowKey("auth")); + Assert.Null(PipelineStages.RowKey(null)); + Assert.Contains(PipelineStages.Configured, s => s.Key == "pause_budget"); + Assert.Equal(9, PipelineStages.Configured.Count); + } +} + +public sealed class ModelFactsTests +{ + [Fact] + public void Selected_before_a_pause_is_not_an_attempted_model() + { + var f = ModelFacts.From(Rec.Pause()); + Assert.Equal("gpt-4o-mini", f.Selected); + Assert.Equal("None — no provider call", f.Attempted); + Assert.Equal("None — not served", f.Served); + } + + [Fact] + public void Cache_hit_shows_served_from_cache_and_no_attempt() + { + var f = ModelFacts.From(Rec.V2(cacheHit: true, attempted: null, costBasis: "no_call")); + Assert.StartsWith("Served from cache (no provider call)", f.Served, StringComparison.Ordinal); + Assert.Equal("None — no provider call", f.Attempted); + } + + [Fact] + public void Legacy_record_nulls_are_not_recorded() + { + var f = ModelFacts.From(Rec.Legacy()); + Assert.Equal("Not recorded", f.Selected); + Assert.Equal("Not recorded", f.Attempted); + Assert.Equal("gpt-4o-mini", f.Served); + Assert.Equal("Not recorded", f.Classification); + Assert.Equal("Not recorded", ModelFacts.Served(NoServed(Rec.Legacy()))); + } + + private static AuditEntryView NoServed(AuditEntryView r) + { + r.ServedByModel = null; + return r; + } + + [Fact] + public void Evaluated_classification_shows_the_signal_when_present() + { + Assert.Equal("Pii · US SSN pattern", ModelFacts.Classification(Rec.V2(classification: "Pii", signal: "US SSN pattern"))); + Assert.Equal("Internal · no rule matched", ModelFacts.Classification(Rec.V2())); + } + + [Fact] + public void Selected_to_served_cell() + { + Assert.Equal("gpt-4o-mini", ModelFacts.SelectedToServed(Rec.V2())); + Assert.Equal("gpt-4o-mini → not served", ModelFacts.SelectedToServed(Rec.Pause())); + Assert.Equal("gpt-4o-mini → cache", ModelFacts.SelectedToServed(Rec.V2(cacheHit: true))); + } +} + +public sealed class CostTextTests +{ + [Fact] + public void Each_cost_basis_has_its_own_wording() + { + Assert.Equal("$0.0012 (estimated provider charge)", CostText.Cost(Rec.V2(costBasis: "reported", cost: 0.0012m))); + Assert.Equal("$0.00 configured provider charge · infrastructure excluded", CostText.Cost(Rec.V2(costBasis: "zero_priced", cost: 0m))); + Assert.Equal("≈ $0.0030 estimated from text length", CostText.Cost(Rec.V2(costBasis: "estimated_from_text", cost: 0.003m))); + Assert.Equal("≈ $0.0004 estimated from text length", CostText.Cost(Rec.Upstream())); + Assert.Equal("$0.00 — no provider call", CostText.Cost(Rec.Pause())); + Assert.Equal("$0.0001 (legacy record)", CostText.Cost(Rec.Legacy())); + } + + [Theory] + [InlineData("unknown_failed_call")] + [InlineData("unpriced")] + [InlineData("something_new")] + public void Unknown_cost_is_never_rendered_as_zero(string basis) + { + var r = Rec.V2(costBasis: basis, cost: 0m); + Assert.Equal("Not reported", CostText.Cost(r)); + Assert.Equal("Not reported", CostText.CostShort(r)); + Assert.DoesNotContain("$0", CostText.Cost(r), StringComparison.Ordinal); + } + + [Fact] + public void Tokens_are_not_reported_when_usage_was_not_reported() + { + Assert.Equal("Not reported", CostText.Tokens(Rec.V2(usageReported: false, inTok: 0, outTok: 0))); + Assert.Equal("Not reported", CostText.Tokens(Rec.V2(usageReported: null, inTok: 0, outTok: 0))); + Assert.Equal("10 in · 20 out · 30 total", CostText.Tokens(Rec.V2())); + } + + [Fact] + public void Tokens_without_a_provider_call_or_legacy() + { + Assert.Equal("None — no provider call", CostText.Tokens(Rec.Pause())); + Assert.Equal("None — served from cache", CostText.Tokens(Rec.V2(cacheHit: true, attempted: null))); + Assert.Equal("5 in · 7 out · 12 total (legacy record)", CostText.Tokens(Rec.Legacy())); + } +} + +public sealed class RequestFilterTests +{ + private static readonly DateTimeOffset Now = new(2026, 10, 16, 12, 30, 0, TimeSpan.Zero); + + private static List Items() => + [ + Rec.V2(id: "req_aaaa1111", team: "payments", at: Now.AddMinutes(-1)), + Rec.V2("Deny", "Governance", "pause", attempted: null, served: null, costBasis: "no_call", id: "req_bbbb2222", team: "risk", at: Now.AddMinutes(-5)), + Rec.V2(selected: "local-qwen", attempted: "local-qwen", served: "local-qwen", id: "req_cccc3333", team: "risk", at: Now.AddMinutes(-30)), + Rec.V2("Deny", "Unauthenticated", "auth", selected: null, attempted: null, served: null, classificationEvaluated: false, + id: "req_dddd4444", team: "unknown", at: Now.AddHours(-3)), + ]; + + [Fact] + public void No_criteria_returns_everything() + { + Assert.Equal(4, RequestFilter.Apply(Items(), RequestFilterCriteria.None, Now).Count); + Assert.False(RequestFilterCriteria.None.IsActive); + } + + [Fact] + public void Filters_by_outcome_model_team_id_and_window() + { + var items = Items(); + Assert.Equal("req_bbbb2222", Assert.Single(RequestFilter.Apply(items, new RequestFilterCriteria { Outcome = DisplayOutcome.Paused }, Now)).Id); + Assert.Equal("req_cccc3333", Assert.Single(RequestFilter.Apply(items, new RequestFilterCriteria { Model = "LOCAL-QWEN" }, Now)).Id); + Assert.Equal(2, RequestFilter.Apply(items, new RequestFilterCriteria { Team = "risk" }, Now).Count); + Assert.Equal("req_dddd4444", Assert.Single(RequestFilter.Apply(items, new RequestFilterCriteria { IdSearch = "DDDD" }, Now)).Id); + Assert.Equal(2, RequestFilter.Apply(items, new RequestFilterCriteria { Window = TimeWindow.Last15Minutes }, Now).Count); + Assert.Equal(3, RequestFilter.Apply(items, new RequestFilterCriteria { Window = TimeWindow.LastHour }, Now).Count); + } + + [Fact] + public void Model_filter_matches_selected_even_when_nothing_was_served() + { + var hit = RequestFilter.Apply(Items(), new RequestFilterCriteria { Model = "gpt-4o-mini" }, Now); + Assert.Contains(hit, r => r.Id == "req_bbbb2222"); // selected before the pause, never attempted + } + + [Fact] + public void Criteria_combine_and_report_active() + { + var c = new RequestFilterCriteria { Team = "risk", Window = TimeWindow.Last15Minutes }; + Assert.True(c.IsActive); + Assert.Equal("req_bbbb2222", Assert.Single(RequestFilter.Apply(Items(), c, Now)).Id); + Assert.Empty(RequestFilter.Apply(Items(), c with { IdSearch = "zzzz" }, Now)); + } + + [Fact] + public void Options_are_distinct_and_sorted() + { + Assert.Equal(new[] { "gpt-4o-mini", "local-qwen" }, RequestFilter.Models(Items())); + Assert.Equal(new[] { "payments", "risk", "unknown" }, RequestFilter.Teams(Items())); + Assert.Contains(DisplayOutcome.AuthenticationFailed, RequestFilter.Outcomes(Items())); + } +} + +public sealed class SnapshotAndPresetTests +{ + private static readonly DateTimeOffset T0 = new(2026, 10, 16, 9, 0, 0, TimeSpan.Zero); + + [Fact] + public void Snapshot_is_frozen_against_later_form_and_preset_edits() + { + var form = new PlaygroundForm(); + ScenarioPresets.ApplyTo(ScenarioPresets.Find('A')!, form); + var snap = RequestSnapshot.Freeze(1, form, T0); + Assert.True(snap.MatchesForm(form)); + + // Edit the form, then re-fill it from another preset: the snapshot must not move. + form.Prompt = "edited"; + form.Streaming = true; + ScenarioPresets.ApplyTo(ScenarioPresets.Find('B')!, form); + + Assert.Equal(ScenarioPresets.NormalPrompt, snap.Prompt); + Assert.Null(snap.RequestedModel); + Assert.False(snap.Streaming); + Assert.Equal("Scenario A · Permitted request", snap.ScenarioLabel); + Assert.Equal("Request #1 · Scenario A · Permitted request", snap.Title); + Assert.False(snap.MatchesForm(form)); + } + + [Fact] + public void Editing_a_preset_copy_does_not_change_the_catalogue() + { + var a = ScenarioPresets.Find('A')!; + var edited = a with { Prompt = "changed" }; + Assert.NotEqual(edited.Prompt, ScenarioPresets.Find('A')!.Prompt); + Assert.Equal(ScenarioPresets.NormalPrompt, ScenarioPresets.All[0].Prompt); + } + + [Fact] + public void Edited_preset_prompt_is_labelled_custom() + { + var form = new PlaygroundForm(); + ScenarioPresets.ApplyTo(ScenarioPresets.Find('A')!, form); + form.Prompt += " and more"; + var snap = RequestSnapshot.Freeze(2, form, T0); + Assert.Equal("Custom", snap.ScenarioLabel); + Assert.Null(snap.Scenario); + } + + [Fact] + public void Scenario_B_requests_the_unapproved_test_model_and_A_lets_policy_choose() + { + var form = new PlaygroundForm(); + ScenarioPresets.ApplyTo(ScenarioPresets.Find("b")!, form); + var b = RequestSnapshot.Freeze(1, form, T0); + Assert.Equal("gpt-4-unapproved-test", b.RequestedModel); + Assert.Equal("gpt-4-unapproved-test", b.RoutingLabel); + + ScenarioPresets.ApplyTo(ScenarioPresets.Find('A')!, form); + var a = RequestSnapshot.Freeze(2, form, T0); + Assert.Null(a.RequestedModel); + Assert.Equal("Let policy choose", a.RoutingLabel); + } + + [Fact] + public void Scenario_D_appends_a_fresh_nonce_on_every_run() + { + var form = new PlaygroundForm(); + ScenarioPresets.ApplyTo(ScenarioPresets.Find('D')!, form); + var one = RequestSnapshot.Freeze(1, form, T0); + var two = RequestSnapshot.Freeze(2, form, T0); + + Assert.NotEqual(one.Prompt, two.Prompt); + Assert.StartsWith(ScenarioPresets.NormalPrompt + " [run ", one.Prompt, StringComparison.Ordinal); + Assert.Equal(ScenarioPresets.NormalPrompt, one.BasePrompt); + Assert.Equal("Scenario D · Pause and resume", one.ScenarioLabel); + Assert.True(one.MatchesForm(form)); // the nonce is not a form change + + var nonces = Enumerable.Range(0, 200).Select(_ => ScenarioPresets.NewNonce()).ToHashSet(); + Assert.Equal(200, nonces.Count); + } + + [Fact] + public void Form_problems_block_run() + { + var form = new PlaygroundForm(); + Assert.NotNull(form.Problem); + form.Prompt = "hi"; + Assert.Null(form.Problem); + form.Mode = RouteMode.Explicit; + Assert.NotNull(form.Problem); + form.ExplicitModel = " "; + Assert.NotNull(form.Problem); + form.ExplicitModel = "x"; + Assert.Null(form.Problem); + form.MaxTokens = 0; + Assert.NotNull(form.Problem); + } + + // The presets must exercise the real classifier the way their labels claim. + private static DataClassification Classify(string text) => new RegexDataClassifier().Classify( + new InferenceRequest("tester", [new ChatMessage(ChatRole.User, text)], null, new AttributionTags("t", "w", "u"))).Classification; + + [Fact] + public void Scenario_C_and_the_connection_test_trigger_the_PII_classifier() + { + Assert.Equal(DataClassification.Pii, Classify(ScenarioPresets.SensitivePrompt)); + Assert.Equal(DataClassification.Pii, Classify(ConnectionLogic.GovernedTestPrompt())); + } + + [Fact] + public void Scenarios_A_B_D_are_not_sensitive() + { + var form = new PlaygroundForm(); + ScenarioPresets.ApplyTo(ScenarioPresets.Find('D')!, form); + Assert.Equal(DataClassification.Internal, Classify(ScenarioPresets.NormalPrompt)); + Assert.Equal(DataClassification.Internal, Classify(RequestSnapshot.Freeze(1, form, T0).Prompt)); + } +} + +public sealed class ConnectionLogicTests +{ + [Theory] + [InlineData("http://Ollama-Host:11434/v1/", "http://ollama-host:11434/v1")] + [InlineData("http://10.0.0.5:11434/v1", "http://10.0.0.5:11434/v1")] + [InlineData("http://localhost/v1", "http://localhost:80/v1")] + public void Normalize_matches_the_catalog_shape(string raw, string expected) + => Assert.Equal(expected, ConnectionLogic.Normalize(raw)); + + [Theory] + [InlineData("")] + [InlineData("ollama:11434")] + [InlineData("ftp://host:21/")] + [InlineData("http://user:pw@host:11434/v1")] + [InlineData("http://host:11434/v1?x=1")] + public void Endpoint_problems_are_reported(string raw) => Assert.NotNull(ConnectionLogic.EndpointProblem(raw)); + + [Fact] + 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() + { + Mode = "cloud", + Local = new LocalRouteInfo { Configured = configured, Endpoint = endpoint, ModelId = model, Registered = registered }, + }; + + [Fact] + public void Applied_check_needs_same_endpoint_exact_tag_and_server_registration() + { + 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); + } + + [Fact] + public void Config_block_has_names_and_values_but_no_secret() + { + 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); + + var cloud = ConnectionLogic.ConfigBlock("http://ollama-host:11434/v1", "qwen3:8b", localOnly: false); + Assert.DoesNotContain("\nProviders__Mode=local-only", "\n" + cloud, StringComparison.Ordinal); + } + + [Fact] + public void Route_review_text_depends_on_mode() + { + 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); + } + + [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_credentials_only_from_the_fragment() + { + 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); + + 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")); + } +} diff --git a/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs b/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs new file mode 100644 index 0000000..834bffa --- /dev/null +++ b/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs @@ -0,0 +1,723 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.Json; +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 Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// Shared helpers for the ADR-0009 host-level tests (correlation id ⇄ audit record). +internal static class CorrelationTestKit +{ + public const string AdminToken = "test-admin"; + public const string Header = "X-Covenant-Request-Id"; + + public static StringContent Chat(string content, bool stream = false, string? model = null) => + new($"{{{(model is null ? "" : $"\"model\":\"{model}\",")}\"stream\":{(stream ? "true" : "false")},\"messages\":[{{\"role\":\"user\",\"content\":\"{content}\"}}]}}", + Encoding.UTF8, "application/json"); + + public static string HeaderId(HttpResponseMessage resp) + { + Assert.True(resp.Headers.TryGetValues(Header, out var values), $"missing {Header} on HTTP {(int)resp.StatusCode}"); + var id = Assert.Single(values!); + Assert.True(RequestCorrelation.IsWellFormed(id), $"malformed correlation id '{id}'"); + Assert.StartsWith("req_", id); + return id; + } + + public static HttpRequestMessage Admin(HttpMethod method, string path) + { + var req = new HttpRequestMessage(method, path); + req.Headers.Add("X-Covenant-Admin-Token", AdminToken); + return req; + } + + /// Polls the exact lookup (the sink is asynchronous) — never sleeps a fixed time. + public static async Task LookupAsync(HttpClient client, string id) + { + for (int i = 0; i < 200; i++) + { + using var resp = await client.SendAsync(Admin(HttpMethod.Get, $"/admin/requests/{id}")); + if (resp.StatusCode == HttpStatusCode.OK) + { + var entry = JsonSerializer.Deserialize(await resp.Content.ReadAsStringAsync(), AuditJsonContext.Default.AuditEntry); + Assert.NotNull(entry); + return entry!; + } + Assert.Equal(HttpStatusCode.NotFound, resp.StatusCode); + await Task.Delay(25); + } + throw new Xunit.Sdk.XunitException($"audit record {id} never appeared"); + } + + public static string ReadShared(string path) + { + if (!File.Exists(path)) return ""; + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var reader = new StreamReader(fs); + return reader.ReadToEnd(); + } + + public static void DeleteWithSiblings(string path) + { + foreach (var f in Directory.GetFiles(Path.GetDirectoryName(path)!, Path.GetFileName(path) + "*")) + File.Delete(f); + } +} + +/// Scripted provider for host tests. Prompt markers select behaviour: "FAIL-UPSTREAM" throws on +/// the buffered call; "FAIL-MIDSTREAM" streams one delta then throws. Everything else is served with usage. +internal sealed class ScriptedChatClient : MEAI.IChatClient +{ + private int _calls; + public int Calls => Volatile.Read(ref _calls); + + private static string Prompt(IEnumerable messages) => string.Join("\n", messages.Select(m => m.Text)); + + public Task GetResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _calls); + if (Prompt(messages).Contains("FAIL-UPSTREAM", StringComparison.Ordinal)) + throw new HttpRequestException("simulated upstream 503"); + return Task.FromResult(new MEAI.ChatResponse(new MEAI.ChatMessage(MEAI.ChatRole.Assistant, "scripted reply")) + { Usage = new MEAI.UsageDetails { InputTokenCount = 7, OutputTokenCount = 3 } }); + } + + public async IAsyncEnumerable GetStreamingResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _calls); + bool fail = Prompt(messages).Contains("FAIL-MIDSTREAM", StringComparison.Ordinal); + await Task.Yield(); + yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, "partial "); + 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 })] }; + } + + public object? GetService(Type serviceType, object? serviceKey = null) => null; + public void Dispose() { } +} + +/// ADR-0009 / Task 02: one server-generated id per /v1 request, equal across header, body and +/// audit record, for every outcome the Host can produce; exact admin-only lookup. +public sealed class CorrelationAndEvidenceTests : IClassFixture +{ + public sealed class Factory : WebApplicationFactory + { + public readonly string AuditPath = Path.Combine(Path.GetTempPath(), $"covenant-corr-{Guid.NewGuid():n}.log"); + internal readonly ScriptedChatClient Provider = new(); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Production"); + builder.UseSetting("OpenAI:ApiKey", "unused-stubbed"); + builder.UseSetting("Admin:Token", CorrelationTestKit.AdminToken); + builder.UseSetting("Budget:GlobalCapUsd", "100"); + 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); + // No Local:* → PII routes to the unconfigured local placeholder and fails closed. + builder.ConfigureTestServices(services => + services.AddSingleton(new ChatClientRegistry( + new Dictionary + { + ["openai:gpt-4o-mini"] = Provider, + ["openai:gpt-4o"] = Provider, + }))); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + CorrelationTestKit.DeleteWithSiblings(AuditPath); + } + } + + private readonly Factory _factory; + private readonly HttpClient _client; // with application key + private readonly HttpClient _anon; // no credentials at all + + public CorrelationAndEvidenceTests(Factory factory) + { + _factory = factory; + _client = factory.CreateClient(); + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "k"); + _anon = factory.CreateClient(); + } + + private static string BodyString(JsonElement root, string name) => root.GetProperty(name).GetString()!; + + [Fact] + public async Task Buffered_200_header_equals_body_id_equals_audit_record() + { + var resp = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("a normal internal question")); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal(id, BodyString(doc.RootElement, "id")); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal(id, e.Id); + Assert.Equal(id, e.CorrelationId); + Assert.Equal(2, e.SchemaVersion); + Assert.Equal(PolicyEffect.Allow, e.Effect); + Assert.Null(e.DenialKind); + Assert.Null(e.StoppedAtStage); + Assert.True(e.ClassificationEvaluated); + Assert.Equal("gpt-4o-mini", e.SelectedModel); + Assert.Equal("gpt-4o-mini", e.AttemptedModel); + Assert.Equal("gpt-4o-mini", e.ServedByModel); + Assert.False(e.Stream); + Assert.True(e.UsageReported); + Assert.Equal("reported", e.CostBasis); + } + + [Fact] + public async Task Anthropic_message_id_is_the_correlation_id() + { + using var aclient = _factory.CreateClient(); + aclient.DefaultRequestHeaders.Add("x-api-key", "k"); + var resp = await aclient.PostAsync("/v1/messages", new StringContent( + "{\"model\":\"gpt-4o-mini\",\"max_tokens\":20,\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}]}", + Encoding.UTF8, "application/json")); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal(id, BodyString(doc.RootElement, "id")); + Assert.Equal(id, (await CorrelationTestKit.LookupAsync(_client, id)).Id); + } + + [Fact] + public async Task Auth_denial_401_is_correlated_and_classification_is_not_evaluated() + { + var resp = await _anon.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("no key here")); + Assert.Equal(HttpStatusCode.Unauthorized, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal(id, BodyString(doc.RootElement, "request_id")); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.Equal("Unauthenticated", e.DenialKind); + Assert.Equal("auth", e.StoppedAtStage); + Assert.False(e.ClassificationEvaluated); // never ran ... + Assert.Equal(DataClassification.Phi, e.Classification); // ... restrictive enforcement default kept + Assert.Null(e.SelectedModel); + Assert.Null(e.AttemptedModel); + Assert.Null(e.UsageReported); + Assert.Equal("no_call", e.CostBasis); + Assert.Equal(0m, e.Usage.CostUsd); + } + + [Fact] + public async Task Policy_denial_403_for_unapproved_model_stops_at_policy() + { + var resp = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("hello", model: "not-an-approved-model")); + Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal(id, BodyString(doc.RootElement, "request_id")); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal("Governance", e.DenialKind); + Assert.Equal("policy", e.StoppedAtStage); + Assert.True(e.ClassificationEvaluated); + Assert.Equal(DataClassification.Internal, e.Classification); + Assert.Null(e.AttemptedModel); + Assert.Equal("no_call", e.CostBasis); + } + + [Fact] + public async Task Pause_403_stops_at_pause_without_calling_the_provider() + { + using (var engage = CorrelationTestKit.Admin(HttpMethod.Post, "/admin/kill-switch")) + { + engage.Content = new StringContent("{\"engaged\":true,\"reason\":\"pause test\"}", Encoding.UTF8, "application/json"); + Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync(engage)).StatusCode); + } + try + { + int callsBefore = _factory.Provider.Calls; + var resp = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("while paused")); + Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal(id, BodyString(doc.RootElement, "request_id")); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal("Governance", e.DenialKind); + Assert.Equal("pause", e.StoppedAtStage); + Assert.Equal("gpt-4o-mini", e.SelectedModel); // policy chose it ... + Assert.Null(e.AttemptedModel); // ... but no call was started + Assert.Equal("no_call", e.CostBasis); + Assert.Equal(callsBefore, _factory.Provider.Calls); + } + finally + { + using var release = CorrelationTestKit.Admin(HttpMethod.Post, "/admin/kill-switch"); + release.Content = new StringContent("{\"engaged\":false}", Encoding.UTF8, "application/json"); + await _client.SendAsync(release); + } + } + + [Fact] + public async Task Missing_local_adapter_403_selected_but_never_attempted() + { + 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); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal(id, BodyString(doc.RootElement, "request_id")); + + 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.Null(e.AttemptedModel); + Assert.Null(e.ServedByModel); + Assert.Equal("no_call", e.CostBasis); + } + + [Fact] + public async Task Upstream_failure_502_is_attempted_and_charged_an_estimate() + { + var resp = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("FAIL-UPSTREAM please")); + Assert.Equal(HttpStatusCode.BadGateway, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal(id, BodyString(doc.RootElement, "request_id")); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.Equal("UpstreamFailure", e.DenialKind); + Assert.Equal("provider", e.StoppedAtStage); + Assert.Equal("gpt-4o-mini", e.AttemptedModel); + Assert.Null(e.ServedByModel); + Assert.False(e.UsageReported); + Assert.Equal("estimated_failed_call", e.CostBasis); + Assert.True(e.Usage.CostUsd > 0m); + } + + [Fact] + public async Task Mid_stream_failure_keeps_http_200_but_records_a_failed_outcome() + { + var resp = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("FAIL-MIDSTREAM now", stream: true)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); // transport already committed + Assert.Equal("text/event-stream", resp.Content.Headers.ContentType?.MediaType); + var id = CorrelationTestKit.HeaderId(resp); + + var body = await resp.Content.ReadAsStringAsync(); + bool sawError = false, sawChunk = false; + foreach (var line in body.Split('\n')) + { + if (!line.StartsWith("data: ", StringComparison.Ordinal)) continue; + var payload = line["data: ".Length..].Trim(); + if (payload == "[DONE]") continue; + using var ev = JsonDocument.Parse(payload); + if (ev.RootElement.TryGetProperty("error", out var err)) + { + sawError = true; + Assert.Equal("upstream_error", err.GetString()); + Assert.Equal(id, BodyString(ev.RootElement, "request_id")); + } + else + { + sawChunk = true; + Assert.Equal(id, BodyString(ev.RootElement, "id")); + } + } + Assert.True(sawChunk); + Assert.True(sawError); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.Equal("UpstreamFailure", e.DenialKind); + Assert.Equal("gpt-4o-mini", e.AttemptedModel); + Assert.True(e.Stream); + Assert.Equal("estimated_failed_call", e.CostBasis); + } + + [Fact] + public async Task Malformed_json_is_400_with_header_and_no_audit_record() + { + var bad = await _client.PostAsync("/v1/chat/completions", + new StringContent("{not json", Encoding.UTF8, "application/json")); + Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); + var badId = CorrelationTestKit.HeaderId(bad); + + // A later request's record proves the (FIFO, single-reader) sink has drained everything before it. + var good = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("after the bad one")); + var goodId = CorrelationTestKit.HeaderId(good); + await CorrelationTestKit.LookupAsync(_client, goodId); + + Assert.DoesNotContain(badId, CorrelationTestKit.ReadShared(_factory.AuditPath)); + using var lookup = await _client.SendAsync(CorrelationTestKit.Admin(HttpMethod.Get, $"/admin/requests/{badId}")); + Assert.Equal(HttpStatusCode.NotFound, lookup.StatusCode); + } + + [Fact] + public async Task Twenty_concurrent_identical_prompts_resolve_to_their_own_records() + { + var responses = await Task.WhenAll(Enumerable.Range(0, 20) + .Select(_ => _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("identical concurrent prompt")))); + var ids = responses.Select(r => { Assert.Equal(HttpStatusCode.OK, r.StatusCode); return CorrelationTestKit.HeaderId(r); }).ToList(); + Assert.Equal(20, ids.Distinct(StringComparer.Ordinal).Count()); + + var entries = await Task.WhenAll(ids.Select(id => CorrelationTestKit.LookupAsync(_client, id))); + for (int i = 0; i < ids.Count; i++) Assert.Equal(ids[i], entries[i].Id); + Assert.Single(entries.Select(e => e.PromptSha256).Distinct()); // same content — joined by id, never by content + } + + [Fact] + public async Task Lookup_and_list_are_admin_only() + { + Assert.Equal(HttpStatusCode.Unauthorized, (await _anon.GetAsync("/admin/requests/req_0123")).StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, (await _anon.GetAsync("/admin/requests")).StatusCode); + // An application key is not an admin token. + Assert.Equal(HttpStatusCode.Unauthorized, (await _client.GetAsync("/admin/requests/req_0123")).StatusCode); + } + + [Theory] + [InlineData("has.dot")] + [InlineData("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")] // 65 chars + public async Task Malformed_lookup_id_is_400(string id) + { + using var resp = await _client.SendAsync(CorrelationTestKit.Admin(HttpMethod.Get, $"/admin/requests/{id}")); + Assert.Equal(HttpStatusCode.BadRequest, resp.StatusCode); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal("invalid_id", BodyString(doc.RootElement, "error")); + } + + [Fact] + public async Task Unknown_id_is_404_with_scanned_count() + { + using var resp = await _client.SendAsync(CorrelationTestKit.Admin(HttpMethod.Get, $"/admin/requests/req_{Guid.NewGuid():n}")); + Assert.Equal(HttpStatusCode.NotFound, resp.StatusCode); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal("not_found", BodyString(doc.RootElement, "error")); + Assert.True(doc.RootElement.GetProperty("scanned").GetInt32() >= 0); + } + + private async Task ListAsync(string query) + { + using var resp = await _client.SendAsync(CorrelationTestKit.Admin(HttpMethod.Get, "/admin/requests" + query)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + return JsonSerializer.Deserialize(await resp.Content.ReadAsStringAsync(), AuditJsonContext.Default.RequestsPage)!; + } + + [Fact] + public async Task Request_list_is_newest_first_and_limit_is_clamped() + { + var a = CorrelationTestKit.HeaderId(await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("list A"))); + await CorrelationTestKit.LookupAsync(_client, a); + var b = CorrelationTestKit.HeaderId(await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("list B"))); + await CorrelationTestKit.LookupAsync(_client, b); + + var two = await ListAsync("?limit=2"); + Assert.Equal(2, two.Items.Count); + Assert.Equal(b, two.Items[0].Id); + Assert.Equal(a, two.Items[1].Id); + Assert.True(two.Segment.ChainValid); + Assert.True(two.Segment.Entries >= 2); + + Assert.Single((await ListAsync("?limit=0")).Items); // clamped up to 1 + Assert.Single((await ListAsync("?limit=-5")).Items); + var big = await ListAsync("?limit=1000000"); // clamped down to 1000 + Assert.True(big.Items.Count <= 1000); + Assert.Equal(Math.Min(big.Segment.Entries, 1000), big.Items.Count); + } + + [Fact] + public async Task Records_never_contain_prompt_content_without_preview_opt_in() + { + var marker = $"zebra-secret-{Guid.NewGuid():n}"; + var resp = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat($"please keep {marker} private")); + var id = CorrelationTestKit.HeaderId(resp); + var e = await CorrelationTestKit.LookupAsync(_client, id); + + Assert.Null(e.PromptPreview); + Assert.DoesNotContain(marker, JsonSerializer.Serialize(e, AuditJsonContext.Default.AuditEntry)); + Assert.DoesNotContain(marker, CorrelationTestKit.ReadShared(_factory.AuditPath)); + using var list = await _client.SendAsync(CorrelationTestKit.Admin(HttpMethod.Get, "/admin/requests")); + Assert.DoesNotContain(marker, await list.Content.ReadAsStringAsync()); + } +} + +/// Rate-limited 429 is correlated. Own host: a global cap of 1/min would starve the other suite. +public sealed class CorrelationRateLimitTests : IClassFixture +{ + public sealed class Factory : WebApplicationFactory + { + public readonly string AuditPath = Path.Combine(Path.GetTempPath(), $"covenant-corr-rl-{Guid.NewGuid():n}.log"); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Production"); + builder.UseSetting("OpenAI:ApiKey", "unused-stubbed"); + builder.UseSetting("Admin:Token", CorrelationTestKit.AdminToken); + builder.UseSetting("Budget:GlobalCapUsd", "100"); + 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); + builder.UseSetting("RateLimit:GlobalPerMinute", "1"); + builder.ConfigureTestServices(services => + services.AddSingleton(new ChatClientRegistry( + new Dictionary { ["openai"] = new ScriptedChatClient() }))); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + CorrelationTestKit.DeleteWithSiblings(AuditPath); + } + } + + private readonly HttpClient _client; + + public CorrelationRateLimitTests(Factory factory) + { + _client = factory.CreateClient(); + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "k"); + } + + [Fact] + public async Task Rate_limited_429_is_correlated_and_stops_at_rate_limit() + { + // Cap 1/min: at most one minute boundary can fall inside the burst, so a 429 must appear within 3. + HttpResponseMessage? limited = null; + for (int i = 0; i < 3 && limited is null; i++) + { + var r = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat($"burst {i}")); + if (r.StatusCode == HttpStatusCode.TooManyRequests) limited = r; + } + Assert.NotNull(limited); + var id = CorrelationTestKit.HeaderId(limited!); + using var doc = JsonDocument.Parse(await limited!.Content.ReadAsStringAsync()); + Assert.Equal(id, doc.RootElement.GetProperty("request_id").GetString()); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal("RateLimited", e.DenialKind); + Assert.Equal("rate_limit", e.StoppedAtStage); + Assert.Null(e.AttemptedModel); + Assert.Equal("no_call", e.CostBasis); + } +} + +/// Cancellation is evidence (ADR-0009 §3): the record is written even though the request token +/// is cancelled, and a started call is charged an estimate — never a silent $0. +public sealed class CancellationEvidenceTests +{ + private sealed class HangingChatClient : MEAI.IChatClient + { + public readonly TaskCompletionSource Started = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public async Task GetResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, CancellationToken cancellationToken = default) + { + Started.TrySetResult(); + await Task.Delay(Timeout.Infinite, cancellationToken); + throw new InvalidOperationException("unreachable: the delay only ends by cancellation"); + } + + public IAsyncEnumerable GetStreamingResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public object? GetService(Type serviceType, object? serviceKey = null) => null; + public void Dispose() { } + } + + /// Provider-side timeout: an OperationCanceledException the CALLER did not request. + private sealed class ProviderTimeoutChatClient : MEAI.IChatClient + { + public Task GetResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, CancellationToken cancellationToken = default) + => throw new TaskCanceledException("The request was canceled due to the configured HttpClient.Timeout"); + + public IAsyncEnumerable GetStreamingResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public object? GetService(Type serviceType, object? serviceKey = null) => null; + public void Dispose() { } + } + + /// Refuses any cancellable token: proves the audit stage enqueues with CancellationToken.None. + private sealed class StrictSink : IAuditSink + { + public List Entries { get; } = []; + public ValueTask EnqueueAsync(AuditEntry entry, CancellationToken cancellationToken = default) + { + if (cancellationToken.CanBeCanceled) + throw new InvalidOperationException("audit enqueue must not use the (cancellable) request token"); + lock (Entries) Entries.Add(entry); + return ValueTask.CompletedTask; + } + } + + private static InferencePipeline Build(IAuditSink sink, MEAI.IChatClient client, ISpendLedger ledger) + { + var prices = new PriceBook(new Dictionary { ["gpt-4o-mini"] = (0.01m, 0.03m) }); + var policy = new PolicyConfig + { + AllowedRoutes = new Dictionary> + { + [DataClassification.Internal] = [new("openai", "gpt-4o-mini")], + } + }; + return new InferencePipeline( + [ + new AuditStage(sink), + new AuthStage(new AuthConfig { AllowAnonymous = true, Keys = [] }), + new ClassifyStage(new RegexDataClassifier()), + new PolicyStage(new PolicyEngine(policy)), + new BudgetStage(new KillSwitch(), ledger, new BudgetConfig { GlobalCapUsd = 1_000m }, prices), + new ProviderCallStage(new ChatClientRegistry(new Dictionary { ["openai"] = client })), + new AttributionStage(prices), + ]); + } + + private static InferenceContext Ctx(string content) => + new(new InferenceRequest("tester", [new ChatMessage(ChatRole.User, content)], null, + new AttributionTags("team-c", "wf", "uc"), RequestId: $"req_{Guid.NewGuid():n}")); + + [Fact] + public async Task Cancelled_request_still_produces_exactly_one_charged_record() + { + var sink = new StrictSink(); + var client = new HangingChatClient(); + var ledger = new InMemorySpendLedger(); + var pipeline = Build(sink, client, ledger); + var prompt = new string('x', 400); // 100 estimated input tokens + var ctx = Ctx(prompt); + + using var cts = new CancellationTokenSource(); + var run = pipeline.ExecuteAsync(ctx, cts.Token); + await client.Started.Task; // the provider call is genuinely in flight + cts.Cancel(); + await Assert.ThrowsAnyAsync(() => run); + + var e = Assert.Single(sink.Entries); + Assert.Equal(ctx.Request.RequestId, e.Id); + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.Equal("Cancelled", e.DenialKind); + Assert.Equal("provider", e.StoppedAtStage); + Assert.Equal("gpt-4o-mini", e.AttemptedModel); + Assert.Equal("estimated_failed_call", e.CostBasis); + Assert.Equal(100 / 1000m * 0.01m, e.Usage.CostUsd); // input estimate, no output streamed + Assert.True(e.Usage.CostUsd > 0m); + Assert.Equal(e.Usage.CostUsd, ledger.GlobalSpendUsd); // and it counts against the budget + } + + [Fact] + public async Task Provider_side_timeout_is_an_upstream_failure_not_a_cancellation() + { + var sink = new StrictSink(); + var pipeline = Build(sink, new ProviderTimeoutChatClient(), new InMemorySpendLedger()); + var ctx = Ctx("time me out"); + + await pipeline.ExecuteAsync(ctx, CancellationToken.None); // governed refusal, no exception escapes + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + var e = Assert.Single(sink.Entries); + Assert.Equal("UpstreamFailure", e.DenialKind); + Assert.Equal("estimated_failed_call", e.CostBasis); + } +} + +/// Audit v2 is additive and hash-compatible (ADR-0009 §2): a TRUE legacy (v1) chain — no v2 keys in +/// the stored bytes — keeps verifying (with anchors) after v2 entries are appended; replay stays correct. +public sealed class LegacyAuditCompatibilityTests : IDisposable +{ + private readonly string _log = Path.Combine(Path.GetTempPath(), $"covenant-legacy-{Guid.NewGuid():n}.log"); + private readonly string _anchors = Path.Combine(Path.GetTempPath(), $"covenant-legacy-{Guid.NewGuid():n}.anchors"); + + public void Dispose() + { + CorrelationTestKit.DeleteWithSiblings(_log); + CorrelationTestKit.DeleteWithSiblings(_anchors); + } + + // Exactly the v1 shape the pre-ADR-0009 sink wrote (no SchemaVersion/CorrelationId/... keys). + private static readonly string[] LegacyContents = + [ + """{"Id":"0f8fad5bd9cb469fa16570867728950e","TimestampUtc":"2026-09-01T10:00:00+00:00","Principal":"alice","Tags":{"Team":"legacy-team","Workflow":"wf","UseCase":"uc"},"Classification":"Internal","Effect":"Allow","Reason":"allowed","ServedByModel":"gpt-4o-mini","Usage":{"InputTokens":100,"OutputTokens":50,"CostUsd":0.002,"TotalTokens":150},"DurationMs":12.5,"PromptChars":40,"PromptSha256":"abc","Signal":null,"PromptPreview":null,"CacheHit":false}""", + """{"Id":"7c9e6679742540de944be07fc1f90ae7","TimestampUtc":"2026-09-01T10:01:00+00:00","Principal":"bob","Tags":{"Team":"legacy-team","Workflow":"wf","UseCase":"uc"},"Classification":"Pii","Effect":"Deny","Reason":"no adapter registered for 'local:llama-3.1-8b-instruct'","ServedByModel":null,"Usage":{"InputTokens":0,"OutputTokens":0,"CostUsd":0,"TotalTokens":0},"DurationMs":1,"PromptChars":20,"PromptSha256":"def","Signal":"US SSN pattern","PromptPreview":null,"CacheHit":false}""", + ]; + + [Fact] + public async Task Legacy_chain_plus_v2_entries_verifies_replays_and_reads_v2_fields_as_null() + { + // Hand-write the legacy chain exactly as the old sink did. + var previous = AuditChain.GenesisHash; + var legacyLines = new List(); + foreach (var content in LegacyContents) + { + var hash = AuditChain.Hash(previous, content); + legacyLines.Add($"{previous}{AuditChain.Separator}{hash}{AuditChain.Separator}{content}"); + previous = hash; + } + await File.WriteAllTextAsync(_log, string.Join(Environment.NewLine, legacyLines) + Environment.NewLine); + + // Append v2 entries through the real sink, anchoring every entry from here on. + var sink = new FileAuditSink(_log, _anchors, anchorEvery: 1); + await sink.StartAsync(CancellationToken.None); + await sink.EnqueueAsync(new AuditEntry("req_v2a", DateTimeOffset.Parse("2026-10-16T09:00:00Z"), "carol", + new AttributionTags("v2-team", "wf", "uc"), DataClassification.Internal, PolicyEffect.Deny, "provider 'openai' call failed", + null, new Usage(0, 0, 0.01m), SchemaVersion: 2, CorrelationId: "req_v2a", ClassificationEvaluated: true, + DenialKind: "UpstreamFailure", StoppedAtStage: "provider", SelectedModel: "gpt-4o-mini", AttemptedModel: "gpt-4o-mini", + Stream: false, UsageReported: false, CostBasis: "estimated_failed_call")); + await sink.EnqueueAsync(new AuditEntry("req_v2b", DateTimeOffset.Parse("2026-10-16T09:01:00Z"), "carol", + new AttributionTags("v2-team", "wf", "uc"), DataClassification.Internal, PolicyEffect.Allow, "allowed", + "gpt-4o-mini", new Usage(10, 5, 0.0005m), SchemaVersion: 2, CorrelationId: "req_v2b", ClassificationEvaluated: true, + SelectedModel: "gpt-4o-mini", AttemptedModel: "gpt-4o-mini", Stream: false, UsageReported: true, CostBasis: "reported")); + await sink.StopAsync(CancellationToken.None); // drains + + // Legacy bytes untouched (history is never rewritten). + var lines = File.ReadAllLines(_log).Where(l => l.Length > 0).ToList(); + Assert.Equal(4, lines.Count); + Assert.Equal(legacyLines[0], lines[0]); + Assert.Equal(legacyLines[1], lines[1]); + + var (verification, entries) = AuditChainVerifier.VerifyAndRead(_log, _anchors); + Assert.True(verification.Valid, verification.Failure); + Assert.Equal(4, verification.EntryCount); + Assert.Equal(2, File.ReadAllLines(_anchors).Count(l => l.Length > 0)); + + foreach (var legacy in entries.Take(2)) + { + Assert.Null(legacy.SchemaVersion); + Assert.Null(legacy.CorrelationId); + Assert.Null(legacy.ClassificationEvaluated); + Assert.Null(legacy.DenialKind); + Assert.Null(legacy.StoppedAtStage); + Assert.Null(legacy.SelectedModel); + Assert.Null(legacy.AttemptedModel); + Assert.Null(legacy.Stream); + Assert.Null(legacy.UsageReported); + Assert.Null(legacy.CostBasis); + } + Assert.Equal(2, entries[2].SchemaVersion); + Assert.Equal("estimated_failed_call", entries[2].CostBasis); + + var ledger = new InMemorySpendLedger(); + 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 + + var report = EvidenceExport.Build(_log, TimeProvider.System, _anchors); + Assert.True(report.ChainValid); + Assert.True(report.AnchorConfigured); + Assert.Equal(2, report.AnchorCount); + } +} diff --git a/tests/Covenant.Tests/Covenant.Tests.csproj b/tests/Covenant.Tests/Covenant.Tests.csproj index 9c50f2d..6ca31a8 100644 --- a/tests/Covenant.Tests/Covenant.Tests.csproj +++ b/tests/Covenant.Tests/Covenant.Tests.csproj @@ -25,4 +25,12 @@ + + + + + + diff --git a/tests/Covenant.Tests/LocalOnlyModeTests.cs b/tests/Covenant.Tests/LocalOnlyModeTests.cs new file mode 100644 index 0000000..3cc5200 --- /dev/null +++ b/tests/Covenant.Tests/LocalOnlyModeTests.cs @@ -0,0 +1,226 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; +using Covenant.Adapters; +using Covenant.Host; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// ADR-0010: Providers:Mode=local-only starts with no cloud credential, routes every +/// classification to the one approved local model, and never reaches a cloud client. +public sealed class LocalOnlyModeTests : IClassFixture +{ + private const string Tag = "qwen3:8b"; + + public sealed class Factory : WebApplicationFactory + { + public readonly string AuditPath = Path.Combine(Path.GetTempPath(), $"covenant-localonly-{Guid.NewGuid():n}.log"); + internal readonly ScriptedChatClient LocalClient = new(); + internal readonly ScriptedChatClient CloudTripwire = new(); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Production"); + // Neutralize any developer-shell cloud keys (env vars): local-only refuses them by design. + builder.UseSetting("OpenAI:ApiKey", ""); + builder.UseSetting("Anthropic:ApiKey", ""); + builder.UseSetting("Providers:Mode", "local-only"); + builder.UseSetting("Local:Endpoint", "http://127.0.0.1:11434/v1"); + builder.UseSetting("Local:ModelId", Tag); + builder.UseSetting("Admin:Token", CorrelationTestKit.AdminToken); + builder.UseSetting("Budget:GlobalCapUsd", "10"); + 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); + // 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( + new Dictionary + { + [$"local:{Tag}"] = LocalClient, + ["openai:gpt-4o-mini"] = CloudTripwire, + ["openai:gpt-4o"] = CloudTripwire, + ["openai"] = CloudTripwire, + }))); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + CorrelationTestKit.DeleteWithSiblings(AuditPath); + } + } + + private readonly Factory _factory; + private readonly HttpClient _client; + + public LocalOnlyModeTests(Factory factory) + { + _factory = factory; + _client = factory.CreateClient(); + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "k"); + } + + [Fact] + public async Task Starts_without_a_cloud_key_and_reports_local_only_mode() + { + using var resp = await _client.SendAsync(CorrelationTestKit.Admin(HttpMethod.Get, "/admin/status")); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal("local-only", doc.RootElement.GetProperty("mode").GetString()); + foreach (var route in doc.RootElement.GetProperty("routes").EnumerateArray()) + Assert.Equal("local", route.GetProperty("adapter").GetString()); + } + + [Theory] + [InlineData("a normal internal question")] + [InlineData("my ssn is 123-45-6789")] // PII: local, never cloud + [InlineData("patient id 42, diagnosis pending")] // PHI + public async Task Every_classification_is_served_locally_and_never_by_cloud(string prompt) + { + int cloudBefore = _factory.CloudTripwire.Calls; + var resp = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat(prompt)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal(Tag, doc.RootElement.GetProperty("model").GetString()); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal(Tag, e.SelectedModel); + Assert.Equal(Tag, e.AttemptedModel); + Assert.Equal(Tag, e.ServedByModel); + Assert.Equal("zero_priced", e.CostBasis); + Assert.Equal(cloudBefore, _factory.CloudTripwire.Calls); + } + + [Fact] + public async Task Requesting_a_cloud_model_is_denied_not_rerouted() + { + int cloudBefore = _factory.CloudTripwire.Calls; + var resp = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("hello", model: "gpt-4o-mini")); + Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); + var e = await CorrelationTestKit.LookupAsync(_client, CorrelationTestKit.HeaderId(resp)); + Assert.Equal("policy", e.StoppedAtStage); + Assert.Equal(cloudBefore, _factory.CloudTripwire.Calls); + } + + [Fact] + public async Task Catalog_shows_local_only_registered_local_and_no_cloud_models() + { + using var resp = await _client.SendAsync(CorrelationTestKit.Admin(HttpMethod.Get, "/admin/catalog")); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + var root = doc.RootElement; + + Assert.Equal("local-only", root.GetProperty("mode").GetString()); + var local = root.GetProperty("local"); + Assert.True(local.GetProperty("configured").GetBoolean()); + Assert.True(local.GetProperty("registered").GetBoolean()); + Assert.Equal(Tag, local.GetProperty("model_id").GetString()); + Assert.Equal("http://127.0.0.1:11434/v1", local.GetProperty("endpoint").GetString()); + + var models = root.GetProperty("models").EnumerateArray().ToList(); + Assert.NotEmpty(models); + Assert.All(models, m => Assert.Equal("local", m.GetProperty("adapter").GetString())); + Assert.DoesNotContain(models, m => m.GetProperty("adapter").GetString() == "openai"); + var model = Assert.Single(models); + Assert.Equal(Tag, model.GetProperty("model_id").GetString()); + Assert.True(model.GetProperty("registered").GetBoolean()); + Assert.Equal("zero", model.GetProperty("price_basis").GetString()); + } + + [Fact] + public async Task Model_listing_exposes_only_the_local_tag() + { + using var resp = await _client.GetAsync("/v1/models"); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + var ids = doc.RootElement.GetProperty("data").EnumerateArray().Select(m => m.GetProperty("id").GetString()!).ToList(); + Assert.Equal(new[] { Tag }, ids); + } +} + +/// The startup refusal rules, tested as a pure function (Program exits the process on them, +/// which must never happen inside the test host). +public sealed class StartupValidationTests +{ + private static IConfiguration Config(params (string Key, string? Value)[] pairs) + => new ConfigurationBuilder() + .AddInMemoryCollection(pairs.Select(p => new KeyValuePair(p.Key, p.Value))) + .Build(); + + private static List Errors(params (string Key, string? Value)[] pairs) + => StartupValidation.ValidateProviders(Config(pairs)); + + [Fact] + public void Cloud_mode_requires_the_openai_key() + { + Assert.Contains(Errors(), e => e.StartsWith("OpenAI:ApiKey", StringComparison.Ordinal)); + Assert.Empty(Errors(("OpenAI:ApiKey", "sk-test"))); + } + + [Fact] + public void Local_only_with_endpoint_and_tag_needs_no_cloud_key() + => Assert.Empty(Errors(("Providers:Mode", "local-only"), ("Local:Endpoint", "http://localhost:11434/v1"), ("Local:ModelId", "qwen3:8b"))); + + [Fact] + public void Mode_is_normalized() + { + Assert.Equal("local-only", StartupValidation.ProviderMode(Config(("Providers:Mode", " Local-Only ")))); + Assert.Equal("cloud", StartupValidation.ProviderMode(Config())); + } + + [Theory] + [InlineData(null, "qwen3:8b", "Local:Endpoint")] + [InlineData("http://localhost:11434/v1", null, "Local:ModelId")] + public void Local_only_incomplete_configuration_is_refused(string? endpoint, string? model, string expectedKey) + { + var errors = Errors(("Providers:Mode", "local-only"), ("Local:Endpoint", endpoint), ("Local:ModelId", model)); + Assert.Contains(errors, e => e.StartsWith(expectedKey, StringComparison.Ordinal)); + } + + [Theory] + [InlineData("OpenAI:ApiKey")] + [InlineData("Anthropic:ApiKey")] + public void Local_only_refuses_cloud_credentials(string key) + { + var errors = Errors(("Providers:Mode", "local-only"), ("Local:Endpoint", "http://localhost:11434/v1"), + ("Local:ModelId", "qwen3:8b"), (key, "sk-present")); + Assert.Contains(errors, e => e.Contains("no cloud fallback", StringComparison.Ordinal)); + } + + [Fact] + public void Local_endpoint_without_tag_is_refused_in_cloud_mode_too() + { + var errors = Errors(("OpenAI:ApiKey", "sk-test"), ("Local:Endpoint", "http://localhost:11434/v1")); + Assert.Contains(errors, e => e.StartsWith("Local:ModelId", StringComparison.Ordinal)); + } + + [Theory] + [InlineData("ftp://localhost:11434/v1")] + [InlineData("not a url")] + [InlineData(" ")] + public void Local_endpoint_must_be_absolute_http(string endpoint) + { + var errors = Errors(("OpenAI:ApiKey", "sk-test"), ("Local:Endpoint", endpoint), ("Local:ModelId", "qwen3:8b")); + Assert.Contains(errors, e => e.StartsWith("Local:Endpoint", StringComparison.Ordinal)); + } + + [Fact] + public void Blank_local_tag_is_refused() + => Assert.Contains(Errors(("Providers:Mode", "local-only"), ("Local:Endpoint", "http://localhost:11434/v1"), ("Local:ModelId", " ")), + e => e.StartsWith("Local:ModelId", StringComparison.Ordinal)); + + [Fact] + public void Unknown_mode_is_refused() + => Assert.Contains(Errors(("Providers:Mode", "hybrid"), ("OpenAI:ApiKey", "sk-test")), + e => e.StartsWith("Providers:Mode", StringComparison.Ordinal)); +} diff --git a/tests/Covenant.Tests/ProviderProbeTests.cs b/tests/Covenant.Tests/ProviderProbeTests.cs new file mode 100644 index 0000000..e78c13c --- /dev/null +++ b/tests/Covenant.Tests/ProviderProbeTests.cs @@ -0,0 +1,347 @@ +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using Covenant.Host; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Xunit; + +namespace Covenant.Tests; + +/// Minimal loopback HTTP/1.1 server for probe contract tests (TcpListener, ephemeral port). The +/// responder maps a request line to raw response bytes; null = accept and never answer (timeout). +internal sealed class LoopbackHttpServer : IDisposable +{ + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource _cts = new(); + private readonly List _requests = []; + private int _connections; + + public Func Respond { get; set; } + public int Port { get; } + public int Connections => Volatile.Read(ref _connections); + public IReadOnlyList Requests { get { lock (_requests) return _requests.ToList(); } } + public string Authority => $"127.0.0.1:{Port}"; + public string V1 => $"http://127.0.0.1:{Port}/v1"; + + public LoopbackHttpServer(Func respond) + { + Respond = respond; + _listener.Start(); + Port = ((IPEndPoint)_listener.LocalEndpoint).Port; + _ = AcceptLoopAsync(); + } + + public static byte[] Http(int status, string body, string contentType = "application/json", string extraHeaders = "", bool contentLength = true) + => Encoding.UTF8.GetBytes( + $"HTTP/1.1 {status} X\r\nContent-Type: {contentType}\r\n" + + (contentLength ? $"Content-Length: {Encoding.UTF8.GetByteCount(body)}\r\n" : "") + + $"Connection: close\r\n{extraHeaders}\r\n{body}"); + + private async Task AcceptLoopAsync() + { + try + { + while (!_cts.IsCancellationRequested) + { + var client = await _listener.AcceptTcpClientAsync(_cts.Token); + Interlocked.Increment(ref _connections); + _ = HandleAsync(client); + } + } + catch (Exception) { /* listener stopped */ } + } + + private async Task HandleAsync(TcpClient client) + { + using (client) + { + try + { + var stream = client.GetStream(); + var buffer = new byte[8192]; + var head = new StringBuilder(); + while (!head.ToString().Contains("\r\n\r\n", StringComparison.Ordinal)) + { + int n = await stream.ReadAsync(buffer, _cts.Token); + if (n == 0) return; + head.Append(Encoding.ASCII.GetString(buffer, 0, n)); + } + var raw = head.ToString(); + lock (_requests) _requests.Add(raw); + var response = Respond(raw.Split("\r\n")[0]); + if (response is null) + { + await Task.Delay(Timeout.Infinite, _cts.Token); + return; + } + await stream.WriteAsync(response, _cts.Token); + await stream.FlushAsync(_cts.Token); + } + catch (Exception) { /* client went away / server disposed */ } + } + } + + public void Dispose() + { + _cts.Cancel(); + _listener.Stop(); + } +} + +/// Task 06: the host-side probe is an allow-listed, bounded, redirect-refusing model-list check — +/// never a general URL fetcher — and observed health supersedes stale success. +public sealed class ProviderProbeTests +{ + private static HashSet Allow(LoopbackHttpServer s) => new(StringComparer.OrdinalIgnoreCase) { s.Authority }; + + [Fact] + public async Task Reachable_endpoint_returns_discovered_model_ids() + { + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(200, """{"object":"list","data":[{"id":"qwen3:8b"},{"id":"llama3.2:3b"}]}""")); + var r = await ProviderProbe.RunAsync(server.V1, Allow(server), CancellationToken.None); + + Assert.True(r.Allowed); + Assert.True(r.Reachable, r.Error); + Assert.Equal(200, r.HttpStatus); + Assert.Equal(new[] { "qwen3:8b", "llama3.2:3b" }, r.Models); + Assert.StartsWith("GET /v1/models ", Assert.Single(server.Requests)); + } + + [Fact] + public async Task Probe_never_forwards_credentials() + { + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(200, """{"data":[]}""")); + await ProviderProbe.RunAsync(server.V1, Allow(server), CancellationToken.None); + var request = Assert.Single(server.Requests); + Assert.DoesNotContain("Authorization", request, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("X-Covenant", request, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Cookie", request, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task Empty_discovery_is_reachable_with_no_models() + { + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(200, """{"data":[]}""")); + var r = await ProviderProbe.RunAsync(server.V1, Allow(server), CancellationToken.None); + Assert.True(r.Reachable, r.Error); + Assert.Empty(r.Models); + Assert.Null(r.Error); + } + + [Fact] + public async Task Refused_port_is_unreachable() + { + var probe = new TcpListener(IPAddress.Loopback, 0); + probe.Start(); + int port = ((IPEndPoint)probe.LocalEndpoint).Port; + probe.Stop(); // nothing listens there now + + var allow = new HashSet(StringComparer.OrdinalIgnoreCase) { $"127.0.0.1:{port}" }; + var r = await ProviderProbe.RunAsync($"http://127.0.0.1:{port}/v1", allow, CancellationToken.None); + Assert.True(r.Allowed); + Assert.False(r.Reachable); + Assert.StartsWith("connection failed", r.Error); + Assert.Empty(r.Models); + } + + [Fact] + public async Task Silent_server_times_out_within_the_deadline() + { + using var server = new LoopbackHttpServer(_ => null); // accepts, never answers + var started = DateTimeOffset.UtcNow; + var r = await ProviderProbe.RunAsync(server.V1, Allow(server), TimeSpan.FromMilliseconds(400), CancellationToken.None); + + Assert.True(r.Allowed); + Assert.False(r.Reachable); + Assert.Contains("timed out", r.Error); + Assert.True(DateTimeOffset.UtcNow - started < TimeSpan.FromSeconds(4)); + } + + [Theory] + [InlineData("this is not json", "text/plain")] + [InlineData("""{"models":[{"name":"qwen3:8b"}]}""", "application/json")] + [InlineData("""[{"id":"qwen3:8b"}]""", "application/json")] + [InlineData("""{"data":"nope"}""", "application/json")] + public async Task Wrong_shape_or_non_json_is_an_error(string body, string contentType) + { + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(200, body, contentType)); + var r = await ProviderProbe.RunAsync(server.V1, Allow(server), CancellationToken.None); + Assert.False(r.Reachable); + Assert.Contains("not an OpenAI-compatible model list", r.Error); + } + + [Fact] + public async Task Non_success_status_is_an_error() + { + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(500, """{"error":"boom"}""")); + var r = await ProviderProbe.RunAsync(server.V1, Allow(server), CancellationToken.None); + Assert.False(r.Reachable); + Assert.Equal(500, r.HttpStatus); + } + + [Fact] + public async Task Redirect_is_not_followed() + { + int port = 0; + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(302, "", + extraHeaders: $"Location: http://127.0.0.1:{port}/elsewhere/models\r\n")); + port = server.Port; + var r = await ProviderProbe.RunAsync(server.V1, Allow(server), CancellationToken.None); + + Assert.False(r.Reachable); + Assert.Equal(302, r.HttpStatus); + Assert.Contains("redirect", r.Error); + Assert.Single(server.Requests); // the Location was never requested + } + + [Theory] + [InlineData(true)] // Content-Length declares the oversize up front + [InlineData(false)] // no length: the streaming cap must catch it + public async Task Oversized_body_is_refused(bool declareLength) + { + var huge = """{"data":[""" + string.Join(",", Enumerable.Repeat("""{"id":"padding-model-name-xxxxxxxxxxxxxxxx"}""", 2000)) + "]}"; + Assert.True(huge.Length > ProviderProbe.MaxResponseBytes); + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(200, huge, contentLength: declareLength)); + var r = await ProviderProbe.RunAsync(server.V1, Allow(server), CancellationToken.None); + Assert.False(r.Reachable); + Assert.Contains("exceeded", r.Error); + } + + [Fact] + public async Task Destination_not_on_allow_list_is_refused_without_connecting() + { + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(200, """{"data":[]}""")); + var allow = new HashSet(StringComparer.OrdinalIgnoreCase) { "127.0.0.1:1" }; + var r = await ProviderProbe.RunAsync(server.V1, allow, CancellationToken.None); + + Assert.False(r.Allowed); + Assert.False(r.Reachable); + Assert.Contains("allow-list", r.Error); + Assert.Equal(0, server.Connections); + } + + [Theory] + [InlineData("http://user:pass@127.0.0.1:{port}/v1", "credentials")] + [InlineData("http://127.0.0.1:{port}/v1?x=1", "query")] + [InlineData("http://127.0.0.1:{port}/v1#frag", "query")] + [InlineData("ftp://127.0.0.1:{port}/v1", "http and https")] + [InlineData("file:///etc/passwd", "http and https")] + [InlineData("no-scheme-here", "absolute")] + [InlineData("", "required")] + public async Task Unsafe_endpoint_shapes_are_refused_without_connecting(string template, string expected) + { + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(200, """{"data":[]}""")); + var r = await ProviderProbe.RunAsync(template.Replace("{port}", server.Port.ToString()), Allow(server), CancellationToken.None); + Assert.False(r.Allowed); + Assert.Contains(expected, r.Error); + Assert.Equal(0, server.Connections); + } + + [Fact] + public void Allow_list_defaults_the_ollama_port_and_includes_the_applied_local_endpoint() + { + var set = ProviderProbe.BuildAllowList("ollama, 10.0.0.5:8000", "http://gpu-box:11434/v1"); + Assert.Contains("ollama:11434", set); + Assert.Contains("10.0.0.5:8000", set); + Assert.Contains("gpu-box:11434", set); + Assert.Equal(3, set.Count); + Assert.Empty(ProviderProbe.BuildAllowList(null, null)); + } + + [Fact] + public void Health_failure_after_success_is_failed_but_keeps_last_success() + { + var health = new ProviderHealth(); + Assert.Equal("unknown", health.Get("local:qwen3:8b").State); + + health.RecordSuccess("local", "qwen3:8b"); + var ok = health.Get("local:qwen3:8b"); + Assert.Equal("ok", ok.State); + Assert.NotNull(ok.LastSuccessUtc); + + health.RecordFailure("local", "qwen3:8b", "connection refused"); + var failed = health.Get("local:qwen3:8b"); + Assert.Equal("failed", failed.State); // stale success no longer shows green + Assert.Equal(ok.LastSuccessUtc, failed.LastSuccessUtc); // ... but "last worked at" survives + Assert.Equal("connection refused", failed.LastError); + Assert.NotNull(failed.LastFailureUtc); + + health.Success("local:qwen3:8b"); + var again = health.Get("local:qwen3:8b"); + Assert.Equal("ok", again.State); + Assert.Equal(failed.LastFailureUtc, again.LastFailureUtc); + } + + [Fact] + public async Task Applied_endpoint_probe_success_then_failure_updates_catalog_health() + { + bool healthy = true; + using var server = new LoopbackHttpServer(_ => Volatile.Read(ref healthy) + ? LoopbackHttpServer.Http(200, """{"data":[{"id":"qwen3:8b"}]}""") + : LoopbackHttpServer.Http(503, """{"error":"down"}""")); + var audit = Path.Combine(Path.GetTempPath(), $"covenant-probe-{Guid.NewGuid():n}.log"); + try + { + using var baseFactory = new WebApplicationFactory(); + using var factory = baseFactory.WithWebHostBuilder(b => + { + b.UseEnvironment("Production"); + b.UseSetting("OpenAI:ApiKey", "unused"); + b.UseSetting("Admin:Token", CorrelationTestKit.AdminToken); + b.UseSetting("Budget:GlobalCapUsd", "10"); + b.UseSetting("Auth:AllowAnonymous", "true"); + b.UseSetting("Audit:Path", audit); + b.UseSetting("Local:Endpoint", server.V1); + b.UseSetting("Local:ModelId", "qwen3:8b"); + }); + using var client = factory.CreateClient(); + + async Task ProbeAsync() + { + using var req = CorrelationTestKit.Admin(HttpMethod.Post, "/admin/providers/probe"); + req.Content = new StringContent($"{{\"endpoint\":\"{server.V1}\"}}", Encoding.UTF8, "application/json"); + using var resp = await client.SendAsync(req); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + return JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement.Clone(); + } + + async Task EndpointHealthAsync() + { + using var resp = await client.SendAsync(CorrelationTestKit.Admin(HttpMethod.Get, "/admin/catalog")); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + return doc.RootElement.GetProperty("local").GetProperty("endpoint_health").Clone(); + } + + Assert.Equal("unknown", (await EndpointHealthAsync()).GetProperty("state").GetString()); + + var first = await ProbeAsync(); + Assert.True(first.GetProperty("reachable").GetBoolean()); + var afterOk = await EndpointHealthAsync(); + Assert.Equal("ok", afterOk.GetProperty("state").GetString()); + var lastSuccess = afterOk.GetProperty("last_success_utc").GetString(); + Assert.False(string.IsNullOrEmpty(lastSuccess)); + + Volatile.Write(ref healthy, false); + var second = await ProbeAsync(); + Assert.False(second.GetProperty("reachable").GetBoolean()); + var afterFail = await EndpointHealthAsync(); + Assert.Equal("failed", afterFail.GetProperty("state").GetString()); + Assert.Equal(lastSuccess, afterFail.GetProperty("last_success_utc").GetString()); + + // The admin token never reaches the probed endpoint. + Assert.All(server.Requests, r => Assert.DoesNotContain(CorrelationTestKit.AdminToken, r)); + + // A probe is admin-only. + using var anon = await client.PostAsync("/admin/providers/probe", + new StringContent($"{{\"endpoint\":\"{server.V1}\"}}", Encoding.UTF8, "application/json")); + Assert.Equal(HttpStatusCode.Unauthorized, anon.StatusCode); + } + finally + { + CorrelationTestKit.DeleteWithSiblings(audit); + } + } +}