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

Title

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

Sub

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

#### four

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

bold and it and b2 and i2

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

use a*b*c here

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

line one
line two

para two

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

snake_case_name stays

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

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

Every tag in the output is one the renderer itself writes. + private static void AssertOnlyAllowedTags(string html) + { + var allowed = new HashSet(StringComparer.Ordinal) { "p", "br", "h3", "h4", "h5", "strong", "em", "code", "pre", "ul", "ol", "li", "a" }; + foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(html, "<\\/?([a-zA-Z0-9]+)")) + Assert.Contains(m.Groups[1].Value, allowed); + foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(html, "]*)>")) + Assert.Matches("^href=\"https?://[^\"<>]*\" target=\"_blank\" rel=\"noopener noreferrer\"$", m.Groups[1].Value); + } +} + +public sealed class TraceModelTests +{ + private static TraceEventDto E(long seq, string stage, string state, double? ms = null, string? attempt = null, string? reason = null, string? target = null) + => new() { Seq = seq, Stage = stage, State = state, DurationMs = ms, AttemptId = attempt, ReasonCode = reason, Target = target }; + + private static TraceStepView Step(TraceView v, string stage) => v.Steps.Single(s => s.Stage == stage); + + [Fact] + public void Steps_follow_the_canonical_order_and_unreported_stages_are_pending_until_complete() + { + var open = TraceModel.Reduce([E(1, "auth", "passed", 2)], complete: false); + Assert.Equal(TraceModel.Stages, open.Steps.Select(s => s.Stage)); + Assert.Equal(TraceStepState.Passed, Step(open, "auth").State); + Assert.Equal(2, Step(open, "auth").DurationMs); + Assert.Equal(TraceStepState.Pending, Step(open, "policy").State); + + var done = TraceModel.Reduce([E(1, "auth", "passed", 2)], complete: true); + Assert.Equal(TraceStepState.NotReported, Step(done, "policy").State); // never invented as passed/skipped + } + + [Fact] + public void Duplicates_are_dropped_by_seq_and_out_of_order_delivery_cannot_regress_a_state() + { + var events = new[] + { + E(3, "policy", "passed", 4, reason: "allowed"), + E(1, "auth", "running"), + E(2, "auth", "passed", 1.5), + E(2, "auth", "failed"), // duplicate seq (replay): ignored, first copy wins + E(3, "policy", "refused"), // duplicate seq + E(4, "policy", "running"), // stray later event wins only because its seq is higher + }; + var v = TraceModel.Reduce(events, complete: false); + Assert.Equal(TraceStepState.Passed, Step(v, "auth").State); + Assert.Equal(1.5, Step(v, "auth").DurationMs); + Assert.Equal(TraceStepState.Running, Step(v, "policy").State); + Assert.Equal("allowed", Step(v, "policy").ReasonCode); + Assert.Equal(4, v.LastSeq); + } + + [Fact] + public void Skipped_stages_are_reported_as_skipped_with_their_reason() + { + var v = TraceModel.Reduce( + [ + E(1, "cache", "passed", 1, reason: "cache_hit"), + E(2, "rate_limit", "skipped", reason: "cache_hit"), + E(3, "pause", "skipped", reason: "cache_hit"), + E(4, "provider", "skipped", reason: "cache_hit"), + ], complete: true); + Assert.Equal(TraceStepState.Skipped, Step(v, "rate_limit").State); + Assert.Equal(TraceStepState.Skipped, Step(v, "provider").State); + Assert.Empty(Step(v, "provider").Attempts); + Assert.Equal("cache_hit", Step(v, "provider").ReasonCode); + Assert.Null(Step(v, "rate_limit").DurationMs); + } + + [Fact] + public void Provider_events_are_grouped_into_attempts_in_order_of_first_appearance() + { + var v = TraceModel.Reduce( + [ + E(10, "provider", "running", attempt: "a1", target: "openai/gpt-x"), + E(12, "provider", "running", attempt: "a2", target: "ollama/qwen"), + E(11, "provider", "failed", 5000, attempt: "a1", reason: "timeout"), + E(13, "provider", "passed", 800, attempt: "a2"), + ], complete: true); + var p = Step(v, "provider"); + Assert.Equal(2, p.Attempts.Count); + Assert.Equal("a1", p.Attempts[0].AttemptId); + Assert.Equal(TraceStepState.Failed, p.Attempts[0].State); + Assert.Equal("openai/gpt-x", p.Attempts[0].Target); + Assert.Equal("timeout", p.Attempts[0].ReasonCode); + Assert.Equal(5000, p.Attempts[0].DurationMs); + Assert.Equal("a2", p.Attempts[1].AttemptId); + Assert.Equal(TraceStepState.Passed, p.Attempts[1].State); + Assert.Equal("ollama/qwen", p.Attempts[1].Target); + Assert.Equal(TraceStepState.Passed, p.State); // last attempt decides + Assert.Equal(5800, p.DurationMs); // sum of reported attempt durations + Assert.Equal(new[] { 1, 2 }, p.Attempts.Select(a => a.Number)); + } + + [Fact] + public void Provider_is_running_while_any_attempt_runs() + { + var v = TraceModel.Reduce([E(1, "provider", "running", attempt: "a1")], complete: false); + Assert.Equal(TraceStepState.Running, Step(v, "provider").State); + } + + [Fact] + public void Accumulator_dedupes_tracks_last_seq_and_merges_snapshots() + { + var acc = new TraceAccumulator(); + Assert.True(acc.Add(E(1, "auth", "passed"))); + Assert.False(acc.Add(E(1, "auth", "passed"))); + Assert.True(acc.Add(E(5, "policy", "passed"))); + Assert.Equal(5, acc.LastSeq); + + acc.ApplySnapshot(new TraceSnapshotDto { Complete = true, ConfigVersion = 7, Events = [E(1, "auth", "passed"), E(6, "attribution", "passed")] }); + Assert.Equal(3, acc.Count); + Assert.True(acc.Complete); + var view = acc.View(); + Assert.Equal(7, view.ConfigVersion); + Assert.Equal(TraceStepState.NotReported, Step(view, "budget").State); + } + + [Fact] + public void Unknown_states_and_stages_are_kept_honestly() + { + var v = TraceModel.Reduce([E(1, "auth", "weird"), E(2, "future_stage", "passed")], complete: true); + Assert.Equal(TraceStepState.NotReported, Step(v, "auth").State); + Assert.Equal("future_stage", v.Steps[^1].Stage); + } + + [Fact] + public void Audit_summary_fallback_reads_objects_and_compact_strings() + { + var summary = System.Text.Json.JsonDocument.Parse( + "[{\"Stage\":\"auth\",\"State\":\"passed\",\"DurationMs\":1},\"policy:passed:3\",\"provider:failed:900\",\"provider:passed:400\",{\"nonsense\":1}]") + .RootElement.EnumerateArray().Select(e => e.Clone()).ToList(); + var attempts = new List + { + new() { AttemptId = "a1", ConnectionId = "openai", ModelId = "gpt-x" }, + new() { AttemptId = "a2", ConnectionId = "ollama", ModelId = "qwen" }, + }; + var v = TraceModel.FromAuditSummary(summary, attempts, 3)!; + Assert.Equal("audit summary", v.Source); + Assert.True(v.Complete); + Assert.Equal(TraceStepState.Passed, Step(v, "auth").State); + Assert.Equal(3, Step(v, "policy").DurationMs); + var p = Step(v, "provider"); + Assert.Equal(2, p.Attempts.Count); + Assert.Equal("openai/gpt-x", p.Attempts[0].Target); + Assert.Equal(TraceStepState.Failed, p.Attempts[0].State); + Assert.Equal(TraceStepState.Passed, p.State); + Assert.Null(TraceModel.FromAuditSummary(null)); + Assert.Null(TraceModel.FromAuditSummary([])); + } + + [Fact] + public void Sse_parser_dispatches_on_blank_lines_and_joins_data() + { + var p = new SseParser(); + Assert.Null(p.Feed(": comment")); + Assert.Null(p.Feed("id: 7")); + Assert.Null(p.Feed("data: {\"a\":")); + Assert.Null(p.Feed("data: 1}")); + var ev = p.Feed(""); + Assert.NotNull(ev); + Assert.Equal("7", ev!.Id); + Assert.Equal("message", ev.Event); + Assert.Equal("{\"a\":\n1}", ev.Data); + + Assert.Null(p.Feed("event: end")); + var end = p.Feed(""); + Assert.Equal("end", end!.Event); + Assert.Null(p.Feed("")); // nothing pending + } +} + +public sealed class ShellStatusTests +{ + [Theory] + [InlineData("local-only", "Local-only", "local")] + [InlineData("LocalOnly", "Local-only", "local")] + [InlineData("hybrid", "Hybrid", "hybrid")] + [InlineData("Hybrid", "Hybrid", "hybrid")] + [InlineData("legacy-cloud", "Legacy cloud", "legacy")] + [InlineData("LegacyCloud", "Legacy cloud", "legacy")] + [InlineData("cloud", "Legacy cloud", "legacy")] + [InlineData(null, "Mode not reported", "unknown")] + [InlineData("", "Mode not reported", "unknown")] + [InlineData("quantum", "Mode not reported", "unknown")] + public void Mode_badge_mapping(string? mode, string label, string tone) + { + var b = ShellStatus.Mode(mode); + Assert.Equal(label, b.Label); + Assert.Equal(tone, b.Tone); + } + + private static readonly DateTimeOffset Now = new(2026, 10, 16, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public void Live_shows_no_counter_and_the_exact_time_goes_in_the_title() + { + var f = ShellStatus.Freshness(true, false, Now.AddSeconds(-1), Now, null); + Assert.Equal("Live", f.Label); + Assert.Equal("ok", f.Tone); + Assert.False(f.Stale); + Assert.Equal("Last status update 2026-10-16 11:59:59 UTC", f.Title); + Assert.DoesNotMatch("\\d+ s", f.Label); + } + + [Fact] + public void Stale_shows_age_and_the_feed_problem() + { + var f = ShellStatus.Freshness(true, true, Now.AddSeconds(-12), Now, "Connection lost — retrying"); + Assert.Equal("Stale · 12 s", f.Label); + Assert.Equal("warn", f.Tone); + Assert.Contains("Connection lost", f.Title, StringComparison.Ordinal); + Assert.Equal("Stale · 3 min", ShellStatus.Freshness(true, true, Now.AddSeconds(-200), Now, null).Label); + Assert.Equal("Stale · no update", ShellStatus.Freshness(true, true, null, Now, null).Label); + Assert.Equal("Disconnected", ShellStatus.Freshness(false, false, null, Now, null).Label); + } + + [Fact] + public void Announcement_depends_on_state_changes_only() + { + var a = ShellStatus.Announcement(true, false, false); + Assert.Equal("Console connected. New provider calls accepted.", a); + Assert.Equal("Console connected. New provider calls paused. Status is stale.", ShellStatus.Announcement(true, true, true)); + Assert.Equal("Console disconnected.", ShellStatus.Announcement(false, true, true)); + // Same state, any time → same text: nothing to re-announce while the clock ticks. + Assert.Equal(a, ShellStatus.Announcement(true, false, false)); + } +} + +public sealed class AttemptAndDestinationTests +{ + private static AuditEntryView Fallback() => Set(Rec.V2(selected: "openai/gpt-x", attempted: "ollama/qwen", served: "ollama/qwen"), + [ + new AuditAttemptView { AttemptId = "a1", ConnectionId = "openai", ModelId = "gpt-x", Outcome = "failed", ErrorClass = "timeout", DurationMs = 5000, CostUsd = 0.0001m, CostBasis = "estimated_failed_call" }, + new AuditAttemptView { AttemptId = "a2", ConnectionId = "ollama", ModelId = "qwen", Outcome = "served", DurationMs = 800, CostUsd = 0m, CostBasis = "zero_priced" }, + ]); + + private static AuditEntryView Set(AuditEntryView r, List attempts) { r.Attempts = attempts; return r; } + + private static readonly List Connections = + [ + new() { Id = "openai", Boundary = "Cloud", Enabled = true }, + new() { Id = "ollama", Boundary = "Local", Enabled = true }, + ]; + + [Fact] + public void Fallback_is_explained_attempt_by_attempt() + { + var r = Fallback(); + var v = OutcomeModel.FromRecord(r); + Assert.Equal(DisplayOutcome.Served, v.Outcome); + Assert.Equal("Served by approved fallback", v.Title); + Assert.Contains("Attempt 1 (openai/gpt-x) failed: timeout; attempt 2 (ollama/qwen) served.", v.Explanation, StringComparison.Ordinal); + + var lines = AttemptFacts.Lines(r, Connections); + Assert.Equal(2, lines.Count); + Assert.Equal("openai/gpt-x", lines[0].Target); + Assert.Equal("Cloud", lines[0].Boundary); + Assert.Equal("timeout", lines[0].ErrorClass); + Assert.Equal("≈ $0.0001 estimated", lines[0].Cost); + Assert.Equal("ollama/qwen", lines[1].Target); + Assert.Equal("Local", lines[1].Boundary); + } + + [Fact] + public void Destination_is_the_serving_attempt_with_its_boundary() + { + var d = ModelFacts.Destination(Fallback(), Connections); + Assert.Equal("ollama/qwen", d.Text); + Assert.Equal("Local", d.Boundary); + Assert.True(d.Served); + + var unknown = ModelFacts.Destination(Fallback(), null); + Assert.Null(unknown.Boundary); // never guessed from the name + + var refused = ModelFacts.Destination(Rec.PolicyDeny()); + Assert.Equal(ModelFacts.NoProviderCall, refused.Text); + Assert.False(refused.Served); + + var cache = ModelFacts.Destination(Rec.V2(cacheHit: true, attempted: null, served: "ollama/qwen"), Connections); + Assert.StartsWith("Cache — no provider call", cache.Text, StringComparison.Ordinal); + } + + [Fact] + public void Single_attempt_is_not_called_a_fallback() + { + var r = Set(Rec.V2(), [new AuditAttemptView { AttemptId = "a1", ConnectionId = "openai", ModelId = "gpt-x", Outcome = "served" }]); + Assert.Null(AttemptFacts.FallbackSentence(r)); + Assert.Equal("Served", OutcomeModel.FromRecord(r).Title); + } + + [Fact] + public void Cancel_with_partial_text_says_so_truthfully() + { + var v = OutcomeModel.Compute(new OutcomeInput(200, Cancelled: true, HasPartialText: true)); + Assert.Equal(DisplayOutcome.Cancelled, v.Outcome); + Assert.Equal("Cancelled — partial response", v.Title); + Assert.Contains("the provider may have charged for work done", v.Explanation, StringComparison.Ordinal); + Assert.Equal("Cancelled — no response received", OutcomeModel.Compute(new OutcomeInput(Cancelled: true)).Title); + } + + [Fact] + public void Duplicate_submission_is_not_a_success() + { + var v = OutcomeModel.Compute(new OutcomeInput(409, "duplicate_submission")); + Assert.Equal(DisplayOutcome.DuplicateSubmission, v.Outcome); + Assert.Equal("unknown", v.PillKind); } } @@ -627,13 +1155,13 @@ public void Governed_connection_test_prompt_is_fresh_every_run_so_it_cannot_hit_ => Assert.NotEqual(ConnectionLogic.GovernedTestPrompt(), ConnectionLogic.GovernedTestPrompt()); [Fact] - public void Launch_link_reads_credentials_only_from_the_fragment() + public void Launch_link_reads_only_the_admin_token_from_the_fragment_and_ignores_appkey() { var c = LaunchLink.Parse("http://localhost:5201/ui/connect#token=abc%2B1&appkey=k-2"); Assert.NotNull(c); Assert.Equal("abc+1", c!.AdminToken); - Assert.Equal("k-2", c.ApplicationKey); + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#appkey=k-2")); // application keys are never accepted Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect?token=abc")); // query is sent to the server: never accepted Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect")); Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#")); diff --git a/tests/Covenant.Tests/Covenant.Tests.csproj b/tests/Covenant.Tests/Covenant.Tests.csproj index 6ca31a8..a9975c4 100644 --- a/tests/Covenant.Tests/Covenant.Tests.csproj +++ b/tests/Covenant.Tests/Covenant.Tests.csproj @@ -30,7 +30,7 @@ without referencing the Blazor WebAssembly project. Ui types live in Covenant.Ui.* namespaces — qualify them in tests where Covenant.Host has a same-named type (ErrorResponse, StatusReport, …). --> - + From 8bb89238e8912f8cd1465b1b8ac138597a5a5b93 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Sat, 17 Oct 2026 00:18:48 -0400 Subject: [PATCH 06/14] =?UTF-8?q?fix(config):=20review=20round=201=20?= =?UTF-8?q?=E2=80=94=20total=20validation,=20ambiguity=20refusal,=20frozen?= =?UTF-8?q?=20snapshots,=20journal=20lineage,=20torn-tail=20repair?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - out-of-range enums / null objects → validation errors (200 valid=false, 422), never 500 - ambiguous bare model override refused; connection/model required - RuntimeSnapshot deep-copies every collection - unknown connections never eligible; legacy local placeholder imported as DISABLED - AllowSensitiveCloud removed: PII/PHI cloud target is a validation error - Local boundary bound to startup-approved endpoints - application missing after legacy import → 403 at auth - console identity cannot be set from /v1 - activation journal defines history; orphans excluded and never reused; compile before durable write - torn journal tail quarantined + journal rewritten before any append (reviewer reproducer added) - provider clients: no redirects, SDK retries off, connection timeout enforced - UI: v2 test assertions, config contract round-trip test, AllowSensitiveCloud removed --- docs/console-v2-progress.md | 103 +++++ docs/migration-v2.md | 16 +- docs/ui-api-contract.md | 44 ++- src/Covenant.Core/CanonicalModel.cs | 8 +- src/Covenant.Core/Configuration.cs | 4 +- src/Covenant.Core/InferenceContext.cs | 20 +- src/Covenant.Governance/Auth.cs | 38 +- src/Covenant.Governance/ConfigValidation.cs | 171 ++++++++- src/Covenant.Governance/PolicyV2.cs | 70 ++-- src/Covenant.Governance/RuntimeSnapshot.cs | 62 ++- src/Covenant.Host/ConfigAdminApi.cs | 32 +- src/Covenant.Host/ConfigBootstrap.cs | 87 ++++- src/Covenant.Host/ConfigContracts.cs | 23 +- src/Covenant.Host/ConfigRepository.cs | 307 +++++++++++++-- src/Covenant.Host/Program.cs | 74 +++- src/Covenant.Host/ProviderClients.cs | 132 +++++-- src/Covenant.Ui/Logic/ShellStatus.cs | 2 +- src/Covenant.Ui/Models/ConfigContracts.cs | 2 +- src/Covenant.Ui/Pages/Policies.razor | 1 + tests/Covenant.Tests/AnthropicIngressTests.cs | 4 +- .../ClassificationProfileTests.cs | 17 +- tests/Covenant.Tests/ConfigApiTests.cs | 172 +++++++++ tests/Covenant.Tests/ConfigRepositoryTests.cs | 161 +++++++- tests/Covenant.Tests/ConfigV2TestKit.cs | 36 +- .../ConfigValidationTotalityTests.cs | 235 ++++++++++++ tests/Covenant.Tests/ConsoleAssetsTests.cs | 5 +- tests/Covenant.Tests/ConsoleLogicTests.cs | 102 ++++- .../Covenant.Tests/ContractRoundTripTests.cs | 361 ++++++++++++++++++ .../CorrelationAndEvidenceTests.cs | 34 +- tests/Covenant.Tests/HttpMappingTests.cs | 4 +- tests/Covenant.Tests/LegacyImportTests.cs | 54 ++- tests/Covenant.Tests/LocalOnlyModeTests.cs | 2 +- tests/Covenant.Tests/PolicyEngineV2Tests.cs | 139 ++++++- .../ProviderClientConstructionTests.cs | 134 +++++++ tests/Covenant.Tests/ProviderProbeTests.cs | 2 +- tests/Covenant.Tests/ServedPathTests.cs | 5 +- tests/Covenant.Tests/WireShapeTests.cs | 4 +- 37 files changed, 2416 insertions(+), 251 deletions(-) create mode 100644 tests/Covenant.Tests/ConfigValidationTotalityTests.cs create mode 100644 tests/Covenant.Tests/ContractRoundTripTests.cs create mode 100644 tests/Covenant.Tests/ProviderClientConstructionTests.cs diff --git a/docs/console-v2-progress.md b/docs/console-v2-progress.md index b34e469..747568a 100644 --- a/docs/console-v2-progress.md +++ b/docs/console-v2-progress.md @@ -358,3 +358,106 @@ CorrelationAndEvidenceTests, HttpMappingTests, AnthropicIngressTests, WireShapeT ConsoleAssetsTests, …) unchanged and green. Manual: start with `Config:Seed=demo-hybrid` on a fresh `Audit:Path`, `curl -H "X-Covenant-Admin-Token: …" :PORT/admin/config` → `etag "v1"`; PUT with `If-Match: "v1"` → v2; restart → v2 still active; corrupt `active.json` → refuses to start with the diagnostic. + +## UI test fixes + round-trip + +Reviewer build: Host + UI compiled, `tests/Covenant.Tests` did not (stale `ScenarioPresets.NormalPrompt` / +`SensitivePrompt` and `LaunchLink.ApplicationKey`). In the current tree `ConsoleLogicTests.cs` already used the v2 +API (`TicketPrompt` / `SensitiveTicketPrompt`, `Credentials(AdminToken)`); every remaining call was re-checked +against `src/Covenant.Ui/Logic` + `Models`, and the v2 behaviour is now pinned explicitly. + +### Files + +- `tests/Covenant.Tests/ConsoleLogicTests.cs` — presets: every preset populate-only (operator settings untouched, + `StillMatches`), A detects nothing (no signal = no escalation, Public baseline kept), B/C carry the synthetic SSN + `078-05-1120` → `Pii` / "US SSN pattern", D fresh nonce + no forced profile + nonce never sensitive. LaunchLink: + `#token=` accepted, `#appkey=` ignored, `Credentials` exposes only `AdminToken`, query-string tokens rejected + (even beside a fragment), empty / >512-char tokens rejected. Eligible overrides use the wire mode spellings + (`hybrid`, `local-only`) and still accept the enum names. +- `tests/Covenant.Tests/ContractRoundTripTests.cs` (new) — Host `ConfigGetResponse` (ConfigJsonContext) → UI + `ConfigEnvelopeDto` (UiJsonContext) → UI `ConfigPutRequestDto` → Host `ConfigPutRequest`; the Host re-serialization + of the result is byte-identical to the original, plus field-by-field checks (mode ×3, kinds ×4, boundaries, + strategies, periods, enforcement, classifications, `input_per_1m`/`output_per_1m`, target order, paused flags, + retry) and the exact wire strings. The UI DTOs were already linked (`src/Covenant.Ui/Models/*.cs`, no Blazor + types), so the csproj is unchanged. Alias is `UiModels`, not `Ui`: inside `namespace Covenant.Tests` the simple + name `Ui` binds to the `Covenant.Ui` namespace before any compilation-unit alias. +- `src/Covenant.Ui/Models/ConfigContracts.cs` — removed `PolicyDto.AllowSensitiveCloud` (PII/PHI never route to + cloud destinations). The UI DTO spellings already matched the Host vocabulary; no other DTO change. +- `src/Covenant.Ui/Logic/ShellStatus.cs` — Hybrid badge text: "PII/PHI never route to cloud destinations." +- `src/Covenant.Ui/Pages/Policies.razor` — "In plain words" list states "PII/PHI never route to cloud destinations." + +### Verifier (not executed — no SDK here) + +``` +dotnet build Covenant.sln -c Release --disable-build-servers +dotnet test tests/Covenant.Tests -c Release --disable-build-servers --filter "FullyQualifiedName~ContractRoundTripTests|FullyQualifiedName~SnapshotAndPresetTests|FullyQualifiedName~ConnectionLogicTests|FullyQualifiedName~ComposerRulesTests" +``` +Dependency: the round-trip asserts the kebab wire spellings and passes only while `PolicyConfigV2` serializes +`allow_sensitive_cloud` identically on both Host passes (it does: false) or after the backend removes it. + +--- + +## Review fixes round 1 (backend — CODEX-REVIEW.txt + corrected ADR-0011..0014) + +**Status: NOT EXECUTED — no .NET SDK in the authoring sandbox.** Written for Nullable + TreatWarningsAsErrors + +IsAotCompatible (source-gen JSON only; generic `Enum.IsDefined`). SDK option names were verified against the +referenced assemblies' metadata (OpenAI 2.12.0, System.ClientModel 1.14.0, Anthropic 12.8.0 from the local build +output), not compiled. Supersedes T02/T03 "Decisions / deviations" #2 (unknown_connection as a warning in +legacy-cloud) and the "unbound key = legacy behaviour" rule. + +| # | Defect | Fix | Regression test(s) | +|---|---|---|---| +| 1 | Validation not total (mode=999 accepted, settings=null → 500) | `ConfigValidator.Structural`: every required object/list/element/id non-null (`required`) and every enum (`ProviderMode`, `ProviderKind`, `Boundary`, `RoutingStrategy`, `BudgetPeriod`, `BudgetEnforcement`, `DataClassification` in profiles/policies) defined via `Enum.IsDefined` (`invalid_enum`), with field paths; semantic pass and impact run only when structurally sound (`ConfigValidationResult.StructurallySound`). Kebab converters accept numbers on READ so 999 reaches the validator. validate → 200 `{valid:false, impact:null}`, PUT → 422 | `ConfigValidationTotalityTests.Every_out_of_range_enum_is_an_invalid_enum_error_with_its_path` (8 enums), `…Null_required_objects_lists_and_elements_are_required_errors_never_exceptions` (24 paths), `…Null_ids_and_required_strings_…`, `…Undefined_numeric_enum_and_null_settings_deserialize_…`; Host: `ConfigApiTests.Structurally_broken_candidates_are_200_valid_false_on_validate_and_422_on_put` (settings=null, mode=999, kind=999, …) | +| 2 | Ambiguous bare model override → FirstOrDefault | `PolicyEngineV2.ResolveOverride`: `connection/model` exact; bare id only if exactly one ELIGIBLE target has it, else deny "model id 'X' is ambiguous across connections a, b — use connection/model". Simulator uses the same engine; cache key and prices are connection-scoped; FinOps' bare-id savings map takes the highest price for an id on several connections (never overstates savings) | `PolicyEngineV2Tests.Ambiguous_bare_model_override_is_refused_and_connection_slash_model_resolves_exactly` | +| 3 | Snapshot aliased caller lists | `ConfigFreezer.Freeze` (RuntimeSnapshot ctor): every list copied into a new array wrapped in `ReadOnlyCollection`, recursively; refuses null instead of defaulting | `ConfigValidationTotalityTests.Snapshot_is_a_deep_copy_unaffected_by_later_mutation_of_the_callers_lists`, `…Snapshot_refuses_a_structurally_unsound_configuration_instead_of_defaulting` | +| 4 | Unknown connection eligible in LegacyCloud | Bypass removed (engine + validator; `ValidationEnvironment.LegacyCompat` deleted): unknown → never eligible, `unknown_connection` always an error; disabled → never eligible ("connection 'x' is disabled (not configured)" when it has no endpoint). Legacy import without `Local:*` adds the DISABLED placeholder `local` ("Local model — not configured (import placeholder)", OpenAiCompatible, Local, endpoint null, model `local-model-not-configured`, zero-marginal-local price) | `PolicyEngineV2Tests.Disabled_or_unknown_connection_targets_are_ineligible_in_every_mode`, `LegacyImportTests.Modes_connections_and_the_unconfigured_local_placeholder_are_explicit`, `LegacyImportTests.Imported_configuration_routes_exactly_like_the_pre_v2_policy` (see changed assertions) | +| 5 | AllowSensitiveCloud escape hatch | Removed from `PolicyConfigV2`, validator, engine, test kit (UI DTO removed by the UI agent). PII/PHI policy with a Cloud target → error `sensitive_cloud_target`; engine excludes cloud for PII/PHI in every mode | `PolicyEngineV2Tests.Sensitive_data_never_reaches_cloud_and_a_sensitive_policy_with_a_cloud_target_is_invalid` | +| 6 | Boundary self-declared | `Boundary.Local` only if the endpoint authority ∈ `Providers:LocalEndpoints` (comma-separated host:port or URLs) ∪ legacy `Local:Endpoint` authority (`StartupEgress.LocalEndpoints`, `ValidationEnvironment.LocalEndpoints`); `OpenAi`/`Anthropic` always Cloud; else `boundary_not_approved`. Labels only — egress is still the allow-list | `PolicyEngineV2Tests.Local_boundary_requires_a_startup_approved_endpoint` (allow-listed cloud host labelled Local → error) | +| 7 | Missing application after import fell back to legacy | AuthStage with a configuration: key whose application is absent → 403 Governance at `auth`, "application not configured: …". Legacy import (and seeds) create one application for EVERY key via `ApplicationIds.FromKey` (valid id verbatim, else `-`), the same normalization `ApiKeyRecord.Application` uses | `ConfigApiTests.Key_whose_application_was_removed_is_403_at_auth`, `ClassificationProfileTests.Key_without_a_configured_application_is_refused_at_auth`, `LegacyImportTests.Identities_budgets_and_operational_settings_are_imported` | +| 8 | Pre-authenticated identity settable via /v1 | Removed from `InferenceRequest` (the wire-derived record); now `InferenceContext.PreAuthenticated` with a private setter, bound only by `BindConsoleIdentity(identity, operatorRef)` (also sets EntryPoint/OperatorRef, now private-set). /v1 handlers never call it | `PublicIngressIdentityTests.Pre_authenticated_identity_is_not_part_of_any_wire_derived_request_type`, `PublicIngressIdentityTests.V1_ignores_every_attempt_to_claim_a_console_identity_and_requires_a_key` (both dialects; admin token + spoof headers + body fields → 401, audit EntryPoint v1) | +| 9 | Paused policy fall-through | Already correct (Match returns the most specific tier, paused ⇒ deny); now pinned | `PolicyEngineV2Tests.Paused_specific_policy_never_falls_through_to_a_less_specific_policy` | +| 10 | Repository lineage (orphan in history) | `activations.jsonl` journal (`ActivationRecord`: version, base, rolled_back_from, utc, origin, summary, recovered), appended + fsync after the pointer rename (`IConfigFileSystem.AppendDurable`); boot appends `recovered: true` when the active version is missing; torn last line tolerated, corrupt earlier line refuses start. History / `GET versions/{n}` / rollback read the journal only (orphan → 404); next = max(files, journal, active)+1. Compile (provider clients) happens in `prepare` before any write, `ConfigCompileException` ⇒ Invalid, nothing written; Program compiles v1 before `Bootstrap` and refuses to start on compile failure | `ConfigRepositoryTests.Crash_between_version_file_and_pointer_keeps_the_old_version_and_reports_the_orphan` (repaired: ListVersions = [3,1], survives restart, next = 4), `…Crash_between_pointer_and_journal_is_recovered_at_boot`, `…Compile_failure_writes_nothing_durable`, `…Journal_corruption_before_the_last_line_refuses_to_start_but_a_torn_last_line_is_tolerated`; Host: `ConfigApiTests.Orphan_version_is_404_refused_for_rollback_absent_from_history_and_never_reused` | +| 11 | SDK transports/retries/timeouts default | Per connection: `SocketsHttpHandler { AllowAutoRedirect = false, ConnectTimeout ≤ 30 s }`, `HttpClient.Timeout = Infinite`; OpenAI/compatible/Ollama: `OpenAIClientOptions { Transport = new HttpClientPipelineTransport(http), RetryPolicy = new ClientRetryPolicy(0), NetworkTimeout = timeout_seconds }`; Anthropic: `new AnthropicClient { ApiKey, BaseUrl, HttpClient = http, MaxRetries = 0, Timeout = timeout_seconds }` (all init properties exist in 12.8.0 — no limitation to document). HttpClients are owned and disposed by the `ProviderClientSet`. Enabled connection referenced by an enabled policy without a client ⇒ `client_unbuildable` (validate endpoint, apply → 422, boot refuses) | `ProviderClientConstructionTests` (real SDKs against loopback sockets: 503 → exactly one request; 302/307 → redirect target never contacted; 1 s timeout enforced; `Unbuildable_referenced_connection_is_a_validation_error_not_a_silent_skip`) | +| 12 | Enum spelling contract | Documented in `ConfigContracts.cs` and `docs/ui-api-contract.md` v2 "Wire spellings": mode/strategy/period/enforcement kebab, kind/boundary/classification C# names, `input_per_1m`/`output_per_1m` | `ConfigValidationTotalityTests.Wire_spellings_are_the_documented_contract` (+ the UI agent's `ContractRoundTripTests`) | +| 13 | Unbounded/unredacted summaries | `ConfigRepository.Bound`: value redaction (`StartupEgress.Redactor`: OpenAI/Anthropic/Local keys, `Secrets:*`, `Auth:Keys` values, `Admin:Token`) + pattern redaction (`sk-…`, `Bearer …`, 40+ char token runs) → `[redacted]`, control chars stripped, ≤ 500 chars (499 + "…"); same text in version file, journal and `config.activated` audit reason | `ConfigRepositoryTests.Change_summaries_are_redacted_and_bounded`, `ConfigApiTests.Change_summary_is_redacted_and_bounded_everywhere_it_is_recorded` | +| 14 | Test isolation | `CorrelationTestKit.IsolatePaths(builder, auditPath)` sets `Audit:Path`, `Config:Path = .config`, `Budget:LedgerPath = .ledger.jsonl` in EVERY WebApplicationFactory (HybridSeedFactory, Correlation×2, LocalOnly, ServedPath, ConsoleAssets, HttpMapping, AnthropicIngress, WireShape.Ingress, ProviderProbe); `DeleteWithSiblings` now also removes the derived config directory. No test relies on a shared /tmp default | all host suites | + +### Existing tests changed to the stricter behaviour (intent kept: refused, no provider call, no cloud call) + +- `CorrelationAndEvidenceTests.Missing_local_adapter_403_selected_but_never_attempted` → renamed + `Missing_local_model_403_refused_at_policy_never_selected_or_attempted`: `StoppedAtStage` `provider` → `policy`; + `SelectedModel` `local-model-not-configured` → null; reason now contains "connection 'local' is disabled (not + configured)"; added: provider call count unchanged. +- `LegacyImportTests.Imported_configuration_routes_exactly_like_the_pre_v2_policy`: for shapes without `Local:*`, + PII/PHI now must be a policy Deny (pre-v2 "allowed" the placeholder then refused at provider); where pre-v2 already + denied, the reason is still identical. `Modes_connections_…`: cloud import now has connections `[openai, local]` + (placeholder). `Imported_configuration_validates_…` uses `LocalEndpoints`, asserts no `unknown_connection`. +- `ClassificationProfileTests.Key_without_a_configured_application_keeps_legacy_behaviour` → renamed + `…_is_refused_at_auth` (403 auth, audited, no classify, no provider). +- `PolicyEngineV2Tests`: `Sensitive_data_never_reaches_cloud_without_an_explicit_acknowledgement` → no acknowledgement + path exists; `Disabled_or_unknown_connection_targets_are_ineligible_outside_legacy_cloud` → `…_in_every_mode`. +- `LegacyImportTests.Identities_…`: the `alice@example.com` key is now bound to `alice-example.com-` (was + unbound). `PipelineSliceTests` / `TelemetryTests` keep "no adapter registered" — they run the pure pipeline with + the legacy engine (no configuration), which is unchanged. + +### Notes / residual risks + +- Repositories written by the previous build have no `activations.jsonl`: at first boot only the active version is + recovered into the journal; older version files then show as orphans (not history). Pre-release only. +- A previously persisted legacy-cloud v1 without the placeholder (unknown `local` target) no longer validates ⇒ boot + refuses; delete the test/demo repository (it is beside the audit log) to re-import. +- `/v1/models` still lists the placeholder model id for an imported cloud configuration (unchanged listing rule). +- Highest compile risks: local functions `Defined`/`NonNullList` in `ConfigValidator.Structural`; Anthropic + object initializer (`HttpClient`, `MaxRetries`, `Timeout` are init-only); `ClientRetryPolicy(0)`; the + `GeneratedRegex` in `SecretRedaction`. + +### Verifier commands (not executed) + +``` +dotnet build Covenant.sln -c Release --disable-build-servers +dotnet test tests/Covenant.Tests -c Release --disable-build-servers --filter "FullyQualifiedName~ConfigValidationTotalityTests|FullyQualifiedName~ProviderClientConstructionTests|FullyQualifiedName~ConfigRepositoryTests|FullyQualifiedName~ConfigApiTests|FullyQualifiedName~PublicIngressIdentityTests|FullyQualifiedName~PolicyEngineV2Tests|FullyQualifiedName~LegacyImportTests|FullyQualifiedName~ClassificationProfileTests|FullyQualifiedName~SnapshotIsolationTests|FullyQualifiedName~SimulatorTests|FullyQualifiedName~CorrelationAndEvidenceTests" +dotnet test tests/Covenant.Tests -c Release --disable-build-servers # full suite +``` +Manual: `POST /admin/config/validate` with `"settings": null` → 200 `valid:false` path `settings`; `"mode": 999` → +`invalid_enum` at `mode`; same bodies via PUT → 422; drop a fake `versions/v000002.json` into the config dir → +`GET /admin/config/versions/2` 404, next apply becomes v3. diff --git a/docs/migration-v2.md b/docs/migration-v2.md index a2b1ab0..cef2f4b 100644 --- a/docs/migration-v2.md +++ b/docs/migration-v2.md @@ -1,6 +1,6 @@ # Migrating to configuration v2 (ADR-0011) -On first start of a v2 build with no configuration repository (`Config:Path`, default `covenant-config/`): +On first start of a v2 build with no configuration repository (`Config:Path`, default `.config/`): 1. **`Config:Seed=demo-local-only` or `demo-hybrid`** (isolated demo profiles only) ⇒ the seed becomes v1. 2. **Otherwise the legacy startup keys are imported into v1** (`origin: legacy-import`) and reproduce today's @@ -10,10 +10,18 @@ On first start of a v2 build with no configuration repository (`Config:Path`, de - default (cloud) ⇒ mode `LegacyCloud`: an `openai` connection (secretRef `OpenAI:ApiKey`) with the public and strong models; `anthropic` if `Anthropic:ApiKey` is set; `local` if `Local:*` is set. Public/Internal → openai cheap model with the existing length heuristic to the strong model (threshold `Routing:ComplexityTokenThreshold`); - PII/PHI → local (or refused when local is not configured). Nothing is silently re-routed. + PII/PHI → local. Without `Local:*` the import creates an explicitly **disabled** placeholder connection `local` + ("Local model — not configured (import placeholder)", model `local-model-not-configured`), so PII/PHI are + refused at the policy stage ("no eligible destination: connection 'local' is disabled (not configured)") — + never served, never sent to cloud. Disabled connections are never eligible in any mode. Nothing is silently + re-routed. - `Budget:GlobalCapUsd`/`TeamCapsUsd` ⇒ budgets with period `None` (as before). `Pricing:*` ⇒ model prices. - - Each `Auth:Keys` entry ⇒ an application (id = `Application` or `Principal`, team = `Team`, profile - `legacy-internal`, console testing off). + - Each `Auth:Keys` entry ⇒ an application, once, at v1 (id = `Application` or `Principal`; a value that is not + a valid id, e.g. an e-mail principal, is normalized to `-<8 hex of SHA-256>` the same way the auth + stage normalizes it; team = `Team`, profile `legacy-internal`, console testing off). After v1, a key whose + application is missing from the active configuration is refused (403 at `auth`, "application not configured"). + - Boundary: a `Local` connection must point at a startup-approved local endpoint (`Local:Endpoint`, or + `Providers:LocalEndpoints` = comma-separated `host:port`); otherwise `boundary_not_approved`. 3. The console's Policies page shows the imported effective rules and a "Move to Hybrid defaults" preview; nothing changes until an operator applies it. 4. Spend: if no ledger exists, the current audit segment's spend is imported once (`legacy-import`) into the current diff --git a/docs/ui-api-contract.md b/docs/ui-api-contract.md index f7be673..b364065 100644 --- a/docs/ui-api-contract.md +++ b/docs/ui-api-contract.md @@ -79,10 +79,46 @@ v2 supersedes the read-only parts above. Everything above stays valid unless res `Impact` = `{ "classifications": [{ "classification","profile","before":"|refused","after":… }], "applications_affected":[…], "unavailable_destinations":[…], "pricing_gaps":[…], "newly_refused":[…] }`. -Validation codes include: `duplicate_id`, `unknown_connection`, `unknown_model`, `endpoint_not_allow_listed`, -`secret_unavailable`, `cloud_in_local_only`, `sensitive_cloud_target` (error), `ambiguous_policy_overlap`, -`no_route_for_classification` (warning), `unpriced_paid_target_under_hard_budget`, `invalid_budget_scope`, -`profile_not_found`, `default_profile_not_granted`. +Validation codes include: `duplicate_id`, `unknown_connection` (always an error, every mode), `unknown_model`, +`endpoint_not_allow_listed`, `secret_unavailable`, `cloud_in_local_only`, `sensitive_cloud_target` (error — there is no +`allow_sensitive_cloud` field), `boundary_not_approved` (a `Local` connection whose endpoint authority is not on the +startup `Providers:LocalEndpoints` / `Local:Endpoint` list, or an `OpenAi`/`Anthropic` connection not `Cloud`), +`client_unbuildable` (an enabled connection referenced by an enabled policy for which no provider client could be +built), `ambiguous_policy_overlap`, `no_route_for_classification` (warning), `unpriced_paid_target_under_hard_budget`, +`invalid_budget_scope`, `profile_not_found`, `default_profile_not_granted`. + +**Validation is total.** Structural errors — `required` (a required object, list, list element or id is `null`) and +`invalid_enum` (a numeric enum value that is not a defined member, e.g. `"mode": 999`) — carry the field path +(`settings`, `connections[0].kind`, `policies[0].targets[2]`, …). `POST /admin/config/validate` answers **200** +`{ "valid": false, "errors": [...], "impact": null }` for them (no impact preview of a candidate that cannot be +compiled); `PUT /admin/config` answers **422**. Never a 500. Malformed JSON / a missing required property is 400. + +**History is the activation journal** (`/activations.jsonl`, ADR-0011). `GET /admin/config/versions` +lists activated versions only; `GET /admin/config/versions/{n}` and `POST /admin/config/rollback` with a version that +was written but never activated (an orphan of an interrupted apply) answer **404**, exactly like an unknown number; +orphan numbers are never reused. `change_summary` is redacted (no secret values) and bounded to ≤ 500 characters in +history, journal and the `config.activated` audit event. + +**Model override** (`model` on `/v1`, the simulator and console inference): `connection/model` names exactly one +target; a bare model id is accepted only when exactly one ELIGIBLE target of the matching policy carries it — +otherwise refused: `model id 'X' is ambiguous across connections a, b — use connection/model`. + +### Wire spellings (stable contract, `ConfigJsonContext`) +Properties are snake_case. Enum values are always written as: + +| Field | Type | Values | +|---|---|---| +| `mode` | ProviderMode | `"local-only"`, `"hybrid"`, `"legacy-cloud"` | +| `strategy` | RoutingStrategy | `"fixed"`, `"length-heuristic"` | +| `period` | BudgetPeriod | `"none"`, `"daily"`, `"monthly"` | +| `enforcement` | BudgetEnforcement | `"hard"`, `"warn-only"` | +| `kind` | ProviderKind | `"Ollama"`, `"OpenAiCompatible"`, `"OpenAi"`, `"Anthropic"` (C# names) | +| `boundary` | Boundary | `"Local"`, `"Cloud"` (C# names) | +| `classifications[]`, `baseline` | DataClassification | `"Public"`, `"Internal"`, `"Pii"`, `"Phi"` (C# names) | + +Prices: `"price": { "input_per_1m", "output_per_1m", "basis", "effective_date" }` (never `input_per1_m`). On read a +JSON number is tolerated for an enum only so that an undefined value reaches the validator (`invalid_enum`); clients +must send the names above. `/admin/status.mode` uses the same `mode` spellings. ## Console inference (ADR-0012) `POST /admin/playground/requests` body `{ "application_id", "profile_id"?, "messages":[{role,content}], "model"?, diff --git a/src/Covenant.Core/CanonicalModel.cs b/src/Covenant.Core/CanonicalModel.cs index b518ad4..27c0860 100644 --- a/src/Covenant.Core/CanonicalModel.cs +++ b/src/Covenant.Core/CanonicalModel.cs @@ -30,11 +30,13 @@ public sealed record InferenceRequest( int? MaxOutputTokens = null, string? UnsupportedFeature = null, // set by ingress when the wire carried something governance cannot see (images, tools) → denied in-pipeline, audited string? RequestId = null, // server-generated correlation id (ADR-0009); never caller-supplied - string? RequestedProfile = null, // workload profile asked for (X-Covenant-Profile / console); must be granted (ADR-0012) - PreAuthenticatedIdentity? PreAuthenticated = null); // console entry point: identity resolved server-side, no key (ADR-0012) + string? RequestedProfile = null); // workload profile asked for (X-Covenant-Profile / console); must be granted (ADR-0012) /// An application identity resolved by the Host itself (console inference, ADR-0012) — never -/// taken from a client header. The auth stage still enforces enabled + console testing + profile grant. +/// taken from a client header or body. Deliberately NOT a member of (the canonical +/// request every ingress builds from wire input): it can only be attached server-side through +/// . The auth stage still enforces enabled + console testing + +/// profile grant. public sealed record PreAuthenticatedIdentity(string ApplicationId, string Team, string Principal); /// Who the pipeline decided the caller is: self-declared until the auth stage overwrites it diff --git a/src/Covenant.Core/Configuration.cs b/src/Covenant.Core/Configuration.cs index cf37785..748fa4f 100644 --- a/src/Covenant.Core/Configuration.cs +++ b/src/Covenant.Core/Configuration.cs @@ -121,8 +121,8 @@ public sealed record PolicyConfigV2 /// LengthHeuristic only: chars/4 estimate above this takes the LAST target. public int ThresholdTokens { get; init; } = 400; public RetrySettings Retry { get; init; } = new(); - /// Must be explicitly true for a cloud target to serve PII/PHI. Demo seeds never set it. - public bool AllowSensitiveCloud { get; init; } + // No sensitive-cloud escape hatch (ADR-0013): a policy covering PII/PHI that lists a cloud target is a + // validation error, and the engine never makes a cloud target eligible for PII/PHI. public string? Explanation { get; init; } } diff --git a/src/Covenant.Core/InferenceContext.cs b/src/Covenant.Core/InferenceContext.cs index 0f7cc19..6d6112d 100644 --- a/src/Covenant.Core/InferenceContext.cs +++ b/src/Covenant.Core/InferenceContext.cs @@ -25,11 +25,27 @@ public sealed class InferenceContext(InferenceRequest request) public int? ConfigVersion { get; set; } /// "v1" (application key on /v1) or "console" (admin-authenticated console inference). - public string EntryPoint { get; set; } = "v1"; + public string EntryPoint { get; private set; } = "v1"; /// Who operated the console (honest: "shared-admin-token" — one shared credential cannot /// attribute an individual). Null on /v1. - public string? OperatorRef { get; set; } + public string? OperatorRef { get; private set; } + + /// Console entry point only (ADR-0012): the application identity the Host resolved server-side after + /// admin authentication. Never part of the wire-derived ; null on /v1, where a key + /// is always required. + public PreAuthenticatedIdentity? PreAuthenticated { get; private set; } + + /// Server-side only: called by the Host's console endpoint after it authenticated the admin session + /// and resolved the application. /v1 ingress never calls it. Once per context. + public void BindConsoleIdentity(PreAuthenticatedIdentity identity, string operatorRef) + { + ArgumentNullException.ThrowIfNull(identity); + if (PreAuthenticated is not null) throw new InvalidOperationException("console identity is already bound"); + PreAuthenticated = identity; + EntryPoint = "console"; + OperatorRef = operatorRef; + } /// Resolved application (written by the auth stage when the configuration knows it). public string? ApplicationId { get; set; } diff --git a/src/Covenant.Governance/Auth.cs b/src/Covenant.Governance/Auth.cs index a3515e0..670db1b 100644 --- a/src/Covenant.Governance/Auth.cs +++ b/src/Covenant.Governance/Auth.cs @@ -1,3 +1,5 @@ +using System.Security.Cryptography; +using System.Text; using Covenant.Core; namespace Covenant.Governance; @@ -7,7 +9,26 @@ namespace Covenant.Governance; /// Application this key binds to (Auth:Keys:N:Application; default = Principal, ADR-0012). public sealed record ApiKeyRecord(string Key, string Principal, string Team, string? ApplicationId = null) { - public string Application => ApplicationId ?? Principal; + /// The configuration application id this key binds to (normalized exactly like the legacy import). + public string Application => ApplicationIds.FromKey(ApplicationId ?? Principal); +} + +/// Key → application id (ADR-0012). A valid configuration id is used verbatim; anything else (e.g. an +/// e-mail principal) maps deterministically to "<sanitized>-<8 hex of SHA-256>" (≤64 chars), so the legacy +/// import can create one application for EVERY key and the auth stage finds it — no key is left unbound. +public static class ApplicationIds +{ + public static string FromKey(string raw) + { + if (ConfigValidator.IsValidId(raw)) return raw; + var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(raw ?? ""))).ToLowerInvariant()[..8]; + var sb = new StringBuilder(); + foreach (var ch in raw ?? "") + sb.Append(char.IsAsciiLetterOrDigit(ch) || ch is '-' or '_' or '.' ? ch : '-'); + var clean = sb.ToString().Trim('-'); + if (clean.Length == 0) return "app-" + hash; + return (clean.Length > 55 ? clean[..55] : clean) + "-" + hash; + } } public sealed class AuthConfig @@ -40,7 +61,7 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance // Console entry point (ADR-0012): identity was resolved server-side by the Host from an authorized // admin session; no application key exists in the browser. Still enforced here: application enabled, // console testing allowed, profile granted — governed, audited refusals. - if (ctx.Request.PreAuthenticated is { } pre) + if (ctx.PreAuthenticated is { } pre) { if (ctx.Configuration is not { } cfg) { @@ -69,14 +90,17 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance if (ctx.Configuration is { } cfg) { // Key → application (ADR-0012). /v1 key authentication itself is unchanged (team from the key); - // the application adds enabled state and profile grants. A key whose application is absent - // from configuration behaves as before: legacy-internal profile. + // the application adds enabled state and profile grants. Fail-closed: a key whose application + // is missing from the active configuration (removed, renamed, never added) is refused — there is + // no implicit legacy fallback once a configuration governs. var app = cfg.FindApplication(record.Application); - if (app is not null) + if (app is null) { - ctx.ApplicationId = app.Id; - if (!app.Enabled) { ctx.Deny($"application '{app.Id}' disabled"); return; } + ctx.Deny($"application not configured: '{Evidence.Bounded(record.Application)}' is not in configuration v{cfg.Version}"); + return; } + ctx.ApplicationId = app.Id; + if (!app.Enabled) { ctx.Deny($"application '{app.Id}' disabled"); return; } if (!ResolveProfile(ctx, cfg, app)) return; } await next(ctx, ct); diff --git a/src/Covenant.Governance/ConfigValidation.cs b/src/Covenant.Governance/ConfigValidation.cs index ac3d57b..efe7494 100644 --- a/src/Covenant.Governance/ConfigValidation.cs +++ b/src/Covenant.Governance/ConfigValidation.cs @@ -8,10 +8,24 @@ public sealed record ConfigIssue(string Path, string Code, string Message); public sealed record ConfigValidationResult(IReadOnlyList Errors, IReadOnlyList Warnings) { public bool IsValid => Errors.Count == 0; + + /// False ⇒ the candidate has structural errors (a required object/list/element is null, or an enum value + /// is not a defined member). Semantic checks and the impact preview were NOT run: the candidate cannot even be + /// compiled into a snapshot. + public bool StructurallySound { get; init; } = true; +} + +/// A configuration that validated but could not be compiled into a runtime snapshot (e.g. a provider +/// client for an enabled, referenced connection could not be built). Thrown by the compile step BEFORE anything +/// durable is written; surfaced as validation errors (422), never a silently skipped target. +public sealed class ConfigCompileException(IReadOnlyList issues) + : Exception("configuration could not be compiled: " + string.Join("; ", issues.Select(i => $"{i.Path} {i.Code}"))) +{ + public IReadOnlyList Issues { get; } = issues; } /// Startup-owned facts the validator checks a candidate against (ADR-0011). None of these are -/// console-editable: a configuration edit can never widen egress or invent a secret. +/// console-editable: a configuration edit can never widen egress, invent a secret, or declare a host in-perimeter. public sealed class ValidationEnvironment { /// Egress allow-list as "host:port" (startup Providers:ProbeAllowList ∪ bootstrap endpoints). @@ -20,13 +34,14 @@ public sealed class ValidationEnvironment /// Secret reference → is a non-empty value configured server-side. Never returns the value. public required Func SecretAvailable { get; init; } - /// Legacy-import compatibility: the imported PII/PHI placeholder target on the unconfigured "local" - /// connection is a WARNING (behaviour preserved, provider stage refuses it) instead of an error. - public bool LegacyCompat { get; init; } + /// Endpoint authorities ("host:port") the operator declared in-perimeter at startup + /// (Providers:LocalEndpoints ∪ the legacy Local:Endpoint). Only these may carry Boundary.Local. + public IReadOnlySet LocalEndpoints { get; init; } = new HashSet(StringComparer.OrdinalIgnoreCase); } /// Pure configuration validator (ADR-0011/0013/0014). Codes are part of the API contract -/// (docs/ui-api-contract.md v2 "Configuration"). +/// (docs/ui-api-contract.md v2 "Configuration"). Total: never throws on any deserializable candidate — a null +/// required object/list/element or an undefined enum value is a structural error with a field path. public static class ConfigValidator { public static readonly IReadOnlySet LegacySecretRefs = @@ -58,8 +73,116 @@ public static bool IsAllowedSecretRef(string secretRef) return $"{u.Host}:{u.Port}"; } + /// Authority a connection would connect to (explicit endpoint, else the cloud SDK default); null if none/invalid. + public static string? AuthorityOf(ConnectionConfig conn) + => conn.Endpoint is null ? DefaultAuthority(conn.Kind) : EndpointAuthority(conn.Endpoint); + + /// Structural pass (ADR-0011 "validation is total"): every required object, list, element and id is + /// non-null and every enum value is a defined member. Generic Enum.IsDefined<T> is AOT-safe. + public static List Structural(CovenantConfig c) + { + var e = new System.Collections.Generic.List(); + void Req(string path) => e.Add(new ConfigIssue(path, "required", "required value is missing (null)")); + void Defined(string path, T value) where T : struct, System.Enum + { + if (!System.Enum.IsDefined(value)) + e.Add(new ConfigIssue(path, "invalid_enum", + $"'{Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture)}' is not a defined {typeof(T).Name} value")); + } + bool NonNullList(string path, IReadOnlyList? list) + { + if (list is null) { Req(path); return false; } + for (int i = 0; i < list.Count; i++) + if (list[i] is null) Req($"{path}[{i}]"); + return true; + } + + Defined("mode", c.Mode); + + if (NonNullList("connections", c.Connections)) + for (int i = 0; i < c.Connections.Count; i++) + { + if (c.Connections[i] is not { } conn) continue; + var p = $"connections[{i}]"; + if (conn.Id is null) Req($"{p}.id"); + Defined($"{p}.kind", conn.Kind); + Defined($"{p}.boundary", conn.Boundary); + if (NonNullList($"{p}.models", conn.Models)) + for (int m = 0; m < conn.Models.Count; m++) + { + if (conn.Models[m] is not { } model) continue; + if (model.ModelId is null) Req($"{p}.models[{m}].model_id"); + if (model.Price is { } price && price.Basis is null) Req($"{p}.models[{m}].price.basis"); + } + } + + if (NonNullList("applications", c.Applications)) + for (int i = 0; i < c.Applications.Count; i++) + if (c.Applications[i] is { } app) + { + if (app.Id is null) Req($"applications[{i}].id"); + if (app.Team is null) Req($"applications[{i}].team"); + NonNullList($"applications[{i}].granted_profiles", app.GrantedProfiles); + } + + if (NonNullList("profiles", c.Profiles)) + for (int i = 0; i < c.Profiles.Count; i++) + if (c.Profiles[i] is { } pr) + { + if (pr.Id is null) Req($"profiles[{i}].id"); + Defined($"profiles[{i}].baseline", pr.Baseline); + if (pr.Name is null) Req($"profiles[{i}].name"); + } + + if (NonNullList("policies", c.Policies)) + for (int i = 0; i < c.Policies.Count; i++) + { + if (c.Policies[i] is not { } pol) continue; + var p = $"policies[{i}]"; + if (pol.Id is null) Req($"{p}.id"); + if (pol.Name is null) Req($"{p}.name"); + Defined($"{p}.strategy", pol.Strategy); + if (NonNullList($"{p}.classifications", pol.Classifications)) + for (int k = 0; k < pol.Classifications.Count; k++) Defined($"{p}.classifications[{k}]", pol.Classifications[k]); + NonNullList($"{p}.profiles", pol.Profiles); + if (NonNullList($"{p}.targets", pol.Targets)) + for (int t = 0; t < pol.Targets.Count; t++) + { + if (pol.Targets[t] is not { } target) continue; + if (target.ConnectionId is null) Req($"{p}.targets[{t}].connection_id"); + if (target.ModelId is null) Req($"{p}.targets[{t}].model_id"); + } + if (pol.Retry is null) Req($"{p}.retry"); + else NonNullList($"{p}.retry.on", pol.Retry.On); + } + + if (NonNullList("budgets", c.Budgets)) + for (int i = 0; i < c.Budgets.Count; i++) + { + if (c.Budgets[i] is not { } b) continue; + if (b.Id is null) Req($"budgets[{i}].id"); + if (b.Scope is null) Req($"budgets[{i}].scope"); + Defined($"budgets[{i}].period", b.Period); + Defined($"budgets[{i}].enforcement", b.Enforcement); + NonNullList($"budgets[{i}].warn_at", b.WarnAt); + } + + if (c.Settings is null) Req("settings"); + if (c.SavingsBaseline is { } sb) + { + if (sb.ConnectionId is null) Req("savings_baseline.connection_id"); + if (sb.ModelId is null) Req("savings_baseline.model_id"); + } + return e; + } + public static ConfigValidationResult Validate(CovenantConfig c, ValidationEnvironment env) { + ArgumentNullException.ThrowIfNull(c); + var structural = Structural(c); + if (structural.Count > 0) + return new ConfigValidationResult(structural, []) { StructurallySound = false }; + var errors = new List(); var warnings = new List(); void Err(string path, string code, string msg) => errors.Add(new ConfigIssue(path, code, msg)); @@ -75,14 +198,16 @@ public static ConfigValidationResult Validate(CovenantConfig c, ValidationEnviro if (!connections.TryAdd(conn.Id, conn)) { Err($"{p}.id", "duplicate_id", $"connection id '{conn.Id}' is used more than once"); continue; } if (string.IsNullOrWhiteSpace(conn.DisplayName)) Err($"{p}.display_name", "required", "display name is required"); - if (conn.Kind is ProviderKind.OpenAi or ProviderKind.Anthropic && conn.Boundary != Boundary.Cloud) - Err($"{p}.boundary", "invalid_boundary", $"{conn.Kind} is a cloud provider; boundary must be cloud"); + bool cloudKind = conn.Kind is ProviderKind.OpenAi or ProviderKind.Anthropic; + if (cloudKind && conn.Boundary != Boundary.Cloud) + Err($"{p}.boundary", "boundary_not_approved", $"{conn.Kind} is a cloud provider; its boundary is always cloud"); string? authority; if (conn.Endpoint is null) { authority = DefaultAuthority(conn.Kind); - if (authority is null) + // A disabled connection with no endpoint is an explicit "not configured" placeholder (legacy import). + if (authority is null && conn.Enabled) Err($"{p}.endpoint", "endpoint_required", $"{conn.Kind} connections need an explicit http(s) endpoint"); } else @@ -98,6 +223,12 @@ public static ConfigValidationResult Validate(CovenantConfig c, ValidationEnviro else Warn($"{p}.endpoint", "endpoint_not_allow_listed", msg); } + // Boundary is not self-declared (ADR-0011): Local only for startup-approved in-perimeter endpoints. + if (!cloudKind && conn.Boundary == Boundary.Local && (conn.Enabled || authority is not null) + && (authority is null || !env.LocalEndpoints.Contains(authority))) + Err($"{p}.boundary", "boundary_not_approved", + $"{authority ?? "this endpoint"} is not a startup-approved local endpoint (Providers:LocalEndpoints / Local:Endpoint); a connection cannot declare itself in-perimeter"); + if (conn.SecretRef is { } secretRef) { if (!IsAllowedSecretRef(secretRef)) @@ -105,7 +236,7 @@ public static ConfigValidationResult Validate(CovenantConfig c, ValidationEnviro else if (conn.Enabled && !env.SecretAvailable(secretRef)) Err($"{p}.secret_ref", "secret_unavailable", $"secret '{secretRef}' is not configured on the server (set it in the environment/vault and restart)"); } - else if (conn.Enabled && conn.Kind is ProviderKind.OpenAi or ProviderKind.Anthropic) + else if (conn.Enabled && cloudKind) Err($"{p}.secret_ref", "secret_unavailable", $"{conn.Kind} requires a server-side secret reference"); if (conn.Enabled && conn.Boundary == Boundary.Cloud && c.Mode == ProviderMode.LocalOnly) @@ -150,10 +281,10 @@ public static ConfigValidationResult Validate(CovenantConfig c, ValidationEnviro if (string.IsNullOrWhiteSpace(app.Team)) Err($"{p}.team", "required", "team is required"); for (int g = 0; g < app.GrantedProfiles.Count; g++) if (!profiles.Contains(app.GrantedProfiles[g])) - Err($"{p}.granted_profiles[{g}]", "profile_not_found", $"profile '{app.GrantedProfiles[g]}' does not exist"); + Err($"{p}.granted_profiles[{g}]", "profile_not_found", $"profile '{Evidence.Bounded(app.GrantedProfiles[g])}' does not exist"); if (app.DefaultProfile is { } def) { - if (!profiles.Contains(def)) Err($"{p}.default_profile", "profile_not_found", $"profile '{def}' does not exist"); + if (!profiles.Contains(def)) Err($"{p}.default_profile", "profile_not_found", $"profile '{Evidence.Bounded(def)}' does not exist"); else if (!app.GrantedProfiles.Contains(def, StringComparer.Ordinal)) Err($"{p}.default_profile", "default_profile_not_granted", $"default profile '{def}' is not granted to '{app.Id}'"); } @@ -198,7 +329,7 @@ public static ConfigValidationResult Validate(CovenantConfig c, ValidationEnviro if (pol.Classifications.Count == 0) Err($"{p}.classifications", "required", "a policy applies to at least one classification"); for (int g = 0; g < pol.Profiles.Count; g++) if (!profiles.Contains(pol.Profiles[g])) - Err($"{p}.profiles[{g}]", "profile_not_found", $"profile '{pol.Profiles[g]}' does not exist"); + Err($"{p}.profiles[{g}]", "profile_not_found", $"profile '{Evidence.Bounded(pol.Profiles[g])}' does not exist"); if (pol.Targets.Count == 0 && pol.Enabled) Warn($"{p}.targets", "no_route_for_classification", "policy has no targets: its matching traffic is refused"); if (pol.Strategy == RoutingStrategy.LengthHeuristic && pol.ThresholdTokens < 0) @@ -212,21 +343,19 @@ public static ConfigValidationResult Validate(CovenantConfig c, ValidationEnviro { var target = pol.Targets[t]; var tp = $"{p}.targets[{t}]"; + // Always an error, in every mode: an unknown connection is never eligible (no legacy bypass). if (!connections.TryGetValue(target.ConnectionId, out var conn)) { - var msg = $"connection '{target.ConnectionId}' does not exist"; - if (env.LegacyCompat) Warn(tp, "unknown_connection", msg + " — imported legacy rule; requests matching it are refused at the provider stage"); - else Err(tp, "unknown_connection", msg); + Err(tp, "unknown_connection", $"connection '{Evidence.Bounded(target.ConnectionId)}' does not exist"); continue; } var model = conn.Models.FirstOrDefault(m => string.Equals(m.ModelId, target.ModelId, StringComparison.Ordinal)); - if (model is null) { Err(tp, "unknown_model", $"model '{target.ModelId}' is not permitted on connection '{conn.Id}'"); continue; } + if (model is null) { Err(tp, "unknown_model", $"model '{Evidence.Bounded(target.ModelId)}' is not permitted on connection '{conn.Id}'"); continue; } if (conn.Boundary == Boundary.Cloud) { - if (sensitive && !pol.AllowSensitiveCloud) - Warn(tp, "sensitive_cloud_without_ack", $"cloud target never serves PII/PHI under this policy (allow_sensitive_cloud is off); it is ineligible for those classifications"); - else if (sensitive && pol.AllowSensitiveCloud) - Warn(tp, "sensitive_cloud_without_ack", "WARNING: this policy explicitly allows PII/PHI to reach a cloud destination"); + // No escape hatch (ADR-0013): a PII/PHI policy cannot list a cloud destination. + if (sensitive) + Err(tp, "sensitive_cloud_target", $"{conn.Id}/{model.ModelId} is a cloud destination; a policy covering PII/PHI may list only local targets"); if (model.Price is null && anyHard && pol.Enabled) Err(tp, "unpriced_paid_target_under_hard_budget", $"{conn.Id}/{model.ModelId} has no price; a paid destination cannot run under a hard budget unpriced"); } @@ -249,7 +378,7 @@ public static ConfigValidationResult Validate(CovenantConfig c, ValidationEnviro } // Coverage: every classification should have some applicable policy for the default (no-profile) path. - foreach (var cls in Enum.GetValues()) + foreach (var cls in System.Enum.GetValues()) { if (cls == DataClassification.Public) continue; // Public is reachable only via an explicit Public profile if (!c.Policies.Any(pol => pol.Enabled && pol.Classifications.Contains(cls))) diff --git a/src/Covenant.Governance/PolicyV2.cs b/src/Covenant.Governance/PolicyV2.cs index 11738a1..90f1866 100644 --- a/src/Covenant.Governance/PolicyV2.cs +++ b/src/Covenant.Governance/PolicyV2.cs @@ -7,7 +7,7 @@ namespace Covenant.Governance; /// policies at the same specificity are refused (validation rejects that configuration; runtime refuses /// rather than choosing an arbitrary winner). No match ⇒ refusal. Paused policy ⇒ refusal. Each target is /// then checked for eligibility (route paused, connection known + enabled, model permitted on the connection, -/// mode boundary, sensitive-cloud rule, priced under a hard budget); the eligible ones in order are the +/// mode boundary, PII/PHI never cloud, priced under a hard budget); the eligible ones in order are the /// candidates [primary, approved fallback…]. Availability (is a client registered/healthy) is NOT /// eligibility — the provider stage owns that and fails closed. public static class PolicyEngineV2 @@ -25,25 +25,22 @@ public static IReadOnlyList Match(CovenantConfig config, DataCla return specific.Count > 0 ? specific : matching; } - /// Why this target is not eligible for this request; null = eligible. - public static string? Ineligibility(IRequestConfiguration cfg, PolicyConfigV2 policy, PolicyTarget target, DataClassification classification) + /// Why this target is not eligible for this request; null = eligible. No mode bypasses these rules: + /// an unknown or disabled connection is never eligible (legacy-cloud included), and PII/PHI never reach a + /// cloud destination (no escape hatch; validation also refuses such a policy). + public static string? Ineligibility(IRequestConfiguration cfg, PolicyTarget target, DataClassification classification) { if (target.Paused) return "route paused"; var connection = cfg.FindConnection(target.ConnectionId); - if (connection is null) - { - // Legacy-cloud compatibility (migration-v2.md): the imported PII/PHI rule names the unconfigured - // local placeholder exactly as before v2; it stays a candidate so the provider stage refuses it - // fail-closed ("no adapter registered …"), preserving the pre-v2 evidence. Never in other modes. - return cfg.Config.Mode == ProviderMode.LegacyCloud ? null : $"unknown connection '{Evidence.Bounded(target.ConnectionId)}'"; - } - if (!connection.Enabled) return $"connection '{connection.Id}' disabled"; + if (connection is null) return $"unknown connection '{Evidence.Bounded(target.ConnectionId)}'"; + if (!connection.Enabled) + return $"connection '{connection.Id}' is disabled" + (connection.Endpoint is null ? " (not configured)" : ""); var model = cfg.FindModel(connection.Id, target.ModelId); if (model is null) return $"model not permitted on connection '{connection.Id}'"; if (connection.Boundary == Boundary.Cloud) { if (cfg.Config.Mode == ProviderMode.LocalOnly) return "cloud destination excluded in local-only mode"; - if (classification >= DataClassification.Pii && !policy.AllowSensitiveCloud) + if (classification >= DataClassification.Pii) return $"{classification} is never routed to a cloud destination"; if (model.Price is null && cfg.Config.Budgets.Any(b => b.Enforcement == BudgetEnforcement.Hard)) return "unpriced paid destination under a hard budget"; @@ -51,6 +48,34 @@ public static IReadOnlyList Match(CovenantConfig config, DataCla return null; } + /// Resolves a model override against routes (ADR-0013): "connection/model" names exactly that target; + /// a bare model id resolves only when exactly one route carries it. Returns the matching distinct routes (0, 1 or + /// several — several means ambiguous and MUST be refused, never "first wins"). + public static List ResolveOverride(IEnumerable routes, string requested) + { + bool IsComposite(RouteTarget r) => string.Equals($"{r.AdapterKey}/{r.ModelId}", requested, StringComparison.OrdinalIgnoreCase); + bool IsBare(RouteTarget r) => string.Equals(r.ModelId, requested, StringComparison.OrdinalIgnoreCase); + + var matches = new List(); + foreach (var r in routes) + if ((IsComposite(r) || IsBare(r)) && !matches.Contains(r)) matches.Add(r); + if (matches.Count > 1) + { + // The composite form is exact: it wins when it singles out one route and no OTHER route carries the + // same string as a bare model id (that pathological collision stays ambiguous — refused). + var composite = matches.Where(IsComposite).ToList(); + if (composite.Count == 1 && matches.Where(IsBare).All(b => b == composite[0])) + return composite; + } + return matches; + } + + /// Evidence text for an ambiguous bare model id. + public static string AmbiguousOverride(string requested, IEnumerable matches) + => $"model id '{Evidence.Bounded(requested)}' is ambiguous across connections " + + string.Join(", ", matches.Select(m => Evidence.Bounded(m.AdapterKey)).Distinct(StringComparer.Ordinal)) + + " — use connection/model"; + public static PolicyOutcome Evaluate(IRequestConfiguration cfg, InferenceContext ctx) => Evaluate(cfg, ctx.Classification, ctx.ProfileId, ctx.Request.RequestedModel, ctx.Request.Messages); @@ -74,21 +99,22 @@ public static PolicyOutcome Evaluate( foreach (var t in policy.Targets) { var route = new RouteTarget(t.ConnectionId, t.ModelId); - if (Ineligibility(cfg, policy, t, classification) is { } why) excluded.Add(new ExcludedTarget(route, why)); + if (Ineligibility(cfg, t, classification) is { } why) excluded.Add(new ExcludedTarget(route, why)); else eligible.Add((t, route)); } - // Model override: must name a target of the matching policy AND be eligible; it pins (no fallback). + // Model override: must resolve to exactly ONE eligible target of the matching policy; it pins (no fallback). + // An ambiguous bare id (eligible on two connections) is refused — never "first wins". if (!string.IsNullOrWhiteSpace(requestedModel)) { - bool Named(RouteTarget r) => string.Equals(r.ModelId, requestedModel, StringComparison.OrdinalIgnoreCase) - || string.Equals($"{r.AdapterKey}/{r.ModelId}", requestedModel, StringComparison.OrdinalIgnoreCase); - var pinned = eligible.FirstOrDefault(e => Named(e.Route)).Route; - if (pinned is not null) - return Allowed(cfg, policy, classification, pinned, [pinned], excluded, "allowed"); - var refusedNamed = excluded.FirstOrDefault(x => Named(x.Target)); - var reason = refusedNamed is not null - ? $"model '{Evidence.Bounded(requestedModel)}' not permitted for classification '{classification}' ({refusedNamed.Reason})" + var pinned = ResolveOverride(eligible.Select(e => e.Route), requestedModel); + if (pinned.Count > 1) + return PolicyOutcome.Deny(AmbiguousOverride(requestedModel, pinned)) with { PolicyId = policy.Id, Excluded = excluded }; + if (pinned.Count == 1) + return Allowed(cfg, policy, classification, pinned[0], [pinned[0]], excluded, "allowed"); + var refusedNamed = ResolveOverride(excluded.Select(x => x.Target), requestedModel); + var reason = refusedNamed.Count > 0 + ? $"model '{Evidence.Bounded(requestedModel)}' not permitted for classification '{classification}' ({excluded.First(x => x.Target == refusedNamed[0]).Reason})" : $"model '{Evidence.Bounded(requestedModel)}' not permitted for classification '{classification}'"; return PolicyOutcome.Deny(reason) with { PolicyId = policy.Id, Excluded = excluded }; } diff --git a/src/Covenant.Governance/RuntimeSnapshot.cs b/src/Covenant.Governance/RuntimeSnapshot.cs index 6fb9bcf..418b8b8 100644 --- a/src/Covenant.Governance/RuntimeSnapshot.cs +++ b/src/Covenant.Governance/RuntimeSnapshot.cs @@ -1,7 +1,54 @@ +using System.Collections.ObjectModel; using Covenant.Core; namespace Covenant.Governance; +/// Deep copy of a validated configuration into snapshot-owned, read-only collections (ADR-0011): every +/// list (connections, models, applications, granted profiles, profiles, policies, classifications, policy profiles, +/// targets, retry triggers, budgets, warning thresholds) is copied into a new array wrapped in a +/// , so neither later mutation of the caller's lists nor a cast back to a mutable +/// type can change an active snapshot. Records themselves are init-only. Only structurally valid configurations +/// (see ) are compiled; a null list or element is refused, never defaulted. +public static class ConfigFreezer +{ + public static CovenantConfig Freeze(CovenantConfig c) + { + ArgumentNullException.ThrowIfNull(c); + var settings = c.Settings ?? throw NotSound("settings"); + return c with + { + Connections = Copy(c.Connections, "connections", conn => conn with { Models = Copy(conn.Models, "models", m => m) }), + Applications = Copy(c.Applications, "applications", a => a with { GrantedProfiles = Copy(a.GrantedProfiles, "granted_profiles", g => g) }), + Profiles = Copy(c.Profiles, "profiles", p => p), + Policies = Copy(c.Policies, "policies", p => p with + { + Classifications = Copy(p.Classifications, "classifications", x => x), + Profiles = Copy(p.Profiles, "profiles", x => x), + Targets = Copy(p.Targets, "targets", t => t), + Retry = (p.Retry ?? throw NotSound("retry")) with { On = Copy(p.Retry.On, "retry.on", x => x) }, + }), + Budgets = Copy(c.Budgets, "budgets", b => b with { WarnAt = Copy(b.WarnAt, "warn_at", x => x) }), + Settings = settings with { }, + }; + } + + private static ReadOnlyCollection Copy(IReadOnlyList? source, string what, Func map) + { + if (source is null) throw NotSound(what); + var copy = new T[source.Count]; + for (int i = 0; i < copy.Length; i++) + { + var item = source[i]; + if (item is null) throw NotSound(what); + copy[i] = map(item); + } + return Array.AsReadOnly(copy); + } + + private static ArgumentException NotSound(string what) + => new($"configuration is not structurally valid ({what} is null); validate before compiling"); +} + /// Compiled, immutable view of one validated version (ADR-0011): lookup /// tables for applications, profiles, connections and the connection-scoped price book, plus the snapshot-owned /// runtime resources (provider clients) built by the Host. Reference-counted: the holder owns one reference @@ -20,18 +67,21 @@ public sealed class RuntimeSnapshot : IRequestConfiguration public RuntimeSnapshot(CovenantConfig config, object? resources = null) { - Config = config; + // Snapshot-owned deep copy: the caller's lists may alias anything (a deserialized body, a test's List<>). + Config = ConfigFreezer.Freeze(config); _resources = resources; _applications = new Dictionary(StringComparer.Ordinal); - foreach (var a in config.Applications) _applications.TryAdd(a.Id, a); + // Null ids cannot occur after structural validation; skipped defensively (an impact preview of an invalid + // candidate must never throw). + foreach (var a in Config.Applications) if (a.Id is not null) _applications.TryAdd(a.Id, a); _profiles = new Dictionary(StringComparer.Ordinal); - foreach (var p in config.Profiles) _profiles.TryAdd(p.Id, p); + foreach (var p in Config.Profiles) if (p.Id is not null) _profiles.TryAdd(p.Id, p); _connections = new Dictionary(StringComparer.Ordinal); _models = new Dictionary<(string, string), ModelConfig>(); - foreach (var c in config.Connections) + foreach (var c in Config.Connections) { - if (!_connections.TryAdd(c.Id, c)) continue; - foreach (var m in c.Models) _models.TryAdd((c.Id, m.ModelId), m); + if (c.Id is null || !_connections.TryAdd(c.Id, c)) continue; + foreach (var m in c.Models) if (m.ModelId is not null) _models.TryAdd((c.Id, m.ModelId), m); } } diff --git a/src/Covenant.Host/ConfigAdminApi.cs b/src/Covenant.Host/ConfigAdminApi.cs index d212cd5..fc45055 100644 --- a/src/Covenant.Host/ConfigAdminApi.cs +++ b/src/Covenant.Host/ConfigAdminApi.cs @@ -106,18 +106,36 @@ public static void MapConfigAdmin(this WebApplication app, ConfigAdminServices s return Error("invalid_request", "config is required", StatusCodes.Status400BadRequest); var active = s.Runtime.Current; var validation = s.Validate(candidate); + var errors = validation.Errors.ToList(); var warnings = validation.Warnings.ToList(); if (body.BaseVersion is { } bv && bv != active.Version) warnings.Add(new ConfigIssue("base_version", "stale_base_version", $"candidate was edited from v{bv}; the active version is v{active.Version} — applying with If-Match \"v{bv}\" will be rejected (412)")); - var impact = ImpactAnalyzer.Analyze(active, new RuntimeSnapshot(candidate), s.SecretAvailable); + if (validation.IsValid) + { + // Same compile step as apply (provider clients included, no network I/O): a client that cannot be + // built for an enabled, referenced connection is reported here too (client_unbuildable). + try + { + s.Compile(candidate).Release(); + } + catch (ConfigCompileException ex) + { + errors.AddRange(ex.Issues); + } + } + // A structurally broken candidate (null required value / undefined enum) cannot be compiled even for + // a preview: report the errors with their paths, no impact — never an exception or a 500. + ImpactView? impact = validation.StructurallySound + ? ImpactView.From(ImpactAnalyzer.Analyze(active, new RuntimeSnapshot(candidate), s.SecretAvailable)) + : null; return Json(new ConfigValidateResponse { - Valid = validation.IsValid, + Valid = errors.Count == 0, ActiveVersion = active.Version, - Errors = ConfigIssueView.From(validation.Errors), + Errors = ConfigIssueView.From(errors), Warnings = ConfigIssueView.From(warnings), - Impact = ImpactView.From(impact), + Impact = impact, }, ConfigJsonContext.Default.ConfigValidateResponse); }); @@ -159,7 +177,8 @@ public static void MapConfigAdmin(this WebApplication app, ConfigAdminServices s { if (!s.Authorized(http)) return Unauthorized(); http.Response.Headers.CacheControl = "no-store"; - return n <= s.Runtime.Current.Version && s.Repository.GetVersion(n) is { } c + // Journal-only (ADR-0011): an orphan (written, never activated) is 404 exactly like an unknown number. + return s.Repository.GetVersion(n) is { } c ? Json(c, ConfigJsonContext.Default.CovenantConfig) : Error("not_found", $"no activated configuration version {n}", StatusCodes.Status404NotFound); }); @@ -171,7 +190,8 @@ public static void MapConfigAdmin(this WebApplication app, ConfigAdminServices s var (body, failure) = await ReadAsync(http, ConfigJsonContext.Default.ConfigRollbackRequest, ct); if (failure is not null) return failure; var active = s.Runtime.Current.Version; - if (body!.TargetVersion < 1 || body.TargetVersion > active || s.Repository.GetVersion(body.TargetVersion) is not { } target) + // Only activated versions (journal entries) can be rolled back to; orphans and unknown numbers are 404. + if (s.Repository.GetVersion(body!.TargetVersion) is not { } target) return Error("not_found", $"no activated configuration version {body.TargetVersion}", StatusCodes.Status404NotFound, active); return await ApplyAsync(http, s, target, body.ExpectedActiveVersion, "rollback", $"rollback to v{body.TargetVersion}", body.TargetVersion, ct); diff --git a/src/Covenant.Host/ConfigBootstrap.cs b/src/Covenant.Host/ConfigBootstrap.cs index cc48436..0c9909d 100644 --- a/src/Covenant.Host/ConfigBootstrap.cs +++ b/src/Covenant.Host/ConfigBootstrap.cs @@ -27,6 +27,37 @@ void AddEndpoint(string? endpoint) return set; } + /// Startup-approved in-perimeter endpoint authorities (ADR-0011 boundary binding): every "host:port" in + /// Providers:LocalEndpoints (comma-separated host:port or absolute URLs) plus the legacy Local:Endpoint + /// authority. Only these may carry Boundary.Local. Startup-only, never console-editable. (They must still be on + /// the egress allow-list to be reachable — this list labels, it does not widen egress.) + public static HashSet LocalEndpoints(IConfiguration config) + { + var set = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var raw in (config["Providers:LocalEndpoints"] ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var authority = raw.Contains("://", StringComparison.Ordinal) ? ConfigValidator.EndpointAuthority(raw) : NormalizeHostPort(raw); + if (authority is not null) set.Add(authority); + } + if (StartupValidation.Trimmed(config["Local:Endpoint"]) is { } local && ConfigValidator.EndpointAuthority(local) is { } la) + set.Add(la); + return set; + } + + private static string? NormalizeHostPort(string hostPort) + => Uri.TryCreate("http://" + hostPort, UriKind.Absolute, out var u) && u.AbsolutePath == "/" && !hostPort.EndsWith(':') + && hostPort.Contains(':', StringComparison.Ordinal) ? $"{u.Host}:{u.Port}" : null; + + /// Secret values the configuration-write history must never contain (redaction source): every allowed + /// secret reference's value, Auth:Keys values and Admin:Token. Values stay in this closure; never logged. + public static Func Redactor(IConfiguration config) + { + var values = new List { config["OpenAI:ApiKey"], config["Anthropic:ApiKey"], config["Local:ApiKey"], config["Admin:Token"] }; + foreach (var child in config.GetSection("Secrets").GetChildren()) values.Add(child.Value); + foreach (var child in config.GetSection("Auth:Keys").GetChildren()) values.Add(child["Key"]); + return SecretRedaction.ForValues(values); + } + /// Secret reference → configured (non-empty) on the server. Only the permitted reference forms resolve. public static Func SecretAvailability(IConfiguration config) => secretRef => ConfigValidator.IsAllowedSecretRef(secretRef) && !string.IsNullOrWhiteSpace(config[secretRef]); @@ -45,6 +76,17 @@ public static Func SecretAvailability(IConfiguration config) public static class LegacyImport { public const string UnconfiguredLocalModel = "local-model-not-configured"; + public const string UnconfiguredLocalDisplayName = "Local model — not configured (import placeholder)"; + + /// The explicitly DISABLED placeholder a legacy import creates when no Local:* is configured: the + /// pre-v2 PII/PHI route keeps pointing at it, so the migration preview and every refusal say why sensitive data + /// is refused ("connection 'local' is disabled (not configured)"). Disabled connections are never eligible. + public static ConnectionConfig LocalPlaceholder() => new() + { + Id = "local", DisplayName = UnconfiguredLocalDisplayName, Kind = ProviderKind.OpenAiCompatible, Boundary = Boundary.Local, + Endpoint = null, Enabled = false, SecretRef = null, + Models = [new ModelConfig { ModelId = UnconfiguredLocalModel, Price = new PriceConfig { InputPer1M = 0m, OutputPer1M = 0m, Basis = "zero-marginal-local" } }], + }; public static CovenantConfig Build(IConfiguration config, DateTimeOffset now, List errors) { @@ -104,9 +146,11 @@ public static CovenantConfig Build(IConfiguration config, DateTimeOffset now, Li SecretRef = string.IsNullOrWhiteSpace(config["Local:ApiKey"]) ? null : "Local:ApiKey", Models = [Model(localModelId)], }); + else + connections.Add(LocalPlaceholder()); // Pre-v2 routes: Public/Internal ordered cheapest → (Anthropic mid-list) → strongest with the length - // heuristic; PII/PHI → local (the unconfigured placeholder fails closed at the provider stage, as before). + // heuristic; PII/PHI → local (without Local:* the target is the DISABLED placeholder: refused at policy). // Local-only: every classification → the one approved local model. Single attempt (no pre-v2 fallback). var single = new RetrySettings { MaxAttempts = 1 }; var localTarget = new PolicyTarget { ConnectionId = "local", ModelId = localModelId }; @@ -152,20 +196,16 @@ public static CovenantConfig Build(IConfiguration config, DateTimeOffset now, Li Description = "Default for pre-v2 application keys: baseline Internal." }, }; + // One application per key, ONCE, at v1 (ADR-0012). The id is the key's Application ?? Principal, normalized by + // ApplicationIds.FromKey exactly as the auth stage normalizes it — so every key is bound (e.g. an e-mail + // principal maps to "alice-example.com-"). After v1, a key whose application is missing is refused. var applications = new List(); - foreach (var child in config.GetSection("Auth:Keys").GetChildren()) - { - var appId = child["Application"] is { Length: > 0 } a ? a : child["Principal"]; - var team = child["Team"]; - // Keys whose application id is not a valid configuration id stay unbound (legacy behaviour: team from - // the key, legacy-internal profile) — never a refusal to start over a cosmetic identifier. - if (!ConfigValidator.IsValidId(appId) || string.IsNullOrEmpty(team) || applications.Any(x => x.Id == appId)) continue; + foreach (var (appId, team) in KeyApplications(config)) applications.Add(new ApplicationConfig { - Id = appId!, Team = team, Enabled = true, ConsoleTesting = false, + Id = appId, Team = team, Enabled = true, ConsoleTesting = false, GrantedProfiles = [PolicyEngineV2.LegacyInternalProfile], DefaultProfile = PolicyEngineV2.LegacyInternalProfile, }); - } var budgets = new List(); if (TryCap(config, errors) is { } globalCap) @@ -214,6 +254,22 @@ public static CovenantConfig Build(IConfiguration config, DateTimeOffset now, Li }; } + /// Distinct (application id, team) per Auth:Keys entry, in key order (first key wins the team). + internal static List<(string AppId, string Team)> KeyApplications(IConfiguration config) + { + var list = new List<(string, string)>(); + foreach (var child in config.GetSection("Auth:Keys").GetChildren()) + { + var raw = child["Application"] is { Length: > 0 } a ? a : child["Principal"]; + var team = child["Team"]; + if (string.IsNullOrEmpty(raw) || string.IsNullOrEmpty(team)) continue; // Program refuses such keys at startup + var appId = ApplicationIds.FromKey(raw); + if (list.Any(x => x.Item1 == appId)) continue; + list.Add((appId, team)); + } + return list; + } + internal static decimal? TryCap(IConfiguration config, List errors) { var raw = config["Budget:GlobalCapUsd"]; @@ -286,14 +342,12 @@ public static CovenantConfig Build(string seed, IConfiguration config, DateTimeO GrantedProfiles = ["public-demo", "internal-default"], DefaultProfile = "internal-default", }, }; - foreach (var child in config.GetSection("Auth:Keys").GetChildren()) + foreach (var (appId, team) in LegacyImport.KeyApplications(config)) { - var appId = child["Application"] is { Length: > 0 } a ? a : child["Principal"]; - var team = child["Team"]; - if (!ConfigValidator.IsValidId(appId) || string.IsNullOrEmpty(team) || applications.Any(x => x.Id == appId)) continue; + if (applications.Any(x => x.Id == appId)) continue; applications.Add(new ApplicationConfig { - Id = appId!, Team = team, Enabled = true, ConsoleTesting = false, + Id = appId, Team = team, Enabled = true, ConsoleTesting = false, GrantedProfiles = ["internal-default"], DefaultProfile = "internal-default", }); } @@ -352,7 +406,8 @@ public static class ConfigAuditEvents public static AuditEntry Activated(CovenantConfig config, string operatorRef, DateTimeOffset now, bool recovered = false) { - var summary = config.ChangeSummary is { Length: > 0 } s ? ": " + Governance.Evidence.Bounded(s) : ""; + // The summary was redacted + bounded (≤ 500) when the version was stamped; bound again defensively. + var summary = ConfigRepository.BoundSummary(config.ChangeSummary) is { Length: > 0 } s ? ": " + s : ""; var reason = $"config.activated v{config.Version}" + (config.BaseVersion is { } b ? $" (base v{b})" : "") + (config.RolledBackFrom is { } r ? $" rollback of v{r}" : "") diff --git a/src/Covenant.Host/ConfigContracts.cs b/src/Covenant.Host/ConfigContracts.cs index 961fc4c..c23d504 100644 --- a/src/Covenant.Host/ConfigContracts.cs +++ b/src/Covenant.Host/ConfigContracts.cs @@ -6,9 +6,18 @@ namespace Covenant.Host; // Configuration persistence + admin API payloads (ADR-0011, docs/ui-api-contract.md v2 "Configuration"). -// snake_case property names; enums as their C# names via JsonStringEnumConverter (one per enum, AOT-safe). -// Bodies are (de)serialized explicitly with ConfigJsonContext.Default.* — never through the web-default options — -// so the wire names are exactly the snake_case names below. +// snake_case property names. Enum spellings are a STABLE CONTRACT (docs/ui-api-contract.md v2 "Wire spellings"): +// mode ProviderMode "local-only" | "hybrid" | "legacy-cloud" (kebab-case) +// strategy RoutingStrategy "fixed" | "length-heuristic" (kebab-case) +// period BudgetPeriod "none" | "daily" | "monthly" (kebab-case) +// enforcement BudgetEnforcement "hard" | "warn-only" (kebab-case) +// kind ProviderKind "Ollama" | "OpenAiCompatible" | "OpenAi" | "Anthropic" (C# names) +// boundary Boundary "Local" | "Cloud" (C# names) +// classifications / baseline DataClassification "Public" | "Internal" | "Pii" | "Phi" (C# names) +// price input_per_1m / output_per_1m (explicit [JsonPropertyName] on PriceConfig) +// Always WRITTEN as those names. On READ a JSON number is accepted so that an out-of-range value (e.g. "mode": 999) +// reaches the validator and is reported as invalid_enum with its field path (200 valid=false / 422) instead of an +// opaque 400. Bodies are (de)serialized explicitly with ConfigJsonContext.Default.* — never the web defaults. /// active.json: which immutable version file is live, and its SHA-256 (crash recovery, ADR-0011). public sealed class ActivePointer @@ -202,11 +211,12 @@ public sealed class CatalogConnectionModel [JsonPropertyName("health")] public required HealthView Health { get; init; } } -/// JsonStringEnumConverter<T> with kebab-case-lower names and no integer values: the ADR vocabulary -/// ("local-only", "hybrid", "legacy-cloud", "fixed", "length-heuristic", "none|daily|monthly", "hard|warn-only"). +/// JsonStringEnumConverter<T> with kebab-case-lower names: the ADR vocabulary ("local-only", "hybrid", +/// "legacy-cloud", "fixed", "length-heuristic", "none|daily|monthly", "hard|warn-only"). Integers are accepted on +/// read only so the validator can report an undefined value with its path; defined values are always written as names. public sealed class KebabEnumConverter : JsonStringEnumConverter where TEnum : struct, Enum { - public KebabEnumConverter() : base(JsonNamingPolicy.KebabCaseLower, allowIntegerValues: false) { } + public KebabEnumConverter() : base(JsonNamingPolicy.KebabCaseLower, allowIntegerValues: true) { } } // Wire vocabulary: mode/strategy/period/enforcement in ADR kebab-case; provider kind, boundary and classification @@ -226,6 +236,7 @@ public KebabEnumConverter() : base(JsonNamingPolicy.KebabCaseLower, allowInteger ])] [JsonSerializable(typeof(CovenantConfig))] [JsonSerializable(typeof(ActivePointer))] +[JsonSerializable(typeof(ActivationRecord))] [JsonSerializable(typeof(ConfigGetResponse))] [JsonSerializable(typeof(ConfigValidateRequest))] [JsonSerializable(typeof(ConfigValidateResponse))] diff --git a/src/Covenant.Host/ConfigRepository.cs b/src/Covenant.Host/ConfigRepository.cs index baac12a..dce5e53 100644 --- a/src/Covenant.Host/ConfigRepository.cs +++ b/src/Covenant.Host/ConfigRepository.cs @@ -16,6 +16,8 @@ public interface IConfigFileSystem void WriteDurable(string path, byte[] content); /// Atomic rename. overwrite=false must fail when the destination exists. void Move(string source, string destination, bool overwrite); + /// Append (create if missing), then flush to disk (fsync). Used for the activation journal. + void AppendDurable(string path, byte[] content); void CreateDirectory(string path); IEnumerable EnumerateFiles(string directory, string pattern); } @@ -35,6 +37,14 @@ public void WriteDurable(string path, byte[] content) } public void Move(string source, string destination, bool overwrite) => File.Move(source, destination, overwrite); + + public void AppendDurable(string path, byte[] content) + { + using var fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read); + fs.Write(content); + fs.Flush(flushToDisk: true); + } + public void CreateDirectory(string path) => Directory.CreateDirectory(path); public IEnumerable EnumerateFiles(string directory, string pattern) @@ -59,31 +69,45 @@ public sealed class ApplyResult public CovenantConfig? Applied { get; init; } public required int ActiveVersion { get; init; } public ConfigValidationResult? Validation { get; init; } + /// Non-fatal repository notes (e.g. the journal append failed after the pointer rename; boot repairs it). + public IReadOnlyList Notes { get; init; } = []; } /// Single-appliance configuration repository (ADR-0011): immutable snapshots -/// versions/v000001.json … plus active.json = { version, sha256 }. Only non-secret configuration and -/// secret REFERENCES are persisted. -/// Write ordering (apply/rollback), all under one writer lock: check If-Match → stamp + validate → write -/// vM.json.tmp, flush, rename to vM.json (create-new; never overwrites) → write -/// active.json.tmp, flush, rename over active.json → activate (swap the in-memory snapshot, append the -/// config.activated audit event) → release. A crash before the pointer rename leaves a version file that is -/// reported as "written, never activated" and is never reused (M is always above every existing file). +/// versions/v000001.json …, active.json = { version, sha256 }, and activations.jsonl, the +/// append-only ACTIVATION JOURNAL (one line per activation). The journal — not the presence of a version file — +/// defines history: version files never activated (orphans of an interrupted apply) are excluded from history, +/// and rollback, and their numbers are never reused. Only non-secret configuration and secret +/// REFERENCES are persisted; change summaries are redacted and bounded (≤ 500 chars). +/// Write ordering (apply/rollback), all under one writer lock: check If-Match → stamp + validate → COMPILE (the +/// caller's prepare step, provider clients included; a failure writes nothing) → write vM.json.tmp, flush, +/// rename to vM.json (create-new) → write active.json.tmp, flush, rename over active.json → +/// append the journal line, flush → activate (swap the in-memory snapshot, enqueue the config.activated +/// audit event) → release. M = max(version files, journal) + 1. public sealed class ConfigRepository { public const string PointerFile = "active.json"; public const string VersionsDir = "versions"; + public const string JournalFile = "activations.jsonl"; + public const int MaxSummaryChars = 500; private readonly IConfigFileSystem _fs; private readonly TimeProvider _clock; + private readonly Func _redact; private readonly SemaphoreSlim _writer = new(1, 1); private volatile CovenantConfig? _active; + private readonly object _journalGate = new(); + private readonly List _journal = []; - public ConfigRepository(string directory, IConfigFileSystem? fileSystem = null, TimeProvider? clock = null) + /// Replaces secret values in free text (change summaries) — the Host passes one that knows + /// every configured secret value; default = identity (pattern-based redaction still applies). + public ConfigRepository(string directory, IConfigFileSystem? fileSystem = null, TimeProvider? clock = null, + Func? redact = null) { Directory = directory; _fs = fileSystem ?? PhysicalConfigFileSystem.Instance; _clock = clock ?? TimeProvider.System; + _redact = redact ?? (x => x); } public string Directory { get; } @@ -91,6 +115,7 @@ public ConfigRepository(string directory, IConfigFileSystem? fileSystem = null, private string VersionsPath => Path.Combine(Directory, VersionsDir); private string PointerPath => Path.Combine(Directory, PointerFile); + private string JournalPath => Path.Combine(Directory, JournalFile); public string VersionPath(int version) => Path.Combine(VersionsPath, $"v{version.ToString("D6", CultureInfo.InvariantCulture)}.json"); public static string ETag(int version) => $"\"v{version.ToString(CultureInfo.InvariantCulture)}\""; @@ -124,21 +149,26 @@ public List ExistingVersions() return list; } - /// Boot: read + verify the pointer. Missing pointer with no versions ⇒ empty (bootstrap). Missing - /// pointer with versions, unreadable pointer, missing/altered version file ⇒ errors (refuse to start). + /// Boot: read + verify the pointer and the activation journal. Missing pointer with no versions ⇒ empty + /// (bootstrap). Missing pointer with versions, unreadable pointer, missing/altered version file, corrupt journal + /// line (other than a torn last line) ⇒ errors (refuse to start). Version files not in the journal ⇒ orphan + /// warnings. Active version missing from the journal (crash between pointer rename and journal append) ⇒ a + /// recovered: true line is appended. public ConfigOpenResult Open() { var versions = ExistingVersions(); + var result = new ConfigOpenResult(); + var journal = ReadJournal(result); + if (result.Errors.Count > 0) return result; + if (!_fs.FileExists(PointerPath)) { - if (versions.Count == 0) return new ConfigOpenResult { IsEmpty = true }; - var r = new ConfigOpenResult(); - r.Errors.Add($"Config:Path {Directory} — {PointerFile} is missing but {versions.Count} version file(s) exist; " + - "refusing to guess the active version. Restore active.json (version + sha256) from backup."); - return r; + if (versions.Count == 0 && journal.Count == 0) return new ConfigOpenResult { IsEmpty = true }; + result.Errors.Add($"Config:Path {Directory} — {PointerFile} is missing but {versions.Count} version file(s) exist; " + + "refusing to guess the active version. Restore active.json (version + sha256) from backup."); + return result; } - var result = new ConfigOpenResult(); ActivePointer? pointer; try { @@ -182,25 +212,143 @@ public ConfigOpenResult Open() return result; } - foreach (var orphan in versions.Where(v => v > pointer.Version)) - result.Warnings.Add($"configuration v{orphan} was written but never activated (interrupted apply); it is ignored and never reused"); + if (!journal.Any(j => j.Version == config.Version)) + { + // Crash between the pointer rename and the journal append: the pointer is the activation point, so the + // active version WAS activated — record it, marked recovered, before serving. + var recovered = ActivationRecord.For(config, _clock.GetUtcNow(), recovered: true); + try + { + AppendJournal(recovered); + result.Warnings.Add($"configuration v{config.Version} was active but missing from {JournalFile}; recorded as recovered"); + } + catch (IOException ex) + { + result.Errors.Add($"Config:Path {Directory} — cannot append the recovered activation of v{config.Version} to {JournalFile} ({ex.Message})."); + return result; + } + journal.Add(recovered); + } + + var activated = journal.Select(j => j.Version).ToHashSet(); + foreach (var orphan in versions.Where(v => !activated.Contains(v))) + result.Warnings.Add($"configuration v{orphan} was written but never activated (interrupted apply); it is excluded from history and its number is never reused"); foreach (var tmp in _fs.EnumerateFiles(VersionsPath, "*.tmp").Concat(_fs.EnumerateFiles(Directory, "*.tmp"))) result.Warnings.Add($"leftover temporary file {Path.GetFileName(tmp)} from an interrupted write is ignored"); + lock (_journalGate) + { + _journal.Clear(); + _journal.AddRange(journal); + } _active = config; return new ConfigOpenResult { Active = config }.WithMessages(result); } - /// Bootstrap v1 into an EMPTY repository (legacy import or seed). Same durable write ordering. + /// Reads the journal. A TORN tail — the final line, with no terminating newline, that does not parse + /// (an interrupted append) — is quarantined to activations.jsonl.torn-<utc> and the journal is + /// rewritten atomically with only the complete lines, BEFORE anything else can append. Without that repair the + /// next append would be concatenated onto the torn bytes and corrupt history. Any other unparsable line (including + /// a complete, newline-terminated last line) is corruption ⇒ refuse to start (fail-closed). + private List ReadJournal(ConfigOpenResult result) + { + var list = new List(); + if (!_fs.FileExists(JournalPath)) return list; + var text = System.Text.Encoding.UTF8.GetString(_fs.ReadAllBytes(JournalPath)); + bool endsWithNewline = text.Length == 0 || text[^1] == '\n'; + var lines = text.Split('\n'); + int last = lines.Length - 1; + while (last >= 0 && lines[last].Trim().Length == 0) last--; + string? tornTail = null; + var goodLines = new System.Text.StringBuilder(); + for (int i = 0; i <= last; i++) + { + var raw = lines[i]; + var line = raw.Trim(); + if (line.Length == 0) continue; + ActivationRecord? rec = null; + try { rec = JsonSerializer.Deserialize(line, ConfigJsonContext.Default.ActivationRecord); } + catch (JsonException) { } + if (rec is { Version: > 0 }) { list.Add(rec); goodLines.Append(line).Append('\n'); continue; } + if (i == last && !endsWithNewline) + tornTail = raw; + else + { + result.Errors.Add($"Config:Path {Directory} — {JournalFile} line {i + 1} is corrupt; the activation history cannot be trusted. Restore it from backup."); + return list; + } + } + if (tornTail is null && !endsWithNewline && last >= 0) + { + // Last line parsed but its newline never landed: terminate it so the next append starts a new line. + tornTail = ""; + } + if (tornTail is not null) + { + try + { + if (tornTail.Length > 0) + { + var quarantine = $"{JournalPath}.torn-{DateTime.UtcNow:yyyyMMddTHHmmssfffZ}"; + _fs.WriteDurable(quarantine, System.Text.Encoding.UTF8.GetBytes(tornTail)); + result.Warnings.Add($"{JournalFile}: the last line was torn (interrupted append); preserved in {Path.GetFileName(quarantine)} and removed from the journal"); + } + var tmp = JournalPath + ".tmp"; + _fs.WriteDurable(tmp, System.Text.Encoding.UTF8.GetBytes(goodLines.ToString())); + _fs.Move(tmp, JournalPath, overwrite: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + result.Errors.Add($"Config:Path {Directory} — {JournalFile} has a torn tail that could not be repaired ({ex.Message}); refusing to start."); + } + } + return list; + } + + private void AppendJournal(ActivationRecord record) + { + // Defence in depth: never append onto an unterminated line (Open() repairs torn tails first). + if (_fs.FileExists(JournalPath) && _fs.ReadAllBytes(JournalPath) is { Length: > 0 } existing && existing[^1] != (byte)'\n') + throw new IOException($"{JournalFile} does not end with a newline; refusing to append (restart to repair the torn tail)"); + var line = JsonSerializer.SerializeToUtf8Bytes(record, ConfigJsonContext.Default.ActivationRecord); + var bytes = new byte[line.Length + 1]; + line.CopyTo(bytes, 0); + bytes[^1] = (byte)'\n'; + _fs.CreateDirectory(Directory); + _fs.AppendDurable(JournalPath, bytes); + } + + /// The activation journal, oldest first (copy). + public IReadOnlyList Journal() + { + lock (_journalGate) return _journal.ToArray(); + } + + /// True when version was activated (is in the journal). + public bool IsActivated(int version) + { + lock (_journalGate) return _journal.Any(j => j.Version == version); + } + + private int JournalMax() + { + lock (_journalGate) return _journal.Count == 0 ? 0 : _journal.Max(j => j.Version); + } + + /// Bootstrap v1 into an EMPTY repository (legacy import or seed). Same durable write ordering. The caller + /// compiles the snapshot from BEFORE calling this, so a compile failure writes nothing. public CovenantConfig Bootstrap(CovenantConfig v1) { _writer.Wait(); try { - if (_active is not null || _fs.FileExists(PointerPath) || ExistingVersions().Count > 0) + if (_active is not null || _fs.FileExists(PointerPath) || ExistingVersions().Count > 0 || JournalMax() > 0) throw new InvalidOperationException("configuration repository is not empty"); - var stamped = v1 with { Version = 1, BaseVersion = null }; + var stamped = StampV1(v1); Persist(stamped); + var record = ActivationRecord.For(stamped, _clock.GetUtcNow(), recovered: false); + AppendJournal(record); // a failure here propagates: boot refuses to start (and recovers next time) + lock (_journalGate) _journal.Add(record); _active = stamped; return stamped; } @@ -210,10 +358,15 @@ public CovenantConfig Bootstrap(CovenantConfig v1) } } + /// The exact v1 that will persist (version 1, no base, redacted bounded summary). + public CovenantConfig StampV1(CovenantConfig v1) + => v1 with { Version = 1, BaseVersion = null, ChangeSummary = Bound(v1.ChangeSummary) }; + /// Validate-and-activate a candidate as a NEW version (apply and rollback). - /// compiles the runtime snapshot BEFORE anything is persisted (a construction failure leaves the active - /// version untouched); swaps it in and appends the audit event after the pointer - /// rename. A stale ⇒ Stale; validation errors ⇒ Invalid (nothing written). + /// compiles the runtime snapshot BEFORE anything is persisted; a from it is a + /// validation failure (Invalid, nothing written). swaps it in and appends the audit + /// event after the pointer rename and the journal append. A stale ⇒ + /// Stale; validation errors ⇒ Invalid (nothing written). public async Task ApplyAsync( CovenantConfig candidate, int expectedActiveVersion, string origin, string? changeSummary, int? rolledBackFrom, Func validate, @@ -229,8 +382,9 @@ public async Task ApplyAsync( if (expectedActiveVersion != active.Version) return new ApplyResult { Status = ApplyStatus.Stale, ActiveVersion = active.Version }; + // Monotonic and never reusing an orphan's number: above every version file AND every journal entry. var existing = ExistingVersions(); - int next = Math.Max(active.Version, existing.Count > 0 ? existing[^1] : 0) + 1; + int next = Math.Max(Math.Max(active.Version, existing.Count > 0 ? existing[^1] : 0), JournalMax()) + 1; var stamped = candidate with { Version = next, @@ -245,7 +399,21 @@ public async Task ApplyAsync( if (!validation.IsValid) return new ApplyResult { Status = ApplyStatus.Invalid, ActiveVersion = active.Version, Validation = validation }; - var prepared = prepare(stamped); + T prepared; + try + { + prepared = prepare(stamped); // compile (provider clients included) — nothing durable written yet + } + catch (ConfigCompileException ex) + { + return new ApplyResult + { + Status = ApplyStatus.Invalid, + ActiveVersion = active.Version, + Validation = new ConfigValidationResult(ex.Issues, validation.Warnings), + }; + } + try { Persist(stamped); @@ -255,9 +423,23 @@ public async Task ApplyAsync( discard?.Invoke(prepared); throw; } + + var notes = new List(); + var record = ActivationRecord.For(stamped, _clock.GetUtcNow(), recovered: false); + try + { + AppendJournal(record); + } + catch (IOException ex) + { + // The pointer rename (the activation point) already happened: disk says vM is active, so the process + // honours it. The next boot finds vM missing from the journal and appends it as recovered. + notes.Add($"activation journal append failed ({ex.GetType().Name}); repaired at next boot"); + } + lock (_journalGate) _journal.Add(record); _active = stamped; activate(stamped, prepared); - return new ApplyResult { Status = ApplyStatus.Applied, Applied = stamped, ActiveVersion = stamped.Version, Validation = validation }; + return new ApplyResult { Status = ApplyStatus.Applied, Applied = stamped, ActiveVersion = stamped.Version, Validation = validation, Notes = notes }; } finally { @@ -281,7 +463,11 @@ private void Persist(CovenantConfig stamped) _fs.Move(pointerTmp, PointerPath, overwrite: true); // the activation point } + /// An ACTIVATED version (in the journal); null for unknown numbers and for orphans. public CovenantConfig? GetVersion(int version) + => version >= 1 && IsActivated(version) ? ReadVersionFile(version) : null; + + private CovenantConfig? ReadVersionFile(int version) { var path = VersionPath(version); if (version < 1 || !_fs.FileExists(path)) return null; @@ -295,27 +481,80 @@ private void Persist(CovenantConfig stamped) } } - /// Newest first, bounded. Versions written-but-never-activated (above the active one) are excluded. + /// Activation history, newest first, bounded: journal entries only (orphans never appear). public List ListVersions(int limit) { - var activeVersion = _active?.Version ?? 0; var list = new List(); - foreach (var v in ExistingVersions().Where(v => v <= activeVersion).OrderByDescending(v => v)) + var seen = new HashSet(); + foreach (var rec in Enumerable.Reverse(Journal())) { if (list.Count >= limit) break; - if (GetVersion(v) is { } c) list.Add(c); + if (!seen.Add(rec.Version)) continue; + if (ReadVersionFile(rec.Version) is { } c) list.Add(c); } return list; } - private static string? Bound(string? summary) + /// Redacted (secret values and secret-looking tokens replaced) and bounded (≤ 500 chars, no control chars). + public string? Bound(string? summary) => BoundSummary(summary is null ? null : _redact(summary)); + + public static string? BoundSummary(string? summary) { if (string.IsNullOrWhiteSpace(summary)) return null; - var clean = new string(summary.Where(c => !char.IsControl(c)).ToArray()).Trim(); - return clean.Length <= 500 ? clean : clean[..500] + "…"; + var clean = SecretRedaction.Patterns(new string(summary.Where(c => !char.IsControl(c)).ToArray())).Trim(); + return clean.Length <= MaxSummaryChars ? clean : clean[..(MaxSummaryChars - 1)] + "…"; } } +/// Free-text redaction for configuration-write history (ADR-0011: never secret values). Value-based: every +/// configured secret value the Host knows (secret refs, legacy provider keys, Auth:Keys values, Admin:Token) is +/// replaced; pattern-based: common credential shapes ("sk-…", "Bearer …", long hex/base64 runs) are replaced too. +public static partial class SecretRedaction +{ + public const string Marker = "[redacted]"; + + public static Func ForValues(IEnumerable secretValues) + { + var values = secretValues.Where(v => v is { Length: >= 6 }).Select(v => v!).Distinct(StringComparer.Ordinal) + .OrderByDescending(v => v.Length).ToArray(); + return text => + { + foreach (var v in values) text = text.Replace(v, Marker, StringComparison.Ordinal); + return text; + }; + } + + public static string Patterns(string text) => CredentialShape().Replace(text, Marker); + + [System.Text.RegularExpressions.GeneratedRegex( + @"(?i)\b(?:sk|pk|rk|ak)-[A-Za-z0-9_\-]{8,}|\bBearer\s+[A-Za-z0-9._~+/\-]{8,}=*|\b[A-Za-z0-9+/_\-]{40,}={0,2}")] + private static partial System.Text.RegularExpressions.Regex CredentialShape(); +} + +/// One line of activations.jsonl (ADR-0011): version, base, rolled-back-from, UTC time, bounded +/// redacted summary, and whether boot recovered it (crash between pointer rename and journal append). +public sealed class ActivationRecord +{ + public required int Version { get; init; } + public int? Base { get; init; } + public int? RolledBackFrom { get; init; } + public required DateTimeOffset Utc { get; init; } + public string? Origin { get; init; } + public string? Summary { get; init; } + public bool Recovered { get; init; } + + public static ActivationRecord For(CovenantConfig c, DateTimeOffset now, bool recovered) => new() + { + Version = c.Version, + Base = c.BaseVersion, + RolledBackFrom = c.RolledBackFrom, + Utc = now, + Origin = c.Origin, + Summary = ConfigRepository.BoundSummary(c.ChangeSummary), + Recovered = recovered, + }; +} + internal static class ConfigOpenResultExtensions { public static ConfigOpenResult WithMessages(this ConfigOpenResult target, ConfigOpenResult source) diff --git a/src/Covenant.Host/Program.cs b/src/Covenant.Host/Program.cs index ec3330d..069ca3b 100644 --- a/src/Covenant.Host/Program.cs +++ b/src/Covenant.Host/Program.cs @@ -68,13 +68,13 @@ void FailIfConfigErrors() // Default location: ".config/" — beside the audit log, and unique per audit log. --- string configDir = StartupValidation.Trimmed(builder.Configuration["Config:Path"]) is { Length: > 0 } cp ? cp : auditPath + ".config"; var egressAllowList = StartupEgress.BuildAllowList(builder.Configuration); +var localEndpoints = StartupEgress.LocalEndpoints(builder.Configuration); // ADR-0011 boundary binding (startup-only) var secretAvailable = StartupEgress.SecretAvailability(builder.Configuration); ConfigValidationResult ValidateConfig(CovenantConfig c) => ConfigValidator.Validate(c, new ValidationEnvironment { EgressAllowList = egressAllowList, SecretAvailable = secretAvailable, - // Imported legacy-cloud configurations keep the pre-v2 PII/PHI placeholder (refused at the provider stage). - LegacyCompat = c.Mode == ProviderMode.LegacyCloud, + LocalEndpoints = localEndpoints, }); void AddValidationErrors(CovenantConfig c, ConfigValidationResult v) { @@ -82,13 +82,44 @@ void AddValidationErrors(CovenantConfig c, ConfigValidationResult v) foreach (var w in v.Warnings) Console.Error.WriteLine($"covenant: config warning v{c.Version} {w.Path} — {w.Code}: {w.Message}"); } -var configRepo = new ConfigRepository(configDir); +// --- Provider layer (ADR-0001) + runtime snapshots (ADR-0011): each validated version compiles into an immutable +// RuntimeSnapshot owning its provider clients ("connectionId:modelId"); a request acquires one at entry. A client +// that cannot be built for an enabled, referenced connection makes the version INVALID (client_unbuildable) — +// compiled BEFORE anything durable is written, never silently skipped. --- +var clientFactory = new SdkProviderClientFactory(builder.Configuration, egressAllowList); +RuntimeSnapshot CompileSnapshot(CovenantConfig c) +{ + var clients = clientFactory.Build(c); + var unbuildable = ProviderClientSet.UnbuildableIssues(c, clients); + if (unbuildable.Count > 0) + { + clients.Dispose(); + throw new ConfigCompileException(unbuildable); + } + foreach (var skip in clients.Skipped) Console.Error.WriteLine($"covenant: config v{c.Version} — no provider client for {skip}"); + return new RuntimeSnapshot(c, clients); +} +RuntimeSnapshot? CompileAtBoot(CovenantConfig c) +{ + try + { + return CompileSnapshot(c); + } + catch (ConfigCompileException ex) + { + foreach (var e in ex.Issues) configErrors.Add($"Config v{c.Version} ({c.Origin}) {e.Path} — {e.Code}: {e.Message}"); + return null; + } +} + +var configRepo = new ConfigRepository(configDir, redact: StartupEgress.Redactor(builder.Configuration)); var opened = configRepo.Open(); configErrors.AddRange(opened.Errors); FailIfConfigErrors(); foreach (var w in opened.Warnings) Console.Error.WriteLine($"covenant: config warning — {w}"); CovenantConfig activeConfig; +RuntimeSnapshot? initialSnapshot; bool bootstrapped = false; if (opened.IsEmpty) { @@ -106,18 +137,23 @@ void AddValidationErrors(CovenantConfig c, ConfigValidationResult v) v1 = LegacyImport.Build(builder.Configuration, DateTimeOffset.UtcNow, configErrors); } FailIfConfigErrors(); - AddValidationErrors(v1!, ValidateConfig(v1!)); + var stampedV1 = configRepo.StampV1(v1!); + AddValidationErrors(stampedV1, ValidateConfig(stampedV1)); + FailIfConfigErrors(); + initialSnapshot = CompileAtBoot(stampedV1); // compile (clients included) BEFORE the first durable write FailIfConfigErrors(); - activeConfig = configRepo.Bootstrap(v1!); + activeConfig = configRepo.Bootstrap(stampedV1); bootstrapped = true; } else { activeConfig = opened.Active!; // Fail-closed: an active configuration that no longer validates (e.g. a referenced secret was removed from - // the environment) refuses to start rather than serving on half-valid rules. + // the environment) or no longer compiles refuses to start rather than serving on half-valid rules. AddValidationErrors(activeConfig, ValidateConfig(activeConfig)); FailIfConfigErrors(); + initialSnapshot = CompileAtBoot(activeConfig); + FailIfConfigErrors(); foreach (var legacyKey in new[] { "Providers:Mode", "OpenAI:ModelId", "OpenAI:StrongModelId", "Routing:ComplexityTokenThreshold", "Cache:TtlSeconds", "RateLimit:GlobalPerMinute", "RateLimit:PerTeamPerMinute", "Budget:GlobalCapUsd" }) if (!string.IsNullOrWhiteSpace(builder.Configuration[legacyKey])) Console.Error.WriteLine($"covenant: note — {legacyKey} is a legacy startup key; configuration v{activeConfig.Version} in {configDir} governs routing/budgets (key ignored)."); @@ -145,16 +181,7 @@ void AddValidationErrors(CovenantConfig c, ConfigValidationResult v) builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.TypeInfoResolverChain.Insert(0, CovenantJsonContext.Default)); -// --- Provider layer (ADR-0001) + runtime snapshots (ADR-0011): each validated version compiles into an immutable -// RuntimeSnapshot owning its provider clients ("connectionId:modelId"); a request acquires one at entry. --- -var clientFactory = new SdkProviderClientFactory(builder.Configuration, egressAllowList); -RuntimeSnapshot CompileSnapshot(CovenantConfig c) -{ - var clients = clientFactory.Build(c); - foreach (var skip in clients.Skipped) Console.Error.WriteLine($"covenant: config v{c.Version} — no provider client for {skip}"); - return new RuntimeSnapshot(c, clients); -} -var runtime = new SnapshotHolder(CompileSnapshot(activeConfig)); +var runtime = new SnapshotHolder(initialSnapshot!); // Chain-head anchoring (ADR-0007): both settings together or neither; the anchor path should live // on an independent storage domain — that placement is the entire security value. @@ -540,13 +567,22 @@ IResult Unauthorized() => Results.Json( // never a second source of truth. var startedUtc = DateTimeOffset.UtcNow; -// Model-id keyed price view (per 1K) of a configuration, for FinOps' pre-v2 savings math (first entry wins). +// Model-id keyed price view (per 1K) of a configuration, for FinOps' pre-v2 savings estimate, which only knows the +// served model id (audit records carry no connection id yet). A bare id priced on several connections is AMBIGUOUS: +// it never resolves "first wins" — it takes the HIGHEST configured price, so a routing/local saving is never +// overstated (the estimate stays conservative). Authoritative charges are always connection-scoped (ConfigPrices). static Dictionary PricesByModel(CovenantConfig c) { - var map = new Dictionary(StringComparer.Ordinal); + var map = new Dictionary(StringComparer.Ordinal); foreach (var conn in c.Connections) foreach (var m in conn.Models) - if (m.Price is { } p) map.TryAdd(m.ModelId, (p.InputPer1M / 1000m, p.OutputPer1M / 1000m)); + if (m.Price is { } p) + { + var price = (p.InputPer1M / 1000m, p.OutputPer1M / 1000m); + map[m.ModelId] = map.TryGetValue(m.ModelId, out var seen) + ? (Math.Max(seen.In, price.Item1), Math.Max(seen.Out, price.Item2)) + : price; + } return map; } diff --git a/src/Covenant.Host/ProviderClients.cs b/src/Covenant.Host/ProviderClients.cs index 24a54df..6d04966 100644 --- a/src/Covenant.Host/ProviderClients.cs +++ b/src/Covenant.Host/ProviderClients.cs @@ -1,4 +1,5 @@ using System.ClientModel; +using System.ClientModel.Primitives; using Anthropic; using Covenant.Adapters; using Covenant.Core; @@ -8,22 +9,32 @@ namespace Covenant.Host; +/// A connection for which NO client was built, and why (disabled, egress, secret, mode, construction). +public sealed record SkippedConnection(string ConnectionId, string Reason) +{ + public override string ToString() => $"{ConnectionId}: {Reason}"; +} + /// The provider clients compiled for ONE configuration version, keyed "connectionId:modelId" (the /// ChatClientRegistry key format — legacy-imported connections are named openai/anthropic/local, so pre-v2 keys -/// keep matching). Owned by the snapshot; disposed when the retired snapshot's last request releases it. +/// keep matching). Owned by the snapshot; disposed (clients AND their HttpClients) when the retired snapshot's last +/// request releases it. public sealed class ProviderClientSet : IChatClientRegistry, IDisposable { private readonly Dictionary _clients; + private readonly IReadOnlyList _owned; private int _disposed; - public ProviderClientSet(Dictionary clients, IReadOnlyList? skipped = null) + public ProviderClientSet(Dictionary clients, IReadOnlyList? skipped = null, + IReadOnlyList? owned = null) { _clients = clients; - Skipped = skipped ?? Array.Empty(); + Skipped = skipped ?? Array.Empty(); + _owned = owned ?? Array.Empty(); } - /// "connection: reason" for connections that were NOT built (disabled, secret missing, egress, mode). - public IReadOnlyList Skipped { get; } + /// Connections that were NOT built (disabled, secret missing, egress, mode, construction failure). + public IReadOnlyList Skipped { get; } public IReadOnlyCollection Keys => _clients.Keys; @@ -36,6 +47,30 @@ public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 1) return; foreach (var c in _clients.Values.Distinct()) c.Dispose(); + foreach (var o in _owned) o.Dispose(); + } + + /// ADR-0011: a target whose client cannot be built makes the candidate INVALID — never a silently skipped + /// target. Every enabled connection referenced by an enabled policy must have been built; otherwise one + /// client_unbuildable error per such connection (path = the connection). + public static List UnbuildableIssues(CovenantConfig config, ProviderClientSet clients) + { + var referenced = new HashSet(StringComparer.Ordinal); + foreach (var p in config.Policies) + if (p.Enabled) + foreach (var t in p.Targets) referenced.Add(t.ConnectionId); + var issues = new List(); + for (int i = 0; i < config.Connections.Count; i++) + { + var conn = config.Connections[i]; + if (!conn.Enabled || !referenced.Contains(conn.Id)) continue; + var skip = clients.Skipped.FirstOrDefault(x => x.ConnectionId == conn.Id); + bool missing = skip is not null || conn.Models.Any(m => !clients.TryResolve(conn.Id, m.ModelId, out _)); + if (missing) + issues.Add(new ConfigIssue($"connections[{i}]", "client_unbuildable", + $"no provider client could be built for enabled connection '{conn.Id}' ({skip?.Reason ?? "model client missing"}); it is referenced by an enabled policy")); + } + return issues; } } @@ -45,63 +80,114 @@ public interface IProviderClientFactory ProviderClientSet Build(CovenantConfig config); } -/// OpenAI SDK for OpenAi / OpenAiCompatible / Ollama (endpoint + secret), Anthropic SDK for Anthropic — -/// the same construction the pre-v2 Program.cs used. Execution-time revalidation (ADR-0011): a connection whose -/// endpoint is not on the startup egress allow-list, whose secret is missing, or which is cloud in local-only -/// mode gets NO client (the provider stage then refuses fail-closed). Secret values are read here and never -/// leave this method. +/// OpenAI SDK for OpenAi / OpenAiCompatible / Ollama (endpoint + secret), Anthropic SDK for Anthropic. +/// ADR-0011 transport rules, per connection: +/// +/// automatic redirects OFF — a 3xx can never move a request off the approved egress endpoint +/// ( = false on a handler owned by this connection); +/// SDK-internal retries OFF — attempts are Covenant's own, counted and accounted (ADR-0013/0014): OpenAI via +/// ClientPipelineOptions.RetryPolicy = new ClientRetryPolicy(0), Anthropic via MaxRetries = 0; +/// the connection's timeout_seconds is the effective network timeout: OpenAI +/// ClientPipelineOptions.NetworkTimeout, Anthropic Timeout (the HttpClient's own timeout is infinite +/// so it never pre-empts the configured one). +/// +/// API names verified against the referenced assemblies' metadata (OpenAI 2.12.0 / System.ClientModel 1.14.0: +/// OpenAIClientOptions : ClientPipelineOptions { Transport, RetryPolicy, NetworkTimeout }; +/// HttpClientPipelineTransport(HttpClient); ClientRetryPolicy(int maxRetries). Anthropic 12.8.0: +/// AnthropicClient init properties { ApiKey, BaseUrl, HttpClient, MaxRetries (int?), Timeout (TimeSpan?) }). +/// Execution-time revalidation: a connection whose endpoint is not on the startup egress allow-list, whose secret +/// is missing, or which is cloud in local-only mode gets NO client and is reported in . +/// Secret values are read here and never leave this method. public sealed class SdkProviderClientFactory(IConfiguration configuration, IReadOnlySet egressAllowList) : IProviderClientFactory { + /// The per-connection handler: no redirects, bounded connect time. Public for regression tests. + public static SocketsHttpHandler CreateHandler(ConnectionConfig connection) => new() + { + AllowAutoRedirect = false, + ConnectTimeout = TimeSpan.FromSeconds(Math.Clamp(connection.TimeoutSeconds, 1, 30)), + PooledConnectionLifetime = TimeSpan.FromMinutes(5), + UseCookies = false, + }; + + /// HttpClient over ; its own Timeout is infinite — the SDK option enforces + /// the connection's timeout_seconds. + public static HttpClient CreateHttpClient(ConnectionConfig connection) + => new(CreateHandler(connection), disposeHandler: true) { Timeout = Timeout.InfiniteTimeSpan }; + + public static OpenAIClientOptions OpenAiOptions(ConnectionConfig connection, HttpClient http) + { + var options = new OpenAIClientOptions + { + Transport = new HttpClientPipelineTransport(http), + RetryPolicy = new ClientRetryPolicy(0), + NetworkTimeout = TimeSpan.FromSeconds(connection.TimeoutSeconds), + }; + if (connection.Endpoint is { Length: > 0 } endpoint) options.Endpoint = new Uri(endpoint); + return options; + } + public ProviderClientSet Build(CovenantConfig config) { var clients = new Dictionary(StringComparer.Ordinal); - var skipped = new List(); + var skipped = new List(); + var owned = new List(); foreach (var conn in config.Connections) { - if (!conn.Enabled) { skipped.Add($"{conn.Id}: disabled"); continue; } - if (conn.Boundary == Boundary.Cloud && config.Mode == ProviderMode.LocalOnly) { skipped.Add($"{conn.Id}: cloud in local-only mode"); continue; } + if (!conn.Enabled) { skipped.Add(new(conn.Id, "disabled")); continue; } + if (conn.Boundary == Boundary.Cloud && config.Mode == ProviderMode.LocalOnly) { skipped.Add(new(conn.Id, "cloud in local-only mode")); continue; } - var authority = conn.Endpoint is null ? ConfigValidator.DefaultAuthority(conn.Kind) : ConfigValidator.EndpointAuthority(conn.Endpoint); - if (authority is null || !egressAllowList.Contains(authority)) { skipped.Add($"{conn.Id}: endpoint not on the egress allow-list"); continue; } + var authority = ConfigValidator.AuthorityOf(conn); + if (authority is null || !egressAllowList.Contains(authority)) { skipped.Add(new(conn.Id, "endpoint not on the egress allow-list")); continue; } string? secret = conn.SecretRef is { } sr && ConfigValidator.IsAllowedSecretRef(sr) ? configuration[sr] : null; if (string.IsNullOrWhiteSpace(secret)) { if (conn.Kind is ProviderKind.OpenAi or ProviderKind.Anthropic || conn.SecretRef is not null) { - skipped.Add($"{conn.Id}: secret unavailable"); + skipped.Add(new(conn.Id, "secret unavailable")); continue; } secret = "not-needed"; // keyless in-perimeter servers (Ollama/vLLM) — never a Covenant credential } + HttpClient? http = null; try { + http = CreateHttpClient(conn); if (conn.Kind == ProviderKind.Anthropic) { foreach (var m in conn.Models) { var anthropic = conn.Endpoint is { Length: > 0 } baseUrl - ? new AnthropicClient { ApiKey = secret, BaseUrl = baseUrl } - : new AnthropicClient { ApiKey = secret }; + ? new AnthropicClient + { + ApiKey = secret, BaseUrl = baseUrl, HttpClient = http, MaxRetries = 0, + Timeout = TimeSpan.FromSeconds(conn.TimeoutSeconds), + } + : new AnthropicClient + { + ApiKey = secret, HttpClient = http, MaxRetries = 0, + Timeout = TimeSpan.FromSeconds(conn.TimeoutSeconds), + }; clients[$"{conn.Id}:{m.ModelId}"] = anthropic.AsIChatClient(m.ModelId); } } else { - var root = conn.Endpoint is { Length: > 0 } endpoint - ? new OpenAIClient(new ApiKeyCredential(secret), new OpenAIClientOptions { Endpoint = new Uri(endpoint) }) - : new OpenAIClient(secret); + var root = new OpenAIClient(new ApiKeyCredential(secret), OpenAiOptions(conn, http)); foreach (var m in conn.Models) clients[$"{conn.Id}:{m.ModelId}"] = root.GetChatClient(m.ModelId).AsIChatClient(); } + owned.Add(http); } catch (Exception ex) when (ex is ArgumentException or UriFormatException or InvalidOperationException) { - skipped.Add($"{conn.Id}: client construction failed ({ex.GetType().Name})"); + http?.Dispose(); + foreach (var m in conn.Models) clients.Remove($"{conn.Id}:{m.ModelId}"); + skipped.Add(new(conn.Id, $"client construction failed ({ex.GetType().Name})")); } } - return new ProviderClientSet(clients, skipped); + return new ProviderClientSet(clients, skipped, owned); } } diff --git a/src/Covenant.Ui/Logic/ShellStatus.cs b/src/Covenant.Ui/Logic/ShellStatus.cs index eb9f90e..5815ab1 100644 --- a/src/Covenant.Ui/Logic/ShellStatus.cs +++ b/src/Covenant.Ui/Logic/ShellStatus.cs @@ -25,7 +25,7 @@ public static ModeBadge Mode(string? mode) "localonly" or "local" => new("Local-only", "local", "Only in-perimeter (local) connections can execute; cloud configuration cannot run."), "hybrid" => new("Hybrid", "hybrid", - "Local and approved cloud routes; sensitive classifications stay local unless a policy explicitly allows otherwise."), + "Local and approved cloud routes; PII/PHI never route to cloud destinations."), "legacycloud" or "cloud" => new("Legacy cloud", "legacy", "Imported pre-v2 routing (cloud default). Review the effective rules before relying on it."), _ => new(ModeNotReported, "unknown", "The Host did not report a provider mode."), diff --git a/src/Covenant.Ui/Models/ConfigContracts.cs b/src/Covenant.Ui/Models/ConfigContracts.cs index 7ece79c..5f10c39 100644 --- a/src/Covenant.Ui/Models/ConfigContracts.cs +++ b/src/Covenant.Ui/Models/ConfigContracts.cs @@ -118,7 +118,7 @@ public sealed class PolicyDto [JsonPropertyName("strategy")] public string? Strategy { get; set; } [JsonPropertyName("threshold_tokens")] public int? ThresholdTokens { get; set; } [JsonPropertyName("retry")] public RetrySettingsDto? Retry { get; set; } - [JsonPropertyName("allow_sensitive_cloud")] public bool AllowSensitiveCloud { get; set; } + // No "allow sensitive cloud" switch: PII/PHI never route to cloud destinations (the Host enforces it). [JsonPropertyName("explanation")] public string? Explanation { get; set; } } diff --git a/src/Covenant.Ui/Pages/Policies.razor b/src/Covenant.Ui/Pages/Policies.razor index 3ce4384..6dc1ea5 100644 --- a/src/Covenant.Ui/Pages/Policies.razor +++ b/src/Covenant.Ui/Pages/Policies.razor @@ -46,6 +46,7 @@ } } +
  • PII/PHI never route to cloud destinations.
  • 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) diff --git a/tests/Covenant.Tests/AnthropicIngressTests.cs b/tests/Covenant.Tests/AnthropicIngressTests.cs index dd60dc1..d0d3748 100644 --- a/tests/Covenant.Tests/AnthropicIngressTests.cs +++ b/tests/Covenant.Tests/AnthropicIngressTests.cs @@ -26,7 +26,7 @@ public AnthropicIngressTests(WebApplicationFactory factory) b.UseSetting("Auth:Keys:0:Key", "test-api-key"); b.UseSetting("Auth:Keys:0:Principal", "itest"); b.UseSetting("Auth:Keys:0:Team", "itest-team"); - b.UseSetting("Audit:Path", _auditPath); + CorrelationTestKit.IsolatePaths(b, _auditPath); }); _client = _factory.CreateClient(); _client.DefaultRequestHeaders.Add("x-api-key", "test-api-key"); // Anthropic-style auth header @@ -35,7 +35,7 @@ public AnthropicIngressTests(WebApplicationFactory factory) public void Dispose() { _factory.Dispose(); - if (File.Exists(_auditPath)) File.Delete(_auditPath); + CorrelationTestKit.DeleteWithSiblings(_auditPath); } private static StringContent Messages(string content, string? model = null, bool stream = false) => diff --git a/tests/Covenant.Tests/ClassificationProfileTests.cs b/tests/Covenant.Tests/ClassificationProfileTests.cs index 8ed1a0e..3ff8170 100644 --- a/tests/Covenant.Tests/ClassificationProfileTests.cs +++ b/tests/Covenant.Tests/ClassificationProfileTests.cs @@ -47,7 +47,7 @@ public ClassificationProfileTests() new ApiKeyRecord("demo-key", "demo-service", "platform", "demo-app"), new ApiKeyRecord("batch-key", "batch-app", "data"), // Application defaults to Principal new ApiKeyRecord("off-key", "off-service", "data", "off-app"), - new ApiKeyRecord("unbound-key", "nobody", "misc"), // no such application ⇒ legacy behaviour + new ApiKeyRecord("unbound-key", "nobody", "misc"), // no such application ⇒ refused (fail-closed) ], }), new ShapeStage(), @@ -174,15 +174,20 @@ public async Task Disabled_application_is_a_governed_refusal() Assert.Equal("off-app", _sink.Entries.Single().ApplicationId); } + /// Review fix 7 (ADR-0012): once a configuration governs, a key whose application is not in it is + /// refused at auth — no implicit legacy fallback. (Was: "keeps legacy behaviour".) [Fact] - public async Task Key_without_a_configured_application_keeps_legacy_behaviour() + public async Task Key_without_a_configured_application_is_refused_at_auth() { var ctx = await Run(PublicText, key: "unbound-key"); - Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.True(ctx.IsDenied); + Assert.Equal(DenialKind.Governance, ctx.DenialKind); + Assert.Equal("auth", ctx.StoppedAtStage); + Assert.Contains("application not configured", ctx.DenialReason, StringComparison.Ordinal); Assert.Null(ctx.ApplicationId); - Assert.Equal(PolicyEngineV2.LegacyInternalProfile, ctx.ProfileId); - Assert.Equal(DataClassification.Internal, ctx.Classification); - Assert.Equal("misc", ctx.Identity.Tags.Team); + Assert.False(ctx.ClassificationEvaluated); + Assert.Equal(0, _local.Calls + _cloud.Calls); + Assert.Single(_sink.Entries); // audited } [Fact] diff --git a/tests/Covenant.Tests/ConfigApiTests.cs b/tests/Covenant.Tests/ConfigApiTests.cs index 68e0cb3..3bfb9f5 100644 --- a/tests/Covenant.Tests/ConfigApiTests.cs +++ b/tests/Covenant.Tests/ConfigApiTests.cs @@ -1,5 +1,8 @@ using System.Net; +using System.Net.Http.Headers; +using System.Text; using System.Text.Json; +using System.Text.Json.Nodes; using Covenant.Core; using Covenant.Host; using Xunit; @@ -243,4 +246,173 @@ public async Task Status_and_catalog_report_mode_version_and_connections() Assert.True(ollama.GetProperty("models")[0].GetProperty("registered").GetBoolean()); Assert.Equal($"ollama:{V2.LocalTag}", ollama.GetProperty("models")[0].GetProperty("key").GetString()); } + + // ---------------- Review fixes round 1 ---------------- + + private static string WithConfigEdit(string rawGetResponse, Action edit, bool put = false) + { + var config = JsonNode.Parse(rawGetResponse)!["config"]!.AsObject(); + edit(config); + var body = new JsonObject { ["config"] = config.DeepClone() }; + if (put) body["change_summary"] = "malformed candidate"; + else body["base_version"] = 1; + return body.ToJsonString(); + } + + /// Review fix 1: settings=null and mode=999 are reported as validation errors with field paths — + /// 200 {valid:false} from validate, 422 from PUT — never a 500/NullReferenceException. + [Fact] + public async Task Structurally_broken_candidates_are_200_valid_false_on_validate_and_422_on_put() + { + var (_, _, raw) = await V2Admin.GetConfigAsync(_client); + var cases = new (Action Edit, string Path, string Code)[] + { + (c => c["settings"] = null, "settings", "required"), + (c => c["mode"] = 999, "mode", "invalid_enum"), + (c => c["connections"]![0]!["kind"] = 999, "connections[0].kind", "invalid_enum"), + (c => c["connections"] = null, "connections", "required"), + (c => c["policies"]![0]!["targets"]!.AsArray().Add(null), "policies[0].targets[2]", "required"), + (c => c["policies"]![0]!["retry"] = null, "policies[0].retry", "required"), + (c => c["budgets"]![0]!["warn_at"] = null, "budgets[0].warn_at", "required"), + (c => c["applications"]![0]!["granted_profiles"] = null, "applications[0].granted_profiles", "required"), + (c => c["profiles"]![0]!["baseline"] = 77, "profiles[0].baseline", "invalid_enum"), + }; + foreach (var (edit, path, code) in cases) + { + var (status, body, _) = await V2Admin.SendAsync(_client, HttpMethod.Post, "/admin/config/validate", WithConfigEdit(raw, edit)); + Assert.Equal(HttpStatusCode.OK, status); + Assert.False(body.GetProperty("valid").GetBoolean(), path); + Assert.Contains(body.GetProperty("errors").EnumerateArray(), + e => e.GetProperty("path").GetString() == path && e.GetProperty("code").GetString() == code); + Assert.True(!body.TryGetProperty("impact", out var impact) || impact.ValueKind == JsonValueKind.Null); // no preview of an uncompilable candidate + + var (putStatus, putBody, _) = await V2Admin.SendAsync(_client, HttpMethod.Put, "/admin/config", WithConfigEdit(raw, edit, put: true), "\"v1\""); + Assert.Equal((HttpStatusCode)422, putStatus); + Assert.Contains(putBody.GetProperty("errors").EnumerateArray(), e => e.GetProperty("path").GetString() == path); + } + Assert.Equal(1, (await V2Admin.GetConfigAsync(_client)).Version); // nothing activated + Assert.False(File.Exists(Path.Combine(_factory.ConfigDir, "versions", "v000002.json"))); + } + + /// Review fix 7: after the application is removed from the active configuration, its key is refused + /// at auth (403 Governance, "application not configured") — no implicit legacy fallback. + [Fact] + public async Task Key_whose_application_was_removed_is_403_at_auth() + { + using var app = _factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + Assert.Equal(HttpStatusCode.OK, (await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("internal question"))).StatusCode); + + var (_, cfg, _) = await V2Admin.GetConfigAsync(_client); + Assert.Equal(2, await V2Admin.ApplyAsync(_client, cfg with { Applications = cfg.Applications.Where(a => a.Id != "demo-app").ToList() }, 1, "remove demo-app")); + + int calls = _factory.Local.Calls + _factory.Cloud.Calls; + using var resp = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("internal question")); + Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); + var e = await CorrelationTestKit.LookupAsync(_client, CorrelationTestKit.HeaderId(resp)); + Assert.Equal("auth", e.StoppedAtStage); + Assert.Equal("Governance", e.DenialKind); + Assert.Contains("application not configured", e.Reason, StringComparison.Ordinal); + Assert.Equal(2, e.ConfigVersion); + Assert.Equal(calls, _factory.Local.Calls + _factory.Cloud.Calls); + } + + /// Review fix 10 through the API: a version file that was never activated (orphan of an interrupted + /// apply) is 404 for GET /versions/{n}, refused for rollback, absent from history, and its number is never reused. + [Fact] + public async Task Orphan_version_is_404_refused_for_rollback_absent_from_history_and_never_reused() + { + var versionsDir = Path.Combine(_factory.ConfigDir, "versions"); + var v1Json = await File.ReadAllTextAsync(Path.Combine(versionsDir, "v000001.json")); + await File.WriteAllTextAsync(Path.Combine(versionsDir, "v000002.json"), v1Json.Replace("\"version\":1", "\"version\":2", StringComparison.Ordinal)); + + var (getStatus, _, _) = await V2Admin.SendAsync(_client, HttpMethod.Get, "/admin/config/versions/2"); + Assert.Equal(HttpStatusCode.NotFound, getStatus); + var (rbStatus, _, _) = await V2Admin.SendAsync(_client, HttpMethod.Post, "/admin/config/rollback", + """{"target_version":2,"expected_active_version":1}"""); + Assert.Equal(HttpStatusCode.NotFound, rbStatus); + Assert.Equal(1, (await V2Admin.GetConfigAsync(_client)).Version); + + var (_, cfg, _) = await V2Admin.GetConfigAsync(_client); + Assert.Equal(3, await V2Admin.ApplyAsync(_client, WithCacheTtl(cfg, 15), 1)); // never reuses 2 + var (_, versions, _) = await V2Admin.SendAsync(_client, HttpMethod.Get, "/admin/config/versions"); + Assert.Equal(new[] { 3, 1 }, versions.EnumerateArray().Select(v => v.GetProperty("version").GetInt32()).ToArray()); + Assert.Equal(HttpStatusCode.NotFound, (await V2Admin.SendAsync(_client, HttpMethod.Get, "/admin/config/versions/2")).Status); + Assert.Equal(HttpStatusCode.OK, (await V2Admin.SendAsync(_client, HttpMethod.Get, "/admin/config/versions/1")).Status); + var journal = await File.ReadAllTextAsync(Path.Combine(_factory.ConfigDir, ConfigRepository.JournalFile)); + Assert.Equal(2, journal.Split('\n', StringSplitOptions.RemoveEmptyEntries).Length); // v1 + v3 activations + } + + /// Review fix 13 through the API: the change summary in history, journal and audit is bounded and + /// never carries a secret value (provider key, admin token). + [Fact] + public async Task Change_summary_is_redacted_and_bounded_everywhere_it_is_recorded() + { + var (_, cfg, _) = await V2Admin.GetConfigAsync(_client); + var summary = $"pasted {HybridSeedFactory.Secret} and {CorrelationTestKit.AdminToken} by mistake " + string.Join(" ", Enumerable.Repeat("note", 400)); + Assert.Equal(2, await V2Admin.ApplyAsync(_client, WithCacheTtl(cfg, 5), 1, summary)); + + var (_, versions, _) = await V2Admin.SendAsync(_client, HttpMethod.Get, "/admin/config/versions"); + var stored = versions[0].GetProperty("change_summary").GetString()!; + Assert.True(stored.Length <= 500, $"{stored.Length}"); + Assert.DoesNotContain(HybridSeedFactory.Secret, stored, StringComparison.Ordinal); + Assert.DoesNotContain(CorrelationTestKit.AdminToken, stored, StringComparison.Ordinal); + Assert.Contains("[redacted]", stored, StringComparison.Ordinal); + + var entries = await V2Admin.AuditAsync(_factory.AuditPath, l => l.Any(e => e.EventType == AuditEntryKinds.ConfigActivated && e.ConfigVersion == 2)); + var ev = entries.Single(e => e.EventType == AuditEntryKinds.ConfigActivated && e.ConfigVersion == 2); + Assert.DoesNotContain(HybridSeedFactory.Secret, ev.Reason, StringComparison.Ordinal); + Assert.True(ev.Reason.Length <= 700, $"{ev.Reason.Length}"); + foreach (var file in Directory.GetFiles(_factory.ConfigDir, "*", SearchOption.AllDirectories)) + Assert.DoesNotContain(HybridSeedFactory.Secret, await File.ReadAllTextAsync(file), StringComparison.Ordinal); + } +} + +/// Review fix 8: the console's pre-authenticated identity is server-only. Nothing a /v1 caller sends — +/// headers, body fields, even a valid admin token — can bind it; /v1 still requires an application key. +public sealed class PublicIngressIdentityTests : IDisposable +{ + private readonly HybridSeedFactory _factory = new(); + public void Dispose() => _factory.Dispose(); + + [Fact] + public void Pre_authenticated_identity_is_not_part_of_any_wire_derived_request_type() + { + foreach (var t in new[] { typeof(InferenceRequest), typeof(OpenAiChatRequest), typeof(AnthropicMessagesRequest) }) + Assert.DoesNotContain(t.GetProperties(), p => p.PropertyType == typeof(PreAuthenticatedIdentity)); + Assert.Null(typeof(InferenceContext).GetProperty(nameof(InferenceContext.PreAuthenticated))!.GetSetMethod()); // no public setter + } + + [Theory] + [InlineData("/v1/chat/completions")] + [InlineData("/v1/messages")] + public async Task V1_ignores_every_attempt_to_claim_a_console_identity_and_requires_a_key(string path) + { + using var client = _factory.CreateClient(); + using var req = new HttpRequestMessage(HttpMethod.Post, path); + foreach (var (h, v) in new[] + { + ("X-Covenant-Admin-Token", CorrelationTestKit.AdminToken), ("X-Covenant-Application", "demo-app"), + ("X-Covenant-Application-Id", "demo-app"), ("X-Covenant-PreAuthenticated", "demo-app"), + ("X-Covenant-Entry-Point", "console"), ("X-Covenant-Operator", "shared-admin-token"), + ("X-Covenant-Profile", "public-demo"), ("X-Covenant-Principal", "demo-service"), ("X-Covenant-Team", "platform"), + }) + req.Headers.TryAddWithoutValidation(h, v); + req.Content = new StringContent( + """{"model":"gpt-4o-mini","max_tokens":16,"messages":[{"role":"user","content":"hello"}],"pre_authenticated":{"application_id":"demo-app","team":"platform","principal":"op"},"PreAuthenticated":{"ApplicationId":"demo-app"},"application_id":"demo-app","entry_point":"console"}""", + Encoding.UTF8, "application/json"); + using var resp = await client.SendAsync(req); + Assert.Equal(HttpStatusCode.Unauthorized, resp.StatusCode); + Assert.Equal(0, _factory.Local.Calls + _factory.Cloud.Calls); + + if (path == "/v1/chat/completions") + { + var e = await CorrelationTestKit.LookupAsync(_factory.CreateClient(), CorrelationTestKit.HeaderId(resp)); + Assert.Equal("Unauthenticated", e.DenialKind); + Assert.Equal("auth", e.StoppedAtStage); + Assert.Equal("v1", e.EntryPoint); + Assert.Null(e.OperatorRef); + Assert.Null(e.ApplicationId); + } + } } diff --git a/tests/Covenant.Tests/ConfigRepositoryTests.cs b/tests/Covenant.Tests/ConfigRepositoryTests.cs index 673dfe4..987b87c 100644 --- a/tests/Covenant.Tests/ConfigRepositoryTests.cs +++ b/tests/Covenant.Tests/ConfigRepositoryTests.cs @@ -6,9 +6,10 @@ namespace Covenant.Tests; -/// ADR-0011 repository guarantees: monotonic versions, write ordering (version file before pointer), -/// crash recovery (orphan version ignored + reported; corrupt pointer / hash mismatch refuse to start), -/// rollback as a NEW version, and single-writer optimistic concurrency. +/// ADR-0011 repository guarantees: monotonic versions, write ordering (compile → version file → pointer → +/// activation journal), crash recovery (orphan version excluded from history + reported + never reused; journal +/// repaired when the pointer moved but the journal line is missing; corrupt pointer / hash mismatch / corrupt journal +/// refuse to start), rollback as a NEW version, redacted bounded summaries, single-writer optimistic concurrency. public sealed class ConfigRepositoryTests : IDisposable { private readonly string _dir = Path.Combine(Path.GetTempPath(), $"covenant-cfgrepo-{Guid.NewGuid():n}"); @@ -92,9 +93,117 @@ public async Task Crash_between_version_file_and_pointer_keeps_the_old_version_a Assert.Equal(1, open.Active!.Version); Assert.Contains(open.Warnings, w => w.Contains("v2 was written but never activated", StringComparison.Ordinal)); + Assert.Null(reopened.GetVersion(2)); // an orphan is not history: GET n / rollback see nothing + Assert.False(reopened.IsActivated(2)); + var next = await Apply(reopened, V2.Hybrid(), 1); Assert.Equal(3, next.Applied!.Version); // monotonic: v2 is never overwritten or reused - Assert.DoesNotContain(2, reopened.ListVersions(10).Select(c => c.Version)); + // Review fix 10: history comes from the activation journal only — the orphan never appears. + Assert.Equal(new[] { 3, 1 }, reopened.ListVersions(10).Select(c => c.Version).ToList()); + Assert.Equal(new[] { 1, 3 }, reopened.Journal().Select(j => j.Version).ToList()); + Assert.Null(reopened.GetVersion(2)); + + // Still true after another restart (journal is durable), and the next number stays above the orphan. + var again = new ConfigRepository(_dir); + var reopen2 = again.Open(); + Assert.Empty(reopen2.Errors); + Assert.Equal(3, reopen2.Active!.Version); + Assert.Equal(new[] { 3, 1 }, again.ListVersions(10).Select(c => c.Version).ToList()); + Assert.Contains(reopen2.Warnings, w => w.Contains("v2 was written but never activated", StringComparison.Ordinal)); + Assert.Equal(4, (await Apply(again, V2.Hybrid(), 3)).Applied!.Version); + } + + /// Review fix 10: crash AFTER the pointer rename but BEFORE the journal append. The pointer is the + /// activation point, so v2 is active; boot appends a recovered: true journal line and history shows v2. + [Fact] + public async Task Crash_between_pointer_and_journal_is_recovered_at_boot() + { + var faulty = new CrashingFileSystem { FailOnJournalAppend = true }; + var repo = Bootstrapped(faulty); + faulty.Armed = true; + var activated = new List(); + var r = await Apply(repo, V2.Hybrid(), 1, activated: activated); + Assert.Equal(ApplyStatus.Applied, r.Status); // disk says v2 is active: the process honours it + Assert.Equal(new[] { 2 }, activated); + Assert.Contains(r.Notes, n => n.Contains("journal", StringComparison.Ordinal)); + Assert.DoesNotContain("\"version\":2", File.ReadAllText(Path.Combine(_dir, ConfigRepository.JournalFile)), StringComparison.Ordinal); + + var reopened = new ConfigRepository(_dir); + var open = reopened.Open(); + Assert.Empty(open.Errors); + Assert.Equal(2, open.Active!.Version); + Assert.Contains(open.Warnings, w => w.Contains("recorded as recovered", StringComparison.Ordinal)); + var line = Assert.Single(reopened.Journal(), j => j.Version == 2); + Assert.True(line.Recovered); + Assert.Equal(new[] { 2, 1 }, reopened.ListVersions(10).Select(c => c.Version).ToList()); + Assert.NotNull(reopened.GetVersion(2)); + // Durable: a third boot does not append a second recovered line. + var third = new ConfigRepository(_dir); + third.Open(); + Assert.Single(third.Journal(), j => j.Version == 2); + } + + /// Review fix 10: the snapshot (provider clients included) is compiled BEFORE any durable write — a + /// compile failure (client_unbuildable) is Invalid and writes nothing: no version file, no pointer, no journal line. + [Fact] + public async Task Compile_failure_writes_nothing_durable() + { + var repo = Bootstrapped(); + var pointerBefore = File.ReadAllBytes(Path.Combine(_dir, ConfigRepository.PointerFile)); + var journalBefore = File.ReadAllBytes(Path.Combine(_dir, ConfigRepository.JournalFile)); + var activated = new List(); + var result = await repo.ApplyAsync(V2.Hybrid(), 1, "console", "edit", null, Ok, + new Func(_ => throw new ConfigCompileException([new ConfigIssue("connections[0]", "client_unbuildable", "boom")])), + (c, v) => activated.Add(v)); + Assert.Equal(ApplyStatus.Invalid, result.Status); + Assert.Contains(result.Validation!.Errors, e => e.Code == "client_unbuildable"); + Assert.Empty(activated); + Assert.Equal(new[] { 1 }, repo.ExistingVersions()); + Assert.False(File.Exists(repo.VersionPath(2) + ".tmp")); + Assert.Equal(pointerBefore, File.ReadAllBytes(Path.Combine(_dir, ConfigRepository.PointerFile))); + Assert.Equal(journalBefore, File.ReadAllBytes(Path.Combine(_dir, ConfigRepository.JournalFile))); + Assert.Equal(1, repo.Active!.Version); + } + + [Fact] + public void Journal_corruption_before_the_last_line_refuses_to_start_but_a_torn_last_line_is_tolerated() + { + Bootstrapped(); + var journal = Path.Combine(_dir, ConfigRepository.JournalFile); + File.AppendAllText(journal, "{\"version\":7,\"ut"); // torn append (crash mid-line) + var torn = new ConfigRepository(_dir).Open(); + Assert.Empty(torn.Errors); + Assert.Contains(torn.Warnings, w => w.Contains("torn", StringComparison.Ordinal)); + + File.WriteAllText(journal, "garbage\n" + File.ReadAllText(journal)); + var corrupt = new ConfigRepository(_dir).Open(); + Assert.Null(corrupt.Active); + Assert.Contains(corrupt.Errors, e => e.Contains("corrupt", StringComparison.Ordinal)); + } + + /// Review fix 13: config-write history is bounded (≤ 500 chars) and redacted (never a secret value). + [Fact] + public async Task Change_summaries_are_redacted_and_bounded() + { + const string secret = "sk-live-THIS-IS-A-SECRET-0123456789"; + var repo = new ConfigRepository(_dir, redact: SecretRedaction.ForValues([secret, "vault-value-42"])); + Assert.True(repo.Open().IsEmpty); + repo.Bootstrap(V2.Hybrid()); + var summary = $"rotated key {secret} and vault-value-42 and Bearer abcdefghijklmnopqrstuvwx " + string.Join(" ", Enumerable.Repeat("word", 500)); + var r = await repo.ApplyAsync(V2.Hybrid(), 1, "console", summary, null, Ok, c => c.Version, (_, _) => { }); + var stored = r.Applied!.ChangeSummary!; + Assert.True(stored.Length <= ConfigRepository.MaxSummaryChars, $"{stored.Length} chars"); + Assert.DoesNotContain(secret, stored, StringComparison.Ordinal); + Assert.DoesNotContain("vault-value-42", stored, StringComparison.Ordinal); + Assert.DoesNotContain("abcdefghijklmnopqrstuvwx", stored, StringComparison.Ordinal); + Assert.Contains(SecretRedaction.Marker, stored, StringComparison.Ordinal); + foreach (var file in Directory.GetFiles(_dir, "*", SearchOption.AllDirectories)) + Assert.DoesNotContain(secret, File.ReadAllText(file), StringComparison.Ordinal); + Assert.True(stored.Length == ConfigRepository.MaxSummaryChars && stored.EndsWith('…')); // truncated, marked + Assert.True(repo.Journal().Last().Summary!.Length <= ConfigRepository.MaxSummaryChars); + var words = string.Join(" ", Enumerable.Repeat("word", 300)); // 1 499 chars + Assert.Equal(500, ConfigRepository.BoundSummary(words)!.Length); + Assert.Equal(words[..499], ConfigRepository.BoundSummary(words[..499])); // ≤ 500: unchanged } [Fact] @@ -108,6 +217,7 @@ public async Task Activation_happens_only_after_both_files_are_durable() Assert.Empty(activated); // no in-memory swap / audit event for an unpersisted version Assert.Equal(1, repo.Active!.Version); Assert.Equal(new[] { "v000002.json.tmp→v000002.json", "active.json.tmp→active.json" }, faulty.Moves.TakeLast(2).ToList()); + Assert.DoesNotContain(faulty.Appends, a => a.Contains("\"version\":2", StringComparison.Ordinal)); // no journal line either } [Fact] @@ -195,7 +305,9 @@ private sealed class CrashingFileSystem : IConfigFileSystem { public bool Armed { get; set; } public bool FailOnPointerRename { get; init; } + public bool FailOnJournalAppend { get; init; } public List Moves { get; } = []; + public List Appends { get; } = []; private readonly PhysicalConfigFileSystem _inner = PhysicalConfigFileSystem.Instance; public bool FileExists(string path) => _inner.FileExists(path); @@ -204,6 +316,13 @@ private sealed class CrashingFileSystem : IConfigFileSystem public void CreateDirectory(string path) => _inner.CreateDirectory(path); public IEnumerable EnumerateFiles(string directory, string pattern) => _inner.EnumerateFiles(directory, pattern); + public void AppendDurable(string path, byte[] content) + { + if (Armed && FailOnJournalAppend) throw new IOException("simulated crash before the journal append"); + Appends.Add(Encoding.UTF8.GetString(content)); + _inner.AppendDurable(path, content); + } + public void Move(string source, string destination, bool overwrite) { Moves.Add($"{Path.GetFileName(source)}→{Path.GetFileName(destination)}"); @@ -212,4 +331,38 @@ public void Move(string source, string destination, bool overwrite) _inner.Move(source, destination, overwrite); } } + + // Reviewer reproducer (docs/verification-2026-10-16/v2/torn-tail-regression.cs.txt): before the fix, the torn + // tail was ignored on read but the next append was concatenated onto it, corrupting history at the 2nd restart. + [Fact] + public async Task Torn_journal_tail_is_quarantined_and_repaired_so_later_activations_and_restarts_stay_clean() + { + _ = Bootstrapped(); + var journalPath = Path.Combine(_dir, ConfigRepository.JournalFile); + File.AppendAllText(journalPath, "{\"version\":7"); // interrupted append, no newline + + var reopened = new ConfigRepository(_dir); + Assert.Empty(reopened.Open().Errors); + Assert.Single(Directory.GetFiles(_dir, ConfigRepository.JournalFile + ".torn-*")); // evidence preserved + Assert.EndsWith("\n", File.ReadAllText(journalPath)); // repaired before any append + await Apply(reopened, V2.Hybrid(), 1); + + var second = new ConfigRepository(_dir); + Assert.Empty(second.Open().Errors); + await Apply(second, V2.Hybrid(), 2); + + var third = new ConfigRepository(_dir); + Assert.Empty(third.Open().Errors); + Assert.Equal(new[] { 3, 2, 1 }, third.Journal().Select(j => j.Version).Reverse().ToArray()); + foreach (var line in File.ReadAllLines(journalPath).Where(l => l.Length > 0)) + Assert.StartsWith("{", line); // one JSON object per line, never concatenated + } + + [Fact] + public void Complete_but_corrupt_last_journal_line_is_not_treated_as_torn_and_refuses_to_start() + { + Bootstrapped(); + File.AppendAllText(Path.Combine(_dir, ConfigRepository.JournalFile), "not json\n"); // newline-terminated ⇒ corruption + Assert.NotEmpty(new ConfigRepository(_dir).Open().Errors); + } } diff --git a/tests/Covenant.Tests/ConfigV2TestKit.cs b/tests/Covenant.Tests/ConfigV2TestKit.cs index 79c32dc..f883d70 100644 --- a/tests/Covenant.Tests/ConfigV2TestKit.cs +++ b/tests/Covenant.Tests/ConfigV2TestKit.cs @@ -43,10 +43,10 @@ internal static class V2 public static PolicyConfigV2 Policy(string id, DataClassification[] classes, PolicyTarget[] targets, string[]? profiles = null, bool paused = false, bool enabled = true, RoutingStrategy strategy = RoutingStrategy.Fixed, - int threshold = 400, bool allowSensitiveCloud = false) => new() + int threshold = 400) => new() { Id = id, Name = id, Enabled = enabled, Paused = paused, Classifications = classes, Targets = targets, - Profiles = profiles ?? [], Strategy = strategy, ThresholdTokens = threshold, AllowSensitiveCloud = allowSensitiveCloud, + Profiles = profiles ?? [], Strategy = strategy, ThresholdTokens = threshold, }; /// Hybrid demo defaults (spec §3): Public → cloud with local fallback; Internal/PII/PHI → local. @@ -97,18 +97,29 @@ public static CovenantConfig Hybrid(int version = 1, Func new(c); - public static ValidationEnvironment Env(bool legacy = false, bool secrets = true) => new() + /// Startup environment of the tests: egress allows the local Ollama and OpenAI; only the Ollama + /// authority is a startup-approved LOCAL endpoint (boundary binding, ADR-0011). + public static ValidationEnvironment Env(bool secrets = true, params string[] extraEgress) { - EgressAllowList = new HashSet(StringComparer.OrdinalIgnoreCase) { "127.0.0.1:11434", "api.openai.com:443" }, - SecretAvailable = _ => secrets, - LegacyCompat = legacy, - }; + var egress = new HashSet(StringComparer.OrdinalIgnoreCase) { "127.0.0.1:11434", "api.openai.com:443" }; + foreach (var e in extraEgress) egress.Add(e); + return new() + { + EgressAllowList = egress, + SecretAvailable = _ => secrets, + LocalEndpoints = new HashSet(StringComparer.OrdinalIgnoreCase) { "127.0.0.1:11434" }, + }; + } public static InferenceContext Ctx(string prompt, string? model = null, string? profile = null, string? credential = null, PreAuthenticatedIdentity? pre = null) - => new(new InferenceRequest("caller", [new ChatMessage(ChatRole.User, prompt)], model, + { + var ctx = new InferenceContext(new InferenceRequest("caller", [new ChatMessage(ChatRole.User, prompt)], model, new AttributionTags("self-declared", "wf", "uc"), Credential: credential, RequestId: $"req_{Guid.NewGuid():n}", - RequestedProfile: profile, PreAuthenticated: pre)); + RequestedProfile: profile)); + if (pre is not null) ctx.BindConsoleIdentity(pre, "shared-admin-token"); // server-side only (ADR-0012) + return ctx; + } } /// Counts calls; optional gate blocks every call until released (snapshot isolation tests). @@ -149,7 +160,7 @@ public sealed class HybridSeedFactory : WebApplicationFactory internal readonly GatedChatClient Local = new("local reply"); internal readonly GatedChatClient Cloud = new("cloud reply"); - public string ConfigDir => AuditPath + ".config"; + public string ConfigDir => CorrelationTestKit.ConfigDirFor(AuditPath); protected override void ConfigureWebHost(IWebHostBuilder builder) { @@ -165,7 +176,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("Auth:Keys:0:Principal", "demo-service"); builder.UseSetting("Auth:Keys:0:Team", "platform"); builder.UseSetting("Auth:Keys:0:Application", "demo-app"); - builder.UseSetting("Audit:Path", AuditPath); + CorrelationTestKit.IsolatePaths(builder, AuditPath); builder.ConfigureTestServices(services => services.AddSingleton(new ChatClientRegistry(new Dictionary { @@ -177,8 +188,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) protected override void Dispose(bool disposing) { base.Dispose(disposing); - CorrelationTestKit.DeleteWithSiblings(AuditPath); - try { if (Directory.Exists(ConfigDir)) Directory.Delete(ConfigDir, recursive: true); } catch (IOException) { } + CorrelationTestKit.DeleteWithSiblings(AuditPath); // audit file, ledger and the configuration repository } } diff --git a/tests/Covenant.Tests/ConfigValidationTotalityTests.cs b/tests/Covenant.Tests/ConfigValidationTotalityTests.cs new file mode 100644 index 0000000..13ec607 --- /dev/null +++ b/tests/Covenant.Tests/ConfigValidationTotalityTests.cs @@ -0,0 +1,235 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; + +namespace Covenant.Tests; + +/// Review fixes 1, 3 and 12 (ADR-0011 "validation is total", snapshot deep copy, wire spellings). +/// Every malformed-but-deserializable candidate is a validation error with a field path — never an exception. +public sealed class ConfigValidationTotalityTests +{ + private static ConfigValidationResult Validate(CovenantConfig c) => ConfigValidator.Validate(c, V2.Env()); + + private static void AssertError(CovenantConfig c, string path, string code) + { + var result = Validate(c); // must not throw + Assert.False(result.IsValid); + Assert.False(result.StructurallySound); + Assert.Contains(result.Errors, e => e.Path == path && e.Code == code); + } + + public static TheoryData UndefinedEnums => new() + { + "mode", "kind", "boundary", "strategy", "period", "enforcement", "baseline", "classification", + }; + + [Theory] + [MemberData(nameof(UndefinedEnums))] + public void Every_out_of_range_enum_is_an_invalid_enum_error_with_its_path(string which) + { + var c = V2.Hybrid(); + var (bad, path) = which switch + { + "mode" => (c with { Mode = (ProviderMode)999 }, "mode"), + "kind" => (c with { Connections = [c.Connections[0] with { Kind = (ProviderKind)999 }, c.Connections[1]] }, "connections[0].kind"), + "boundary" => (c with { Connections = [c.Connections[0], c.Connections[1] with { Boundary = (Boundary)(-1) }] }, "connections[1].boundary"), + "strategy" => (c with { Policies = [c.Policies[0] with { Strategy = (RoutingStrategy)7 }, c.Policies[1], c.Policies[2]] }, "policies[0].strategy"), + "period" => (c with { Budgets = [c.Budgets[0] with { Period = (BudgetPeriod)42 }] }, "budgets[0].period"), + "enforcement" => (c with { Budgets = [c.Budgets[0] with { Enforcement = (BudgetEnforcement)42 }] }, "budgets[0].enforcement"), + "baseline" => (c with { Profiles = [c.Profiles[0] with { Baseline = (DataClassification)9 }, c.Profiles[1], c.Profiles[2]] }, "profiles[0].baseline"), + _ => (c with { Policies = [c.Policies[0], c.Policies[1] with { Classifications = [DataClassification.Internal, (DataClassification)4] }, c.Policies[2]] }, + "policies[1].classifications[1]"), + }; + AssertError(bad, path, "invalid_enum"); + } + + [Fact] + public void Null_required_objects_lists_and_elements_are_required_errors_never_exceptions() + { + var c = V2.Hybrid(); + var pol = c.Policies[0]; + var app = c.Applications[0]; + var conn = c.Connections[0]; + var cases = new (CovenantConfig Config, string Path)[] + { + (c with { Settings = null! }, "settings"), + (c with { Connections = null! }, "connections"), + (c with { Connections = [conn, null!] }, "connections[1]"), + (c with { Connections = [conn with { Models = null! }, c.Connections[1]] }, "connections[0].models"), + (c with { Connections = [conn with { Models = [null!] }, c.Connections[1]] }, "connections[0].models[0]"), + (c with { Applications = null! }, "applications"), + (c with { Applications = [null!] }, "applications[0]"), + (c with { Applications = [app with { GrantedProfiles = null! }] }, "applications[0].granted_profiles"), + (c with { Applications = [app with { GrantedProfiles = ["public-demo", null!] }] }, "applications[0].granted_profiles[1]"), + (c with { Profiles = null! }, "profiles"), + (c with { Profiles = [c.Profiles[0], null!] }, "profiles[1]"), + (c with { Policies = null! }, "policies"), + (c with { Policies = [pol, null!] }, "policies[1]"), + (c with { Policies = [pol with { Targets = null! }] }, "policies[0].targets"), + (c with { Policies = [pol with { Targets = [pol.Targets[0], null!] }] }, "policies[0].targets[1]"), + (c with { Policies = [pol with { Targets = [new PolicyTarget { ConnectionId = null!, ModelId = "m" }] }] }, "policies[0].targets[0].connection_id"), + (c with { Policies = [pol with { Classifications = null! }] }, "policies[0].classifications"), + (c with { Policies = [pol with { Profiles = null! }] }, "policies[0].profiles"), + (c with { Policies = [pol with { Retry = null! }] }, "policies[0].retry"), + (c with { Policies = [pol with { Retry = pol.Retry with { On = null! } }] }, "policies[0].retry.on"), + (c with { Budgets = null! }, "budgets"), + (c with { Budgets = [null!] }, "budgets[0]"), + (c with { Budgets = [c.Budgets[0] with { WarnAt = null! }] }, "budgets[0].warn_at"), + (c with { SavingsBaseline = new ModelRef(null!, "m") }, "savings_baseline.connection_id"), + }; + foreach (var (config, path) in cases) + { + var result = Validate(config); + Assert.False(result.IsValid, path); + Assert.False(result.StructurallySound, path); + Assert.Contains(result.Errors, e => e.Path == path && e.Code == "required"); + } + } + + [Fact] + public void Null_ids_and_required_strings_are_required_errors_and_never_reach_the_snapshot() + { + var c = V2.Hybrid(); + var weird = c with + { + Connections = [c.Connections[0] with { Id = null! }, c.Connections[1] with { Models = [c.Connections[1].Models[0] with { ModelId = null! }] }], + Applications = [c.Applications[0] with { Id = null!, Team = null! }], + Profiles = [c.Profiles[0] with { Id = null! }, c.Profiles[1], c.Profiles[2]], + Policies = [c.Policies[0] with { Id = null!, Name = null! }, c.Policies[1], c.Policies[2]], + Budgets = [c.Budgets[0] with { Scope = null!, Id = null! }], + }; + var result = Validate(weird); + Assert.False(result.StructurallySound); + foreach (var path in new[] { "connections[0].id", "connections[1].models[0].model_id", "applications[0].id", "applications[0].team", + "profiles[0].id", "policies[0].id", "policies[0].name", "budgets[0].scope", "budgets[0].id" }) + Assert.Contains(result.Errors, e => e.Path == path && e.Code == "required"); + + // Semantically invalid but structurally sound candidates still get an impact preview without throwing. + var dup = c with { Connections = [.. c.Connections, c.Connections[0]], Applications = [.. c.Applications, c.Applications[0]] }; + Assert.True(Validate(dup).StructurallySound); + Assert.False(Validate(dup).IsValid); + Assert.NotNull(ImpactAnalyzer.Analyze(new RuntimeSnapshot(c), new RuntimeSnapshot(dup), _ => true)); + } + + [Fact] + public void Undefined_numeric_enum_and_null_settings_deserialize_and_are_reported_not_thrown() + { + var json = JsonNode.Parse(System.Text.Encoding.UTF8.GetString(ConfigRepository.Serialize(V2.Hybrid())))!.AsObject(); + json["mode"] = 999; + json["settings"] = null; + var c = JsonSerializer.Deserialize(json.ToJsonString(), ConfigJsonContext.Default.CovenantConfig)!; + Assert.Equal((ProviderMode)999, c.Mode); + var result = Validate(c); + Assert.Contains(result.Errors, e => e.Path == "mode" && e.Code == "invalid_enum"); + Assert.Contains(result.Errors, e => e.Path == "settings" && e.Code == "required"); + } + + /// Review fix 3: the snapshot owns deep, read-only copies — mutating the caller's lists after compile + /// changes nothing, and the snapshot's lists cannot be cast back to a mutable type. + [Fact] + public void Snapshot_is_a_deep_copy_unaffected_by_later_mutation_of_the_callers_lists() + { + var targets = new List { V2.T("ollama", V2.LocalTag) }; + var classes = new List { DataClassification.Internal }; + var models = new List { V2.Ollama().Models[0] }; + var connections = new List { V2.Ollama() with { Models = models }, V2.OpenAi() }; + var granted = new List { "internal-default" }; + var baseCfg = V2.Hybrid(); + var cfg = baseCfg with + { + Connections = connections, + Applications = [baseCfg.Applications[0] with { GrantedProfiles = granted, DefaultProfile = "internal-default" }], + Policies = [baseCfg.Policies[0], new PolicyConfigV2 { Id = "internal", Name = "i", Enabled = true, Classifications = classes, Targets = targets }, baseCfg.Policies[2]], + }; + var snap = new RuntimeSnapshot(cfg); + var before = PolicyEngineV2.Summary(snap, DataClassification.Internal, null); + + // Caller mutates everything it still holds. + targets.Clear(); + targets.Add(V2.T("openai", V2.CloudModel)); + classes.Add(DataClassification.Public); + models.Clear(); + connections.RemoveAt(0); + granted.Add("public-demo"); + + Assert.Equal(before, PolicyEngineV2.Summary(snap, DataClassification.Internal, null)); + Assert.Equal($"ollama/{V2.LocalTag}", before); + var internalPolicy = snap.Config.Policies.Single(p => p.Id == "internal"); + Assert.Equal(new[] { V2.T("ollama", V2.LocalTag) }, internalPolicy.Targets); + Assert.Equal(new[] { DataClassification.Internal }, internalPolicy.Classifications); + Assert.NotNull(snap.FindConnection("ollama")); + Assert.NotNull(snap.FindModel("ollama", V2.LocalTag)); + Assert.Single(snap.Config.Connections.Single(x => x.Id == "ollama").Models); + Assert.Equal(new[] { "internal-default" }, snap.FindApplication("demo-app")!.GrantedProfiles); + + // Not aliased and not castable back to a mutable list. + Assert.NotSame(cfg.Policies, snap.Config.Policies); + Assert.IsNotType>(internalPolicy.Targets); + Assert.IsNotType(internalPolicy.Targets); + Assert.True(((ICollection)internalPolicy.Targets).IsReadOnly); + Assert.Throws(() => ((IList)internalPolicy.Targets).Add(V2.T("openai", V2.CloudModel))); + } + + [Fact] + public void Snapshot_refuses_a_structurally_unsound_configuration_instead_of_defaulting() + => Assert.Throws(() => new RuntimeSnapshot(V2.Hybrid() with { Settings = null! })); + + /// Review fix 12: the documented, stable wire spellings (docs/ui-api-contract.md v2 "Wire spellings"). + [Fact] + public void Wire_spellings_are_the_documented_contract() + { + var all = V2.Hybrid() with + { + Connections = + [ + V2.Ollama(), + V2.OpenAi(), + new ConnectionConfig + { + Id = "compat", DisplayName = "c", Kind = ProviderKind.OpenAiCompatible, Boundary = Boundary.Local, Endpoint = "http://127.0.0.1:11434/v1", + Enabled = false, Models = [], + }, + new ConnectionConfig { Id = "claude", DisplayName = "a", Kind = ProviderKind.Anthropic, Boundary = Boundary.Cloud, Enabled = false, Models = [] }, + ], + Policies = + [ + .. V2.Hybrid().Policies, + V2.Policy("lh", [DataClassification.Public], [V2.T("ollama", V2.LocalTag)], profiles: ["phi-workload"], strategy: RoutingStrategy.LengthHeuristic), + ], + Budgets = + [ + new BudgetConfigV2 { Id = "g", Scope = "global", CapUsd = 1, Period = BudgetPeriod.None, Enforcement = BudgetEnforcement.Hard }, + new BudgetConfigV2 { Id = "d", Scope = "team:a", CapUsd = 1, Period = BudgetPeriod.Daily, Enforcement = BudgetEnforcement.WarnOnly }, + new BudgetConfigV2 { Id = "m", Scope = "team:b", CapUsd = 1, Period = BudgetPeriod.Monthly }, + ], + }; + var json = System.Text.Encoding.UTF8.GetString(ConfigRepository.Serialize(all)); + foreach (var expected in new[] + { + "\"mode\":\"hybrid\"", "\"strategy\":\"fixed\"", "\"strategy\":\"length-heuristic\"", + "\"period\":\"none\"", "\"period\":\"daily\"", "\"period\":\"monthly\"", + "\"enforcement\":\"hard\"", "\"enforcement\":\"warn-only\"", + "\"kind\":\"Ollama\"", "\"kind\":\"OpenAi\"", "\"kind\":\"OpenAiCompatible\"", "\"kind\":\"Anthropic\"", + "\"boundary\":\"Local\"", "\"boundary\":\"Cloud\"", + "\"baseline\":\"Public\"", "\"baseline\":\"Internal\"", "\"baseline\":\"Phi\"", + "\"classifications\":[\"Pii\",\"Phi\"]", + "\"input_per_1m\":0.15", "\"output_per_1m\":0.60", + }) + Assert.Contains(expected, json, StringComparison.Ordinal); + Assert.DoesNotContain("input_per1_m", json, StringComparison.Ordinal); + Assert.DoesNotContain("allow_sensitive_cloud", json, StringComparison.Ordinal); + + foreach (var (mode, value) in new[] { ("local-only", ProviderMode.LocalOnly), ("hybrid", ProviderMode.Hybrid), ("legacy-cloud", ProviderMode.LegacyCloud) }) + { + var node = JsonNode.Parse(json)!.AsObject(); + node["mode"] = mode; + Assert.Equal(value, JsonSerializer.Deserialize(node.ToJsonString(), ConfigJsonContext.Default.CovenantConfig)!.Mode); + } + // Round trip is lossless for every enum. + var back = JsonSerializer.Deserialize(json, ConfigJsonContext.Default.CovenantConfig)!; + Assert.Equal(json, System.Text.Encoding.UTF8.GetString(ConfigRepository.Serialize(back))); + } +} diff --git a/tests/Covenant.Tests/ConsoleAssetsTests.cs b/tests/Covenant.Tests/ConsoleAssetsTests.cs index 71ebd2d..990dcc6 100644 --- a/tests/Covenant.Tests/ConsoleAssetsTests.cs +++ b/tests/Covenant.Tests/ConsoleAssetsTests.cs @@ -91,14 +91,13 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("Auth:Keys:0:Key", "k"); builder.UseSetting("Auth:Keys:0:Principal", "p"); builder.UseSetting("Auth:Keys:0:Team", "t"); - builder.UseSetting("Audit:Path", AuditPath); + CorrelationTestKit.IsolatePaths(builder, AuditPath); } protected override void Dispose(bool disposing) { base.Dispose(disposing); - foreach (var f in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(AuditPath) + "*")) - File.Delete(f); + CorrelationTestKit.DeleteWithSiblings(AuditPath); } } diff --git a/tests/Covenant.Tests/ConsoleLogicTests.cs b/tests/Covenant.Tests/ConsoleLogicTests.cs index 98bb36d..73ebc92 100644 --- a/tests/Covenant.Tests/ConsoleLogicTests.cs +++ b/tests/Covenant.Tests/ConsoleLogicTests.cs @@ -589,8 +589,10 @@ public void Form_problems_block_run() } // 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; + private static ClassificationResult Detect(string text) => new RegexDataClassifier().Classify( + new InferenceRequest("tester", [new ChatMessage(ChatRole.User, text)], null, new AttributionTags("t", "w", "u"))); + + private static DataClassification Classify(string text) => Detect(text).Classification; [Fact] public void Scenarios_B_C_and_the_connection_test_trigger_the_PII_classifier() @@ -598,15 +600,68 @@ public void Scenarios_B_C_and_the_connection_test_trigger_the_PII_classifier() Assert.Equal(DataClassification.Pii, Classify(ScenarioPresets.Find('B')!.Prompt)); Assert.Equal(DataClassification.Pii, Classify(ScenarioPresets.Find('C')!.Prompt)); Assert.Equal(DataClassification.Pii, Classify(ConnectionLogic.GovernedTestPrompt())); + // The synthetic marker is the published sample SSN, and B/C are the same request (C differs only in the + // operator's route state), so both escalate their Public baseline the same way. + Assert.Contains("078-05-1120", ScenarioPresets.SensitiveTicketPrompt, StringComparison.Ordinal); + Assert.Equal(ScenarioPresets.Find('B')!.Prompt, ScenarioPresets.Find('C')!.Prompt); + Assert.Equal("US SSN pattern", Detect(ScenarioPresets.SensitiveTicketPrompt).Signal); + Assert.Equal("Public", ScenarioPresets.Find('B')!.PreferredBaseline); + Assert.Equal("Public", ScenarioPresets.Find('C')!.PreferredBaseline); + } + + [Fact] + public void Scenario_A_detects_nothing_so_its_Public_baseline_is_not_escalated() + { + // The detector's no-match result is Internal with NO signal = "no escalation"; the final classification is + // max(baseline, detected-if-signalled), so A stays at its Public profile baseline. + var a = ScenarioPresets.Find('A')!; + Assert.Equal("Public", a.PreferredBaseline); + var r = Detect(a.Prompt); + Assert.Null(r.Signal); + Assert.True(r.Classification < DataClassification.Pii); + Assert.Equal(ScenarioPresets.TicketPrompt, a.Prompt); + Assert.False(a.FreshNonce); } [Fact] - public void Scenarios_A_and_D_carry_nothing_sensitive() + public void Scenario_D_carries_nothing_sensitive_and_keeps_the_operator_profile() { + var d = ScenarioPresets.Find('D')!; + Assert.True(d.FreshNonce); + Assert.Null(d.PreferredBaseline); // pause demo: no baseline is forced + var form = new PlaygroundForm(); - ScenarioPresets.ApplyTo(ScenarioPresets.Find('D')!, form); - Assert.True(Classify(ScenarioPresets.TicketPrompt) < DataClassification.Pii); - Assert.True(Classify(RequestSnapshot.Freeze(1, form, T0).Prompt) < DataClassification.Pii); + ScenarioPresets.ApplyTo(d, form, Apps(), Profiles()); + Assert.Equal("internal", form.ProfileId); // the app default stays — D never picks a profile + Assert.True(form.FreshNonce); + var frozen = RequestSnapshot.Freeze(1, form, T0).Prompt; + Assert.Null(Detect(ScenarioPresets.TicketPrompt).Signal); + Assert.Null(Detect(frozen).Signal); // the nonce never looks like PII/PHI + Assert.True(Classify(frozen) < DataClassification.Pii); + } + + [Fact] + public void Every_preset_only_populates_and_never_touches_the_operator_settings() + { + Assert.Equal(new[] { 'A', 'B', 'C', 'D' }, ScenarioPresets.All.Select(p => p.Letter)); + foreach (var p in ScenarioPresets.All) + { + var form = new PlaygroundForm { Streaming = false, MaxTokens = 33, Workflow = "wf", UseCase = "uc" }; + ScenarioPresets.ApplyTo(p, form, Apps(), Profiles()); + Assert.Equal(p.Letter, form.Scenario); + Assert.Equal(p.Prompt, form.Prompt); + Assert.Equal(RouteMode.Policy, form.Mode); + Assert.Equal(p.FreshNonce, form.FreshNonce); + Assert.False(form.Streaming); + Assert.Equal(33, form.MaxTokens); + Assert.Equal("wf", form.Workflow); + Assert.Equal("uc", form.UseCase); + Assert.Equal(ScenarioPresets.ExpectedLow, p.ExpectedAnswer); + Assert.True(p.StillMatches(form)); + } + Assert.Same(ScenarioPresets.Find('b'), ScenarioPresets.Find("B")); + Assert.Null(ScenarioPresets.Find('Z')); + Assert.Null(ScenarioPresets.Find("AB")); } } @@ -676,7 +731,7 @@ public void Eligible_overrides_follow_policies_profile_baseline_and_mode() { var config = new CovenantConfigDto { - Mode = "Hybrid", + Mode = "hybrid", // v2 wire spelling (KebabEnumConverter) Connections = [ new() { Id = "ollama", DisplayName = "Ollama", Boundary = "Local", Enabled = true, Models = [new() { ModelId = "qwen3:8b", DisplayName = "Qwen" }] }, @@ -700,7 +755,9 @@ public void Eligible_overrides_follow_policies_profile_baseline_and_mode() Assert.Equal(new[] { "ollama/qwen3:8b" }, ComposerRules.EligibleOverrides(config, "internal", null).Select(o => o.Value)); - config.Mode = "LocalOnly"; + config.Mode = "local-only"; + Assert.Equal(new[] { "ollama/qwen3:8b" }, ComposerRules.EligibleOverrides(config, "public-tickets", null).Select(o => o.Value)); + config.Mode = "LocalOnly"; // enum-name spelling from an older Host is still understood Assert.Equal(new[] { "ollama/qwen3:8b" }, ComposerRules.EligibleOverrides(config, "public-tickets", null).Select(o => o.Value)); } } @@ -1167,4 +1224,33 @@ public void Launch_link_reads_only_the_admin_token_from_the_fragment_and_ignores Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#")); Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#other=1")); } + + [Fact] + public void Launch_link_token_rides_only_in_the_fragment() + { + Assert.Equal("t-1", LaunchLink.Parse("http://localhost:5201/ui/connect#token=t-1")!.AdminToken); + Assert.Equal("t-2", LaunchLink.Parse("http://localhost:5201/ui/connect#appkey=k&token=t-2")!.AdminToken); + Assert.Equal("t-3", LaunchLink.Parse("http://localhost:5201/ui/connect#token=%20t-3%20")!.AdminToken); + + // Query-string tokens are sent to the server (and its logs): never accepted, even beside a fragment. + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect?token=abc")); + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect?token=abc#appkey=k")); + Assert.Equal("frag", LaunchLink.Parse("http://localhost:5201/ui/connect?token=query#token=frag")!.AdminToken); + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#token=")); + Assert.Null(LaunchLink.Parse("http://localhost:5201/ui/connect#token=" + new string('x', 513))); + Assert.Null(LaunchLink.Parse(null)); + } + + [Fact] + public void Launch_link_credentials_expose_no_application_key() + { + // Console v2 (ADR-0012): the console never holds an application key — the parsed credentials carry the + // admin token and nothing else, whatever the launcher put in the fragment. + var props = typeof(LaunchLink.Credentials).GetProperties().Select(p => p.Name).ToList(); + Assert.Equal(new[] { "AdminToken" }, props); + + var c = LaunchLink.Parse("http://localhost:5201/ui/connect#appkey=secret-app-key&token=adm"); + Assert.NotNull(c); + Assert.DoesNotContain("secret-app-key", c!.ToString(), StringComparison.Ordinal); + } } diff --git a/tests/Covenant.Tests/ContractRoundTripTests.cs b/tests/Covenant.Tests/ContractRoundTripTests.cs new file mode 100644 index 0000000..97cf98e --- /dev/null +++ b/tests/Covenant.Tests/ContractRoundTripTests.cs @@ -0,0 +1,361 @@ +using System.Text.Json; +using Covenant.Core; +using Covenant.Host; +using Xunit; +// Aliased, not imported: Core/Host and the console both have config shapes. Not "Ui": inside namespace +// Covenant.Tests that simple name would bind to the Covenant.Ui namespace before any compilation-unit alias. +using UiModels = Covenant.Ui.Models; + +namespace Covenant.Tests; + +// Proof that a configuration the console saves round-trips through the Host (console v2, ADR-0011): +// Host GET body (ConfigJsonContext.ConfigGetResponse) +// → console reads it (UiJsonContext.ConfigEnvelopeDto) +// → console writes the PUT body (UiJsonContext.ConfigPutRequestDto) +// → Host reads it (ConfigJsonContext.ConfigPutRequest) +// and the configuration that comes out is the one that went in. The UI DTOs are compiled in by link +// (Covenant.Tests.csproj), so a field the console drops or misspells fails here, not in production. +public sealed class ContractRoundTripTests +{ + private static readonly DateTimeOffset Created = new(2026, 10, 16, 9, 30, 0, TimeSpan.Zero); + + /// A representative v2 configuration that uses every enum value at least once. + private static CovenantConfig Representative(ProviderMode mode) => new() + { + Version = 7, + BaseVersion = 6, + RolledBackFrom = null, + Origin = "console", + CreatedUtc = Created, + ChangeSummary = "round-trip fixture", + Mode = mode, + Connections = + [ + new ConnectionConfig + { + Id = "ollama", DisplayName = "Ollama (in perimeter)", Kind = ProviderKind.Ollama, Boundary = Boundary.Local, + Endpoint = "http://ollama-host:11434/v1", Enabled = true, SecretRef = null, TimeoutSeconds = 90, + Models = + [ + new ModelConfig + { + ModelId = "qwen3:8b", DisplayName = "Qwen 3 8B", ContextTokens = 32768, MaxOutputTokens = 4096, + Price = new PriceConfig { InputPer1M = 0m, OutputPer1M = 0m, Basis = "zero-marginal-local", EffectiveDate = new DateOnly(2026, 10, 1) }, + }, + ], + }, + new ConnectionConfig + { + Id = "vllm", DisplayName = "vLLM", Kind = ProviderKind.OpenAiCompatible, Boundary = Boundary.Local, + Endpoint = "http://vllm-host:8000/v1", Enabled = false, SecretRef = "Secrets:vllm", + Models = [new ModelConfig { ModelId = "llama-3.1-8b", Price = null }], // unknown price stays unknown + }, + new ConnectionConfig + { + Id = "openai", DisplayName = "OpenAI", Kind = ProviderKind.OpenAi, Boundary = Boundary.Cloud, + Endpoint = null, Enabled = true, SecretRef = "Secrets:openai", TimeoutSeconds = 30, + Models = + [ + new ModelConfig + { + ModelId = "gpt-x-mini", DisplayName = "GPT-X mini", + Price = new PriceConfig { InputPer1M = 0.15m, OutputPer1M = 0.60m, Basis = "provider-list", EffectiveDate = new DateOnly(2026, 9, 15) }, + }, + new ModelConfig + { + ModelId = "gpt-x", + Price = new PriceConfig { InputPer1M = 2.50m, OutputPer1M = 10.00m, Basis = "contract" }, + }, + ], + }, + new ConnectionConfig + { + Id = "anthropic", DisplayName = "Anthropic", Kind = ProviderKind.Anthropic, Boundary = Boundary.Cloud, + Enabled = true, SecretRef = "Secrets:anthropic", + Models = + [ + new ModelConfig + { + ModelId = "claude-x", MaxOutputTokens = 8192, + Price = new PriceConfig { InputPer1M = 3.0m, OutputPer1M = 15.0m, Basis = "provider-list" }, + }, + ], + }, + ], + Applications = + [ + new ApplicationConfig + { + Id = "demo-app", Team = "payments", Enabled = true, ConsoleTesting = true, + GrantedProfiles = ["public-tickets", "internal", "customer-pii", "clinical"], DefaultProfile = "internal", MaxOutputTokens = 512, + }, + new ApplicationConfig + { + Id = "prod-app", Team = "risk", Enabled = false, ConsoleTesting = false, GrantedProfiles = ["internal"], + }, + ], + Profiles = + [ + new WorkloadProfileConfig { Id = "public-tickets", Name = "Public tickets", Baseline = DataClassification.Public, Description = "Synthetic public text" }, + new WorkloadProfileConfig { Id = "internal", Name = "Internal", Baseline = DataClassification.Internal }, + new WorkloadProfileConfig { Id = "customer-pii", Name = "Customer PII", Baseline = DataClassification.Pii }, + new WorkloadProfileConfig { Id = "clinical", Name = "Clinical", Baseline = DataClassification.Phi }, + ], + Policies = + [ + new PolicyConfigV2 + { + Id = "public", Name = "Public: economical cloud, local fallback", Enabled = true, + Classifications = [DataClassification.Public], + Profiles = ["public-tickets"], + // Order is precedence: primary first, then approved fallbacks. + Targets = + [ + new PolicyTarget { ConnectionId = "openai", ModelId = "gpt-x-mini" }, + new PolicyTarget { ConnectionId = "anthropic", ModelId = "claude-x", Paused = true }, + new PolicyTarget { ConnectionId = "ollama", ModelId = "qwen3:8b" }, + ], + Strategy = RoutingStrategy.Fixed, + Retry = new RetrySettings { MaxAttempts = 3, DeadlineMs = 45_000, On = ["timeout", "5xx"] }, + Explanation = "Public text may use the approved cloud model.", + }, + new PolicyConfigV2 + { + Id = "internal", Name = "Internal: length heuristic", Enabled = true, Paused = true, + Classifications = [DataClassification.Internal], + Targets = + [ + new PolicyTarget { ConnectionId = "ollama", ModelId = "qwen3:8b" }, + new PolicyTarget { ConnectionId = "openai", ModelId = "gpt-x" }, + ], + Strategy = RoutingStrategy.LengthHeuristic, + ThresholdTokens = 750, + }, + new PolicyConfigV2 + { + Id = "sensitive", Name = "PII/PHI: local only", Enabled = false, + Classifications = [DataClassification.Pii, DataClassification.Phi], + Targets = [new PolicyTarget { ConnectionId = "ollama", ModelId = "qwen3:8b" }, new PolicyTarget { ConnectionId = "vllm", ModelId = "llama-3.1-8b" }], + Retry = new RetrySettings { MaxAttempts = 1, DeadlineMs = 10_000, On = ["connect"] }, + }, + ], + Budgets = + [ + new BudgetConfigV2 { Id = "global", Scope = "global", CapUsd = 250.00m, Period = BudgetPeriod.Monthly, WarnAt = [0.5m, 0.9m], Enforcement = BudgetEnforcement.Hard }, + new BudgetConfigV2 { Id = "team-risk", Scope = "team:risk", CapUsd = 12.5m, Period = BudgetPeriod.Daily, Enforcement = BudgetEnforcement.WarnOnly }, + new BudgetConfigV2 { Id = "app-demo", Scope = "application:demo-app", CapUsd = 1m, Period = BudgetPeriod.None, WarnAt = [], Enforcement = BudgetEnforcement.Hard }, + ], + Settings = new OperationalSettings + { + CacheTtlSeconds = 300, CacheMaxEntries = 2_000, PromptPreviewChars = 80, TraceRetentionMinutes = 15, + RateLimitGlobalPerMinute = 600, RateLimitPerTeamPerMinute = 60, + }, + SavingsBaseline = new ModelRef("openai", "gpt-x"), + }; + + private static string HostGetBody(CovenantConfig cfg) => JsonSerializer.Serialize(new ConfigGetResponse + { + Version = cfg.Version, + Etag = "\"v" + cfg.Version + "\"", + Config = cfg, + Secrets = new Dictionary + { + ["Secrets:openai"] = new() { Available = true }, + ["Secrets:anthropic"] = new() { Available = false }, + ["Secrets:vllm"] = new() { Available = false }, + }, + AllowList = ["api.openai.com:443", "ollama-host:11434"], + }, ConfigJsonContext.Default.ConfigGetResponse); + + /// GET body → console envelope → console PUT body → Host PUT request. + private static (string GetBody, UiModels.ConfigEnvelopeDto Envelope, string PutBody, ConfigPutRequest Put) RoundTrip(CovenantConfig cfg) + { + var getBody = HostGetBody(cfg); + var envelope = JsonSerializer.Deserialize(getBody, UiModels.UiJsonContext.Default.ConfigEnvelopeDto); + Assert.NotNull(envelope); + Assert.NotNull(envelope!.Config); + + var putBody = JsonSerializer.Serialize( + new UiModels.ConfigPutRequestDto { Config = envelope.Config, ChangeSummary = "saved by the console" }, + UiModels.UiJsonContext.Default.ConfigPutRequestDto); + var put = JsonSerializer.Deserialize(putBody, ConfigJsonContext.Default.ConfigPutRequest); + Assert.NotNull(put); + Assert.NotNull(put!.Config); + return (getBody, envelope, putBody, put); + } + + [Theory] + [InlineData(ProviderMode.LocalOnly, "local-only")] + [InlineData(ProviderMode.Hybrid, "hybrid")] + [InlineData(ProviderMode.LegacyCloud, "legacy-cloud")] + public void Console_saved_config_round_trips_through_the_host_unchanged(ProviderMode mode, string wireMode) + { + var original = Representative(mode); + var (_, envelope, putBody, put) = RoundTrip(original); + + // The console saw the wire spelling verbatim. + Assert.Equal(wireMode, envelope.Config!.Mode); + Assert.Equal(wireMode, Wire(putBody).GetProperty("config").GetProperty("mode").GetString()); + Assert.Equal("saved by the console", put.ChangeSummary); + + // Deep equality: the Host's own serialization of what came back is byte-identical to what went out. + // (Records with IReadOnlyList members compare lists by reference, so compare canonical JSON instead.) + var before = JsonSerializer.Serialize(original, ConfigJsonContext.Default.CovenantConfig); + var after = JsonSerializer.Serialize(put.Config!, ConfigJsonContext.Default.CovenantConfig); + Assert.Equal(before, after); + + AssertMeaningfulFieldsEqual(original, put.Config!); + } + + private static void AssertMeaningfulFieldsEqual(CovenantConfig a, CovenantConfig b) + { + Assert.Equal(a.Version, b.Version); + Assert.Equal(a.BaseVersion, b.BaseVersion); + Assert.Equal(a.Origin, b.Origin); + Assert.Equal(a.CreatedUtc, b.CreatedUtc); + Assert.Equal(a.ChangeSummary, b.ChangeSummary); + Assert.Equal(a.Mode, b.Mode); + Assert.Equal(a.SavingsBaseline, b.SavingsBaseline); + + Assert.Equal(a.Connections.Select(c => c.Id), b.Connections.Select(c => c.Id)); + foreach (var (x, y) in a.Connections.Zip(b.Connections)) + { + Assert.Equal(x.Kind, y.Kind); + Assert.Equal(x.Boundary, y.Boundary); + Assert.Equal(x.DisplayName, y.DisplayName); + Assert.Equal(x.Endpoint, y.Endpoint); + Assert.Equal(x.Enabled, y.Enabled); + Assert.Equal(x.SecretRef, y.SecretRef); + Assert.Equal(x.TimeoutSeconds, y.TimeoutSeconds); + Assert.Equal(x.Models.Select(m => m.ModelId), y.Models.Select(m => m.ModelId)); + foreach (var (mx, my) in x.Models.Zip(y.Models)) + { + Assert.Equal(mx.DisplayName, my.DisplayName); + Assert.Equal(mx.ContextTokens, my.ContextTokens); + Assert.Equal(mx.MaxOutputTokens, my.MaxOutputTokens); + Assert.Equal(mx.Price, my.Price); // PriceConfig has only scalar members: record equality is deep + } + } + + Assert.Equal(a.Applications.Count, b.Applications.Count); + foreach (var (x, y) in a.Applications.Zip(b.Applications)) + { + Assert.Equal(x.Id, y.Id); + Assert.Equal(x.Team, y.Team); + Assert.Equal(x.Enabled, y.Enabled); + Assert.Equal(x.ConsoleTesting, y.ConsoleTesting); + Assert.Equal(x.GrantedProfiles, y.GrantedProfiles); + Assert.Equal(x.DefaultProfile, y.DefaultProfile); + Assert.Equal(x.MaxOutputTokens, y.MaxOutputTokens); + } + + Assert.Equal(a.Profiles, b.Profiles); // scalar-only records: deep + + Assert.Equal(a.Policies.Count, b.Policies.Count); + foreach (var (x, y) in a.Policies.Zip(b.Policies)) + { + Assert.Equal(x.Id, y.Id); + Assert.Equal(x.Name, y.Name); + Assert.Equal(x.Enabled, y.Enabled); + Assert.Equal(x.Paused, y.Paused); + Assert.Equal(x.Classifications, y.Classifications); + Assert.Equal(x.Profiles, y.Profiles); + Assert.Equal(x.Targets, y.Targets); // order, connection, model and paused flag + Assert.Equal(x.Strategy, y.Strategy); + Assert.Equal(x.ThresholdTokens, y.ThresholdTokens); + Assert.Equal(x.Retry.MaxAttempts, y.Retry.MaxAttempts); + Assert.Equal(x.Retry.DeadlineMs, y.Retry.DeadlineMs); + Assert.Equal(x.Retry.On, y.Retry.On); + Assert.Equal(x.Explanation, y.Explanation); + } + + Assert.Equal(a.Budgets.Count, b.Budgets.Count); + foreach (var (x, y) in a.Budgets.Zip(b.Budgets)) + { + Assert.Equal(x.Id, y.Id); + Assert.Equal(x.Scope, y.Scope); + Assert.Equal(x.CapUsd, y.CapUsd); + Assert.Equal(x.Period, y.Period); + Assert.Equal(x.WarnAt, y.WarnAt); + Assert.Equal(x.Enforcement, y.Enforcement); + } + + Assert.Equal(a.Settings, b.Settings); + } + + [Fact] + public void Host_wire_spellings_are_the_contract_vocabulary_and_the_console_reads_them_verbatim() + { + var (getBody, envelope, putBody, _) = RoundTrip(Representative(ProviderMode.Hybrid)); + + foreach (var body in new[] { getBody, putBody }) + { + var cfg = Wire(body).GetProperty("config"); + Assert.Equal("hybrid", cfg.GetProperty("mode").GetString()); + + var conns = cfg.GetProperty("connections").EnumerateArray().ToList(); + Assert.Equal(new[] { "Ollama", "OpenAiCompatible", "OpenAi", "Anthropic" }, conns.Select(c => c.GetProperty("kind").GetString())); + Assert.Equal(new[] { "Local", "Local", "Cloud", "Cloud" }, conns.Select(c => c.GetProperty("boundary").GetString())); + + var price = conns[2].GetProperty("models")[0].GetProperty("price"); + Assert.Equal(0.15m, price.GetProperty("input_per_1m").GetDecimal()); + Assert.Equal(0.60m, price.GetProperty("output_per_1m").GetDecimal()); + Assert.False(price.TryGetProperty("input_per1_m", out _)); + + var policies = cfg.GetProperty("policies").EnumerateArray().ToList(); + Assert.Equal(new[] { "fixed", "length-heuristic", "fixed" }, policies.Select(p => p.GetProperty("strategy").GetString())); + Assert.Equal(new[] { "Public", "Internal", "Pii", "Phi" }, + policies.SelectMany(p => p.GetProperty("classifications").EnumerateArray().Select(c => c.GetString()))); + Assert.Equal(new[] { "openai/gpt-x-mini", "anthropic/claude-x", "ollama/qwen3:8b" }, + policies[0].GetProperty("targets").EnumerateArray().Select(t => t.GetProperty("connection_id").GetString() + "/" + t.GetProperty("model_id").GetString())); + + Assert.Equal(new[] { "Public", "Internal", "Pii", "Phi" }, + cfg.GetProperty("profiles").EnumerateArray().Select(p => p.GetProperty("baseline").GetString())); + + var budgets = cfg.GetProperty("budgets").EnumerateArray().ToList(); + Assert.Equal(new[] { "monthly", "daily", "none" }, budgets.Select(b => b.GetProperty("period").GetString())); + Assert.Equal(new[] { "hard", "warn-only", "hard" }, budgets.Select(b => b.GetProperty("enforcement").GetString())); + } + + // The console DTOs hold the same strings (enums travel as strings; nothing re-spelled client-side). + var dto = envelope.Config!; + Assert.Equal(new[] { "Ollama", "OpenAiCompatible", "OpenAi", "Anthropic" }, dto.Connections.Select(x => x.Kind)); + Assert.Equal(new[] { "Local", "Local", "Cloud", "Cloud" }, dto.Connections.Select(x => x.Boundary)); + Assert.Equal(new[] { "fixed", "length-heuristic", "fixed" }, dto.Policies.Select(p => p.Strategy)); + Assert.Equal(new[] { "monthly", "daily", "none" }, dto.Budgets.Select(b => b.Period)); + Assert.Equal(new[] { "hard", "warn-only", "hard" }, dto.Budgets.Select(b => b.Enforcement)); + Assert.Equal(new[] { "Public", "Internal", "Pii", "Phi" }, dto.Profiles.Select(p => p.Baseline)); + Assert.Equal(new[] { "Pii", "Phi" }, dto.Policies[2].Classifications); + Assert.Equal(0.15m, dto.Connections[2].Models[0].Price!.InputPer1M); + Assert.Equal(0.60m, dto.Connections[2].Models[0].Price!.OutputPer1M); + Assert.Equal("2026-09-15", dto.Connections[2].Models[0].Price!.EffectiveDate); + Assert.Null(dto.Connections[1].Models[0].Price); // unknown price is not $0 + Assert.Equal(new[] { false, true, false }, dto.Policies[0].Targets.Select(t => t.Paused)); + Assert.Equal(new[] { false, true, false }, dto.Policies.Select(p => p.Paused)); + Assert.Equal(3, dto.Policies[0].Retry!.MaxAttempts); + Assert.Equal(45_000, dto.Policies[0].Retry!.DeadlineMs); + Assert.Equal(new[] { "timeout", "5xx" }, dto.Policies[0].Retry!.On); + + // Envelope metadata survives too. + Assert.Equal(7, envelope.Version); + Assert.Equal("\"v7\"", envelope.Etag); + Assert.True(envelope.Secrets!["Secrets:openai"].Available); + Assert.False(envelope.Secrets!["Secrets:anthropic"].Available); + Assert.Equal(new[] { "api.openai.com:443", "ollama-host:11434" }, envelope.AllowList); + } + + [Fact] + public void Console_put_body_never_carries_an_allow_sensitive_cloud_switch() + { + // PII/PHI never route to cloud destinations: there is no console-side override to send. + var (_, _, putBody, _) = RoundTrip(Representative(ProviderMode.Hybrid)); + foreach (var p in Wire(putBody).GetProperty("config").GetProperty("policies").EnumerateArray()) + Assert.False(p.TryGetProperty("allow_sensitive_cloud", out _)); + } + + private static JsonElement Wire(string json) + { + using var doc = JsonDocument.Parse(json); + return doc.RootElement.Clone(); + } +} diff --git a/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs b/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs index 834bffa..f61027c 100644 --- a/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs +++ b/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs @@ -68,10 +68,25 @@ public static string ReadShared(string path) return reader.ReadToEnd(); } + /// Every per-instance durable path derives from ONE unique audit path (no shared /tmp default): the audit + /// log, the configuration repository (Config:Path) and the budget ledger (Budget:LedgerPath). + public static void IsolatePaths(IWebHostBuilder builder, string auditPath) + { + builder.UseSetting("Audit:Path", auditPath); + builder.UseSetting("Config:Path", ConfigDirFor(auditPath)); + builder.UseSetting("Budget:LedgerPath", auditPath + ".ledger.jsonl"); + } + + public static string ConfigDirFor(string auditPath) => auditPath + ".config"; + + /// Deletes the audit file and every sibling derived from it (archives, anchors, ledger, config repository). public static void DeleteWithSiblings(string path) { - foreach (var f in Directory.GetFiles(Path.GetDirectoryName(path)!, Path.GetFileName(path) + "*")) + var dir = Path.GetDirectoryName(path)!; + foreach (var f in Directory.GetFiles(dir, Path.GetFileName(path) + "*")) File.Delete(f); + foreach (var d in Directory.GetDirectories(dir, Path.GetFileName(path) + "*")) + try { Directory.Delete(d, recursive: true); } catch (IOException) { } } } @@ -126,7 +141,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("Auth:Keys:0:Key", "k"); builder.UseSetting("Auth:Keys:0:Principal", "p"); builder.UseSetting("Auth:Keys:0:Team", "t"); - builder.UseSetting("Audit:Path", AuditPath); + CorrelationTestKit.IsolatePaths(builder, AuditPath); // No Local:* → PII routes to the unconfigured local placeholder and fails closed. builder.ConfigureTestServices(services => services.AddSingleton(new ChatClientRegistry( @@ -271,9 +286,13 @@ public async Task Pause_403_stops_at_pause_without_calling_the_provider() } } + /// Review fix 4 (stricter than pre-v2, same intent): with no Local:* the legacy import's PII/PHI route + /// names the explicitly DISABLED placeholder connection, so the request is refused at POLICY — no model is + /// selected, none attempted, no provider and no cloud call. (Pre-v2: selected the placeholder, refused at provider.) [Fact] - public async Task Missing_local_adapter_403_selected_but_never_attempted() + public async Task Missing_local_model_403_refused_at_policy_never_selected_or_attempted() { + int callsBefore = _factory.Provider.Calls; var resp = await _client.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("my ssn is 123-45-6789")); Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); var id = CorrelationTestKit.HeaderId(resp); @@ -283,11 +302,14 @@ public async Task Missing_local_adapter_403_selected_but_never_attempted() var e = await CorrelationTestKit.LookupAsync(_client, id); Assert.Equal(DataClassification.Pii, e.Classification); Assert.Equal("Governance", e.DenialKind); - Assert.Equal("provider", e.StoppedAtStage); - Assert.Equal("local-model-not-configured", e.SelectedModel); + Assert.Equal("policy", e.StoppedAtStage); + Assert.Contains("no eligible destination", e.Reason, StringComparison.Ordinal); + Assert.Contains("connection 'local' is disabled (not configured)", e.Reason, StringComparison.Ordinal); + Assert.Null(e.SelectedModel); Assert.Null(e.AttemptedModel); Assert.Null(e.ServedByModel); Assert.Equal("no_call", e.CostBasis); + Assert.Equal(callsBefore, _factory.Provider.Calls); // no provider (and so no cloud) call } [Fact] @@ -471,7 +493,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("Auth:Keys:0:Key", "k"); builder.UseSetting("Auth:Keys:0:Principal", "p"); builder.UseSetting("Auth:Keys:0:Team", "t"); - builder.UseSetting("Audit:Path", AuditPath); + CorrelationTestKit.IsolatePaths(builder, AuditPath); builder.UseSetting("RateLimit:GlobalPerMinute", "1"); builder.ConfigureTestServices(services => services.AddSingleton(new ChatClientRegistry( diff --git a/tests/Covenant.Tests/HttpMappingTests.cs b/tests/Covenant.Tests/HttpMappingTests.cs index fbbd2bf..614d9d6 100644 --- a/tests/Covenant.Tests/HttpMappingTests.cs +++ b/tests/Covenant.Tests/HttpMappingTests.cs @@ -27,7 +27,7 @@ public HttpMappingTests(WebApplicationFactory factory) b.UseSetting("Auth:Keys:0:Principal", "itest"); b.UseSetting("Auth:Keys:0:Team", "itest-team"); b.UseSetting("RateLimit:PerTeamPerMinute", "1"); - b.UseSetting("Audit:Path", _auditPath); + CorrelationTestKit.IsolatePaths(b, _auditPath); }); _client = _factory.CreateClient(); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "test-api-key"); @@ -36,7 +36,7 @@ public HttpMappingTests(WebApplicationFactory factory) public void Dispose() { _factory.Dispose(); - if (File.Exists(_auditPath)) File.Delete(_auditPath); + CorrelationTestKit.DeleteWithSiblings(_auditPath); } private static StringContent Chat(string content, bool stream = false) => diff --git a/tests/Covenant.Tests/LegacyImportTests.cs b/tests/Covenant.Tests/LegacyImportTests.cs index 2ff399d..ca95e3d 100644 --- a/tests/Covenant.Tests/LegacyImportTests.cs +++ b/tests/Covenant.Tests/LegacyImportTests.cs @@ -70,6 +70,7 @@ public void Imported_configuration_routes_exactly_like_the_pre_v2_policy(string var (legacyPolicy, threshold) = LegacyPolicy(cfg); var legacy = new PolicyEngine(legacyPolicy, new RoutingOptions { ComplexityTokenThreshold = threshold }); var snapshot = new RuntimeSnapshot(Import(cfg)); + bool localConfigured = StartupValidation.Trimmed(cfg["Local:ModelId"]) is { Length: > 0 }; var prompts = new[] { "hi", new string('x', 99), new string('x', 101), new string('x', 1601), new string('x', 1605) }; var models = new string?[] { null, "gpt-4o-mini", "GPT-4O", "gpt-4o", "claude-haiku-4-5", "qwen3:8b", "cheap-1", "strong-1", @@ -84,6 +85,19 @@ public void Imported_configuration_routes_exactly_like_the_pre_v2_policy(string var before = legacy.Evaluate(ctx); var after = PolicyEngineV2.Evaluate(snapshot, cls, PolicyEngineV2.LegacyInternalProfile, model, ctx.Request.Messages); var label = $"{shape} {cls} len={prompt.Length} model={model ?? "(none)"}"; + if (!localConfigured && cls >= DataClassification.Pii) + { + // Review fix 4 (deliberately STRICTER than pre-v2): without Local:* the PII/PHI route points + // at the explicitly DISABLED placeholder, so it is refused at POLICY. Pre-v2 "allowed" it to + // the placeholder and refused at the provider stage — never served either way. + if (after.Effect != PolicyEffect.Deny) throw new Xunit.Sdk.XunitException($"{label}: expected a policy refusal, got {after.Effect}"); + if (before.Effect == PolicyEffect.Allow) + Assert.Contains("connection 'local' is disabled (not configured)", after.Reason, StringComparison.Ordinal); + else + Assert.Equal(before.Reason, after.Reason); + compared++; + continue; + } if (before.Effect != after.Effect) throw new Xunit.Sdk.XunitException($"{label}: effect {before.Effect} → {after.Effect} ({after.Reason})"); if (before.Route != after.Route) throw new Xunit.Sdk.XunitException($"{label}: route {before.Route} → {after.Route}"); if (before.Effect == PolicyEffect.Deny) Assert.Equal(before.Reason, after.Reason); @@ -102,9 +116,10 @@ public void Imported_configuration_validates_against_the_startup_environment(str { EgressAllowList = StartupEgress.BuildAllowList(cfg), SecretAvailable = StartupEgress.SecretAvailability(cfg), - LegacyCompat = v1.Mode == ProviderMode.LegacyCloud, + LocalEndpoints = StartupEgress.LocalEndpoints(cfg), }); Assert.True(result.IsValid, string.Join("; ", result.Errors.Select(e => $"{e.Path} {e.Code} {e.Message}"))); + Assert.DoesNotContain(result.Warnings, w => w.Code == "unknown_connection"); // every target names a real connection } [Fact] @@ -133,13 +148,31 @@ public void Modes_connections_and_the_unconfigured_local_placeholder_are_explici var cloud = Import(Shape("cloud")); Assert.Equal(ProviderMode.LegacyCloud, cloud.Mode); Assert.Equal("legacy-import", cloud.Origin); - Assert.Equal(new[] { "openai" }, cloud.Connections.Select(c => c.Id).ToArray()); + Assert.Equal(new[] { "openai", "local" }, cloud.Connections.Select(c => c.Id).ToArray()); var sensitive = cloud.Policies.Single(p => p.Id == "legacy-sensitive"); Assert.Equal(new[] { DataClassification.Pii, DataClassification.Phi }, sensitive.Classifications); Assert.Equal("local", sensitive.Targets.Single().ConnectionId); Assert.Equal(LegacyImport.UnconfiguredLocalModel, sensitive.Targets.Single().ModelId); Assert.Equal(new ModelRef("openai", "gpt-4o"), cloud.SavingsBaseline); + // Review fix 4: the explicitly DISABLED placeholder, and PII/PHI refused at policy because of it. + var placeholder = cloud.Connections.Single(c => c.Id == "local"); + Assert.False(placeholder.Enabled); + Assert.Null(placeholder.Endpoint); + Assert.Equal(Boundary.Local, placeholder.Boundary); + Assert.Equal(ProviderKind.OpenAiCompatible, placeholder.Kind); + Assert.Equal("Local model — not configured (import placeholder)", placeholder.DisplayName); + var pm = Assert.Single(placeholder.Models); + Assert.Equal(LegacyImport.UnconfiguredLocalModel, pm.ModelId); + Assert.Equal("zero-marginal-local", pm.Price!.Basis); + var refused = PolicyEngineV2.Evaluate(new RuntimeSnapshot(cloud), DataClassification.Pii, PolicyEngineV2.LegacyInternalProfile, null, + [new ChatMessage(ChatRole.User, "x")]); + Assert.Equal(PolicyEffect.Deny, refused.Effect); + Assert.Contains("no eligible destination", refused.Reason, StringComparison.Ordinal); + Assert.Contains("connection 'local' is disabled (not configured)", refused.Reason, StringComparison.Ordinal); + Assert.Equal(new[] { "openai", "local" }, Import(Shape("cloud+anthropic")).Connections.Where(c => c.Id != "anthropic").Select(c => c.Id).ToArray()); + Assert.True(Import(Shape("cloud+local")).Connections.Single(c => c.Id == "local").Enabled); + var localOnly = Import(Shape("local-only")); Assert.Equal(ProviderMode.LocalOnly, localOnly.Mode); var conn = Assert.Single(localOnly.Connections); @@ -156,11 +189,18 @@ public void Identities_budgets_and_operational_settings_are_imported() var cfg = Config(("OpenAI:ApiKey", "sk"), ("Budget:GlobalCapUsd", "7.5"), ("Budget:TeamCapsUsd:payments", "2"), ("Auth:Keys:0:Key", "k0"), ("Auth:Keys:0:Principal", "svc-a"), ("Auth:Keys:0:Team", "payments"), ("Auth:Keys:1:Key", "k1"), ("Auth:Keys:1:Principal", "svc-b"), ("Auth:Keys:1:Team", "risk"), ("Auth:Keys:1:Application", "risk-app"), - ("Auth:Keys:2:Key", "k2"), ("Auth:Keys:2:Principal", "alice@example.com"), ("Auth:Keys:2:Team", "ops"), // not a valid id → unbound + ("Auth:Keys:2:Key", "k2"), ("Auth:Keys:2:Principal", "alice@example.com"), ("Auth:Keys:2:Team", "ops"), // not a valid id → normalized ("Cache:TtlSeconds", "30"), ("RateLimit:PerTeamPerMinute", "9"), ("Audit:PromptPreviewChars", "40")); var v1 = Import(cfg); - Assert.Equal(new[] { "svc-a", "risk-app" }, v1.Applications.Select(a => a.Id).ToArray()); + // Review fix 7: one application per key at v1 — including a principal that is not a valid id (normalized + // deterministically, exactly as the auth stage normalizes it), so no key is left unbound. + var alice = ApplicationIds.FromKey("alice@example.com"); + Assert.StartsWith("alice-example.com-", alice, StringComparison.Ordinal); + Assert.True(ConfigValidator.IsValidId(alice)); + Assert.Equal(alice, new ApiKeyRecord("k2", "alice@example.com", "ops").Application); + Assert.Equal(new[] { "svc-a", "risk-app", alice }, v1.Applications.Select(a => a.Id).ToArray()); + Assert.Equal("ops", v1.Applications.Single(a => a.Id == alice).Team); Assert.All(v1.Applications, a => { Assert.False(a.ConsoleTesting); @@ -194,7 +234,11 @@ public void Demo_seeds_use_the_restrictive_defaults() var hybrid = DemoSeeds.Build(DemoSeeds.Hybrid, cfg, DateTimeOffset.UtcNow, errors); var local = DemoSeeds.Build(DemoSeeds.LocalOnly, cfg, DateTimeOffset.UtcNow, errors); Assert.Empty(errors); - var env = new ValidationEnvironment { EgressAllowList = StartupEgress.BuildAllowList(cfg), SecretAvailable = StartupEgress.SecretAvailability(cfg) }; + var env = new ValidationEnvironment + { + EgressAllowList = StartupEgress.BuildAllowList(cfg), SecretAvailable = StartupEgress.SecretAvailability(cfg), + LocalEndpoints = StartupEgress.LocalEndpoints(cfg), + }; Assert.True(ConfigValidator.Validate(hybrid, env).IsValid); Assert.True(ConfigValidator.Validate(local, env).IsValid); diff --git a/tests/Covenant.Tests/LocalOnlyModeTests.cs b/tests/Covenant.Tests/LocalOnlyModeTests.cs index 3cc5200..0897f0f 100644 --- a/tests/Covenant.Tests/LocalOnlyModeTests.cs +++ b/tests/Covenant.Tests/LocalOnlyModeTests.cs @@ -39,7 +39,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("Auth:Keys:0:Key", "k"); builder.UseSetting("Auth:Keys:0:Principal", "p"); builder.UseSetting("Auth:Keys:0:Team", "t"); - builder.UseSetting("Audit:Path", AuditPath); + CorrelationTestKit.IsolatePaths(builder, AuditPath); // Stub the local endpoint in-process; register cloud keys too, as tripwires that must stay at 0 calls. builder.ConfigureTestServices(services => services.AddSingleton(new ChatClientRegistry( diff --git a/tests/Covenant.Tests/PolicyEngineV2Tests.cs b/tests/Covenant.Tests/PolicyEngineV2Tests.cs index ee2ad9f..3e33924 100644 --- a/tests/Covenant.Tests/PolicyEngineV2Tests.cs +++ b/tests/Covenant.Tests/PolicyEngineV2Tests.cs @@ -13,8 +13,8 @@ private static PolicyOutcome Eval(CovenantConfig c, DataClassification cls, stri private static CovenantConfig WithPolicies(params PolicyConfigV2[] policies) => V2.Hybrid() with { Policies = policies }; - private static ConfigValidationResult Validate(CovenantConfig c, bool legacy = false, bool secrets = true) - => ConfigValidator.Validate(c, V2.Env(legacy, secrets)); + private static ConfigValidationResult Validate(CovenantConfig c, bool secrets = true) + => ConfigValidator.Validate(c, V2.Env(secrets)); [Fact] public void Demo_defaults_validate_cleanly_and_route_as_specified() @@ -121,26 +121,84 @@ public void Local_only_mode_excludes_cloud_targets_even_if_a_cloud_connection_is Assert.Contains(o.Excluded, x => x.Target.AdapterKey == "openai" && x.Reason.Contains("local-only", StringComparison.Ordinal)); } + /// Review fix 5: no AllowSensitiveCloud escape hatch. A PII/PHI policy listing a cloud target is a + /// validation ERROR (sensitive_cloud_target), and the engine still excludes cloud targets for PII/PHI. [Fact] - public void Sensitive_data_never_reaches_cloud_without_an_explicit_acknowledgement() + public void Sensitive_data_never_reaches_cloud_and_a_sensitive_policy_with_a_cloud_target_is_invalid() { var c = WithPolicies( V2.Policy("public", [DataClassification.Public, DataClassification.Internal], [V2.T("ollama", V2.LocalTag)]), V2.Policy("sensitive", [DataClassification.Pii, DataClassification.Phi], [V2.T("openai", V2.CloudModel), V2.T("ollama", V2.LocalTag)])); - var o = Eval(c, DataClassification.Pii); + var error = Assert.Single(Validate(c).Errors, e => e.Code == "sensitive_cloud_target"); + Assert.Equal("policies[1].targets[0]", error.Path); + var o = Eval(c, DataClassification.Pii); // defensive: engine excludes it anyway Assert.Equal(new[] { new RouteTarget("ollama", V2.LocalTag) }, o.Candidates); - Assert.Contains(Validate(c).Warnings, w => w.Code == "sensitive_cloud_without_ack"); + Assert.Contains(o.Excluded, x => x.Target.AdapterKey == "openai" && x.Reason.Contains("never routed to a cloud", StringComparison.Ordinal)); var onlyCloud = WithPolicies( V2.Policy("public", [DataClassification.Public, DataClassification.Internal], [V2.T("ollama", V2.LocalTag)]), V2.Policy("sensitive", [DataClassification.Pii, DataClassification.Phi], [V2.T("openai", V2.CloudModel)])); + Assert.Contains(Validate(onlyCloud).Errors, e => e.Code == "sensitive_cloud_target"); Assert.Equal(PolicyEffect.Deny, Eval(onlyCloud, DataClassification.Phi).Effect); // refused, never sent to cloud + Assert.Equal(PolicyEffect.Deny, Eval(onlyCloud, DataClassification.Pii, model: V2.CloudModel).Effect); + Assert.Equal(PolicyEffect.Deny, Eval(onlyCloud with { Mode = ProviderMode.LegacyCloud }, DataClassification.Pii).Effect); + Assert.Null(typeof(PolicyConfigV2).GetProperty("AllowSensitiveCloud")); // the escape hatch is gone + } - var acknowledged = WithPolicies( - V2.Policy("public", [DataClassification.Public, DataClassification.Internal], [V2.T("ollama", V2.LocalTag)]), - V2.Policy("sensitive", [DataClassification.Pii, DataClassification.Phi], [V2.T("openai", V2.CloudModel)], allowSensitiveCloud: true)); - Assert.Equal(new RouteTarget("openai", V2.CloudModel), Eval(acknowledged, DataClassification.Pii).Route); - Assert.Contains(Validate(acknowledged).Warnings, w => w.Code == "sensitive_cloud_without_ack" && w.Message.Contains("WARNING", StringComparison.Ordinal)); + /// Review fix 9: a paused profile-specific policy refuses its traffic; it never falls through to the + /// less specific (classification-only) policy that would otherwise serve it. + [Fact] + public void Paused_specific_policy_never_falls_through_to_a_less_specific_policy() + { + var c = WithPolicies( + V2.Policy("public-generic", [DataClassification.Public], [V2.T("openai", V2.CloudModel)]), + V2.Policy("public-demo-only", [DataClassification.Public], [V2.T("ollama", V2.LocalTag)], profiles: ["public-demo"], paused: true), + V2.Policy("rest", [DataClassification.Internal, DataClassification.Pii, DataClassification.Phi], [V2.T("ollama", V2.LocalTag)])); + Assert.Empty(Validate(c).Errors); + var o = Eval(c, DataClassification.Public, "public-demo"); + Assert.Equal(PolicyEffect.Deny, o.Effect); + Assert.Equal("public-demo-only", o.PolicyId); + Assert.Equal("policy 'public-demo-only' is paused", o.Reason); + Assert.Null(o.Route); + // With an override naming the generic policy's target, still refused (the paused policy decided). + Assert.Equal(PolicyEffect.Deny, Eval(c, DataClassification.Public, "public-demo", model: V2.CloudModel).Effect); + // Other profiles are unaffected: the generic policy serves them. + Assert.Equal("public-generic", Eval(c, DataClassification.Public, "internal-default").PolicyId); + } + + /// Review fix 2: a bare model id eligible on two connections is REFUSED (never first-wins); + /// connection/model resolves exactly; a bare id eligible on exactly one connection still pins. + [Fact] + public void Ambiguous_bare_model_override_is_refused_and_connection_slash_model_resolves_exactly() + { + var c = V2.Hybrid() with + { + Connections = [V2.Ollama(id: "local-a"), V2.Ollama(id: "local-b"), V2.OpenAi()], + Policies = + [ + V2.Policy("public", [DataClassification.Public], [V2.T("openai", V2.CloudModel), V2.T("local-a", V2.LocalTag)]), + V2.Policy("internal", [DataClassification.Internal, DataClassification.Pii, DataClassification.Phi], + [V2.T("local-a", V2.LocalTag), V2.T("local-b", V2.LocalTag)]), + ], + }; + Assert.Empty(Validate(c).Errors); + + var ambiguous = Eval(c, DataClassification.Internal, model: V2.LocalTag); + Assert.Equal(PolicyEffect.Deny, ambiguous.Effect); + Assert.Equal($"model id '{V2.LocalTag}' is ambiguous across connections local-a, local-b — use connection/model", ambiguous.Reason); + Assert.Null(ambiguous.Route); + + var exactB = Eval(c, DataClassification.Internal, model: $"local-b/{V2.LocalTag}"); + Assert.Equal(new[] { new RouteTarget("local-b", V2.LocalTag) }, exactB.Candidates); // pinned, no fallback + var exactA = Eval(c, DataClassification.Internal, model: $"LOCAL-A/{V2.LocalTag}"); + Assert.Equal(new RouteTarget("local-a", V2.LocalTag), exactA.Route); + + // Only ONE eligible target carries the bare id under the Public policy ⇒ it resolves. + Assert.Equal(new RouteTarget("local-a", V2.LocalTag), Eval(c, DataClassification.Public, "public-demo", model: V2.LocalTag).Route); + + // Ambiguity is about ELIGIBLE targets: pause local-b and the bare id resolves to local-a. + var paused = c with { Policies = c.Policies.Select(p => p.Id != "internal" ? p : p with { Targets = [V2.T("local-a", V2.LocalTag), V2.T("local-b", V2.LocalTag, paused: true)] }).ToList() }; + Assert.Equal(new RouteTarget("local-a", V2.LocalTag), Eval(paused, DataClassification.Internal, model: V2.LocalTag).Route); } [Fact] @@ -188,17 +246,62 @@ public void Unpriced_paid_target_under_a_hard_budget_is_ineligible_and_invalid() Assert.Contains(o.Excluded, x => x.Reason.Contains("unpriced", StringComparison.Ordinal)); } + /// Review fix 4: no mode bypass. Unknown and disabled connections are never eligible — legacy-cloud + /// included — and unknown_connection is always a validation error. + [Fact] + public void Disabled_or_unknown_connection_targets_are_ineligible_in_every_mode() + { + foreach (var mode in new[] { ProviderMode.Hybrid, ProviderMode.LegacyCloud, ProviderMode.LocalOnly }) + { + var disabled = V2.Hybrid() with { Mode = mode, Connections = [V2.Ollama(enabled: false), V2.OpenAi(enabled: false)] }; + var d = Eval(disabled, DataClassification.Internal); + Assert.Equal(PolicyEffect.Deny, d.Effect); + Assert.Contains(d.Excluded, x => x.Reason.Contains("is disabled", StringComparison.Ordinal)); + + var unknown = V2.Hybrid() with { Mode = mode, Connections = [V2.OpenAi(enabled: mode != ProviderMode.LocalOnly)] }; // ollama removed + var u = Eval(unknown, DataClassification.Internal); + Assert.Equal(PolicyEffect.Deny, u.Effect); + Assert.Contains("unknown connection 'ollama'", u.Reason, StringComparison.Ordinal); + Assert.Contains(Validate(unknown).Errors, e => e.Code == "unknown_connection"); + Assert.DoesNotContain(Validate(unknown).Warnings, w => w.Code == "unknown_connection"); + } + } + + /// Review fix 6: Boundary.Local must be bound to a startup-approved local endpoint; cloud SDK kinds are + /// always Cloud. A cloud host relabelled Local (to reach PII/PHI) is boundary_not_approved. [Fact] - public void Disabled_or_unknown_connection_targets_are_ineligible_outside_legacy_cloud() + public void Local_boundary_requires_a_startup_approved_endpoint() { - var disabled = V2.Hybrid() with { Connections = [V2.Ollama(), V2.OpenAi(enabled: false)] }; - Assert.Contains(Eval(disabled, DataClassification.Public, "public-demo").Excluded, x => x.Reason.Contains("disabled", StringComparison.Ordinal)); + var relabelled = new ConnectionConfig + { + Id = "sneaky", DisplayName = "Cloud host labelled local", Kind = ProviderKind.OpenAiCompatible, Boundary = Boundary.Local, + Endpoint = "https://api.openai.com/v1", Enabled = true, SecretRef = "OpenAI:ApiKey", + Models = [new ModelConfig { ModelId = "gpt-4o-mini", Price = new PriceConfig { InputPer1M = 0m, OutputPer1M = 0m, Basis = "zero-marginal-local" } }], + }; + var c = V2.Hybrid() with + { + Connections = [V2.Ollama(), V2.OpenAi(), relabelled], + Policies = [.. V2.Hybrid().Policies.Where(p => p.Id != "sensitive"), + V2.Policy("sensitive", [DataClassification.Pii, DataClassification.Phi], [V2.T("sneaky", "gpt-4o-mini")])], + }; + var errors = Validate(c).Errors; + var e = Assert.Single(errors, x => x.Code == "boundary_not_approved"); + Assert.Equal("connections[2].boundary", e.Path); + Assert.DoesNotContain(errors, x => x.Code == "endpoint_not_allow_listed"); // the host IS allow-listed — only the label is refused + + // The same endpoint labelled Cloud is fine (and then a PII/PHI policy cannot use it). + var honest = c with { Connections = [V2.Ollama(), V2.OpenAi(), relabelled with { Boundary = Boundary.Cloud }] }; + Assert.DoesNotContain(Validate(honest).Errors, x => x.Code == "boundary_not_approved"); + Assert.Contains(Validate(honest).Errors, x => x.Code == "sensitive_cloud_target"); + + // Cloud SDK kinds are always Cloud. + var openAiLocal = V2.Hybrid() with { Connections = [V2.Ollama(), V2.OpenAi() with { Boundary = Boundary.Local }] }; + Assert.Contains(Validate(openAiLocal).Errors, x => x.Code == "boundary_not_approved" && x.Path == "connections[1].boundary"); - var unknown = V2.Hybrid() with { Connections = [V2.OpenAi()] }; // ollama removed - Assert.Equal(PolicyEffect.Deny, Eval(unknown, DataClassification.Internal).Effect); - Assert.Contains(Validate(unknown).Errors, e => e.Code == "unknown_connection"); - Assert.Contains(Validate(unknown, legacy: true).Warnings, w => w.Code == "unknown_connection"); - Assert.DoesNotContain(Validate(unknown, legacy: true).Errors, e => e.Code == "unknown_connection"); + // An approved local endpoint passes; the same Ollama on an unapproved host does not. + Assert.DoesNotContain(Validate(V2.Hybrid()).Errors, x => x.Code == "boundary_not_approved"); + var otherHost = V2.Hybrid() with { Connections = [V2.Ollama() with { Endpoint = "http://10.1.2.3:11434/v1" }, V2.OpenAi()] }; + Assert.Contains(ConfigValidator.Validate(otherHost, V2.Env(true, "10.1.2.3:11434")).Errors, x => x.Code == "boundary_not_approved"); } [Fact] diff --git a/tests/Covenant.Tests/ProviderClientConstructionTests.cs b/tests/Covenant.Tests/ProviderClientConstructionTests.cs new file mode 100644 index 0000000..03cfe96 --- /dev/null +++ b/tests/Covenant.Tests/ProviderClientConstructionTests.cs @@ -0,0 +1,134 @@ +using System.Diagnostics; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Microsoft.Extensions.Configuration; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// Review fix 11 (ADR-0011 "Provider clients"): SDK clients are built with automatic redirects OFF, +/// SDK-internal retries OFF and the connection's timeout as the network timeout — exercised against real loopback +/// sockets through the real OpenAI and Anthropic SDK clients. And a client that cannot be built for an enabled, +/// referenced connection is a validation error (client_unbuildable), never a silently skipped target. +public sealed class ProviderClientConstructionTests +{ + private static IConfiguration Secrets() => new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["Anthropic:ApiKey"] = "ak-test-not-real", + ["OpenAI:ApiKey"] = "sk-test-not-real", + }).Build(); + + private static ConnectionConfig Compat(string endpoint, int timeoutSeconds = 30) => new() + { + Id = "compat", DisplayName = "loopback", Kind = ProviderKind.OpenAiCompatible, Boundary = Boundary.Local, + Endpoint = endpoint, Enabled = true, TimeoutSeconds = timeoutSeconds, + Models = [new ModelConfig { ModelId = "m1", Price = new PriceConfig { InputPer1M = 0, OutputPer1M = 0, Basis = "zero-marginal-local" } }], + }; + + private static ConnectionConfig Claude(string baseUrl, int timeoutSeconds = 30) => new() + { + Id = "claude", DisplayName = "loopback anthropic", Kind = ProviderKind.Anthropic, Boundary = Boundary.Cloud, + Endpoint = baseUrl, Enabled = true, SecretRef = "Anthropic:ApiKey", TimeoutSeconds = timeoutSeconds, + Models = [new ModelConfig { ModelId = "claude-test", Price = new PriceConfig { InputPer1M = 1, OutputPer1M = 1, Basis = "x" } }], + }; + + private static CovenantConfig With(params ConnectionConfig[] connections) => V2.Hybrid() with + { + Connections = connections, + Policies = [V2.Policy("all", [DataClassification.Public, DataClassification.Internal], + connections.Select(c => V2.T(c.Id, c.Models[0].ModelId)).ToArray())], + }; + + private static MEAI.IChatClient Build(ConnectionConfig conn, params string[] egress) + { + var set = new SdkProviderClientFactory(Secrets(), new HashSet(egress, StringComparer.OrdinalIgnoreCase)).Build(With(conn)); + Assert.Empty(set.Skipped); + Assert.True(set.TryResolve(conn.Id, conn.Models[0].ModelId, out var client)); + return client; + } + + private static Task Call(MEAI.IChatClient client) + => client.GetResponseAsync([new MEAI.ChatMessage(MEAI.ChatRole.User, "hi")]); + + [Fact] + public void Handler_never_follows_redirects() + { + using var handler = SdkProviderClientFactory.CreateHandler(Compat("http://127.0.0.1:1/v1")); + Assert.False(handler.AllowAutoRedirect); + using var http = SdkProviderClientFactory.CreateHttpClient(Compat("http://127.0.0.1:1/v1")); + Assert.Equal(Timeout.InfiniteTimeSpan, http.Timeout); // the SDK option (connection timeout) governs + } + + [Fact] + public async Task OpenAi_compatible_client_does_not_retry_a_503_internally() + { + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(503, """{"error":{"message":"busy"}}""")); + var client = Build(Compat(server.V1), server.Authority); + await Assert.ThrowsAnyAsync(() => Call(client)); + await Task.Delay(300); // a default SDK retry would arrive well within this + Assert.Single(server.Requests); // exactly one attempt: retries are Covenant's own + } + + [Fact] + public async Task OpenAi_compatible_client_does_not_follow_a_redirect_off_the_approved_endpoint() + { + using var elsewhere = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(200, """{"id":"x","choices":[]}""")); + using var server = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(302, "", + extraHeaders: $"Location: http://127.0.0.1:{elsewhere.Port}/v1/chat/completions\r\n")); + var client = Build(Compat(server.V1), server.Authority); + await Assert.ThrowsAnyAsync(() => Call(client)); + Assert.Single(server.Requests); + Assert.Equal(0, elsewhere.Connections); // the redirect target was never contacted + } + + [Fact] + public async Task OpenAi_compatible_client_enforces_the_connection_timeout() + { + using var server = new LoopbackHttpServer(_ => null); // accepts, never answers + var client = Build(Compat(server.V1, timeoutSeconds: 1), server.Authority); + var sw = Stopwatch.StartNew(); + await Assert.ThrowsAnyAsync(() => Call(client)); + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(15), $"took {sw.Elapsed}"); + Assert.Single(server.Requests); // and no retry after the timeout + } + + [Fact] + public async Task Anthropic_client_does_not_retry_and_does_not_follow_redirects() + { + using var busy = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(503, """{"type":"error","error":{"type":"overloaded_error","message":"busy"}}""")); + var c1 = Build(Claude($"http://127.0.0.1:{busy.Port}"), busy.Authority); + await Assert.ThrowsAnyAsync(() => Call(c1)); + await Task.Delay(300); + Assert.Single(busy.Requests); + + using var elsewhere = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(200, "{}")); + using var redirecting = new LoopbackHttpServer(_ => LoopbackHttpServer.Http(307, "", + extraHeaders: $"Location: http://127.0.0.1:{elsewhere.Port}/v1/messages\r\n")); + var c2 = Build(Claude($"http://127.0.0.1:{redirecting.Port}"), redirecting.Authority); + await Assert.ThrowsAnyAsync(() => Call(c2)); + Assert.Single(redirecting.Requests); + Assert.Equal(0, elsewhere.Connections); + } + + /// An enabled connection referenced by an enabled policy that gets no client (here: its endpoint is not + /// on the execution-time egress list) makes the candidate invalid — client_unbuildable — instead of being skipped. + [Fact] + public void Unbuildable_referenced_connection_is_a_validation_error_not_a_silent_skip() + { + var conn = Compat("http://127.0.0.1:11434/v1"); + var cfg = With(conn, V2.Ollama(id: "spare") with { Enabled = false }); + var set = new SdkProviderClientFactory(Secrets(), new HashSet(StringComparer.OrdinalIgnoreCase)).Build(cfg); + Assert.Contains(set.Skipped, s => s.ConnectionId == "compat"); + var issue = Assert.Single(ProviderClientSet.UnbuildableIssues(cfg, set)); + Assert.Equal("client_unbuildable", issue.Code); + Assert.Equal("connections[0]", issue.Path); + + // Disabled or unreferenced connections are not errors; a fully built set has none. + var ok = new SdkProviderClientFactory(Secrets(), new HashSet(StringComparer.OrdinalIgnoreCase) { "127.0.0.1:11434" }).Build(cfg); + Assert.Empty(ProviderClientSet.UnbuildableIssues(cfg, ok)); + ok.Dispose(); + set.Dispose(); + } +} diff --git a/tests/Covenant.Tests/ProviderProbeTests.cs b/tests/Covenant.Tests/ProviderProbeTests.cs index e78c13c..d107727 100644 --- a/tests/Covenant.Tests/ProviderProbeTests.cs +++ b/tests/Covenant.Tests/ProviderProbeTests.cs @@ -292,7 +292,7 @@ public async Task Applied_endpoint_probe_success_then_failure_updates_catalog_he b.UseSetting("Admin:Token", CorrelationTestKit.AdminToken); b.UseSetting("Budget:GlobalCapUsd", "10"); b.UseSetting("Auth:AllowAnonymous", "true"); - b.UseSetting("Audit:Path", audit); + CorrelationTestKit.IsolatePaths(b, audit); b.UseSetting("Local:Endpoint", server.V1); b.UseSetting("Local:ModelId", "qwen3:8b"); }); diff --git a/tests/Covenant.Tests/ServedPathTests.cs b/tests/Covenant.Tests/ServedPathTests.cs index 41336ca..1030270 100644 --- a/tests/Covenant.Tests/ServedPathTests.cs +++ b/tests/Covenant.Tests/ServedPathTests.cs @@ -31,7 +31,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("Auth:Keys:0:Key", "k"); builder.UseSetting("Auth:Keys:0:Principal", "p"); builder.UseSetting("Auth:Keys:0:Team", "t"); - builder.UseSetting("Audit:Path", AuditPath); + CorrelationTestKit.IsolatePaths(builder, AuditPath); // Replace the provider registry with in-memory stubs for the policy's OpenAI routes. // ConfigureTestServices runs AFTER the app's registrations, so this override wins; the @@ -51,8 +51,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) protected override void Dispose(bool disposing) { base.Dispose(disposing); - foreach (var f in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(AuditPath) + "*")) - File.Delete(f); + CorrelationTestKit.DeleteWithSiblings(AuditPath); } } diff --git a/tests/Covenant.Tests/WireShapeTests.cs b/tests/Covenant.Tests/WireShapeTests.cs index 2531f42..a4b2015 100644 --- a/tests/Covenant.Tests/WireShapeTests.cs +++ b/tests/Covenant.Tests/WireShapeTests.cs @@ -205,14 +205,14 @@ public Ingress(WebApplicationFactory factory) b.UseSetting("Auth:Keys:0:Key", "k"); b.UseSetting("Auth:Keys:0:Principal", "shape-tester"); b.UseSetting("Auth:Keys:0:Team", "t"); - b.UseSetting("Audit:Path", _auditPath); + CorrelationTestKit.IsolatePaths(b, _auditPath); }); _client = _factory.CreateClient(); _client.DefaultRequestHeaders.Add("x-api-key", "k"); _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "k"); } - public void Dispose() { _factory.Dispose(); if (File.Exists(_auditPath)) File.Delete(_auditPath); } + public void Dispose() { _factory.Dispose(); CorrelationTestKit.DeleteWithSiblings(_auditPath); } private static StringContent Body(string json) => new(json, Encoding.UTF8, "application/json"); From a16bed83fa1ae85a4b7a4dfd0dd9872f63d0d916 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Sat, 17 Oct 2026 01:03:55 -0400 Subject: [PATCH 07/14] feat(budget,trace,fallback): ledger reservations, console inference + live trace, approved fallback, cache isolation, archive/export (T04/T05/T06 checkpoint) --- docs/ui-api-contract.md | 94 +++++ src/Covenant.Adapters/ProviderLayer.cs | 303 +++++++++++--- src/Covenant.Core/Decisions.cs | 34 +- src/Covenant.Core/Execution.cs | 138 +++++++ src/Covenant.Core/InferenceContext.cs | 89 +++- src/Covenant.Core/Pipeline.cs | 78 +++- src/Covenant.Governance/Attribution.cs | 10 +- src/Covenant.Governance/Audit.cs | 11 +- src/Covenant.Governance/Budget.cs | 95 ++++- src/Covenant.Governance/BudgetGate.cs | 179 ++++++++ src/Covenant.Governance/BudgetLedger.cs | 388 ++++++++++++++++++ src/Covenant.Governance/Cache.cs | 11 +- src/Covenant.Host/AuditSegments.cs | 279 +++++++++++++ src/Covenant.Host/BudgetLedgerStore.cs | 275 +++++++++++++ src/Covenant.Host/ConsoleBackend.cs | 5 + src/Covenant.Host/Evidence.cs | 5 +- src/Covenant.Host/FailureClassifier.cs | 32 ++ src/Covenant.Host/FileAuditSink.cs | 2 + src/Covenant.Host/InferenceEndpoints.cs | 301 ++++++++++++++ src/Covenant.Host/OpenAiContracts.cs | 4 + src/Covenant.Host/Program.cs | 217 ++++------ src/Covenant.Host/StatusContracts.cs | 42 ++ src/Covenant.Host/Trace.cs | 283 +++++++++++++ tests/Covenant.Tests/ArchiveExportTests.cs | 179 ++++++++ tests/Covenant.Tests/BudgetHostTests.cs | 190 +++++++++ tests/Covenant.Tests/BudgetLedgerTests.cs | 355 ++++++++++++++++ tests/Covenant.Tests/CacheIsolationTests.cs | 143 +++++++ .../Covenant.Tests/ConsolePlaygroundTests.cs | 203 +++++++++ tests/Covenant.Tests/FallbackTests.cs | 314 ++++++++++++++ tests/Covenant.Tests/RuntimeV2TestKit.cs | 252 ++++++++++++ tests/Covenant.Tests/TraceTests.cs | 240 +++++++++++ 31 files changed, 4526 insertions(+), 225 deletions(-) create mode 100644 src/Covenant.Core/Execution.cs create mode 100644 src/Covenant.Governance/BudgetGate.cs create mode 100644 src/Covenant.Governance/BudgetLedger.cs create mode 100644 src/Covenant.Host/AuditSegments.cs create mode 100644 src/Covenant.Host/BudgetLedgerStore.cs create mode 100644 src/Covenant.Host/FailureClassifier.cs create mode 100644 src/Covenant.Host/InferenceEndpoints.cs create mode 100644 src/Covenant.Host/Trace.cs create mode 100644 tests/Covenant.Tests/ArchiveExportTests.cs create mode 100644 tests/Covenant.Tests/BudgetHostTests.cs create mode 100644 tests/Covenant.Tests/BudgetLedgerTests.cs create mode 100644 tests/Covenant.Tests/CacheIsolationTests.cs create mode 100644 tests/Covenant.Tests/ConsolePlaygroundTests.cs create mode 100644 tests/Covenant.Tests/FallbackTests.cs create mode 100644 tests/Covenant.Tests/RuntimeV2TestKit.cs create mode 100644 tests/Covenant.Tests/TraceTests.cs diff --git a/docs/ui-api-contract.md b/docs/ui-api-contract.md index b364065..b2f8c60 100644 --- a/docs/ui-api-contract.md +++ b/docs/ui-api-contract.md @@ -129,6 +129,20 @@ Governed refusals (application disabled / not console-testable / profile not gra `GET /admin/applications` → `[{ "id","team","enabled","console_testing","granted_profiles","default_profile" }]` (no credentials). +Implementation details (T05, binding): +- Admin token required (401 `{error:"unauthorized"}` otherwise). Every answer — including 400 — carries + `X-Covenant-Request-Id`; for 400 the id names nothing (no audit record, no trace). On 409 the header and `request_id` + are the ORIGINAL request's id (the duplicate is not run; window 10 min, claimed atomically before the pipeline runs). +- 400 rules: malformed JSON; `application_id` missing/blank or > 64 chars; `profile_id` > 64; `messages` missing/empty + or > 200; a null message; `role` not `system|user|assistant`; `content` not a string; total content > 200 000 chars; + `max_tokens` < 1; `model` > 200 chars; `client_request_id` not 1–128 chars of `[A-Za-z0-9-_.:]`. Body: + `{ "error":"invalid_request", "reason":"… — rejected before governance; no evidence record" }`. +- An unknown `application_id` is a governed 403 at `auth` ("application 'x' is not configured"), audited. +- Audit: `EntryPoint="console"`, `OperatorRef="shared-admin-token"`, `ApplicationId`, `Tags.Team` = the application's + team, `Principal="console:"`, `Tags.Workflow`/`UseCase` from the body (default `console`/`playground`, + bounded to 64 chars). +- Cancellation (client disconnect) propagates to the provider call (`RequestAborted`); the record is `Cancelled`. + ## Trace (ADR-0013) `GET /admin/requests/{id}/trace` → `{ "request_id","config_version","complete":bool,"events":[TraceEvent] }`; 404 unknown/expired. `GET /admin/requests/{id}/trace/stream` → SSE `id: ` + `data: TraceEvent`, replay then @@ -136,6 +150,27 @@ live, honours `Last-Event-ID`; ends with `event: end`. `TraceEvent` = `{ "seq"," "ts_utc","duration_ms"?,"reason_code"?,"target"? }`. Stages: `auth, shape, classify, policy, cache, rate_limit, pause, budget, provider, attribution`. States: `pending, running, passed, refused, failed, cancelled, skipped`. +Implementation details (T05, binding — supersedes "404 unknown/expired" above): +- Both endpoints: admin token (401); id must be ≤ 64 chars of `[A-Za-z0-9_-]` (400 `invalid_id`); **404** + `{error:"not_found"}` = never traced by this process; **410** `{error:"expired"}` = traced but past retention (or evicted). +- Every request is traced — `/v1/chat/completions`, `/v1/messages` and console inference — in a buffer created BEFORE the + pipeline starts; `seq` is monotonic from 1. Each event also carries `request_id` and `config_version`. Null fields are + omitted. Snapshot adds `"truncated":bool` (more than 64 events were emitted; later ones dropped). +- Stage events: `running` on entry; `passed` (with `duration_ms`, Stopwatch-measured) when the stage hands over to the next + one — or returns without denying (a cache hit: `reason_code:"cache_hit"`); `refused` / `failed` (upstream) / `cancelled` + on a short-circuit with a bounded `reason_code`; after the run, every stage never entered is `skipped` with + `not_reached` or `cache_hit`. Provider attempts emit `provider` events with `attempt_id` (`att_1`, `att_2`, …) and + `target` (`connection/model`); a fallback's pause and budget re-checks emit `pause`/`budget` events with its `attempt_id`. + The audit stage itself is not traced. +- `reason_code` vocabulary (bounded, never provider text or content): `cache_hit`, `not_reached`, `paused`, + `budget_exceeded`, `governance_denied`, `unauthenticated`, `rate_limited`, `unsupported`, `upstream_failure`, + `client_cancelled`, `client_disconnected`, `no_client`, `error`, and the failure classes `connect`, `timeout`, `429`, + `5xx`, `non_retryable`. +- Stream: replay of `seq > Last-Event-ID`, then live; `: keep-alive` comment every 15 s while idle; `event: end` + + `data: {}` once complete. Clients de-duplicate by `seq`. +- Bounds: ≤ 64 events/request, ≤ 2 000 requests (oldest completed evicted first), retention = the request's configuration + `trace_retention_minutes` (default 10) after completion. In memory only; the audit record keeps the compact summary. + ## Policy simulator `POST /admin/policies/simulate` `{ "application_id","profile_id"?,"prompt","model"?,"config"? }` → dry-run `{ "classification","baseline","detected_signal","policy_id","eligible":[{target, "excluded_reason"?}], @@ -147,6 +182,25 @@ never records spend or audit. Labelled "Dry run" in the UI. "warn_at","warning":"none|warn|critical|exceeded","enforcement" }]`; caps are edited through `/admin/config`. `GET /admin/budgets/{id}/requests?limit=` → contributing settled request ids and amounts. +Implementation details (T04, binding): +- `period` = `none|daily|monthly`; `period_id` = `all` / `yyyy-MM-dd` / `yyyy-MM` (UTC); additive `period_start_utc`, + `period_end_utc` (null for `none`). `spent_usd` = settled charges of the budget's SCOPE inside its current window (the + ledger records scopes, never budget ids — renaming a budget or changing its period/cap never resets accrual). + `reserved_usd` = open reservations of that scope (in-flight attempts). `remaining_usd = max(0, cap − spent − reserved)`. + `enforcement` = `hard|warn-only`. +- `warning`: `exceeded` when spent ≥ cap (cap 0: only when something was spent); `critical` at ≥ the highest `warn_at` + fraction; `warn` at ≥ the lowest; else `none`. Status only — warnings never block; warn-only budgets never block. +- `/admin/budgets/{id}/requests?limit=` (default 100, max 1000) → `{ "budget_id","scope","period_id","items":[{ "request_id", + "attempt_id","kind":"settle|settle-recovered|legacy-import","amount_usd","ts_utc","overrun" }] }` newest first; + 404 for an id not in the active configuration. +- Ledger: `Budget:LedgerPath` (startup-only; default `.ledger.jsonl`). `POST /admin/reset` archives the audit + log only — it never reopens a budget. `/admin/status.budget` reads the same ledger (global budget's period; team spend + over that period). +- A hard-budget refusal is a governed 403 at stage `budget` (reason names the budget, scope, period, spent, reserved, the + attempt's bound and the cap). Reservation bound per attempt = (UTF-8 bytes of all message contents + 16 per message) × + input price + min(request `max_tokens`, application `max_output_tokens` (default 1024), model `max_output_tokens`) × + output price; that output bound is sent to the provider. Explicit $0 (local) prices reserve nothing. + ## Requests archive (spec §5) `GET /admin/requests?limit=&cursor=&segment=` — `cursor` is an opaque newest-first position; `segment` is an id from `GET /admin/audit/segments` (`[{ "id","label","entries","first_utc","last_utc","chain_valid" }]`, the current @@ -154,9 +208,49 @@ segment plus `*.archived` siblings of the audit file — ids only, never caller- `GET /admin/requests/{id}/export` → `{ request record, attempts, trace summary, config_version, integrity }` with no prompt/response content. +Implementation details (T06, binding): +- Segment ids: `current`, or `a-<16 hex>` (SHA-256 of the archive's file name) for `.yyyyMMdd-HHmmss.archived` + siblings, newest first. Segment view adds `current`:bool, `events` (control-plane events, not counted in `entries`), + `archived_utc`. No paths. Archived chains are verified with their archived anchor file when one exists. +- `GET /admin/requests`: `segment` default `current`; an id outside the enumerated set (path, `..`, unknown) → **400** + `{error:"unknown_segment"}`. `limit` 1–1000 (default 200). Response = the existing `RequestsPage` plus + `segment.id`, `segment.label` and `next_cursor` (null on the last page). A cursor encodes its segment; `cursor` alone is + enough for the next page; a malformed cursor or one for another segment → **400** `{error:"invalid_cursor"}`. +- `GET /admin/requests/{id}/export?segment=` (default: search current, then archived newest first) → `{ "exported_utc", + "request_id", "segment": SegmentView, "config_version", "record": AuditEntry (PascalCase, `PromptPreview` removed), + "attempts", "trace", "integrity": { "segment_id","chain_valid","chain_failure","line","previous_hash","entry_hash", + "anchor_configured","status":"verified|unverified" }, "content_included": false }`; 404 not found; 400 bad id/segment. + The prompt SHA-256 fingerprint stays (it proves which prompt, not what). + ## Audit record v3 (additive) `EventType` (null/"request" | "config.activated" | "budget.recovered"), `ConfigVersion`, `EntryPoint` ("v1" | "console"), `OperatorRef`, `ApplicationId`, `ProfileId`, `BaselineClassification`, `Attempts[]` (`{AttemptId, ConnectionId, ModelId, Outcome, ErrorClass, DurationMs, CostUsd, CostBasis}`), `Trace[]` (`{Stage, State, DurationMs}`), `ReservedUsd`, `SettledUsd`. Legacy lines verify unchanged; absent = Not recorded. Event entries (`EventType` ≠ request) are excluded from request counts, spend and FinOps. + +Implementation details (T04–T06, binding): +- `Attempts[]` items also carry `ReservedUsd` and `Overrun` (bool, reported charge above the reservation — settled in + full). `Outcome` ∈ `served|failed|cancelled`; `ErrorClass` ∈ `connect|timeout|429|5xx|non_retryable|client_cancelled| + client_disconnected`. Only STARTED attempts appear (a fallback refused at pause/budget never started; see `Trace`). +- `Trace[]` items: `{Stage, State, DurationMs, AttemptId?, ReasonCode?}` — terminal states only; one `provider` step per + attempt; attempt-level `pause`/`budget` steps only when they refused; skipped stages included. +- `Attempts`, `Trace`, `ReservedUsd`, `SettledUsd` are written only when a configuration version is bound (always on the + Host); `[]`/null on a cache hit or a refusal before any attempt. +- `Usage.CostUsd` of a record = **everything settled for the request** (`SettledUsd`: a failed attempt's estimate plus the + served fallback's charge), so FinOps totals include possibly-billed failed attempts. `Usage` tokens are the served + attempt's. +- `SelectedModel` = the policy's primary; `AttemptedModel` = the last attempt started; `ServedByModel` = the attempt that + produced the response (a fallback when one served). `CostBasis` (v2 meaning): `estimated_from_text` = served, usage not + reported, charged the reservation bound; `estimated_failed_call` = failed/cancelled attempt charged its reservation + bound; `no_call`, `reported`, `zero_priced`, `unpriced`, `unknown_failed_call` unchanged. +- `budget.recovered` events record reservations a crash left open, settled at boot at their reserved amount. + +## Status FinOps savings (T06) +`/admin/status.finops.savings` = `{ "label":"Estimated provider charge avoided", "baseline":"connection/model", +"route_avoided_usd","cache_avoided_usd","total_usd","excluded_records" }` **only** when the active configuration's +`savings_baseline` names a PRICED connection/model; otherwise `null` and the legacy `estimated_savings_usd`, +`savings_local_usd`, `savings_router_usd`, `savings_cache_usd` are 0. Counterfactual: each allowed request with known usage +(`reported`/`zero_priced`/cache `no_call`) priced on the baseline; route-avoided = baseline − served model price (route +selection, incl. local); cache-avoided = the served model's charge a hit did not incur. Estimated/unknown-cost records are +excluded (`excluded_records`). Not total business savings; not evidence of equal answer quality. diff --git a/src/Covenant.Adapters/ProviderLayer.cs b/src/Covenant.Adapters/ProviderLayer.cs index e081912..64435b1 100644 --- a/src/Covenant.Adapters/ProviderLayer.cs +++ b/src/Covenant.Adapters/ProviderLayer.cs @@ -27,13 +27,93 @@ public interface IProviderHealth void RecordFailure(string adapterKey, string modelId, string error); } +/// Classifies a provider exception into the bounded failure vocabulary of ADR-0013 (the policy's +/// retry.on set): connect, timeout, 429, 5xx (500/502/503/504) or non_retryable. +/// The Host supplies an SDK-aware implementation (it knows the OpenAI/Anthropic exception types); this layer only +/// knows BCL types. Caller cancellation never reaches a classifier — it is not a provider failure. +public interface IProviderFailureClassifier +{ + string Classify(Exception exception); +} + +/// BCL-only classification: HttpRequestException with a status code (429 / 500,502,503,504 / other ⇒ +/// non-retryable), without one ⇒ connect; SocketException ⇒ connect; TimeoutException / provider-side +/// OperationCanceledException ⇒ timeout; anything else ⇒ non-retryable. Inner exceptions are inspected. +public class BclProviderFailureClassifier : IProviderFailureClassifier +{ + public static readonly BclProviderFailureClassifier Instance = new(); + + public static string FromStatus(int status) => status switch + { + 429 => TraceReasons.RateLimited429, + 500 or 502 or 503 or 504 => TraceReasons.ServerError5xx, + _ => TraceReasons.NonRetryable, + }; + + public virtual string Classify(Exception exception) + { + for (Exception? e = exception; e is not null; e = e.InnerException) + { + if (ClassifyOne(e) is { } c) return c; + } + return TraceReasons.NonRetryable; + } + + /// Null = "not recognised here, look at the inner exception". + protected virtual string? ClassifyOne(Exception e) => e switch + { + HttpRequestException { StatusCode: { } status } => FromStatus((int)status), + HttpRequestException => TraceReasons.Connect, + System.Net.Sockets.SocketException => TraceReasons.Connect, + TimeoutException => TraceReasons.Timeout, + OperationCanceledException => TraceReasons.Timeout, // provider-side (caller cancellation is handled before) + _ => null, + }; +} + /// The one place provider concepts exist (ADR-0001): canonical ↔ Microsoft.Extensions.AI -/// mapping around the resolved IChatClient. No governance here; no provider concept escapes. +/// mapping around the resolved IChatClient. No governance decisions here; no provider concept escapes. +/// ADR-0013 bounded fallback: with a bound configuration the stage iterates the policy's ordered eligible +/// candidates (). Before EACH attempt the request's +/// (installed by the budget stage) re-checks the global pause and reserves budget; a refusal stops at stage +/// pause/budget. A failed attempt falls back to the next candidate only when its failure class is in the policy's +/// retry.on, within maxAttempts and deadlineMs, and NEVER after any content reached the client; +/// never on caller cancellation (rethrown) or non-retryable errors. Every started attempt is recorded +/// () and settled exactly once; health is recorded per connection:model. +/// Deadline semantics: no attempt starts after deadlineMs; an attempt still waiting for its response (or, +/// streaming, its first content) at the deadline is cancelled and classified timeout. Once streamed content is +/// flowing the deadline no longer applies (the connection timeout does) — a delivered answer is never cut off by the +/// fallback budget. /// ADR-0011: resolve against the provider clients compiled into the request's /// bound configuration snapshot (so a request keeps the clients of the version it started on). The Host sets it /// only when its own snapshot-backed registry is the DI registration; a test-substituted registry always wins. -public sealed class ProviderCallStage(IChatClientRegistry registry, IProviderHealth? health = null, bool preferRequestClients = false) : IPipelineStage +public sealed class ProviderCallStage( + IChatClientRegistry registry, + IProviderHealth? health = null, + bool preferRequestClients = false, + IProviderFailureClassifier? classifier = null) : IPipelineStage { + private const string Stage = "provider"; + private readonly IProviderFailureClassifier _classifier = classifier ?? BclProviderFailureClassifier.Instance; + + private enum AttemptEnd { Served, Failed, ClientGone } + + private sealed record Plan(IReadOnlyList Candidates, int MaxAttempts, int? DeadlineMs, HashSet RetryOn); + + private static HashSet NoRetry() => new(StringComparer.OrdinalIgnoreCase); + + /// Legacy compositions (no configuration, or no policy v2 candidates) make exactly one attempt on Route. + private static Plan PlanFor(InferenceContext ctx, RouteTarget route) + { + var outcome = ctx.Policy!; + if (ctx.Configuration is not { } cfg || outcome.Candidates.Count == 0) + return new Plan([route], 1, null, NoRetry()); + var retry = outcome.PolicyId is { } pid ? cfg.Config.Policies.FirstOrDefault(p => p.Id == pid)?.Retry : null; + if (retry is null) return new Plan([outcome.Candidates[0]], 1, null, NoRetry()); + return new Plan(outcome.Candidates, Math.Clamp(retry.MaxAttempts, 1, 3), retry.DeadlineMs > 0 ? (int?)retry.DeadlineMs : null, + new HashSet(retry.On, StringComparer.OrdinalIgnoreCase)); + } + public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, CancellationToken ct) { var route = ctx.Policy?.Route; @@ -42,31 +122,101 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance var effective = preferRequestClients && ctx.Configuration?.GetResource() is { } snapshotClients ? snapshotClients : registry; - if (!effective.TryResolve(route.AdapterKey, route.ModelId, out var client)) + var plan = PlanFor(ctx, route); + var messages = ctx.Request.Messages.Select(ToMeai).ToList(); + + using var deadline = plan.DeadlineMs is not null ? CancellationTokenSource.CreateLinkedTokenSource(ct) : null; + if (deadline is not null) deadline.CancelAfter(plan.DeadlineMs!.Value); + var elapsed = System.Diagnostics.Stopwatch.StartNew(); + + for (int i = 0; ; i++) { - ctx.Deny($"no adapter registered for '{route.AdapterKey}:{route.ModelId}'"); // fail-closed - return; + var target = plan.Candidates[i]; + var attemptId = "att_" + (i + 1).ToString(System.Globalization.CultureInfo.InvariantCulture); + + if (ctx.AttemptGate is { } gate) + { + var admission = gate.Admit(ctx, target, attemptId); + if (!admission.Admitted) + { + ctx.Deny(admission.Reason ?? "attempt refused", DenialKind.Governance, admission.Stage, admission.Code); + return; + } + } + + if (!effective.TryResolve(target.AdapterKey, target.ModelId, out var client)) + { + ctx.AttemptGate?.Release(ctx, attemptId); + ctx.Deny($"no adapter registered for '{target.AdapterKey}:{target.ModelId}'", code: TraceReasons.NoClient); // fail-closed + return; + } + + var attempt = new AttemptRecord + { + AttemptId = attemptId, + ConnectionId = target.AdapterKey, + ModelId = target.ModelId, + ReservedUsd = ctx.AttemptGate is null ? null : ctx.ActiveReservationUsd, + }; + ctx.Attempts.Add(attempt); + var (end, errorClass, message) = await AttemptAsync(ctx, client, target, attempt, messages, deadline, ct); + + if (end == AttemptEnd.Served) + { + await next(ctx, ct); + SettleServed(ctx, attempt); + return; + } + if (end == AttemptEnd.ClientGone) + { + // Writing to the CLIENT failed (it disconnected): an incomplete request, not a provider failure. + ctx.Deny("client disconnected during streaming", DenialKind.Cancelled, code: TraceReasons.ClientDisconnected); + return; + } + + bool emitted = ctx.PartialOutputChars > 0; + bool moreCandidates = i + 1 < plan.Candidates.Count && i + 1 < plan.MaxAttempts; + bool withinDeadline = plan.DeadlineMs is not { } ms || (elapsed.ElapsedMilliseconds < ms && !(deadline?.IsCancellationRequested ?? false)); + bool retryable = errorClass is not null && plan.RetryOn.Contains(errorClass); + if (emitted || !moreCandidates || !withinDeadline || !retryable) + { + // Terminal failure: content already emitted (never continued by a second provider), no approved + // fallback left, deadline spent, or a failure class the policy does not retry. + ctx.Deny(message, DenialKind.UpstreamFailure, code: errorClass); + return; + } + ctx.PartialOutputChars = 0; // nothing was emitted; the next attempt starts clean } + } - var messages = ctx.Request.Messages.Select(ToMeai).ToList(); - ctx.AttemptedModel = route.ModelId; // a call is now actually started (not merely selected) - var options = new MEAI.ChatOptions { ModelId = route.ModelId, MaxOutputTokens = ctx.Request.MaxOutputTokens }; + /// One provider attempt. Caller cancellation is rethrown after the attempt is recorded and settled. + private async Task<(AttemptEnd End, string? ErrorClass, string Message)> AttemptAsync( + InferenceContext ctx, MEAI.IChatClient client, RouteTarget target, AttemptRecord attempt, + List messages, CancellationTokenSource? deadline, CancellationToken ct) + { + var targetLabel = $"{target.AdapterKey}/{target.ModelId}"; + var callToken = deadline?.Token ?? ct; + ctx.AttemptedModel = target.ModelId; // a call is now actually started (not merely selected) + ctx.Trace(Stage, TraceStates.Running, attemptId: attempt.AttemptId, target: targetLabel); + var watch = System.Diagnostics.Stopwatch.StartNew(); + var options = new MEAI.ChatOptions { ModelId = target.ModelId, MaxOutputTokens = RequestBounds.OutputTokenBound(ctx, target) }; - // ADR-0002: streaming is an emission mode, not a different pipeline. The stream is consumed - // HERE so attribution, budget, and audit run on the normal unwind with real usage. - if (ctx.Request.Stream && ctx.DeltaSink is { } sink) + try { - var text = new StringBuilder(); - MEAI.UsageDetails? usageDetails = null; - try + // ADR-0002: streaming is an emission mode, not a different pipeline. The stream is consumed + // HERE so attribution, budget, and audit run on the normal unwind with real usage. + if (ctx.Request.Stream && ctx.DeltaSink is { } sink) { - await foreach (var update in client.GetStreamingResponseAsync(messages, options, ct)) + var text = new StringBuilder(); + MEAI.UsageDetails? usageDetails = null; + await foreach (var update in client.GetStreamingResponseAsync(messages, options, callToken)) { foreach (var uc in update.Contents.OfType()) usageDetails = uc.Details; if (update.Text is { Length: > 0 } fragment) { + if (text.Length == 0) deadline?.CancelAfter(Timeout.Infinite); // content flowing: deadline no longer applies text.Append(fragment); ctx.PartialOutputChars = text.Length; try @@ -75,69 +225,98 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance } catch (Exception) when (!ct.IsCancellationRequested) { - // Writing to the CLIENT failed (it disconnected): an incomplete request, not - // a provider failure — no health penalty for the provider. - ctx.Deny("client disconnected during streaming", DenialKind.Cancelled); - return; + End(ctx, attempt, watch, TraceStates.Cancelled, TraceReasons.ClientDisconnected, targetLabel); + SettleIncomplete(ctx, attempt); + return (AttemptEnd.ClientGone, TraceReasons.ClientDisconnected, "client disconnected during streaming"); } } } + + health?.RecordSuccess(target.AdapterKey, target.ModelId); + ctx.ServedTarget = target; + ctx.Response = new InferenceResponse( + Message: new ChatMessage(ChatRole.Assistant, text.ToString()), + Usage: new Usage(usageDetails?.InputTokenCount ?? 0, usageDetails?.OutputTokenCount ?? 0, 0m), + ServedByModel: target.ModelId, + UsageReported: usageDetails?.InputTokenCount is not null && usageDetails.OutputTokenCount is not null); } - catch (OperationCanceledException) when (ct.IsCancellationRequested) - { - throw; // caller cancelled — not a provider failure (a provider-side timeout is, below) - } - catch (Exception ex) + else { - // Mid-stream failure: same governed refusal as the buffered path. The Host decides - // how to terminate the already-started SSE stream; evidence records the denial. - ctx.Deny($"provider '{route.AdapterKey}' stream failed: {Bound(ex.Message)}", DenialKind.UpstreamFailure); - health?.RecordFailure(route.AdapterKey, route.ModelId, Bound(ex.Message)); - return; + var response = await client.GetResponseAsync(messages, options, callToken); + health?.RecordSuccess(target.AdapterKey, target.ModelId); + ctx.ServedTarget = target; + ctx.Response = new InferenceResponse( + Message: new ChatMessage(ChatRole.Assistant, response.Text ?? string.Empty), + Usage: new Usage( + InputTokens: response.Usage?.InputTokenCount ?? 0, + OutputTokens: response.Usage?.OutputTokenCount ?? 0, + CostUsd: 0m), // cost is computed by the attribution stage + ServedByModel: target.ModelId, + UsageReported: response.Usage?.InputTokenCount is not null && response.Usage.OutputTokenCount is not null); } - - health?.RecordSuccess(route.AdapterKey, route.ModelId); - ctx.Response = new InferenceResponse( - Message: new ChatMessage(ChatRole.Assistant, text.ToString()), - Usage: new Usage(usageDetails?.InputTokenCount ?? 0, usageDetails?.OutputTokenCount ?? 0, 0m), - ServedByModel: route.ModelId, - UsageReported: usageDetails?.InputTokenCount is not null && usageDetails.OutputTokenCount is not null); - - await next(ctx, ct); - return; - } - - MEAI.ChatResponse response; - try - { - response = await client.GetResponseAsync(messages, options, ct); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { - throw; // caller cancelled — not a provider failure (a provider-side timeout is, below) + // Caller cancelled — not a provider failure (a provider-side timeout is, below). Possibly billed: settled. + End(ctx, attempt, watch, TraceStates.Cancelled, TraceReasons.ClientCancelled, targetLabel); + SettleIncomplete(ctx, attempt); + throw; } catch (Exception ex) { - // Adapter contract: error mapping (src/CLAUDE.md). An upstream failure is a governed, - // audited refusal — never an unhandled exception escaping the pipeline as a 500. - ctx.Deny($"provider '{route.AdapterKey}' call failed: {Bound(ex.Message)}", DenialKind.UpstreamFailure); - health?.RecordFailure(route.AdapterKey, route.ModelId, Bound(ex.Message)); - return; + // Adapter contract: error mapping (src/CLAUDE.md). An upstream failure is a governed, audited outcome — + // never an unhandled exception escaping the pipeline as a 500. The deadline firing is a timeout. + var errorClass = deadline is { IsCancellationRequested: true } && !ct.IsCancellationRequested + ? TraceReasons.Timeout + : _classifier.Classify(ex); + var verb = ctx.Request.Stream && ctx.DeltaSink is not null ? "stream failed" : "call failed"; + var message = $"provider '{target.AdapterKey}' {verb}: {Bound(ex.Message)}"; + health?.RecordFailure(target.AdapterKey, target.ModelId, Bound(ex.Message)); + End(ctx, attempt, watch, TraceStates.Failed, errorClass, targetLabel); + SettleIncomplete(ctx, attempt); + return (AttemptEnd.Failed, errorClass, message); } - health?.RecordSuccess(route.AdapterKey, route.ModelId); - var usage = new Usage( - InputTokens: response.Usage?.InputTokenCount ?? 0, - OutputTokens: response.Usage?.OutputTokenCount ?? 0, - CostUsd: 0m); // cost is computed by the attribution stage + attempt.Outcome = "served"; + attempt.DurationMs = watch.Elapsed.TotalMilliseconds; + ctx.Trace(Stage, TraceStates.Passed, attempt.DurationMs, attemptId: attempt.AttemptId, target: targetLabel); + return (AttemptEnd.Served, null, "served"); + } - ctx.Response = new InferenceResponse( - Message: new ChatMessage(ChatRole.Assistant, response.Text ?? string.Empty), - Usage: usage, - ServedByModel: route.ModelId, - UsageReported: response.Usage?.InputTokenCount is not null && response.Usage.OutputTokenCount is not null); + private static void End(InferenceContext ctx, AttemptRecord attempt, System.Diagnostics.Stopwatch watch, string state, string errorClass, string target) + { + attempt.Outcome = state == TraceStates.Cancelled ? "cancelled" : "failed"; + attempt.ErrorClass = errorClass; + attempt.DurationMs = watch.Elapsed.TotalMilliseconds; + ctx.Trace(Stage, state, attempt.DurationMs, errorClass, attempt.AttemptId, target); + } + + /// A started attempt that produced no complete response may still be billed (ADR-0009/0014): settled at the + /// conservative reservation-bound estimate — never $0. + private static void SettleIncomplete(InferenceContext ctx, AttemptRecord attempt) + { + if (ctx.AttemptGate is not { } gate) return; + var charge = gate.Settle(ctx, attempt.AttemptId, null); + attempt.CostUsd = charge.CostUsd; + attempt.CostBasis = charge.CostBasis; + attempt.Overrun = charge.Overrun; + ctx.CostBasis = charge.CostBasis; + } - await next(ctx, ct); + /// The served attempt is settled with the attributed (priced) cost after the attribution stage ran. + private static void SettleServed(InferenceContext ctx, AttemptRecord attempt) + { + decimal? cost = ctx.Attribution?.Usage.CostUsd; + attempt.CostBasis = ctx.CostBasis; + if (ctx.AttemptGate is not { } gate) + { + attempt.CostUsd = cost; + return; + } + var charge = gate.Settle(ctx, attempt.AttemptId, cost); + attempt.CostUsd = charge.CostUsd; + attempt.CostBasis ??= charge.CostBasis; + attempt.Overrun = charge.Overrun; } /// Provider error text lands in evidence: bounded, single-line. diff --git a/src/Covenant.Core/Decisions.cs b/src/Covenant.Core/Decisions.cs index 6f493e3..1676748 100644 --- a/src/Covenant.Core/Decisions.cs +++ b/src/Covenant.Core/Decisions.cs @@ -72,13 +72,45 @@ public sealed record AuditEntry( string? OperatorRef = null, string? ApplicationId = null, string? ProfileId = null, - DataClassification? BaselineClassification = null); + DataClassification? BaselineClassification = null, + // ---- v3 continued (ADR-0013/0014): provider attempts, compact trace, budget reservation/settlement. + // Null on legacy compositions (no bound configuration) and on every pre-T04 line → "Not recorded". + IReadOnlyList? Attempts = null, + IReadOnlyList? Trace = null, + decimal? ReservedUsd = null, + decimal? SettledUsd = null); + +/// One provider attempt in an audit v3 record (ADR-0013): which connection/model was called, how it ended, +/// the bounded error class, its measured duration and its charge (ADR-0014). Outcome ∈ served | failed | cancelled. +/// ErrorClass ∈ connect | timeout | 429 | 5xx | non_retryable | client_cancelled | client_disconnected (bounded codes, +/// never provider free text). Overrun = the reported charge exceeded the attempt's reservation (settled in full). +public sealed record AuditAttempt( + string AttemptId, + string ConnectionId, + string ModelId, + string Outcome, + string? ErrorClass, + double DurationMs, + decimal? CostUsd, + string? CostBasis, + decimal? ReservedUsd = null, + bool? Overrun = null); + +/// Compact persisted trace step (ADR-0013): stage, terminal state and measured duration. Provider steps are +/// per attempt (AttemptId). No content, no credentials, no provider free text — ReasonCode is a bounded code. +public sealed record AuditTraceStep( + string Stage, + string State, + double? DurationMs = null, + string? AttemptId = null, + string? ReasonCode = null); /// Not a property on AuditEntry: a computed property would be serialized into every audit line. public static class AuditEntryKinds { public const string Request = "request"; public const string ConfigActivated = "config.activated"; + public const string BudgetRecovered = "budget.recovered"; /// True for inference records (legacy lines have no EventType ⇒ request). public static bool IsRequest(this AuditEntry entry) => entry.EventType is null or Request; diff --git a/src/Covenant.Core/Execution.cs b/src/Covenant.Core/Execution.cs new file mode 100644 index 0000000..6dbb6b1 --- /dev/null +++ b/src/Covenant.Core/Execution.cs @@ -0,0 +1,138 @@ +using System.Text; + +namespace Covenant.Core; + +// Execution facts of one request (ADR-0013/0014): canonical trace events, provider attempts, the attempt gate +// (pause re-check + budget reservation before EACH attempt) and the enforced token bounds. Pure Core types — the +// Governance budget gate and the Host trace hub implement/consume them; Core depends on nothing. + +/// Canonical trace states (ADR-0013). +public static class TraceStates +{ + public const string Pending = "pending"; + public const string Running = "running"; + public const string Passed = "passed"; + public const string Refused = "refused"; + public const string Failed = "failed"; + public const string Cancelled = "cancelled"; + public const string Skipped = "skipped"; + + public static bool IsTerminal(string state) => state is not (Pending or Running); +} + +/// Bounded reason codes carried by trace events and attempt evidence. Never provider free text, never +/// content: a fixed vocabulary only. +public static class TraceReasons +{ + public const string NotReached = "not_reached"; + public const string CacheHit = "cache_hit"; + public const string Paused = "paused"; + public const string BudgetExceeded = "budget_exceeded"; + public const string ClientCancelled = "client_cancelled"; + public const string ClientDisconnected = "client_disconnected"; + public const string NoClient = "no_client"; + public const string Error = "error"; + + // Provider failure classes (IProviderFailureClassifier, ADR-0013) — also the policy retry.on vocabulary. + public const string Connect = "connect"; + public const string Timeout = "timeout"; + public const string RateLimited429 = "429"; + public const string ServerError5xx = "5xx"; + public const string NonRetryable = "non_retryable"; + + /// Default code of a denial when the denying stage did not name a finer one. + public static string ForDenial(DenialKind kind) => kind switch + { + DenialKind.Unauthenticated => "unauthenticated", + DenialKind.RateLimited => "rate_limited", + DenialKind.Unsupported => "unsupported", + DenialKind.Cancelled => ClientCancelled, + DenialKind.UpstreamFailure => "upstream_failure", + _ => "governance_denied", + }; +} + +/// One canonical stage/attempt event (ADR-0013) as emitted by the pipeline itself: server UTC timestamp, +/// Stopwatch-measured duration on terminal states, bounded reason code. Sequence numbers are assigned by the +/// consumer (the Host trace hub) in emission order. +public sealed record PipelineTraceEvent( + string Stage, + string State, + DateTimeOffset TsUtc, + double? DurationMs = null, + string? ReasonCode = null, + string? AttemptId = null, + string? Target = null); + +/// Mutable record of one provider attempt while the request runs; the audit stage freezes it into an +/// . Created immediately before the provider call starts (Started = true). +public sealed class AttemptRecord +{ + public required string AttemptId { get; init; } + public required string ConnectionId { get; init; } + public required string ModelId { get; init; } + /// running | served | failed | cancelled. + public string Outcome { get; set; } = TraceStates.Running; + public string? ErrorClass { get; set; } + public double DurationMs { get; set; } + public decimal? CostUsd { get; set; } + public string? CostBasis { get; set; } + public decimal? ReservedUsd { get; set; } + public bool? Overrun { get; set; } + + public AuditAttempt ToAudit() => new(AttemptId, ConnectionId, ModelId, Outcome, ErrorClass, DurationMs, CostUsd, CostBasis, ReservedUsd, Overrun); +} + +/// Result of asking the gate whether an attempt may start. +public sealed record AttemptAdmission(bool Admitted, decimal ReservedUsd = 0m, string? Reason = null, string? Stage = null, string? Code = null) +{ + public static AttemptAdmission Ok(decimal reservedUsd) => new(true, reservedUsd); + public static AttemptAdmission Refused(string reason, string stage, string code) => new(false, 0m, reason, stage, code); +} + +/// What one attempt was charged. Settled = false when this call was a duplicate (already settled — ignored). +public readonly record struct AttemptCharge(decimal CostUsd, string CostBasis, bool Overrun, bool Settled); + +/// Per-request attempt gate (ADR-0013/0014), installed by the budget stage on configured requests. The provider +/// stage calls before EVERY attempt (the first attempt was already reserved by the budget stage; +/// later attempts re-check the global pause and reserve), exactly once per started attempt and +/// for an admitted attempt that never started. Implementations are idempotent per attempt id. +public interface IAttemptGate +{ + AttemptAdmission Admit(InferenceContext context, RouteTarget target, string attemptId); + + /// Settles a started attempt. = the priced reported usage; null ⇒ the conservative + /// reservation-bound estimate (failed, cancelled or unreported). A reported cost above the reservation is settled in + /// full and flagged as an overrun. + AttemptCharge Settle(InferenceContext context, string attemptId, decimal? costUsd); + + void Release(InferenceContext context, string attemptId); +} + +/// Enforced token bounds (ADR-0014). The input bound is the UTF-8 byte count of every message's content plus +/// 16 per message (byte-level tokenizers never emit more tokens than bytes; chars/4 is an average and is never used for +/// enforcement). The output bound is min(request max_tokens, application MaxOutputTokens, model MaxOutputTokens); it is +/// SENT to the provider (ChatOptions.MaxOutputTokens) so the bound is real. +public static class RequestBounds +{ + public const int DefaultOutputTokens = 1024; + public const int PerMessageOverheadTokens = 16; + + public static long InputTokenBound(IReadOnlyList messages) + { + long total = 0; + foreach (var m in messages) total += Encoding.UTF8.GetByteCount(m.Content) + PerMessageOverheadTokens; + return total; + } + + /// Without a bound configuration (pure pipeline compositions) the request's own max_tokens is passed + /// through unchanged (pre-v2 behaviour). + public static int? OutputTokenBound(InferenceContext ctx, RouteTarget target) + { + if (ctx.Configuration is not { } cfg) return ctx.Request.MaxOutputTokens; + int bound = ctx.ApplicationId is { } appId && cfg.FindApplication(appId) is { } app ? app.MaxOutputTokens : DefaultOutputTokens; + if (ctx.Request.MaxOutputTokens is { } requested) bound = Math.Min(bound, requested); + if (cfg.FindModel(target.AdapterKey, target.ModelId)?.MaxOutputTokens is { } modelMax) bound = Math.Min(bound, modelMax); + return Math.Max(1, bound); + } +} diff --git a/src/Covenant.Core/InferenceContext.cs b/src/Covenant.Core/InferenceContext.cs index 6d6112d..5741a3f 100644 --- a/src/Covenant.Core/InferenceContext.cs +++ b/src/Covenant.Core/InferenceContext.cs @@ -111,13 +111,100 @@ public void BindConsoleIdentity(PreAuthenticatedIdentity identity, string operat /// (failure/cancellation): estimated, never a silent zero. public Usage? FailedCallUsage { get; set; } + /// Bounded reason code of the denial for trace/evidence (e.g. "paused", "budget_exceeded", "5xx"); null ⇒ + /// derived from (). + public string? DenialCode { get; private set; } + /// Refuse the request. First reason wins; later calls are ignored. The stopping stage is /// the one executing, unless the caller names a finer one (e.g. "pause" inside the budget stage). - public void Deny(string reason, DenialKind kind = DenialKind.Governance, string? stage = null) + public void Deny(string reason, DenialKind kind = DenialKind.Governance, string? stage = null, string? code = null) { if (DenialReason is not null) return; DenialReason = reason; DenialKind = kind; StoppedAtStage = stage ?? CurrentStage; + DenialCode = code; + } + + // ---- Provider attempts and budget reservation (ADR-0013/0014). Additive; empty/null on legacy compositions. ---- + + /// Installed by the budget stage on configured requests: pause re-check + reservation before each attempt, + /// exactly-once settlement. Null ⇒ no per-attempt budget accounting (pure pipeline compositions). + public IAttemptGate? AttemptGate { get; set; } + + /// Every provider attempt that was actually started, in order. + public List Attempts { get; } = []; + + /// The target whose attempt produced (primary or an approved fallback). + public RouteTarget? ServedTarget { get; set; } + + /// Reservation of the attempt currently running (USD) — the conservative bound used when usage is unreported. + public decimal? ActiveReservationUsd { get; set; } + + /// Total reserved across this request's attempts (USD); null when no reservation was made. + public decimal? ReservedUsd { get; set; } + + /// Total settled (charged) across this request's attempts (USD); null when nothing was settled. + public decimal? SettledUsd { get; set; } + + // ---- Real request trace (ADR-0013). The pipeline emits; the Host's trace hub (TraceSink) sequences and serves. ---- + + public const int MaxTraceEvents = 64; + private readonly List _trace = []; + private readonly HashSet _enteredStages = new(StringComparer.Ordinal); + private bool _traceCompleted; + + /// Installed by the Host BEFORE the pipeline starts (so the earliest events are retained). Must not throw; + /// an exception from it is swallowed — diagnostics never break governance. + public Action? TraceSink { get; set; } + + /// Events emitted so far (bounded to ), in emission order. + public IReadOnlyList TraceEvents => _trace; + + /// Traced stage names in pipeline order (set by the pipeline at start); stages never entered are reported as skipped. + public IReadOnlyList StageOrder { get; set; } = []; + + public void MarkStageEntered(string stage) => _enteredStages.Add(stage); + + /// Emits one trace event (server UTC time). Bounded: events beyond are dropped. + public void Trace(string stage, string state, double? durationMs = null, string? reasonCode = null, string? attemptId = null, string? target = null) + { + if (_trace.Count >= MaxTraceEvents) return; + var ev = new PipelineTraceEvent(stage, state, DateTimeOffset.UtcNow, durationMs, reasonCode, attemptId, target); + _trace.Add(ev); + if (TraceSink is { } sink) + { + try { sink(ev); } + catch (Exception) { /* diagnostics must never break the governed request */ } + } + } + + /// Marks every stage of that was never entered as skipped (reason cache_hit after a + /// cache hit, else not_reached). Idempotent; called by the audit stage before it writes evidence and by the pipeline + /// when it finishes. + public void CompleteTrace() + { + if (_traceCompleted) return; + _traceCompleted = true; + foreach (var stage in StageOrder) + if (!_enteredStages.Contains(stage)) + Trace(stage, TraceStates.Skipped, reasonCode: ServedFromCache ? TraceReasons.CacheHit : TraceReasons.NotReached); + } + + /// Compact durable summary for the audit record: terminal states only. Stage-level steps for every stage, + /// one provider step per attempt (the stage-level provider step is dropped when attempt steps exist), and + /// attempt-level pause/budget re-checks only when they refused. + public IReadOnlyList CompactTrace() + { + bool providerAttempts = _trace.Any(e => e.Stage == "provider" && e.AttemptId is not null); + var steps = new List(); + foreach (var e in _trace) + { + if (!TraceStates.IsTerminal(e.State)) continue; + if (e.AttemptId is not null && e.Stage != "provider" && e.State != TraceStates.Refused) continue; + if (e.Stage == "provider" && e.AttemptId is null && providerAttempts) continue; + steps.Add(new AuditTraceStep(e.Stage, e.State, e.DurationMs is { } d ? Math.Round(d, 3) : null, e.AttemptId, e.ReasonCode)); + } + return steps; } } diff --git a/src/Covenant.Core/Pipeline.cs b/src/Covenant.Core/Pipeline.cs index 4c6716c..f94fcdd 100644 --- a/src/Covenant.Core/Pipeline.cs +++ b/src/Covenant.Core/Pipeline.cs @@ -25,40 +25,112 @@ public static class CovenantDiagnostics public sealed class InferencePipeline { private readonly PipelineDelegate _entry; + private readonly IReadOnlyList _tracedStages; + + /// The audit stage is the evidence writer itself, not a governance step: it is never traced. + private const string AuditStageName = "audit"; public InferencePipeline(IReadOnlyList stages) { + var traced = new List(); + foreach (var s in stages) + { + var n = StageName(s); + if (n != AuditStageName && !traced.Contains(n)) traced.Add(n); + } + _tracedStages = traced; + PipelineDelegate next = static (_, _) => Task.CompletedTask; for (int i = stages.Count - 1; i >= 0; i--) { var stage = stages[i]; var spanName = "covenant.stage." + stage.GetType().Name; var stageName = StageName(stage); + bool isTraced = stageName != AuditStageName; var localNext = next; - next = (ctx, ct) => ctx.IsDenied ? Task.CompletedTask : RunStageAsync(stage, spanName, stageName, ctx, localNext, ct); + next = (ctx, ct) => ctx.IsDenied ? Task.CompletedTask : RunStageAsync(stage, spanName, stageName, isTraced, ctx, localNext, ct); } _entry = next; } + /// Traced stage names in execution order (excludes the audit stage). + public IReadOnlyList TracedStages => _tracedStages; + public async Task ExecuteAsync(InferenceContext context, CancellationToken cancellationToken) { using var activity = CovenantDiagnostics.Source.StartActivity("covenant.request"); + if (context.StageOrder.Count == 0) context.StageOrder = _tracedStages; try { await _entry(context, cancellationToken); } finally { + context.CompleteTrace(); // idempotent: the audit stage normally completed it before writing evidence if (activity is not null) Enrich(activity, context); } } + /// Runs one stage and emits its real trace (ADR-0013): "running" on entry; "passed" with the Stopwatch-measured + /// duration at the moment the stage hands over to the next one (or returns without denying — e.g. a cache hit); on a + /// short-circuit denial "refused" / "failed" (upstream) / "cancelled" with a bounded reason code; "cancelled" or + /// "failed" when an exception escapes the stage before it passed. private static async Task RunStageAsync( - IPipelineStage stage, string spanName, string stageName, InferenceContext ctx, PipelineDelegate next, CancellationToken ct) + IPipelineStage stage, string spanName, string stageName, bool traced, InferenceContext ctx, PipelineDelegate next, CancellationToken ct) { using var activity = CovenantDiagnostics.Source.StartActivity(spanName); ctx.CurrentStage = stageName; - await stage.InvokeAsync(ctx, next, ct); + if (!traced) + { + await stage.InvokeAsync(ctx, next, ct); + return; + } + + ctx.MarkStageEntered(stageName); + ctx.Trace(stageName, TraceStates.Running); + var watch = Stopwatch.StartNew(); + bool handedOver = false; + PipelineDelegate onward = (c, t) => + { + if (!handedOver) + { + handedOver = true; + c.Trace(stageName, TraceStates.Passed, watch.Elapsed.TotalMilliseconds); + } + return next(c, t); + }; + + try + { + await stage.InvokeAsync(ctx, onward, ct); + } + catch (OperationCanceledException) + { + if (!handedOver) ctx.Trace(stageName, TraceStates.Cancelled, watch.Elapsed.TotalMilliseconds, TraceReasons.ClientCancelled); + throw; + } + catch (Exception) + { + if (!handedOver) ctx.Trace(stageName, TraceStates.Failed, watch.Elapsed.TotalMilliseconds, TraceReasons.Error); + throw; + } + + if (handedOver) return; + if (ctx.IsDenied) + { + var state = ctx.DenialKind switch + { + DenialKind.Cancelled => TraceStates.Cancelled, + DenialKind.UpstreamFailure => TraceStates.Failed, + _ => TraceStates.Refused, + }; + ctx.Trace(stageName, state, watch.Elapsed.TotalMilliseconds, ctx.DenialCode ?? TraceReasons.ForDenial(ctx.DenialKind)); + } + else + { + ctx.Trace(stageName, TraceStates.Passed, watch.Elapsed.TotalMilliseconds, + ctx.ServedFromCache && stageName == "cache" ? TraceReasons.CacheHit : null); + } } ///
    Stable evidence names for stages (audit field StoppedAtStage); unknown stage types diff --git a/src/Covenant.Governance/Attribution.cs b/src/Covenant.Governance/Attribution.cs index 1cb8566..72e9cbd 100644 --- a/src/Covenant.Governance/Attribution.cs +++ b/src/Covenant.Governance/Attribution.cs @@ -20,7 +20,8 @@ public sealed class AttributionStage(IPriceBook priceBook) : IPipelineStage { public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, CancellationToken ct) { - if (ctx.Response is { } resp && ctx.Policy?.Route is { } route) + // The SERVED target (primary or an approved fallback, ADR-0013) is what gets priced and attributed. + if (ctx.Response is { } resp && (ctx.ServedTarget ?? ctx.Policy?.Route) is { } route) { decimal cost; (decimal InputPer1K, decimal OutputPer1K) p; @@ -37,6 +38,13 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance cost = (resp.Usage.InputTokens / 1000m * p.InputPer1K) + (resp.Usage.OutputTokens / 1000m * p.OutputPer1K); ctx.CostBasis = p.InputPer1K == 0m && p.OutputPer1K == 0m ? "zero_priced" : "reported"; } + else if (ctx.Configuration is not null && ctx.AttemptGate is not null && ctx.ActiveReservationUsd is { } bound) + { + // ADR-0014: usage unreported under a v2 reservation → settle the conservative reservation bound (enforced + // input + output bounds at this target's prices). Labelled an estimate; token counts stay unreported. + cost = bound; + ctx.CostBasis = p.InputPer1K == 0m && p.OutputPer1K == 0m ? "zero_priced" : "estimated_from_text"; + } else { // ADR-0009: billable call, provider reported no usage → estimate from text and CHARGE it, diff --git a/src/Covenant.Governance/Audit.cs b/src/Covenant.Governance/Audit.cs index c04d396..c7aa948 100644 --- a/src/Covenant.Governance/Audit.cs +++ b/src/Covenant.Governance/Audit.cs @@ -28,9 +28,14 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance // Final outcome, not any single stage's opinion: only a request that produced a response // was allowed. Denied anywhere, or errored with no response → recorded as a denial. bool served = !ctx.IsDenied && ctx.Response is not null; + ctx.CompleteTrace(); // stages never entered → skipped (not_reached | cache_hit) before evidence is written int previewChars = ctx.Configuration?.Config.Settings.PromptPreviewChars ?? promptPreviewChars; var id = ctx.Request.RequestId ?? $"req_{Guid.NewGuid():n}"; var usage = ctx.Response?.Usage ?? ctx.FailedCallUsage ?? Usage.Empty; + // ADR-0014: the request's charge is everything settled across its attempts (a failed primary plus the served + // fallback), not only the served attempt; Attempts[] carries the breakdown. + if (ctx.SettledUsd is { } settled && ctx.Attempts.Count > 0) usage = usage with { CostUsd = settled }; + bool v3 = ctx.Configuration is not null; var entry = new AuditEntry( Id: id, TimestampUtc: _clock.GetUtcNow(), @@ -71,7 +76,11 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance OperatorRef: ctx.OperatorRef, ApplicationId: ctx.ApplicationId, ProfileId: ctx.ProfileId, - BaselineClassification: ctx.BaselineClassification); + BaselineClassification: ctx.BaselineClassification, + Attempts: v3 ? ctx.Attempts.Select(a => a.ToAudit()).ToList() : null, + Trace: v3 ? ctx.CompactTrace() : null, + ReservedUsd: v3 ? ctx.ReservedUsd : null, + SettledUsd: v3 ? ctx.SettledUsd : null); // CancellationToken.None: a cancelled request must still produce its audit record. await sink.EnqueueAsync(entry, CancellationToken.None); diff --git a/src/Covenant.Governance/Budget.cs b/src/Covenant.Governance/Budget.cs index 63cafe7..f3746ee 100644 --- a/src/Covenant.Governance/Budget.cs +++ b/src/Covenant.Governance/Budget.cs @@ -94,21 +94,74 @@ public void Reset() } } -/// Kill switch + budget enforcement, after policy and before the provider call (nothing that costs money runs past an exhausted cap); records actual attributed cost on the unwind. -/// Check-then-spend: the last admitted request may overshoot by its own cost — deliberate first-slice trade-off (pre-call estimation needs a tokenizer). -public sealed class BudgetStage(IKillSwitch killSwitch, ISpendLedger ledger, BudgetConfig config, IPriceBook? prices = null) : IPipelineStage +/// Global provider-call pause as its own pipeline stage (trace stage "pause", ADR-0013), placed after the cache +/// (a cache hit is served during a pause — documented semantics) and before the budget. Refusal ⇒ governed denial at +/// stage "pause". The provider stage re-checks the pause before every fallback attempt through the attempt gate. +public sealed class PauseStage(IKillSwitch killSwitch) : IPipelineStage { public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, CancellationToken ct) { if (killSwitch.IsTripped) { - ctx.Deny(killSwitch.Reason is { } r ? $"kill switch engaged: {r}" : "kill switch engaged", stage: "pause"); + ctx.Deny(BudgetStage.PauseReason(killSwitch), stage: "pause", code: TraceReasons.Paused); + return; + } + await next(ctx, ct); + } +} + +/// Kill switch + budget enforcement, after policy and before the provider call (nothing that costs money runs past +/// an exhausted cap). +/// Configured requests with a v2 ledger (ADR-0014): the stage resolves the charged scopes (global, team, +/// application), installs the per-request and reserves the FIRST candidate's conservative +/// bound against every applicable hard budget, all-or-none (refusal ⇒ denial at stage "budget"). Later attempts are +/// admitted by the provider stage through the same gate; every attempt is settled exactly once and any reservation left +/// open is closed on the unwind (started ⇒ settled at the estimate, never started ⇒ released). +/// Legacy compositions (no configuration, or no v2 ledger): check-then-spend against the in-memory ledger +/// (the last admitted request may overshoot by its own cost), unchanged. +public sealed class BudgetStage : IPipelineStage +{ + private readonly IKillSwitch killSwitch; + private readonly ISpendLedger ledger; + private readonly BudgetConfig config; + private readonly IPriceBook? prices; + private readonly BudgetLedger? v2Ledger; + + public BudgetStage(IKillSwitch killSwitch, ISpendLedger ledger, BudgetConfig config, IPriceBook? prices = null) + { + this.killSwitch = killSwitch; + this.ledger = ledger; + this.config = config; + this.prices = prices; + } + + /// v2 composition (the Host): reservations against the persistent ledger for configured requests. A context + /// without a configuration is refused by the zero legacy cap (fail-closed; the Host never produces one). + public BudgetStage(IKillSwitch killSwitch, BudgetLedger v2Ledger) + : this(killSwitch, new InMemorySpendLedger(), new BudgetConfig { GlobalCapUsd = 0m }) + { + this.v2Ledger = v2Ledger; + } + + internal static string PauseReason(IKillSwitch killSwitch) + => killSwitch.Reason is { } r ? $"kill switch engaged: {r}" : "kill switch engaged"; + + public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, CancellationToken ct) + { + if (killSwitch.IsTripped) + { + ctx.Deny(PauseReason(killSwitch), stage: "pause", code: TraceReasons.Paused); + return; + } + + if (ctx.Configuration is { } configured && v2Ledger is not null) + { + await ReserveAndRunAsync(ctx, configured, v2Ledger, next, ct); return; } // Caps come from the request's bound configuration when present (ADR-0011): hard "global" and - // "team:" budgets. Spend lives in the ledger and is never reset by an apply. (Application scopes and - // UTC periods with reservations are ADR-0014 / T04.) + // "team:" budgets against the in-memory ledger (pure compositions without a v2 ledger). decimal? globalCap = config.GlobalCapUsd; decimal? teamCapFromConfig = null; var team = ctx.Identity.Tags.Team; @@ -122,7 +175,7 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance if (globalCap is { } gcap && ledger.GlobalSpendUsd >= gcap) { - ctx.Deny($"global budget exhausted (cap {gcap} USD)"); + ctx.Deny($"global budget exhausted (cap {gcap} USD)", code: TraceReasons.BudgetExceeded); return; } @@ -131,7 +184,7 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance : config.TeamCapsUsd.TryGetValue(team, out var legacyTeamCap) ? (decimal?)legacyTeamCap : null; if (teamCap is { } tcap && ledger.TeamSpendUsd(team) >= tcap) { - ctx.Deny($"budget exhausted for team '{team}' (cap {tcap} USD)"); + ctx.Deny($"budget exhausted for team '{team}' (cap {tcap} USD)", code: TraceReasons.BudgetExceeded); return; } @@ -149,6 +202,30 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance } } + private async Task ReserveAndRunAsync(InferenceContext ctx, IRequestConfiguration cfg, BudgetLedger budgetLedger, PipelineDelegate next, CancellationToken ct) + { + var gate = new BudgetAttemptGate(budgetLedger, killSwitch, cfg, ctx); + ctx.AttemptGate = gate; + var first = ctx.Policy is { } p ? (p.Candidates.Count > 0 ? p.Candidates[0] : p.Route) : null; + if (first is not null) + { + var admission = gate.ReserveFirst(ctx, first); + if (!admission.Admitted) + { + ctx.Deny(admission.Reason ?? "budget refused", stage: "budget", code: admission.Code); + return; + } + } + try + { + await next(ctx, ct); + } + finally + { + gate.Finish(ctx); + } + } + /// ADR-0009 fail-closed accounting: a provider call that was started but produced no /// response (upstream failure, mid-stream failure, cancellation) may still be billed. It is never /// recorded as $0: input (+ any streamed output) is estimated at chars/4 and charged when the model @@ -158,7 +235,7 @@ private void ChargeFailedCall(InferenceContext ctx, string model) bool priced; (decimal InputPer1K, decimal OutputPer1K) p; if (ctx.Configuration is { } cfg) - priced = ConfigPrices.TryGet(cfg, ctx.Policy?.Route?.AdapterKey ?? "", model, out p); + priced = ConfigPrices.TryGet(cfg, ctx.Attempts.Count > 0 ? ctx.Attempts[^1].ConnectionId : ctx.Policy?.Route?.AdapterKey ?? "", model, out p); else if (prices is not null) priced = prices.TryGetPrice(model, out p); else { priced = false; p = default; } diff --git a/src/Covenant.Governance/BudgetGate.cs b/src/Covenant.Governance/BudgetGate.cs new file mode 100644 index 0000000..e184c74 --- /dev/null +++ b/src/Covenant.Governance/BudgetGate.cs @@ -0,0 +1,179 @@ +using Covenant.Core; + +namespace Covenant.Governance; + +/// Scopes one request is charged to (ADR-0014): always global, the caller's team:<t>, and +/// application:<a> when the application is known — independent of which budgets exist, so a budget added or +/// renamed later sees the scope's whole accrued history. +public static class BudgetScopes +{ + public const string Global = "global"; + + public static IReadOnlyList For(InferenceContext ctx) + { + var scopes = new List { Global, "team:" + ctx.Identity.Tags.Team }; + if (ctx.ApplicationId is { Length: > 0 } app) scopes.Add("application:" + app); + return scopes; + } + + /// The hard budgets of whose scope this request is charged to. + public static IReadOnlyList HardChecks(IRequestConfiguration cfg, IReadOnlyList scopes) + => cfg.Config.Budgets + .Where(b => b.Enforcement == BudgetEnforcement.Hard && scopes.Contains(b.Scope, StringComparer.OrdinalIgnoreCase)) + .Select(b => new BudgetCheck(b.Id, b.Scope, b.CapUsd, b.Period)) + .ToList(); +} + +/// Conservative reservation estimate for one attempt (ADR-0014): input bound (UTF-8 bytes + 16 per message) at +/// the target's input price + enforced output bound at its output price, connection-scoped. Unpriced ⇒ 0 with +/// Priced = false (an unpriced paid target is ineligible under a hard budget — the engine and validator enforce that). +public static class ReservationEstimate +{ + public static (decimal AmountUsd, bool Priced) For(InferenceContext ctx, IRequestConfiguration cfg, RouteTarget target) + { + if (!ConfigPrices.TryGet(cfg, target.AdapterKey, target.ModelId, out var p)) return (0m, false); + long input = RequestBounds.InputTokenBound(ctx.Request.Messages); + long output = RequestBounds.OutputTokenBound(ctx, target) ?? RequestBounds.DefaultOutputTokens; + return (input / 1000m * p.InputPer1K + output / 1000m * p.OutputPer1K, true); + } +} + +/// The per-request over the persistent (ADR-0013/0014). +/// Attempt 1 is reserved by the budget stage (); every later attempt re-checks the global +/// pause and reserves before it starts (trace events pause/budget with the attempt id). Settlement is exactly once per +/// attempt (the gate and the ledger are both idempotent); zero-bound attempts (explicit $0 local price) write nothing. +/// Charged scopes are captured when the gate is created — an attempt settles against the scopes that applied when it was +/// reserved, even across a configuration activation. +public sealed class BudgetAttemptGate : IAttemptGate +{ + private sealed class Slot + { + public required RouteTarget Target { get; init; } + public required decimal Reserved { get; init; } + public required bool Priced { get; init; } + public bool Closed { get; set; } + public AttemptCharge? Charge { get; set; } + } + + private readonly BudgetLedger _ledger; + private readonly IKillSwitch _killSwitch; + private readonly IRequestConfiguration _cfg; + private readonly IReadOnlyList _scopes; + private readonly IReadOnlyList _checks; + private readonly string _requestId; + private readonly Dictionary _slots = new(StringComparer.Ordinal); + private readonly object _gate = new(); + + public BudgetAttemptGate(BudgetLedger ledger, IKillSwitch killSwitch, IRequestConfiguration cfg, InferenceContext ctx) + { + _ledger = ledger; + _killSwitch = killSwitch; + _cfg = cfg; + _scopes = BudgetScopes.For(ctx); + _checks = BudgetScopes.HardChecks(cfg, _scopes); + _requestId = ctx.Request.RequestId ?? $"req_{Guid.NewGuid():n}"; + } + + public IReadOnlyList Scopes => _scopes; + + /// Budget stage: reserve attempt 1 for the primary candidate (no attempt-level trace — the stage itself is traced). + public AttemptAdmission ReserveFirst(InferenceContext ctx, RouteTarget target) => Reserve(ctx, target, "att_1"); + + public AttemptAdmission Admit(InferenceContext ctx, RouteTarget target, string attemptId) + { + lock (_gate) + { + if (_slots.TryGetValue(attemptId, out var existing) && !existing.Closed && existing.Target == target) + { + ctx.ActiveReservationUsd = existing.Reserved; + return AttemptAdmission.Ok(existing.Reserved); // pre-reserved by the budget stage + } + } + + // A fallback attempt: the global pause is re-checked before it starts (no governance bypass). + var watch = System.Diagnostics.Stopwatch.StartNew(); + if (_killSwitch.IsTripped) + { + ctx.Trace("pause", TraceStates.Refused, watch.Elapsed.TotalMilliseconds, TraceReasons.Paused, attemptId); + return AttemptAdmission.Refused(BudgetStage.PauseReason(_killSwitch), "pause", TraceReasons.Paused); + } + ctx.Trace("pause", TraceStates.Passed, watch.Elapsed.TotalMilliseconds, attemptId: attemptId); + + watch.Restart(); + var admission = Reserve(ctx, target, attemptId); + ctx.Trace("budget", admission.Admitted ? TraceStates.Passed : TraceStates.Refused, watch.Elapsed.TotalMilliseconds, + admission.Admitted ? null : admission.Code, attemptId); + return admission; + } + + private AttemptAdmission Reserve(InferenceContext ctx, RouteTarget target, string attemptId) + { + var (amount, priced) = ReservationEstimate.For(ctx, _cfg, target); + if (amount > 0m) + { + var result = _ledger.TryReserve(_requestId, attemptId, _scopes, amount, _checks); + if (!result.Reserved) + return AttemptAdmission.Refused(result.Reason ?? "budget refused", "budget", TraceReasons.BudgetExceeded); + } + lock (_gate) + _slots[attemptId] = new Slot { Target = target, Reserved = amount, Priced = priced }; + ctx.ActiveReservationUsd = amount; + ctx.ReservedUsd = (ctx.ReservedUsd ?? 0m) + amount; + return AttemptAdmission.Ok(amount); + } + + public AttemptCharge Settle(InferenceContext ctx, string attemptId, decimal? costUsd) + { + Slot? slot; + lock (_gate) + { + _slots.TryGetValue(attemptId, out slot); + if (slot is { Closed: true }) return slot.Charge is { } c ? c with { Settled = false } : new AttemptCharge(0m, "no_call", false, false); + if (slot is not null) slot.Closed = true; + } + + bool priced = slot?.Priced ?? false; + decimal reserved = slot?.Reserved ?? 0m; + decimal amount = costUsd ?? reserved; + string basis = costUsd is not null ? "reported" : priced ? "estimated_failed_call" : "unknown_failed_call"; + var result = _ledger.Settle(_requestId, attemptId, amount, _scopes); + var charge = new AttemptCharge(amount, basis, result.Overrun || (costUsd is { } c2 && c2 > reserved && reserved > 0m), result.Settled || amount == 0m); + lock (_gate) + if (slot is not null) slot.Charge = charge; + ctx.SettledUsd = (ctx.SettledUsd ?? 0m) + amount; + return charge; + } + + public void Release(InferenceContext ctx, string attemptId) + { + lock (_gate) + { + if (!_slots.TryGetValue(attemptId, out var slot) || slot.Closed) return; + slot.Closed = true; + } + _ledger.Release(_requestId, attemptId); + } + + /// Unwind safety net (budget stage finally): an attempt that started but was never settled (an exception + /// escaped) is settled at its estimate; an admitted attempt that never started is released. Then the request-level + /// failed-call charge and cost basis are derived from the attempts (never a silent $0). + public void Finish(InferenceContext ctx) + { + List open; + lock (_gate) open = _slots.Where(kv => !kv.Value.Closed).Select(kv => kv.Key).ToList(); + foreach (var id in open) + { + var started = ctx.Attempts.FirstOrDefault(a => a.AttemptId == id); + if (started is null) { Release(ctx, id); continue; } + var charge = Settle(ctx, id, null); + started.CostUsd ??= charge.CostUsd; + started.CostBasis ??= charge.CostBasis; + } + + if (ctx.Response is null && ctx.Attempts.Count > 0) + { + ctx.FailedCallUsage ??= new Usage(0, 0, ctx.SettledUsd ?? 0m); // tokens NOT reported; cost is an estimate + ctx.CostBasis ??= ctx.Attempts[^1].CostBasis ?? "unknown_failed_call"; + } + } +} diff --git a/src/Covenant.Governance/BudgetLedger.cs b/src/Covenant.Governance/BudgetLedger.cs new file mode 100644 index 0000000..e5cfe0f --- /dev/null +++ b/src/Covenant.Governance/BudgetLedger.cs @@ -0,0 +1,388 @@ +using System.Globalization; +using Covenant.Core; + +namespace Covenant.Governance; + +/// Ledger operations (ADR-0014). reserve → settle (exactly once) → release (the unused remainder, exactly once); +/// release without settle closes a reservation whose attempt never started; settle-recovered closes a reservation that +/// was still open at boot (crash) at its reserved amount; legacy-import is the one-time import of pre-ledger spend. +public static class LedgerOps +{ + public const string Reserve = "reserve"; + public const string Settle = "settle"; + public const string Release = "release"; + public const string SettleRecovered = "settle-recovered"; + public const string LegacyImport = "legacy-import"; + + public static bool IsCharge(string op) => op is Settle or SettleRecovered or LegacyImport; +} + +/// One append-only ledger line. Keyed by (RequestId, AttemptId); records the SCOPES charged (global, +/// team:<t>, application:<a>) and a UTC timestamp — never a budget id or a period id, so editing a budget's id, +/// period or cap never resets accrual (ADR-0014). +public sealed record LedgerRecord +{ + public required string Op { get; init; } + public required string RequestId { get; init; } + public required string AttemptId { get; init; } + public required IReadOnlyList Scopes { get; init; } + public required decimal AmountUsd { get; init; } + public required DateTimeOffset TsUtc { get; init; } + /// Settle only: the reported charge exceeded the reservation (settled in full anyway). + public bool? Overrun { get; init; } +} + +/// Durable append seam (the Host's file store fsyncs; tests use ). Append must +/// be durable when it returns, or throw. +public interface ILedgerStore +{ + void Append(IReadOnlyList records); +} + +public sealed class InMemoryLedgerStore : ILedgerStore +{ + private readonly object _gate = new(); + private readonly List _records = []; + + public IReadOnlyList Records + { + get { lock (_gate) return _records.ToArray(); } + } + + public void Append(IReadOnlyList records) + { + lock (_gate) _records.AddRange(records); + } +} + +/// One hard-budget check applied at reservation time. +public sealed record BudgetCheck(string BudgetId, string Scope, decimal CapUsd, BudgetPeriod Period); + +public sealed record ReservationResult(bool Reserved, string? RefusedBudgetId = null, string? Reason = null) +{ + public static readonly ReservationResult Ok = new(true); +} + +public readonly record struct SettleResult(bool Settled, decimal AmountUsd, decimal ReservedUsd, bool Overrun); + +/// A settled charge that contributes to a scope (drill-down: GET /admin/budgets/{id}/requests). +public sealed record LedgerContribution(string RequestId, string AttemptId, string Op, decimal AmountUsd, DateTimeOffset TsUtc, bool Overrun); + +/// UTC budget periods (ADR-0014): none ⇒ all time ("all"); daily ⇒ "yyyy-MM-dd"; monthly ⇒ "yyyy-MM". +public static class BudgetPeriods +{ + public static string PeriodId(BudgetPeriod period, DateTimeOffset utc) + { + var u = utc.ToUniversalTime(); + return period switch + { + BudgetPeriod.Daily => u.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + BudgetPeriod.Monthly => u.ToString("yyyy-MM", CultureInfo.InvariantCulture), + _ => "all", + }; + } + + /// Bucket key a charge at accrues to for . + internal static string Bucket(BudgetPeriod period, DateTimeOffset utc) => period switch + { + BudgetPeriod.Daily => "d:" + PeriodId(period, utc), + BudgetPeriod.Monthly => "m:" + PeriodId(period, utc), + _ => "all", + }; + + /// [start, end) of the period containing ; (MinValue, MaxValue) for none. + public static (DateTimeOffset Start, DateTimeOffset End) Window(BudgetPeriod period, DateTimeOffset utc) + { + var u = utc.ToUniversalTime(); + return period switch + { + BudgetPeriod.Daily => (new DateTimeOffset(u.Year, u.Month, u.Day, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(u.Year, u.Month, u.Day, 0, 0, 0, TimeSpan.Zero).AddDays(1)), + BudgetPeriod.Monthly => (new DateTimeOffset(u.Year, u.Month, 1, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(u.Year, u.Month, 1, 0, 0, 0, TimeSpan.Zero).AddMonths(1)), + _ => (DateTimeOffset.MinValue, DateTimeOffset.MaxValue), + }; + } +} + +/// Persistent budget ledger (ADR-0014), independent of audit segments. State is rebuilt by replaying the +/// journal at boot; every mutation is appended durably BEFORE memory changes (a refused/failed write changes nothing). +/// One lock serializes reservations across all applicable hard budgets: spent(period) + reserved + estimate ≤ cap +/// for every check, all-or-none — concurrent requests cannot both take the last allowance. Spend per budget is +/// computed at read time from settled amounts of its scope in its current UTC period window. Scopes compare +/// case-insensitively (team names come from key configuration). +public sealed class BudgetLedger +{ + private sealed record Open(decimal Amount, IReadOnlyList Scopes, DateTimeOffset TsUtc); + + private const int MaxContributions = 20_000; + private const int MaxClosedKeys = 200_000; + + private readonly object _gate = new(); + private readonly ILedgerStore _store; + private readonly TimeProvider _clock; + private readonly Dictionary<(string Req, string Att), Open> _open = new(); + private readonly HashSet<(string Req, string Att)> _closed = new(); + private readonly Queue<(string Req, string Att)> _closedOrder = new(); + private readonly Dictionary _reserved = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary<(string Scope, string Bucket), decimal> _spent = new(ScopeBucketComparer.Instance); + private readonly LinkedList<(LedgerContribution C, IReadOnlyList Scopes)> _contributions = new(); + + public BudgetLedger(ILedgerStore store, IEnumerable? existing = null, TimeProvider? clock = null) + { + _store = store; + _clock = clock ?? TimeProvider.System; + if (existing is not null) + foreach (var r in existing) Apply(r); + } + + public TimeProvider Clock => _clock; + + /// Open reservations (diagnostics/tests). + public int OpenReservations + { + get { lock (_gate) return _open.Count; } + } + + /// Reserves for (request, attempt) against every check whose scope is charged, + /// all-or-none under the ledger lock. A key that is already reserved returns Ok (idempotent); a closed key is refused. + public ReservationResult TryReserve(string requestId, string attemptId, IReadOnlyList scopes, decimal amountUsd, IReadOnlyList checks) + { + lock (_gate) + { + var key = (requestId, attemptId); + if (_open.ContainsKey(key)) return ReservationResult.Ok; + if (_closed.Contains(key)) return new ReservationResult(false, null, "attempt already settled"); + var now = _clock.GetUtcNow(); + foreach (var check in checks) + { + if (!scopes.Contains(check.Scope, StringComparer.OrdinalIgnoreCase)) continue; + var spent = SpentLocked(check.Scope, check.Period, now); + var reserved = _reserved.GetValueOrDefault(check.Scope); + if (spent + reserved + amountUsd > check.CapUsd) + return new ReservationResult(false, check.BudgetId, + $"budget '{Evidence.Bounded(check.BudgetId)}' ({Evidence.Bounded(check.Scope)}, period {BudgetPeriods.PeriodId(check.Period, now)}) would be exceeded: " + + $"spent {Usd(spent)} + reserved {Usd(reserved)} + this attempt's bound {Usd(amountUsd)} > cap {Usd(check.CapUsd)} USD"); + } + var record = new LedgerRecord + { + Op = LedgerOps.Reserve, RequestId = requestId, AttemptId = attemptId, Scopes = scopes.ToArray(), AmountUsd = amountUsd, TsUtc = now, + }; + _store.Append([record]); + Apply(record); + return ReservationResult.Ok; + } + } + + /// Settles (request, attempt) exactly once with and releases the unused remainder + /// in the same durable write. A second settle (or a settle after release) is ignored. A charge with no reservation + /// (zero-bound attempt) is recorded against and flagged as an overrun when > 0. + public SettleResult Settle(string requestId, string attemptId, decimal amountUsd, IReadOnlyList scopesIfUnreserved) + { + lock (_gate) + { + var key = (requestId, attemptId); + if (_closed.Contains(key)) return new SettleResult(false, 0m, 0m, false); + var now = _clock.GetUtcNow(); + if (_open.TryGetValue(key, out var open)) + { + bool overrun = amountUsd > open.Amount; + var remainder = overrun ? 0m : open.Amount - amountUsd; + var settle = new LedgerRecord + { + Op = LedgerOps.Settle, RequestId = requestId, AttemptId = attemptId, Scopes = open.Scopes, AmountUsd = amountUsd, TsUtc = now, + Overrun = overrun ? true : null, + }; + var release = new LedgerRecord + { + Op = LedgerOps.Release, RequestId = requestId, AttemptId = attemptId, Scopes = open.Scopes, AmountUsd = remainder, TsUtc = now, + }; + _store.Append([settle, release]); + Apply(settle); + Apply(release); + return new SettleResult(true, amountUsd, open.Amount, overrun); + } + if (amountUsd <= 0m) + { + Close(key); + return new SettleResult(true, 0m, 0m, false); + } + var direct = new LedgerRecord + { + Op = LedgerOps.Settle, RequestId = requestId, AttemptId = attemptId, Scopes = scopesIfUnreserved.ToArray(), AmountUsd = amountUsd, TsUtc = now, + Overrun = true, + }; + _store.Append([direct]); + Apply(direct); + return new SettleResult(true, amountUsd, 0m, true); + } + } + + /// Releases an open reservation whose attempt never started (no charge). Idempotent. + public bool Release(string requestId, string attemptId) + { + lock (_gate) + { + var key = (requestId, attemptId); + if (!_open.TryGetValue(key, out var open)) return false; + var release = new LedgerRecord + { + Op = LedgerOps.Release, RequestId = requestId, AttemptId = attemptId, Scopes = open.Scopes, AmountUsd = open.Amount, TsUtc = _clock.GetUtcNow(), + }; + _store.Append([release]); + Apply(release); + return true; + } + } + + /// Boot recovery (ADR-0014): every reservation still open (process crashed mid-attempt) is settled at its + /// reserved amount — conservative, never free capacity. Returns what was recovered. + public IReadOnlyList RecoverUnsettled() + { + lock (_gate) + { + if (_open.Count == 0) return []; + var now = _clock.GetUtcNow(); + var records = _open.Select(kv => new LedgerRecord + { + Op = LedgerOps.SettleRecovered, RequestId = kv.Key.Req, AttemptId = kv.Key.Att, Scopes = kv.Value.Scopes, AmountUsd = kv.Value.Amount, TsUtc = now, + }).ToList(); + _store.Append(records); + foreach (var r in records) Apply(r); + return records; + } + } + + /// One-time legacy migration: pre-ledger spend (from the current audit segment) per team, charged to the + /// global and team scopes in the current period. + public IReadOnlyList ImportLegacy(IEnumerable<(string Team, decimal AmountUsd)> spendByTeam) + { + lock (_gate) + { + var now = _clock.GetUtcNow(); + var records = spendByTeam.Where(t => t.AmountUsd > 0m).Select(t => new LedgerRecord + { + Op = LedgerOps.LegacyImport, RequestId = LedgerOps.LegacyImport, AttemptId = "team:" + t.Team, + Scopes = ["global", "team:" + t.Team], AmountUsd = t.AmountUsd, TsUtc = now, + }).ToList(); + if (records.Count == 0) return []; + _store.Append(records); + foreach (var r in records) Apply(r); + return records; + } + } + + /// Settled amount for in the period of containing now. + public decimal Spent(string scope, BudgetPeriod period) + { + lock (_gate) return SpentLocked(scope, period, _clock.GetUtcNow()); + } + + public decimal Reserved(string scope) + { + lock (_gate) return _reserved.GetValueOrDefault(scope); + } + + /// Scopes with a prefix (e.g. "team:") that have any settled spend in the period containing now. + public IReadOnlyDictionary SpentByScopePrefix(string prefix, BudgetPeriod period) + { + lock (_gate) + { + var bucket = BudgetPeriods.Bucket(period, _clock.GetUtcNow()); + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var (k, v) in _spent) + if (k.Bucket == bucket && k.Scope.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && v != 0m) + map[k.Scope] = v; + return map; + } + } + + /// Newest-first settled charges for inside the current window of + /// (bounded to the most recent 20 000 charges kept in memory). + public IReadOnlyList Contributions(string scope, BudgetPeriod period, int limit) + { + lock (_gate) + { + var (start, end) = BudgetPeriods.Window(period, _clock.GetUtcNow()); + var list = new List(); + for (var node = _contributions.Last; node is not null && list.Count < limit; node = node.Previous) + { + var (c, scopes) = node.Value; + if (c.TsUtc >= start && c.TsUtc < end && scopes.Contains(scope, StringComparer.OrdinalIgnoreCase)) list.Add(c); + } + return list; + } + } + + private decimal SpentLocked(string scope, BudgetPeriod period, DateTimeOffset now) + => _spent.GetValueOrDefault((scope, BudgetPeriods.Bucket(period, now))); + + /// Replays one record into memory (boot) or applies a just-appended one. + private void Apply(LedgerRecord r) + { + var key = (r.RequestId, r.AttemptId); + switch (r.Op) + { + case LedgerOps.Reserve: + if (_open.ContainsKey(key) || _closed.Contains(key)) return; + _open[key] = new Open(r.AmountUsd, r.Scopes, r.TsUtc); + foreach (var s in r.Scopes) _reserved[s] = _reserved.GetValueOrDefault(s) + r.AmountUsd; + return; + case LedgerOps.Settle: + case LedgerOps.SettleRecovered: + if (_closed.Contains(key)) return; // exactly once, also on replay + Unreserve(key); + Charge(r); + Close(key); + return; + case LedgerOps.Release: + Unreserve(key); + Close(key); + return; + case LedgerOps.LegacyImport: + Charge(r); + return; + } + } + + private void Unreserve((string, string) key) + { + if (!_open.Remove(key, out var open)) return; + foreach (var s in open.Scopes) + { + var left = _reserved.GetValueOrDefault(s) - open.Amount; + if (left <= 0m) _reserved.Remove(s); else _reserved[s] = left; + } + } + + private void Charge(LedgerRecord r) + { + if (r.AmountUsd == 0m) return; + foreach (var s in r.Scopes) + foreach (var period in AllPeriods) + { + var k = (s, BudgetPeriods.Bucket(period, r.TsUtc)); + _spent[k] = _spent.GetValueOrDefault(k) + r.AmountUsd; + } + _contributions.AddLast((new LedgerContribution(r.RequestId, r.AttemptId, r.Op, r.AmountUsd, r.TsUtc, r.Overrun == true), r.Scopes)); + while (_contributions.Count > MaxContributions) _contributions.RemoveFirst(); + } + + private void Close((string, string) key) + { + if (!_closed.Add(key)) return; + _closedOrder.Enqueue(key); + while (_closedOrder.Count > MaxClosedKeys) _closed.Remove(_closedOrder.Dequeue()); + } + + private static readonly BudgetPeriod[] AllPeriods = [BudgetPeriod.None, BudgetPeriod.Daily, BudgetPeriod.Monthly]; + + private static string Usd(decimal v) => v.ToString("0.########", CultureInfo.InvariantCulture); + + private sealed class ScopeBucketComparer : IEqualityComparer<(string Scope, string Bucket)> + { + public static readonly ScopeBucketComparer Instance = new(); + public bool Equals((string Scope, string Bucket) x, (string Scope, string Bucket) y) + => StringComparer.OrdinalIgnoreCase.Equals(x.Scope, y.Scope) && StringComparer.Ordinal.Equals(x.Bucket, y.Bucket); + public int GetHashCode((string Scope, string Bucket) obj) + => HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Scope), StringComparer.Ordinal.GetHashCode(obj.Bucket)); + } +} diff --git a/src/Covenant.Governance/Cache.cs b/src/Covenant.Governance/Cache.cs index 9e4ec72..0d0d20f 100644 --- a/src/Covenant.Governance/Cache.cs +++ b/src/Covenant.Governance/Cache.cs @@ -66,10 +66,15 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance return; } + // v2 key (ADR-0013): SHA-256 over application, team, profile, FINAL classification, configuration version, the + // ordered approved candidates (connection id + model id), the enforced output bound sent to the provider and the + // message content — so a new activation, another identity or another eligible route set never reuses an entry. + IReadOnlyList candidates = ctx.Policy!.Candidates.Count > 0 ? ctx.Policy.Candidates : new[] { route }; var key = ctx.Configuration is { } cfg - ? Key(string.Join('\u001e', "v2", cfg.Version.ToString(System.Globalization.CultureInfo.InvariantCulture), - ctx.ApplicationId ?? "", ctx.ProfileId ?? "", ctx.Classification.ToString(), route.AdapterKey, ctx.Identity.Tags.Team), - route.ModelId, ctx.Request.Messages, ctx.Request.MaxOutputTokens) + ? Key(string.Join('\u001e', "v3", cfg.Version.ToString(System.Globalization.CultureInfo.InvariantCulture), + ctx.ApplicationId ?? "", ctx.ProfileId ?? "", ctx.Classification.ToString(), ctx.Identity.Tags.Team, + string.Join('\u001d', candidates.Select(c => c.AdapterKey + "/" + c.ModelId))), + route.ModelId, ctx.Request.Messages, RequestBounds.OutputTokenBound(ctx, route)) : Key(ctx.Identity.Tags.Team, route.ModelId, ctx.Request.Messages, ctx.Request.MaxOutputTokens); if (cache.TryGet(key, out var hit)) { diff --git a/src/Covenant.Host/AuditSegments.cs b/src/Covenant.Host/AuditSegments.cs new file mode 100644 index 0000000..4725a7b --- /dev/null +++ b/src/Covenant.Host/AuditSegments.cs @@ -0,0 +1,279 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using Covenant.Core; + +namespace Covenant.Host; + +/// One audit segment: the current log or an archived sibling (spec §5). The id is opaque and server-generated; +/// a caller can only ever name a segment from the enumerated set — never a path. +public sealed record AuditSegment(string Id, string Label, bool Current, string FilePath, string? AnchorPath, DateTimeOffset? ArchivedUtc); + +public sealed class SegmentView +{ + [JsonPropertyName("id")] public required string Id { get; init; } + [JsonPropertyName("label")] public required string Label { get; init; } + [JsonPropertyName("current")] public required bool Current { get; init; } + [JsonPropertyName("entries")] public required int Entries { get; init; } + [JsonPropertyName("events")] public int Events { get; init; } + [JsonPropertyName("first_utc")] public DateTimeOffset? FirstUtc { get; init; } + [JsonPropertyName("last_utc")] public DateTimeOffset? LastUtc { get; init; } + [JsonPropertyName("chain_valid")] public required bool ChainValid { get; init; } + [JsonPropertyName("archived_utc")] public DateTimeOffset? ArchivedUtc { get; init; } +} + +public sealed class ExportIntegrity +{ + [JsonPropertyName("segment_id")] public required string SegmentId { get; init; } + [JsonPropertyName("chain_valid")] public required bool ChainValid { get; init; } + [JsonPropertyName("chain_failure")] public string? ChainFailure { get; init; } + /// 1-based line of the record in its segment. + [JsonPropertyName("line")] public int? Line { get; init; } + [JsonPropertyName("previous_hash")] public string? PreviousHash { get; init; } + [JsonPropertyName("entry_hash")] public string? EntryHash { get; init; } + [JsonPropertyName("anchor_configured")] public required bool AnchorConfigured { get; init; } + /// "verified" (record inside a valid chain) | "unverified" (chain broken — do not trust). + [JsonPropertyName("status")] public required string Status { get; init; } +} + +/// GET /admin/requests/{id}/export: a self-contained evidence export of one request. Never prompt/response content: +/// the opt-in PromptPreview is removed; the prompt SHA-256 fingerprint stays (it proves which prompt, not what). +public sealed class RequestExport +{ + [JsonPropertyName("exported_utc")] public required DateTimeOffset ExportedUtc { get; init; } + [JsonPropertyName("request_id")] public required string RequestId { get; init; } + [JsonPropertyName("segment")] public required SegmentView Segment { get; init; } + [JsonPropertyName("config_version")] public int? ConfigVersion { get; init; } + [JsonPropertyName("record")] public required AuditEntry Record { get; init; } + [JsonPropertyName("attempts")] public IReadOnlyList? Attempts { get; init; } + [JsonPropertyName("trace")] public IReadOnlyList? Trace { get; init; } + [JsonPropertyName("integrity")] public required ExportIntegrity Integrity { get; init; } + [JsonPropertyName("content_included")] public bool ContentIncluded { get; init; } +} + +/// Enumerates audit segments: the current file plus <audit file>.yyyyMMdd-HHmmss.archived siblings in the same +/// directory (the names produces). Ids: "current", or "a-" + 16 hex of SHA-256 over +/// the archive's file name. Cursors are opaque base64url tokens bound to one segment. +public sealed partial class AuditSegments(string auditPath, string? anchorPath) +{ + public const string CurrentId = "current"; + + [GeneratedRegex(@"^\d{8}-\d{6}$")] + private static partial Regex StampPattern(); + + public IReadOnlyList List() + { + var full = Path.GetFullPath(auditPath); + var dir = Path.GetDirectoryName(full)!; + var name = Path.GetFileName(full); + var list = new List { new(CurrentId, "Current segment", true, full, anchorPath, null) }; + if (!Directory.Exists(dir)) return list; + var archived = new List(); + foreach (var file in Directory.EnumerateFiles(dir, name + ".*.archived")) + { + var fileName = Path.GetFileName(file); + var stamp = fileName[(name.Length + 1)..^".archived".Length]; + if (!StampPattern().IsMatch(stamp)) continue; // e.g. an anchor archive that shares the prefix — not a segment + DateTimeOffset? at = DateTime.TryParseExact(stamp, "yyyyMMdd-HHmmss", CultureInfo.InvariantCulture, + DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var t) ? new DateTimeOffset(t, TimeSpan.Zero) : null; + string? anchors = anchorPath is not null && File.Exists($"{anchorPath}.{stamp}.archived") ? $"{anchorPath}.{stamp}.archived" : null; + var id = "a-" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(fileName))).ToLowerInvariant()[..16]; + var label = at is { } a ? $"Archived {a.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)} UTC" : "Archived segment"; + archived.Add(new AuditSegment(id, label, false, file, anchors, at)); + } + list.AddRange(archived.OrderByDescending(s => s.ArchivedUtc ?? DateTimeOffset.MinValue).ThenByDescending(s => s.FilePath, StringComparer.Ordinal)); + return list; + } + + /// Only ids from the enumerated set resolve (null ⇒ current). Anything else — a path, "..", an unknown id — is null. + public AuditSegment? Resolve(string? id) + { + var all = List(); + if (string.IsNullOrEmpty(id)) return all[0]; + return all.FirstOrDefault(s => string.Equals(s.Id, id, StringComparison.Ordinal)); + } + + public static (ChainVerification Verification, IReadOnlyList Entries) Read(AuditSegment segment) + => AuditChainVerifier.VerifyAndRead(segment.FilePath, segment.AnchorPath); + + public static SegmentView View(AuditSegment segment, ChainVerification verification, IReadOnlyList all) + { + var requests = all.Where(e => e.IsRequest()).ToList(); + return new SegmentView + { + Id = segment.Id, + Label = segment.Label, + Current = segment.Current, + Entries = requests.Count, + Events = all.Count - requests.Count, + FirstUtc = requests.Count > 0 ? requests[0].TimestampUtc : null, + LastUtc = requests.Count > 0 ? requests[^1].TimestampUtc : null, + ChainValid = verification.Valid, + ArchivedUtc = segment.ArchivedUtc, + }; + } + + public static string Cursor(string segmentId, int offset) + => Base64Url(Encoding.UTF8.GetBytes($"c1|{segmentId}|{offset.ToString(CultureInfo.InvariantCulture)}")); + + /// Opaque newest-first position: (segment id, number of newest items already returned). Null when malformed. + public static (string SegmentId, int Offset)? ParseCursor(string? cursor) + { + if (string.IsNullOrEmpty(cursor) || cursor.Length > 200) return null; + try + { + var s = cursor.Replace('-', '+').Replace('_', '/'); + s = s.PadRight(s.Length + (4 - s.Length % 4) % 4, '='); + var parts = Encoding.UTF8.GetString(Convert.FromBase64String(s)).Split('|'); + if (parts.Length != 3 || parts[0] != "c1") return null; + if (!int.TryParse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture, out var offset) || offset < 0) return null; + return (parts[1], offset); + } + catch (FormatException) + { + return null; + } + } + + private static string Base64Url(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + /// Hashes and 1-based line of the request record in (last match). + public static (int Line, string PreviousHash, string EntryHash)? Locate(AuditSegment segment, string id) + { + if (!File.Exists(segment.FilePath)) return null; + (int, string, string)? found = null; + int lineNo = 0; + using var fs = new FileStream(segment.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var reader = new StreamReader(fs); + while (reader.ReadLine() is { } line) + { + if (string.IsNullOrWhiteSpace(line)) continue; + lineNo++; + var parts = line.Split(AuditChain.Separator, 3); + if (parts.Length != 3 || !parts[2].Contains(id, StringComparison.Ordinal)) continue; + AuditEntry? e; + try { e = JsonSerializer.Deserialize(parts[2], AuditJsonContext.Default.AuditEntry); } + catch (JsonException) { continue; } + if (e is not null && e.IsRequest() && e.Id == id) found = (lineNo, parts[0], parts[1]); + } + return found; + } +} + +/// Archive navigation and evidence export (docs/ui-api-contract.md v2 "Requests archive"). +public static class ArchiveApi +{ + private static IResult Error(string error, string reason, int status) + => Results.Json(new ErrorResponse { Error = error, Reason = reason }, CovenantJsonContext.Default.ErrorResponse, statusCode: status); + + public static void MapArchive(this WebApplication app, AuditSegments segments, Func authorized, string? anchorPath) + { + app.MapGet("/admin/audit/segments", (HttpContext http) => + { + if (!authorized(http)) return Error("unauthorized", "invalid admin token", StatusCodes.Status401Unauthorized); + http.Response.Headers.CacheControl = "no-store"; + var views = segments.List().Select(s => + { + var (v, entries) = AuditSegments.Read(s); + return AuditSegments.View(s, v, entries); + }).ToList(); + return Results.Json(views, AuditJsonContext.Default.ListSegmentView); + }); + + // Newest-first records of ONE segment (current by default), bounded, with an opaque cursor for the next page. + app.MapGet("/admin/requests", (HttpContext http, int? limit, string? cursor, string? segment) => + { + if (!authorized(http)) return Error("unauthorized", "invalid admin token", StatusCodes.Status401Unauthorized); + http.Response.Headers.CacheControl = "no-store"; + int offset = 0; + string? segmentId = segment; + if (cursor is not null) + { + if (AuditSegments.ParseCursor(cursor) is not { } c) + return Error("invalid_cursor", "cursor is malformed (use next_cursor from a previous page)", StatusCodes.Status400BadRequest); + if (segmentId is not null && segmentId != c.SegmentId) + return Error("invalid_cursor", "cursor belongs to another segment", StatusCodes.Status400BadRequest); + segmentId = c.SegmentId; + offset = c.Offset; + } + if (segments.Resolve(segmentId) is not { } seg) + return Error("unknown_segment", "segment must be an id from GET /admin/audit/segments", StatusCodes.Status400BadRequest); + + var (verification, all) = AuditSegments.Read(seg); + var entries = all.Where(e => e.IsRequest()).ToList(); // v3: control-plane events → GET /admin/config/versions + int take = Math.Clamp(limit ?? 200, 1, 1000); + var items = Enumerable.Reverse(entries).Skip(offset).Take(take).ToList(); + var view = AuditSegments.View(seg, verification, all); + var page = new RequestsPage + { + Segment = new SegmentInfo + { + Path = seg.FilePath, + Entries = view.Entries, + ChainValid = view.ChainValid, + FirstUtc = view.FirstUtc, + LastUtc = view.LastUtc, + Events = view.Events, + Id = seg.Id, + Label = seg.Label, + }, + Items = items, + NextCursor = offset + items.Count < entries.Count ? AuditSegments.Cursor(seg.Id, offset + items.Count) : null, + }; + return Results.Json(page, AuditJsonContext.Default.RequestsPage); + }); + + app.MapGet("/admin/requests/{id}/export", (HttpContext http, string id, string? segment) => + { + if (!authorized(http)) return Error("unauthorized", "invalid admin token", StatusCodes.Status401Unauthorized); + http.Response.Headers.CacheControl = "no-store"; + if (!RequestCorrelation.IsWellFormed(id)) + return Error("invalid_id", "request id must be ≤64 chars of [A-Za-z0-9_-]", StatusCodes.Status400BadRequest); + IEnumerable search; + if (segment is not null) + { + if (segments.Resolve(segment) is not { } only) + return Error("unknown_segment", "segment must be an id from GET /admin/audit/segments", StatusCodes.Status400BadRequest); + search = [only]; + } + else search = segments.List(); + + foreach (var seg in search) + { + var (verification, all) = AuditSegments.Read(seg); + AuditEntry? entry = null; + for (int i = all.Count - 1; i >= 0; i--) + if (all[i].IsRequest() && all[i].Id == id) { entry = all[i]; break; } + if (entry is null) continue; + var located = AuditSegments.Locate(seg, id); + var export = new RequestExport + { + ExportedUtc = DateTimeOffset.UtcNow, + RequestId = id, + Segment = AuditSegments.View(seg, verification, all), + ConfigVersion = entry.ConfigVersion, + Record = entry with { PromptPreview = null }, // default export excludes content + Attempts = entry.Attempts, + Trace = entry.Trace, + Integrity = new ExportIntegrity + { + SegmentId = seg.Id, + ChainValid = verification.Valid, + ChainFailure = verification.Failure, + Line = located?.Line, + PreviousHash = located?.PreviousHash, + EntryHash = located?.EntryHash, + AnchorConfigured = seg.AnchorPath is not null || (seg.Current && anchorPath is not null), + Status = verification.Valid ? "verified" : "unverified", + }, + ContentIncluded = false, + }; + return Results.Json(export, AuditJsonContext.Default.RequestExport); + } + return Error("not_found", "no request record with this id in any audit segment", StatusCodes.Status404NotFound); + }); + } +} diff --git a/src/Covenant.Host/BudgetLedgerStore.cs b/src/Covenant.Host/BudgetLedgerStore.cs new file mode 100644 index 0000000..65b8eb9 --- /dev/null +++ b/src/Covenant.Host/BudgetLedgerStore.cs @@ -0,0 +1,275 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using Covenant.Core; +using Covenant.Governance; + +namespace Covenant.Host; + +/// Result of opening the budget ledger journal at boot. Errors ⇒ refuse to start (fail-closed). +public sealed class LedgerOpenResult +{ + public List Records { get; } = []; + public List Errors { get; } = []; + public List Warnings { get; } = []; + /// False when no journal file existed before this boot (⇒ the one-time legacy import runs). + public bool Existed { get; init; } +} + +/// Append-only JSONL journal of the budget ledger (ADR-0014), Budget:LedgerPath (default +/// <Audit:Path>.ledger.jsonl), independent of audit segments (an audit archive never touches it). +/// Torn-tail handling mirrors the configuration activation journal (ADR-0011): a final line without its newline that does +/// not parse (an interrupted append) is quarantined to …ledger.jsonl.torn-<utc> and the journal is rewritten +/// atomically with only the complete lines BEFORE anything can append; a complete last line whose newline never landed +/// is terminated; any other corrupt line refuses start. Appends are refused onto an unterminated line, and every append +/// is flushed to disk before it returns. A failed append halts the process (like a failed audit write): an appliance +/// that cannot record spend must not keep spending. +public sealed class FileLedgerStore : ILedgerStore +{ + private readonly object _gate = new(); + private bool _terminated; // unknown until Open() verified the tail (or the first append checks it) + + public FileLedgerStore(string path) => Path = path; + + public string Path { get; } + + public LedgerOpenResult Open() + { + lock (_gate) + { + if (!File.Exists(Path)) return new LedgerOpenResult { Existed = false }; + var result = new LedgerOpenResult { Existed = true }; + var text = Encoding.UTF8.GetString(File.ReadAllBytes(Path)); + bool endsWithNewline = text.Length == 0 || text[^1] == '\n'; + var lines = text.Split('\n'); + int last = lines.Length - 1; + while (last >= 0 && lines[last].Trim().Length == 0) last--; + string? tornTail = null; + var good = new StringBuilder(); + for (int i = 0; i <= last; i++) + { + var raw = lines[i]; + var line = raw.Trim(); + if (line.Length == 0) continue; + LedgerRecord? rec = null; + try { rec = JsonSerializer.Deserialize(line, LedgerJsonContext.Default.LedgerRecord); } + catch (JsonException) { } + if (rec is { Op.Length: > 0, RequestId.Length: > 0, AttemptId: not null, Scopes: not null }) + { + result.Records.Add(rec); + good.Append(line).Append('\n'); + continue; + } + if (i == last && !endsWithNewline) tornTail = raw; + else + { + result.Errors.Add($"Budget:LedgerPath {Path} — line {i + 1} is corrupt; accrued spend cannot be trusted. Restore the ledger from backup (never delete it)."); + return result; + } + } + if (tornTail is null && !endsWithNewline && last >= 0) tornTail = ""; // parsed, but its newline never landed + if (tornTail is not null) + { + try + { + if (tornTail.Length > 0) + { + var quarantine = $"{Path}.torn-{DateTime.UtcNow.ToString("yyyyMMddTHHmmssfffZ", CultureInfo.InvariantCulture)}"; + WriteDurable(quarantine, Encoding.UTF8.GetBytes(tornTail)); + result.Warnings.Add($"budget ledger: the last line was torn (interrupted append); preserved in {System.IO.Path.GetFileName(quarantine)} and removed from the journal"); + } + var tmp = Path + ".tmp"; + WriteDurable(tmp, Encoding.UTF8.GetBytes(good.ToString())); + File.Move(tmp, Path, overwrite: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + result.Errors.Add($"Budget:LedgerPath {Path} — torn tail could not be repaired ({ex.Message}); refusing to start."); + } + } + _terminated = true; + return result; + } + } + + /// Creates an empty journal (marks the one-time legacy import as done). + public void EnsureCreated() + { + lock (_gate) + { + if (File.Exists(Path)) return; + if (System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(Path)) is { Length: > 0 } dir) Directory.CreateDirectory(dir); + WriteDurable(Path, []); + } + } + + public void Append(IReadOnlyList records) + { + if (records.Count == 0) return; + var sb = new StringBuilder(); + foreach (var r in records) sb.Append(JsonSerializer.Serialize(r, LedgerJsonContext.Default.LedgerRecord)).Append('\n'); + var bytes = Encoding.UTF8.GetBytes(sb.ToString()); + lock (_gate) + { + try + { + // Defence in depth: never append onto an unterminated line (Open() repairs torn tails first). + if (!_terminated && File.Exists(Path)) + { + var info = new FileInfo(Path); + if (info.Length > 0) + { + using var check = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + check.Seek(-1, SeekOrigin.End); + if (check.ReadByte() != '\n') + throw new IOException("ledger does not end with a newline; refusing to append (restart to repair the torn tail)"); + } + } + _terminated = false; + using (var fs = new FileStream(Path, FileMode.Append, FileAccess.Write, FileShare.Read)) + { + fs.Write(bytes); + fs.Flush(flushToDisk: true); + } + _terminated = true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Environment.FailFast($"covenant: budget ledger write failed ({ex.Message}) — halting rather than spending unrecorded."); + } + } + } + + private static void WriteDurable(string path, byte[] content) + { + using var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); + fs.Write(content); + fs.Flush(flushToDisk: true); + } +} + +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +[JsonSerializable(typeof(LedgerRecord))] +public partial class LedgerJsonContext : JsonSerializerContext; + +/// Budget state views (docs/ui-api-contract.md v2 "Budgets"). +public sealed class BudgetStateView +{ + [JsonPropertyName("id")] public required string Id { get; init; } + [JsonPropertyName("scope")] public required string Scope { get; init; } + [JsonPropertyName("period")] public required string Period { get; init; } + [JsonPropertyName("period_id")] public required string PeriodId { get; init; } + [JsonPropertyName("period_start_utc")] public DateTimeOffset? PeriodStartUtc { get; init; } + [JsonPropertyName("period_end_utc")] public DateTimeOffset? PeriodEndUtc { get; init; } + [JsonPropertyName("cap_usd")] public required decimal CapUsd { get; init; } + [JsonPropertyName("spent_usd")] public required decimal SpentUsd { get; init; } + [JsonPropertyName("reserved_usd")] public required decimal ReservedUsd { get; init; } + [JsonPropertyName("remaining_usd")] public required decimal RemainingUsd { get; init; } + [JsonPropertyName("warn_at")] public required List WarnAt { get; init; } + /// none | warn | critical | exceeded (status only — warnings never block; warn-only budgets never block). + [JsonPropertyName("warning")] public required string Warning { get; init; } + [JsonPropertyName("enforcement")] public required string Enforcement { get; init; } +} + +public sealed class BudgetContributionView +{ + [JsonPropertyName("request_id")] public required string RequestId { get; init; } + [JsonPropertyName("attempt_id")] public required string AttemptId { get; init; } + /// settle | settle-recovered | legacy-import. + [JsonPropertyName("kind")] public required string Kind { get; init; } + [JsonPropertyName("amount_usd")] public required decimal AmountUsd { get; init; } + [JsonPropertyName("ts_utc")] public required DateTimeOffset TsUtc { get; init; } + [JsonPropertyName("overrun")] public bool Overrun { get; init; } +} + +public sealed class BudgetRequestsView +{ + [JsonPropertyName("budget_id")] public required string BudgetId { get; init; } + [JsonPropertyName("scope")] public required string Scope { get; init; } + [JsonPropertyName("period_id")] public required string PeriodId { get; init; } + [JsonPropertyName("items")] public required List Items { get; init; } +} + +/// Read side of the ledger for the admin API and status (spend at read time, by scope and UTC period). +public static class BudgetViews +{ + public static string PeriodName(BudgetPeriod p) => p switch { BudgetPeriod.Daily => "daily", BudgetPeriod.Monthly => "monthly", _ => "none" }; + + public static BudgetStateView State(BudgetConfigV2 b, BudgetLedger ledger) + { + var now = ledger.Clock.GetUtcNow(); + var spent = ledger.Spent(b.Scope, b.Period); + var reserved = ledger.Reserved(b.Scope); + var (start, end) = BudgetPeriods.Window(b.Period, now); + return new BudgetStateView + { + Id = b.Id, + Scope = b.Scope, + Period = PeriodName(b.Period), + PeriodId = BudgetPeriods.PeriodId(b.Period, now), + PeriodStartUtc = b.Period == BudgetPeriod.None ? null : start, + PeriodEndUtc = b.Period == BudgetPeriod.None ? null : end, + CapUsd = b.CapUsd, + SpentUsd = spent, + ReservedUsd = reserved, + RemainingUsd = Math.Max(0m, b.CapUsd - spent - reserved), + WarnAt = b.WarnAt.ToList(), + Warning = Warning(b, spent), + Enforcement = b.Enforcement == BudgetEnforcement.WarnOnly ? "warn-only" : "hard", + }; + } + + /// exceeded when spent ≥ cap (with any spend); critical at the highest warn fraction; warn at the lowest. + public static string Warning(BudgetConfigV2 b, decimal spent) + { + if (b.CapUsd <= 0m) return spent > 0m ? "exceeded" : "none"; + if (spent >= b.CapUsd) return "exceeded"; + var ratio = spent / b.CapUsd; + var thresholds = b.WarnAt.OrderBy(x => x).ToList(); + if (thresholds.Count == 0) return "none"; + if (ratio >= thresholds[^1]) return "critical"; + if (ratio >= thresholds[0]) return "warn"; + return "none"; + } +} + +/// GET /admin/budgets and /admin/budgets/{id}/requests (docs/ui-api-contract.md v2 "Budgets"). Caps are edited +/// through /admin/config (an audited activation); these endpoints are read-only views of the ledger. +public static class BudgetApi +{ + private static IResult Error(string error, string reason, int status) + => Results.Json(new ErrorResponse { Error = error, Reason = reason }, CovenantJsonContext.Default.ErrorResponse, statusCode: status); + + public static void MapBudgets(this WebApplication app, IRuntimeConfig runtime, BudgetLedger ledger, Func authorized) + { + app.MapGet("/admin/budgets", (HttpContext http) => + { + if (!authorized(http)) return Error("unauthorized", "invalid admin token", StatusCodes.Status401Unauthorized); + http.Response.Headers.CacheControl = "no-store"; + var list = runtime.Current.Config.Budgets.Select(b => BudgetViews.State(b, ledger)).ToList(); + return Results.Json(list, CovenantJsonContext.Default.ListBudgetStateView); + }); + + app.MapGet("/admin/budgets/{id}/requests", (HttpContext http, string id, int? limit) => + { + if (!authorized(http)) return Error("unauthorized", "invalid admin token", StatusCodes.Status401Unauthorized); + http.Response.Headers.CacheControl = "no-store"; + var budget = runtime.Current.Config.Budgets.FirstOrDefault(b => string.Equals(b.Id, id, StringComparison.Ordinal)); + if (budget is null) return Error("not_found", "no budget with this id in the active configuration", StatusCodes.Status404NotFound); + var items = ledger.Contributions(budget.Scope, budget.Period, Math.Clamp(limit ?? 100, 1, 1000)) + .Select(c => new BudgetContributionView + { + RequestId = c.RequestId, AttemptId = c.AttemptId, Kind = c.Op, AmountUsd = c.AmountUsd, TsUtc = c.TsUtc, Overrun = c.Overrun, + }).ToList(); + return Results.Json(new BudgetRequestsView + { + BudgetId = budget.Id, + Scope = budget.Scope, + PeriodId = BudgetPeriods.PeriodId(budget.Period, ledger.Clock.GetUtcNow()), + Items = items, + }, CovenantJsonContext.Default.BudgetRequestsView); + }); + } +} diff --git a/src/Covenant.Host/ConsoleBackend.cs b/src/Covenant.Host/ConsoleBackend.cs index cd79874..fe3804b 100644 --- a/src/Covenant.Host/ConsoleBackend.cs +++ b/src/Covenant.Host/ConsoleBackend.cs @@ -260,6 +260,8 @@ public sealed class RequestsPage { [JsonPropertyName("segment")] public required SegmentInfo Segment { get; init; } [JsonPropertyName("items")] public required List Items { get; init; } + /// Opaque newest-first position of the next page of the SAME segment; null on the last page. + [JsonPropertyName("next_cursor")] public string? NextCursor { get; init; } } public sealed class SegmentInfo @@ -271,6 +273,9 @@ public sealed class SegmentInfo [JsonPropertyName("last_utc")] public DateTimeOffset? LastUtc { get; init; } /// Control-plane events in this segment (config.activated, …), excluded from Entries/items (v3). [JsonPropertyName("events")] public int Events { get; init; } + /// Opaque segment id (GET /admin/audit/segments): "current" or an archived segment's id. + [JsonPropertyName("id")] public string? Id { get; init; } + [JsonPropertyName("label")] public string? Label { get; init; } } public sealed class CatalogReport diff --git a/src/Covenant.Host/Evidence.cs b/src/Covenant.Host/Evidence.cs index bfa546b..ba477b9 100644 --- a/src/Covenant.Host/Evidence.cs +++ b/src/Covenant.Host/Evidence.cs @@ -129,8 +129,9 @@ public sealed class EvidenceReport [JsonPropertyName("last_anchor_utc")] public DateTimeOffset? LastAnchorUtc { get; init; } } -/// Durable budgets without new infrastructure: the audit log is the event store, the ledger its -/// projection rebuilt by replay at boot. Outgrowing replay is the trigger for the audit-store ADR — not before. +/// Pre-v2 projection of audit spend into an in-memory ledger (legacy compositions and tests). Since ADR-0014 +/// the Host no longer rebuilds budgets from the audit log: the persistent budget ledger is the source of accrued spend +/// (the current audit segment is imported into it once, when no ledger exists). public static class LedgerReplay { public static void Rebuild(IReadOnlyList entries, Covenant.Governance.ISpendLedger ledger) diff --git a/src/Covenant.Host/FailureClassifier.cs b/src/Covenant.Host/FailureClassifier.cs new file mode 100644 index 0000000..cd0adf8 --- /dev/null +++ b/src/Covenant.Host/FailureClassifier.cs @@ -0,0 +1,32 @@ +using System.ClientModel; +using Anthropic.Exceptions; +using Covenant.Adapters; +using Covenant.Core; + +namespace Covenant.Host; + +/// SDK-aware provider failure classification (ADR-0013; the Host knows the SDK types, the adapter layer does not). +/// +/// OpenAI / OpenAI-compatible / Ollama (OpenAI SDK 2.12, System.ClientModel 1.14): +/// (int; 0 when no response was received ⇒ connect). +/// Anthropic SDK 12.8.0 (types verified in the assembly metadata): +/// (System.Net.HttpStatusCode) on the API exception family (AnthropicRateLimitException, Anthropic5xxException, …); +/// (network I/O) ⇒ connect. +/// BCL: HttpRequestException (status or connect), SocketException ⇒ connect, TimeoutException / provider-side +/// cancellation ⇒ timeout (see ). +/// +/// 429 ⇒ "429"; 500/502/503/504 ⇒ "5xx"; any other status ⇒ "non_retryable" (400/401/403/404/422 are never retried). +public sealed class SdkProviderFailureClassifier : BclProviderFailureClassifier +{ + public static readonly SdkProviderFailureClassifier Shared = new(); + + protected override string? ClassifyOne(Exception e) => e switch + { + ClientResultException { Status: > 0 } cre => FromStatus(cre.Status), + ClientResultException { InnerException: not null } => null, // no response: classify the transport cause + ClientResultException => TraceReasons.Connect, + AnthropicApiException api => FromStatus((int)api.StatusCode), + AnthropicIOException => TraceReasons.Connect, + _ => base.ClassifyOne(e), + }; +} diff --git a/src/Covenant.Host/FileAuditSink.cs b/src/Covenant.Host/FileAuditSink.cs index 34d3d31..489050a 100644 --- a/src/Covenant.Host/FileAuditSink.cs +++ b/src/Covenant.Host/FileAuditSink.cs @@ -133,4 +133,6 @@ public interface IAuditEventWriter [JsonSourceGenerationOptions(Converters = [typeof(JsonStringEnumConverter), typeof(JsonStringEnumConverter)])] [JsonSerializable(typeof(AuditEntry))] [JsonSerializable(typeof(RequestsPage))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(RequestExport))] public partial class AuditJsonContext : JsonSerializerContext; diff --git a/src/Covenant.Host/InferenceEndpoints.cs b/src/Covenant.Host/InferenceEndpoints.cs new file mode 100644 index 0000000..c05970b --- /dev/null +++ b/src/Covenant.Host/InferenceEndpoints.cs @@ -0,0 +1,301 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using System.Text.Json.Serialization; +using Covenant.Core; +using Covenant.Governance; + +namespace Covenant.Host; + +/// The OpenAI chat-completions response contract (buffered JSON or SSE), shared by /v1/chat/completions +/// and the console endpoint POST /admin/playground/requests (ADR-0012) so both speak exactly the same wire and run +/// exactly the same governed pipeline. The caller has already built the canonical request and bound the configuration +/// snapshot (and, for the console, the server-resolved identity). +public static class ChatCompletions +{ + /// Runs the pipeline for and writes the response. The per-request trace buffer is + /// created BEFORE the pipeline starts (ADR-0013) so a subscriber that connects after submission still gets the + /// earliest events; it is completed when the pipeline has finished. + public static async Task RunAsync(HttpContext http, InferencePipeline pipe, InferenceContext ctx, TraceHub? traces, CancellationToken ct) + { + var request = ctx.Request; + var buffer = traces?.Begin(request.RequestId!, ctx.ConfigVersion, ctx.Configuration?.Config.Settings.TraceRetentionMinutes ?? 10); + if (buffer is not null) ctx.TraceSink = buffer.Append; + try + { + return await RunCoreAsync(http, pipe, ctx, ct); + } + finally + { + buffer?.Complete(traces!.Clock.GetUtcNow()); + } + } + + private static async Task RunCoreAsync(HttpContext http, InferencePipeline pipe, InferenceContext ctx, CancellationToken ct) + { + var request = ctx.Request; + + // --- Streamed mode (ADR-0002): SSE headers commit lazily on the FIRST delta, so a pre-flight denial still returns a plain JSON error below. --- + if (request.Stream) + { + var resp = http.Response; + var chunkId = request.RequestId!; + bool sseStarted = false; + + async ValueTask WriteChunkAsync(OpenAiChatChunk chunk, CancellationToken token) + { + var json = JsonSerializer.Serialize(chunk, CovenantJsonContext.Default.OpenAiChatChunk); + await resp.WriteAsync($"data: {json}\n\n", token); + await resp.Body.FlushAsync(token); + } + + // The model of the attempt actually streaming (an approved fallback may serve, ADR-0013). + OpenAiChatChunk Chunk(string? role, string? content, string? finish, OpenAiUsage? usage) => new() + { + Id = chunkId, + Model = ctx.Response?.ServedByModel ?? ctx.AttemptedModel ?? ctx.Policy?.Route?.ModelId ?? "", + Choices = [new OpenAiChunkChoice { Index = 0, Delta = new OpenAiDelta { Role = role, Content = content }, FinishReason = finish }], + Usage = usage, + }; + + ctx.DeltaSink = async (delta, token) => + { + if (!sseStarted) + { + sseStarted = true; + resp.StatusCode = StatusCodes.Status200OK; + resp.ContentType = "text/event-stream"; + resp.Headers.CacheControl = "no-cache"; + await WriteChunkAsync(Chunk("assistant", null, null, null), token); + } + await WriteChunkAsync(Chunk(null, delta.Content, null, null), token); + }; + + await pipe.ExecuteAsync(ctx, ct); + + if (!sseStarted) + { + // Denied before the first byte — same JSON error contract as buffered mode. + return DenialResult(ctx); + } + + if (ctx.IsDenied) + { + // Mid-stream failure after a committed 200: terminate with an error event (audited already). + var err = JsonSerializer.Serialize( + new ErrorResponse { Error = "upstream_error", Reason = ctx.DenialReason ?? "stream failed", RequestId = request.RequestId }, + CovenantJsonContext.Default.ErrorResponse); + await resp.WriteAsync($"data: {err}\n\n", ct); + } + else if (ctx.Response is { } finalResp) + { + await WriteChunkAsync(Chunk(null, null, "stop", new OpenAiUsage + { + PromptTokens = finalResp.Usage.InputTokens, + CompletionTokens = finalResp.Usage.OutputTokens, + TotalTokens = finalResp.Usage.TotalTokens, + }), ct); + } + + await resp.WriteAsync("data: [DONE]\n\n", ct); + await resp.Body.FlushAsync(ct); + return Results.Empty; + } + + await pipe.ExecuteAsync(ctx, ct); + + if (ctx.IsDenied || ctx.Response is null) + return DenialResult(ctx); + + var r = ctx.Response; + var dto = new OpenAiChatResponse + { + Id = request.RequestId, + Model = r.ServedByModel, + Choices = [new OpenAiChoice { Index = 0, Message = new OpenAiMessage { Role = "assistant", Content = OpenAiWire.TextElement(r.Message.Content) } }], + Usage = new OpenAiUsage + { + PromptTokens = r.Usage.InputTokens, + CompletionTokens = r.Usage.OutputTokens, + TotalTokens = r.Usage.TotalTokens + } + }; + return Results.Json(dto, CovenantJsonContext.Default.OpenAiChatResponse); + } + + /// No credentials → 401. Governance said no → 403. Upstream broke, refused fail-closed → 502. + public static IResult DenialResult(InferenceContext ctx) + { + var (error, status) = ctx.DenialKind switch + { + DenialKind.Unauthenticated => ("unauthenticated", StatusCodes.Status401Unauthorized), + DenialKind.UpstreamFailure => ("upstream_error", StatusCodes.Status502BadGateway), + DenialKind.RateLimited => ("rate_limited", StatusCodes.Status429TooManyRequests), + DenialKind.Unsupported => ("unsupported", StatusCodes.Status400BadRequest), + DenialKind.Cancelled => ("cancelled", 499), + _ => ("denied", StatusCodes.Status403Forbidden), + }; + return Results.Json( + new ErrorResponse { Error = error, Reason = ctx.DenialReason ?? "no response", RequestId = ctx.Request.RequestId }, + CovenantJsonContext.Default.ErrorResponse, statusCode: status); + } +} + +// ---- Console inference (ADR-0012) ---- + +public sealed class PlaygroundMessage +{ + [JsonPropertyName("role")] public string? Role { get; set; } + [JsonPropertyName("content")] public string? Content { get; set; } +} + +/// POST /admin/playground/requests body (docs/ui-api-contract.md v2 "Console inference"). +public sealed class PlaygroundRequest +{ + [JsonPropertyName("application_id")] public string? ApplicationId { get; set; } + [JsonPropertyName("profile_id")] public string? ProfileId { get; set; } + [JsonPropertyName("messages")] public List? Messages { get; set; } + [JsonPropertyName("model")] public string? Model { get; set; } + [JsonPropertyName("max_tokens")] public int? MaxTokens { get; set; } + [JsonPropertyName("stream")] public bool Stream { get; set; } + [JsonPropertyName("workflow")] public string? Workflow { get; set; } + [JsonPropertyName("use_case")] public string? UseCase { get; set; } + [JsonPropertyName("client_request_id")] public string? ClientRequestId { get; set; } +} + +/// client_request_id de-duplication (ADR-0012): a resubmission within 10 minutes is answered 409 with the ORIGINAL +/// request id — a browser reload never replays inference. Claimed atomically before the pipeline runs (two concurrent +/// submissions: exactly one runs). Bounded memory. +public sealed class ConsoleSubmissions(TimeProvider? clock = null, TimeSpan? window = null, int maxEntries = 10_000) +{ + private readonly TimeProvider _clock = clock ?? TimeProvider.System; + private readonly TimeSpan _window = window ?? TimeSpan.FromMinutes(10); + private readonly ConcurrentDictionary _seen = new(StringComparer.Ordinal); + + /// True ⇒ claimed for ; false ⇒ duplicate of . + public bool TryClaim(string clientRequestId, string requestId, out string originalRequestId) + { + var now = _clock.GetUtcNow(); + if (_seen.Count >= maxEntries) Sweep(now); + while (true) + { + if (_seen.TryAdd(clientRequestId, (requestId, now))) { originalRequestId = requestId; return true; } + if (_seen.TryGetValue(clientRequestId, out var existing)) + { + if (now - existing.At <= _window) { originalRequestId = existing.RequestId; return false; } + if (_seen.TryUpdate(clientRequestId, (requestId, now), existing)) { originalRequestId = requestId; return true; } + } + } + } + + private void Sweep(DateTimeOffset now) + { + foreach (var kv in _seen) + if (now - kv.Value.At > _window) _seen.TryRemove(kv.Key, out _); + if (_seen.Count < maxEntries) return; + foreach (var kv in _seen.OrderBy(kv => kv.Value.At).Take(_seen.Count - maxEntries + 1).ToList()) + _seen.TryRemove(kv.Key, out _); + } +} + +public static class PlaygroundApi +{ + public const int MaxMessages = 200; + public const int MaxContentChars = 200_000; + public const int MaxClientRequestIdChars = 128; + private const int MaxTagChars = 64; + + /// Body validation BEFORE governance (no audit record, 400). Returns the reason or null when valid. + public static string? Validate(PlaygroundRequest? body) + { + if (body is null) return "request body is required"; + if (string.IsNullOrWhiteSpace(body.ApplicationId)) return "application_id is required"; + if (body.ApplicationId.Length > 64) return "application_id is too long"; + if (body.ProfileId is { Length: > 64 }) return "profile_id is too long"; + if (body.Messages is not { Count: > 0 } messages) return "messages must be a non-empty array"; + if (messages.Count > MaxMessages) return $"at most {MaxMessages} messages"; + long chars = 0; + foreach (var m in messages) + { + if (m is null) return "a message is null"; + if (m.Role is not ("system" or "user" or "assistant")) return "message role must be system, user or assistant"; + if (m.Content is null) return "message content must be a string"; + chars += m.Content.Length; + } + if (chars > MaxContentChars) return $"messages exceed {MaxContentChars} characters"; + if (body.MaxTokens is < 1) return "max_tokens must be a positive integer"; + if (body.Model is { Length: > 200 }) return "model is too long"; + if (body.ClientRequestId is { } crid + && (crid.Length is 0 or > MaxClientRequestIdChars || !crid.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.' or ':'))) + return $"client_request_id must be 1–{MaxClientRequestIdChars} chars of [A-Za-z0-9-_.:]"; + return null; + } + + private static string Tag(string? value, string fallback) + { + var v = Evidence.Bounded(value); + if (v.Length == 0) return fallback; + return v.Length <= MaxTagChars ? v : v[..MaxTagChars]; + } + + private static ChatRole Role(string role) => role switch + { + "system" => ChatRole.System, + "assistant" => ChatRole.Assistant, + _ => ChatRole.User, + }; + + private static IResult Error(string error, string reason, int status, string? requestId = null) + => Results.Json(new ErrorResponse { Error = error, Reason = reason, RequestId = requestId }, CovenantJsonContext.Default.ErrorResponse, statusCode: status); + + /// POST /admin/playground/requests (ADR-0012): admin-authenticated; the application is resolved SERVER-SIDE and + /// bound with (a field the /v1 ingress can never set); the same + /// governed pipeline as /v1 then enforces enabled + console testing + profile grant (governed 403, audited). The + /// browser never holds or receives an application credential. + public static void MapPlayground(this WebApplication app, IRuntimeConfig runtime, TraceHub traces, ConsoleSubmissions submissions, + Func authorized) + { + app.MapPost("/admin/playground/requests", async Task (HttpContext http, InferencePipeline pipe, CancellationToken ct) => + { + if (!authorized(http)) return Error("unauthorized", "invalid admin token", StatusCodes.Status401Unauthorized); + var requestId = RequestCorrelation.NewId(); + http.Response.Headers[RequestCorrelation.Header] = requestId; + + PlaygroundRequest? body; + try + { + body = await JsonSerializer.DeserializeAsync(http.Request.Body, CovenantJsonContext.Default.PlaygroundRequest, ct); + } + catch (JsonException) + { + return Error("invalid_request", "malformed JSON — rejected before governance; no evidence record", StatusCodes.Status400BadRequest); + } + var invalid = Validate(body); + if (invalid is not null || body is null) + return Error("invalid_request", (invalid ?? "request body is required") + " — rejected before governance; no evidence record", + StatusCodes.Status400BadRequest); + + if (body.ClientRequestId is { } clientRequestId && !submissions.TryClaim(clientRequestId, requestId, out var original)) + { + http.Response.Headers[RequestCorrelation.Header] = original; + return Error("duplicate_submission", "this client_request_id was already submitted; it is not run again", StatusCodes.Status409Conflict, original); + } + + var appId = body.ApplicationId!.Trim(); + var request = new InferenceRequest( + Principal: "console:" + appId, + Messages: body.Messages!.Select(m => new ChatMessage(Role(m!.Role!), m.Content!)).ToList(), + RequestedModel: string.IsNullOrWhiteSpace(body.Model) ? null : body.Model.Trim(), + Attribution: new AttributionTags("unknown", Tag(body.Workflow, "console"), Tag(body.UseCase, "playground")), + Stream: body.Stream, + Credential: null, + MaxOutputTokens: body.MaxTokens, + RequestId: requestId, + RequestedProfile: string.IsNullOrWhiteSpace(body.ProfileId) ? null : body.ProfileId.Trim()); + var ctx = new InferenceContext(request); + using var lease = SnapshotLease.Bind(runtime, ctx); // ADR-0011: one configuration version for the whole request + var team = ctx.Configuration?.FindApplication(appId)?.Team ?? "unknown"; + ctx.BindConsoleIdentity(new PreAuthenticatedIdentity(appId, team, "console:" + appId), ConfigAuditEvents.SharedAdminOperator); + return await ChatCompletions.RunAsync(http, pipe, ctx, traces, ct); + }); + } +} diff --git a/src/Covenant.Host/OpenAiContracts.cs b/src/Covenant.Host/OpenAiContracts.cs index d176cc2..848587f 100644 --- a/src/Covenant.Host/OpenAiContracts.cs +++ b/src/Covenant.Host/OpenAiContracts.cs @@ -224,4 +224,8 @@ public sealed class ResetResponse [JsonSerializable(typeof(AnthropicMessagesRequest))] [JsonSerializable(typeof(AnthropicMessageResponse))] [JsonSerializable(typeof(AnthropicErrorResponse))] +// Console v2 (T04/T05): console inference body, budget views. +[JsonSerializable(typeof(PlaygroundRequest))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(BudgetRequestsView))] public partial class CovenantJsonContext : JsonSerializerContext; diff --git a/src/Covenant.Host/Program.cs b/src/Covenant.Host/Program.cs index 069ca3b..7c9e3b2 100644 --- a/src/Covenant.Host/Program.cs +++ b/src/Covenant.Host/Program.cs @@ -194,9 +194,7 @@ RuntimeSnapshot CompileSnapshot(CovenantConfig c) var auditSink = new FileAuditSink(auditPath, anchorPath, anchorEvery); var killSwitch = new KillSwitch(); -var spendLedger = new InMemorySpendLedger(); -// Budgets survive restarts: replay the audit log (event store) into the ledger (projection). // A tampered chain at boot is fail-closed — never serve on top of corrupted evidence. var (chainAtBoot, priorEntries) = AuditChainVerifier.VerifyAndRead(auditPath, anchorPath); if (!chainAtBoot.Valid) @@ -208,7 +206,47 @@ RuntimeSnapshot CompileSnapshot(CovenantConfig c) "Point Audit:Path at a fresh file to resume serving."); Environment.Exit(1); } -LedgerReplay.Rebuild(priorEntries, spendLedger); // control-plane events are skipped +// --- Budget ledger (ADR-0014): an append-only journal independent of audit segments (Budget:LedgerPath, default +// ".ledger.jsonl"). Replayed at boot; it — not the audit log — is the source of accrued spend, so an +// audit archive never reopens a budget and a configuration apply never resets one. No journal yet ⇒ the current +// audit segment's recorded spend is imported ONCE (legacy-import) into the global + team scopes. Reservations left +// open by a crash are settled at their reserved amount (settle-recovered) — never free capacity. --- +string ledgerPath = StartupValidation.Trimmed(builder.Configuration["Budget:LedgerPath"]) is { Length: > 0 } lp ? lp : auditPath + ".ledger.jsonl"; +var ledgerStore = new FileLedgerStore(ledgerPath); +var ledgerOpened = ledgerStore.Open(); +configErrors.AddRange(ledgerOpened.Errors); +FailIfConfigErrors(); +foreach (var w in ledgerOpened.Warnings) Console.Error.WriteLine($"covenant: warning — {w}"); +var budgetLedger = new BudgetLedger(ledgerStore, ledgerOpened.Records); +if (!ledgerOpened.Existed) +{ + var legacySpend = priorEntries + .Where(e => e.IsRequest() && e.Usage.CostUsd > 0m) // control-plane events never carry spend + .GroupBy(e => e.Tags.Team, StringComparer.OrdinalIgnoreCase) + .Select(g => (Team: g.Key, AmountUsd: g.Sum(e => e.Usage.CostUsd))) + .ToList(); + ledgerStore.EnsureCreated(); + budgetLedger.ImportLegacy(legacySpend); +} +var recoveredReservations = budgetLedger.RecoverUnsettled(); +if (recoveredReservations.Count > 0) + auditSink.TryWrite(new AuditEntry( + Id: $"bud_{Guid.NewGuid():n}", + TimestampUtc: DateTimeOffset.UtcNow, + Principal: "covenant-boot", + Tags: new AttributionTags("covenant", "budget", "recovery"), + Classification: DataClassification.Internal, + Effect: PolicyEffect.Allow, + Reason: $"budget.recovered: {recoveredReservations.Count} reservation(s) left open by an interrupted run settled at their reserved amount " + + $"({recoveredReservations.Sum(r => r.AmountUsd).ToString(System.Globalization.CultureInfo.InvariantCulture)} USD)", + ServedByModel: null, + Usage: Usage.Empty, + SchemaVersion: 2, + CostBasis: "no_call", + EventType: AuditEntryKinds.BudgetRecovered, + ConfigVersion: activeConfig.Version, + EntryPoint: "boot", + OperatorRef: "covenant-boot")); // ADR-0011: the active version's activation is evidenced in the chain. A fresh bootstrap records it; a crash // between pointer rename and audit append (no event for the active version) is recovered here, marked as such. @@ -222,6 +260,10 @@ RuntimeSnapshot CompileSnapshot(CovenantConfig c) // (ctx.Configuration); the constructor arguments below are only the fail-closed fallback for a context // without one (deny-all policy, zero budget), which the Host never produces. --- builder.Services.AddSingleton(runtime); +var traceHub = new TraceHub(); // ADR-0013: in-memory, bounded request traces +var consoleSubmissions = new ConsoleSubmissions(); // ADR-0012: client_request_id de-duplication (10 min) +builder.Services.AddSingleton(traceHub); +builder.Services.AddSingleton(budgetLedger); builder.Services.AddSingleton(new SnapshotChatClientRegistry(runtime)); var providerHealth = new ProviderHealth(); var probeAllowList = ProviderProbe.BuildAllowList(builder.Configuration["Providers:ProbeAllowList"], StartupValidation.Trimmed(builder.Configuration["Local:Endpoint"])); @@ -244,9 +286,11 @@ RuntimeSnapshot CompileSnapshot(CovenantConfig c) new PolicyStage(new PolicyEngine(denyAllPolicy)),// policy v2 on the bound snapshot, fail-closed new CacheStage(responseCache, new CacheConfig()),// cache before budget/provider: a hit skips the model call new RateLimitStage(rateCounterGlobal, rateCounterTeams, new RateLimitConfig()), // rate half of budget/rate; cache hits bypass (free) - new BudgetStage(killSwitch, spendLedger, new BudgetConfig { GlobalCapUsd = 0m }, noPrices), // pause + caps; charges failed calls on unwind + new PauseStage(killSwitch), // global provider-call pause (after cache: a hit is served during a pause) + new BudgetStage(killSwitch, budgetLedger), // ADR-0014: scopes + atomic reservation of attempt 1; gate for fallbacks new ProviderCallStage(liveRegistry, providerHealth, - preferRequestClients: liveRegistry is SnapshotChatClientRegistry), // route + provider call on the request's snapshot clients + preferRequestClients: liveRegistry is SnapshotChatClientRegistry, + classifier: SdkProviderFailureClassifier.Shared), // approved fallback over the request's snapshot clients (ADR-0013) new AttributionStage(noPrices), // attribute cost (connection-scoped price book of the snapshot) ]); }); @@ -306,6 +350,9 @@ RuntimeSnapshot CompileSnapshot(CovenantConfig c) var ctx = new InferenceContext(request); using var lease = SnapshotLease.Bind(runtime, ctx); // ADR-0011: one configuration version for the whole request var msgId = requestId; + var traceBuffer = traceHub.Begin(requestId, ctx.ConfigVersion, ctx.Configuration?.Config.Settings.TraceRetentionMinutes ?? 10); + ctx.TraceSink = traceBuffer.Append; // created BEFORE the pipeline starts (ADR-0013) + using var traceDone = new TraceCompletion(traceBuffer, traceHub.Clock); if (request.Stream) { @@ -326,7 +373,7 @@ async ValueTask WriteEventAsync(string evt, string json, CancellationToken token resp.StatusCode = StatusCodes.Status200OK; resp.ContentType = "text/event-stream"; resp.Headers.CacheControl = "no-cache"; - await WriteEventAsync("message_start", AnthropicWire.MessageStartEvent(msgId, ctx.Policy?.Route?.ModelId ?? ""), token); + await WriteEventAsync("message_start", AnthropicWire.MessageStartEvent(msgId, ctx.AttemptedModel ?? ctx.Policy?.Route?.ModelId ?? ""), token); await WriteEventAsync("content_block_start", AnthropicWire.ContentBlockStartEvent, token); } await WriteEventAsync("content_block_delta", AnthropicWire.ContentBlockDeltaEvent(delta.Content), token); @@ -385,7 +432,7 @@ async ValueTask WriteEventAsync(string evt, string json, CancellationToken token }); app.MapPost("/v1/chat/completions", - async (OpenAiChatRequest body, InferencePipeline pipe, HttpContext http, CancellationToken ct) => + async Task (OpenAiChatRequest body, InferencePipeline pipe, HttpContext http, CancellationToken ct) => { // Bearer key for the auth stage. OpenAI SDK clients pointed at Covenant send their configured // api-key here automatically — a virtual key drops into existing tooling unchanged. @@ -414,111 +461,9 @@ async ValueTask WriteEventAsync(string evt, string json, CancellationToken token var ctx = new InferenceContext(request); using var lease = SnapshotLease.Bind(runtime, ctx); // ADR-0011: one configuration version for the whole request - - // --- Streamed mode (ADR-0002): SSE headers commit lazily on the FIRST delta, so a pre-flight denial still returns a plain JSON error below. --- - if (request.Stream) - { - var resp = http.Response; - var chunkId = request.RequestId!; - bool sseStarted = false; - - async ValueTask WriteChunkAsync(OpenAiChatChunk chunk, CancellationToken token) - { - var json = System.Text.Json.JsonSerializer.Serialize(chunk, CovenantJsonContext.Default.OpenAiChatChunk); - await resp.WriteAsync($"data: {json}\n\n", token); - await resp.Body.FlushAsync(token); - } - - OpenAiChatChunk Chunk(string? role, string? content, string? finish, OpenAiUsage? usage) => new() - { - Id = chunkId, - Model = ctx.Policy?.Route?.ModelId ?? "", - Choices = [new OpenAiChunkChoice { Index = 0, Delta = new OpenAiDelta { Role = role, Content = content }, FinishReason = finish }], - Usage = usage, - }; - - ctx.DeltaSink = async (delta, token) => - { - if (!sseStarted) - { - sseStarted = true; - resp.StatusCode = StatusCodes.Status200OK; - resp.ContentType = "text/event-stream"; - resp.Headers.CacheControl = "no-cache"; - await WriteChunkAsync(Chunk("assistant", null, null, null), token); - } - await WriteChunkAsync(Chunk(null, delta.Content, null, null), token); - }; - - await pipe.ExecuteAsync(ctx, ct); - - if (!sseStarted) - { - // Denied before the first byte — same JSON error contract as buffered mode. - return DenialResult(ctx); - } - - if (ctx.IsDenied) - { - // Mid-stream failure after a committed 200: terminate with an error event (audited already). - var err = System.Text.Json.JsonSerializer.Serialize( - new ErrorResponse { Error = "upstream_error", Reason = ctx.DenialReason ?? "stream failed", RequestId = request.RequestId }, - CovenantJsonContext.Default.ErrorResponse); - await resp.WriteAsync($"data: {err}\n\n", ct); - } - else if (ctx.Response is { } finalResp) - { - await WriteChunkAsync(Chunk(null, null, "stop", new OpenAiUsage - { - PromptTokens = finalResp.Usage.InputTokens, - CompletionTokens = finalResp.Usage.OutputTokens, - TotalTokens = finalResp.Usage.TotalTokens, - }), ct); - } - - await resp.WriteAsync("data: [DONE]\n\n", ct); - await resp.Body.FlushAsync(ct); - return Results.Empty; - } - - await pipe.ExecuteAsync(ctx, ct); - - if (ctx.IsDenied || ctx.Response is null) - return DenialResult(ctx); - - var r = ctx.Response; - var dto = new OpenAiChatResponse - { - Id = request.RequestId, - Model = r.ServedByModel, - Choices = [new OpenAiChoice { Index = 0, Message = new OpenAiMessage { Role = "assistant", Content = OpenAiWire.TextElement(r.Message.Content) } }], - Usage = new OpenAiUsage - { - PromptTokens = r.Usage.InputTokens, - CompletionTokens = r.Usage.OutputTokens, - TotalTokens = r.Usage.TotalTokens - } - }; - return Results.Json(dto, CovenantJsonContext.Default.OpenAiChatResponse); + return await ChatCompletions.RunAsync(http, pipe, ctx, traceHub, ct); // same contract as console inference }); -// No credentials → 401. Governance said no → 403. Upstream broke, refused fail-closed → 502. -static IResult DenialResult(InferenceContext ctx) -{ - var (error, status) = ctx.DenialKind switch - { - DenialKind.Unauthenticated => ("unauthenticated", StatusCodes.Status401Unauthorized), - DenialKind.UpstreamFailure => ("upstream_error", StatusCodes.Status502BadGateway), - DenialKind.RateLimited => ("rate_limited", StatusCodes.Status429TooManyRequests), - DenialKind.Unsupported => ("unsupported", StatusCodes.Status400BadRequest), - DenialKind.Cancelled => ("cancelled", 499), - _ => ("denied", StatusCodes.Status403Forbidden), - }; - return Results.Json( - new ErrorResponse { Error = error, Reason = ctx.DenialReason ?? "no response", RequestId = ctx.Request.RequestId }, - CovenantJsonContext.Default.ErrorResponse, statusCode: status); -} - // Anthropic-dialect denial: same DenialKind semantics, Anthropic's error taxonomy and statuses. static IResult AnthropicDenial(InferenceContext ctx) { @@ -607,7 +552,11 @@ StatusReport BuildStatus() var cfg = snapshot.Config; var (verification, entries) = AuditChainVerifier.VerifyAndRead(auditPath, anchorPath); var anchorInfo = AnchorInfo.Read(anchorPath); - var teamSpend = spendLedger.SnapshotByTeam(); + // Spend comes from the budget ledger (ADR-0014): the global budget's current period; teams over the same period. + var globalBudget = cfg.Budgets.FirstOrDefault(b => b.Scope == "global"); + var statusPeriod = globalBudget?.Period ?? BudgetPeriod.None; + var teamSpend = budgetLedger.SpentByScopePrefix("team:", statusPeriod) + .ToDictionary(kv => kv.Key["team:".Length..], kv => kv.Value, StringComparer.OrdinalIgnoreCase); var teamCaps = cfg.Budgets .Where(b => b.Scope.StartsWith("team:", StringComparison.Ordinal)) @@ -628,7 +577,9 @@ StatusReport BuildStatus() // where no savings are claimed). The "local" model for the local split is the first local-boundary model. var localModel = cfg.Connections.Where(c => c.Boundary == Boundary.Local).SelectMany(c => c.Models).Select(m => m.ModelId).FirstOrDefault() ?? LegacyImport.UnconfiguredLocalModel; - var baselineModel = cfg.SavingsBaseline?.ModelId ?? localModel; + // Savings only against a configured, PRICED baseline (spec §4.5); otherwise hidden (null) and every legacy figure is 0. + var baseline = cfg.SavingsBaseline is { } sb && snapshot.FindModel(sb.ConnectionId, sb.ModelId)?.Price is not null ? sb : null; + var baselineModel = baseline?.ModelId ?? localModel; return new StatusReport { @@ -637,12 +588,12 @@ StatusReport BuildStatus() KillSwitch = new KillSwitchState { Engaged = killSwitch.IsTripped, Reason = killSwitch.Reason }, Budget = new BudgetStatus { - GlobalCapUsd = cfg.Budgets.FirstOrDefault(b => b.Scope == "global")?.CapUsd ?? 0m, - GlobalSpendUsd = spendLedger.GlobalSpendUsd, + GlobalCapUsd = globalBudget?.CapUsd ?? 0m, + GlobalSpendUsd = budgetLedger.Spent("global", statusPeriod), Teams = teams, }, Routes = routes, - FinOps = FinOps.Build(entries, localModel, baselineModel, PricesByModel(cfg)), + FinOps = FinOps.Build(entries, localModel, baselineModel, PricesByModel(cfg), baseline?.ToString()), ChainValid = verification.Valid, AuditEntries = verification.EntryCount, Auth = new AuthStatus { AllowAnonymous = allowAnonymous, KeyCount = apiKeys.Count }, @@ -695,14 +646,14 @@ StatusReport BuildStatus() return Results.Empty; }); -// Demo/ops reset: ARCHIVES the audit log (rename — evidence is never deleted) and clears the ledger -// together, so ledger and evidence stay consistent; the archived chain remains verifiable. +// Audit archive: ARCHIVES the audit log (rename — evidence is never deleted); the archived chain remains verifiable and +// navigable (GET /admin/audit/segments). It is NOT a budget operation: the budget ledger is independent of audit segments +// (ADR-0014), so an archive never reopens a budget or erases accrued spend. app.MapPost("/admin/reset", async (HttpContext http) => { if (!Authorized(http)) return Unauthorized(); var archived = await auditSink.RotateAsync(); - spendLedger.Reset(); return Results.Json( new ResetResponse { ArchivedTo = archived }, CovenantJsonContext.Default.ResetResponse); @@ -710,30 +661,7 @@ StatusReport BuildStatus() // ---- Console API (docs/ui-api-contract.md) ---- -// Recent evidence: newest-first records of the CURRENT audit segment (since the last archive), bounded. -// Not a historical search — the response says which segment it covers. -app.MapGet("/admin/requests", (HttpContext http, int? limit) => -{ - if (!Authorized(http)) return Unauthorized(); - http.Response.Headers.CacheControl = "no-store"; - var (verification, all) = AuditChainVerifier.VerifyAndRead(auditPath, anchorPath); - var entries = all.Where(e => e.IsRequest()).ToList(); // v3: control-plane events → GET /admin/config/versions - int take = Math.Clamp(limit ?? 200, 1, 1000); - var page = new RequestsPage - { - Segment = new SegmentInfo - { - Path = Path.GetFullPath(auditPath), - Entries = entries.Count, - ChainValid = verification.Valid, - FirstUtc = entries.Count > 0 ? entries[0].TimestampUtc : null, - LastUtc = entries.Count > 0 ? entries[^1].TimestampUtc : null, - Events = all.Count - entries.Count, - }, - Items = Enumerable.Reverse(entries).Take(take).ToList(), - }; - return Results.Json(page, AuditJsonContext.Default.RequestsPage); -}); +// Recent evidence (GET /admin/requests?limit=&cursor=&segment=), segments and export: see ArchiveApi (AuditSegments.cs). // Exact lookup by correlation id (== audit Id). 404 means "not in the current segment yet" — the sink // is asynchronous, so a caller polls briefly before concluding "unavailable"; it is never proof that an @@ -897,6 +825,11 @@ StatusReport BuildStatus() Authorized = Authorized, }); +app.MapPlayground(runtime, traceHub, consoleSubmissions, Authorized); // ADR-0012 console inference +app.MapTrace(traceHub, Authorized); // ADR-0013 request trace +app.MapBudgets(runtime, budgetLedger, Authorized); // ADR-0014 budget state +app.MapArchive(new AuditSegments(auditPath, anchorPath), Authorized, anchorPath); // spec §5 archive + export + app.MapConsole(); app.Run(); diff --git a/src/Covenant.Host/StatusContracts.cs b/src/Covenant.Host/StatusContracts.cs index 111e080..da3dac3 100644 --- a/src/Covenant.Host/StatusContracts.cs +++ b/src/Covenant.Host/StatusContracts.cs @@ -95,6 +95,25 @@ public sealed class FinOpsSummary /// Newest-first metadata for the live feed. Deliberately NO message content — the admin /// plane never sees prompts or responses; that is a product guarantee, not an omission. [JsonPropertyName("recent")] public required List Recent { get; init; } + /// "Estimated provider charge avoided" (spec §4.5, ADR-0014) — present ONLY when the active configuration names a + /// priced savings baseline; null (hidden) otherwise. When null, the legacy estimated_savings_* fields above are 0. + [JsonPropertyName("savings")] public SavingsSummary? Savings { get; init; } +} + +/// Counterfactual: every allowed request with KNOWN usage (reported / zero-priced / cache no-call) priced on the +/// configured baseline connection/model. Route-avoided = baseline price − served model price (route selection, incl. +/// local); cache-avoided = the served model's charge a cache hit did not incur. Records with estimated or unknown cost are +/// excluded and counted. An estimate of provider charges only — not total business savings, not evidence of equal answer +/// quality. +public sealed class SavingsSummary +{ + [JsonPropertyName("label")] public string Label { get; init; } = "Estimated provider charge avoided"; + /// "connection/model" of the configured baseline. + [JsonPropertyName("baseline")] public required string Baseline { get; init; } + [JsonPropertyName("route_avoided_usd")] public required decimal RouteAvoidedUsd { get; init; } + [JsonPropertyName("cache_avoided_usd")] public required decimal CacheAvoidedUsd { get; init; } + [JsonPropertyName("total_usd")] public required decimal TotalUsd { get; init; } + [JsonPropertyName("excluded_records")] public required int ExcludedRecords { get; init; } } public sealed class ActivityBucket @@ -166,7 +185,20 @@ public static FinOpsSummary Build( string localModelId, string strongModelId, IReadOnlyDictionary prices) + => Build(entries, localModelId, strongModelId, prices, savingsBaseline: null, legacySavings: true); + + /// v2: savings are reported only against a configured, priced baseline ( + /// = "connection/model"); without one every savings figure is 0 and is null. + /// keeps the pre-v2 behaviour (strong model as implicit baseline) for direct callers. + public static FinOpsSummary Build( + IReadOnlyList entries, + string localModelId, + string strongModelId, + IReadOnlyDictionary prices, + string? savingsBaseline, + bool legacySavings = false) { + bool savingsShown = legacySavings || savingsBaseline is not null; // v3: control-plane events (config.activated, …) are not requests — no counts, spend or activity. if (entries.Any(e => !e.IsRequest())) entries = entries.Where(e => e.IsRequest()).ToList(); var strongPrice = prices.GetValueOrDefault(strongModelId); @@ -242,8 +274,18 @@ public static FinOpsSummary Build( } } + int excluded = entries.Count(e => e.Effect == PolicyEffect.Allow && !(e.CostBasis is null or "reported" or "zero_priced" or "no_call")); + if (!savingsShown) savingsLocal = savingsRouter = savingsCache = 0m; return new FinOpsSummary { + Savings = savingsBaseline is null ? null : new SavingsSummary + { + Baseline = savingsBaseline, + RouteAvoidedUsd = savingsLocal + savingsRouter, + CacheAvoidedUsd = savingsCache, + TotalUsd = savingsLocal + savingsRouter + savingsCache, + ExcludedRecords = excluded, + }, Requests = entries.Count, Allowed = allowed, Denied = denied, diff --git a/src/Covenant.Host/Trace.cs b/src/Covenant.Host/Trace.cs new file mode 100644 index 0000000..c6adef0 --- /dev/null +++ b/src/Covenant.Host/Trace.cs @@ -0,0 +1,283 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +using Covenant.Core; + +namespace Covenant.Host; + +/// Wire shape of one trace event (docs/ui-api-contract.md v2 "Trace"). No content, no credentials, no +/// provider free text: stage/state/bounded reason code/target identity only. +public sealed class TraceEventView +{ + [JsonPropertyName("seq")] public required long Seq { get; init; } + [JsonPropertyName("request_id")] public required string RequestId { get; init; } + [JsonPropertyName("config_version")] public int? ConfigVersion { get; init; } + [JsonPropertyName("stage")] public required string Stage { get; init; } + [JsonPropertyName("attempt_id")] public string? AttemptId { get; init; } + [JsonPropertyName("state")] public required string State { get; init; } + [JsonPropertyName("ts_utc")] public required DateTimeOffset TsUtc { get; init; } + [JsonPropertyName("duration_ms")] public double? DurationMs { get; init; } + [JsonPropertyName("reason_code")] public string? ReasonCode { get; init; } + [JsonPropertyName("target")] public string? Target { get; init; } +} + +public sealed class TraceSnapshotView +{ + [JsonPropertyName("request_id")] public required string RequestId { get; init; } + [JsonPropertyName("config_version")] public int? ConfigVersion { get; init; } + [JsonPropertyName("complete")] public required bool Complete { get; init; } + /// True when more than the per-request bound of events was emitted (later ones were dropped). + [JsonPropertyName("truncated")] public bool Truncated { get; init; } + [JsonPropertyName("events")] public required List Events { get; init; } +} + +[JsonSourceGenerationOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] +[JsonSerializable(typeof(TraceEventView))] +[JsonSerializable(typeof(TraceSnapshotView))] +public partial class TraceJsonContext : JsonSerializerContext; + +/// Per-request event buffer. Created by the Host BEFORE the pipeline starts, so the earliest stage events are +/// retained for a subscriber that connects after submission. Sequence numbers are monotonic from 1 in emission order; +/// clients de-duplicate by seq. Thread-safe (the pipeline appends while SSE readers wait). +public sealed class TraceBuffer +{ + private readonly object _gate = new(); + private readonly List _events = []; + private readonly int _maxEvents; + private TaskCompletionSource _changed = new(TaskCreationOptions.RunContinuationsAsynchronously); + + internal TraceBuffer(string requestId, int? configVersion, TimeSpan ttl, DateTimeOffset createdUtc, int maxEvents) + { + RequestId = requestId; + ConfigVersion = configVersion; + Ttl = ttl; + CreatedUtc = createdUtc; + _maxEvents = maxEvents; + } + + public string RequestId { get; } + public int? ConfigVersion { get; } + public TimeSpan Ttl { get; } + public DateTimeOffset CreatedUtc { get; } + public DateTimeOffset? CompletedUtc { get; private set; } + public bool Truncated { get; private set; } + + public bool IsComplete + { + get { lock (_gate) return CompletedUtc is not null; } + } + + public void Append(PipelineTraceEvent e) + { + TaskCompletionSource signal; + lock (_gate) + { + if (CompletedUtc is not null) return; + if (_events.Count >= _maxEvents) { Truncated = true; return; } + _events.Add(new TraceEventView + { + Seq = _events.Count + 1, + RequestId = RequestId, + ConfigVersion = ConfigVersion, + Stage = e.Stage, + AttemptId = e.AttemptId, + State = e.State, + TsUtc = e.TsUtc, + DurationMs = e.DurationMs is { } d ? Math.Round(d, 3) : null, + ReasonCode = e.ReasonCode, + Target = e.Target, + }); + signal = _changed; + _changed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } + signal.TrySetResult(); + } + + public void Complete(DateTimeOffset utc) + { + TaskCompletionSource signal; + lock (_gate) + { + if (CompletedUtc is not null) return; + CompletedUtc = utc; + signal = _changed; + } + signal.TrySetResult(); + } + + /// Events with seq > , whether the run is complete, and a task that completes on + /// the next change (taken atomically with the read, so no event can slip between read and wait). + public (List Events, bool Complete, Task Changed) Since(long afterSeq) + { + lock (_gate) + { + var list = _events.Where(e => e.Seq > afterSeq).ToList(); + return (list, CompletedUtc is not null, _changed.Task); + } + } + + public TraceSnapshotView Snapshot() + { + lock (_gate) + return new TraceSnapshotView + { + RequestId = RequestId, ConfigVersion = ConfigVersion, Complete = CompletedUtc is not null, + Truncated = Truncated, Events = _events.ToList(), + }; + } + + internal bool IsExpired(DateTimeOffset now) => CompletedUtc is { } done && now - done > Ttl; +} + +/// In-memory trace registry (ADR-0013): ≤ maxRequests buffers (oldest completed evicted first), ≤ 64 events +/// each, retention = the request's configuration trace_retention_minutes after completion. Expired ids are +/// remembered (bounded) so the API can answer 410 Gone rather than 404 for them. Never persisted — the audit record holds +/// the compact durable summary. +public sealed class TraceHub(TimeProvider? clock = null, int maxRequests = 2000, int maxEventsPerRequest = InferenceContext.MaxTraceEvents) +{ + private const int MaxRememberedExpired = 4000; + private readonly TimeProvider _clock = clock ?? TimeProvider.System; + private readonly object _gate = new(); + private readonly Dictionary _buffers = new(StringComparer.Ordinal); + private readonly LinkedList _order = new(); + private readonly HashSet _expired = new(StringComparer.Ordinal); + private readonly Queue _expiredOrder = new(); + + public TimeProvider Clock => _clock; + + public TraceBuffer Begin(string requestId, int? configVersion, int retentionMinutes) + { + var ttl = TimeSpan.FromMinutes(Math.Clamp(retentionMinutes, 1, 1440)); + var buffer = new TraceBuffer(requestId, configVersion, ttl, _clock.GetUtcNow(), maxEventsPerRequest); + lock (_gate) + { + Sweep(); + if (_buffers.Remove(requestId)) _order.Remove(requestId); + _buffers[requestId] = buffer; + _order.AddLast(requestId); + while (_buffers.Count > maxRequests) EvictOne(); + } + return buffer; + } + + public enum Lookup { Found, Unknown, Expired } + + public Lookup TryGet(string requestId, out TraceBuffer? buffer) + { + lock (_gate) + { + Sweep(); + if (_buffers.TryGetValue(requestId, out buffer)) return Lookup.Found; + return _expired.Contains(requestId) ? Lookup.Expired : Lookup.Unknown; + } + } + + private void Sweep() + { + var now = _clock.GetUtcNow(); + var expired = _buffers.Values.Where(b => b.IsExpired(now)).Select(b => b.RequestId).ToList(); + foreach (var id in expired) Forget(id); + } + + private void EvictOne() + { + // Oldest COMPLETED first; only when every buffer is still running is the oldest running one dropped. + string? victim = null; + foreach (var id in _order) + if (_buffers[id].IsComplete) { victim = id; break; } + victim ??= _order.First?.Value; + if (victim is not null) Forget(victim); + } + + private void Forget(string id) + { + _buffers.Remove(id); + _order.Remove(id); + if (_expired.Add(id)) + { + _expiredOrder.Enqueue(id); + while (_expiredOrder.Count > MaxRememberedExpired) _expired.Remove(_expiredOrder.Dequeue()); + } + } +} + +/// GET /admin/requests/{id}/trace (snapshot) and /trace/stream (SSE replay-then-live, Last-Event-ID resume, +/// event: end on completion; 404 unknown, 410 expired). Admin token required. AOT-safe (source-generated JSON). +public static class TraceApi +{ + private static readonly TimeSpan Heartbeat = TimeSpan.FromSeconds(15); + + private static IResult Error(string error, string reason, int status, string? requestId = null) + => Results.Json(new ErrorResponse { Error = error, Reason = reason, RequestId = requestId }, CovenantJsonContext.Default.ErrorResponse, statusCode: status); + + private static IResult? Missing(TraceHub.Lookup lookup, string id) => lookup switch + { + TraceHub.Lookup.Expired => Error("expired", "the transient trace for this request has expired; the audit record keeps the compact summary", StatusCodes.Status410Gone, id), + TraceHub.Lookup.Unknown => Error("not_found", "no trace for this request id (unknown, or never traced by this process)", StatusCodes.Status404NotFound, id), + _ => null, + }; + + public static void MapTrace(this WebApplication app, TraceHub hub, Func authorized) + { + app.MapGet("/admin/requests/{id}/trace", (HttpContext http, string id) => + { + if (!authorized(http)) return Error("unauthorized", "invalid admin token", StatusCodes.Status401Unauthorized); + http.Response.Headers.CacheControl = "no-store"; + if (!RequestCorrelation.IsWellFormed(id)) + return Error("invalid_id", "request id must be ≤64 chars of [A-Za-z0-9_-]", StatusCodes.Status400BadRequest); + var lookup = hub.TryGet(id, out var buffer); + if (Missing(lookup, id) is { } missing) return missing; + return Results.Json(buffer!.Snapshot(), TraceJsonContext.Default.TraceSnapshotView); + }); + + app.MapGet("/admin/requests/{id}/trace/stream", async Task (HttpContext http, string id, CancellationToken ct) => + { + if (!authorized(http)) return Error("unauthorized", "invalid admin token", StatusCodes.Status401Unauthorized); + if (!RequestCorrelation.IsWellFormed(id)) + return Error("invalid_id", "request id must be ≤64 chars of [A-Za-z0-9_-]", StatusCodes.Status400BadRequest); + var lookup = hub.TryGet(id, out var buffer); + if (Missing(lookup, id) is { } missing) return missing; + + long after = 0; + if (http.Request.Headers["Last-Event-ID"].FirstOrDefault() is { Length: > 0 } last + && long.TryParse(last, NumberStyles.None, CultureInfo.InvariantCulture, out var parsed) && parsed > 0) + after = parsed; + + var resp = http.Response; + resp.StatusCode = StatusCodes.Status200OK; + resp.ContentType = "text/event-stream"; + resp.Headers.CacheControl = "no-store"; + try + { + while (!ct.IsCancellationRequested) + { + var (events, complete, changed) = buffer!.Since(after); + foreach (var e in events) + { + var json = JsonSerializer.Serialize(e, TraceJsonContext.Default.TraceEventView); + await resp.WriteAsync($"id: {e.Seq.ToString(CultureInfo.InvariantCulture)}\ndata: {json}\n\n", ct); + after = e.Seq; + } + if (complete) + { + await resp.WriteAsync("event: end\ndata: {}\n\n", ct); + await resp.Body.FlushAsync(ct); + break; + } + await resp.Body.FlushAsync(ct); + var finished = await Task.WhenAny(changed, Task.Delay(Heartbeat, ct)); + if (finished != changed && !ct.IsCancellationRequested) + await resp.WriteAsync(": keep-alive\n\n", ct); + } + } + catch (OperationCanceledException) { /* subscriber went away — normal */ } + return Results.Empty; + }); + } +} + +/// Completes a request's trace buffer when the handler finishes (using-scope helper for multi-return handlers). +public sealed class TraceCompletion(TraceBuffer buffer, TimeProvider clock) : IDisposable +{ + public void Dispose() => buffer.Complete(clock.GetUtcNow()); +} diff --git a/tests/Covenant.Tests/ArchiveExportTests.cs b/tests/Covenant.Tests/ArchiveExportTests.cs new file mode 100644 index 0000000..1769898 --- /dev/null +++ b/tests/Covenant.Tests/ArchiveExportTests.cs @@ -0,0 +1,179 @@ +using System.Net; +using System.Text.Json; +using Covenant.Core; +using Covenant.Host; +using Xunit; + +namespace Covenant.Tests; + +/// Spec §5 archive navigation: segments are the current audit file plus its archived siblings, addressed only by +/// opaque ids from the enumerated set (no caller paths); cursor pagination per segment; per-request export without +/// prompt/response content. +public sealed class ArchiveExportTests : IDisposable +{ + private readonly RestartableHybridFactory _factory = new(RestartableHybridFactory.NewAuditPath()); + private readonly HttpClient _admin; + + public ArchiveExportTests() => _admin = _factory.CreateClient(); + + public void Dispose() => _factory.Dispose(); + + private async Task RunAsync(string prompt) + { + using var resp = await Playground.PostAsync(_admin, Playground.Body("demo-app", prompt)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + await CorrelationTestKit.LookupAsync(_admin, id); + return id; + } + + private async Task<(HttpStatusCode, JsonElement)> GetAsync(string path) + { + var (status, body, _) = await V2Admin.SendAsync(_admin, HttpMethod.Get, path); + return (status, body); + } + + [Fact] + public async Task Segments_enumerate_current_and_archived_and_requests_page_through_one_segment_by_cursor() + { + var old1 = await RunAsync("first request before the archive"); + var old2 = await RunAsync("second request before the archive"); + var (resetStatus, _, _) = await V2Admin.SendAsync(_admin, HttpMethod.Post, "/admin/reset"); + Assert.Equal(HttpStatusCode.OK, resetStatus); + var current = await RunAsync("after the archive"); + + var (status, segments) = await GetAsync("/admin/audit/segments"); + Assert.Equal(HttpStatusCode.OK, status); + var list = segments.EnumerateArray().ToList(); + Assert.Equal(2, list.Count); + Assert.Equal("current", list[0].GetProperty("id").GetString()); + Assert.True(list[0].GetProperty("current").GetBoolean()); + Assert.Equal(1, list[0].GetProperty("entries").GetInt32()); + var archivedId = list[1].GetProperty("id").GetString()!; + Assert.Matches("^a-[0-9a-f]{16}$", archivedId); // opaque: no path, no file name + Assert.Equal(2, list[1].GetProperty("entries").GetInt32()); + Assert.True(list[1].GetProperty("chain_valid").GetBoolean()); + Assert.DoesNotContain(Path.GetDirectoryName(_factory.AuditPath)!, segments.GetRawText(), StringComparison.Ordinal); + + var (_, page1) = await GetAsync($"/admin/requests?segment={archivedId}&limit=1"); + Assert.Equal(archivedId, page1.GetProperty("segment").GetProperty("id").GetString()); + Assert.Equal(old2, page1.GetProperty("items")[0].GetProperty("Id").GetString()); // newest first + var cursor = page1.GetProperty("next_cursor").GetString()!; + var (_, page2) = await GetAsync($"/admin/requests?cursor={Uri.EscapeDataString(cursor)}&limit=1"); + Assert.Equal(old1, page2.GetProperty("items")[0].GetProperty("Id").GetString()); + Assert.Equal(JsonValueKind.Null, page2.GetProperty("next_cursor").ValueKind); + + var (_, now) = await GetAsync("/admin/requests"); + Assert.Equal(current, Assert.Single(now.GetProperty("items").EnumerateArray()).GetProperty("Id").GetString()); + Assert.Equal("current", now.GetProperty("segment").GetProperty("id").GetString()); + } + + [Theory] + [InlineData("../../etc/passwd")] + [InlineData("/tmp/covenant-audit.log")] + [InlineData("covenant-audit.log.20260719-014211.archived")] + [InlineData("a-0000000000000000")] + [InlineData("current/..")] + public async Task Unknown_segment_ids_and_paths_are_rejected(string segment) + { + var (status, body) = await GetAsync($"/admin/requests?segment={Uri.EscapeDataString(segment)}"); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Equal("unknown_segment", body.GetProperty("error").GetString()); + var (exportStatus, _) = await GetAsync($"/admin/requests/req_00000000000000000000000000000000/export?segment={Uri.EscapeDataString(segment)}"); + Assert.Equal(HttpStatusCode.BadRequest, exportStatus); + } + + [Theory] + [InlineData("not-base64!!")] + [InlineData("YzF8Y3VycmVudHwtMQ")] // "c1|current|-1" + [InlineData("eHx5")] // "x|y" + public async Task Malformed_cursor_is_rejected(string cursor) + { + var (status, body) = await GetAsync($"/admin/requests?cursor={Uri.EscapeDataString(cursor)}"); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Equal("invalid_cursor", body.GetProperty("error").GetString()); + } + + [Fact] + public async Task Export_carries_version_attempts_trace_costs_and_integrity_but_no_content() + { + // Opt in to a prompt preview so the record itself holds content: the export must still exclude it. + var (version, cfg, _) = await V2Admin.GetConfigAsync(_admin); + await V2Admin.ApplyAsync(_admin, cfg with { Settings = cfg.Settings with { PromptPreviewChars = 200 } }, version, "preview on"); + const string secretPrompt = "ZEBRA-PROMPT-MARKER internal question"; + var id = await RunAsync(secretPrompt); + var record = await CorrelationTestKit.LookupAsync(_admin, id); + Assert.Contains("ZEBRA-PROMPT-MARKER", record.PromptPreview, StringComparison.Ordinal); // the record has it… + + var (status, export) = await GetAsync($"/admin/requests/{id}/export"); + Assert.Equal(HttpStatusCode.OK, status); + var raw = export.GetRawText(); + Assert.DoesNotContain("ZEBRA-PROMPT-MARKER", raw, StringComparison.Ordinal); // …the export does not + Assert.DoesNotContain("local reply", raw, StringComparison.Ordinal); + Assert.False(export.GetProperty("content_included").GetBoolean()); + Assert.Equal(2, export.GetProperty("config_version").GetInt32()); + Assert.Equal(id, export.GetProperty("record").GetProperty("Id").GetString()); + Assert.Equal(1, export.GetProperty("attempts").GetArrayLength()); + Assert.True(export.GetProperty("trace").GetArrayLength() > 0); + var integrity = export.GetProperty("integrity"); + Assert.Equal("verified", integrity.GetProperty("status").GetString()); + Assert.True(integrity.GetProperty("chain_valid").GetBoolean()); + Assert.Matches("^[0-9a-f]{64}$", integrity.GetProperty("entry_hash").GetString()!); + Assert.Equal("current", integrity.GetProperty("segment_id").GetString()); + + // Archived records stay exportable. + await V2Admin.SendAsync(_admin, HttpMethod.Post, "/admin/reset"); + var (archivedStatus, archived) = await GetAsync($"/admin/requests/{id}/export"); + Assert.Equal(HttpStatusCode.OK, archivedStatus); + Assert.StartsWith("a-", archived.GetProperty("integrity").GetProperty("segment_id").GetString(), StringComparison.Ordinal); + + var (missing, _) = await GetAsync("/admin/requests/req_ffffffffffffffffffffffffffffffff/export"); + Assert.Equal(HttpStatusCode.NotFound, missing); + } +} + +/// Savings are reported only against a configured, priced baseline; cache and route avoidance separately; +/// estimated/unknown records never feed a claim. +public sealed class SavingsTests +{ + private static AuditEntry Served(string model, string? basis, bool cacheHit = false) => new( + $"req_{Guid.NewGuid():n}", DateTimeOffset.UtcNow, "p", new AttributionTags("t", "w", "u"), + DataClassification.Public, PolicyEffect.Allow, "allowed", model, new Usage(1000, 1000, cacheHit ? 0m : 0.001m), + CacheHit: cacheHit, SchemaVersion: 2, CostBasis: basis); + + private static readonly Dictionary Prices = new() + { + ["gpt-4o"] = (0.0025m, 0.01m), + ["gpt-4o-mini"] = (0.00015m, 0.0006m), + ["qwen3:8b"] = (0m, 0m), + }; + + [Fact] + public void Without_a_baseline_savings_are_hidden_and_zero() + { + var f = FinOps.Build([Served("gpt-4o-mini", "reported"), Served("gpt-4o-mini", "no_call", cacheHit: true)], "qwen3:8b", "qwen3:8b", Prices, savingsBaseline: null); + Assert.Null(f.Savings); + Assert.Equal(0m, f.EstimatedSavingsUsd); + Assert.Equal(0m, f.SavingsCacheUsd); + } + + [Fact] + public void With_a_priced_baseline_route_and_cache_avoidance_are_reported_separately_excluding_estimates() + { + var f = FinOps.Build( + [ + Served("gpt-4o-mini", "reported"), + Served("gpt-4o-mini", "no_call", cacheHit: true), + Served("gpt-4o-mini", "estimated_from_text"), + ], "qwen3:8b", "gpt-4o", Prices, savingsBaseline: "openai/gpt-4o"); + + var s = Assert.IsType(f.Savings); + Assert.Equal("openai/gpt-4o", s.Baseline); + Assert.Equal("Estimated provider charge avoided", s.Label); + decimal routeDelta = 1m * (0.0025m - 0.00015m) + 1m * (0.01m - 0.0006m); // per request vs the baseline + Assert.Equal(2 * routeDelta, s.RouteAvoidedUsd); // the reported + the cache hit, not the estimate + Assert.Equal(1m * 0.00015m + 1m * 0.0006m, s.CacheAvoidedUsd); + Assert.Equal(s.RouteAvoidedUsd + s.CacheAvoidedUsd, s.TotalUsd); + Assert.Equal(1, s.ExcludedRecords); + } +} diff --git a/tests/Covenant.Tests/BudgetHostTests.cs b/tests/Covenant.Tests/BudgetHostTests.cs new file mode 100644 index 0000000..8c5bcd0 --- /dev/null +++ b/tests/Covenant.Tests/BudgetHostTests.cs @@ -0,0 +1,190 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; + +namespace Covenant.Tests; + +/// ADR-0014 in the Host: GET /admin/budgets / {id}/requests from the persistent ledger; an audit archive never +/// reopens a budget; budget id/period/cap edits keep accrual; restart replays the ledger (and recovers open +/// reservations); a pre-ledger audit segment is imported once. +public sealed class BudgetHostTests +{ + private static async Task BudgetsAsync(HttpClient admin) + { + var (status, body, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/budgets"); + Assert.Equal(HttpStatusCode.OK, status); + return body; + } + + private static JsonElement Budget(JsonElement list, string id) => list.EnumerateArray().Single(b => b.GetProperty("id").GetString() == id); + + private static async Task PublicRequestAsync(RestartableHybridFactory factory, string prompt = "Summarize this public announcement.") + { + using var app = factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + app.DefaultRequestHeaders.Add("X-Covenant-Profile", "public-demo"); + using var resp = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat(prompt)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + return CorrelationTestKit.HeaderId(resp); + } + + // Seed cloud price $0.15 / $0.60 per 1M; the stub reports 10 in / 5 out. + private const decimal OneRequest = 10 / 1_000_000m * 0.15m + 5 / 1_000_000m * 0.60m; + + [Fact] + public async Task Budgets_report_spent_reserved_remaining_period_and_contributing_requests() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + var id = await PublicRequestAsync(factory); + await CorrelationTestKit.LookupAsync(admin, id); + + var global = Budget(await BudgetsAsync(admin), "global"); + Assert.Equal("global", global.GetProperty("scope").GetString()); + Assert.Equal("monthly", global.GetProperty("period").GetString()); + Assert.Equal(DateTimeOffset.UtcNow.ToString("yyyy-MM", System.Globalization.CultureInfo.InvariantCulture), global.GetProperty("period_id").GetString()); + Assert.Equal(OneRequest, global.GetProperty("spent_usd").GetDecimal()); + Assert.Equal(0m, global.GetProperty("reserved_usd").GetDecimal()); + Assert.Equal(100m - OneRequest, global.GetProperty("remaining_usd").GetDecimal()); + Assert.Equal("none", global.GetProperty("warning").GetString()); + Assert.Equal("hard", global.GetProperty("enforcement").GetString()); + + var (status, contributions, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/budgets/global/requests?limit=10"); + Assert.Equal(HttpStatusCode.OK, status); + var item = Assert.Single(contributions.GetProperty("items").EnumerateArray()); + Assert.Equal(id, item.GetProperty("request_id").GetString()); + Assert.Equal("att_1", item.GetProperty("attempt_id").GetString()); + Assert.Equal(OneRequest, item.GetProperty("amount_usd").GetDecimal()); + + var (missing, _, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/budgets/nope/requests"); + Assert.Equal(HttpStatusCode.NotFound, missing); + using var noToken = await admin.GetAsync("/admin/budgets"); + Assert.Equal(HttpStatusCode.Unauthorized, noToken.StatusCode); + + // Status reads the same ledger. + var (_, statusBody, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/status"); + Assert.Equal(OneRequest, statusBody.GetProperty("budget").GetProperty("global_spend_usd").GetDecimal()); + } + + [Fact] + public async Task Audit_archive_does_not_reopen_a_budget() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + await CorrelationTestKit.LookupAsync(admin, await PublicRequestAsync(factory)); + + var (resetStatus, _, _) = await V2Admin.SendAsync(admin, HttpMethod.Post, "/admin/reset"); + Assert.Equal(HttpStatusCode.OK, resetStatus); + Assert.Equal(OneRequest, Budget(await BudgetsAsync(admin), "global").GetProperty("spent_usd").GetDecimal()); + + await CorrelationTestKit.LookupAsync(admin, await PublicRequestAsync(factory, "a second public request")); + Assert.Equal(2 * OneRequest, Budget(await BudgetsAsync(admin), "global").GetProperty("spent_usd").GetDecimal()); + } + + [Fact] + public async Task Renaming_a_budget_and_changing_its_period_and_cap_preserves_accrual_and_a_cap_below_spend_blocks_paid_work() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + await CorrelationTestKit.LookupAsync(admin, await PublicRequestAsync(factory)); + + var (version, cfg, _) = await V2Admin.GetConfigAsync(admin); + var edited = cfg with + { + Budgets = [new BudgetConfigV2 { Id = "appliance-total", Scope = "global", CapUsd = OneRequest / 2, Period = BudgetPeriod.None }], + }; + await V2Admin.ApplyAsync(admin, edited, version, "rename + period + cap below spend"); + + var renamed = Budget(await BudgetsAsync(admin), "appliance-total"); + Assert.Equal(OneRequest, renamed.GetProperty("spent_usd").GetDecimal()); // accrual kept across id/period/cap edits + Assert.Equal("all", renamed.GetProperty("period_id").GetString()); + Assert.Equal(0m, renamed.GetProperty("remaining_usd").GetDecimal()); + Assert.Equal("exceeded", renamed.GetProperty("warning").GetString()); + + // New paid work is refused at the budget stage; spend is kept; zero-priced local work still runs. + using var app = factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + using var paidReq = new HttpRequestMessage(HttpMethod.Post, "/v1/chat/completions") { Content = CorrelationTestKit.Chat("one more public request") }; + paidReq.Headers.Add("X-Covenant-Profile", "public-demo"); + using var paid = await app.SendAsync(paidReq); + Assert.Equal(HttpStatusCode.Forbidden, paid.StatusCode); + var refused = await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(paid)); + Assert.Equal("budget", refused.StoppedAtStage); + Assert.Equal(1, factory.Cloud.Calls); + + using var local = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("an internal question")); + Assert.Equal(HttpStatusCode.OK, local.StatusCode); + } + + [Fact] + public async Task Restart_replays_the_ledger_and_recovers_an_open_reservation_conservatively() + { + var auditPath = RestartableHybridFactory.NewAuditPath(); + try + { + using (var first = new RestartableHybridFactory(auditPath, cleanup: false)) + { + var admin = first.CreateClient(); + await CorrelationTestKit.LookupAsync(admin, await PublicRequestAsync(first)); + } + + // Simulate a crash mid-attempt: a reservation with no settle/release in the journal. + var store = new FileLedgerStore(auditPath + ".ledger.jsonl"); + store.Open(); + store.Append([new LedgerRecord + { + Op = LedgerOps.Reserve, RequestId = "req_crashed", AttemptId = "att_1", Scopes = ["global", "team:platform"], + AmountUsd = 0.25m, TsUtc = DateTimeOffset.UtcNow, + }]); + + using var second = new RestartableHybridFactory(auditPath, cleanup: false); + var admin2 = second.CreateClient(); + var global = Budget(await BudgetsAsync(admin2), "global"); + Assert.Equal(OneRequest + 0.25m, global.GetProperty("spent_usd").GetDecimal()); // settled at the reserved amount + Assert.Equal(0m, global.GetProperty("reserved_usd").GetDecimal()); + var events = await V2Admin.AuditAsync(auditPath, l => l.Any(e => e.EventType == AuditEntryKinds.BudgetRecovered)); + Assert.Contains(events, e => e.EventType == AuditEntryKinds.BudgetRecovered && e.Reason.Contains("1 reservation", StringComparison.Ordinal)); + Assert.Contains(File.ReadAllLines(auditPath + ".ledger.jsonl"), l => l.Contains("\"settle-recovered\"", StringComparison.Ordinal)); + } + finally + { + CorrelationTestKit.DeleteWithSiblings(auditPath); + } + } + + [Fact] + public async Task Without_a_ledger_the_current_audit_segment_spend_is_imported_once() + { + var auditPath = RestartableHybridFactory.NewAuditPath(); + try + { + using (var first = new RestartableHybridFactory(auditPath, cleanup: false)) + { + var admin = first.CreateClient(); + await CorrelationTestKit.LookupAsync(admin, await PublicRequestAsync(first)); + } + File.Delete(auditPath + ".ledger.jsonl"); // a pre-T04 deployment: audit log, no ledger + + using (var second = new RestartableHybridFactory(auditPath, cleanup: false)) + { + var admin = second.CreateClient(); + Assert.Equal(OneRequest, Budget(await BudgetsAsync(admin), "global").GetProperty("spent_usd").GetDecimal()); + var lines = File.ReadAllLines(auditPath + ".ledger.jsonl"); + Assert.Single(lines, l => l.Contains("\"legacy-import\"", StringComparison.Ordinal)); + } + using (var third = new RestartableHybridFactory(auditPath, cleanup: false)) + { + var admin = third.CreateClient(); + Assert.Equal(OneRequest, Budget(await BudgetsAsync(admin), "global").GetProperty("spent_usd").GetDecimal()); // not twice + } + } + finally + { + CorrelationTestKit.DeleteWithSiblings(auditPath); + } + } +} diff --git a/tests/Covenant.Tests/BudgetLedgerTests.cs b/tests/Covenant.Tests/BudgetLedgerTests.cs new file mode 100644 index 0000000..0fbcb10 --- /dev/null +++ b/tests/Covenant.Tests/BudgetLedgerTests.cs @@ -0,0 +1,355 @@ +using System.Text; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// ADR-0014 ledger guarantees, deterministic (barriers, settable clock — no sleeps): atomic all-or-none +/// reservation across scopes, exactly-once settle/release, crash recovery, UTC periods independent of budget ids, +/// overrun flagging, torn-tail repair of the journal. +public sealed class BudgetLedgerTests : IDisposable +{ + private readonly string _path = Path.Combine(Path.GetTempPath(), $"covenant-ledger-{Guid.NewGuid():n}.jsonl"); + + public void Dispose() => CorrelationTestKit.DeleteWithSiblings(_path); + + private static readonly IReadOnlyList Scopes = ["global", "team:platform", "application:demo-app"]; + + private static BudgetCheck Global(decimal cap, BudgetPeriod period = BudgetPeriod.Monthly, string id = "global") + => new(id, "global", cap, period); + + [Fact] + public void Concurrent_reservations_cannot_both_take_the_last_allowance() + { + var ledger = new BudgetLedger(new InMemoryLedgerStore()); + Assert.True(ledger.TryReserve("seed", "att_1", Scopes, 0.6m, [Global(1m)]).Reserved); + ledger.Settle("seed", "att_1", 0.6m, Scopes); // spent 0.6 of a 1.0 cap + + const int contenders = 16; + using var barrier = new Barrier(contenders); + var results = new bool[contenders]; + Parallel.For(0, contenders, new ParallelOptions { MaxDegreeOfParallelism = contenders }, i => + { + barrier.SignalAndWait(); + results[i] = ledger.TryReserve($"req_{i}", "att_1", Scopes, 0.3m, [Global(1m)]).Reserved; + }); + + Assert.Single(results, r => r); // 0.6 + 0.3 fits; a second 0.3 never does + Assert.Equal(0.3m, ledger.Reserved("global")); + } + + [Fact] + public void Reservation_is_all_or_none_across_every_applicable_hard_budget() + { + var store = new InMemoryLedgerStore(); + var ledger = new BudgetLedger(store); + var checks = new[] { Global(100m), new BudgetCheck("team", "team:platform", 0.5m, BudgetPeriod.Monthly) }; + + var refused = ledger.TryReserve("r1", "att_1", Scopes, 0.6m, checks); + Assert.False(refused.Reserved); + Assert.Equal("team", refused.RefusedBudgetId); + Assert.Equal(0m, ledger.Reserved("global")); // nothing reserved anywhere + Assert.Empty(store.Records); + + // A budget on a scope this request is not charged to does not apply. + Assert.True(ledger.TryReserve("r2", "att_1", ["global", "team:other"], 0.6m, checks).Reserved); + } + + [Fact] + public void Settle_and_release_happen_exactly_once() + { + var store = new InMemoryLedgerStore(); + var ledger = new BudgetLedger(store); + Assert.True(ledger.TryReserve("r1", "att_1", Scopes, 0.10m, [Global(1m)]).Reserved); + Assert.True(ledger.TryReserve("r1", "att_1", Scopes, 0.10m, [Global(1m)]).Reserved); // idempotent: no second hold + Assert.Equal(0.10m, ledger.Reserved("global")); + + var first = ledger.Settle("r1", "att_1", 0.04m, Scopes); + var second = ledger.Settle("r1", "att_1", 0.04m, Scopes); + Assert.True(first.Settled); + Assert.False(second.Settled); // double settle ignored + Assert.False(ledger.Release("r1", "att_1")); // remainder already released with the settle + Assert.Equal(0.04m, ledger.Spent("global", BudgetPeriod.Monthly)); + Assert.Equal(0m, ledger.Reserved("global")); + + var ops = store.Records.Select(r => r.Op).ToList(); + Assert.Equal(new[] { LedgerOps.Reserve, LedgerOps.Settle, LedgerOps.Release }, ops); + Assert.Equal(0.06m, store.Records[2].AmountUsd); // the released remainder + + // A never-started attempt is released with no charge, once. + Assert.True(ledger.TryReserve("r2", "att_1", Scopes, 0.2m, [Global(1m)]).Reserved); + Assert.True(ledger.Release("r2", "att_1")); + Assert.False(ledger.Release("r2", "att_1")); + Assert.False(ledger.Settle("r2", "att_1", 0.2m, Scopes).Settled); + Assert.Equal(0.04m, ledger.Spent("global", BudgetPeriod.Monthly)); + } + + [Fact] + public void Reported_cost_above_the_reservation_is_settled_in_full_and_flagged_as_overrun() + { + var store = new InMemoryLedgerStore(); + var ledger = new BudgetLedger(store); + ledger.TryReserve("r1", "att_1", Scopes, 0.01m, [Global(1m)]); + var s = ledger.Settle("r1", "att_1", 0.05m, Scopes); + Assert.True(s.Overrun); + Assert.Equal(0.05m, ledger.Spent("global", BudgetPeriod.None)); // never truncated to the reservation + Assert.True(store.Records.Single(r => r.Op == LedgerOps.Settle).Overrun); + Assert.Equal(0m, store.Records.Single(r => r.Op == LedgerOps.Release).AmountUsd); + } + + [Fact] + public void Spend_is_computed_per_scope_and_UTC_period_so_budget_id_period_and_cap_edits_never_reset_accrual() + { + var clock = new SettableClock(DateTimeOffset.Parse("2026-09-30T23:59:00Z")); + var ledger = new BudgetLedger(new InMemoryLedgerStore(), clock: clock); + ledger.TryReserve("sep", "att_1", Scopes, 1m, []); + ledger.Settle("sep", "att_1", 1m, Scopes); // September + clock.Set(DateTimeOffset.Parse("2026-10-16T08:00:00Z")); + ledger.TryReserve("oct", "att_1", Scopes, 2m, []); + ledger.Settle("oct", "att_1", 2m, Scopes); // October + + Assert.Equal(2m, ledger.Spent("global", BudgetPeriod.Monthly)); + Assert.Equal(2m, ledger.Spent("global", BudgetPeriod.Daily)); + Assert.Equal(3m, ledger.Spent("global", BudgetPeriod.None)); + Assert.Equal(3m, ledger.Spent("application:demo-app", BudgetPeriod.None)); + Assert.Equal(3m, ledger.Spent("TEAM:Platform", BudgetPeriod.None)); // scopes compare case-insensitively + + // The same scope under another budget id / cap: identical accrual (the ledger never records budget ids). + Assert.False(ledger.TryReserve("x", "att_1", Scopes, 0.5m, [Global(2.4m, BudgetPeriod.Monthly, id: "renamed")]).Reserved); + Assert.True(ledger.TryReserve("y", "att_1", Scopes, 0.5m, [Global(2.6m, BudgetPeriod.Monthly, id: "renamed")]).Reserved); + + clock.Set(DateTimeOffset.Parse("2026-11-01T00:00:00Z")); // period rollover reopens monthly, not all-time + Assert.Equal(0m, ledger.Spent("global", BudgetPeriod.Monthly)); + Assert.Equal(3m, ledger.Spent("global", BudgetPeriod.None)); + Assert.Equal("2026-11", BudgetPeriods.PeriodId(BudgetPeriod.Monthly, clock.GetUtcNow())); + Assert.Equal("2026-11-01", BudgetPeriods.PeriodId(BudgetPeriod.Daily, clock.GetUtcNow())); + Assert.Equal("all", BudgetPeriods.PeriodId(BudgetPeriod.None, clock.GetUtcNow())); + } + + [Fact] + public void Restart_replays_the_journal_and_settles_open_reservations_at_their_reserved_amount() + { + var store = new FileLedgerStore(_path); + Assert.False(store.Open().Existed); + store.EnsureCreated(); + var ledger = new BudgetLedger(store); + ledger.TryReserve("done", "att_1", Scopes, 0.5m, [Global(10m)]); + ledger.Settle("done", "att_1", 0.2m, Scopes); + ledger.TryReserve("crashed", "att_1", Scopes, 0.7m, [Global(10m)]); // the process "dies" here + + var reopened = new FileLedgerStore(_path); + var opened = reopened.Open(); + Assert.True(opened.Existed); + Assert.Empty(opened.Errors); + var after = new BudgetLedger(reopened, opened.Records); + Assert.Equal(0.7m, after.Reserved("global")); + var recovered = after.RecoverUnsettled(); + var r = Assert.Single(recovered); + Assert.Equal((LedgerOps.SettleRecovered, "crashed", 0.7m), (r.Op, r.RequestId, r.AmountUsd)); + Assert.Equal(0.9m, after.Spent("global", BudgetPeriod.Monthly)); // conservative: never free capacity + Assert.Equal(0m, after.Reserved("global")); + + // A second restart: nothing left to recover, same spend (exactly once on replay too). + var third = new FileLedgerStore(_path); + var again = new BudgetLedger(third, third.Open().Records); + Assert.Empty(again.RecoverUnsettled()); + Assert.Equal(0.9m, again.Spent("global", BudgetPeriod.Monthly)); + } + + [Fact] + public void Torn_tail_is_quarantined_and_repaired_before_the_next_append_and_survives_two_more_restarts() + { + var store = new FileLedgerStore(_path); + store.Open(); + store.EnsureCreated(); + var ledger = new BudgetLedger(store); + ledger.TryReserve("r1", "att_1", Scopes, 0.5m, []); + ledger.Settle("r1", "att_1", 0.5m, Scopes); + File.AppendAllText(_path, "{\"op\":\"reserve\",\"request_id\":\"r2\",\"att"); // interrupted append + + for (int restart = 0; restart < 3; restart++) + { + var s = new FileLedgerStore(_path); + var opened = s.Open(); + Assert.Empty(opened.Errors); + var l = new BudgetLedger(s, opened.Records); + Assert.Equal(0.5m + restart * 0.25m, l.Spent("global", BudgetPeriod.None)); + l.TryReserve($"after{restart}", "att_1", Scopes, 0.25m, []); + l.Settle($"after{restart}", "att_1", 0.25m, Scopes); + } + Assert.Single(Directory.GetFiles(Path.GetDirectoryName(_path)!, Path.GetFileName(_path) + ".torn-*")); + Assert.EndsWith("\n", File.ReadAllText(_path), StringComparison.Ordinal); + } + + [Fact] + public void Corrupt_line_before_the_tail_refuses_to_start() + { + File.WriteAllText(_path, "{\"op\":\"settle\"\n{not json}\n" + + "{\"op\":\"settle\",\"request_id\":\"a\",\"attempt_id\":\"b\",\"scopes\":[\"global\"],\"amount_usd\":1,\"ts_utc\":\"2026-10-16T00:00:00+00:00\"}\n", + Encoding.UTF8); + var opened = new FileLedgerStore(_path).Open(); + Assert.NotEmpty(opened.Errors); + } + + [Fact] + public void Legacy_import_charges_global_and_team_scopes_once() + { + var ledger = new BudgetLedger(new InMemoryLedgerStore()); + ledger.ImportLegacy(new[] { ("payments", 1.5m), ("data", 0.5m), ("idle", 0m) }); + Assert.Equal(2m, ledger.Spent("global", BudgetPeriod.Monthly)); + Assert.Equal(1.5m, ledger.Spent("team:payments", BudgetPeriod.Monthly)); + Assert.Equal(0m, ledger.Spent("team:idle", BudgetPeriod.Monthly)); + } +} + +/// ADR-0014 through the real pipeline stages (budget stage + gate + provider + attribution + audit). +public sealed class BudgetPipelineTests +{ + private readonly StubChatClient _mini = new("mini reply"); + private readonly StubChatClient _local = new("local reply"); + + private V2Rig Rig(decimal cap = 100m, Func? tweak = null) + => V2Rig.Build(V2Rig.FallbackConfig(new RetrySettings { MaxAttempts = 1, DeadlineMs = 60_000 }, cap, tweak), + new Dictionary + { + [$"openai:{V2.CloudModel}"] = _mini, + [$"ollama:{V2.LocalTag}"] = _local, + }); + + private static decimal Bound(string prompt, int outputTokens = RequestBounds.DefaultOutputTokens) + => (Encoding.UTF8.GetByteCount(prompt) + RequestBounds.PerMessageOverheadTokens) / 1_000_000m * 0.15m + outputTokens / 1_000_000m * 0.60m; + + [Fact] + public async Task Reservation_uses_utf8_bytes_plus_16_per_message_and_the_enforced_output_bound() + { + var rig = Rig(); + const string prompt = "Résumé — public naïve café"; // multi-byte: bytes > chars + var (ctx, e) = await rig.RunAsync(prompt, profile: "public-demo", maxTokens: 200); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal(Bound(prompt, 200), e.ReservedUsd); + Assert.Equal(10 / 1_000_000m * 0.15m + 5 / 1_000_000m * 0.60m, e.SettledUsd); // reported usage + Assert.Equal("reported", e.CostBasis); + Assert.Equal(e.SettledUsd, rig.Ledger.Spent("application:demo-app", BudgetPeriod.Monthly)); + Assert.Equal(e.SettledUsd, rig.Ledger.Spent("team:platform", BudgetPeriod.Monthly)); + Assert.Equal(0m, rig.Ledger.Reserved("global")); + } + + [Fact] + public async Task Unreported_usage_settles_the_conservative_reservation_bound() + { + _mini.Then(StubChatClient.Mode.ServeNoUsage); + var rig = Rig(); + var (_, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.False(e.UsageReported); + Assert.Equal("estimated_from_text", e.CostBasis); + Assert.Equal(Bound(V2Rig.PublicPrompt), e.SettledUsd); + Assert.Equal(e.ReservedUsd, e.SettledUsd); + Assert.Equal(e.SettledUsd, e.Usage.CostUsd); + } + + [Fact] + public async Task Overrun_is_settled_in_full_and_flagged_in_the_attempt_evidence() + { + _mini.Then(StubChatClient.Mode.ServeHugeUsage); + var rig = Rig(); + var (_, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + var a = Assert.Single(e.Attempts!); + Assert.True(a.Overrun); + Assert.Equal(0.15m + 0.60m, a.CostUsd); // 1M in + 1M out, never truncated to the bound + Assert.True(a.CostUsd > a.ReservedUsd); + Assert.Equal(0.75m, rig.Ledger.Spent("global", BudgetPeriod.Monthly)); + } + + [Fact] + public async Task Hard_cap_refuses_at_the_budget_stage_before_any_provider_call_and_local_zero_price_still_runs() + { + var rig = Rig(cap: 0.0001m); // below one cloud bound + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.True(ctx.IsDenied); + Assert.Equal("budget", e.StoppedAtStage); + Assert.Contains("would be exceeded", e.Reason, StringComparison.Ordinal); + Assert.Equal(0, _mini.Calls); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "budget" && t.State == TraceStates.Refused && t.ReasonCode == TraceReasons.BudgetExceeded); + + var (local, le) = await rig.RunAsync("an internal question", profile: "internal-default"); // explicit $0 local price + Assert.False(local.IsDenied, local.DenialReason); + Assert.Equal(0m, le.ReservedUsd ?? 0m); + Assert.Equal(1, _local.Calls); + } + + [Fact] + public async Task Warn_only_budget_never_blocks() + { + var rig = Rig(tweak: c => c with + { + Budgets = [new BudgetConfigV2 { Id = "global", Scope = "global", CapUsd = 0m, Enforcement = BudgetEnforcement.WarnOnly }], + }); + var (ctx, _) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal(1, _mini.Calls); + } + + [Fact] + public async Task Application_scope_budget_is_enforced() + { + var rig = Rig(tweak: c => c with + { + Budgets = + [ + new BudgetConfigV2 { Id = "global", Scope = "global", CapUsd = 100m }, + new BudgetConfigV2 { Id = "demo", Scope = "application:demo-app", CapUsd = 0.00001m }, + ], + }); + var (_, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal("budget", e.StoppedAtStage); + Assert.Contains("'demo'", e.Reason, StringComparison.Ordinal); + } + + [Fact] + public async Task Cancellation_settles_the_started_attempt_once_and_releases_the_reservation() + { + _mini.Then(StubChatClient.Mode.Hang); + var rig = Rig(); + using var cts = new CancellationTokenSource(); + var run = rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", ct: cts.Token); + await _mini.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.True(rig.Ledger.Reserved("global") > 0m); // held while in flight + cts.Cancel(); + var (_, e) = await run; + + Assert.Equal("Cancelled", e.DenialKind); + Assert.Equal(0, rig.Ledger.OpenReservations); + Assert.Equal(0m, rig.Ledger.Reserved("global")); + var ops = rig.Store.Records.Select(r => r.Op).ToList(); + Assert.Equal(new[] { LedgerOps.Reserve, LedgerOps.Settle, LedgerOps.Release }, ops); // exactly once each + Assert.Equal(e.SettledUsd, rig.Ledger.Spent("global", BudgetPeriod.Monthly)); + Assert.Equal("estimated_failed_call", e.CostBasis); + } + + [Fact] + public async Task Unpriced_cloud_target_is_ineligible_under_a_hard_budget() + { + var rig = Rig(tweak: c => c with + { + Connections = c.Connections.Select(x => x.Id != "openai" ? x : x with + { + Models = x.Models.Select(m => m with { Price = null }).ToList(), + }).ToList(), + }); + var (ctx, _) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + // The cloud primary is excluded ("unpriced paid destination under a hard budget"); the local fallback serves. + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Contains(ctx.Policy!.Excluded, x => x.Reason.Contains("unpriced", StringComparison.Ordinal)); + Assert.Equal(0, _mini.Calls); + Assert.Equal(1, _local.Calls); + + var invalid = ConfigValidator.Validate(V2Rig.FallbackConfig(tweak: c => c with + { + Connections = c.Connections.Select(x => x.Id != "openai" ? x : x with { Models = x.Models.Select(m => m with { Price = null }).ToList() }).ToList(), + }), V2.Env()); + Assert.Contains(invalid.Errors, i => i.Code == "unpriced_paid_target_under_hard_budget"); + } +} diff --git a/tests/Covenant.Tests/CacheIsolationTests.cs b/tests/Covenant.Tests/CacheIsolationTests.cs new file mode 100644 index 0000000..1764987 --- /dev/null +++ b/tests/Covenant.Tests/CacheIsolationTests.cs @@ -0,0 +1,143 @@ +using System.Net; +using Covenant.Core; +using Covenant.Governance; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// ADR-0013 exact cache with a bound configuration: key = application, team, profile, FINAL classification, +/// configuration version, approved candidates, enforced output bound and content. Hits run after the current +/// auth/shape/classify/policy checks, skip pause/budget/provider (a hit is served during a global pause — documented), +/// cost $0 with basis no_call, and are audited with CacheHit and the originally served model. Failures are never stored. +public sealed class CacheIsolationTests +{ + private readonly StubChatClient _mini = new("mini reply"); + private readonly StubChatClient _local = new("local reply"); + private readonly ResponseCache _cache = new(); + + private static CovenantConfig Config(int version = 1) + => V2Rig.FallbackConfig(new RetrySettings { MaxAttempts = 1, DeadlineMs = 60_000 }) with + { + Version = version, + Settings = new OperationalSettings { CacheTtlSeconds = 300 }, + Applications = + [ + new ApplicationConfig { Id = "demo-app", Team = "platform", Enabled = true, ConsoleTesting = true, GrantedProfiles = ["public-demo", "internal-default"], DefaultProfile = "internal-default" }, + new ApplicationConfig { Id = "batch-app", Team = "data", Enabled = true, ConsoleTesting = false, GrantedProfiles = ["public-demo", "internal-default"], DefaultProfile = "internal-default" }, + ], + }; + + private V2Rig Rig(CovenantConfig? cfg = null) => V2Rig.Build(cfg ?? Config(), new Dictionary + { + [$"openai:{V2.CloudModel}"] = _mini, + [$"ollama:{V2.LocalTag}"] = _local, + }, cache: _cache); + + [Fact] + public async Task Exact_repeat_is_served_from_cache_with_no_provider_call_no_charge_and_explicit_provenance() + { + var rig = Rig(); + var (_, first) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + var spent = rig.Ledger.Spent("global", BudgetPeriod.Monthly); + var (ctx, hit) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + + Assert.Equal(1, _mini.Calls); + Assert.True(hit.CacheHit); + Assert.Equal("no_call", hit.CostBasis); + Assert.Equal(0m, hit.Usage.CostUsd); + Assert.Equal(first.ServedByModel, hit.ServedByModel); // the original served model + Assert.Empty(hit.Attempts!); + Assert.Null(hit.SettledUsd); + Assert.Equal(spent, rig.Ledger.Spent("global", BudgetPeriod.Monthly)); + // Trace: cache passed (cache_hit); every later stage skipped with reason cache_hit. + Assert.Contains(ctx.TraceEvents, t => t.Stage == "cache" && t.State == TraceStates.Passed && t.ReasonCode == TraceReasons.CacheHit); + foreach (var stage in new[] { "rate_limit", "pause", "budget", "provider", "attribution" }) + Assert.Contains(ctx.TraceEvents, t => t.Stage == stage && t.State == TraceStates.Skipped && t.ReasonCode == TraceReasons.CacheHit); + Assert.Contains(hit.Trace!, s => s.Stage == "provider" && s.State == TraceStates.Skipped); + } + + [Fact] + public async Task Entries_are_isolated_across_applications_teams_and_profiles() + { + var rig = Rig(); + await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); // demo-app / platform / public-demo + var (_, otherApp) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", key: "batch-key"); // batch-app / data + Assert.False(otherApp.CacheHit); + Assert.Equal(2, _mini.Calls); + + // Same application, another profile ⇒ another classification baseline and key (Internal → local). + var (_, otherProfile) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "internal-default"); + Assert.False(otherProfile.CacheHit); + Assert.Equal(1, _local.Calls); + } + + [Fact] + public async Task A_new_configuration_version_never_reuses_an_entry() + { + var rig = Rig(); + await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + rig.Snapshot = new RuntimeSnapshot(Config(version: 2)); // any activation changes the key space + var (_, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.False(e.CacheHit); + Assert.Equal(2, _mini.Calls); + Assert.Equal(2, e.ConfigVersion); + } + + [Fact] + public async Task A_different_enforced_output_bound_is_a_different_entry() + { + var rig = Rig(); + await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", maxTokens: 400); + var (_, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", maxTokens: 5); + Assert.False(e.CacheHit); + Assert.Equal(2, _mini.Calls); + } + + [Fact] + public async Task Cache_hit_during_a_global_pause_is_served_and_a_miss_is_refused() + { + var rig = Rig(); + await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + rig.Kill.Trip("pause for the demo"); + + var (hitCtx, hit) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.False(hitCtx.IsDenied, hitCtx.DenialReason); // documented semantics: pause stops provider calls only + Assert.True(hit.CacheHit); + + var (_, miss) = await rig.RunAsync(V2Rig.PublicPrompt + " (new)", profile: "public-demo"); + Assert.Equal("pause", miss.StoppedAtStage); + Assert.Equal(1, _mini.Calls); + } + + [Fact] + public async Task Current_policy_is_enforced_before_a_hit() + { + var rig = Rig(); + await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + // Same version number, but the public policy is now paused: the policy stage (before the cache) refuses. + rig.Snapshot = new RuntimeSnapshot(Config() with + { + Policies = Config().Policies.Select(p => p.Id == "public" ? p with { Paused = true } : p).ToList(), + }); + var (_, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal("policy", e.StoppedAtStage); + Assert.False(e.CacheHit); + } + + [Fact] + public async Task Failures_and_partial_streams_are_never_stored() + { + _mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)) + .Then(StubChatClient.Mode.StreamThenThrow) + .Then(StubChatClient.Mode.Serve); + var rig = Rig(); + var (_, failed) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal(PolicyEffect.Deny, failed.Effect); + var (_, partial) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + Assert.Equal(PolicyEffect.Deny, partial.Effect); + var (_, served) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.False(served.CacheHit); // nothing was cached from the failures + Assert.Equal(3, _mini.Calls); + } +} diff --git a/tests/Covenant.Tests/ConsolePlaygroundTests.cs b/tests/Covenant.Tests/ConsolePlaygroundTests.cs new file mode 100644 index 0000000..1d8ce06 --- /dev/null +++ b/tests/Covenant.Tests/ConsolePlaygroundTests.cs @@ -0,0 +1,203 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using Covenant.Core; +using Covenant.Host; +using Xunit; + +namespace Covenant.Tests; + +internal static class Playground +{ + public static string Body(string applicationId, string prompt, string? profile = null, bool stream = false, + string? clientRequestId = null, int? maxTokens = null, string? model = null) + { + var sb = new StringBuilder(); + sb.Append("{\"application_id\":").Append(JsonSerializer.Serialize(applicationId, CovenantJsonContext.Default.String)); + if (profile is not null) sb.Append(",\"profile_id\":").Append(JsonSerializer.Serialize(profile, CovenantJsonContext.Default.String)); + sb.Append(",\"messages\":[{\"role\":\"user\",\"content\":").Append(JsonSerializer.Serialize(prompt, CovenantJsonContext.Default.String)).Append("}]"); + sb.Append(",\"stream\":").Append(stream ? "true" : "false"); + if (clientRequestId is not null) sb.Append(",\"client_request_id\":\"").Append(clientRequestId).Append('"'); + if (maxTokens is not null) sb.Append(",\"max_tokens\":").Append(maxTokens.Value); + if (model is not null) sb.Append(",\"model\":").Append(JsonSerializer.Serialize(model, CovenantJsonContext.Default.String)); + return sb.Append('}').ToString(); + } + + public static async Task PostAsync(HttpClient client, string json, bool admin = true) + { + using var req = admin + ? CorrelationTestKit.Admin(HttpMethod.Post, "/admin/playground/requests") + : new HttpRequestMessage(HttpMethod.Post, "/admin/playground/requests"); + req.Content = new StringContent(json, Encoding.UTF8, "application/json"); + return await client.SendAsync(req); + } + + /// Adds a disabled application and an application that is not console-testable (validated apply). + public static async Task AddTestApplicationsAsync(HttpClient admin) + { + var (version, cfg, _) = await V2Admin.GetConfigAsync(admin); + var apps = cfg.Applications.ToList(); + apps.Add(new ApplicationConfig { Id = "off-app", Team = "data", Enabled = false, ConsoleTesting = true, GrantedProfiles = ["public-demo"], DefaultProfile = "public-demo" }); + apps.Add(new ApplicationConfig { Id = "batch-app", Team = "data", Enabled = true, ConsoleTesting = false, GrantedProfiles = ["internal-default"], DefaultProfile = "internal-default" }); + return await V2Admin.ApplyAsync(admin, cfg with { Applications = apps }, version, "test applications"); + } +} + +/// ADR-0012 console inference: POST /admin/playground/requests runs the SAME governed pipeline as /v1 with an +/// application resolved server-side; 400 before governance (no audit), governed 403 with audit, 409 on a repeated +/// client_request_id, no application credential anywhere in the browser-facing payloads. +public sealed class ConsolePlaygroundTests : IDisposable +{ + private readonly HybridSeedFactory _factory = new(); + private readonly HttpClient _client; + + public ConsolePlaygroundTests() => _client = _factory.CreateClient(); + + public void Dispose() => _factory.Dispose(); + + [Fact] + public async Task Console_request_runs_the_governed_pipeline_as_the_application_with_honest_operator_attribution() + { + using var resp = await Playground.PostAsync(_client, Playground.Body("demo-app", "Summarize this public announcement.", profile: "public-demo")); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + var text = await resp.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(text); + Assert.Equal(id, doc.RootElement.GetProperty("id").GetString()); // same response contract as /v1 + Assert.Equal(V2.CloudModel, doc.RootElement.GetProperty("model").GetString()); + Assert.Equal("cloud reply", doc.RootElement.GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString()); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal("console", e.EntryPoint); + Assert.Equal("shared-admin-token", e.OperatorRef); + Assert.Equal("demo-app", e.ApplicationId); + Assert.Equal("platform", e.Tags.Team); + Assert.Equal("public-demo", e.ProfileId); + Assert.Equal(1, e.ConfigVersion); + Assert.NotNull(e.Trace); + Assert.Single(e.Attempts!); + Assert.True(e.ReservedUsd > 0m); + Assert.Equal(e.Usage.CostUsd, e.SettledUsd); + + // Credentials never cross to the browser: no application key, admin token or provider secret in the payload. + Assert.DoesNotContain("demo-key", text, StringComparison.Ordinal); + Assert.DoesNotContain(CorrelationTestKit.AdminToken, text, StringComparison.Ordinal); + Assert.DoesNotContain(HybridSeedFactory.Secret, text, StringComparison.Ordinal); + } + + [Fact] + public async Task Streaming_console_request_speaks_the_same_SSE_contract() + { + using var resp = await Playground.PostAsync(_client, Playground.Body("demo-app", "an internal question", stream: true)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + Assert.Equal("text/event-stream", resp.Content.Headers.ContentType?.MediaType); + var id = CorrelationTestKit.HeaderId(resp); + var body = await resp.Content.ReadAsStringAsync(); + Assert.Contains("local reply", body, StringComparison.Ordinal); + Assert.Contains($"\"id\":\"{id}\"", body, StringComparison.Ordinal); + Assert.EndsWith("data: [DONE]\n\n", body, StringComparison.Ordinal); + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal("console", e.EntryPoint); + Assert.True(e.Stream); + } + + [Theory] + [InlineData("off-app", null, "disabled")] + [InlineData("batch-app", null, "not enabled for console testing")] + [InlineData("demo-app", "phi-workload", "not granted")] + [InlineData("ghost-app", null, "is not configured")] + public async Task Refused_identities_are_governed_403_with_an_audit_record_and_no_provider_call(string app, string? profile, string reason) + { + await Playground.AddTestApplicationsAsync(_client); + int calls = _factory.Cloud.Calls + _factory.Local.Calls; + using var resp = await Playground.PostAsync(_client, Playground.Body(app, "hello", profile: profile)); + Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + using var doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); + Assert.Equal("denied", doc.RootElement.GetProperty("error").GetString()); + Assert.Equal(id, doc.RootElement.GetProperty("request_id").GetString()); + + var e = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Equal("auth", e.StoppedAtStage); + Assert.Equal("Governance", e.DenialKind); + Assert.Equal("console", e.EntryPoint); + Assert.Contains(reason, e.Reason, StringComparison.Ordinal); + Assert.Equal(calls, _factory.Cloud.Calls + _factory.Local.Calls); + } + + [Theory] + [InlineData("{not json")] + [InlineData("""{"profile_id":"public-demo","messages":[{"role":"user","content":"x"}]}""")] + [InlineData("""{"application_id":"demo-app","messages":[]}""")] + [InlineData("""{"application_id":"demo-app","messages":[{"role":"wizard","content":"x"}]}""")] + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":null}]}""")] + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}],"max_tokens":0}""")] + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}],"client_request_id":"bad id with spaces"}""")] + public async Task Invalid_body_is_400_before_governance_with_no_audit_record(string json) + { + await V2Admin.AuditAsync(_factory.AuditPath, l => l.Count >= 1); // bootstrap event is on disk + using var bad = await Playground.PostAsync(_client, json); + Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); + var badId = CorrelationTestKit.HeaderId(bad); + using var doc = JsonDocument.Parse(await bad.Content.ReadAsStringAsync()); + Assert.Equal("invalid_request", doc.RootElement.GetProperty("error").GetString()); + + // FIFO proof (single-reader sink): a later request's record exists ⇒ nothing was ever enqueued for the 400. + using var ok = await Playground.PostAsync(_client, Playground.Body("demo-app", "after the bad one")); + await CorrelationTestKit.LookupAsync(_client, CorrelationTestKit.HeaderId(ok)); + using var lookup = await _client.SendAsync(CorrelationTestKit.Admin(HttpMethod.Get, $"/admin/requests/{badId}")); + Assert.Equal(HttpStatusCode.NotFound, lookup.StatusCode); + Assert.Equal(1, _factory.Local.Calls); + } + + [Fact] + public async Task Repeated_client_request_id_is_409_with_the_original_request_id_and_never_runs_again() + { + using var first = await Playground.PostAsync(_client, Playground.Body("demo-app", "run once", clientRequestId: "run-7f3a")); + Assert.Equal(HttpStatusCode.OK, first.StatusCode); + var originalId = CorrelationTestKit.HeaderId(first); + int calls = _factory.Local.Calls; + + using var again = await Playground.PostAsync(_client, Playground.Body("demo-app", "run once", clientRequestId: "run-7f3a")); + Assert.Equal(HttpStatusCode.Conflict, again.StatusCode); + using var doc = JsonDocument.Parse(await again.Content.ReadAsStringAsync()); + Assert.Equal("duplicate_submission", doc.RootElement.GetProperty("error").GetString()); + Assert.Equal(originalId, doc.RootElement.GetProperty("request_id").GetString()); + Assert.Equal(calls, _factory.Local.Calls); // a reload never replays inference + } + + [Fact] + public async Task Admin_token_is_required_and_v1_is_unchanged() + { + using var noToken = await Playground.PostAsync(_client, Playground.Body("demo-app", "hi"), admin: false); + Assert.Equal(HttpStatusCode.Unauthorized, noToken.StatusCode); + + // /v1 still requires an application key: the admin token is not one. + using var v1 = new HttpRequestMessage(HttpMethod.Post, "/v1/chat/completions") { Content = CorrelationTestKit.Chat("hi") }; + v1.Headers.Add("X-Covenant-Admin-Token", CorrelationTestKit.AdminToken); + using var v1Resp = await _client.SendAsync(v1); + Assert.Equal(HttpStatusCode.Unauthorized, v1Resp.StatusCode); + + using var app = _factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + using var keyed = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("hi from v1")); + Assert.Equal(HttpStatusCode.OK, keyed.StatusCode); + var e = await CorrelationTestKit.LookupAsync(_client, CorrelationTestKit.HeaderId(keyed)); + Assert.Equal("v1", e.EntryPoint); + Assert.Null(e.OperatorRef); + } + + [Fact] + public void Submissions_window_expires_and_is_bounded() + { + var clock = new SettableClock(DateTimeOffset.Parse("2026-10-17T10:00:00Z")); + var s = new ConsoleSubmissions(clock, TimeSpan.FromMinutes(10), maxEntries: 4); + Assert.True(s.TryClaim("a", "req_1", out _)); + Assert.False(s.TryClaim("a", "req_2", out var original)); + Assert.Equal("req_1", original); + clock.Advance(TimeSpan.FromMinutes(11)); + Assert.True(s.TryClaim("a", "req_3", out _)); // outside the 10-minute window + for (int i = 0; i < 10; i++) Assert.True(s.TryClaim($"k{i}", $"req_k{i}", out _)); + } +} diff --git a/tests/Covenant.Tests/FallbackTests.cs b/tests/Covenant.Tests/FallbackTests.cs new file mode 100644 index 0000000..c4f3e70 --- /dev/null +++ b/tests/Covenant.Tests/FallbackTests.cs @@ -0,0 +1,314 @@ +using System.Net; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// ADR-0013 bounded approved fallback through the REAL stages (stub IChatClients, never a paid provider): +/// fallback only for the policy's retry classes, within maxAttempts and deadlineMs, never after content was emitted, +/// never on caller cancellation, pause or non-retryable errors; every attempt evidenced and charged (ADR-0014). +public sealed class FallbackTests +{ + private readonly StubChatClient _mini = new("mini reply"); + private readonly StubChatClient _strong = new("strong reply"); + private readonly StubChatClient _local = new("local reply"); + + private V2Rig Rig(RetrySettings? retry = null, Func? tweak = null) + => V2Rig.Build(V2Rig.FallbackConfig(retry, tweak: tweak), new Dictionary + { + [$"openai:{V2.CloudModel}"] = _mini, + ["openai:gpt-4o"] = _strong, + [$"ollama:{V2.LocalTag}"] = _local, + }); + + public static TheoryData RetryableFailures => new() { "429", "timeout", "5xx-500", "5xx-502", "5xx-503", "5xx-504", "connect" }; + + private static Exception Make(string kind) => kind switch + { + "429" => Failures.Status(HttpStatusCode.TooManyRequests), + "timeout" => Failures.ProviderTimeout(), + "5xx-500" => Failures.Status(HttpStatusCode.InternalServerError), + "5xx-502" => Failures.Status(HttpStatusCode.BadGateway), + "5xx-503" => Failures.Status(HttpStatusCode.ServiceUnavailable), + "5xx-504" => Failures.Status(HttpStatusCode.GatewayTimeout), + "connect" => Failures.Connect(), + _ => throw new ArgumentOutOfRangeException(nameof(kind)), + }; + + [Theory] + [MemberData(nameof(RetryableFailures))] + public async Task Retryable_failure_before_output_falls_back_to_the_next_approved_target(string kind) + { + _mini.Then(StubChatClient.Mode.Throw, () => Make(kind)); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal(1, _mini.Calls); + Assert.Equal(1, _strong.Calls); + Assert.Equal("strong reply", ctx.Response!.Message.Content); + Assert.Equal("gpt-4o", e.ServedByModel); + Assert.Equal(V2.CloudModel, e.SelectedModel); // policy's primary + Assert.Equal("gpt-4o", e.AttemptedModel); // last attempt started + + var attempts = Assert.IsAssignableFrom>(e.Attempts); + Assert.Equal(2, attempts.Count); + Assert.Equal(("att_1", "openai", V2.CloudModel, "failed"), (attempts[0].AttemptId, attempts[0].ConnectionId, attempts[0].ModelId, attempts[0].Outcome)); + Assert.Equal(kind.StartsWith("5xx", StringComparison.Ordinal) ? "5xx" : kind, attempts[0].ErrorClass); + Assert.Equal(("att_2", "gpt-4o", "served"), (attempts[1].AttemptId, attempts[1].ModelId, attempts[1].Outcome)); + + // Both attempts charged: the failed one at its reservation-bound estimate (possibly billed, never $0). + Assert.Equal("estimated_failed_call", attempts[0].CostBasis); + Assert.True(attempts[0].CostUsd > 0m); + Assert.Equal(attempts[0].ReservedUsd, attempts[0].CostUsd); + Assert.Equal("reported", attempts[1].CostBasis); + Assert.Equal(attempts[0].CostUsd + attempts[1].CostUsd, e.SettledUsd); + Assert.Equal(e.SettledUsd, e.Usage.CostUsd); // the request's charge includes the failed attempt + Assert.Equal(e.SettledUsd, rig.Ledger.Spent("global", BudgetPeriod.Monthly)); + Assert.Equal(0, rig.Ledger.OpenReservations); + Assert.Equal(0m, rig.Ledger.Reserved("global")); + + // Observed health per connection:model from the real attempts. + Assert.Equal("failed", rig.Health.Get($"openai:{V2.CloudModel}").State); + Assert.Equal("ok", rig.Health.Get("openai:gpt-4o").State); + + // Trace: two provider attempts; the fallback's pause + budget re-checks are recorded with its attempt id. + Assert.Contains(ctx.TraceEvents, t => t.Stage == "provider" && t.AttemptId == "att_1" && t.State == TraceStates.Failed); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "pause" && t.AttemptId == "att_2" && t.State == TraceStates.Passed); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "budget" && t.AttemptId == "att_2" && t.State == TraceStates.Passed); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "provider" && t.AttemptId == "att_2" && t.State == TraceStates.Passed); + } + + public static TheoryData NonRetryableStatuses => new() { 400, 401, 403, 404, 422 }; + + [Theory] + [MemberData(nameof(NonRetryableStatuses))] + public async Task Non_retryable_provider_error_never_falls_back(int status) + { + _mini.Then(StubChatClient.Mode.Throw, () => Failures.Status((HttpStatusCode)status)); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(0, _strong.Calls + _local.Calls); + var a = Assert.Single(e.Attempts!); + Assert.Equal("non_retryable", a.ErrorClass); + Assert.Equal("estimated_failed_call", e.CostBasis); + Assert.True(e.Usage.CostUsd > 0m); + } + + [Fact] + public async Task Failure_class_not_in_retry_on_is_terminal() + { + _mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.TooManyRequests)); + var rig = Rig(new RetrySettings { MaxAttempts = 3, DeadlineMs = 60_000, On = ["5xx"] }); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal("429", Assert.Single(e.Attempts!).ErrorClass); + Assert.Equal(0, _strong.Calls); + } + + [Fact] + public async Task Max_attempts_is_respected() + { + var fail = () => Failures.Status(HttpStatusCode.ServiceUnavailable); + _mini.Then(StubChatClient.Mode.Throw, fail); + _strong.Then(StubChatClient.Mode.Throw, fail); + var rig = Rig(new RetrySettings { MaxAttempts = 2, DeadlineMs = 60_000 }); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(2, e.Attempts!.Count); + Assert.Equal(0, _local.Calls); // a third approved target exists but maxAttempts = 2 + Assert.All(e.Attempts!, a => Assert.True(a.CostUsd > 0m)); + Assert.Equal(e.Attempts!.Sum(a => a.CostUsd), e.SettledUsd); + } + + [Fact] + public async Task Deadline_cancels_a_hanging_attempt_as_timeout_and_starts_no_further_attempt() + { + _mini.Then(StubChatClient.Mode.Hang); + var rig = Rig(new RetrySettings { MaxAttempts = 3, DeadlineMs = 50 }); // pure rig: below the validator minimum on purpose + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + var a = Assert.Single(e.Attempts!); + Assert.Equal("timeout", a.ErrorClass); + Assert.Equal(0, _strong.Calls + _local.Calls); + } + + [Fact] + public async Task Streaming_failure_after_the_first_chunk_never_continues_on_a_second_provider() + { + _mini.Then(StubChatClient.Mode.StreamThenThrow); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(0, _strong.Calls + _local.Calls); // 503 is retryable, but content was already emitted + Assert.Equal("partial ".Length, ctx.PartialOutputChars); // partial output preserved as a fact + var a = Assert.Single(e.Attempts!); + Assert.Equal("failed", a.Outcome); + Assert.Equal("5xx", a.ErrorClass); + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.Equal("estimated_failed_call", e.CostBasis); + } + + [Fact] + public async Task Streaming_failure_before_any_chunk_may_fall_back() + { + _mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.BadGateway)); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal("gpt-4o", e.ServedByModel); + Assert.Equal(2, e.Attempts!.Count); + } + + [Fact] + public async Task Pause_tripped_between_attempts_refuses_the_second_attempt_at_pause() + { + var rig = Rig(); + _mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)); + _mini.OnCall = () => rig.Kill.Trip("operator pause mid-request"); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + + Assert.True(ctx.IsDenied); + Assert.Equal("pause", e.StoppedAtStage); + Assert.Equal("Governance", e.DenialKind); + Assert.Contains("kill switch engaged", e.Reason, StringComparison.Ordinal); + Assert.Equal(0, _strong.Calls); + Assert.Single(e.Attempts!); // the refused fallback never started + Assert.Contains(ctx.TraceEvents, t => t.Stage == "pause" && t.AttemptId == "att_2" && t.State == TraceStates.Refused); + Assert.True(e.Usage.CostUsd > 0m); // the failed first attempt is still charged + Assert.Equal(0, rig.Ledger.OpenReservations); + } + + [Fact] + public async Task Pause_before_the_request_refuses_with_no_attempt() + { + var rig = Rig(); + rig.Kill.Trip("maintenance"); + var (_, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal("pause", e.StoppedAtStage); + Assert.Empty(e.Attempts!); + Assert.Equal(0, _mini.Calls + _strong.Calls + _local.Calls); + } + + [Fact] + public async Task Policy_denial_makes_no_attempt() + { + var rig = Rig(); + var (_, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", model: "openai/not-a-target"); + Assert.Equal("policy", e.StoppedAtStage); + Assert.Empty(e.Attempts!); + Assert.Equal(0, _mini.Calls + _strong.Calls + _local.Calls); + } + + [Fact] + public async Task Caller_cancellation_is_not_a_provider_failure_and_never_falls_back() + { + _mini.Then(StubChatClient.Mode.Hang); + var rig = Rig(); + using var cts = new CancellationTokenSource(); + var run = rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", ct: cts.Token); + await _mini.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + cts.Cancel(); + var (ctx, e) = await run; + + Assert.Equal(DenialKind.Cancelled, ctx.DenialKind); + Assert.Equal("Cancelled", e.DenialKind); + Assert.Equal(0, _strong.Calls + _local.Calls); + var a = Assert.Single(e.Attempts!); + Assert.Equal("cancelled", a.Outcome); + Assert.Equal("client_cancelled", a.ErrorClass); + Assert.NotEqual("failed", rig.Health.Get($"openai:{V2.CloudModel}").State); // no health penalty for the provider + // Cancellation settles the (possibly billed) attempt at its estimate and releases the reservation. + Assert.Equal(a.ReservedUsd, a.CostUsd); + Assert.Equal(0, rig.Ledger.OpenReservations); + Assert.Equal(0m, rig.Ledger.Reserved("global")); + Assert.Equal(a.CostUsd, rig.Ledger.Spent("global", BudgetPeriod.Monthly)); + } + + [Fact] + public async Task Model_override_pins_one_target_with_no_fallback() + { + _mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", model: $"openai/{V2.CloudModel}"); + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Single(e.Attempts!); + Assert.Equal(0, _strong.Calls + _local.Calls); + } + + [Fact] + public async Task Sensitive_request_whose_local_primary_fails_never_reaches_a_cloud_target() + { + // Even a (validation-invalid) sensitive policy that lists a cloud fallback cannot make it eligible: the engine + // excludes cloud destinations for PII/PHI, so the failing local primary is terminal. + _local.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)); + var rig = Rig(tweak: c => c with + { + Policies = c.Policies.Select(p => p.Id != "sensitive" ? p : p with + { + Targets = [V2.T("ollama", V2.LocalTag), V2.T("openai", V2.CloudModel), V2.T("openai", "gpt-4o")], + Retry = new RetrySettings { MaxAttempts = 3, DeadlineMs = 60_000 }, + }).ToList(), + }); + var (ctx, e) = await rig.RunAsync("Customer SSN 078-05-1120 needs a summary.", profile: "public-demo"); + + Assert.Equal(DataClassification.Pii, e.Classification); + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(1, _local.Calls); + Assert.Equal(0, _mini.Calls + _strong.Calls); + Assert.Equal("ollama", Assert.Single(e.Attempts!).ConnectionId); + Assert.All(ctx.Policy!.Candidates, c => Assert.Equal("ollama", c.AdapterKey)); + } + + [Fact] + public async Task The_enforced_output_bound_is_sent_to_the_provider() + { + var rig = Rig(); + await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal(RequestBounds.DefaultOutputTokens, _mini.LastOptions?.MaxOutputTokens); // application default 1024 + + await rig.RunAsync(V2Rig.PublicPrompt + " again", profile: "public-demo", maxTokens: 64); + Assert.Equal(64, _mini.LastOptions?.MaxOutputTokens); // min(request, application) + + await rig.RunAsync(V2Rig.PublicPrompt + " once more", profile: "public-demo", maxTokens: 100_000); + Assert.Equal(RequestBounds.DefaultOutputTokens, _mini.LastOptions?.MaxOutputTokens); // capped by the application + } +} + +/// SDK-aware failure classification (ADR-0013) — BCL shapes the stub providers raise. +public sealed class ProviderFailureClassifierTests +{ + [Theory] + [InlineData(429, "429")] + [InlineData(500, "5xx")] + [InlineData(502, "5xx")] + [InlineData(503, "5xx")] + [InlineData(504, "5xx")] + [InlineData(501, "non_retryable")] + [InlineData(400, "non_retryable")] + [InlineData(401, "non_retryable")] + [InlineData(404, "non_retryable")] + public void Http_status_maps_to_the_bounded_class(int status, string expected) + => Assert.Equal(expected, SdkProviderFailureClassifier.Shared.Classify(Failures.Status((HttpStatusCode)status))); + + [Fact] + public void Transport_and_timeout_failures_are_classified() + { + var c = SdkProviderFailureClassifier.Shared; + Assert.Equal("connect", c.Classify(Failures.Connect())); + Assert.Equal("connect", c.Classify(new System.Net.Sockets.SocketException(10061))); + Assert.Equal("timeout", c.Classify(new TimeoutException())); + Assert.Equal("timeout", c.Classify(Failures.ProviderTimeout())); + Assert.Equal("5xx", c.Classify(new InvalidOperationException("wrapped", Failures.Status(HttpStatusCode.BadGateway)))); + Assert.Equal("connect", c.Classify(new System.ClientModel.ClientResultException("no response", null, null))); + Assert.Equal("non_retryable", c.Classify(new InvalidOperationException("anything else"))); + } +} diff --git a/tests/Covenant.Tests/RuntimeV2TestKit.cs b/tests/Covenant.Tests/RuntimeV2TestKit.cs new file mode 100644 index 0000000..0146919 --- /dev/null +++ b/tests/Covenant.Tests/RuntimeV2TestKit.cs @@ -0,0 +1,252 @@ +using System.Net; +using System.Runtime.CompilerServices; +using Covenant.Adapters; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +/// Settable clock (no sleeps): budget periods, trace retention. +internal sealed class SettableClock(DateTimeOffset start) : TimeProvider +{ + private DateTimeOffset _now = start; + public override DateTimeOffset GetUtcNow() => _now; + public void Set(DateTimeOffset now) => _now = now; + public void Advance(TimeSpan by) => _now += by; +} + +/// Stub provider whose behaviour per call is scripted (never a paid provider). Each call dequeues the next +/// behaviour (the last one repeats). Records the ChatOptions it saw. +internal sealed class StubChatClient(string reply = "stub reply") : MEAI.IChatClient +{ + public enum Mode { Serve, ServeNoUsage, Throw, Hang, StreamThenThrow, ServeHugeUsage, StreamGated } + + /// StreamGated: the first chunk is sent, then the stream waits for this gate before finishing. + public TaskCompletionSource? Gate { get; set; } + + private readonly Queue<(Mode Mode, Func? Error)> _script = new(); + private (Mode Mode, Func? Error) _last = (Mode.Serve, null); + private int _calls; + + public int Calls => Volatile.Read(ref _calls); + public MEAI.ChatOptions? LastOptions { get; private set; } + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + /// Invoked when a call starts (before its behaviour), e.g. to trip the pause between attempts. + public Action? OnCall { get; set; } + + public StubChatClient Then(Mode mode, Func? error = null) + { + lock (_script) _script.Enqueue((mode, error)); + return this; + } + + private (Mode Mode, Func? Error) Next() + { + lock (_script) + { + if (_script.Count > 0) _last = _script.Dequeue(); + return _last; + } + } + + public async Task GetResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _calls); + LastOptions = options; + OnCall?.Invoke(); + Entered.TrySetResult(); + var (mode, error) = Next(); + switch (mode) + { + case Mode.Throw: + throw error?.Invoke() ?? new HttpRequestException("stub failure"); + case Mode.Hang: + await Task.Delay(Timeout.Infinite, cancellationToken); + break; + } + var usage = mode switch + { + Mode.ServeNoUsage => null, + Mode.ServeHugeUsage => new MEAI.UsageDetails { InputTokenCount = 1_000_000, OutputTokenCount = 1_000_000 }, + _ => new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 }, + }; + return new MEAI.ChatResponse(new MEAI.ChatMessage(MEAI.ChatRole.Assistant, reply)) { Usage = usage }; + } + + public async IAsyncEnumerable GetStreamingResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _calls); + LastOptions = options; + OnCall?.Invoke(); + Entered.TrySetResult(); + var (mode, error) = Next(); + await Task.Yield(); + if (mode == Mode.Throw) throw error?.Invoke() ?? new HttpRequestException("stub failure"); + if (mode == Mode.Hang) await Task.Delay(Timeout.Infinite, cancellationToken); + yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, "partial "); + if (mode == Mode.StreamGated && Gate is { } gate) await gate.Task.WaitAsync(cancellationToken); + if (mode == Mode.StreamThenThrow) throw error?.Invoke() ?? new HttpRequestException("connection reset mid-stream", null, HttpStatusCode.ServiceUnavailable); + yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply); + yield return new MEAI.ChatResponseUpdate { Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 })] }; + } + + public object? GetService(Type serviceType, object? serviceKey = null) => null; + public void Dispose() { } +} + +internal static class Failures +{ + public static Exception Status(HttpStatusCode code) => new HttpRequestException($"stub HTTP {(int)code}", null, code); + public static Exception Connect() => new HttpRequestException("stub connection refused", new System.Net.Sockets.SocketException(10061)); + public static Exception ProviderTimeout() => new TaskCanceledException("stub provider-side timeout"); +} + +/// Pure v2 pipeline (no Host): the Host's stage order with a bound configuration snapshot, the persistent-ledger +/// budget stage over an in-memory store, the SDK-aware classifier and observed health. +internal sealed class V2Rig +{ + public sealed class ListSink : IAuditSink + { + public List Entries { get; } = []; + public ValueTask EnqueueAsync(AuditEntry entry, CancellationToken cancellationToken = default) + { + lock (Entries) Entries.Add(entry); + return ValueTask.CompletedTask; + } + } + + public required InferencePipeline Pipeline { get; init; } + public required ListSink Sink { get; init; } + public required InMemoryLedgerStore Store { get; init; } + public required BudgetLedger Ledger { get; init; } + public required KillSwitch Kill { get; init; } + public required ProviderHealth Health { get; init; } + public RuntimeSnapshot Snapshot { get; set; } = null!; + + public static V2Rig Build(CovenantConfig config, IReadOnlyDictionary clients, TimeProvider? clock = null, + ResponseCache? cache = null, BudgetLedger? ledger = null, InMemoryLedgerStore? store = null) + { + store ??= new InMemoryLedgerStore(); + ledger ??= new BudgetLedger(store, clock: clock); + var sink = new ListSink(); + var kill = new KillSwitch(); + var health = new ProviderHealth(); + var pipeline = new InferencePipeline( + [ + new AuditStage(sink), + new AuthStage(new AuthConfig + { + AllowAnonymous = false, + Keys = + [ + new ApiKeyRecord("demo-key", "demo-service", "platform", "demo-app"), + new ApiKeyRecord("batch-key", "batch-app", "data"), + ], + }), + new ShapeStage(), + new ClassifyStage(new RegexDataClassifier()), + new PolicyStage(new PolicyEngine(new PolicyConfig { AllowedRoutes = new Dictionary>() })), + new CacheStage(cache ?? new ResponseCache(clock), new CacheConfig()), + new RateLimitStage(new RateCounter(), new RateCounter(), new RateLimitConfig()), + new PauseStage(kill), + new BudgetStage(kill, ledger), + new ProviderCallStage(new ChatClientRegistry(clients), health, classifier: SdkProviderFailureClassifier.Shared), + new AttributionStage(new PriceBook(new Dictionary())), + ]); + return new V2Rig { Pipeline = pipeline, Sink = sink, Store = store, Ledger = ledger, Kill = kill, Health = health, Snapshot = new RuntimeSnapshot(config) }; + } + + public async Task<(InferenceContext Ctx, AuditEntry Entry)> RunAsync(string prompt, string? profile = null, string key = "demo-key", + bool stream = false, int? maxTokens = null, string? model = null, CancellationToken ct = default) + { + var ctx = new InferenceContext(new InferenceRequest("caller", [new ChatMessage(ChatRole.User, prompt)], model, + new AttributionTags("self-declared", "wf", "uc"), Stream: stream, Credential: key, MaxOutputTokens: maxTokens, + RequestId: $"req_{Guid.NewGuid():n}", RequestedProfile: profile)); + ctx.Configuration = Snapshot; + ctx.ConfigVersion = Snapshot.Version; + var deltas = new System.Text.StringBuilder(); + if (stream) ctx.DeltaSink = (d, _) => { deltas.Append(d.Content); return ValueTask.CompletedTask; }; + int before; + lock (Sink.Entries) before = Sink.Entries.Count; + try + { + await Pipeline.ExecuteAsync(ctx, ct); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + // the caller cancelled: the record is still written (asserted by the caller) + } + lock (Sink.Entries) + { + if (Sink.Entries.Count != before + 1) throw new Xunit.Sdk.XunitException($"expected exactly one audit record, got {Sink.Entries.Count - before}"); + return (ctx, Sink.Entries[^1]); + } + } + + /// Hybrid demo config with a priced cloud primary and a priced second cloud fallback so fallback charges are + /// visible; Public → [openai/gpt-4o-mini, openai/gpt-4o, ollama/qwen3:8b] with the given retry settings. + public static CovenantConfig FallbackConfig(RetrySettings? retry = null, decimal cap = 100m, Func? tweak = null) + => V2.Hybrid(tweak: c => + { + var x = c with + { + Policies = c.Policies.Select(p => p.Id != "public" ? p : p with + { + Targets = [V2.T("openai", V2.CloudModel), V2.T("openai", "gpt-4o"), V2.T("ollama", V2.LocalTag)], + Retry = retry ?? new RetrySettings { MaxAttempts = 3, DeadlineMs = 60_000 }, + }).ToList(), + Budgets = [new BudgetConfigV2 { Id = "global", Scope = "global", CapUsd = cap, Period = BudgetPeriod.Monthly }], + }; + return tweak is null ? x : tweak(x); + }); + + public const string PublicPrompt = "Rewrite this public product announcement in one sentence."; +} + +/// A Host booted from the demo-hybrid seed with stub providers on a caller-chosen audit path, optionally NOT +/// deleting its files on dispose — so a second instance can boot on the same audit log, configuration and ledger +/// (restart tests). Cloud price from the seed: $0.15 / $0.60 per 1M. +public sealed class RestartableHybridFactory(string auditPath, bool cleanup = true) : WebApplicationFactory +{ + public string AuditPath { get; } = auditPath; + public string LedgerPath => AuditPath + ".ledger.jsonl"; + internal StubChatClient Local { get; } = new("local reply"); + internal StubChatClient Cloud { get; } = new("cloud reply"); + + public static string NewAuditPath() => Path.Combine(Path.GetTempPath(), $"covenant-t04-{Guid.NewGuid():n}.log"); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Production"); + builder.UseSetting("Config:Seed", "demo-hybrid"); + builder.UseSetting("OpenAI:ApiKey", HybridSeedFactory.Secret); + builder.UseSetting("Anthropic:ApiKey", ""); + builder.UseSetting("Local:Endpoint", "http://127.0.0.1:11434/v1"); + builder.UseSetting("Local:ModelId", V2.LocalTag); + builder.UseSetting("Admin:Token", CorrelationTestKit.AdminToken); + builder.UseSetting("Budget:GlobalCapUsd", "100"); + builder.UseSetting("Auth:Keys:0:Key", "demo-key"); + builder.UseSetting("Auth:Keys:0:Principal", "demo-service"); + builder.UseSetting("Auth:Keys:0:Team", "platform"); + builder.UseSetting("Auth:Keys:0:Application", "demo-app"); + CorrelationTestKit.IsolatePaths(builder, AuditPath); + builder.ConfigureTestServices(services => + services.AddSingleton(new ChatClientRegistry(new Dictionary + { + [$"ollama:{V2.LocalTag}"] = Local, + [$"openai:{V2.CloudModel}"] = Cloud, + }))); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (cleanup) CorrelationTestKit.DeleteWithSiblings(AuditPath); + } +} diff --git a/tests/Covenant.Tests/TraceTests.cs b/tests/Covenant.Tests/TraceTests.cs new file mode 100644 index 0000000..e9b155f --- /dev/null +++ b/tests/Covenant.Tests/TraceTests.cs @@ -0,0 +1,240 @@ +using System.Net; +using System.Text.Json; +using Covenant.Core; +using Covenant.Host; +using Xunit; + +namespace Covenant.Tests; + +/// ADR-0013 real request trace: emitted by the pipeline itself (server UTC time, Stopwatch durations, bounded +/// reason codes), buffered BEFORE the pipeline starts, served as snapshot and SSE (replay-then-live, Last-Event-ID), +/// skipped stages explicit, compact summary persisted in the audit record. +public sealed class TraceTests : IDisposable +{ + private static readonly string[] Stages = ["auth", "shape", "classify", "policy", "cache", "rate_limit", "pause", "budget", "provider", "attribution"]; + + private readonly HybridSeedFactory _factory = new(); + private readonly HttpClient _client; + + public TraceTests() => _client = _factory.CreateClient(); + + public void Dispose() => _factory.Dispose(); + + private static List<(long Id, string? Event, JsonElement Data)> ParseSse(string body) + { + var list = new List<(long, string?, JsonElement)>(); + foreach (var block in body.Split("\n\n", StringSplitOptions.RemoveEmptyEntries)) + { + long id = 0; + string? evt = null; + string? data = null; + foreach (var line in block.Split('\n')) + { + if (line.StartsWith("id: ", StringComparison.Ordinal)) id = long.Parse(line[4..], System.Globalization.CultureInfo.InvariantCulture); + else if (line.StartsWith("event: ", StringComparison.Ordinal)) evt = line[7..]; + else if (line.StartsWith("data: ", StringComparison.Ordinal)) data = line[6..]; + } + if (data is null) continue; + list.Add((id, evt, JsonDocument.Parse(data).RootElement.Clone())); + } + return list; + } + + private async Task RunConsoleAsync(string json) + { + using var resp = await Playground.PostAsync(_client, json); + return CorrelationTestKit.HeaderId(resp); + } + + private async Task<(HttpStatusCode Status, string Body)> GetAsync(string path, string? lastEventId = null) + { + using var req = CorrelationTestKit.Admin(HttpMethod.Get, path); + if (lastEventId is not null) req.Headers.TryAddWithoutValidation("Last-Event-ID", lastEventId); + using var resp = await _client.SendAsync(req); + return (resp.StatusCode, await resp.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task Subscribing_after_completion_replays_every_event_then_ends() + { + var id = await RunConsoleAsync(Playground.Body("demo-app", "Summarize this public announcement.", profile: "public-demo")); + var (status, body) = await GetAsync($"/admin/requests/{id}/trace/stream"); + Assert.Equal(HttpStatusCode.OK, status); + var events = ParseSse(body); + Assert.Equal("end", events[^1].Event); + var data = events.Where(e => e.Event is null).ToList(); + Assert.Equal(Enumerable.Range(1, data.Count).Select(i => (long)i), data.Select(e => e.Id)); // monotonic seq from 1 + Assert.All(data, e => Assert.Equal(id, e.Data.GetProperty("request_id").GetString())); + Assert.All(data, e => Assert.Equal(1, e.Data.GetProperty("config_version").GetInt32())); + + foreach (var stage in Stages) + { + Assert.Contains(data, e => e.Data.GetProperty("stage").GetString() == stage && e.Data.GetProperty("state").GetString() == "running"); + var terminal = data.Last(e => e.Data.GetProperty("stage").GetString() == stage && e.Data.GetProperty("state").GetString() != "running"); + Assert.Equal("passed", terminal.Data.GetProperty("state").GetString()); + Assert.True(terminal.Data.GetProperty("duration_ms").GetDouble() >= 0); + } + var attempt = data.First(e => e.Data.TryGetProperty("attempt_id", out _)); + Assert.Equal("att_1", attempt.Data.GetProperty("attempt_id").GetString()); + Assert.Equal($"openai/{V2.CloudModel}", attempt.Data.GetProperty("target").GetString()); + Assert.DoesNotContain("public announcement", body, StringComparison.Ordinal); // never content + Assert.DoesNotContain("cloud reply", body, StringComparison.Ordinal); + + // Snapshot: same events, complete. + var (snapStatus, snap) = await GetAsync($"/admin/requests/{id}/trace"); + Assert.Equal(HttpStatusCode.OK, snapStatus); + using var doc = JsonDocument.Parse(snap); + Assert.True(doc.RootElement.GetProperty("complete").GetBoolean()); + Assert.Equal(data.Count, doc.RootElement.GetProperty("events").GetArrayLength()); + + // Durable compact summary in the audit record. + var audit = await CorrelationTestKit.LookupAsync(_client, id); + Assert.NotNull(audit.Trace); + Assert.All(Stages.Where(s => s != "provider"), s => Assert.Contains(audit.Trace!, t => t.Stage == s && t.State == "passed")); + Assert.Contains(audit.Trace!, t => t.Stage == "provider" && t.AttemptId == "att_1" && t.State == "passed"); + } + + [Fact] + public async Task Last_Event_ID_resumes_after_the_given_sequence() + { + var id = await RunConsoleAsync(Playground.Body("demo-app", "an internal question")); + var (_, all) = await GetAsync($"/admin/requests/{id}/trace/stream"); + int total = ParseSse(all).Count(e => e.Event is null); + var (_, resumed) = await GetAsync($"/admin/requests/{id}/trace/stream", lastEventId: "5"); + var events = ParseSse(resumed).Where(e => e.Event is null).ToList(); + Assert.Equal(total - 5, events.Count); + Assert.Equal(6, events[0].Id); + Assert.Equal("end", ParseSse(resumed)[^1].Event); + } + + [Fact] + public async Task Refusal_marks_every_stage_not_entered_as_skipped_not_reached() + { + var id = await RunConsoleAsync(Playground.Body("demo-app", "hello", profile: "not-granted")); + var (_, snap) = await GetAsync($"/admin/requests/{id}/trace"); + using var doc = JsonDocument.Parse(snap); + var events = doc.RootElement.GetProperty("events").EnumerateArray().ToList(); + var auth = events.Last(e => e.GetProperty("stage").GetString() == "auth"); + Assert.Equal("refused", auth.GetProperty("state").GetString()); + Assert.Equal("governance_denied", auth.GetProperty("reason_code").GetString()); + foreach (var stage in Stages.Skip(1)) + { + var ev = Assert.Single(events, e => e.GetProperty("stage").GetString() == stage); + Assert.Equal("skipped", ev.GetProperty("state").GetString()); + Assert.Equal("not_reached", ev.GetProperty("reason_code").GetString()); + } + var entry = await CorrelationTestKit.LookupAsync(_client, id); + Assert.Contains(entry.Trace!, t => t.Stage == "provider" && t.State == "skipped" && t.ReasonCode == "not_reached"); + Assert.Empty(entry.Attempts!); + } + + [Fact] + public async Task A_subscriber_joining_mid_request_gets_the_early_events_then_live_ones_until_the_end() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var client = factory.CreateClient(); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + factory.Cloud.Gate = gate; + factory.Cloud.Then(StubChatClient.Mode.StreamGated); + + // Streaming console request: headers (with the request id) commit on the first delta; the provider then waits. + using var req = CorrelationTestKit.Admin(HttpMethod.Post, "/admin/playground/requests"); + req.Content = new StringContent(Playground.Body("demo-app", "Summarize this public announcement.", profile: "public-demo", stream: true), + System.Text.Encoding.UTF8, "application/json"); + using var resp = await client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + + using var streamReq = CorrelationTestKit.Admin(HttpMethod.Get, $"/admin/requests/{id}/trace/stream"); + using var stream = await client.SendAsync(streamReq, HttpCompletionOption.ResponseHeadersRead); + Assert.Equal(HttpStatusCode.OK, stream.StatusCode); + + using var snapReq = CorrelationTestKit.Admin(HttpMethod.Get, $"/admin/requests/{id}/trace"); + using var snapResp = await client.SendAsync(snapReq); + using (var snap = JsonDocument.Parse(await snapResp.Content.ReadAsStringAsync())) + { + Assert.False(snap.RootElement.GetProperty("complete").GetBoolean()); // still in flight + var first = snap.RootElement.GetProperty("events")[0]; + Assert.Equal(1, first.GetProperty("seq").GetInt64()); + Assert.Equal("auth", first.GetProperty("stage").GetString()); // the very first event was retained + Assert.Equal("running", first.GetProperty("state").GetString()); + } + + gate.SetResult(); + var body = await stream.Content.ReadAsStringAsync(); // completes when the server writes event: end + await resp.Content.ReadAsStringAsync(); + var events = ParseSse(body); + Assert.Equal("end", events[^1].Event); + var data = events.Where(e => e.Event is null).ToList(); + Assert.Equal(1, data[0].Id); + Assert.Equal(Enumerable.Range(1, data.Count).Select(i => (long)i), data.Select(e => e.Id)); + Assert.Contains(data, e => e.Data.GetProperty("stage").GetString() == "attribution" && e.Data.GetProperty("state").GetString() == "passed"); + } + + [Fact] + public async Task Unknown_trace_is_404_and_malformed_id_is_400() + { + var (status, _) = await GetAsync("/admin/requests/req_00000000000000000000000000000000/trace"); + Assert.Equal(HttpStatusCode.NotFound, status); + var (streamStatus, _) = await GetAsync("/admin/requests/req_00000000000000000000000000000000/trace/stream"); + Assert.Equal(HttpStatusCode.NotFound, streamStatus); + var (bad, _) = await GetAsync("/admin/requests/bad%20id/trace"); + Assert.Equal(HttpStatusCode.BadRequest, bad); + using var noToken = await _client.GetAsync("/admin/requests/req_00000000000000000000000000000000/trace"); + Assert.Equal(HttpStatusCode.Unauthorized, noToken.StatusCode); + } +} + +/// TraceHub bounds and retention (no Host). +public sealed class TraceHubTests +{ + private static PipelineTraceEvent Ev(string stage, string state) => new(stage, state, DateTimeOffset.UtcNow); + + [Fact] + public void Expired_traces_are_410_not_404_and_unknown_ids_are_404() + { + var clock = new SettableClock(DateTimeOffset.Parse("2026-10-17T10:00:00Z")); + var hub = new TraceHub(clock); + var b = hub.Begin("req_a", 1, retentionMinutes: 10); + b.Append(Ev("auth", "running")); + b.Complete(clock.GetUtcNow()); + clock.Advance(TimeSpan.FromMinutes(9)); + Assert.Equal(TraceHub.Lookup.Found, hub.TryGet("req_a", out _)); + clock.Advance(TimeSpan.FromMinutes(2)); + Assert.Equal(TraceHub.Lookup.Expired, hub.TryGet("req_a", out _)); + Assert.Equal(TraceHub.Lookup.Unknown, hub.TryGet("req_never", out _)); + } + + [Fact] + public void Events_and_requests_are_bounded() + { + var hub = new TraceHub(maxRequests: 3, maxEventsPerRequest: 4); + var b = hub.Begin("req_0", 1, 10); + for (int i = 0; i < 10; i++) b.Append(Ev("auth", "running")); + var snap = b.Snapshot(); + Assert.Equal(4, snap.Events.Count); + Assert.True(snap.Truncated); + b.Complete(DateTimeOffset.UtcNow); + + for (int i = 1; i <= 3; i++) hub.Begin($"req_{i}", 1, 10); // a 4th buffer evicts the oldest COMPLETED one + Assert.Equal(TraceHub.Lookup.Expired, hub.TryGet("req_0", out _)); + Assert.Equal(TraceHub.Lookup.Found, hub.TryGet("req_3", out _)); + } + + [Fact] + public void A_completed_buffer_accepts_no_more_events_and_wakes_waiters() + { + var hub = new TraceHub(); + var b = hub.Begin("req_x", 2, 10); + var (_, complete, changed) = b.Since(0); + Assert.False(complete); + b.Append(Ev("auth", "running")); + Assert.True(changed.IsCompleted); + var (_, _, next) = b.Since(1); + b.Complete(DateTimeOffset.UtcNow); + Assert.True(next.IsCompleted); + b.Append(Ev("shape", "running")); + Assert.Single(b.Snapshot().Events); + Assert.Equal(2, b.Snapshot().ConfigVersion); + } +} From 96deed50dff2c7bc745410067741f8a8775b17b7 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Sat, 17 Oct 2026 01:03:55 -0400 Subject: [PATCH 08/14] feat(ui): editable connections, policies, budgets, settings; requests archive + evidence export (T08 checkpoint) --- docs/console-v2-progress.md | 432 ++++++++++ .../Components/ConnectionEditor.razor | 497 ++++++++++++ src/Covenant.Ui/Components/EditorBar.razor | 304 +++++++ src/Covenant.Ui/Components/FieldIssues.razor | 22 + .../Components/ImpactPreview.razor | 103 +++ .../Components/PolicySimulator.razor | 171 ++++ src/Covenant.Ui/Layout/MainLayout.razor | 13 + src/Covenant.Ui/Logic/BudgetView.cs | 150 ++++ src/Covenant.Ui/Logic/ConfigDraft.cs | 291 +++++++ src/Covenant.Ui/Logic/ConnectionDrafts.cs | 416 ++++++++++ src/Covenant.Ui/Logic/ConnectionLogic.cs | 50 +- src/Covenant.Ui/Logic/CostText.cs | 3 +- src/Covenant.Ui/Logic/ImpactText.cs | 60 ++ src/Covenant.Ui/Logic/Money.cs | 85 ++ src/Covenant.Ui/Logic/PolicyRoutes.cs | 266 +++++++ src/Covenant.Ui/Logic/RequestFilter.cs | 16 +- src/Covenant.Ui/Logic/SegmentScope.cs | 79 ++ src/Covenant.Ui/Models/ConfigContracts.cs | 56 ++ src/Covenant.Ui/Models/Contracts.cs | 49 ++ src/Covenant.Ui/Pages/Budgets.razor | 515 ++++++++---- src/Covenant.Ui/Pages/Connections.razor | 691 +++++++--------- src/Covenant.Ui/Pages/Evidence.razor | 391 ++++++--- src/Covenant.Ui/Pages/Policies.razor | 473 ++++++++--- src/Covenant.Ui/Pages/Requests.razor | 424 +++++++--- src/Covenant.Ui/Pages/Settings.razor | 353 ++++++--- src/Covenant.Ui/Program.cs | 1 + src/Covenant.Ui/Services/AdminApi.cs | 84 ++ src/Covenant.Ui/Services/ConfigEditor.cs | 399 ++++++++++ src/Covenant.Ui/Services/Fmt.cs | 10 +- src/Covenant.Ui/Services/Interop.cs | 7 +- src/Covenant.Ui/Services/PlaygroundState.cs | 12 + src/Covenant.Ui/Services/RequestsViewState.cs | 49 +- src/Covenant.Ui/wwwroot/css/app.css | 97 +++ src/Covenant.Ui/wwwroot/js/interop.js | 13 +- tests/Covenant.Tests/ConsoleLogicTests.cs | 745 +++++++++++++++++- .../Covenant.Tests/ContractRoundTripTests.cs | 256 ++++++ 36 files changed, 6506 insertions(+), 1077 deletions(-) create mode 100644 src/Covenant.Ui/Components/ConnectionEditor.razor create mode 100644 src/Covenant.Ui/Components/EditorBar.razor create mode 100644 src/Covenant.Ui/Components/FieldIssues.razor create mode 100644 src/Covenant.Ui/Components/ImpactPreview.razor create mode 100644 src/Covenant.Ui/Components/PolicySimulator.razor create mode 100644 src/Covenant.Ui/Logic/BudgetView.cs create mode 100644 src/Covenant.Ui/Logic/ConfigDraft.cs create mode 100644 src/Covenant.Ui/Logic/ConnectionDrafts.cs create mode 100644 src/Covenant.Ui/Logic/ImpactText.cs create mode 100644 src/Covenant.Ui/Logic/Money.cs create mode 100644 src/Covenant.Ui/Logic/PolicyRoutes.cs create mode 100644 src/Covenant.Ui/Logic/SegmentScope.cs create mode 100644 src/Covenant.Ui/Services/ConfigEditor.cs diff --git a/docs/console-v2-progress.md b/docs/console-v2-progress.md index 747568a..1d0c8d3 100644 --- a/docs/console-v2-progress.md +++ b/docs/console-v2-progress.md @@ -461,3 +461,435 @@ dotnet test tests/Covenant.Tests -c Release --disable-build-servers # full s Manual: `POST /admin/config/validate` with `"settings": null` → 200 `valid:false` path `settings`; `"mode": 999` → `invalid_enum` at `mode`; same bodies via PUT → 422; drop a fake `versions/v000002.json` into the config dir → `GET /admin/config/versions/2` 404, next apply becomes v3. + +--- + +## T04/T05/T06 backend — budget periods + reservations, console inference + real trace, approved fallback / cache / cost / archive + +**Status: NOT EXECUTED — no .NET SDK in the authoring sandbox.** Nothing below has been compiled or run. Written for +Nullable + TreatWarningsAsErrors + IsAotCompatible (source-generated JSON only; every new minimal-API async lambda is +`async Task (…) =>`). SDK exception types were verified against the referenced assemblies' metadata in the local +build output (Anthropic 12.8.0: `Anthropic.Exceptions.AnthropicApiException.StatusCode : System.Net.HttpStatusCode`, +`AnthropicIOException`; System.ClientModel 1.14.0: `ClientResultException.Status : int`), not compiled. Treat every claim +as *implemented, unverified* until the verifier commands below pass. + +### What is implemented + +- **T04 budgets (ADR-0014).** `BudgetLedger` (Governance, pure) over `ILedgerStore`: append-only reserve / settle / + release / settle-recovered / legacy-import records keyed (requestId, attemptId) with the charged SCOPES (`global`, + `team:`, `application:`) and a UTC timestamp — never a budget id or period id. Spend per budget = settled amounts + of its scope in its current UTC window (none ⇒ all time), computed at read time from per-(scope, period-bucket) totals, + so renaming a budget / changing its period or cap never resets accrual. One lock; `spent + reserved + bound ≤ cap` for + every applicable HARD budget, all-or-none; the record is appended durably before memory changes. `FileLedgerStore` + (Host): `Budget:LedgerPath` (default `.ledger.jsonl`), JSONL, fsync per append, torn-tail quarantine + (`.torn-`) + atomic rewrite before any append, refuses to append onto an unterminated line, corrupt earlier line ⇒ + refuse to start, failed append ⇒ `Environment.FailFast` (like a failed audit write). Boot: replay; open reservations ⇒ + `settle-recovered` at the reserved amount + a `budget.recovered` audit event; no ledger file ⇒ the current audit + segment's spend is imported once (`legacy-import`, global + team scopes) and the file is created. The audit-replay + in-memory ledger is gone from the Host; `/admin/reset` no longer touches spend (an archive never reopens a budget). + `BudgetStage(killSwitch, BudgetLedger)` (configured requests): installs the per-request `BudgetAttemptGate` and reserves + attempt 1 for the primary candidate (refusal ⇒ 403 at stage `budget`, code `budget_exceeded`); the legacy constructor and + path are unchanged for pure compositions. Bound per attempt = (UTF-8 bytes of all contents + 16/message) × input price + + min(request max_tokens, application max_output_tokens, model max_output_tokens) × output price; that output bound is + now sent as `ChatOptions.MaxOutputTokens` (`RequestBounds`, Core). Settle exactly once with the attributed cost; usage + unreported ⇒ the reservation bound (`estimated_from_text`); reported cost above the reservation ⇒ settled in full, + `Overrun` in the attempt evidence and the ledger record; release of the remainder in the same durable write; failed / + cancelled attempts settle at their bound (`estimated_failed_call`); an admitted attempt that never started is released; + the budget stage's `finally` closes anything left open. Explicit $0 local prices reserve and write nothing. Warn-only + budgets never block; warnings are status only. Unpriced paid (cloud) targets under a hard budget: verified ineligible in + `PolicyEngineV2.Ineligibility` and a validation error (`unpriced_paid_target_under_hard_budget`) — no change needed. + APIs: `GET /admin/budgets`, `GET /admin/budgets/{id}/requests`; `/admin/status.budget` reads the ledger. +- **T05 console inference (ADR-0012).** `POST /admin/playground/requests` (`PlaygroundApi`): admin auth; 400 before the + pipeline (no audit) for malformed/invalid bodies; `client_request_id` claimed atomically (`ConsoleSubmissions`, 10 min, + bounded) ⇒ 409 `duplicate_submission` with the original `request_id`; the application is resolved server-side and bound + with `ctx.BindConsoleIdentity(…, "shared-admin-token")`; the response is produced by `ChatCompletions.RunAsync`, the + former `/v1/chat/completions` handler body (now shared — `/v1` calls the same function); `X-Covenant-Request-Id` on every + answer; `RequestAborted` propagates. `GET /admin/applications` already existed (T03). +- **T05 trace (ADR-0013).** Core: `PipelineTraceEvent`, `InferenceContext.TraceSink` / `Trace()` / `CompleteTrace()` / + `CompactTrace()`; `InferencePipeline.RunStageAsync` emits running → passed (Stopwatch duration at hand-over) / refused / + failed / cancelled with bounded reason codes (`ctx.Deny(…, code:)`), and `skipped` (`not_reached` | `cache_hit`) for + stages never entered; the audit stage is not traced. Provider attempts emit attempt events (`att_N`, target), fallback + pause/budget re-checks emit attempt-level `pause`/`budget` events. Host: `TraceHub` singleton (≤ 64 events/request, + ≤ 2 000 requests, retention `trace_retention_minutes` after completion, remembered expired ids ⇒ 410), buffer created + BEFORE the pipeline for `/v1/chat/completions`, `/v1/messages` and console inference; `GET /admin/requests/{id}/trace` + and `/trace/stream` (SSE `id:`/`data:`, replay then live, `Last-Event-ID`, `: keep-alive`, `event: end`, 404/410/400). + New `PauseStage` (Governance) between rate limit and budget gives the global pause its own trace stage (the budget + stage keeps its own check for legacy compositions). +- **T05/T06 audit v3.** `AuditEntry` + `Attempts[]` (`AuditAttempt`: id, connection, model, outcome, error class, + duration, cost, basis, reserved, overrun), `Trace[]` (`AuditTraceStep`), `ReservedUsd`, `SettledUsd` (additive, + nullable, written only when a configuration is bound). `Usage.CostUsd` = total settled for the request. +- **T06 fallback (ADR-0013).** `ProviderCallStage` iterates `PolicyOutcome.Candidates` when a configuration and a policy + retry block exist (legacy compositions: one attempt on `Route`, unchanged). Before EACH attempt the gate re-checks the + pause and reserves. Failure classes via `IProviderFailureClassifier` (Adapters interface, BCL default + `BclProviderFailureClassifier`; Host `SdkProviderFailureClassifier`: `ClientResultException.Status`, + `AnthropicApiException.StatusCode`, `AnthropicIOException` ⇒ connect, HttpRequestException status/connect, + SocketException ⇒ connect, TimeoutException / provider-side cancellation ⇒ timeout; 429 ⇒ `429`; 500/502/503/504 ⇒ + `5xx`; anything else ⇒ `non_retryable`). Fallback only for classes in `retry.on`, within `max_attempts` and + `deadline_ms`, never after content was emitted, never on caller cancellation (rethrown), pause, policy denial or + non-retryable errors. Health per `connection:model` from every real attempt. `ServedTarget` drives attribution/pricing. + PII/PHI: verified cloud candidates are excluded by the engine in every mode (test added). +- **T06 cache.** v2 key = SHA-256 over application, team, profile, FINAL classification, config version, the ordered + approved candidates (connection/model), the enforced output bound and the messages; hits after auth/shape/classify/ + policy, before rate-limit/pause/budget/provider (a hit is served during a global pause), `no_call`, `CacheHit`, original + served model; only successful complete responses are stored. +- **T06 savings.** `FinOps.Build(…, savingsBaseline)` + `FinOpsSummary.Savings` (`SavingsSummary`): present only when the + configuration's `savings_baseline` is a priced connection/model; route-avoided and cache-avoided reported separately; + estimated/unknown records excluded and counted. Without a baseline every savings figure is 0 and `savings` is null. + The 4-argument `FinOps.Build` keeps its pre-v2 behaviour (FinOpsTests unchanged). +- **T06 archive.** `AuditSegments` + `ArchiveApi`: `GET /admin/audit/segments` (current + `.yyyyMMdd-HHmmss.archived` + siblings, opaque ids `current` / `a-<16 hex>`), `GET /admin/requests?limit=&cursor=&segment=` (moved out of Program; + same `RequestsPage` + `segment.id/label`, `next_cursor`; unknown segment / malformed cursor ⇒ 400), + `GET /admin/requests/{id}/export` (no `PromptPreview`, attempts, trace, config version, integrity with line + hashes). + +### Files + +``` +src/Covenant.Core/Execution.cs new TraceStates, TraceReasons, PipelineTraceEvent, AttemptRecord, IAttemptGate, + AttemptAdmission, AttemptCharge, RequestBounds +src/Covenant.Core/InferenceContext.cs DenialCode + Deny(code:), AttemptGate, Attempts, ServedTarget, Active/Reserved/ + SettledUsd, TraceSink, Trace(), StageOrder, CompleteTrace(), CompactTrace() +src/Covenant.Core/Pipeline.cs per-stage trace instrumentation, TracedStages, CompleteTrace in ExecuteAsync +src/Covenant.Core/Decisions.cs AuditEntry v3 Attempts/Trace/ReservedUsd/SettledUsd; AuditAttempt; AuditTraceStep; + AuditEntryKinds.BudgetRecovered +src/Covenant.Adapters/ProviderLayer.cs IProviderFailureClassifier, BclProviderFailureClassifier, fallback loop +src/Covenant.Governance/BudgetLedger.cs new LedgerOps, LedgerRecord, ILedgerStore, InMemoryLedgerStore, BudgetCheck, + BudgetPeriods, BudgetLedger +src/Covenant.Governance/BudgetGate.cs new BudgetScopes, ReservationEstimate, BudgetAttemptGate +src/Covenant.Governance/Budget.cs PauseStage; BudgetStage v2 constructor + reservation path (legacy path kept) +src/Covenant.Governance/Attribution.cs served target; unreported usage ⇒ reservation bound under a v2 gate +src/Covenant.Governance/Cache.cs v3 key (candidates + enforced output bound) +src/Covenant.Governance/Audit.cs CompleteTrace before writing; Attempts/Trace/Reserved/Settled; Usage = settled +src/Covenant.Host/BudgetLedgerStore.cs new FileLedgerStore, LedgerJsonContext, BudgetStateView & co, BudgetViews, BudgetApi +src/Covenant.Host/Trace.cs new TraceEventView/SnapshotView, TraceJsonContext, TraceBuffer, TraceHub, TraceApi, + TraceCompletion +src/Covenant.Host/InferenceEndpoints.cs new ChatCompletions (shared OpenAI wire + DenialResult), PlaygroundRequest, + ConsoleSubmissions, PlaygroundApi +src/Covenant.Host/AuditSegments.cs new AuditSegments, SegmentView, RequestExport, ExportIntegrity, ArchiveApi +src/Covenant.Host/FailureClassifier.cs new SdkProviderFailureClassifier +src/Covenant.Host/Program.cs ledger boot (open/legacy import/recovery), PauseStage + BudgetStage v2 + classifier, + shared /v1 handler, /v1/messages trace, status from the ledger + savings, + reset without ledger reset, /admin/requests moved, new Map* calls +src/Covenant.Host/StatusContracts.cs SavingsSummary, FinOpsSummary.Savings, FinOps.Build overload +src/Covenant.Host/ConsoleBackend.cs RequestsPage.NextCursor, SegmentInfo.Id/Label +src/Covenant.Host/OpenAiContracts.cs CovenantJsonContext += PlaygroundRequest, List, BudgetRequestsView +src/Covenant.Host/FileAuditSink.cs AuditJsonContext += List, RequestExport +src/Covenant.Host/Evidence.cs LedgerReplay doc (no longer used by the Host) +tests/Covenant.Tests/RuntimeV2TestKit.cs new SettableClock, StubChatClient, Failures, V2Rig (pure v2 pipeline), RestartableHybridFactory +tests/Covenant.Tests/FallbackTests.cs new (+ ProviderFailureClassifierTests) +tests/Covenant.Tests/BudgetLedgerTests.cs new (+ BudgetPipelineTests) +tests/Covenant.Tests/CacheIsolationTests.cs new +tests/Covenant.Tests/ConsolePlaygroundTests.cs new (+ Playground helpers) +tests/Covenant.Tests/TraceTests.cs new (+ TraceHubTests) +tests/Covenant.Tests/BudgetHostTests.cs new +tests/Covenant.Tests/ArchiveExportTests.cs new (+ SavingsTests) +docs/ui-api-contract.md v2 "Implementation details" for console inference, trace, budgets, archive, + audit v3; new "Status FinOps savings" +``` + +### Endpoints + +`POST /admin/playground/requests` · `GET /admin/requests/{id}/trace` · `GET /admin/requests/{id}/trace/stream` · +`GET /admin/budgets` · `GET /admin/budgets/{id}/requests` · `GET /admin/audit/segments` · +`GET /admin/requests?limit=&cursor=&segment=` (extended) · `GET /admin/requests/{id}/export`. + +### Tests (each fails if its guarantee is removed) + +- `BudgetLedgerTests` — 16 parallel contenders behind a `Barrier` for the last allowance ⇒ exactly one reserves; + all-or-none across global/team; settle/release exactly once (double settle ignored, release after settle ignored, + journal = reserve/settle/release); overrun settled in full + flagged; per-scope UTC periods (Sep vs Oct vs all-time, + daily) and a renamed budget sees the same accrual; month rollover; restart replay + `settle-recovered` + no double + recovery; torn tail quarantined and repaired, then two more appends + restarts; corrupt middle line refuses start; + legacy import once. +- `BudgetPipelineTests` — bound = UTF-8 bytes + 16 and enforced output bound; reported settle by scope (global, team, + application); unreported ⇒ bound; overrun flagged in attempt evidence; hard cap ⇒ 403 at `budget` before any provider + call and zero-priced local still runs; warn-only never blocks; application-scope budget enforced; cancellation ⇒ + reserve/settle/release exactly once, nothing open; unpriced cloud excluded under a hard budget (+ validator code). +- `FallbackTests` — fallback on 429 / timeout / 500 / 502 / 503 / 504 / connect, both attempts charged (failed one at its + bound, `estimated_failed_call`), settled total = audit `Usage.CostUsd` = ledger spend, health per connection:model, + attempt-level pause/budget trace; no fallback on 400/401/403/404/422, on a class outside `retry.on`, beyond + `max_attempts`, past `deadline_ms` (hanging attempt ⇒ `timeout`), after the first streamed chunk (partial preserved, + failure recorded), on a pinned model override; streaming failure before any chunk may fall back; pause tripped between + attempts ⇒ refused at `pause`, first attempt still charged; pause / policy refusal ⇒ no attempt; caller cancellation ⇒ + `cancelled`, no fallback, no health penalty, settled once; sensitive request whose local primary fails never reaches + cloud (even with a cloud target smuggled into the policy); enforced output bound sent to the provider. + `ProviderFailureClassifierTests` — status/transport/timeout/inner-exception mapping. +- `CacheIsolationTests` — hit: no provider call, `no_call`, $0, `CacheHit`, original served model, no attempts, ledger + unchanged, later stages skipped `cache_hit`; isolation across applications/teams, profiles, configuration versions and + output bounds; hit served during a pause while a miss is refused at `pause`; current policy enforced before a hit; + failures and partial streams never stored. +- `ConsolePlaygroundTests` — buffered run as demo-app (same wire as /v1, `EntryPoint=console`, + `OperatorRef=shared-admin-token`, application/team/profile/version, trace, attempts, reserved/settled, no key/admin + token/provider secret in the payload); streaming SSE; disabled / not-console-testable / ungranted / unknown application + ⇒ governed 403 at `auth` with audit and no provider call; 7 invalid bodies ⇒ 400 with no audit record (FIFO proof); + duplicate `client_request_id` ⇒ 409 with the original id and no second call; admin token required; `/v1` still needs a + key (admin token ⇒ 401) and records `EntryPoint=v1`; submission window/bound. +- `TraceTests` — replay after completion (monotonic seq, all ten stages running→passed, attempt event with target, no + content), snapshot complete, compact audit `Trace[]`; `Last-Event-ID` resume; refusal at auth ⇒ every other stage + skipped `not_reached` (and in the audit summary); a subscriber joining mid-request gets seq 1 (`auth running`) then live + events until `event: end`; 404 unknown, 400 malformed, 401 without token. `TraceHubTests` — 410 after retention vs 404 + unknown; 64-event and request-count bounds (oldest completed evicted ⇒ 410); completed buffer immutable, waiters woken. +- `BudgetHostTests` — `/admin/budgets` + `/{id}/requests` (+404/401) and status from the ledger; `POST /admin/reset` + keeps spend; rename + period + cap-below-spend keeps accrual, blocks paid work at `budget`, local still served; + restart replays and recovers an open reservation (`budget.recovered` event); no ledger ⇒ one-time legacy import, not + repeated on the next boot. +- `ArchiveExportTests` — segments current + archived (opaque ids, no paths), paging an archived segment by cursor, + current-segment default; unknown ids / paths / traversal rejected (requests and export); malformed cursors rejected; + export excludes the opted-in prompt preview and the response, carries version/attempts/trace/integrity and still works + after an archive. `SavingsTests` — hidden without a baseline; route vs cache split; estimates excluded. + +### Existing assertions changed + +None. No existing test file was edited. Behaviour changes that existing tests could observe (all spec-mandated): +- Host pipeline gains a `pause` stage (`PauseStage`); the kill-switch denial text and `StoppedAtStage = "pause"` are + unchanged. +- Configured requests now send `max_tokens` = the enforced output bound (default 1024) to providers. +- `/admin/reset` no longer clears spend (ADR-0014 — archive never reopens a budget). +- `Usage.CostUsd` of a configured request = total settled (equal to the old value for single-attempt requests; for + failed calls the estimate is now the reservation bound instead of chars/4 — both `estimated_failed_call`, both > 0). +- `/admin/status.finops` savings figures are 0 (and `savings` null) when no priced `savings_baseline` is configured. + +### Decisions / deviations from the contract + +1. **Trace 404 vs 410:** the earlier v2 text said "404 unknown/expired"; implemented 404 = never traced, 410 = expired or + evicted (as the task and ADR-0013 require). Contract updated. +2. **Every request is traced** (`/v1` too), not only console requests — same bounded hub. +3. **Failed / cancelled attempts are charged their full reservation bound** (input bound + full output bound), the + conservative "possibly billed" estimate the task specifies — higher than the pre-v2 chars/4 estimate. +4. **Deadline semantics:** no attempt starts after `deadline_ms`; an attempt still waiting for its response (or, streaming, + its first content) at the deadline is cancelled as `timeout`; once streamed content flows the deadline stops applying + (a delivered answer is not cut off; the connection timeout governs). +5. **Cache key** includes the ordered approved candidate list (stricter than "connection + model": a response is reused only + for the same eligible route set). Keyed on the primary's enforced output bound. +6. **Ledger file failure** halts the process (`Environment.FailFast`), consistent with the audit sink. +7. `max_attempts` beyond the eligible candidates is simply bounded by the candidates (no repeated attempts on one target). +8. `SegmentInfo.path` is still returned by `GET /admin/requests` (it was already there for the current segment); segment + ids in the archive APIs are opaque and caller paths are never accepted. + +### Risks + +- **Unbuilt.** Highest compile risk: RDG on the new lambdas (all typed `async Task` or sync `IResult`); + source-gen for positional records with `IReadOnlyList<>` members in `AuditEntry`; `Anthropic.Exceptions` type names; + `ClientResultException(string, PipelineResponse?, Exception?)` in a test; collection expressions in tests. +- Host tests boot real Hosts with fsync'd ledger writes (slower on CI disks). +- The ledger keeps per-key idempotency for the last 200 000 closed attempts and the last 20 000 charges for drill-down. +- Streaming fallback uses the same SSE response: only possible before the first delta, so headers are not yet committed. + +### Verifier commands (not executed) + +``` +dotnet build Covenant.sln -c Release --disable-build-servers +dotnet test tests/Covenant.Tests -c Release --disable-build-servers --filter "FullyQualifiedName~BudgetLedgerTests|FullyQualifiedName~BudgetPipelineTests|FullyQualifiedName~FallbackTests|FullyQualifiedName~ProviderFailureClassifierTests|FullyQualifiedName~CacheIsolationTests|FullyQualifiedName~ConsolePlaygroundTests|FullyQualifiedName~TraceTests|FullyQualifiedName~TraceHubTests|FullyQualifiedName~BudgetHostTests|FullyQualifiedName~ArchiveExportTests|FullyQualifiedName~SavingsTests" +dotnet test tests/Covenant.Tests -c Release --disable-build-servers # full suite: all ~490 pre-existing tests unchanged and green +dotnet test tests/Covenant.Tests -c Release -p:SkipConsolePublish=true -o +``` +Manual (isolated port, `Config:Seed=demo-hybrid`, fresh `Audit:Path`): `POST /admin/playground/requests` with +`{"application_id":"demo-app","profile_id":"public-demo","messages":[{"role":"user","content":"Reply OK."}],"max_tokens":5,"stream":true}` +→ SSE + `X-Covenant-Request-Id`; `GET /admin/requests//trace/stream` → events then `event: end`; +`GET /admin/budgets` → `spent_usd` > 0, `reserved_usd` 0; `POST /admin/reset` → budgets unchanged; +`GET /admin/audit/segments` → `current` + one `a-…`; `GET /admin/requests//export` → no prompt text; restart → +budgets unchanged; resubmit the same `client_request_id` → 409. + +--- + +## T08 UI — editable admin pages and evidence workflows + +**Status: NOT EXECUTED.** Written without a .NET SDK (none in the authoring sandbox), so nothing below has been +compiled, unit-tested or opened in a browser. The budget ledger, fallback/trace and audit-archive endpoints were being +implemented concurrently by the backend agent (uncommitted at the time of writing); every UI call to them is +**integration pending** until the verifier steps below pass. Do not cite T08 as complete before then (spec §7). + +### Files + +``` +src/Covenant.Ui/Logic/Money.cs new USD with significant digits for sub-cent charges ($0.000184, $1.23, + "<$0.000001", never $0.00 for non-zero; null → "Not reported"); caps, + per-1M prices, shares +src/Covenant.Ui/Logic/ConfigDraft.cs new ConfigCopy (deep copy/canonical JSON via UiJsonContext), ConfigDraft (base + version + ETag + draft, content-based dirty tracking, Reset), ChangeSummary + (ids added/removed/changed per section — never values), EditOutcomes + (HTTP status+body → Applied | Stale | Invalid | PreconditionRequired | + Unauthorized | NotFound | Failed), IssueIndex (field-path lookup), IssueHelp +src/Covenant.Ui/Logic/ImpactText.cs new impact preview wording (changed routes, headline, needs-attention) +src/Covenant.Ui/Logic/PolicyRoutes.cs new PolicyText (labels, strategy names, pause semantics), PolicyRoutes + (structural eligibility, definite summary lines, refusal conditions, + add-target options, up/down reorder), HybridDefaults (legacy → hybrid draft) +src/Covenant.Ui/Logic/BudgetView.cs new BudgetText (period/scope/warning/enforcement/thresholds), BudgetRequests + (lenient parser for /admin/budgets/{id}/requests) +src/Covenant.Ui/Logic/SegmentScope.cs new segment labels/coverage sentence; EvidenceCompleteness (pending / + unavailable / recorded / verified / unverifiable) +src/Covenant.Ui/Logic/ConnectionDrafts.cs new ConnectionForm/ModelForm (add/edit, discovery merge, inline problems, + ToConnection/ApplyTo), ConnectionRules, ConnectionHealth (probe vs governed + call, one summary + timestamps) +src/Covenant.Ui/Logic/ConnectionLogic.cs old wizard helpers removed (CheckApplied, ConfigBlock, RouteReview) +src/Covenant.Ui/Logic/CostText.cs Usd → Money.Usd +src/Covenant.Ui/Logic/RequestFilter.cs + Application filter / Applications(); time label "All loaded records" +src/Covenant.Ui/Models/ConfigContracts.cs + ConfigErrorResponseDto, ImpactRow.changed, ValidationResult.active_version, + Simulate request.config / response dry_run, config_version, application_id, + profile, explanation, eligible[].boundary; BudgetState period_start/end; + BudgetRequestDto, AuditSegmentDto +src/Covenant.Ui/Models/Contracts.cs + status.config_version; requests.next_cursor; segment id/label/events; + catalog config_version/connections[]/egress_allow_list (+ CatalogConnectionDto, + CatalogConnectionModelDto); model connection_id/boundary/key; attempt + ReservedUsd/Overrun; UiJsonContext registers ConfigErrorResponseDto, + List +src/Covenant.Ui/Services/ConfigEditor.cs new shared editor service (load/version/ETag, draft, validate, save, conflict, + compare, history, rollback, reload after activation) +src/Covenant.Ui/Services/AdminApi.cs + RawResponse/SendRawAsync, validate/put/rollback (raw), versions, version n, + simulate, budget requests (raw JSON), segments, requests page, export +src/Covenant.Ui/Services/RequestsViewState.cs rewritten: one segment's pages, cursor, bounded (2 000), segments list +src/Covenant.Ui/Services/Fmt.cs Usd/UsdTotal delegate to Money +src/Covenant.Ui/Services/Interop.cs, wwwroot/js/interop.js prefGet/prefSet for allow-listed console preferences +src/Covenant.Ui/Services/PlaygroundState.cs StreamingDefault (browser-local preference) +src/Covenant.Ui/Layout/MainLayout.razor applies the stored "stream-default" preference once +src/Covenant.Ui/Program.cs registers ConfigEditor +src/Covenant.Ui/Components/EditorBar.razor new View/Edit bar: "Applied version vN", history drawer + inline rollback + confirm, Preview impact / Save & apply / Cancel, 412 conflict (Reload / + Compare), 422 banner, discard dialog, unsaved-change guard +src/Covenant.Ui/Components/ImpactPreview.razor new Host validation + impact rendering +src/Covenant.Ui/Components/FieldIssues.razor new inline errors/warnings for a field path +src/Covenant.Ui/Components/ConnectionEditor.razor new add/edit form (Ollama and cloud) with probe/discovery +src/Covenant.Ui/Components/PolicySimulator.razor new dry-run simulator (applied or unsaved draft) +src/Covenant.Ui/Pages/Connections.razor rewritten (7-step "edit a file" wizard removed) +src/Covenant.Ui/Pages/Policies.razor rewritten (route view, editable list, mode, simulator) +src/Covenant.Ui/Pages/Budgets.razor rewritten (ledger state, edit, drill-down) +src/Covenant.Ui/Pages/Settings.razor rewritten (operational / preferences / diagnostics / maintenance) +src/Covenant.Ui/Pages/Requests.razor rewritten (segments, cursor pages, application filter, drawer, export) +src/Covenant.Ui/Pages/Evidence.razor rewritten (decisions + evidence completeness first, integrity separate) +src/Covenant.Ui/wwwroot/css/app.css T08 block (editor bar, impact, connection cards, route view, budgets, …) +tests/Covenant.Tests/ConsoleLogicTests.cs removed the three wizard tests; "$0.003" expectation; + MoneyTests, + ConfigDraftTests, EditOutcomeTests, ImpactTextTests, PolicyRoutesTests, + SegmentScopeTests, BudgetTextTests, ConnectionFormTests, + ConnectionHealthTests, RequestFilterApplicationTests +tests/Covenant.Tests/ContractRoundTripTests.cs + validate request/response, write answers (412/422/200) → outcomes, version + history + rollback body, simulator (with/without draft) + dry-run response, + catalog connections, budget state + contributions, segments + cursor page +``` + +### Endpoint wiring + +| UI | Endpoint | Status | +|---|---|---| +| Every editor page: applied version, draft base, secrets availability, egress list | `GET /admin/config` (ETag) | backend T02 (committed) | +| Preview impact | `POST /admin/config/validate` `{base_version, config}` (200 valid/invalid; `stale_base_version` warning → conflict banner) | backend T02 | +| Save & apply | `PUT /admin/config` + `If-Match` = the draft's base ETag; 200 → reload config, workspace, catalog, status; 412/409 → conflict; 422 → field errors; 428 → reported | backend T02 | +| Version history / rollback | `GET /admin/config/versions?limit=50`; `POST /admin/config/rollback {target_version, expected_active_version}` | backend T02 | +| Conflict "Compare" | `GET /admin/config` (latest) — nothing merged | backend T02 | +| Connections health, registration, allow-listing, secret availability | `GET /admin/catalog` (`connections[]`, model health = governed calls, `local.endpoint_health` = probes of an applied endpoint) | backend T02/T03 | +| Connection Test / Ollama discovery | `POST /admin/providers/probe` | existing | +| Policy simulator | `POST /admin/policies/simulate` (`config` = unsaved draft when chosen; 422 when it does not validate) | backend T03 | +| Simulator applications | `GET /admin/applications` | backend T05 | +| Budget state | `GET /admin/budgets` (404 → pre-v2 counters with an explicit note) | **integration pending (T04, uncommitted)** | +| Budget drill-down | `GET /admin/budgets/{id}/requests` → `{items:[…]}` | **integration pending (T04)** | +| Requests pages | `GET /admin/requests?limit=200&cursor=&segment=` (`segment.id` must echo an archived request, else nothing is shown) | **integration pending (T06)**; current segment works on the committed Host without paging | +| Segment selector / Audit segments | `GET /admin/audit/segments` (404 → "Current segment only") | **integration pending (T06)** | +| Request export | `GET /admin/requests/{id}/export[?segment=]` → raw JSON download | **integration pending (T06)** | +| Archive (Settings → Maintenance) | `POST /admin/reset` (wording from `GET /admin/budgets` presence: ledger ⇒ "budgets NOT reopened") | existing; ledger semantics pending T04 | + +### Decisions + +- **One shared draft.** `ConfigEditor` holds one draft of the whole configuration, owned by one page at a time; a clean + draft is released when its page is left, a dirty one triggers the guard (in-app: `RegisterLocationChangingHandler` → + "Discard unsaved changes?"; reload/close: `NavigationLock ConfirmExternalNavigation`). +- **Save needs a current preview.** "Save & apply" is enabled only when the last `validate` answer was for exactly the + current draft content, valid, and no conflict is open. No optimistic UI: the success line "Applied version vN" appears + only after the 200 carrying `version`, and after config/catalog/workspace/status were reloaded. +- **Never overwrite.** A 412 (or the validator's `stale_base_version` warning) shows "Configuration changed since you + started editing (now vN)" with Reload (discard draft) and Compare (lists server-side vs draft changes). There is no + force-save. +- **Field errors** are matched by the Host's paths (`connections[i]…`, `policies[i].targets[j]`, `budgets[i]…`, + `settings.*`) on member/element boundaries; anything no field claims stays visible in the preview list. +- **Connections**: discovered tags start unselected; local prices default to an explicit, editable `zero-marginal-local` + 0/0; cloud prices are never assumed (unpriced cloud ⇒ blocking problem). Secret references are chosen from the refs the + Host reports (availability only); a known-unavailable ref blocks the form with the server-side fix + (`Secrets__name` env var + restart). Not-on-allow-list probes explain `Providers:ProbeAllowList` / + `Providers:LocalEndpoints` under Technical details. Connection ids are immutable on edit. No delete action (not required; + avoids `unknown_connection` drafts). Cloud default endpoints are not probed (the probe is OpenAI-compatible GET /models). +- **Health**: summary prefers the governed-call fact (newest of success/failure), then the probe; a reachable probe + without a governed success reads "Endpoint reachable … · no governed call observed yet" (never "ready"). +- **Policies**: the effective-route view and summary lines are computed from the configuration with the engine's + structural rules (paused, connection enabled, model permitted, local-only boundary, PII/PHI never cloud) and labelled + as configuration; the simulator (real engine) is the authority for a given request. Cloud models are offered disabled + with "PII/PHI never route to cloud destinations" for sensitive policies. Reorder is ↑/↓ buttons with aria-labels. +- **Legacy cloud**: "Imported legacy rules" + "Move to Hybrid defaults…" builds a draft (Public → first enabled priced + cloud model + local fallback; Internal, PII, PHI → first enabled local model) and previews it; refused (draft untouched) + without a local model. +- **Budgets**: the console never computes spend; all numbers are the ledger's. Zero spend everywhere ⇒ explanatory state + linking to Models & connections (no flat chart). Infrastructure cost is "not configured — none shown". +- **Archive wording** follows the backend contract: with a ledger, archiving the audit segment never reopens budgets; + on a Host without `GET /admin/budgets` the dialog says archive ALSO resets pre-v2 counters. Typed environment name + required. +- **Requests**: `segment=` is sent only when the Host listed segments, and an archived page is shown only if + `segment.id` echoes the request (an older Host would silently answer for the current segment). Bounded to 2 000 loaded + records. Rows of an archived segment open from the loaded page (the by-id lookup searches the current segment only). +- **Console preferences**: theme (existing) and the default response mode (`localStorage covenant.pref.stream-default`, + JS-allow-listed key). Nothing else is persisted. + +### Risks / known gaps + +1. Not compiled. Highest-risk spots: Razor component parameter lambdas (`OnProbed="@(p => …)"`, + `OpenChanged="@(open => { … })"`), deconstruction in `@foreach (var (t, i) in …)`, `@bind` on `int?`/`decimal?` + DTO properties with `@bind:after="Editor.Touch"`, pattern variables in attribute expressions, collection expressions + in conditionals (`cond ? list : []`), `UiJsonContext.Default.ListConfigVersionDto` / `ListAuditSegmentDto`. +2. The round-trip tests reference the backend's uncommitted T04/T06 types (`BudgetStateView`, `BudgetRequestsView`, + `BudgetContributionView`, `SegmentView`, `RequestsPage.NextCursor`, `SegmentInfo.Id/Label`, + `AuditJsonContext.Default.ListSegmentView`). If the backend renames them, fix the test, not the UI shape. +3. Diagnostics shows "Not reported by this Host" for `Config:Path` and the ignored legacy keys (no status field exists; + the Host logs them at startup). +4. The effective-route view does not know runtime availability or the hard-budget pricing rule beyond "unpriced"; + the impact preview and the simulator (both Host-computed) are authoritative. +5. Rollback's resulting version is predicted as active+1 "or the next free number"; the actual number is shown from the + Host's answer. + +### Verifier steps (not executed) + +``` +dotnet build Covenant.sln -c Release --disable-build-servers +dotnet test tests/Covenant.Tests -c Release --disable-build-servers --filter "FullyQualifiedName~MoneyTests|FullyQualifiedName~ConfigDraftTests|FullyQualifiedName~EditOutcomeTests|FullyQualifiedName~ImpactTextTests|FullyQualifiedName~PolicyRoutesTests|FullyQualifiedName~SegmentScopeTests|FullyQualifiedName~BudgetTextTests|FullyQualifiedName~ConnectionFormTests|FullyQualifiedName~ConnectionHealthTests|FullyQualifiedName~RequestFilterApplicationTests|FullyQualifiedName~ContractRoundTripTests|FullyQualifiedName~CostTextTests|FullyQualifiedName~ConnectionLogicTests" +dotnet test tests/Covenant.Tests -c Release --disable-build-servers # full suite +``` + +Browser (isolated port, `Config:Seed=demo-hybrid` on a fresh `Audit:Path`; both themes; 1280×720 and 1920×1080, then +~900 px): + +**H — policy editing** +- [ ] Policies → Edit → on the Public policy press "Pause route" on the primary; summary line becomes + `Public → · no fallback`; Preview impact shows Public before → after; Save & apply → "Applied version vN+1". +- [ ] Playground preset A → served by the fallback; Requests drawer shows the attempts and config vN+1. +- [ ] Pause the remaining route (or "Pause policy") → preview shows Public newly refused → save → preset A refused + at policy. Resume → save → new version vN+3; preset A served again. +- [ ] Simulator: same prompt against "Unsaved draft" vs "Applied vN" differ while a pause is unsaved; label "Dry run — + no provider called, nothing recorded"; Requests shows no new record afterwards. +- [ ] A PII/PHI policy never offers cloud models (disabled option with the reason); ↑/↓ reorder works by keyboard. + +**J — config recovery / conflicts** +- [ ] Open Budgets → Edit in tab A and tab B; save a cap in B; save in A → banner "Configuration changed since you + started editing (now vN)"; A's draft kept; Compare lists both sides; Reload discards A's draft. Nothing overwritten. +- [ ] Settings → Edit → prompt preview 900 → Preview shows the `settings.prompt_preview_chars` error inline; Save stays + disabled; `curl /admin/config` still reports the old version. +- [ ] Version history → Roll back to an older version → confirmation names target and new version → success line shows + the new version number; history lists it as a rollback of the target. +- [ ] Edit something, click another nav item → "Discard unsaved changes?"; Keep editing stays; Discard navigates. Reload + the tab with a dirty draft → browser leave-page prompt. +- [ ] Restart the Host → pages show the same "Applied version"; Budgets spend unchanged. + +**K — evidence** +- [ ] Audit & evidence: session runs show Pending → "Audit integrity verified (record present, chain consistent)" (or + Unavailable + Retry); integrity card separate from answers; recent decisions list who / rule+version / + selected→attempted→served / cost and why; chain/anchors/segments only under the disclosure. +- [ ] Settings → Maintenance → archive (type the environment name) → dialog said budgets are NOT reopened → Budgets spend + unchanged afterwards; Requests segment selector lists the archived segment; selecting it shows "Archived segment … + read-only" and its records; "Load older" pages until "All records of this segment are loaded". +- [ ] Request drawer → Export evidence (JSON) downloads `covenant-request-.json` with `content_included:false` and no + `PromptPreview`. +- [ ] Legacy (pre-v2) audit lines still verify and render "Not recorded" fields. + +**L — browser usability** +- [ ] Models & connections → Add Ollama → endpoint → Test (allowed/unreachable/not-allowed messages as specified) → + tags unselected → select one → price shows zero-marginal-local 0/0 → Preview impact on routes → Save & apply → + card shows the new connection, "Applied version" bumped. Edit prefills actual values; Disable… → preview → save. +- [ ] Add cloud provider with an unavailable secret ref → red "Secret not set on the server — saving is blocked". +- [ ] Budgets: tiny charges render like `$0.000184`; local-only demo shows the explanatory no-spend state; Requests + drill-down links open the request drawer. +- [ ] Every page: loading skeleton, error banner with Retry (stop the Host), empty states, disabled controls with reasons; + keyboard-only: Tab through editor bar, drawers trap focus, Esc closes, focus returns to the opener. +- [ ] No horizontal page scroll at 1280×720 / ~900 px; long model ids and errors wrap. diff --git a/src/Covenant.Ui/Components/ConnectionEditor.razor b/src/Covenant.Ui/Components/ConnectionEditor.razor new file mode 100644 index 0000000..1e144ad --- /dev/null +++ b/src/Covenant.Ui/Components/ConnectionEditor.razor @@ -0,0 +1,497 @@ +@inject AdminApi Api +@inject CatalogState Catalog + +@* Add / edit one connection in a single form (spec §5 Models & connections). Ollama: endpoint → Test & discover + (bounded host-side probe) → choose exact tags (nothing selected by default) → price (explicit zero-marginal-local + basis, editable) → Preview impact (affected routes) → Save & apply. Cloud: provider kind, endpoint where supported, + a server-side secret REFERENCE (availability only, never a value), model ids and prices. The form changes only the + configuration draft; only the Host's 200 makes it a new active version. *@ + +
    +
    + 1 · Connection +
    + @if (Form.IsNew && !Form.IsOllama) + { +
    + + +
    + } + else + { +
    + Provider + @ConnectionRules.KindLabel(Form.Kind) +
    + } +
    + + +
    +
    + + @if (Form.IsNew) + { + + Stable id used by policies and evidence (letters, digits, . _ -). Cannot be changed later. + } + else + { + @Form.Id + Policies and evidence reference this id, so it cannot be renamed. + } +
    +
    + Boundary + @if (Form.Kind == "OpenAiCompatible") + { +
    + + +
    + Local requires the endpoint's host:port in the startup list Providers:LocalEndpoints; a cloud host cannot be relabelled Local. + } + else + { + @(Form.IsOllama ? "Ollama runs inside the perimeter." : "OpenAI and Anthropic are always Cloud.") + } + +
    +
    +
    + + + + @(EndpointProblem ?? (Form.IsOllama ? "“localhost” means the machine running Covenant, not this browser. Point at Ollama itself, not at Open WebUI." : EgressNote)) + + @if (EndpointProblem is null && EgressWarning is { } ew) + { + @ew + } + +
    +
    + +
    + + +
    +
    +
    + + @if (Form.Endpoint.Trim().Length > 0 || Form.IsOllama) + { +
    + 2 · Test @(Form.IsOllama ? "& discover models" : "the endpoint") + Covenant probes from its own host: GET …/models, 5 s timeout, 64 KiB cap, no redirects, allow-listed destinations only. No Covenant credential is sent. Discovery never approves a model. +
    + + @if (_probe is { } done) + { + + + @ProbeHeadline(done) + + } +
    + + @if (_probe is { Allowed: false }) + { + +
    + Technical details + + Add @(ConnectionLogic.Authority(Form.Endpoint) ?? "host:port") to Providers:ProbeAllowList + (environment: Providers__ProbeAllowList=@(ConnectionLogic.Authority(Form.Endpoint) ?? "host:port"), comma-separated) and, for a Local + connection, to Providers:LocalEndpoints (Providers__LocalEndpoints). Restart Covenant, then test again. + +
    + } + else if (_probe is { Reachable: false } unreachable) + { + + } +
    + } + +
    + @(Form.Endpoint.Trim().Length > 0 || Form.IsOllama ? "3" : "2") · Permitted models and prices + @if (Form.IsOllama) + { + Select the exact tags Covenant may route to. Discovered tags start unselected; nothing is approved automatically. + } + else + { + Enter exact provider model ids. A paid cloud model needs input and output prices — an unknown price is never treated as $0. +
    +
    + + +
    + +
    + } + @if (Form.Models.Count == 0) + { + + } + else + { +
      + @foreach (var m in Form.Models) + { + var row = m; + var idx = Form.Models.IndexOf(row); + var sent = Form.SentIndex(row); + var mp = sent is { } si ? Prefix + ".models[" + si.ToString(System.Globalization.CultureInfo.InvariantCulture) + "]" : null; +
    • + + @ModelNote(row) + @if (row.Selected) + { +
      + + @if (row.Priced) + { +
      + + +
      +
      + + +
      +
      + + +
      +
      + + +
      + } + else + { + Unpriced: cost is unknown (never $0). Not eligible as a paid target under a hard budget. + } +
      + @if (mp is not null) + { + + } + } + @if (!row.Configured && !row.Selected && !Form.IsOllama) + { + + } +
    • + } +
    + } + @if (RemovedStillRouted.Count > 0) + { + Still named by enabled policies: @string.Join(", ", RemovedStillRouted). Preview shows which requests would be refused. + } +
    + + @if (!Form.IsOllama || !string.IsNullOrWhiteSpace(Form.SecretRef)) + { +
    + Credential (server-side secret reference) + Choose the configuration key that holds this provider's credential on the server. The console sees only whether it is set — never its value. +
    + + +
    + @if (_otherSecret) + { +
    + + + Secrets:<name> (or a legacy key: OpenAI:ApiKey, Anthropic:ApiKey, Local:ApiKey). Availability is checked by the Host when you preview. +
    + } + @if (SecretAvailability is false && Form.SecretRef is { } sr) + { + + } + +
    + } + +
    + Review & apply + @{ var problems = Form.Problems(OtherIds, Envelope?.Secrets); } + @if (problems.Count > 0) + { +
      + @foreach (var pr in problems) + { +
    • @pr
    • + } +
    + } + @if (Issues.ErrorsAt(Prefix).Count > 0 && DraftIndex is not null) + { + The Host reported problems with this connection — see the messages above and the preview below. + } +
    + + +
    + @if (Validation is { } v) + { + + } + Preview puts this connection into the configuration draft. Closing this panel keeps the draft; “Cancel” in the page bar discards it. +
    +
    + +@code { + [Parameter, EditorRequired] public ConnectionForm Form { get; set; } = default!; + [Parameter] public ConfigEnvelopeDto? Envelope { get; set; } + [Parameter] public IReadOnlyList OtherIds { get; set; } = []; + /// Index of this connection in the draft once previewed (issue paths), else null. + [Parameter] public int? DraftIndex { get; set; } + [Parameter] public IssueIndex Issues { get; set; } = IssueIndex.Empty; + [Parameter] public ConfigValidationResultDto? Validation { get; set; } + [Parameter] public bool ValidationCurrent { get; set; } + [Parameter] public bool Validating { get; set; } + [Parameter] public bool Saving { get; set; } + [Parameter] public bool CanSave { get; set; } + [Parameter] public IReadOnlyList RemovedStillRouted { get; set; } = []; + [Parameter] public EventCallback OnPreview { get; set; } + [Parameter] public EventCallback OnSave { get; set; } + /// Raised after every form edit (the page recomputes derived facts). + [Parameter] public EventCallback OnChanged { get; set; } + /// Raised with the probe result so the page can show it on the connection card. + [Parameter] public EventCallback OnProbed { get; set; } + + private const string OtherValue = "__other__"; + private readonly string P = "cf-" + Guid.NewGuid().ToString("n")[..6]; + private ProbeResponse? _probe; + private bool _probing; + private string? _probeError; + private string? _newModel; + private bool _otherSecret; + + private string Prefix => DraftIndex is { } i ? IssueIndex.Connection(i) : "connections[?]"; + private string? EndpointProblem => Form.Endpoint.Trim().Length == 0 ? null : ConnectionLogic.EndpointProblem(Form.Endpoint); + + private string EgressNote => Form.Kind == "OpenAiCompatible" + ? "The host:port must be on the startup egress allow-list." + : "Empty uses the provider's default API endpoint."; + + private string? EgressWarning + { + get + { + var authority = ConnectionRules.AuthorityOf(Form.Kind, Form.Endpoint); + if (authority is null || Envelope?.AllowList is not { } list) return null; + return list.Contains(authority, StringComparer.OrdinalIgnoreCase) + ? null + : authority + " is not on the startup egress allow-list (Providers:ProbeAllowList); the Host will refuse this connection until it is added and Covenant restarts."; + } + } + + private bool? SecretAvailability + => Form.SecretRef is { Length: > 0 } r && Envelope?.Secrets is { } map && map.TryGetValue(r.Trim(), out var s) ? s.Available : null; + + private string SecretSelectValue + { + get + { + if (_otherSecret) return OtherValue; + if (string.IsNullOrWhiteSpace(Form.SecretRef)) return ""; + return Envelope?.Secrets?.ContainsKey(Form.SecretRef.Trim()) == true ? Form.SecretRef.Trim() : OtherValue; + } + } + + protected override void OnParametersSet() + { + if (!string.IsNullOrWhiteSpace(Form.SecretRef) && Envelope?.Secrets?.ContainsKey(Form.SecretRef.Trim()) != true) _otherSecret = true; + } + + private Task Changed() => OnChanged.InvokeAsync(); + + private Task OnKind(ChangeEventArgs e) + { + Form.SetKind(e.Value?.ToString() ?? "OpenAi"); + return Changed(); + } + + private Task SetBoundary(string b) + { + Form.Boundary = b; + return Changed(); + } + + private Task OnEndpointInput(ChangeEventArgs e) + { + var next = e.Value?.ToString() ?? ""; + if (string.Equals(next, Form.Endpoint, StringComparison.Ordinal)) return Task.CompletedTask; + Form.Endpoint = next; + _probe = null; // a probe of another address proves nothing about this one + _probeError = null; + foreach (var m in Form.Models) m.ReportedByEndpoint = null; + return Changed(); + } + + private async Task ProbeAsync() + { + if (_probing || EndpointProblem is not null) return; + var endpoint = Form.Endpoint.Trim(); + _probing = true; + _probeError = null; + _probe = null; + try + { + var result = await Api.ProbeAsync(endpoint); + if (!string.Equals(Form.Endpoint.Trim(), endpoint, StringComparison.Ordinal)) return; // edited meanwhile + _probe = result; + if (result.Allowed && result.Reachable && Form.IsOllama) Form.ApplyDiscovery(result.Models); + await OnProbed.InvokeAsync(result); + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // ConsoleSession disconnects. + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.NotFound) + { + _probeError = "The probe endpoint is not available on this Host."; + } + catch (Exception ex) + { + _probeError = ex.Message; + } + finally + { + _probing = false; + } + await Catalog.RefreshAsync(); // a probe of an APPLIED endpoint updates its observed health on the server + await Changed(); + } + + private static string ProbeHeadline(ProbeResponse p) + { + if (!p.Allowed) return "Not allowed — destination not on the startup allow-list"; + if (!p.Reachable) return "Unreachable" + (p.HttpStatus is { } s ? " (HTTP " + s.ToString(System.Globalization.CultureInfo.InvariantCulture) + ")" : ""); + var n = p.Models.Count.ToString(System.Globalization.CultureInfo.InvariantCulture); + var ms = p.DurationMs is { } d ? " in " + Fmt.Ms(d) : ""; + return "Reachable" + ms + " · " + n + (p.Models.Count == 1 ? " model reported" : " models reported"); + } + + private string ModelNote(ModelForm m) + { + var parts = new List(); + parts.Add(m.Configured ? "configured" : m.ReportedByEndpoint == true ? "discovered" : "added here"); + if (m.ReportedByEndpoint == false) parts.Add("not reported by the endpoint now"); + if (!m.Selected) parts.Add("not permitted"); + return string.Join(" · ", parts); + } + + private Task SetSelected(ModelForm row, ChangeEventArgs e) + { + row.Selected = e.Value is bool b && b; + return Changed(); + } + + private Task SetPriced(ModelForm row, ChangeEventArgs e) + { + row.Priced = e.Value is bool b && b; + if (row.Priced && row.Basis.Length == 0) row.Basis = Form.Boundary == "Local" ? ConnectionForm.BasisLocal : ConnectionForm.BasisList; + if (row.Priced && Form.Boundary == "Local" && row.InputPer1M is null && row.OutputPer1M is null) + { + row.InputPer1M = 0m; + row.OutputPer1M = 0m; + } + return Changed(); + } + + private Task SetBasis(ModelForm row, ChangeEventArgs e) + { + row.Basis = e.Value?.ToString() ?? ""; + return Changed(); + } + + private Task AddModel() + { + if (string.IsNullOrWhiteSpace(_newModel)) return Task.CompletedTask; + var id = _newModel.Trim(); + if (!Form.Models.Any(m => string.Equals(m.ModelId, id, StringComparison.Ordinal))) Form.AddModel(id); + _newModel = null; + return Changed(); + } + + private Task RemoveRow(ModelForm row) + { + Form.Models.Remove(row); + return Changed(); + } + + private Task OnSecretChoice(ChangeEventArgs e) + { + var v = e.Value?.ToString() ?? ""; + if (v == OtherValue) + { + _otherSecret = true; + if (Envelope?.Secrets?.ContainsKey(Form.SecretRef ?? "") == true) Form.SecretRef = ""; + } + else + { + _otherSecret = false; + Form.SecretRef = v.Length == 0 ? null : v; + } + return Changed(); + } +} diff --git a/src/Covenant.Ui/Components/EditorBar.razor b/src/Covenant.Ui/Components/EditorBar.razor new file mode 100644 index 0000000..41a97ed --- /dev/null +++ b/src/Covenant.Ui/Components/EditorBar.razor @@ -0,0 +1,304 @@ +@inject ConfigEditor Editor +@inject NavigationManager Nav +@implements IDisposable + +@* The shared View/Edit bar of every configuration editor page (ADR-0011): applied version + history/rollback, + Edit → Preview impact → Save & apply / Cancel, the stale-edit conflict, 422 errors, and the unsaved-change guard + (in-app navigation via RegisterLocationChangingHandler; reload/close via NavigationLock). "Applied version vN" is + only ever shown from the Host's answers; nothing here reports success before the 200 with the new version. *@ + + + +
    +
    +
    + @if (Editor.Applied is { } env) + { + @("Applied version " + V(env.Version)) + } + else if (Editor.Loading) + { + Loading configuration… + } + @if (Editor.Editing && Editor.Owner == Owner) + { + + @(Editor.IsDirty ? "Unsaved draft" : "Editing — no changes yet") + + @if (Editor.IsDirty && !Editor.ValidationCurrent && !Editor.Validating) + { + Preview the impact before saving. + } + } + else if (Editor.Editing && Editor.Owner != Owner) + { + Another page holds a draft. + } + else + { + @ViewHint + } +
    +
    + + @if (!(Editor.Editing && Editor.Owner == Owner) && ShowEditButton) + { + + } + else if (Editor.Editing && Editor.Owner == Owner) + { + + + + } +
    +
    + + @if (Editor.AppliedNotice is { } notice && !(Editor.Editing && Editor.IsDirty)) + { +
    @noticeConfirmed by the Host; the console reloaded configuration, catalog and status.
    + } + @if (Editor.LoadError is { } le) + { + + } + + @if (Editor.Conflict is { } conflict && Editor.Owner == Owner) + { + + } + + @if (Editor.LastOutcome is { Succeeded: false } lo && lo.Kind is not EditOutcomeKind.Stale && Editor.Owner == Owner) + { + + } + @if (Editor.ValidationError is { } ve && Editor.Owner == Owner) + { + + } + @if (Editor.Validation is { } v && Editor.Editing && Editor.Owner == Owner) + { + + } + @ChildContent +
    + + +

    Each apply and each rollback is a new immutable version; history is never rewritten. Spend and audit history are not reset by either.

    + @if (Editor.VersionsLoading && Editor.Versions is null) + { + + } + + @if (Editor.Versions is { Count: 0 }) + { + + } + else if (Editor.Versions is { } versions) + { +
      + @foreach (var ver in versions) + { + var row = ver; +
    1. +
      + @V(row.Version) + @if (row.Active) { Active } + @Fmt.Utc(row.CreatedUtc) · @Fmt.OrNotRecorded(row.Origin) +
      + @(row.ChangeSummary ?? "No change summary recorded") + @if (row.RolledBackFrom is { } rb) + { + @("Rollback of " + V(rb)) + } + @if (!row.Active && _confirmTarget == row.Version) + { +
      + @RollbackSentence(row.Version) +
      + + +
      +
      + } + else if (!row.Active) + { + + } +
    2. + } +
    + } + @if (_rollbackOutcome is { } ro) + { + if (ro.Succeeded) + { +
    @ro.MessageConfirmed by the Host.
    + } + else + { + + } + } +
    + + +

    Your draft of the @Subject.ToLowerInvariant() configuration has not been applied. Discarding it changes nothing on the server; the active version stays @(Editor.AppliedVersion is { } av ? V(av) : "unchanged").

    +
    + + +
    +
    + +@code { + /// Owner key of this page's draft ("connections", "policies", "budgets", "settings"). + [Parameter, EditorRequired] public string Owner { get; set; } = ""; + /// "Connections", "Policies", … (dialog wording). + [Parameter] public string Subject { get; set; } = "Configuration"; + [Parameter] public bool ShowEditButton { get; set; } = true; + [Parameter] public string ViewHint { get; set; } = "Viewing the applied configuration."; + /// Path prefixes that the page shows inline next to fields (others are listed in the preview). + [Parameter] public IReadOnlyList ClaimedPaths { get; set; } = []; + [Parameter] public EventCallback OnSaved { get; set; } + [Parameter] public RenderFragment? ChildContent { get; set; } + + private readonly string _id = "ed-" + Guid.NewGuid().ToString("n")[..8]; + private IDisposable? _guard; + private bool _historyOpen; + private bool _discardOpen; + private string? _pendingTarget; + private int? _confirmTarget; + private EditOutcome? _rollbackOutcome; + + private bool OwnsDirtyDraft => Editor.Owner == Owner && Editor.IsDirty; + + private string SaveBlockedReason + { + get + { + if (!Editor.IsDirty) return "No changes to save"; + if (Editor.Conflict is not null) return "The active version changed — reload first"; + if (!Editor.ValidationCurrent) return "Preview the impact of the current draft first"; + if (Editor.Validation is { Valid: false }) return "Fix the validation errors first"; + return "Not available"; + } + } + + protected override async Task OnInitializedAsync() + { + Editor.Changed += OnChanged; + _guard = Nav.RegisterLocationChangingHandler(OnLocationChanging); + await Editor.EnsureLoadedAsync(); + } + + private ValueTask OnLocationChanging(LocationChangingContext context) + { + if (OwnsDirtyDraft) + { + context.PreventNavigation(); + _pendingTarget = context.TargetLocation; + _discardOpen = true; + _ = InvokeAsync(StateHasChanged); + } + return ValueTask.CompletedTask; + } + + private void BeginEdit() => Editor.BeginEdit(Owner); + + private async Task PreviewAsync() => await Editor.ValidateAsync(); + + private async Task SaveAsync() + { + var outcome = await Editor.SaveAsync(); + if (outcome.Succeeded) await OnSaved.InvokeAsync(); + } + + private void RequestCancel() + { + if (!Editor.IsDirty) + { + Editor.Discard(); + return; + } + _pendingTarget = null; + _discardOpen = true; + } + + private void KeepEditing() + { + _pendingTarget = null; + _discardOpen = false; + } + + private void ConfirmDiscard() + { + var target = _pendingTarget; + _pendingTarget = null; + _discardOpen = false; + Editor.Discard(); + if (target is not null) Nav.NavigateTo(target); + } + + private async Task OpenHistory() + { + _historyOpen = true; + _confirmTarget = null; + _rollbackOutcome = null; + await Editor.LoadVersionsAsync(); + } + + private string RollbackSentence(int target) + { + var active = Editor.AppliedVersion ?? 0; + var next = (active + 1).ToString(System.Globalization.CultureInfo.InvariantCulture); + var t = target.ToString(System.Globalization.CultureInfo.InvariantCulture); + return "Covenant validates v" + t + "'s content against today's startup environment and activates it as a NEW version (v" + next + + ", or the next free number if an interrupted apply used it). v" + t + " and the current v" + + active.ToString(System.Globalization.CultureInfo.InvariantCulture) + " stay in history unchanged. Spend and audit history are not reset."; + } + + private async Task RollbackAsync(int target) + { + _rollbackOutcome = await Editor.RollbackAsync(target); + _confirmTarget = null; + if (_rollbackOutcome.Succeeded) await OnSaved.InvokeAsync(); + } + + private static string V(int version) => "v" + version.ToString(System.Globalization.CultureInfo.InvariantCulture); + + private void OnChanged() => _ = InvokeAsync(StateHasChanged); + + public void Dispose() + { + Editor.Changed -= OnChanged; + _guard?.Dispose(); + Editor.Release(Owner); + } +} diff --git a/src/Covenant.Ui/Components/FieldIssues.razor b/src/Covenant.Ui/Components/FieldIssues.razor new file mode 100644 index 0000000..ebbfa42 --- /dev/null +++ b/src/Covenant.Ui/Components/FieldIssues.razor @@ -0,0 +1,22 @@ +@* Inline validation messages for one field path (and anything below it), from the last preview or the last 422. + Give the input aria-describedby="@Id" and aria-invalid when Has(...) is true. *@ +@{ var errors = Issues.ErrorsAt(Path); var warnings = Issues.WarningsAt(Path); } +@if (errors.Count > 0 || warnings.Count > 0) +{ + + @foreach (var e in errors) + { + @(e.Message + (IssueHelp.For(e.Code) is { } h ? " — " + h : "")) + } + @foreach (var w in warnings) + { + @w.Message + } + +} + +@code { + [Parameter, EditorRequired] public IssueIndex Issues { get; set; } = IssueIndex.Empty; + [Parameter, EditorRequired] public string Path { get; set; } = ""; + [Parameter] public string? Id { get; set; } +} diff --git a/src/Covenant.Ui/Components/ImpactPreview.razor b/src/Covenant.Ui/Components/ImpactPreview.razor new file mode 100644 index 0000000..032bfc2 --- /dev/null +++ b/src/Covenant.Ui/Components/ImpactPreview.razor @@ -0,0 +1,103 @@ +@* The Host's validation + impact analysis of the current draft (POST /admin/config/validate): errors (with field + path and, where the fix is outside the console, what to change), warnings, then the impact — classifications + before → after, newly refused, pricing gaps, unavailable destinations, applications affected. The console words + the Host's result; it never computes an impact itself. *@ + +
    +
    + @(Result.Valid ? "Preview: valid" : "Preview: not valid — cannot be saved") + @(Current ? "Computed by the Host for the current draft" : "Out of date — the draft changed after this preview; preview again before saving") +
    + + @if (Result.Errors.Count > 0) + { + + } + @if (Result.Warnings.Count > 0) + { +
    + @Count(Result.Warnings.Count, "warning", "warnings") +
      + @foreach (var w in Result.Warnings) + { +
    • @(w.Path ?? "—") @w.Message
    • + } +
    +
    + } + + @if (Result.Impact is { } impact) + { +
    + Impact: @ImpactText.Headline(impact) + @{ var routes = ImpactText.ChangedRoutes(impact); } + @if (routes.Count > 0) + { +
    + + + + @foreach (var r in routes) + { + + + + + + } + +
    Classification / profileBeforeAfter
    @r.Scope@r.Before@r.After
    +
    + } + @if (impact.NewlyRefused.Count > 0) + { +
    Would now be refused @string.Join(" · ", impact.NewlyRefused)
    + } + @if (impact.UnavailableDestinations.Count > 0) + { +
    Unavailable destinations @string.Join(" · ", impact.UnavailableDestinations)
    + } + @if (impact.PricingGaps.Count > 0) + { +
    Pricing gaps (cost unknown, not zero) @string.Join(" · ", impact.PricingGaps)
    + } + @if (impact.ApplicationsAffected.Count > 0) + { +
    Applications affected @string.Join(" · ", impact.ApplicationsAffected)
    + } + Applying never resets spend or audit history. Requests already running finish on the version they started with. +
    + } + else if (Result.Errors.Count > 0) + { + No impact preview: the Host does not analyse a candidate with structural errors. + } +
    + +@code { + [Parameter, EditorRequired] public ConfigValidationResultDto Result { get; set; } = default!; + /// False when the draft changed after this preview. + [Parameter] public bool Current { get; set; } + [Parameter] public IReadOnlyList ClaimedPaths { get; set; } = []; + + private static string Count(int n, string one, string many) + => n.ToString(System.Globalization.CultureInfo.InvariantCulture) + " " + (n == 1 ? one : many); +} diff --git a/src/Covenant.Ui/Components/PolicySimulator.razor b/src/Covenant.Ui/Components/PolicySimulator.razor new file mode 100644 index 0000000..1f5eaf8 --- /dev/null +++ b/src/Covenant.Ui/Components/PolicySimulator.razor @@ -0,0 +1,171 @@ +@inject AdminApi Api + +@* Policy simulator (POST /admin/policies/simulate): the REAL classifier and policy engine on the Host, as a dry run — + no provider is called, no audit record, spend or reservation is written. Optionally against the unsaved draft + (the Host validates it and never applies it). Always labelled "Dry run". *@ + +
    +
    +

    Policy simulator

    + Dry run — no provider called, nothing recorded +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + Simulate against +
    + + +
    +
    +
    +
    + + + The detector may escalate the profile's trusted baseline; it can never lower it. Nothing is sent to a model. +
    +
    + +
    + + @if (_result is { } r) + { +
    +
    + @(r.Decision == "route" ? "Would route" : "Would be refused") + @("Dry run · " + (r.ConfigVersion is { } cv ? "config v" + cv.ToString(System.Globalization.CultureInfo.InvariantCulture) : "config version not reported") + (_ranOnDraft ? " (unsaved draft)" : "")) +
    +
    +
    Trusted baseline
    @PolicyText.ClassificationLabel(r.Baseline) @(r.Profile is { Length: > 0 } pr ? "· profile " + pr : "")
    +
    Final classification
    @PolicyText.ClassificationLabel(r.Classification) @(r.DetectedSignal is { Length: > 0 } sig ? "· detector: " + sig : "· detector matched nothing (no escalation)")
    +
    Policy
    @(r.PolicyId ?? "No policy matched")
    +
    Primary
    @(r.Primary ?? "None")
    +
    Fallbacks
    @(r.Fallbacks.Count == 0 ? "None" : string.Join(" → ", r.Fallbacks))
    +
    Reason
    @Fmt.OrNotRecorded(r.Reason)
    + @if (r.Explanation is { Length: > 0 } ex) + { +
    Explanation
    @ex
    + } +
    + @if (r.Eligible.Count > 0) + { +
      + @foreach (var t in r.Eligible) + { +
    1. + @(t.Target ?? "target not reported") + + @(t.ExcludedReason is null ? "eligible" : "excluded: " + t.ExcludedReason) +
    2. + } +
    + } +
    + } +
    + +@code { + [Parameter] public IReadOnlyList? Applications { get; set; } + [Parameter] public IReadOnlyList? Profiles { get; set; } + /// The unsaved draft, or null when there is none. + [Parameter] public CovenantConfigDto? Draft { get; set; } + [Parameter] public int? AppliedVersion { get; set; } + + private readonly string P = "sim-" + Guid.NewGuid().ToString("n")[..6]; + private string? _app; + private string? _profile; + private string? _model; + private string _prompt = "Extract the ticket priority from: \"Printer on floor 3 is out of toner. Priority: low.\" Reply as JSON {\"priority\": …}."; + private bool _useDraft; + private bool _running; + private bool _ranOnDraft; + private string? _error; + private SimulateResponseDto? _result; + + private ApplicationSummaryDto? SelectedApp => Applications?.FirstOrDefault(a => a.Id == _app); + private string AppliedLabel => AppliedVersion is { } v ? "Applied v" + v.ToString(System.Globalization.CultureInfo.InvariantCulture) : "Applied version"; + + protected override void OnParametersSet() + { + if (Draft is null) _useDraft = false; + if (_app is null && Applications is { Count: > 0 } apps) _app = (apps.FirstOrDefault(a => a.Enabled) ?? apps[0]).Id; + } + + private void OnApp(ChangeEventArgs e) + { + _app = string.IsNullOrWhiteSpace(e.Value?.ToString()) ? null : e.Value!.ToString(); + _profile = null; + _result = null; + } + + private void OnProfile(ChangeEventArgs e) => _profile = string.IsNullOrWhiteSpace(e.Value?.ToString()) ? null : e.Value!.ToString(); + + private async Task RunAsync() + { + if (_app is null || _running) return; + _running = true; + _error = null; + _result = null; + bool onDraft = _useDraft && Draft is not null; + try + { + _result = await Api.SimulateAsync(new SimulateRequestDto + { + ApplicationId = _app, + ProfileId = _profile, + Prompt = _prompt, + Model = string.IsNullOrWhiteSpace(_model) ? null : _model.Trim(), + Config = onDraft ? ConfigCopy.Deep(Draft!) : null, + }); + _ranOnDraft = onDraft; + if (_result is { DryRun: false }) + { + _error = "The Host did not confirm a dry run — the result is not shown."; + _result = null; + } + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.NotFound) + { + _error = "The simulator is not available on this Host (POST /admin/policies/simulate missing)."; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.UnprocessableEntity) + { + _error = "The unsaved draft does not validate, so it cannot be simulated. Preview its impact to see the errors."; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // ConsoleSession disconnects. + } + catch (Exception ex) + { + _error = ex.Message; + } + finally + { + _running = false; + } + } +} diff --git a/src/Covenant.Ui/Layout/MainLayout.razor b/src/Covenant.Ui/Layout/MainLayout.razor index 467ec94..5d73616 100644 --- a/src/Covenant.Ui/Layout/MainLayout.razor +++ b/src/Covenant.Ui/Layout/MainLayout.razor @@ -1,5 +1,7 @@ @inherits LayoutComponentBase @inject AppState State +@inject PlaygroundState Pg +@inject Interop Interop @implements IDisposable
    @@ -23,6 +25,17 @@ @code { protected override void OnInitialized() => State.Changed += OnChanged; + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender) return; + // Browser-local console preference (Settings → Console preferences); absent = streaming. + try + { + if (await Interop.PrefGetAsync("stream-default") is "false") Pg.SetStreamingDefault(false); + } + catch (JSException) { /* storage unavailable: keep the default */ } + } private void OnChanged() => _ = InvokeAsync(StateHasChanged); public void Dispose() => State.Changed -= OnChanged; } diff --git a/src/Covenant.Ui/Logic/BudgetView.cs b/src/Covenant.Ui/Logic/BudgetView.cs new file mode 100644 index 0000000..9f39ca6 --- /dev/null +++ b/src/Covenant.Ui/Logic/BudgetView.cs @@ -0,0 +1,150 @@ +using System.Globalization; +using System.Text.Json; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// Budget wording (ADR-0014): period identity, warning state, enforcement — all from the server's +/// numbers; the console never computes spend. +public static class BudgetText +{ + public static string Period(string? period, string? periodId) + { + var p = (period ?? "").Trim().ToLowerInvariant() switch + { + "daily" => "Daily (UTC)", + "monthly" => "Monthly (UTC)", + "none" => "No period (cumulative)", + "" => "Period not reported", + _ => period!.Trim(), + }; + return string.IsNullOrWhiteSpace(periodId) ? p : p + " · " + periodId; + } + + public static string Scope(string? scope) + { + var s = (scope ?? "").Trim(); + if (s.Length == 0) return "Scope not reported"; + if (string.Equals(s, "global", StringComparison.OrdinalIgnoreCase)) return "Global"; + if (s.StartsWith("team:", StringComparison.OrdinalIgnoreCase)) return "Team " + s[5..]; + if (s.StartsWith("application:", StringComparison.OrdinalIgnoreCase)) return "Application " + s[12..]; + return s; + } + + /// (label, tone) for the server's warning state: none | warn | critical | exceeded. + public static (string Label, string Tone) Warning(string? warning) => (warning ?? "").Trim().ToLowerInvariant() switch + { + "none" => ("Within budget", "ok"), + "warn" => ("Warning threshold reached", "warn"), + "critical" => ("Critical threshold reached", "warn"), + "exceeded" => ("Cap reached — new paid work blocked", "bad"), + "" => ("Warning state not reported", "hollow"), + _ => (warning!.Trim(), "hollow"), + }; + + public static string Enforcement(string? enforcement) => (enforcement ?? "").Trim().ToLowerInvariant() switch + { + "hard" => "Hard — refuses paid work that would exceed the cap (estimated bound)", + "warn-only" or "warnonly" => "Warn only — never blocks", + "" => "Enforcement not reported", + _ => enforcement!.Trim(), + }; + + public static string Thresholds(IReadOnlyList? warnAt) + => warnAt is null || warnAt.Count == 0 + ? "No warning thresholds" + : string.Join(", ", warnAt.Select(w => (w * 100m).ToString("0.#", CultureInfo.InvariantCulture) + "%")); + + /// Remaining as text; "Exceeded by $x" when negative (spend is never truncated to the cap). + public static string Remaining(decimal remaining) => remaining >= 0 ? Money.Usd(remaining) : "Exceeded by " + Money.Usd(-remaining); + + /// 0–100 for the meter; spend + reserved over cap. A zero cap with any use is full. + public static int MeterPercent(decimal spent, decimal reserved, decimal cap) + { + if (cap <= 0) return spent + reserved > 0 ? 100 : 0; + return (int)Math.Clamp((spent + reserved) / cap * 100m, 0m, 100m); + } + + /// True when the server reports no spend and nothing reserved anywhere — the "local-only, nothing to + /// chart" state that gets an explanation instead of a flat chart. + public static bool NoSpendAnywhere(IReadOnlyList? budgets) + => budgets is not null && budgets.All(b => b.SpentUsd == 0m && b.ReservedUsd == 0m); + + /// Parses "80, 95" (percent) into fractions [0.80, 0.95]; null when malformed or out of (0, 100]. + public static List? ParseThresholds(string? text) + { + if (string.IsNullOrWhiteSpace(text)) return []; + var result = new List(); + foreach (var part in text.Split(new[] { ',', ' ', ';' }, StringSplitOptions.RemoveEmptyEntries)) + { + var p = part.Trim().TrimEnd('%'); + if (!decimal.TryParse(p, NumberStyles.Number, CultureInfo.InvariantCulture, out var pct) || pct <= 0 || pct > 100) return null; + result.Add(Math.Round(pct / 100m, 4)); + } + result.Sort(); + return result; + } + + public static string FormatThresholds(IReadOnlyList? warnAt) + => warnAt is null ? "" : string.Join(", ", warnAt.Select(w => (w * 100m).ToString("0.##", CultureInfo.InvariantCulture))); +} + +/// Lenient reader for GET /admin/budgets/{id}/requests ("contributing settled request ids and amounts"): +/// accepts a bare array or {"items":[…]} and the obvious alternative field names, so a small backend naming +/// difference degrades to "Not reported" values instead of a broken page. Unknown shapes return null. +public static class BudgetRequests +{ + public static List? Parse(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + try + { + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + JsonElement array; + if (root.ValueKind == JsonValueKind.Array) array = root; + else if (root.ValueKind == JsonValueKind.Object && TryGet(root, out array, "items", "requests") && array.ValueKind == JsonValueKind.Array) { } + else return null; + + var list = new List(); + foreach (var e in array.EnumerateArray()) + { + if (e.ValueKind != JsonValueKind.Object) continue; + var id = Str(e, "request_id", "id", "requestId"); + if (string.IsNullOrWhiteSpace(id)) continue; + list.Add(new BudgetRequestDto + { + RequestId = id, + AttemptId = Str(e, "attempt_id", "attemptId"), + AmountUsd = Dec(e, "amount_usd", "settled_usd", "cost_usd", "amount"), + TimestampUtc = Time(e, "ts_utc", "settled_utc", "timestamp_utc", "utc"), + Scope = Str(e, "scope"), + Kind = Str(e, "kind", "op"), + Overrun = TryGet(e, out var ov, "overrun") && ov.ValueKind == JsonValueKind.True, + }); + } + return list; + } + catch (JsonException) + { + return null; + } + } + + private static bool TryGet(JsonElement o, out JsonElement value, params string[] names) + { + foreach (var n in names) + if (o.TryGetProperty(n, out value)) return true; + value = default; + return false; + } + + private static string? Str(JsonElement o, params string[] names) + => TryGet(o, out var v, names) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; + + private static decimal? Dec(JsonElement o, params string[] names) + => TryGet(o, out var v, names) && v.ValueKind == JsonValueKind.Number && v.TryGetDecimal(out var d) ? d : null; + + private static DateTimeOffset? Time(JsonElement o, params string[] names) + => TryGet(o, out var v, names) && v.ValueKind == JsonValueKind.String && v.TryGetDateTimeOffset(out var t) ? t : null; +} diff --git a/src/Covenant.Ui/Logic/ConfigDraft.cs b/src/Covenant.Ui/Logic/ConfigDraft.cs new file mode 100644 index 0000000..b866cc3 --- /dev/null +++ b/src/Covenant.Ui/Logic/ConfigDraft.cs @@ -0,0 +1,291 @@ +using System.Globalization; +using System.Net; +using System.Text.Json; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// Deep copies and canonical comparison of configuration DTOs. Copies go through the source-generated +/// UiJsonContext (the same codec the console uses on the wire), so a copy is exactly what would be sent and no +/// list or nested object is shared with the original. +public static class ConfigCopy +{ + public static CovenantConfigDto Deep(CovenantConfigDto source) + => JsonSerializer.Deserialize(Canonical(source), UiJsonContext.Default.CovenantConfigDto) + ?? throw new InvalidOperationException("configuration copy failed"); + + public static ConnectionDto Deep(ConnectionDto source) + { + var holder = new CovenantConfigDto { Connections = [source] }; + return Deep(holder).Connections[0]; + } + + /// The wire JSON of a configuration (nulls omitted) — the basis of dirty tracking. + public static string Canonical(CovenantConfigDto config) => JsonSerializer.Serialize(config, UiJsonContext.Default.CovenantConfigDto); + + /// Canonical JSON of one connection (for "changed in draft" flags). + public static string Canonical(ConnectionDto connection) => Canonical(new CovenantConfigDto { Connections = [connection] }); + + public static string Canonical(PolicyDto policy) => Canonical(new CovenantConfigDto { Policies = [policy] }); + + public static string Canonical(BudgetConfigDto budget) => Canonical(new CovenantConfigDto { Budgets = [budget] }); + + public static bool SameContent(CovenantConfigDto a, CovenantConfigDto b) => string.Equals(Canonical(a), Canonical(b), StringComparison.Ordinal); +} + +/// An edit session over one applied configuration version: a deep-copied, mutable DRAFT plus the +/// canonical text of the version it was taken from. Dirty = the draft's wire content differs from the base. +/// The base is never mutated, so Cancel/Reset is exact. +public sealed class ConfigDraft +{ + private readonly string _baseJson; + + public ConfigDraft(int baseVersion, string? baseEtag, CovenantConfigDto applied) + { + BaseVersion = baseVersion; + BaseEtag = string.IsNullOrWhiteSpace(baseEtag) ? EtagFor(baseVersion) : baseEtag!; + Base = ConfigCopy.Deep(applied); + _baseJson = ConfigCopy.Canonical(Base); + Draft = ConfigCopy.Deep(applied); + } + + public int BaseVersion { get; } + /// Sent as If-Match on Save: the version the operator started editing from. + public string BaseEtag { get; } + /// Private copy of the applied configuration (never handed out for editing). + public CovenantConfigDto Base { get; } + public CovenantConfigDto Draft { get; private set; } + + public bool IsDirty => !string.Equals(_baseJson, ConfigCopy.Canonical(Draft), StringComparison.Ordinal); + + /// Throws the draft away and starts again from the base version. + public void Reset() => Draft = ConfigCopy.Deep(Base); + + public static string EtagFor(int version) => "\"v" + version.ToString(CultureInfo.InvariantCulture) + "\""; +} + +/// Human change summary (sent as change_summary, ≤ 500 chars server-side; never secret values — +/// the configuration holds only secret REFERENCES). Lists added/removed/changed ids per section. +public static class ChangeSummary +{ + public static IReadOnlyList Lines(CovenantConfigDto before, CovenantConfigDto after) + { + var lines = new List(); + if (!string.Equals(before.Mode, after.Mode, StringComparison.Ordinal)) + lines.Add("mode " + (before.Mode ?? "unset") + " → " + (after.Mode ?? "unset")); + Section(lines, "connection", before.Connections, after.Connections, c => c.Id, c => Json(c)); + Section(lines, "policy", before.Policies, after.Policies, p => p.Id, p => Json(p)); + Section(lines, "budget", before.Budgets, after.Budgets, b => b.Id, b => Json(b)); + Section(lines, "application", before.Applications, after.Applications, a => a.Id, a => Json(a)); + Section(lines, "profile", before.Profiles, after.Profiles, p => p.Id, p => Json(p)); + if (!string.Equals(Json(before.Settings), Json(after.Settings), StringComparison.Ordinal)) + lines.Add("operational settings changed"); + return lines; + } + + /// One line for the PUT body: "Console: connection ollama changed; policy public changed". + public static string Text(CovenantConfigDto before, CovenantConfigDto after) + { + var lines = Lines(before, after); + var text = lines.Count == 0 ? "Console: no effective change" : "Console: " + string.Join("; ", lines); + return text.Length <= 480 ? text : text[..479] + "…"; + } + + private static void Section(List lines, string noun, IReadOnlyList before, IReadOnlyList after, + Func id, Func content) + { + var b = new Dictionary(StringComparer.Ordinal); + foreach (var x in before) b[id(x)] = content(x); + var a = new Dictionary(StringComparer.Ordinal); + foreach (var x in after) a[id(x)] = content(x); + foreach (var k in a.Keys.Where(k => !b.ContainsKey(k))) lines.Add(noun + " " + k + " added"); + foreach (var k in b.Keys.Where(k => !a.ContainsKey(k))) lines.Add(noun + " " + k + " removed"); + foreach (var k in a.Keys.Where(k => b.TryGetValue(k, out var old) && !string.Equals(old, a[k], StringComparison.Ordinal))) + lines.Add(noun + " " + k + " changed"); + var orderBefore = before.Select(id).Where(a.ContainsKey).ToList(); + var orderAfter = after.Select(id).Where(b.ContainsKey).ToList(); + if (!orderBefore.SequenceEqual(orderAfter, StringComparer.Ordinal)) lines.Add(noun + " order changed"); + } + + private static string Json(T value) + { + // Wrap in a config so every section uses the one registered source-generated type. + var holder = new CovenantConfigDto(); + switch (value) + { + case ConnectionDto c: holder.Connections.Add(c); break; + case PolicyDto p: holder.Policies.Add(p); break; + case BudgetConfigDto b: holder.Budgets.Add(b); break; + case ApplicationDto ap: holder.Applications.Add(ap); break; + case WorkloadProfileDto pr: holder.Profiles.Add(pr); break; + case OperationalSettingsDto s: holder.Settings = s; break; + default: return ""; + } + return ConfigCopy.Canonical(holder); + } +} + +public enum EditOutcomeKind +{ + /// 200 — the Host activated a NEW version (the only success). + Applied, + /// 412 (or 409) — the active version moved since editing started; the draft is kept, never overwritten. + Stale, + /// 422 — validation failed; the active version is unchanged; field errors map onto the draft. + Invalid, + /// 428 — the Host refused a write without If-Match (a console bug, reported verbatim). + PreconditionRequired, + /// 401 — admin token rejected (the session disconnects). + Unauthorized, + /// 404 — endpoint or version not available on this Host. + NotFound, + /// Anything else (400, 5xx, transport): nothing is assumed applied. + Failed, +} + +/// The UI state after a config write. is the NEW active version on Applied and the +/// server-reported active version on Stale/Invalid when it sent one. +public sealed record EditOutcome(EditOutcomeKind Kind, string Message, int? Version = null, + IReadOnlyList? Errors = null, IReadOnlyList? Warnings = null) +{ + public bool Succeeded => Kind == EditOutcomeKind.Applied; +} + +/// Maps a config write's HTTP answer (status + body text) onto . Pure: the +/// service hands it the raw response, so every branch is unit-tested. Success is ONLY a 2xx carrying a version. +public static class EditOutcomes +{ + public static EditOutcome FromResponse(int status, string? body, bool rollback = false) + { + if (status is >= 200 and < 300) + { + var ok = TryParse(body, UiJsonContext.Default.ConfigPutResponseDto); + if (ok is { Version: > 0 } put) + return new EditOutcome(EditOutcomeKind.Applied, + (rollback ? "Rollback applied as new version v" : "Applied version v") + V(put.Version), put.Version); + return new EditOutcome(EditOutcomeKind.Failed, "The Host answered " + V(status) + " without a version — not treated as applied."); + } + + var err = TryParse(body, UiJsonContext.Default.ConfigErrorResponseDto); + var reason = Clean(err?.Reason) ?? Clean(err?.Error); + switch (status) + { + case (int)HttpStatusCode.PreconditionFailed: + case (int)HttpStatusCode.Conflict: + return new EditOutcome(EditOutcomeKind.Stale, StaleMessage(err?.ActiveVersion), err?.ActiveVersion); + case (int)HttpStatusCode.UnprocessableEntity: + var errors = err?.Errors ?? []; + return new EditOutcome(EditOutcomeKind.Invalid, + errors.Count == 0 + ? "The Host rejected the configuration (" + (reason ?? "validation failed") + "). The active version is unchanged." + : Plural(errors.Count, "validation error") + " — nothing was applied; the active version is unchanged.", + err?.ActiveVersion, errors, err?.Warnings ?? []); + case 428: + return new EditOutcome(EditOutcomeKind.PreconditionRequired, + "The Host requires the edited version (If-Match). Nothing was applied" + (reason is null ? "." : ": " + reason), err?.ActiveVersion); + case (int)HttpStatusCode.Unauthorized: + return new EditOutcome(EditOutcomeKind.Unauthorized, "Admin token rejected — reconnect. Nothing was applied."); + case (int)HttpStatusCode.NotFound: + return new EditOutcome(EditOutcomeKind.NotFound, + reason is not null && rollback ? "Not found: " + reason : "Not available on this Host (404) — nothing was applied."); + default: + return new EditOutcome(EditOutcomeKind.Failed, + "HTTP " + V(status) + (reason is null ? "" : ": " + reason) + " — nothing is assumed applied."); + } + } + + /// "Configuration changed since you started editing (now v8)." + public static string StaleMessage(int? activeVersion) + => "Configuration changed since you started editing" + (activeVersion is { } v ? " (now v" + V(v) + ")." : ".") + + " Your draft was not applied and is kept."; + + private static T? TryParse(string? body, System.Text.Json.Serialization.Metadata.JsonTypeInfo info) where T : class + { + if (string.IsNullOrWhiteSpace(body)) return null; + try { return JsonSerializer.Deserialize(body, info); } + catch (JsonException) { return null; } + } + + private static string? Clean(string? s) => string.IsNullOrWhiteSpace(s) ? null : (s.Length > 300 ? s[..299] + "…" : s.Trim()); + private static string V(int v) => v.ToString(CultureInfo.InvariantCulture); + private static string Plural(int n, string noun) => V(n) + " " + noun + (n == 1 ? "" : "s"); +} + +/// Field-path lookup over validation issues. Paths are the Host's (connections[0].models[1].price, +/// policies[2].targets[0], settings.prompt_preview_chars); a field shows the issues at its path and +/// below it. +public sealed class IssueIndex +{ + public static readonly IssueIndex Empty = new([], []); + + public IssueIndex(IReadOnlyList errors, IReadOnlyList warnings) + { + Errors = errors; + Warnings = warnings; + } + + public IReadOnlyList Errors { get; } + public IReadOnlyList Warnings { get; } + public bool HasErrors => Errors.Count > 0; + + public IReadOnlyList ErrorsAt(string path) => Errors.Where(i => Under(i.Path, path)).ToList(); + public IReadOnlyList WarningsAt(string path) => Warnings.Where(i => Under(i.Path, path)).ToList(); + public bool HasErrorAt(string path) => Errors.Any(i => Under(i.Path, path)); + + /// Errors whose path is NOT under any of the given prefixes (shown in the page-level list so nothing + /// is ever hidden because no field claimed it). + public IReadOnlyList Unclaimed(IEnumerable claimedPrefixes) + { + var prefixes = claimedPrefixes.ToList(); + return Errors.Where(i => !prefixes.Any(p => Under(i.Path, p))).ToList(); + } + + /// True when equals or is a member/element of it. + public static bool Under(string? issuePath, string prefix) + { + if (string.IsNullOrEmpty(issuePath) || string.IsNullOrEmpty(prefix)) return false; + if (string.Equals(issuePath, prefix, StringComparison.Ordinal)) return true; + if (!issuePath.StartsWith(prefix, StringComparison.Ordinal)) return false; + var next = issuePath[prefix.Length]; + return next is '.' or '['; + } + + public static string Connection(int i) => "connections[" + I(i) + "]"; + public static string Model(int c, int m) => Connection(c) + ".models[" + I(m) + "]"; + public static string Policy(int i) => "policies[" + I(i) + "]"; + public static string Target(int p, int t) => Policy(p) + ".targets[" + I(t) + "]"; + public static string Budget(int i) => "budgets[" + I(i) + "]"; + public static string Setting(string name) => "settings." + name; + + private static string I(int i) => i.ToString(CultureInfo.InvariantCulture); +} + +/// Actionable guidance for validation codes whose fix is OUTSIDE the console (startup configuration, +/// server-side secrets). Never contains a secret value — only key names. +public static class IssueHelp +{ + public static string? For(string? code) => code switch + { + "endpoint_not_allow_listed" => + "The endpoint's host:port is not on the startup egress allow-list. Add it to Providers:ProbeAllowList in the Host's startup configuration and restart Covenant; the console cannot widen where Covenant may connect.", + "boundary_not_approved" => + "A Local connection's endpoint must be listed in Providers:LocalEndpoints (or the legacy Local:Endpoint) at startup; OpenAI and Anthropic connections are always Cloud. Add host:port there and restart.", + "secret_unavailable" => + "The referenced secret is not set on the server. Set it in the Host's environment or vault (for Secrets:openai the environment variable is Secrets__openai) and restart; the console never sees or stores secret values.", + "invalid_secret_ref" => + "Secret references must be Secrets: or one of the legacy keys OpenAI:ApiKey, Anthropic:ApiKey, Local:ApiKey.", + "cloud_in_local_only" => + "Local-only mode cannot execute cloud connections. Switch to Hybrid on the Policies page, or keep this connection disabled.", + "sensitive_cloud_target" => + "PII/PHI never route to cloud destinations. Remove the cloud target from this policy.", + "unpriced_paid_target_under_hard_budget" => + "A paid target needs input and output prices while a hard budget applies — an unknown price is never treated as $0.", + "client_unbuildable" => + "Covenant could not build a provider client for this enabled connection (endpoint, secret or allow-list). Disable it or fix the cause above.", + "ambiguous_policy_overlap" => + "Two enabled policies at the same specificity cover the same classification/profile. Narrow one by profile or disable it — Covenant never picks an arbitrary winner.", + "missing_global_budget" => + "A global budget is required: nothing is unlimited.", + _ => null, + }; +} diff --git a/src/Covenant.Ui/Logic/ConnectionDrafts.cs b/src/Covenant.Ui/Logic/ConnectionDrafts.cs new file mode 100644 index 0000000..6b0ba1b --- /dev/null +++ b/src/Covenant.Ui/Logic/ConnectionDrafts.cs @@ -0,0 +1,416 @@ +using System.Globalization; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// One model row in the connection form. = permitted on the connection (saved); +/// discovered tags start unselected — discovery never approves a model. +public sealed class ModelForm +{ + public string ModelId { get; set; } = ""; + public string? DisplayName { get; set; } + public int? ContextTokens { get; set; } + public int? MaxOutputTokens { get; set; } + public bool Selected { get; set; } + /// True when the row came from the saved configuration (prefilled with actual values). + public bool Configured { get; set; } + /// True/false once the endpoint was probed in this form; null = not probed. + public bool? ReportedByEndpoint { get; set; } + public bool Priced { get; set; } + public decimal? InputPer1M { get; set; } + public decimal? OutputPer1M { get; set; } + public string Basis { get; set; } = ""; + public string? EffectiveDate { get; set; } +} + +/// Editable copy of one connection (Add or Edit). Pure: produces a and is put +/// into the configuration DRAFT only by the page; nothing is applied until the Host confirms a new version. +public sealed class ConnectionForm +{ + public const string BasisLocal = "zero-marginal-local"; + public const string BasisList = "provider-list"; + public const string BasisContract = "contract"; + + public bool IsNew { get; init; } + /// Id of the saved connection being edited (immutable on edit: policies reference it). + public string? OriginalId { get; init; } + public string Id { get; set; } = ""; + public string DisplayName { get; set; } = ""; + /// Ollama | OpenAiCompatible | OpenAi | Anthropic (wire spelling). + public string Kind { get; set; } = "Ollama"; + /// Local | Cloud (wire spelling). + public string Boundary { get; set; } = "Local"; + public string Endpoint { get; set; } = ""; + public bool Enabled { get; set; } = true; + public string? SecretRef { get; set; } + public int? TimeoutSeconds { get; set; } + public List Models { get; set; } = []; + + public bool IsOllama => Kind == "Ollama"; + public bool IsCloudKind => Kind is "OpenAi" or "Anthropic"; + + public static ConnectionForm NewOllama(IEnumerable existingIds) => new() + { + IsNew = true, + Kind = "Ollama", + Boundary = "Local", + DisplayName = "Ollama (in perimeter)", + Id = ConnectionRules.UniqueId("ollama", existingIds), + }; + + public static ConnectionForm NewCloud(string kind, IEnumerable existingIds) + { + var f = new ConnectionForm { IsNew = true }; + f.SetKind(kind); + f.DisplayName = ConnectionRules.KindLabel(kind); + f.Id = ConnectionRules.UniqueId(kind.ToLowerInvariant(), existingIds); + return f; + } + + /// Prefills the form with the saved connection's ACTUAL values. + public static ConnectionForm FromConnection(ConnectionDto c) => new() + { + IsNew = false, + OriginalId = c.Id, + Id = c.Id, + DisplayName = c.DisplayName ?? c.Id, + Kind = c.Kind ?? "", + Boundary = c.Boundary ?? "", + Endpoint = c.Endpoint ?? "", + Enabled = c.Enabled, + SecretRef = c.SecretRef, + TimeoutSeconds = c.TimeoutSeconds, + Models = c.Models.Select(m => new ModelForm + { + ModelId = m.ModelId, + DisplayName = m.DisplayName, + ContextTokens = m.ContextTokens, + MaxOutputTokens = m.MaxOutputTokens, + Selected = true, + Configured = true, + Priced = m.Price is not null, + InputPer1M = m.Price?.InputPer1M, + OutputPer1M = m.Price?.OutputPer1M, + Basis = m.Price?.Basis ?? "", + EffectiveDate = m.Price?.EffectiveDate, + }).ToList(), + }; + + /// Kind fixes the boundary for the SDK kinds (OpenAI/Anthropic are always Cloud, Ollama is Local); + /// OpenAI-compatible keeps the operator's choice (Local needs a startup-approved endpoint). + public void SetKind(string kind) + { + Kind = kind; + if (kind is "OpenAi" or "Anthropic") Boundary = "Cloud"; + else if (kind == "Ollama") Boundary = "Local"; + else if (Boundary is not ("Local" or "Cloud")) Boundary = "Cloud"; + } + + /// Merges probe results: configured rows are marked reported/not reported; NEW tags are added + /// UNSELECTED with an explicit zero-marginal-local price for a local connection (editable, never hidden). + public void ApplyDiscovery(IEnumerable tags) + { + var reported = new HashSet(tags.Where(t => !string.IsNullOrWhiteSpace(t)), StringComparer.Ordinal); + foreach (var m in Models) m.ReportedByEndpoint = reported.Contains(m.ModelId); + foreach (var tag in reported.OrderBy(t => t, StringComparer.Ordinal)) + { + if (Models.Any(m => string.Equals(m.ModelId, tag, StringComparison.Ordinal))) continue; + Models.Add(DefaultModel(tag, reportedByEndpoint: true)); + } + } + + /// A manually added model row (cloud model ids are typed, not discovered). Starts selected. + public ModelForm AddModel(string modelId) + { + var m = DefaultModel(modelId.Trim(), reportedByEndpoint: null); + m.Selected = true; + Models.Add(m); + return m; + } + + private ModelForm DefaultModel(string id, bool? reportedByEndpoint) + { + bool local = Boundary == "Local"; + return new ModelForm + { + ModelId = id, + Selected = false, + Configured = false, + ReportedByEndpoint = reportedByEndpoint, + Priced = local, + InputPer1M = local ? 0m : null, + OutputPer1M = local ? 0m : null, + Basis = local ? BasisLocal : BasisList, + }; + } + + public IReadOnlyList SelectedModels => Models.Where(m => m.Selected).ToList(); + + /// Problems that block "Preview impact" (the Host validator still has the final word). + public IReadOnlyList Problems(IEnumerable otherConnectionIds, IReadOnlyDictionary? secrets) + { + var p = new List(); + var others = otherConnectionIds.ToHashSet(StringComparer.Ordinal); + if (!ConnectionRules.IsValidId(Id)) p.Add("Connection id must be 1–64 characters of letters, digits, '.', '_' or '-'."); + else if (IsNew && others.Contains(Id)) p.Add("A connection with id '" + Id + "' already exists."); + if (string.IsNullOrWhiteSpace(DisplayName)) p.Add("Enter a display name."); + if (Kind is not ("Ollama" or "OpenAiCompatible" or "OpenAi" or "Anthropic")) p.Add("Choose a provider kind."); + if (ConnectionRules.EndpointRequired(Kind) || Endpoint.Trim().Length > 0) + { + if (ConnectionLogic.EndpointProblem(Endpoint) is { } e) p.Add(e); + } + if (Boundary is not ("Local" or "Cloud")) p.Add("Choose Local or Cloud."); + if (IsCloudKind && Boundary != "Cloud") p.Add("OpenAI and Anthropic connections are always Cloud."); + if (TimeoutSeconds is < 1 or > 600) p.Add("Timeout must be 1–600 seconds."); + + var selected = SelectedModels; + if (selected.Count == 0) p.Add("Select at least one exact model id to permit — nothing is approved by default."); + var dup = selected.GroupBy(m => m.ModelId, StringComparer.Ordinal).FirstOrDefault(g => g.Count() > 1); + if (dup is not null) p.Add("Model '" + dup.Key + "' is listed twice."); + foreach (var m in selected) + { + if (string.IsNullOrWhiteSpace(m.ModelId) || m.ModelId.Length > 200) p.Add("Every model needs its exact provider id/tag (≤ 200 characters)."); + if (m.Priced) + { + if (m.InputPer1M is null || m.OutputPer1M is null) p.Add(m.ModelId + ": enter both input and output prices (per 1M tokens), or mark it unpriced."); + else if (m.InputPer1M < 0 || m.OutputPer1M < 0) p.Add(m.ModelId + ": prices cannot be negative."); + if (string.IsNullOrWhiteSpace(m.Basis)) p.Add(m.ModelId + ": state the price basis (e.g. provider-list, contract, zero-marginal-local)."); + } + else if (Boundary == "Cloud") + { + p.Add(m.ModelId + ": a paid cloud model needs prices — an unknown price is never treated as $0."); + } + if (!string.IsNullOrWhiteSpace(m.EffectiveDate) && !DateOnly.TryParseExact(m.EffectiveDate.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _)) + p.Add(m.ModelId + ": effective date must be YYYY-MM-DD."); + } + + if (Boundary == "Cloud" || IsCloudKind) + { + if (string.IsNullOrWhiteSpace(SecretRef)) p.Add("Choose the server-side secret reference that holds this provider's credential."); + else if (!ConnectionRules.IsValidSecretRef(SecretRef)) p.Add("Secret references must be Secrets: or OpenAI:ApiKey / Anthropic:ApiKey / Local:ApiKey."); + else if (secrets is not null && secrets.TryGetValue(SecretRef.Trim(), out var s) && !s.Available) + p.Add("Secret " + SecretRef.Trim() + " is not available on the server — set it server-side and restart before saving."); + } + return p; + } + + /// The connection as it will appear in the draft. Unselected rows are dropped. + public ConnectionDto ToConnection() => new() + { + Id = Id.Trim(), + DisplayName = DisplayName.Trim(), + Kind = Kind, + Boundary = Boundary, + Endpoint = string.IsNullOrWhiteSpace(Endpoint) ? null : Endpoint.Trim(), + Enabled = Enabled, + SecretRef = string.IsNullOrWhiteSpace(SecretRef) ? null : SecretRef.Trim(), + TimeoutSeconds = TimeoutSeconds, + Models = SelectedModels.Select(m => new ModelDto + { + ModelId = m.ModelId.Trim(), + DisplayName = string.IsNullOrWhiteSpace(m.DisplayName) ? null : m.DisplayName.Trim(), + ContextTokens = m.ContextTokens, + MaxOutputTokens = m.MaxOutputTokens, + Price = m.Priced + ? new PriceDto + { + InputPer1M = m.InputPer1M, + OutputPer1M = m.OutputPer1M, + Basis = m.Basis.Trim(), + EffectiveDate = string.IsNullOrWhiteSpace(m.EffectiveDate) ? null : m.EffectiveDate.Trim(), + } + : null, + }).ToList(), + }; + + /// Id under which this form was last put into the draft (a new connection's id may change between previews). + public string? AppliedAsId { get; private set; } + + /// Puts this connection into (replacing the edited one — or this form's earlier + /// copy — in place, or appending). Returns its index in the draft's connection list (for issue paths). + public int ApplyTo(CovenantConfigDto draft) + { + var conn = ToConnection(); + var key = AppliedAsId ?? OriginalId ?? conn.Id; + int i = draft.Connections.FindIndex(c => string.Equals(c.Id, key, StringComparison.Ordinal)); + if (i >= 0) draft.Connections[i] = conn; + else + { + draft.Connections.Add(conn); + i = draft.Connections.Count - 1; + } + AppliedAsId = conn.Id; + return i; + } + + /// Index in the issue path of the n-th SELECTED model row (unselected rows are not sent). + public int? SentIndex(ModelForm row) + { + if (!row.Selected) return null; + int n = 0; + foreach (var m in Models) + { + if (ReferenceEquals(m, row)) return n; + if (m.Selected) n++; + } + return null; + } + + /// Model ids removed from an existing connection that enabled policies still name (shown before preview). + public IReadOnlyList RemovedModelsStillRouted(CovenantConfigDto config) + { + if (OriginalId is null) return []; + var keep = SelectedModels.Select(m => m.ModelId).ToHashSet(StringComparer.Ordinal); + return config.Policies.Where(p => p.Enabled) + .SelectMany(p => p.Targets) + .Where(t => string.Equals(t.ConnectionId, OriginalId, StringComparison.Ordinal) && !keep.Contains(t.ModelId)) + .Select(t => t.ConnectionId + "/" + t.ModelId) + .Distinct(StringComparer.Ordinal) + .ToList(); + } +} + +/// Connection rules mirrored from the Host validator (for early, inline feedback only). +public static class ConnectionRules +{ + public static readonly IReadOnlyList LegacySecretRefs = ["OpenAI:ApiKey", "Anthropic:ApiKey", "Local:ApiKey"]; + + public static bool IsValidId(string? id) + => id is { Length: >= 1 and <= 64 } && id.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-'); + + public static bool IsValidSecretRef(string? r) + { + if (string.IsNullOrWhiteSpace(r)) return false; + var t = r.Trim(); + if (LegacySecretRefs.Contains(t, StringComparer.Ordinal)) return true; + return t.StartsWith("Secrets:", StringComparison.Ordinal) && t.Length > 8 && t.Length <= 136 + && t[8..].All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-'); + } + + /// The environment variable name an operator sets for a secret reference ("Secrets:openai" → "Secrets__openai"). + public static string EnvVarFor(string secretRef) => secretRef.Trim().Replace(":", "__", StringComparison.Ordinal); + + public static bool EndpointRequired(string? kind) => kind is "Ollama" or "OpenAiCompatible"; + + public static string KindLabel(string? kind) => kind switch + { + "Ollama" => "Ollama", + "OpenAiCompatible" => "OpenAI-compatible", + "OpenAi" => "OpenAI", + "Anthropic" => "Anthropic", + null or "" => "Kind not reported", + _ => kind, + }; + + /// "ollama", "ollama-2", … — never reuses an existing id. + public static string UniqueId(string seed, IEnumerable existing) + { + var set = existing.ToHashSet(StringComparer.Ordinal); + var cleaned = new string(seed.Where(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-').ToArray()).ToLowerInvariant(); + if (cleaned.Length == 0) cleaned = "connection"; + if (cleaned.Length > 56) cleaned = cleaned[..56]; + if (!set.Contains(cleaned)) return cleaned; + for (int i = 2; i < 1000; i++) + { + var candidate = cleaned + "-" + i.ToString(CultureInfo.InvariantCulture); + if (!set.Contains(candidate)) return candidate; + } + return cleaned + "-" + Guid.NewGuid().ToString("N")[..6]; + } + + /// "host:port" of an endpoint, or the provider default authority for OpenAI/Anthropic without one. + public static string? AuthorityOf(string? kind, string? endpoint) + { + if (!string.IsNullOrWhiteSpace(endpoint)) return ConnectionLogic.Authority(endpoint); + return kind switch + { + "OpenAi" => "api.openai.com:443", + "Anthropic" => "api.anthropic.com:443", + _ => null, + }; + } + + /// Secret references the Host reported (names only, never values) with their availability. + public static IReadOnlyList<(string Ref, bool Available)> SecretChoices(IReadOnlyDictionary? secrets) + => secrets is null ? [] : secrets.OrderBy(kv => kv.Key, StringComparer.Ordinal).Select(kv => (kv.Key, kv.Value.Available)).ToList(); +} + +/// A connection's observed health, one summary line plus supporting timestamps (spec §5): the last +/// endpoint PROBE and the last successful governed INFERENCE are separate facts and are never merged into a +/// contradictory "ready" / "never succeeded". +public sealed record ConnectionHealthView(string Summary, string Tone, IReadOnlyList<(string Label, string Value)> Details); + +public static class ConnectionHealth +{ + /// Draft/applied enabled state. + /// Per-model health from the catalog (observed from real governed calls). + /// This session's probe of the endpoint (point-in-time), if any. + /// When that probe ran (browser clock) when the Host did not stamp it. + /// The Host's recorded probe health for an APPLIED endpoint, when reported. + public static ConnectionHealthView Summarize(bool enabled, IReadOnlyList models, ProbeResponse? probe, + DateTimeOffset? probedAtUtc, ModelHealth? endpointProbeHealth, DateTimeOffset nowUtc) + { + DateTimeOffset? lastOk = Max(models.Select(h => h?.LastSuccessUtc)); + DateTimeOffset? lastFail = Max(models.Select(h => h?.LastFailureUtc)); + string? lastError = models.Where(h => h is not null && h.LastFailureUtc is not null && h.LastFailureUtc == lastFail).Select(h => h!.LastError).FirstOrDefault(e => !string.IsNullOrWhiteSpace(e)); + + // Probe: this session's result wins over the Host's recorded endpoint health (newer, and it is what the operator just did). + DateTimeOffset? probeAt = null; + bool? probeOk = null; + string? probeError = null; + if (probe is not null) + { + probeAt = probe.CheckedUtc ?? probedAtUtc; + probeOk = probe.Allowed && probe.Reachable; + probeError = !probe.Allowed ? "destination not on the probe allow-list" : probe.Reachable ? null : (probe.Error ?? "unreachable"); + } + else if (endpointProbeHealth is { } eh && (eh.LastSuccessUtc is not null || eh.LastFailureUtc is not null)) + { + bool failedLast = eh.LastFailureUtc is { } f && (eh.LastSuccessUtc is null || f > eh.LastSuccessUtc); + probeAt = failedLast ? eh.LastFailureUtc : eh.LastSuccessUtc; + probeOk = !failedLast; + probeError = failedLast ? (eh.LastError ?? "unreachable") : null; + } + + var details = new List<(string, string)> + { + ("Last endpoint probe", probeAt is null ? "Not probed" : (probeOk == true ? "Reachable" : "Failed") + " · " + Stamp(probeAt, nowUtc) + (probeError is null ? "" : " · " + probeError)), + ("Last successful governed call", lastOk is null ? "None observed" : Stamp(lastOk, nowUtc)), + ("Last failed governed call", lastFail is null ? "None observed" : Stamp(lastFail, nowUtc) + (lastError is null ? "" : " · " + lastError)), + }; + + if (!enabled) return new("Disabled — not eligible for any route", "hollow", details); + + bool failureNewest = lastFail is { } lf && (lastOk is null || lf > lastOk); + if (failureNewest) + return new("Last governed call failed " + Ago(lastFail, nowUtc) + (lastOk is null ? " · no successful call observed" : " · last success " + Ago(lastOk, nowUtc)), "bad", details); + if (lastOk is not null) + return new("Last successful governed call " + Ago(lastOk, nowUtc), "ok", details); + if (probeOk == true) + return new("Endpoint reachable (probe " + Ago(probeAt, nowUtc) + ") · no governed call observed yet", "hollow", details); + if (probeOk == false) + return new("Endpoint probe failed " + Ago(probeAt, nowUtc) + " · no governed call observed yet", "bad", details); + return new("Not observed yet — test the endpoint or run a request", "hollow", details); + } + + private static DateTimeOffset? Max(IEnumerable values) + { + DateTimeOffset? best = null; + foreach (var v in values) + if (v is { } t && (best is null || t > best)) best = t; + return best; + } + + public static string Ago(DateTimeOffset? t, DateTimeOffset now) + { + if (t is null) return "never"; + var s = (long)Math.Max(0, (now - t.Value).TotalSeconds); + if (s < 60) return s.ToString(CultureInfo.InvariantCulture) + " s ago"; + if (s < 3600) return (s / 60).ToString(CultureInfo.InvariantCulture) + " min ago"; + if (s < 86400) return (s / 3600).ToString(CultureInfo.InvariantCulture) + " h ago"; + return (s / 86400).ToString(CultureInfo.InvariantCulture) + " d ago"; + } + + private static string Stamp(DateTimeOffset? t, DateTimeOffset now) + => t is null ? "never" : t.Value.UtcDateTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) + " UTC (" + Ago(t, now) + ")"; +} diff --git a/src/Covenant.Ui/Logic/ConnectionLogic.cs b/src/Covenant.Ui/Logic/ConnectionLogic.cs index 60501ad..07d4e94 100644 --- a/src/Covenant.Ui/Logic/ConnectionLogic.cs +++ b/src/Covenant.Ui/Logic/ConnectionLogic.cs @@ -1,11 +1,8 @@ -using System.Text; -using Covenant.Ui.Models; - namespace Covenant.Ui.Logic; -/// Pure helpers for the Ollama connection wizard: endpoint validation/normalisation (mirrors the Host's -/// ProviderProbe.Validate and catalog formatting), the read-back check, and the configuration guidance text. -/// Nothing here applies configuration — runtime apply is not available in this version. +/// Pure endpoint helpers for Models & connections: validation/normalisation (mirrors the Host's +/// ProviderProbe.Validate and catalog formatting) and the governed-test prompt. Configuration is edited through the +/// versioned draft (ConnectionDrafts / ConfigDraft) — there is no "edit a file and restart" path any more. public static class ConnectionLogic { /// Synthetic prompt for the governed test. It contains the published sample SSN so that in cloud @@ -51,45 +48,4 @@ public static bool SameEndpoint(string? a, string? b) var nb = Normalize(b); return na is not null && nb is not null && string.Equals(na, nb, StringComparison.Ordinal); } - - /// Step 6 gate: the running instance loaded exactly this endpoint and tag, and registered it. - public static (bool Pass, string Message) CheckApplied(CatalogResponse? catalog, string draftEndpoint, string tag) - { - if (catalog is null) return (false, "The catalog could not be read, so the applied configuration is unknown."); - var local = catalog.Local; - if (local is null || !local.Configured) - return (false, "The running instance has no local route configured (Local:Endpoint / Local:ModelId not loaded). Apply the configuration and restart Covenant."); - if (!SameEndpoint(local.Endpoint, draftEndpoint)) - return (false, $"The running endpoint is {local.Endpoint ?? "not reported"}, not {Normalize(draftEndpoint)}. Apply the configuration and restart Covenant."); - if (!string.Equals(local.ModelId, tag, StringComparison.Ordinal)) - return (false, $"The running model id is {local.ModelId ?? "not reported"}, not {tag}. The tag must match exactly."); - if (!local.Registered) - return (false, "The endpoint and tag are loaded but the server reports the local model as NOT registered."); - return (true, "The running instance loaded this endpoint and tag, and the server reports the local model as registered."); - } - - public static string RouteReview(string? mode, string tag) - => string.Equals(mode, "local-only", StringComparison.OrdinalIgnoreCase) - ? $"Local-only mode: every classification (Public, Internal, PII, PHI) routes to local:{tag}. No cloud provider is registered, and Covenant refuses to start if a cloud key is configured." - : $"Cloud mode: PII and PHI requests route to local:{tag}. Public and Internal stay on their cloud routes. If the local model fails, protected requests are refused — there is no cloud fallback."; - - /// Configuration guidance: names and values only, never a secret. - public static string ConfigBlock(string draftEndpoint, string tag, bool localOnly) - { - var endpoint = draftEndpoint.Trim(); - var sb = new StringBuilder(); - sb.AppendLine("# Environment variables (names and values; no secrets)"); - if (localOnly) sb.AppendLine("Providers__Mode=local-only"); - else sb.AppendLine("# Providers__Mode=local-only (optional: route everything locally; requires NO cloud key)"); - sb.AppendLine("Local__Endpoint=" + endpoint); - sb.AppendLine("Local__ModelId=" + tag); - sb.AppendLine(); - sb.AppendLine("# Equivalent dotnet user-secrets (run in src/Covenant.Host)"); - if (localOnly) sb.AppendLine("dotnet user-secrets set \"Providers:Mode\" \"local-only\""); - sb.AppendLine("dotnet user-secrets set \"Local:Endpoint\" \"" + endpoint + "\""); - sb.AppendLine("dotnet user-secrets set \"Local:ModelId\" \"" + tag + "\""); - sb.AppendLine(); - sb.Append("# Local__ApiKey only if Ollama sits behind an authenticating proxy — set it in your vault, never here."); - return sb.ToString(); - } } diff --git a/src/Covenant.Ui/Logic/CostText.cs b/src/Covenant.Ui/Logic/CostText.cs index dfb0e3a..b25eadf 100644 --- a/src/Covenant.Ui/Logic/CostText.cs +++ b/src/Covenant.Ui/Logic/CostText.cs @@ -11,7 +11,8 @@ public static class CostText private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; - public static string Usd(decimal value) => "$" + value.ToString("F4", Inv); + /// Significant-digit USD (Logic/Money): a non-zero charge is never shown as $0.00. + public static string Usd(decimal value) => Money.Usd(value); public static string Cost(AuditEntryView r) => r.CostBasis switch { diff --git a/src/Covenant.Ui/Logic/ImpactText.cs b/src/Covenant.Ui/Logic/ImpactText.cs new file mode 100644 index 0000000..0516fa9 --- /dev/null +++ b/src/Covenant.Ui/Logic/ImpactText.cs @@ -0,0 +1,60 @@ +using System.Globalization; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// One changed route in the impact preview, ready to display. +public sealed record ImpactLine(string Scope, string Before, string After, bool NowRefused, bool WasRefused); + +/// Formats the Host's impact analysis (POST /admin/config/validate → impact). The Host computes it +/// with the real engine against the candidate; the console only words it. Nothing here guesses an impact. +public static class ImpactText +{ + /// "Public" or "Public · profile public-tickets" (profile "*" / empty = any profile). + public static string Scope(ConfigImpactRowDto row) + { + var cls = PolicyText.ClassificationLabel(row.Classification); + return string.IsNullOrWhiteSpace(row.Profile) || row.Profile is "*" or "any" ? cls : cls + " · profile " + row.Profile; + } + + /// Changed rows only (the Host marks changed; a row whose text differs is also treated as changed + /// so an older Host without the flag still previews correctly). + public static IReadOnlyList ChangedRoutes(ConfigImpactDto? impact) + { + if (impact is null) return []; + var lines = new List(); + foreach (var r in impact.Classifications) + { + bool changed = r.Changed || !string.Equals(r.Before, r.After, StringComparison.Ordinal); + if (!changed) continue; + lines.Add(new ImpactLine(Scope(r), Route(r.Before), Route(r.After), IsRefused(r.After), IsRefused(r.Before))); + } + return lines; + } + + public static bool IsRefused(string? route) => route is null || route.StartsWith("refused", StringComparison.OrdinalIgnoreCase); + + public static string Route(string? route) => string.IsNullOrWhiteSpace(route) ? "Not reported" : route; + + /// One-line headline: "2 routes change · 1 newly refused · 1 pricing gap" or "No routing change". + public static string Headline(ConfigImpactDto? impact) + { + if (impact is null) return "Impact not computed (the candidate has structural errors)."; + var parts = new List(); + int changed = ChangedRoutes(impact).Count; + if (changed > 0) parts.Add(Count(changed, "route changes", "routes change")); + if (impact.NewlyRefused.Count > 0) parts.Add(N(impact.NewlyRefused.Count) + " newly refused"); + if (impact.UnavailableDestinations.Count > 0) parts.Add(Count(impact.UnavailableDestinations.Count, "unavailable destination", "unavailable destinations")); + if (impact.PricingGaps.Count > 0) parts.Add(Count(impact.PricingGaps.Count, "pricing gap", "pricing gaps")); + if (impact.ApplicationsAffected.Count > 0) parts.Add(Count(impact.ApplicationsAffected.Count, "application affected", "applications affected")); + return parts.Count == 0 ? "No routing change for any classification or profile." : string.Join(" · ", parts); + } + + /// True when the preview contains something an operator must acknowledge before saving (requests that + /// would now be refused, or destinations that cannot run). + public static bool NeedsAttention(ConfigImpactDto? impact) + => impact is not null && (impact.NewlyRefused.Count > 0 || impact.UnavailableDestinations.Count > 0 || impact.PricingGaps.Count > 0); + + private static string Count(int n, string one, string many) => N(n) + " " + (n == 1 ? one : many); + private static string N(int n) => n.ToString(CultureInfo.InvariantCulture); +} diff --git a/src/Covenant.Ui/Logic/Money.cs b/src/Covenant.Ui/Logic/Money.cs new file mode 100644 index 0000000..3313022 --- /dev/null +++ b/src/Covenant.Ui/Logic/Money.cs @@ -0,0 +1,85 @@ +using System.Globalization; + +namespace Covenant.Ui.Logic; + +/// USD formatting with precision appropriate to tiny charges (spec §4.5, ADR-0014 "Precision"): +/// a non-zero amount is never shown as "$0.00". Rules (invariant culture, the bundle ships no globalization data): +/// +/// null → "Not reported" (unknown is never a zero). +/// exactly zero → "$0.00". +/// |v| ≥ 1 → two decimals with thousands separators ("$1,234.56"). +/// 0.01 ≤ |v| < 1 → up to four decimals, at least two ("$0.50", "$0.0123"). +/// |v| < 0.01 → three significant digits, trailing zeros trimmed ("$0.000184", "$0.003"). +/// 0 < |v| < 0.000001 → "<$0.000001" (still visibly non-zero). +/// +/// Negative amounts carry a leading minus ("-$1.23"). +public static class Money +{ + public const string NotReported = "Not reported"; + + private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; + private const decimal Floor = 0.000001m; + + public static string Usd(decimal? value) => value is { } v ? Usd(v) : NotReported; + + public static string Usd(decimal value) + { + if (value == 0m) return "$0.00"; + var sign = value < 0 ? "-" : ""; + var abs = Math.Abs(value); + if (abs >= 1m) return sign + "$" + Math.Round(abs, 2, MidpointRounding.AwayFromZero).ToString("N2", Inv); + if (abs >= 0.01m) return sign + "$" + TrimTo(Math.Round(abs, 4, MidpointRounding.AwayFromZero), 2); + if (abs < Floor) return sign + "<$0.000001"; + return sign + "$" + TrimTo(Significant(abs, 3), 2); + } + + /// Caps and limits: always two decimals ("$250.00"), tiny caps still significant ("$0.005"). + public static string Cap(decimal value) + => Math.Abs(value) >= 0.01m || value == 0m + ? (value < 0 ? "-" : "") + "$" + Math.Round(Math.Abs(value), 2, MidpointRounding.AwayFromZero).ToString("N2", Inv) + : Usd(value); + + /// A price per one million tokens ("$0.15 / 1M"); null = "Unpriced". + public static string PerMillion(decimal? value) => value is { } v ? Usd(v) + " / 1M" : "Unpriced"; + + /// "in $0.15 · out $0.60 per 1M tokens"; "Unpriced — cost unknown, not zero" when either side is missing. + public static string Price(decimal? input, decimal? output) + { + if (input is null || output is null) return "Unpriced — cost unknown, not zero"; + if (input == 0m && output == 0m) return "$0 provider charge (infrastructure excluded)"; + return "in " + Usd(input.Value) + " · out " + Usd(output.Value) + " per 1M tokens"; + } + + /// Rounds to significant digits (0 < v < 1). + private static decimal Significant(decimal v, int digits) + { + int leadingZeros = 0; + var probe = v; + while (probe < 0.1m && leadingZeros < 26) + { + probe *= 10m; + leadingZeros++; + } + int decimals = Math.Min(28, leadingZeros + digits); + return Math.Round(v, decimals, MidpointRounding.AwayFromZero); + } + + /// Fixed-point text with trailing zeros removed but at least decimals. + private static string TrimTo(decimal v, int minDecimals) + { + var text = v.ToString("0.############################", Inv); + int dot = text.IndexOf('.'); + int have = dot < 0 ? 0 : text.Length - dot - 1; + if (have >= minDecimals) return text; + if (dot < 0) text += "."; + return text + new string('0', minDecimals - have); + } + + /// "62%" style share for meters; "n/a" without a positive cap. + public static string Share(decimal part, decimal whole) + { + if (whole <= 0) return "n/a"; + var pct = part / whole * 100m; + return pct.ToString(pct >= 10 ? "F0" : "F1", Inv) + "%"; + } +} diff --git a/src/Covenant.Ui/Logic/PolicyRoutes.cs b/src/Covenant.Ui/Logic/PolicyRoutes.cs new file mode 100644 index 0000000..dbeaffb --- /dev/null +++ b/src/Covenant.Ui/Logic/PolicyRoutes.cs @@ -0,0 +1,266 @@ +using System.Globalization; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// Why a configured target is or is not usable, judged from the configuration only (the same structural +/// rules the Host's engine applies: paused, connection known + enabled, model permitted, mode boundary, PII/PHI never +/// cloud). Availability (health) is a separate fact; the policy simulator is the authority for a specific request. +public sealed record TargetState(PolicyTargetDto Target, string Key, string? Boundary, string? ExcludedReason) +{ + public bool Eligible => ExcludedReason is null; +} + +/// An option in the "add target" list: only enabled connections' permitted models; cloud models are not +/// offered to PII/PHI policies or in local-only mode (the reason is shown instead). +public sealed record TargetOption(string ConnectionId, string ModelId, string Label, string? Boundary, string? DisabledReason) +{ + public string Value => ConnectionId + "/" + ModelId; +} + +/// Wording for policies (spec §5 Policies): definite effective state, never "may use". +public static class PolicyText +{ + public const string SensitiveNeverCloud = "PII/PHI never route to cloud destinations."; + + public static string ClassificationLabel(string? c) => (c ?? "").Trim().ToLowerInvariant() switch + { + "public" => "Public", + "internal" => "Internal", + "pii" => "PII", + "phi" => "PHI", + "" => "Not reported", + _ => c!.Trim(), + }; + + public static int ClassificationOrder(string? c) => (c ?? "").Trim().ToLowerInvariant() switch + { + "public" => 0, "internal" => 1, "pii" => 2, "phi" => 3, _ => 9, + }; + + public static bool IsSensitive(string? c) => (c ?? "").Trim().ToLowerInvariant() is "pii" or "phi"; + + public static bool CoversSensitive(PolicyDto p) => p.Classifications.Any(IsSensitive); + + /// "Fixed + fallback" or "Length-based heuristic (threshold 400 tokens)". + public static string StrategyName(PolicyDto p) + => IsLengthHeuristic(p) + ? "Length-based heuristic (threshold " + (p.ThresholdTokens ?? 400).ToString("N0", CultureInfo.InvariantCulture) + " tokens)" + : "Fixed + fallback"; + + public static bool IsLengthHeuristic(PolicyDto p) => string.Equals(p.Strategy, "length-heuristic", StringComparison.OrdinalIgnoreCase) + || string.Equals(p.Strategy, "LengthHeuristic", StringComparison.OrdinalIgnoreCase); + + /// "Public", "PII + PHI", "Internal · profile internal-docs". + public static string Applicability(PolicyDto p) + { + var cls = p.Classifications.Count == 0 + ? "No classification" + : string.Join(" + ", p.Classifications.OrderBy(ClassificationOrder).Select(ClassificationLabel)); + return p.Profiles.Count == 0 ? cls : cls + " · profile " + string.Join(", ", p.Profiles); + } + + /// "Active", "Paused — refuses its traffic", "Disabled — not evaluated". + public static string StateText(PolicyDto p) + => !p.Enabled ? "Disabled — not evaluated" : p.Paused ? "Paused — refuses its traffic" : "Active"; + + public static string StateKind(PolicyDto p) => !p.Enabled ? "unknown" : p.Paused ? "paused" : "served"; + + public const string PausedPolicyExplained = + "A paused policy refuses the traffic it matches; it never falls through to a less specific policy."; + public const string PausedRouteExplained = + "A paused route is skipped; the next approved target in order serves instead. If every target is paused, the request is refused."; + + public static bool IsBoundary(string? boundary, string expected) => string.Equals(ComposerRules.BoundaryLabel(boundary), expected, StringComparison.Ordinal); +} + +/// Effective routes and the editable target list. +public static class PolicyRoutes +{ + public static string Key(PolicyTargetDto t) => t.ConnectionId + "/" + t.ModelId; + + public static bool IsLocalOnly(string? mode) + { + var m = (mode ?? "").Trim().ToLowerInvariant().Replace("-", "", StringComparison.Ordinal).Replace("_", "", StringComparison.Ordinal); + return m is "localonly"; + } + + public static bool IsLegacy(string? mode) + { + var m = (mode ?? "").Trim().ToLowerInvariant().Replace("-", "", StringComparison.Ordinal).Replace("_", "", StringComparison.Ordinal); + return m is "legacycloud" or "cloud"; + } + + /// The configured target list with each target's structural eligibility. + public static IReadOnlyList Targets(PolicyDto p, CovenantConfigDto cfg) + { + var list = new List(p.Targets.Count); + foreach (var t in p.Targets) + { + var conn = cfg.Connections.FirstOrDefault(c => string.Equals(c.Id, t.ConnectionId, StringComparison.Ordinal)); + var boundary = conn is null ? null : ComposerRules.BoundaryLabel(conn.Boundary); + string? why = null; + if (t.Paused) why = "route paused — skipped"; + else if (conn is null) why = "connection '" + t.ConnectionId + "' is not configured"; + else if (!conn.Enabled) why = "connection '" + conn.Id + "' is disabled"; + else if (!conn.Models.Any(m => string.Equals(m.ModelId, t.ModelId, StringComparison.Ordinal))) why = "model not permitted on '" + conn.Id + "'"; + else if (boundary == "Cloud" && IsLocalOnly(cfg.Mode)) why = "cloud destination in Local-only mode"; + else if (boundary == "Cloud" && PolicyText.CoversSensitive(p)) why = "cloud destination for PII/PHI — never eligible"; + list.Add(new TargetState(t, Key(t), boundary, why)); + } + return list; + } + + /// The definite effective state line, e.g. "Public → openai/gpt-4o-mini · fallback: ollama/qwen2.5-coder:7b", + /// "PII + PHI → refused (policy paused)", "Internal → ≤ 400 tokens: ollama/qwen · above: openai/gpt-x". + public static string SummaryLine(PolicyDto p, CovenantConfigDto cfg) + { + var scope = PolicyText.Applicability(p); + if (!p.Enabled) return scope + " → not evaluated (policy disabled)"; + if (p.Paused) return scope + " → refused (policy paused)"; + var eligible = Targets(p, cfg).Where(t => t.Eligible).Select(t => t.Key).ToList(); + if (eligible.Count == 0) return scope + " → refused (no eligible target)"; + if (PolicyText.IsLengthHeuristic(p) && eligible.Count > 1) + { + var n = (p.ThresholdTokens ?? 400).ToString("N0", CultureInfo.InvariantCulture); + var rest = eligible.Skip(1).Take(eligible.Count - 2).ToList(); + var line = scope + " → ≤ " + n + " tokens: " + eligible[0] + " · above: " + eligible[^1]; + return rest.Count == 0 ? line : line + " · fallback: " + string.Join(", ", rest); + } + return eligible.Count == 1 + ? scope + " → " + eligible[0] + " · no fallback" + : scope + " → " + eligible[0] + " · fallback: " + string.Join(", ", eligible.Skip(1)); + } + + /// Why matching requests are refused, for the detail panel (never on the summary line). + public static IReadOnlyList RefusalConditions(PolicyDto p, CovenantConfigDto cfg) + { + var list = new List(); + if (!p.Enabled) list.Add("The policy is disabled: it is not evaluated, so its traffic falls to another matching policy or is refused when none matches."); + if (p.Paused) list.Add("The policy is paused: every request it matches is refused."); + foreach (var t in Targets(p, cfg).Where(t => !t.Eligible)) + list.Add(t.Key + ": " + t.ExcludedReason + "."); + if (Targets(p, cfg).All(t => !t.Eligible)) list.Add("No eligible target remains: matching requests are refused (never redirected)."); + list.Add("A requested model outside the eligible targets is refused; an override pins one target (no fallback)."); + list.Add("Fallback happens only for the configured transient failures, before any content was streamed, within the attempt and deadline bounds."); + if (PolicyText.CoversSensitive(p)) list.Add(PolicyText.SensitiveNeverCloud); + return list; + } + + /// Targets that may be added to : enabled connections' permitted models not already + /// listed. Cloud models carry a disabled reason for PII/PHI policies and in Local-only mode. + public static IReadOnlyList Options(PolicyDto p, CovenantConfigDto cfg) + { + var listed = new HashSet(p.Targets.Select(Key), StringComparer.Ordinal); + var options = new List(); + foreach (var c in cfg.Connections) + { + if (!c.Enabled) continue; + var boundary = ComposerRules.BoundaryLabel(c.Boundary); + foreach (var m in c.Models) + { + var key = c.Id + "/" + m.ModelId; + if (listed.Contains(key)) continue; + string? why = null; + if (boundary == "Cloud" && PolicyText.CoversSensitive(p)) why = PolicyText.SensitiveNeverCloud; + else if (boundary == "Cloud" && IsLocalOnly(cfg.Mode)) why = "Cloud destinations cannot execute in Local-only mode."; + options.Add(new TargetOption(c.Id, m.ModelId, key + " · " + (boundary ?? "boundary not reported"), boundary, why)); + } + } + return options; + } + + /// Moves the target at one place earlier (higher precedence). False at the top. + public static bool MoveUp(List targets, int index) + { + if (index <= 0 || index >= targets.Count) return false; + (targets[index - 1], targets[index]) = (targets[index], targets[index - 1]); + return true; + } + + /// Moves the target at one place later. False at the bottom. + public static bool MoveDown(List targets, int index) + { + if (index < 0 || index >= targets.Count - 1) return false; + (targets[index + 1], targets[index]) = (targets[index], targets[index + 1]); + return true; + } + + /// "Primary" for the first target, "Fallback 1", "Fallback 2" … after it. + public static string RoleLabel(int index) => index == 0 ? "Primary" : "Fallback " + index.ToString(CultureInfo.InvariantCulture); +} + +/// The "Move to Hybrid defaults" DRAFT action for imported legacy rules (spec §3 default demonstration +/// policy): Public → an enabled, priced cloud model with the local model as approved fallback; Internal, PII and +/// PHI → the local model only. Produces a candidate for the impact preview — it applies nothing. +public static class HybridDefaults +{ + public sealed record Plan(string? Problem, string? LocalTarget, string? CloudTarget); + + public static Plan Choose(CovenantConfigDto cfg) + { + var local = FirstModel(cfg, "Local", requirePrice: false); + var cloud = FirstModel(cfg, "Cloud", requirePrice: true); + if (local is null) + return new Plan("Hybrid defaults need an enabled Local connection with at least one model (add one under Models & connections).", null, cloud); + return new Plan(null, local, cloud); + } + + /// Rewrites : mode hybrid, policies replaced by the defaults. Returns the problem + /// text (draft untouched) when no local model is configured. + public static string? ApplyTo(CovenantConfigDto draft) + { + var plan = Choose(draft); + if (plan.Problem is not null || plan.LocalTarget is null) return plan.Problem ?? "No local model."; + var local = Split(plan.LocalTarget); + var publicTargets = new List(); + if (plan.CloudTarget is { } cloudKey) + { + var cloud = Split(cloudKey); + publicTargets.Add(new PolicyTargetDto { ConnectionId = cloud.Conn, ModelId = cloud.Model }); + } + publicTargets.Add(new PolicyTargetDto { ConnectionId = local.Conn, ModelId = local.Model }); + + draft.Mode = "hybrid"; + draft.Policies = + [ + new PolicyDto + { + Id = "public", Name = "Public: approved cloud model, local fallback", Enabled = true, + Classifications = ["Public"], Targets = publicTargets, Strategy = "fixed", + Explanation = "Public content may use the approved economical cloud model; the local model is the approved fallback.", + }, + new PolicyDto + { + Id = "internal", Name = "Internal: local model", Enabled = true, + Classifications = ["Internal"], Targets = [new PolicyTargetDto { ConnectionId = local.Conn, ModelId = local.Model }], Strategy = "fixed", + Explanation = "Internal content stays on the approved local model.", + }, + new PolicyDto + { + Id = "sensitive", Name = "PII/PHI: local only", Enabled = true, + Classifications = ["Pii", "Phi"], Targets = [new PolicyTargetDto { ConnectionId = local.Conn, ModelId = local.Model }], Strategy = "fixed", + Explanation = PolicyText.SensitiveNeverCloud, + }, + ]; + return null; + } + + private static string? FirstModel(CovenantConfigDto cfg, string boundary, bool requirePrice) + { + foreach (var c in cfg.Connections) + { + if (!c.Enabled || ComposerRules.BoundaryLabel(c.Boundary) != boundary) continue; + foreach (var m in c.Models) + if (!requirePrice || (m.Price is { InputPer1M: not null, OutputPer1M: not null })) + return c.Id + "/" + m.ModelId; + } + return null; + } + + private static (string Conn, string Model) Split(string key) + { + int slash = key.IndexOf('/'); + return (key[..slash], key[(slash + 1)..]); + } +} diff --git a/src/Covenant.Ui/Logic/RequestFilter.cs b/src/Covenant.Ui/Logic/RequestFilter.cs index e63f476..9d2739f 100644 --- a/src/Covenant.Ui/Logic/RequestFilter.cs +++ b/src/Covenant.Ui/Logic/RequestFilter.cs @@ -14,12 +14,14 @@ public sealed record RequestFilterCriteria /// Matches the selected, attempted or served model (exact, case-insensitive). public string? Model { get; init; } public string? Team { get; init; } + /// Audit v3 ApplicationId (exact, case-insensitive). Legacy records without it never match a set filter. + public string? Application { get; init; } /// Substring of the request id (== correlation id), case-insensitive. public string? IdSearch { get; init; } public TimeWindow Window { get; init; } = TimeWindow.All; public bool IsActive => Outcome is not null || !string.IsNullOrWhiteSpace(Model) || !string.IsNullOrWhiteSpace(Team) - || !string.IsNullOrWhiteSpace(IdSearch) || Window != TimeWindow.All; + || !string.IsNullOrWhiteSpace(Application) || !string.IsNullOrWhiteSpace(IdSearch) || Window != TimeWindow.All; } public static class RequestFilter @@ -44,6 +46,8 @@ public static bool Matches(AuditEntryView r, RequestFilterCriteria c, DateTimeOf if (!string.IsNullOrWhiteSpace(c.Team) && !Same(r.Tags.Team, c.Team.Trim())) return false; + if (!string.IsNullOrWhiteSpace(c.Application) && !Same(r.ApplicationId, c.Application.Trim())) return false; + if (!string.IsNullOrWhiteSpace(c.IdSearch)) { var q = c.IdSearch.Trim(); @@ -69,7 +73,7 @@ public static bool Matches(AuditEntryView r, RequestFilterCriteria c, DateTimeOf TimeWindow.Last15Minutes => "Last 15 minutes", TimeWindow.LastHour => "Last hour", TimeWindow.Last24Hours => "Last 24 hours", - _ => "Whole snapshot", + _ => "All loaded records", }; /// Distinct non-empty model ids (selected/attempted/served) present in the snapshot, sorted. @@ -93,6 +97,14 @@ public static IReadOnlyList Teams(IEnumerable items) return [.. set]; } + public static IReadOnlyList Applications(IEnumerable items) + { + var set = new SortedSet(StringComparer.OrdinalIgnoreCase); + foreach (var r in items) + if (!string.IsNullOrWhiteSpace(r.ApplicationId)) set.Add(r.ApplicationId); + return [.. set]; + } + public static IReadOnlyList Outcomes(IEnumerable items) { var set = new SortedSet(); diff --git a/src/Covenant.Ui/Logic/SegmentScope.cs b/src/Covenant.Ui/Logic/SegmentScope.cs new file mode 100644 index 0000000..905eba5 --- /dev/null +++ b/src/Covenant.Ui/Logic/SegmentScope.cs @@ -0,0 +1,79 @@ +using System.Globalization; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// Scope wording for request lists (spec §5 Requests): which audit segment a list covers, and that +/// filtering applies only to what was loaded — never "all history". +public static class SegmentScope +{ + public const string CurrentId = "current"; + + /// Explicit flag first; else id "current"; else the first row the Host listed. + public static bool IsCurrent(AuditSegmentDto seg, IReadOnlyList? all = null) + { + if (seg.Current is { } flag) return flag; + if (string.Equals(seg.Id, CurrentId, StringComparison.OrdinalIgnoreCase)) return true; + if (all is null || all.Count == 0 || all.Any(s => s.Current == true || string.Equals(s.Id, CurrentId, StringComparison.OrdinalIgnoreCase))) + return false; + return ReferenceEquals(all[0], seg); + } + + /// "Current segment · since 2026-10-16 09:00:00 UTC" or "Archived segment 2026-10-01 · read-only". + public static string Label(AuditSegmentDto seg, bool current) + { + if (current) return "Current segment" + (seg.FirstUtc is { } f ? " · since " + Utc(f) : ""); + var name = string.IsNullOrWhiteSpace(seg.Label) ? seg.Id : seg.Label!; + return "Archived segment " + name + " · read-only"; + } + + /// Selector option text with the entry count when known. + public static string Option(AuditSegmentDto seg, bool current) + { + var label = current ? "Current segment" : "Archived · " + (string.IsNullOrWhiteSpace(seg.Label) ? seg.Id : seg.Label!); + return seg.Entries is { } n ? label + " (" + n.ToString("N0", CultureInfo.InvariantCulture) + " records)" : label; + } + + /// The coverage sentence above the table. + public static string Coverage(string scopeLabel, int loaded, int? segmentEntries, bool moreAvailable, bool filtersActive) + { + var n = loaded.ToString("N0", CultureInfo.InvariantCulture); + var of = segmentEntries is { } total && total > loaded ? " of " + total.ToString("N0", CultureInfo.InvariantCulture) : ""; + var more = moreAvailable ? " Older records: use “Load older”." : loaded > 0 && segmentEntries is { } t2 && t2 > loaded ? " Older records are not reachable from this Host (no cursor)." : ""; + var filter = filtersActive ? " Filters apply only to these loaded records, not to the whole segment or other segments." : ""; + return scopeLabel + ": " + n + of + " records loaded, newest first." + more + filter; + } + + private static string Utc(DateTimeOffset t) => t.UtcDateTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) + " UTC"; +} + +public enum EvidenceCompletenessState { Pending, Unavailable, Recorded, Verified, Unverifiable } + +/// Evidence completeness for one request (spec §4.3/§5 Audit): Pending while the async audit write may +/// still land, Unavailable after the bounded wait, Verified only when the record exists AND its segment's chain +/// verified. A record in a segment whose chain fails is "Unverifiable" — never shown as verified. Integrity is +/// about the record, never about answer quality. +public static class EvidenceCompleteness +{ + public static EvidenceCompletenessState State(bool recordFound, bool? segmentChainValid, bool stillWithinPendingWindow) + { + if (!recordFound) return stillWithinPendingWindow ? EvidenceCompletenessState.Pending : EvidenceCompletenessState.Unavailable; + return segmentChainValid switch + { + true => EvidenceCompletenessState.Verified, + false => EvidenceCompletenessState.Unverifiable, + null => EvidenceCompletenessState.Recorded, + }; + } + + public static (string Label, string Tone) Text(EvidenceCompletenessState s) => s switch + { + EvidenceCompletenessState.Pending => ("Evidence pending — audit write in progress", "hollow"), + EvidenceCompletenessState.Unavailable => ("Evidence unavailable — not found after the bounded wait", "warn"), + EvidenceCompletenessState.Recorded => ("Recorded — chain verification not run", "hollow"), + EvidenceCompletenessState.Verified => ("Audit integrity verified (record present, chain consistent)", "ok"), + _ => ("Recorded, but the segment's chain verification FAILS", "bad"), + }; + + public const string QualityDisclaimer = "Integrity says the record is present and unaltered in the chain. It says nothing about the quality or correctness of the model's answer."; +} diff --git a/src/Covenant.Ui/Models/ConfigContracts.cs b/src/Covenant.Ui/Models/ConfigContracts.cs index 5f10c39..f5f240b 100644 --- a/src/Covenant.Ui/Models/ConfigContracts.cs +++ b/src/Covenant.Ui/Models/ConfigContracts.cs @@ -178,6 +178,7 @@ public sealed class ConfigImpactRowDto [JsonPropertyName("profile")] public string? Profile { get; set; } [JsonPropertyName("before")] public string? Before { get; set; } [JsonPropertyName("after")] public string? After { get; set; } + [JsonPropertyName("changed")] public bool Changed { get; set; } } public sealed class ConfigImpactDto @@ -192,6 +193,7 @@ public sealed class ConfigImpactDto public sealed class ConfigValidationResultDto { [JsonPropertyName("valid")] public bool Valid { get; set; } + [JsonPropertyName("active_version")] public int? ActiveVersion { get; set; } [JsonPropertyName("errors")] public List Errors { get; set; } = []; [JsonPropertyName("warnings")] public List Warnings { get; set; } = []; [JsonPropertyName("impact")] public ConfigImpactDto? Impact { get; set; } @@ -209,6 +211,16 @@ public sealed class ConfigPutResponseDto [JsonPropertyName("etag")] public string? Etag { get; set; } } +/// Error body of /admin/config* (400/404/412/422/428): active_version on 412/422/428, field issues on 422. +public sealed class ConfigErrorResponseDto +{ + [JsonPropertyName("error")] public string? Error { get; set; } + [JsonPropertyName("reason")] public string? Reason { get; set; } + [JsonPropertyName("active_version")] public int? ActiveVersion { get; set; } + [JsonPropertyName("errors")] public List? Errors { get; set; } + [JsonPropertyName("warnings")] public List? Warnings { get; set; } +} + public sealed class ConfigVersionDto { [JsonPropertyName("version")] public int Version { get; set; } @@ -287,6 +299,8 @@ public sealed class BudgetStateDto [JsonPropertyName("scope")] public string Scope { get; set; } = ""; [JsonPropertyName("period")] public string? Period { get; set; } [JsonPropertyName("period_id")] public string? PeriodId { get; set; } + [JsonPropertyName("period_start_utc")] public DateTimeOffset? PeriodStartUtc { get; set; } + [JsonPropertyName("period_end_utc")] public DateTimeOffset? PeriodEndUtc { get; set; } [JsonPropertyName("cap_usd")] public decimal CapUsd { get; set; } [JsonPropertyName("spent_usd")] public decimal SpentUsd { get; set; } [JsonPropertyName("reserved_usd")] public decimal ReservedUsd { get; set; } @@ -303,16 +317,24 @@ public sealed class SimulateRequestDto [JsonPropertyName("profile_id")] public string? ProfileId { get; set; } [JsonPropertyName("prompt")] public string Prompt { get; set; } = ""; [JsonPropertyName("model")] public string? Model { get; set; } + /// Optional unsaved candidate to simulate against (validated by the Host, never applied). + [JsonPropertyName("config")] public CovenantConfigDto? Config { get; set; } } public sealed class SimulateEligibleDto { [JsonPropertyName("target")] public string? Target { get; set; } + [JsonPropertyName("boundary")] public string? Boundary { get; set; } [JsonPropertyName("excluded_reason")] public string? ExcludedReason { get; set; } } public sealed class SimulateResponseDto { + /// Always true from the Host: no provider call, no audit record, no spend or reservation. + [JsonPropertyName("dry_run")] public bool DryRun { get; set; } + [JsonPropertyName("config_version")] public int? ConfigVersion { get; set; } + [JsonPropertyName("application_id")] public string? ApplicationId { get; set; } + [JsonPropertyName("profile")] public string? Profile { get; set; } [JsonPropertyName("classification")] public string? Classification { get; set; } [JsonPropertyName("baseline")] public string? Baseline { get; set; } [JsonPropertyName("detected_signal")] public string? DetectedSignal { get; set; } @@ -323,4 +345,38 @@ public sealed class SimulateResponseDto [JsonPropertyName("primary")] public string? Primary { get; set; } [JsonPropertyName("fallbacks")] public List Fallbacks { get; set; } = []; [JsonPropertyName("reason")] public string? Reason { get; set; } + [JsonPropertyName("explanation")] public string? Explanation { get; set; } +} + +// ---- Budget drill-down and audit archive (ADR-0014, spec §5) — integration pending on the backend ---- + +/// One settled contribution to a budget (GET /admin/budgets/{id}/requests → {budget_id, scope, period_id, +/// items:[{request_id, attempt_id, kind, amount_usd, ts_utc, overrun}]}). Parsed leniently by Logic/BudgetRequests +/// (also a bare array and a few alternative field names) so a naming difference degrades to "Not reported". +public sealed class BudgetRequestDto +{ + public string RequestId { get; set; } = ""; + public string? AttemptId { get; set; } + public decimal? AmountUsd { get; set; } + public DateTimeOffset? TimestampUtc { get; set; } + public string? Scope { get; set; } + /// settle | settle-recovered | legacy-import. + public string? Kind { get; set; } + /// Reported charge exceeded the reservation (settled in full, never truncated). + public bool Overrun { get; set; } +} + +/// GET /admin/audit/segments row: the current segment plus archived siblings (ids only, never paths). +public sealed class AuditSegmentDto +{ + [JsonPropertyName("id")] public string Id { get; set; } = ""; + [JsonPropertyName("label")] public string? Label { get; set; } + [JsonPropertyName("entries")] public int? Entries { get; set; } + [JsonPropertyName("first_utc")] public DateTimeOffset? FirstUtc { get; set; } + [JsonPropertyName("last_utc")] public DateTimeOffset? LastUtc { get; set; } + [JsonPropertyName("chain_valid")] public bool? ChainValid { get; set; } + [JsonPropertyName("events")] public int? Events { get; set; } + [JsonPropertyName("archived_utc")] public DateTimeOffset? ArchivedUtc { get; set; } + /// Optional explicit flag; when absent the console treats id "current" (else the first row) as current. + [JsonPropertyName("current")] public bool? Current { get; set; } } diff --git a/src/Covenant.Ui/Models/Contracts.cs b/src/Covenant.Ui/Models/Contracts.cs index d9c3be2..d24d00c 100644 --- a/src/Covenant.Ui/Models/Contracts.cs +++ b/src/Covenant.Ui/Models/Contracts.cs @@ -29,6 +29,8 @@ public sealed class StatusReport [JsonPropertyName("prompt_preview_chars")] public int? PromptPreviewChars { get; set; } [JsonPropertyName("anchor")] public AnchorStatus? Anchor { get; set; } [JsonPropertyName("version")] public string? Version { get; set; } + // v2: the active configuration version every new request binds to. + [JsonPropertyName("config_version")] public int? ConfigVersion { get; set; } } public sealed class AnchorStatus @@ -172,11 +174,17 @@ public sealed class RequestsResponse { [JsonPropertyName("segment")] public SegmentInfo Segment { get; set; } = new(); [JsonPropertyName("items")] public List Items { get; set; } = []; + /// Opaque newest-first position of the next (older) page; null/absent = no older page from this Host. + [JsonPropertyName("next_cursor")] public string? NextCursor { get; set; } } public sealed class SegmentInfo { + /// Segment id (GET /admin/audit/segments). Required to confirm an archived-segment answer. + [JsonPropertyName("id")] public string? Id { get; set; } + [JsonPropertyName("label")] public string? Label { get; set; } [JsonPropertyName("path")] public string? Path { get; set; } + [JsonPropertyName("events")] public int? Events { get; set; } [JsonPropertyName("entries")] public int Entries { get; set; } [JsonPropertyName("chain_valid")] public bool ChainValid { get; set; } [JsonPropertyName("first_utc")] public DateTimeOffset? FirstUtc { get; set; } @@ -241,6 +249,9 @@ public sealed class AuditAttemptView [JsonPropertyName("DurationMs")] public double? DurationMs { get; set; } [JsonPropertyName("CostUsd")] public decimal? CostUsd { get; set; } [JsonPropertyName("CostBasis")] public string? CostBasis { get; set; } + // T04/T06 additive: the attempt's reservation and whether the reported charge exceeded it (settled in full). + [JsonPropertyName("ReservedUsd")] public decimal? ReservedUsd { get; set; } + [JsonPropertyName("Overrun")] public bool? Overrun { get; set; } } public sealed class AttributionTagsView @@ -266,6 +277,38 @@ public sealed class CatalogResponse [JsonPropertyName("models")] public List Models { get; set; } = []; [JsonPropertyName("local")] public LocalRouteInfo? Local { get; set; } [JsonPropertyName("probe_allow_list")] public List? ProbeAllowList { get; set; } + // v2 (ADR-0011): connection-scoped view of the active configuration. + [JsonPropertyName("config_version")] public int? ConfigVersion { get; set; } + [JsonPropertyName("connections")] public List? Connections { get; set; } + [JsonPropertyName("egress_allow_list")] public List? EgressAllowList { get; set; } +} + +/// Catalog view of one configured connection (Host CatalogConnection): registration and observed health, +/// never credentials. Model health is observed from real governed calls (keyed connection:model). +public sealed class CatalogConnectionDto +{ + [JsonPropertyName("id")] public string Id { get; set; } = ""; + [JsonPropertyName("display_name")] public string? DisplayName { get; set; } + [JsonPropertyName("kind")] public string? Kind { get; set; } + [JsonPropertyName("boundary")] public string? Boundary { get; set; } + [JsonPropertyName("enabled")] public bool Enabled { get; set; } + [JsonPropertyName("endpoint")] public string? Endpoint { get; set; } + [JsonPropertyName("endpoint_allow_listed")] public bool EndpointAllowListed { get; set; } + [JsonPropertyName("secret_ref")] public string? SecretRef { get; set; } + [JsonPropertyName("secret_available")] public bool? SecretAvailable { get; set; } + [JsonPropertyName("models")] public List Models { get; set; } = []; +} + +public sealed class CatalogConnectionModelDto +{ + [JsonPropertyName("key")] public string? Key { get; set; } + [JsonPropertyName("model_id")] public string ModelId { get; set; } = ""; + [JsonPropertyName("display_name")] public string? DisplayName { get; set; } + [JsonPropertyName("registered")] public bool Registered { get; set; } + [JsonPropertyName("price_basis")] public string? PriceBasis { get; set; } + [JsonPropertyName("in_per_1m")] public decimal? InPer1M { get; set; } + [JsonPropertyName("out_per_1m")] public decimal? OutPer1M { get; set; } + [JsonPropertyName("health")] public ModelHealth? Health { get; set; } } public sealed class CatalogModel @@ -279,6 +322,9 @@ public sealed class CatalogModel [JsonPropertyName("out_per_1m")] public decimal? OutPer1M { get; set; } [JsonPropertyName("endpoint_host")] public string? EndpointHost { get; set; } [JsonPropertyName("health")] public ModelHealth? Health { get; set; } + [JsonPropertyName("connection_id")] public string? ConnectionId { get; set; } + [JsonPropertyName("boundary")] public string? Boundary { get; set; } + [JsonPropertyName("key")] public string? Key { get; set; } } public sealed class ModelHealth @@ -406,4 +452,7 @@ public sealed class StreamFrameDto [JsonSerializable(typeof(List))] [JsonSerializable(typeof(SimulateRequestDto))] [JsonSerializable(typeof(SimulateResponseDto))] +// T08 editors and evidence +[JsonSerializable(typeof(ConfigErrorResponseDto))] +[JsonSerializable(typeof(List))] public partial class UiJsonContext : JsonSerializerContext; diff --git a/src/Covenant.Ui/Pages/Budgets.razor b/src/Covenant.Ui/Pages/Budgets.razor index e703d96..b1b39a2 100644 --- a/src/Covenant.Ui/Pages/Budgets.razor +++ b/src/Covenant.Ui/Pages/Budgets.razor @@ -1,208 +1,449 @@ @page "/budgets" @inject AppState State @inject AdminApi Api +@inject ConfigEditor Editor @implements IDisposable Budgets · Covenant +@* + T08. Budget state per scope from the ledger (GET /admin/budgets, ADR-0014): period + period id, spent, reserved, + remaining, cap, warning state, enforcement. Caps/thresholds/period/enforcement are edited in the configuration draft + (ConfigEditor → Preview impact → Save & apply). Drill-down: GET /admin/budgets/{id}/requests. Amounts via + Logic/Money (significant digits; never $0.00 for a non-zero charge). +*@ +
    - @if (State.LastStatus is not { } s) +
    +
    +

    Budgets

    + Provider spend by scope and UTC period, checked before every paid attempt. Spend lives in the budget ledger — independent of audit segments. +
    + +
    + + + + + + @if (_budgets is null && _loading) { - +
    } - else + else if (_endpointMissing) { - var b = s.Budget; - var f = s.FinOps; - var remaining = b.GlobalCapUsd - b.GlobalSpendUsd; - var pct = Fmt.PercentClamped(b.GlobalSpendUsd, b.GlobalCapUsd); - - if (b.GlobalCapUsd > 0 && b.GlobalSpendUsd >= b.GlobalCapUsd) +
    +
    + This Host has no budget ledger yet (GET /admin/budgets is missing) + Integration pending on the backend. Shown below: the pre-v2 status counters (global and team spend of the current audit segment). Periods, reservations and application scopes are not available on this Host. +
    +
    + @if (State.LastStatus is { } s) { - +
    +

    Pre-v2 counters

    + +
    } - else if (pct >= 80) + } + else if (_budgets is { } budgets) + { + if (budgets.Count == 0) { - + } - -
    -
    -

    Budgets

    - Accounting period: the current audit segment@SegmentSuffix. Spend is rebuilt from the audit log at start; it is not a monthly billing cycle. -
    - Caps managed by configuration; restart required -
    - -
    -

    Global cap

    - - = 80 ? "warn" : "")" role="img" aria-label="@(Fmt.Percent(b.GlobalSpendUsd, b.GlobalCapUsd) + " of the global cap used")"> - - -
    -
    - A threshold, checked before each call -

    Before a provider call, Covenant compares estimated spend recorded so far with the cap and refuses new calls once it is reached. Cache hits are not checked.

    -
    -
    - Not an exact invoice cap -

    Cost is known only after a call returns, so calls already in flight when the cap is reached can still finish — concurrent calls can overshoot it. Your provider’s invoice remains the billing record.

    -
    -
    -

    Ledger is reconstructed from the current audit segment; a pre-call threshold check, not an invoice ceiling.

    -
    - -
    -
    -

    Teams

    - Attribution from the audit record’s team tag -
    - @if (b.Teams.Count == 0) + else + { + if (BudgetText.NoSpendAnywhere(budgets)) { -
    +
    } - else - { +
    +
    +

    Budget state

    + @(_loadedUtc is { } t ? "Read " + Fmt.UtcShort(t) + " UTC from the ledger" : "") +
    - +
    - - - + + + + - + + + - @foreach (var t in b.Teams.OrderByDescending(x => x.SpendUsd)) + @foreach (var b in budgets) { + var row = b; + var warn = BudgetText.Warning(row.Warning); + var pct = BudgetText.MeterPercent(row.SpentUsd, row.ReservedUsd, row.CapUsd); - - - - - + + + + + + + + }
    TeamRecorded spendTeam capScopePeriodSpentReserved RemainingLimits that applyCapStateActions
    @t.Team@Fmt.Usd(t.SpendUsd)@(t.CapUsd is { } cap ? Fmt.UsdTotal(cap) : "None configured")@(t.CapUsd is { } c2 ? (c2 - t.SpendUsd >= 0 ? Fmt.Usd(c2 - t.SpendUsd) : "Exceeded") : "—")@(t.CapUsd is null ? "Global cap only" : "Team cap, then global cap")@BudgetText.Scope(row.Scope)
    @row.Id
    @BudgetText.Period(row.Period, row.PeriodId)@Money.Usd(row.SpentUsd)@Money.Usd(row.ReservedUsd)@BudgetText.Remaining(row.RemainingUsd)@Money.Cap(row.CapUsd) + + + @warn.Label + @BudgetText.Enforcement(row.Enforcement) · warn at @BudgetText.Thresholds(row.WarnAt) +
    - } -
    +
    + } + } -
    -

    What counts as spend

    -
      -
    • Estimated provider cost: tokens the provider reports × the configured price for that model. Covenant does not read provider invoices.
    • -
    • Local route: $0 by configured price. Hardware, electricity and operations are excluded, not free.
    • -
    • When a priced model reports no usage, cost is estimated from text length and charged (fail-closed). An unpriced model is charged $0 but counted as unknown — never as a saving.
    • -
    -
    - - @if (_requestsError is not null) - { - Unknown-cost requests: unavailable (@_requestsError) - } - else if (UnknownCostCount is null) + @if (Editing && Editor.Draft is { } draft) + { +
    +
    +

    Edit budgets (draft)

    + Changing a cap never erases spend; lowering it below spend blocks new paid work. Changing a period or id keeps the scope's accrued ledger. +
    +
      + @foreach (var b in draft.Budgets) { - Unknown-cost requests: counting… + var cfgRow = b; + var bi = draft.Budgets.IndexOf(cfgRow); + var path = IssueIndex.Budget(bi); +
    • +
      + @BudgetText.Scope(cfgRow.Scope) + @cfgRow.Id + @if (IsNewBudget(cfgRow)) + { + New in draft + + } +
      +
      +
      + + + +
      +
      + + +
      +
      + + + @if (_thresholdErrors.TryGetValue(bi, out var te)) + { + @te + } + +
      +
      + + +
      +
      + +
    • } - else +
    +
    +
    + + +
    + @if (_newKind != "global") { - Unknown-cost requests: @UnknownCostCount (@_unpriced unknown · @_estimated charged from a text-length estimate, of @_scanned records scanned) +
    + + +
    } +
    -
    - -
    - - @if (_avoidedOpen) + @if (_addError is { } ae) { -
    -

    Baseline assumption: every served request priced on the Host’s configured strong model at configured prices, uncached. An estimate, not a measured saving.

    -
    - - - - - - - -
    SourceEstimateBasis
    Complexity router@Fmt.Usd(f.SavingsRouterUsd)Served by a cheaper permitted cloud model instead of the baseline
    Cache@Fmt.Usd(f.SavingsCacheUsd)@(f.CacheHits == 0 ? "No cache hits in this segment" : $"{Fmt.Int(f.CacheHits)} cache hits priced at the cached model’s rate")
    Local route@Fmt.Usd(f.SavingsLocalUsd)@(f.LocalRequests == 0 ? "No local requests in this segment" : $"{Fmt.Int(f.LocalRequests)} requests, {Fmt.Int(f.LocalTokens)} tokens · provider price delta only; infrastructure cost is not configured")
    -
    -
    + @ae } + Raising or lowering a cap is a configuration activation and is audited with before/after. Hard caps are an estimated bound (reservation from enforced input/output limits), not an invoice ceiling.
    } + +
    +
    +

    Provider charge

    +
      +
    • Provider-reported tokens × configured price for that connection/model. Covenant does not read provider invoices.
    • +
    • Before each attempt a conservative reservation is held; it settles against reported usage (or an explicit estimate) exactly once, and the remainder is released.
    • +
    • An unpriced paid model is not eligible under a hard budget — unknown cost is never counted as $0.
    • +
    +
    +
    +

    Local infrastructure

    +
      +
    • Local models priced “zero marginal” settle $0 provider charge.
    • +
    • Hardware, power and operations are excluded — not free. No infrastructure estimate is configured, so none is shown.
    • +
    +
    +
    +

    Budget period rollover and audit archive are different operations: a budget's period rolls over by UTC date; archiving the audit segment (Settings → Maintenance) never reopens a budget.

    + + + @if (_drill is { } db) + { + @BudgetText.Period(db.Period, db.PeriodId) · settled contributions, newest first. Open a request to see its attempts and evidence. + @if (_drillLoading) + { + + } + + @if (_drillRows is { Count: 0 }) + { + + } + else if (_drillRows is { } rows) + { +
      + @foreach (var r in rows) + { + var req = r; +
    1. + @req.RequestId + @Money.Usd(req.AmountUsd) + @(req.TimestampUtc is { } ts ? Fmt.Utc(ts) : "time not reported")@(req.AttemptId is { Length: > 0 } at ? " · attempt " + at : "")@(req.Kind is { Length: > 0 } k && k != "settle" ? " · " + k : "") + @if (req.Overrun) + { + Reported charge exceeded the reservation — settled in full. + } +
    2. + } +
    + } + } +
    @code { - private static IReadOnlyList GlobalFacts(BudgetStatus b, decimal remaining) => + private List? _budgets; + private bool _loading; + private string? _error; + private bool _endpointMissing; + private DateTimeOffset? _loadedUtc; + private bool _started; + + private BudgetStateDto? _drill; + private bool _drillLoading; + private string? _drillError; + private List? _drillRows; + + private string _newKind = "team"; + private string? _newName; + private string? _addError; + private readonly Dictionary _thresholdErrors = new(); + + private bool Editing => Editor.Editing && Editor.Owner == "budgets"; + + private IReadOnlyList ClaimedPaths => Editing && Editor.Draft is { } d ? Enumerable.Range(0, d.Budgets.Count).Select(IssueIndex.Budget).ToList() : []; + + protected override async Task OnInitializedAsync() + { + State.Changed += OnStateChanged; + Editor.Changed += OnChanged; + await Editor.EnsureLoadedAsync(); + if (State.Connected) await LoadAsync(); + } + + private async Task LoadAsync() + { + if (_loading || !State.Connected) return; + _started = true; + _loading = true; + _error = null; + StateHasChanged(); + try + { + _budgets = await Api.GetBudgetsAsync(); + _endpointMissing = false; + _loadedUtc = DateTimeOffset.UtcNow; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.NotFound) + { + _endpointMissing = true; + _budgets = null; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // ConsoleSession disconnects. + } + catch (Exception ex) + { + _error = ex.Message; // keep the previous rows visible but say they could not be refreshed + } + finally + { + _loading = false; + StateHasChanged(); + } + } + + private static IReadOnlyList LegacyFacts(StatusReport s) => [ - new("Cap", Fmt.UsdTotal(b.GlobalCapUsd), true), - new("Recorded spend", Fmt.Usd(b.GlobalSpendUsd), true), - new("Remaining", remaining >= 0 ? Fmt.Usd(remaining) : "Exceeded by " + Fmt.Usd(-remaining), true), - new("Used", Fmt.Percent(b.GlobalSpendUsd, b.GlobalCapUsd), true), + new("Global cap", Money.Cap(s.Budget.GlobalCapUsd), true), + new("Recorded spend", Money.Usd(s.Budget.GlobalSpendUsd), true), + new("Teams with spend", s.Budget.Teams.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), true), ]; - private bool _avoidedOpen; - private string? _requestsError; - private int? _unpriced; - private int? _estimated; - private int _scanned; - private bool _loadedOnce; + private bool IsNewBudget(BudgetConfigDto b) => Editor.Applied?.Config?.Budgets.All(x => !string.Equals(x.Id, b.Id, StringComparison.Ordinal)) ?? true; + + private void SetPeriod(BudgetConfigDto b, ChangeEventArgs e) + { + b.Period = e.Value?.ToString() is "daily" or "none" ? e.Value!.ToString() : "monthly"; + Editor.Touch(); + } + + private void SetEnforcement(BudgetConfigDto b, ChangeEventArgs e) + { + b.Enforcement = e.Value?.ToString() == "warn-only" ? "warn-only" : "hard"; + Editor.Touch(); + } - private SegmentInfo? Segment { get; set; } - private int? UnknownCostCount => _unpriced is null || _estimated is null ? null : _unpriced + _estimated; - private string SegmentSuffix => Segment is { FirstUtc: { } first } ? ", begun " + Fmt.Utc(first) : ""; + private void SetThresholds(BudgetConfigDto b, int index, ChangeEventArgs e) + { + var parsed = BudgetText.ParseThresholds(e.Value?.ToString()); + if (parsed is null) + { + _thresholdErrors[index] = "Enter percentages between 0 and 100, separated by commas (e.g. 80, 95)."; + return; + } + _thresholdErrors.Remove(index); + b.WarnAt = parsed; + Editor.Touch(); + } - protected override void OnInitialized() => State.Changed += OnChanged; + private void AddBudget() + { + _addError = null; + if (Editor.Draft is not { } d) return; + string scope = _newKind switch + { + "global" => "global", + "application" => "application:" + (_newName ?? "").Trim(), + _ => "team:" + (_newName ?? "").Trim(), + }; + if (d.Budgets.Any(x => string.Equals(x.Scope, scope, StringComparison.OrdinalIgnoreCase))) + { + _addError = "A budget for " + scope + " already exists in the draft."; + return; + } + var seed = scope.Replace(':', '-'); + var id = ConnectionRules.UniqueId(seed, d.Budgets.Select(x => x.Id)); + d.Budgets.Add(new BudgetConfigDto { Id = id, Scope = scope, CapUsd = 0m, Period = "monthly", WarnAt = [0.80m, 0.95m], Enforcement = "hard" }); + _newName = null; + Editor.Touch(); + } - protected override async Task OnParametersSetAsync() + private void RemoveBudget(BudgetConfigDto b) { - if (State.Connected && !_loadedOnce) await LoadRequestsAsync(); + if (Editor.Draft is not { } d) return; + d.Budgets.Remove(b); + _thresholdErrors.Clear(); + Editor.Touch(); } - private async Task LoadRequestsAsync() + private async Task OpenDrillAsync(BudgetStateDto b) { - _loadedOnce = true; + _drill = b; + await LoadDrillAsync(b); + } + + private async Task LoadDrillAsync(BudgetStateDto b) + { + _drillLoading = true; + _drillError = null; + _drillRows = null; + StateHasChanged(); try { - var r = await Api.GetRequestsAsync(1000); - Segment = r.Segment; - _scanned = r.Items.Count; - _unpriced = r.Items.Count(i => i.CostBasis is "unpriced" or "unknown_failed_call"); - _estimated = r.Items.Count(i => i.CostBasis is "estimated_from_text" or "estimated_failed_call"); - _requestsError = null; + var json = await Api.GetBudgetRequestsJsonAsync(b.Id); + if (!ReferenceEquals(_drill, b)) return; + _drillRows = BudgetRequests.Parse(json); + if (_drillRows is null) _drillError = "The Host answered in an unrecognised shape — nothing is shown rather than a guess."; } catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.NotFound) { - _requestsError = "requests endpoint not available on this Host"; + _drillError = "Contributing requests are not available on this Host (GET /admin/budgets/{id}/requests missing)."; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // ConsoleSession disconnects. } catch (Exception ex) { - _requestsError = ex.Message; + _drillError = ex.Message; + } + finally + { + _drillLoading = false; } - StateHasChanged(); } - private void OnChanged() + private void OnDrillOpenChanged(bool open) { - if (State.Connected && !_loadedOnce) _ = InvokeAsync(LoadRequestsAsync); - _ = InvokeAsync(StateHasChanged); + if (open) return; + _drill = null; + _drillRows = null; + _drillError = null; } - public void Dispose() => State.Changed -= OnChanged; + private void OnStateChanged() + { + _ = InvokeAsync(async () => + { + if (State.Connected && !_started) await LoadAsync(); + StateHasChanged(); + }); + } + + private void OnChanged() => _ = InvokeAsync(StateHasChanged); + + public void Dispose() + { + State.Changed -= OnStateChanged; + Editor.Changed -= OnChanged; + } } diff --git a/src/Covenant.Ui/Pages/Connections.razor b/src/Covenant.Ui/Pages/Connections.razor index e6a82a9..4cdce3e 100644 --- a/src/Covenant.Ui/Pages/Connections.razor +++ b/src/Covenant.Ui/Pages/Connections.razor @@ -2,20 +2,17 @@ @inject AppState State @inject AdminApi Api @inject CatalogState Catalog -@inject ConsoleInferenceApi Inference -@inject WorkspaceConfig Ws -@inject EvidenceTracker Evidence +@inject ConfigEditor Editor @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 runs through POST /admin/playground/requests as an authorized test application (ADR-0012) — - the same governed pipeline as /v1; no application key is ever entered in the console. + T08. Connections from the versioned configuration (GET /admin/config) joined with the catalog's observed health + (GET /admin/catalog). Add / Edit / Disable change the configuration DRAFT; Preview impact → Save & apply activates a + new version (PUT /admin/config, If-Match). Test probes the endpoint host-side (POST /admin/providers/probe). + Secrets are references only. The old "edit a file and restart" wizard is gone. *@
    @@ -23,493 +20,351 @@

    Models & connections

    - Where Covenant sends calls. Registration, permission and observed reachability are separate facts. + Where Covenant may send calls: approved connections and the exact models permitted on each. Permission, health and price are separate facts. +
    +
    + + +
    - Managed by configuration; restart required -
    - @{ var cat = State.Catalog; var localRoute = RouteHealth.LocalRoute(cat, DateTimeOffset.UtcNow); } + - @if (cat is null) + @if (Editor.Current is not { } cfg) { - if (State.CatalogError is { } ce) + if (Editor.Loading || (Editor.Applied is null && Editor.LoadError is null)) { - +
    } - else + else if (Editor.EndpointMissing) { - + } } 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) + if (State.CatalogError is { } ce) + { + + } + if (cfg.Connections.Count == 0) + { + + + + + } + else + { +
      + @foreach (var c in cfg.Connections) + { + var conn = c; + var cat = CatalogFor(conn.Id); + var health = HealthFor(conn, cat); + var changed = ChangedInDraft(conn); + var routed = RoutedBy(cfg, conn.Id); +
    • +
      + +
      + @(conn.DisplayName ?? conn.Id) + @conn.Id · @ConnectionRules.KindLabel(conn.Kind) +
      + + @(conn.Enabled ? "Enabled" : "Disabled") + @if (changed is { } ch) { -
    - - - - - - - - + @ch } - -
    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) +
    +
    +
    Endpoint
    +
    @(conn.Endpoint ?? "Provider default") + @if (cat is { EndpointAllowListed: false }) + { + · not on the startup egress allow-list + } +
    +
    Permitted models
    +
    + @if (conn.Models.Count == 0) + { + None — this connection serves nothing + } + else + { +
      + @foreach (var m in conn.Models) + { +
    • @m.ModelId · @Money.Price(m.Price?.InputPer1M, m.Price?.OutputPer1M)@(m.Price?.Basis is { Length: > 0 } b ? " (" + b + ")" : "")@RegisteredNote(cat, m.ModelId)
    • + } +
    + } +
    + @if (conn.SecretRef is { } sr) { -
  • @t
  • +
    Credential
    +
    @sr · @SecretText(sr, cat)
    } - - } - } - - -
    - 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 through the full governed pipeline as the chosen test application, requesting model @(_tag ?? "—") — never directly to Ollama. The prompt carries the published sample SSN so it is classified sensitive and must stay local. -
    - - - @if (Ws.ApplicationsError is { } wae) - { - @wae - } -
    -
    - -
    - @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) +
    Used by
    +
    @(routed.Count == 0 ? "No policy routes" : string.Join(", ", routed))
    +
    Health
    +
    + @health.Summary +
    + Timestamps +
    + @foreach (var (label, value) in health.Details) + { +
    @label
    @value
    + } +
    + A probe shows the endpoint answered; only a governed call shows a model served. GET /v1/models is not a health check. +
    +
    +
    +
    + + @if (conn.Endpoint is { Length: > 0 }) + { + + } + else + { + Test: provider default endpoints are not probed — run a governed Public request in the Playground. + } + +
    + @if (_testErrors.TryGetValue(conn.Id, out var terr)) { -
    Selected / attempted / served
    @ModelFacts.Selected(trec) · @ModelFacts.Attempted(trec) · @ModelFacts.Served(trec)
    -
    Classification
    @ModelFacts.Classification(trec)
    + Test failed to run: @terr } - else + @if (_probes.TryGetValue(conn.Id, out var pr) && !pr.Probe.Allowed) { -
    Evidence
    @EvidenceText
    + Probe refused: @(ConnectionLogic.Authority(conn.Endpoint) ?? "this destination") is not on the probe allow-list (Providers:ProbeAllowList; restart required). } -
    - @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. -
    + + Disable/Enable change the draft only; preview the impact and save to apply. Disabled connections are never eligible for any route. + } + +
    + Using Open WebUI or another client + Point the client at @CovenantV1 with a Covenant application key (never the admin token). Pointing it at Ollama directly bypasses Covenant: no policy, budget, pause or audit. +
    + } + + + @if (_form is { } form) + { + + @if (Editor.LastOutcome is { Succeeded: false } lo && lo.Kind != EditOutcomeKind.Stale) + { + + } + @if (Editor.Conflict is { } conflict) + { + + } + } + + + + @if (_toggleTarget is { } tt) + { +

    + @(tt.Enabled + ? "Disabling removes every model on this connection from eligibility. Routes that name it fall to their next approved target, or are refused when none remains. " + : "Enabling makes this connection's permitted models eligible again for the routes that name them. ") + This changes the draft only; you will preview the impact before anything is applied. +

    +
    + + +
    + } +
    @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? _testApp; - - 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 ConnectionForm? _form; + private int? _draftIndex; + private string? _openerId; + private ConnectionDto? _toggleTarget; + private readonly HashSet _testing = new(StringComparer.Ordinal); + private readonly Dictionary _testErrors = new(StringComparer.Ordinal); + private readonly Dictionary _probes = new(StringComparer.Ordinal); - private string CovenantV1 => new Uri(new Uri(Nav.BaseUri).GetLeftPart(UriPartial.Authority)).ToString().TrimEnd('/') + "/v1"; + private bool CanEdit => Editor.Applied is not null && !Editor.Saving && (!Editor.Editing || Editor.Owner == "connections" || !Editor.IsDirty); - 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 IReadOnlyList ClaimedPaths => Editor.Current is { } c ? Enumerable.Range(0, c.Connections.Count).Select(IssueIndex.Connection).ToList() : []; - 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", - }; + private string DrawerTitle => _form is null ? "" : _form.IsNew + ? (_form.IsOllama ? "Add Ollama connection" : "Add cloud provider") + : "Edit " + (_form.DisplayName.Length > 0 ? _form.DisplayName : _form.Id); + + private string CovenantV1 => new Uri(new Uri(Nav.BaseUri).GetLeftPart(UriPartial.Authority)).ToString().TrimEnd('/') + "/v1"; protected override async Task OnInitializedAsync() { State.Changed += OnChanged; - await Ws.EnsureLoadedAsync(); - _testApp = ComposerRules.Applications(Ws.Applications).FirstOrDefault(c => c.Selectable)?.App.Id; + Editor.Changed += OnChanged; + await Editor.EnsureLoadedAsync(); } - private void OnTestApp(ChangeEventArgs e) + private Task RefreshAsync() => Catalog.RefreshAsync(); + + private CatalogConnectionDto? CatalogFor(string id) + => State.Catalog?.Connections?.FirstOrDefault(c => string.Equals(c.Id, id, StringComparison.Ordinal)); + + private ConnectionHealthView HealthFor(ConnectionDto conn, CatalogConnectionDto? cat) { - var id = e.Value?.ToString(); - _testApp = ComposerRules.Find(Ws.Applications, id) is { } a && ComposerRules.WhyNotSelectable(a) is null ? a.Id : null; + var models = cat?.Models.Select(m => m.Health).ToList() ?? new List(); + if (cat is null && State.Catalog is { } legacy) + models = legacy.Models.Where(m => string.Equals(m.ConnectionId ?? m.Adapter, conn.Id, StringComparison.Ordinal)).Select(m => m.Health).ToList(); + ModelHealth? endpointHealth = null; + if (State.Catalog?.Local is { } local && ConnectionLogic.SameEndpoint(local.Endpoint, conn.Endpoint)) endpointHealth = local.EndpointHealth; + _probes.TryGetValue(conn.Id, out var probe); + return ConnectionHealth.Summarize(conn.Enabled, models, probe.Probe, probe.Probe is null ? null : probe.At, endpointHealth, DateTimeOffset.UtcNow); } - 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 RegisteredNote(CatalogConnectionDto? cat, string modelId) + { + var m = cat?.Models.FirstOrDefault(x => string.Equals(x.ModelId, modelId, StringComparison.Ordinal)); + return m is { Registered: false } ? " · no provider client (refused at the provider stage)" : ""; + } - private static string HealthText(ModelHealth? h) + private string SecretText(string secretRef, CatalogConnectionDto? cat) { - 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); + bool? available = cat?.SecretAvailable; + if (available is null && Editor.Applied?.Secrets is { } map && map.TryGetValue(secretRef, out var s)) available = s.Available; + return available switch + { + true => "available on the server (value never shown)", + false => "NOT SET on the server — set " + ConnectionRules.EnvVarFor(secretRef) + " and restart", + null => "availability not reported (checked on preview)", + }; } - private static string PriceText(CatalogModel m) => m.PriceBasis switch + private string? ChangedInDraft(ConnectionDto conn) { - "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", - }; + if (!Editor.Editing || Editor.Applied?.Config is not { } applied) return null; + var before = applied.Connections.FirstOrDefault(c => string.Equals(c.Id, conn.Id, StringComparison.Ordinal)); + if (before is null) return "New in draft"; + return string.Equals(ConfigCopy.Canonical(before), ConfigCopy.Canonical(conn), StringComparison.Ordinal) ? null : "Changed in draft"; + } + + private static List RoutedBy(CovenantConfigDto cfg, string connectionId) + => cfg.Policies.Where(p => p.Targets.Any(t => string.Equals(t.ConnectionId, connectionId, StringComparison.Ordinal))) + .Select(p => (p.Name ?? p.Id) + (p.Enabled ? "" : " (disabled)")) + .ToList(); - private void OnEndpointInput(ChangeEventArgs e) + private IReadOnlyList OtherIds(ConnectionForm form) + => (Editor.Current?.Connections ?? []).Select(c => c.Id) + .Where(id => !string.Equals(id, form.AppliedAsId ?? form.OriginalId, StringComparison.Ordinal)).ToList(); + + private IEnumerable ExistingIds => (Editor.Current?.Connections ?? []).Select(c => c.Id); + + private void AddOllama() { - 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; + _form = ConnectionForm.NewOllama(ExistingIds); + _draftIndex = null; + _openerId = "add-ollama"; } - /// Editing the endpoint invalidates every later DRAFT result. The running configuration is untouched. - private void InvalidateFromProbe() + private void AddCloud() { - _cts?.Cancel(); - _probe = null; - _probeError = null; - _tag = null; - InvalidateFromApplied(); + _form = ConnectionForm.NewCloud("OpenAi", ExistingIds); + _draftIndex = null; + _openerId = "add-cloud"; } - private void InvalidateFromApplied() + private void EditConnection(ConnectionDto conn) { - _appliedChecked = false; - _appliedPass = false; - _appliedMessage = null; - _testResult = null; - _testOutcome = null; - _testEvidence = EvidenceStatus.Idle; + _form = ConnectionForm.FromConnection(conn); + _draftIndex = Editor.Current?.Connections.IndexOf(conn) is int i and >= 0 && Editor.Editing ? i : null; + _openerId = "edit-" + conn.Id; } - private void ChooseTag(string tag) + private void OnDrawerOpenChanged(bool open) { - if (string.Equals(_tag, tag, StringComparison.Ordinal)) return; - _tag = tag; - InvalidateFromApplied(); + if (!open) _form = null; } - private async Task ProbeAsync() + /// Puts the form into the draft and asks the Host for validation + impact. + private async Task PreviewFormAsync() + { + if (_form is not { } form || !Editor.BeginEdit("connections") || Editor.Draft is not { } draft) return; + _draftIndex = form.ApplyTo(draft); + Editor.Touch(); + await Editor.ValidateAsync(); + } + + private async Task SaveFormAsync() + { + var outcome = await Editor.SaveAsync(); + if (outcome.Succeeded) _form = null; + } + + private void ToggleEnabled(ConnectionDto conn) => _toggleTarget = conn; + + private async Task ConfirmToggleAsync() { - if (EndpointProblem is not null || _probing) return; - var endpoint = _endpoint.Trim(); - _probing = true; - _probeError = null; - _invalidated = false; - _probe = null; - _tag = null; - InvalidateFromApplied(); + if (_toggleTarget is not { } target) return; + _toggleTarget = null; + if (!Editor.BeginEdit("connections") || Editor.Draft is not { } draft) return; + var inDraft = draft.Connections.FirstOrDefault(c => string.Equals(c.Id, target.Id, StringComparison.Ordinal)); + if (inDraft is null) return; + inDraft.Enabled = !inDraft.Enabled; + Editor.Touch(); + await Editor.ValidateAsync(); + } + + private async Task TestAsync(ConnectionDto conn) + { + if (conn.Endpoint is not { Length: > 0 } endpoint || !_testing.Add(conn.Id)) return; + _testErrors.Remove(conn.Id); 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; - } + RecordProbe(conn.Id, result); } catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) { - // handled by ConsoleSession + // ConsoleSession disconnects. } catch (Exception ex) { - _probeError = ex.Message; + _testErrors[conn.Id] = ex.Message; } finally { - _probing = false; + _testing.Remove(conn.Id); } - // 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 async Task RunTestAsync() - { - if (!AppliedPassed || _testing || _tag is not { } tag || _testApp is not { } app) return; - _testing = true; - _testResult = null; - _testOutcome = null; - _testEvidence = EvidenceStatus.Idle; - _cts?.Cancel(); - var cts = new CancellationTokenSource(); - _cts = cts; - try - { - var form = new PlaygroundForm - { - ApplicationId = app, - ProfileId = ComposerRules.Find(Ws.Applications, app) is { } appDto ? ComposerRules.DefaultProfile(appDto) : null, - Streaming = false, - 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, 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 RecordProbe(string connectionId, ProbeResponse p) => _probes[connectionId] = (p, DateTimeOffset.UtcNow); private void OnChanged() => _ = InvokeAsync(StateHasChanged); public void Dispose() { State.Changed -= OnChanged; - _cts?.Cancel(); + Editor.Changed -= OnChanged; } } diff --git a/src/Covenant.Ui/Pages/Evidence.razor b/src/Covenant.Ui/Pages/Evidence.razor index ca0394c..df76e0a 100644 --- a/src/Covenant.Ui/Pages/Evidence.razor +++ b/src/Covenant.Ui/Pages/Evidence.razor @@ -3,114 +3,196 @@ @inject AppState State @inject AdminApi Api @inject Interop Interop +@inject PlaygroundState Pg @implements IDisposable Audit & evidence · Covenant +@* + T08. Leads with request decisions and evidence completeness (pending / unavailable / verified), then integrity of + the audit chain — shown independently of answer quality. Who (application, team, entry point, operator ref), which + rule/version, selected/attempted/served, cost and why. Hashes/anchors are behind a disclosure. Exports: the + segment verification report (GET /admin/evidence) and, per request, GET /admin/requests/{id}/export. +*@ +

    Audit & evidence

    - Hash-chained audit log for this environment. Every allow and every refusal is an entry. + Every governed decision — allowed or refused — is a hash-chained audit record. Integrity is about the record, not about answer quality.
    - @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. - } +
    +
    +

    Audit integrity

    + Current segment · @(_verifiedAt is { } v ? "verified " + Fmt.Utc(v) : "not verified yet") +
    + @if (_report is null && _error is null) + { + + } + else if (_report is { } r) + { +
    + @(r.ChainValid ? "Audit integrity verified" : "Chain verification FAILED") + @Fmt.Int(r.Entries) records · @Fmt.Int(r.Allowed) allowed · @Fmt.Int(r.Denied) refused
    - - @if (!r.ChainValid) + @if (r.ChainValid) + { + Every stored record hashes to the next (internal consistency). @EvidenceCompleteness.QualityDisclaimer + } + else { } -
    - -
    -
    -

    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")
    +
    +
    +

    Evidence for this session's requests

    + Requests run from this console tab · newest first +
    + @if (Pg.Runs.Count == 0) + { + + Open Playground + + } + else + { +
      + @foreach (var run in Pg.Runs.Reverse()) + { + var rr = run; + var ev = SessionEvidence(rr); +
    • + #@rr.Snapshot.Sequence.ToString(System.Globalization.CultureInfo.InvariantCulture) + @rr.Snapshot.ScenarioLabel + @ev.Label + @if (rr.RequestId is { Length: > 0 } rid) + { + @rid + } + @if (rr.Evidence.State is EvidenceState.Unavailable or EvidenceState.Error) + { + + } +
    • + } +
    + } +
    + +
    +
    +

    Recent decisions

    + Newest @Fmt.Int(RecentLimit) records of the current segment · all loaded records, filters and archives in Requests +
    + + @if (_recent is null && _recentError is null) + { +
    + } + else if (_recent is { Count: 0 }) + { +
    + } + else if (_recent is { } items) + { +
      + @foreach (var rec in items) + { + var d = rec; + var o = OutcomeModel.FromRecord(d); + var mf = ModelFacts.From(d); +
    • +
      + + @Fmt.Utc(d.TimestampUtc) + @RecordedLabel(_report?.ChainValid) + Details & export +
      +
      +
      Who
      @WhoText(d)
      +
      Rule / version
      @(d.ConfigVersion is { } cv ? "config v" + cv.ToString(System.Globalization.CultureInfo.InvariantCulture) + " · " : "version not recorded · ")@d.Reason
      +
      Selected → attempted → served
      @mf.Selected → @mf.Attempted → @mf.Served
      +
      Cost and why
      @CostText.Cost(d) · @CostText.BasisDescription(d.CostBasis)
      +
      +
    • + } +
    + } +
    + + @if (_report is { } rep) + { +
    + Chain, anchors and segments (technical details) +
    +
    + A passing verification shows +
      +
    • The stored records and their hash links are internally consistent.
    • +
    • 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, anything about traffic that bypassed Covenant, or answer quality.
    • +
    • Regulatory compliance of any kind.
    • +
    +
    -

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

    -
    + +

    Segments

    + @if (_segments is { Count: > 0 } segs) + { +
    + + + + @foreach (var sg in segs) + { + var current = SegmentScope.IsCurrent(sg, segs); + + + + + + + } + +
    SegmentPeriodRecordsChain
    @(current ? "Current" : "Archived · " + (sg.Label ?? sg.Id))@(sg.FirstUtc is null ? "No records" : Fmt.Utc(sg.FirstUtc) + " → " + Fmt.Utc(sg.LastUtc))@(sg.Entries is { } n ? Fmt.Int(n) : "—")@ChainLabel(sg.ChainValid)
    +
    + Browse an archived segment's records under Requests (segment selector). + } + else + { + @(_segmentsError ?? "Only the current segment is reported.") Current: @(rep.FirstEntryUtc is null ? "no records yet" : Fmt.Utc(rep.FirstEntryUtc) + " → " + Fmt.Utc(rep.LastEntryUtc)). + } + }
    @code { + private const int RecentLimit = 25; + private EvidenceReport? _report; private bool _loading; private bool _exporting; @@ -119,24 +201,43 @@ private DateTimeOffset? _verifiedAt; private bool _started; - protected override void OnInitialized() => State.Changed += OnChanged; + private List? _recent; + private string? _recentError; + private List? _segments; + private string? _segmentsError; + + protected override void OnInitialized() + { + State.Changed += OnChanged; + Pg.Changed += OnPgChanged; + } protected override async Task OnParametersSetAsync() { - if (State.Connected && !_started) await LoadAsync(); + if (State.Connected && !_started) await StartAsync(); + } + + private async Task StartAsync() + { + _started = true; + await Task.WhenAll(LoadAsync(), LoadRecentAsync(), LoadSegmentsAsync()); } private async Task LoadAsync() { if (_loading) return; - _started = true; - _loading = true; _error = null; + _loading = true; + _error = null; StateHasChanged(); try { _report = await Api.GetEvidenceAsync(); _verifiedAt = DateTimeOffset.UtcNow; } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // ConsoleSession disconnects. + } catch (Exception ex) { _error = ex.Message; @@ -149,13 +250,53 @@ } } + private async Task LoadRecentAsync() + { + _recentError = null; + try + { + var page = await Api.GetRequestsAsync(RecentLimit); + _recent = page.Items; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // ConsoleSession disconnects. + } + catch (Exception ex) + { + _recentError = ex.Message; + } + StateHasChanged(); + } + + private async Task LoadSegmentsAsync() + { + try + { + _segments = await Api.GetSegmentsAsync(); + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.NotFound) + { + _segmentsError = "The archive listing is not available on this Host yet."; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) + { + // ConsoleSession disconnects. + } + catch (Exception ex) + { + _segmentsError = "Segments could not be listed: " + ex.Message + "."; + } + } + private async Task ExportAsync() { - _exporting = true; _exportError = null; + _exporting = true; + _exportError = null; try { var json = await Api.GetEvidenceJsonAsync(); - var name = $"covenant-evidence-{DateTimeOffset.UtcNow:yyyyMMdd-HHmmss}Z.json"; + var name = "covenant-evidence-" + DateTimeOffset.UtcNow.UtcDateTime.ToString("yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture) + "Z.json"; await Interop.DownloadTextAsync(name, "application/json", json); } catch (Exception ex) @@ -168,53 +309,71 @@ } } - 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), - ]; + /// Completeness for a run of this session: pending while the bounded lookup runs, verified only when the + /// record exists and this segment's chain verified. + private (string Label, string Tone) SessionEvidence(PlaygroundRun run) + { + if (run.Evidence.State == EvidenceState.Error) + return ("Evidence lookup failed — " + (run.Evidence.Message ?? "retry"), "bad"); + if (run.RequestId is null && !run.InFlight) + return ("No request id — rejected before governance, so no evidence record exists", "hollow"); + bool found = run.Evidence.State == EvidenceState.Found; + bool pending = run.InFlight || run.Evidence.State is EvidenceState.Pending or EvidenceState.Idle; + var state = EvidenceCompleteness.State(found, found ? _report?.ChainValid : null, pending); + return EvidenceCompleteness.Text(state); + } - 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 static string RecordedLabel(bool? chainValid) => chainValid switch + { + true => "Recorded · chain verified", + false => "Recorded · chain FAILS", + null => "Recorded · not verified yet", + }; - private string AnchorStatusText(EvidenceReport r) + private static string ChainLabel(bool? chainValid) => chainValid switch { - 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"; - } + true => "Verified", + false => "FAILED", + null => "Not reported", + }; - private string AnchorPillKind(EvidenceReport r) + private static string WhoText(AuditEntryView r) { - var configured = AnchorConfigured(r); - if (configured != true) return "unknown"; - var count = AnchorCount(r); - return count is > 0 && r.ChainValid ? "served" : "refused"; + var parts = new List + { + "application " + Fmt.OrNotRecorded(r.ApplicationId), + "team " + Fmt.OrNotRecorded(r.Tags.Team), + "entry " + Fmt.OrNotRecorded(r.EntryPoint), + }; + if (r.EntryPoint == "console") parts.Add("operator " + Fmt.OrNotRecorded(r.OperatorRef) + " (shared)"); + if (!string.IsNullOrWhiteSpace(r.ProfileId)) parts.Add("profile " + r.ProfileId); + return string.Join(" · ", parts); } + 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 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("Anchor", AnchorConfigured(r) switch { true => "Configured (path not exposed)", false => "Not configured", null => "Not reported" }), + new("Anchor interval", 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), + new("First / last record", Fmt.Utc(r.FirstEntryUtc) + " → " + Fmt.Utc(r.LastEntryUtc), true), ]; private void OnChanged() { - if (State.Connected && !_started) _ = InvokeAsync(LoadAsync); + if (State.Connected && !_started) _ = InvokeAsync(StartAsync); _ = InvokeAsync(StateHasChanged); } - public void Dispose() => State.Changed -= OnChanged; + private void OnPgChanged() => _ = InvokeAsync(StateHasChanged); + + public void Dispose() + { + State.Changed -= OnChanged; + Pg.Changed -= OnPgChanged; + } } diff --git a/src/Covenant.Ui/Pages/Policies.razor b/src/Covenant.Ui/Pages/Policies.razor index 6dc1ea5..f49f4fa 100644 --- a/src/Covenant.Ui/Pages/Policies.razor +++ b/src/Covenant.Ui/Pages/Policies.razor @@ -1,164 +1,411 @@ @page "/policies" @inject AppState State +@inject ConfigEditor Editor +@inject WorkspaceConfig Ws @implements IDisposable Policies · Covenant +@* + T08. Routing policies from the versioned configuration (ADR-0013): a coloured route view (classification/profile → + primary → approved fallbacks, Local/Cloud, state, strategy) and a compact editable list (targets, order, pause/resume + route and policy, retry), Preview impact → Save & apply via ConfigEditor. Simulator = real engine, dry run. +*@ +
    - @if (State.LastStatus is not { } s) +
    +
    +

    Policies

    + Which approved destination serves each classification, in what order, and when a request is refused. +
    + @if (Editor.Current is { } hc) + { + var badge = ShellStatus.Mode(hc.Mode); + @badge.Label + } + Try in Playground +
    + + + + @if (Editor.Current is not { } cfg) { - + if (Editor.Loading || (Editor.Applied is null && Editor.LoadError is null)) + { +
    + } + else if (Editor.EndpointMissing) + { + + } } 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. +
    +
    +

    Mode

    + @ModeSentence(cfg.Mode)
    - Managed by configuration; restart required - Try in Playground -
    - -
    -

    In plain words

    -
      - @foreach (var g in groups) + @if (PolicyRoutes.IsLegacy(cfg.Mode)) + { +
      +
      + Imported legacy rules + This configuration reproduces the pre-v2 startup routing exactly (legacy cloud mode). Review the effective routes below before relying on it. “Move to Hybrid defaults” builds a DRAFT — Public → approved cloud model with local fallback; Internal, PII and PHI → local only — and previews it; nothing is applied until you save. +
      + +
      + @if (_hybridProblem is { } hp) { -
    • - @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 - { - . - } -
    • + @hp } -
    • PII/PHI never route to cloud destinations.
    • -
    • 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) + } +
      + + + @if (PolicyRoutes.IsLegacy(cfg.Mode)) { -
    • No routes are configured. Every request is refused by policy (fail-closed).
    • + } -
    +
    + @if (Editing) + { + Changing the mode previews its impact automatically. Local-only: cloud targets can never execute. Hybrid: approved cloud targets may serve Public/Internal; PII/PHI never route to cloud destinations. + } -
    +
    -

    Classification routes

    - Read-only · as loaded at start · @(Fmt.Int(s.Routes.Count) + (s.Routes.Count == 1 ? " route" : " routes")) +

    Effective routes

    + @(Editing ? "Draft — not applied" : "Applied version v" + (Editor.AppliedVersion?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "?")) · from configuration; availability is shown under Models & connections
    - @if (s.Routes.Count == 0) + @if (cfg.Policies.Count == 0) { -
    + } else { -
    - - - - - - - - - - - @foreach (var g in groups) - { - var first = true; - foreach (var r in g) +
      + @foreach (var p in OrderedPolicies(cfg)) + { + var pol = p; + var targets = PolicyRoutes.Targets(pol, cfg); +
    1. + @PolicyText.Applicability(pol) + + + @if (!pol.Enabled || pol.Paused) { -
    - - - - - - first = false; + @(pol.Paused ? "Refused — policy paused" : "Not evaluated — disabled") } - } - -
    ClassificationAdapterModelAdapter status
    @(first ? g.Key : "")@r.Adapter@r.Model@AdapterStatus(r)
    -
    - } - @if (unresolved.Count > 0) - { -
    - -
    + else if (targets.All(x => !x.Eligible)) + { + Refused — no eligible target + } + @foreach (var (t, i) in targets.Select((x, n) => (x, n))) + { + + @PolicyRoutes.RoleLabel(i) + @t.Key + @if (t.Eligible) { } + else { @t.ExcludedReason } + + } + + @PolicyText.StrategyName(pol) · + + } + +
      + @foreach (var p in OrderedPolicies(cfg)) + { +
    • @PolicyRoutes.SummaryLine(p, cfg)
    • + } +
    • @PolicyText.SensitiveNeverCloud
    • +
    }
    -
    -
    -

    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. +
    +
    +

    Policies

    + @(Editing ? "Editing the draft" : "Read-only — choose Edit above")
    -

    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))) +
      + Pause policy: @PolicyText.PausedPolicyExplained + Pause route: @PolicyText.PausedRouteExplained +
      +
        + @foreach (var p in cfg.Policies) { -
      • @i@name — @desc
      • + var pol = p; + var pi = cfg.Policies.IndexOf(pol); + var targets = PolicyRoutes.Targets(pol, cfg); + var options = PolicyRoutes.Options(pol, cfg); +
      • +
        +
        + @(pol.Name ?? pol.Id) + @pol.Id · @PolicyText.Applicability(pol) · @PolicyText.StrategyName(pol) +
        + + @if (Editing) + { + + } +
        + @PolicyText.PausedPolicyExplained + + @if (Editing) { } + + @foreach (var (t, ti) in targets.Select((x, n) => (x, n))) + { + var row = t; + var index = ti; + + + + + @if (Editing) + { + + } + + } + +
        OrderTargetStateActions
        @PolicyRoutes.RoleLabel(index)@row.Key @(row.Eligible ? "Eligible" : row.ExcludedReason) + + + + + + +
        + @if (pol.Targets.Count == 0) + { + No targets: every request this policy matches is refused. + } + + @if (Editing) + { +
        +
        +
        + + +
        + +
        + @if (PolicyText.CoversSensitive(pol)) + { + @PolicyText.SensitiveNeverCloud Cloud models are not offered for this policy. + } +
        +
        + + +
        + @if (PolicyText.IsLengthHeuristic(pol)) + { +
        + + + +
        + } +
        + + + +
        +
        + + + +
        +
        +
        + Fall back on (transient failures only, never after content was streamed) + @foreach (var kind in RetryKinds) + { + var k = kind; + + } +
        +
        + } +
        + Refusal conditions +
          + @foreach (var line in PolicyRoutes.RefusalConditions(pol, cfg)) + { +
        • @line
        • + } +
        + @if (pol.Explanation is { Length: > 0 } ex) + { + Policy note: @ex + } +
        + +
      • } -
    +
    -
    -

    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 = + private sealed record RetryKind(string Key, string Label); + + private static readonly RetryKind[] RetryKinds = [ - ("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."), + new("connect", "Connection failure"), + new("timeout", "Provider timeout"), + new("429", "429 rate limited"), + new("5xx", "500/502/503/504"), ]; - private static int ClassificationOrder(string c) => c.ToLowerInvariant() switch + private static readonly string[] DefaultRetryOn = ["connect", "timeout", "429", "5xx"]; + + private readonly Dictionary _add = new(StringComparer.Ordinal); + private string? _hybridProblem; + + private bool Editing => Editor.Editing && Editor.Owner == "policies"; + private bool CanStartEdit => Editor.Applied is not null && !Editor.Saving && (!Editor.IsDirty || Editor.Owner == "policies"); + + private IReadOnlyList ClaimedPaths => Editor.Current is { } c ? Enumerable.Range(0, c.Policies.Count).Select(IssueIndex.Policy).ToList() : []; + + protected override async Task OnInitializedAsync() + { + Editor.Changed += OnChanged; + Ws.Changed += OnChanged; + State.Changed += OnChanged; + await Editor.EnsureLoadedAsync(); + await Ws.EnsureLoadedAsync(); + } + + private static IEnumerable OrderedPolicies(CovenantConfigDto cfg) + => cfg.Policies.OrderBy(p => p.Classifications.Count == 0 ? 9 : p.Classifications.Min(PolicyText.ClassificationOrder)).ThenBy(p => p.Profiles.Count == 0 ? 1 : 0); + + private static bool IsHybrid(string? mode) => string.Equals(mode, "hybrid", StringComparison.OrdinalIgnoreCase); + + private static string ModeSentence(string? mode) + { + if (PolicyRoutes.IsLocalOnly(mode)) return "Local-only: only in-perimeter connections can execute."; + if (IsHybrid(mode)) return "Hybrid: local and approved cloud routes; PII/PHI never route to cloud destinations."; + if (PolicyRoutes.IsLegacy(mode)) return "Legacy cloud: imported pre-v2 routing."; + return "Mode not reported."; + } + + private static RetrySettingsDto Retry(PolicyDto p) => p.Retry ?? new RetrySettingsDto(); + + private static bool RetryOn(PolicyDto p, string key) => (p.Retry?.On ?? (IEnumerable)DefaultRetryOn).Contains(key, StringComparer.Ordinal); + + private async Task SetModeAsync(string mode) + { + if (!Editing || Editor.Draft is not { } d || string.Equals(d.Mode, mode, StringComparison.Ordinal)) return; + d.Mode = mode; + Editor.Touch(); + await Editor.ValidateAsync(); + } + + private async Task MoveToHybridAsync() + { + _hybridProblem = null; + if (!Editor.BeginEdit("policies") || Editor.Draft is not { } d) return; + var problem = HybridDefaults.ApplyTo(d); + if (problem is not null) + { + _hybridProblem = problem; + return; + } + Editor.Touch(); + await Editor.ValidateAsync(); + } + + private void TogglePolicyPause(PolicyDto p) { - "public" => 0, "internal" => 1, "pii" => 2, "phi" => 3, _ => 9, - }; + p.Paused = !p.Paused; + Editor.Touch(); + } - 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 void ToggleRoutePause(PolicyDto p, int index) + { + if (index < 0 || index >= p.Targets.Count) return; + p.Targets[index].Paused = !p.Targets[index].Paused; + Editor.Touch(); + } + + private void Move(PolicyDto p, int index, bool up) + { + if (up ? PolicyRoutes.MoveUp(p.Targets, index) : PolicyRoutes.MoveDown(p.Targets, index)) Editor.Touch(); + } + + private void RemoveTarget(PolicyDto p, int index) + { + if (index < 0 || index >= p.Targets.Count) return; + p.Targets.RemoveAt(index); + Editor.Touch(); + } - private string AdapterStatus(Covenant.Ui.Models.RouteView r) + private void AddTarget(PolicyDto p) { - 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"; + if (!_add.TryGetValue(p.Id, out var value) || string.IsNullOrEmpty(value)) return; + var option = Editor.Draft is { } d ? PolicyRoutes.Options(p, d).FirstOrDefault(o => o.Value == value && o.DisabledReason is null) : null; + if (option is null) return; + p.Targets.Add(new PolicyTargetDto { ConnectionId = option.ConnectionId, ModelId = option.ModelId }); + _add.Remove(p.Id); + Editor.Touch(); + } + + private void SetStrategy(PolicyDto p, ChangeEventArgs e) + { + p.Strategy = e.Value?.ToString() == "length-heuristic" ? "length-heuristic" : "fixed"; + if (p.Strategy == "length-heuristic" && p.ThresholdTokens is null) p.ThresholdTokens = 400; + Editor.Touch(); + } + + private void SetRetryInt(PolicyDto p, ChangeEventArgs e, bool deadline) + { + var retry = p.Retry ??= new RetrySettingsDto(); + int? value = int.TryParse(e.Value?.ToString(), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var n) ? n : null; + if (deadline) retry.DeadlineMs = value; else retry.MaxAttempts = value; + Editor.Touch(); + } + + private void SetRetryOn(PolicyDto p, string key, ChangeEventArgs e) + { + var retry = p.Retry ??= new RetrySettingsDto(); + List on = retry.On ?? new List(DefaultRetryOn); + on.RemoveAll(x => x == key); + if (e.Value is bool b && b) on.Add(key); + retry.On = RetryKinds.Select(k => k.Key).Where(on.Contains).ToList(); + Editor.Touch(); } - protected override void OnInitialized() => State.Changed += OnChanged; private void OnChanged() => _ = InvokeAsync(StateHasChanged); - public void Dispose() => State.Changed -= OnChanged; + + public void Dispose() + { + Editor.Changed -= OnChanged; + Ws.Changed -= OnChanged; + State.Changed -= OnChanged; + } } diff --git a/src/Covenant.Ui/Pages/Requests.razor b/src/Covenant.Ui/Pages/Requests.razor index d863e3a..8f9287d 100644 --- a/src/Covenant.Ui/Pages/Requests.razor +++ b/src/Covenant.Ui/Pages/Requests.razor @@ -5,15 +5,19 @@ @inject AdminApi Api @inject AppState State @inject RequestsViewState View +@inject WorkspaceConfig Ws +@inject Interop Interop @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. + T08. Audit records of ONE segment (current, or an archived one chosen from GET /admin/audit/segments), loaded in + bounded newest-first pages (GET /admin/requests?limit=&cursor=&segment=) with "Load older". Filters apply only to + what is loaded — the page says so. Deep links (/requests/{id}) fetch the exact record (current segment). The drawer + shows attempts, trace summary, config version and identity, and exports the per-request evidence report + (GET /admin/requests/{id}/export — no prompt/response content). *@
    @@ -21,14 +25,25 @@

    Requests

    - @CoverageLabel + @ScopeLabel — governed decisions as recorded at processing time.
    - +
    + + + @(View.SegmentsError ?? (View.Segments is null ? "Loading segments…" : ArchivedSegments.Count == 0 ? "No archived segments." : "Archived segments are read-only.")) +
    +
    - + -
    + +
    +
    +

    Console preferences

    + This browser only · saved immediately · never sent to the server
    +
    +
    + Theme +
    + + +
    +
    +
    + Default response mode for new requests +
    + + +
    + Used when the composer starts empty; each run can still change it under Advanced. +
    +
    + @if (_prefNote is { } pn) + { + @pn + } + Presentation mode follows the operating system's reduced-motion setting; open it from the Playground. +
    -
    + @if (State.LastStatus is { } s) + { +
    -

    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 - } -
    -
    +

    Diagnostics

    + Read-only · startup configuration · restart required to change
    + +
    + Technical details + + Restart-only (never editable in the console): Admin:Token, secret values, Auth:Keys key values, Audit:*, Config:Path, Providers:ProbeAllowList (egress allow-list), Providers:LocalEndpoints. After configuration v1 exists, legacy routing keys (Providers:Mode, OpenAI:*, Local:*, Budget:*, Pricing:*, Routing:*) are ignored; the Host logs each ignored key at startup. +
    -
    +

    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. + Shared admin token in this tab's session storage; disconnecting does not pause Covenant
    @@ -61,59 +148,45 @@
    -
    -
    -

    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.
    • -
    +
    +
    +

    Maintenance — archive the audit segment

    + Separate from accounting · not a demo step · not a fix for an exhausted budget
    - - @if (_resetError is not null) - { - - } +
      +
    • The current audit segment is closed and archived beside the log with a timestamp. Nothing is deleted; the archive stays independently verifiable and browsable under Requests (segment selector).
    • +
    • @AccountingImpact
    • +
    • Budget period rollover is a different thing: it happens by UTC date and never archives evidence.
    • +
    + @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. - + Audit segment archived (confirmed by the Host) + @(done.ArchivedTo is { Length: > 0 } ? "Archived to " + done.ArchivedTo + ". " : "The segment was empty; nothing to archive. ")A new segment has started.
    - View in Evidence + Open Audit & 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.

    + +

    This archives the current audit segment of environment @State.EnvironmentLabel (@Fmt.Int(s.AuditEntries) entries) and starts a new one. Nothing is deleted.

    +

    @AccountingImpact

    @if (State.Paused) { -

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

    +

    New provider calls are paused; archiving does not resume them.

    }
    @@ -121,68 +194,146 @@
    - +
    } + else + { + + }
    @code { - private sealed record Row(string Key, string Value, string? Note = null, bool Mono = false); - + private string _theme = "dark"; + private string? _prefNote; private bool _confirmOpen; private string _typed = ""; private bool _resetting; private string? _resetError; private ResetResponse? _resetResult; + /// null = not checked yet; true = GET /admin/budgets answered (ADR-0014 ledger); false = 404 (pre-v2 counters). + private bool? _ledger; + private bool Editing => Editor.Editing && Editor.Owner == "settings"; private bool CanConfirm => !_resetting && string.Equals(_typed.Trim(), State.EnvironmentLabel, StringComparison.Ordinal); - protected override void OnInitialized() => State.Changed += OnChanged; + private string AccountingImpact => _ledger switch + { + true => "Budgets are NOT reopened and spend is NOT reset: spend and reservations live in the budget ledger, independent of audit segments (ADR-0014).", + false => "This Host has no budget ledger yet (GET /admin/budgets is missing): on it, archiving ALSO resets the pre-v2 spend counters, so reached budgets reopen.", + null => "Accounting impact is being checked (budget ledger present or not)…", + }; + + protected override async Task OnInitializedAsync() + { + State.Changed += OnChanged; + Editor.Changed += OnChanged; + Pg.Changed += OnChanged; + await Editor.EnsureLoadedAsync(); + await CheckLedgerAsync(); + } + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender) return; + try { _theme = await Interop.GetThemeAsync(); } catch (JSException) { _theme = "dark"; } + StateHasChanged(); + } + + private async Task CheckLedgerAsync() + { + if (!State.Connected) return; + try + { + await Api.GetBudgetsAsync(); + _ledger = true; + } + catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.NotFound) + { + _ledger = false; + } + catch (Exception) + { + _ledger = null; // unknown: the confirmation keeps saying so + } + } + + private async Task SetThemeAsync(string theme) + { + try + { + _theme = await Interop.SetThemeAsync(theme); + _prefNote = "Theme saved in this browser."; + } + catch (JSException) + { + _prefNote = "The browser refused to store the theme."; + } + } - private static string NotReported => "Not reported by this Host"; + private async Task SetStreamingAsync(bool streaming) + { + Pg.SetStreamingDefault(streaming); + bool stored; + try { stored = await Interop.PrefSetAsync("stream-default", streaming ? "true" : "false"); } + catch (JSException) { stored = false; } + _prefNote = stored ? "Default response mode saved in this browser." : "Applied for this session; the browser did not store it."; + } - private static List Rows(StatusReport s) => + private IReadOnlyList SummaryFacts(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), + new("Environment", s.Environment ?? NotReported, true), + new("Mode", ShellStatus.Mode(Editor.Applied?.Config?.Mode ?? s.Mode).Label), + new("Active configuration", (Editor.AppliedVersion ?? s.ConfigVersion) is { } v ? "v" + v.ToString(System.Globalization.CultureInfo.InvariantCulture) : NotReported, true), + new("Started", Fmt.Utc(s.StartedUtc), true), ]; + private IReadOnlyList DiagnosticFacts(StatusReport s) => + [ + new("Covenant version", s.Version ?? NotReported, true), + new("Audit log path (Audit:Path)", s.AuditPath ?? NotReported, true), + new("Anchor (Audit:AnchorPath / AnchorEvery)", AnchorText(s)), + new("Configuration directory (Config:Path)", NotReported + " (default: beside the audit log, .config/)"), + new("Legacy keys ignored after import", NotReported + " — listed in the Host's startup log"), + new("Probe allow-list (Providers:ProbeAllowList ∪ Local:Endpoint)", State.Catalog?.ProbeAllowList is { Count: > 0 } pl ? string.Join(", ", pl) : NotReported, true), + new("Egress allow-list", Editor.Applied?.AllowList is { Count: > 0 } al ? string.Join(", ", al) : NotReported, true), + new("Telemetry (OpenTelemetry)", s.OtelEnabled ? "Enabled — in-perimeter collector" : "Disabled"), + new("Application keys (Auth:Keys)", Fmt.Int(s.Auth.KeyCount) + (s.Auth.AllowAnonymous ? " · anonymous requests ALLOWED" : " · anonymous requests refused"), true), + ]; + + private const string NotReported = "Not reported by this Host"; + 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: 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("Credential", "Shared admin token (X-Covenant-Admin-Token) — a shared console operator, not an individual identity", 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", FeedMode.Polling => "Polling every 3 s (stream unavailable)", _ => "Not running" }), new("Application key", "Never held — console requests run as an authorized test application (ADR-0012)"), - new("Theme", "Stored in localStorage (the only value this console persists there)"), ]; + private void OpenConfirm() + { + _confirmOpen = true; + _typed = ""; + _resetError = null; + } + private async Task ResetAsync() { if (!CanConfirm) return; - _resetting = true; _resetError = null; _resetResult = null; + _resetting = true; + _resetError = null; + _resetResult = null; try { _resetResult = await Api.ResetAsync(); @@ -198,7 +349,7 @@ _resetting = false; _typed = ""; } - // Never assume the outcome: re-sync the counters from the server either way. + // Never assume the outcome: re-sync from the server either way. await Session.TryRefreshAsync(); } @@ -209,5 +360,11 @@ } private void OnChanged() => _ = InvokeAsync(StateHasChanged); - public void Dispose() => State.Changed -= OnChanged; + + public void Dispose() + { + State.Changed -= OnChanged; + Editor.Changed -= OnChanged; + Pg.Changed -= OnChanged; + } } diff --git a/src/Covenant.Ui/Program.cs b/src/Covenant.Ui/Program.cs index ffc6214..2bcc131 100644 --- a/src/Covenant.Ui/Program.cs +++ b/src/Covenant.Ui/Program.cs @@ -27,5 +27,6 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); 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 index b00367b..095dd5e 100644 --- a/src/Covenant.Ui/Services/AdminApi.cs +++ b/src/Covenant.Ui/Services/AdminApi.cs @@ -12,6 +12,13 @@ public sealed class ApiException(HttpStatusCode? status, string message) : Excep public HttpStatusCode? Status { get; } = status; } +/// Status, body text and ETag of a raw admin call (body never contains a secret: config payloads carry +/// secret references only). +public sealed record RawResponse(int Status, string Body, string? ETag) +{ + public bool IsSuccess => Status is >= 200 and < 300; +} + /// 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. @@ -86,6 +93,83 @@ public async Task OpenTraceStreamAsync(string requestId, lo return response; } + // ---- T08: configuration editing, budgets drill-down, audit archive, request export ---- + + /// POST /admin/config/validate. Never mutates. Raw answer: 200 carries the result (valid or not); + /// 400/404/5xx are reported by the caller. + public Task ValidateConfigRawAsync(ConfigValidateRequestDto body, CancellationToken ct = default) + => SendRawAsync(HttpMethod.Post, "/admin/config/validate", JsonContent.Create(body, UiJsonContext.Default.ConfigValidateRequestDto), null, ct); + + /// PUT /admin/config with If-Match = the ETag of the version the draft was taken from (never "*"). + public Task PutConfigRawAsync(ConfigPutRequestDto body, string ifMatch, CancellationToken ct = default) + => SendRawAsync(HttpMethod.Put, "/admin/config", JsonContent.Create(body, UiJsonContext.Default.ConfigPutRequestDto), ifMatch, ct); + + /// POST /admin/config/rollback — activates the target's content as a NEW version (412 when the active moved). + public Task RollbackConfigRawAsync(int targetVersion, int expectedActiveVersion, CancellationToken ct = default) + => SendRawAsync(HttpMethod.Post, "/admin/config/rollback", + JsonContent.Create(new ConfigRollbackRequestDto { TargetVersion = targetVersion, ExpectedActiveVersion = expectedActiveVersion }, + UiJsonContext.Default.ConfigRollbackRequestDto), null, ct); + + public Task> GetConfigVersionsAsync(int limit = 50, CancellationToken ct = default) + => GetAsync("/admin/config/versions?limit=" + limit.ToString(System.Globalization.CultureInfo.InvariantCulture), + UiJsonContext.Default.ListConfigVersionDto, ct); + + public Task GetConfigVersionAsync(int version, CancellationToken ct = default) + => GetAsync("/admin/config/versions/" + version.ToString(System.Globalization.CultureInfo.InvariantCulture), + UiJsonContext.Default.CovenantConfigDto, ct); + + /// POST /admin/policies/simulate — dry run with the real engine; no provider call, no audit, no spend. + /// With set, the Host validates that candidate (422 when invalid). + public Task SimulateAsync(SimulateRequestDto body, CancellationToken ct = default) + => PostAsync("/admin/policies/simulate", body, UiJsonContext.Default.SimulateRequestDto, UiJsonContext.Default.SimulateResponseDto, ct); + + /// GET /admin/budgets/{id}/requests as raw JSON (parsed leniently by Logic/BudgetRequests). + public Task GetBudgetRequestsJsonAsync(string budgetId, int limit = 100, CancellationToken ct = default) + => GetTextAsync("/admin/budgets/" + Uri.EscapeDataString(budgetId) + "/requests?limit=" + + limit.ToString(System.Globalization.CultureInfo.InvariantCulture), ct); + + /// GET /admin/audit/segments — the current segment plus archived siblings (ids only). + public Task> GetSegmentsAsync(CancellationToken ct = default) + => GetAsync("/admin/audit/segments", UiJsonContext.Default.ListAuditSegmentDto, ct); + + /// One newest-first page: from the previous page's next_cursor; + /// = a segment id from GET /admin/audit/segments (null = current segment). + public Task GetRequestsPageAsync(int limit, string? cursor, string? segment, CancellationToken ct = default) + { + var path = "/admin/requests?limit=" + limit.ToString(System.Globalization.CultureInfo.InvariantCulture); + if (!string.IsNullOrWhiteSpace(cursor)) path += "&cursor=" + Uri.EscapeDataString(cursor); + if (!string.IsNullOrWhiteSpace(segment)) path += "&segment=" + Uri.EscapeDataString(segment); + return GetAsync(path, UiJsonContext.Default.RequestsResponse, ct); + } + + /// GET /admin/requests/{id}/export — the per-request evidence report (no prompt/response content), + /// byte-for-byte as the server produced it. + public Task GetRequestExportJsonAsync(string id, string? segment = null, CancellationToken ct = default) + => GetTextAsync("/admin/requests/" + Uri.EscapeDataString(id) + "/export" + + (string.IsNullOrWhiteSpace(segment) ? "" : "?segment=" + Uri.EscapeDataString(segment)), ct); + + /// Raw send for calls whose non-2xx bodies carry meaning (config writes: 412/422/428). A 401 still + /// raises . Transport failures throw. + public async Task SendRawAsync(HttpMethod method, string path, HttpContent? content, string? ifMatch, CancellationToken ct) + { + using var request = NewRequest(method, path); + if (content is not null) request.Content = content; + if (!string.IsNullOrWhiteSpace(ifMatch)) request.Headers.TryAddWithoutValidation("If-Match", ifMatch); + using var response = await http.SendAsync(request, ct); + var text = await response.Content.ReadAsStringAsync(ct); + if (response.StatusCode == HttpStatusCode.Unauthorized) Unauthorized?.Invoke(); + string? etag = response.Headers.ETag?.Tag; + return new RawResponse((int)response.StatusCode, text, etag); + } + + private async Task GetTextAsync(string path, CancellationToken ct) + { + using var request = NewRequest(HttpMethod.Get, path); + using var response = await http.SendAsync(request, ct); + await EnsureSuccessAsync(response, ct); + return await response.Content.ReadAsStringAsync(ct); + } + /// For callers that send their own admin requests (console inference): a 401 there means the admin /// token was rejected, which is handled exactly like any other admin 401. public void ReportUnauthorized() => Unauthorized?.Invoke(); diff --git a/src/Covenant.Ui/Services/ConfigEditor.cs b/src/Covenant.Ui/Services/ConfigEditor.cs new file mode 100644 index 0000000..e056d11 --- /dev/null +++ b/src/Covenant.Ui/Services/ConfigEditor.cs @@ -0,0 +1,399 @@ +using System.Net; +using System.Text.Json; +using Covenant.Ui.Logic; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Services; + +/// The stale-edit state after a 412 (or a validate warning stale_base_version): the draft is kept, +/// nothing is overwritten. / are filled by Compare. +public sealed record ConflictInfo(int? ActiveVersion, string Message) +{ + public IReadOnlyList? ServerChanges { get; init; } + public IReadOnlyList? YourChanges { get; init; } +} + +/// Shared configuration editing for every admin page (ADR-0011): loads GET /admin/config (version + ETag), +/// holds ONE deep-copied draft, validates on demand (POST /admin/config/validate — never per keystroke), and saves with +/// PUT If-Match. Success is reported ONLY after the Host's 200 carrying the new version; then config, catalog, +/// workspace and status are reloaded. 412 keeps the draft and reports the conflict; 422 maps field errors onto the +/// draft. Rollback activates a historical version as a NEW version. Cleared on disconnect. +public sealed class ConfigEditor : IDisposable +{ + private readonly AppState _state; + private readonly AdminApi _api; + private readonly WorkspaceConfig _workspace; + private readonly CatalogState _catalog; + private readonly ConsoleSession _session; + private Task? _loading; + private string? _validatedJson; + + public ConfigEditor(AppState state, AdminApi api, WorkspaceConfig workspace, CatalogState catalog, ConsoleSession session) + { + _state = state; + _api = api; + _workspace = workspace; + _catalog = catalog; + _session = session; + _state.Disconnected += Clear; + } + + public event Action? Changed; + + // ---- applied configuration ---- + public ConfigEnvelopeDto? Applied { get; private set; } + public string? LoadError { get; private set; } + /// True when GET /admin/config answered 404: this Host has no versioned configuration (pre-v2). + public bool EndpointMissing { get; private set; } + public DateTimeOffset? LoadedUtc { get; private set; } + public bool Loading => _loading is { IsCompleted: false }; + public int? AppliedVersion => Applied?.Version; + + // ---- draft ---- + public ConfigDraft? Session { get; private set; } + /// Which page owns the draft ("connections", "policies", …). + public string? Owner { get; private set; } + public bool Editing => Session is not null; + public bool IsDirty => Session?.IsDirty == true; + public CovenantConfigDto? Draft => Session?.Draft; + /// What a page shows: the draft while editing, else the applied configuration. + public CovenantConfigDto? Current => Session?.Draft ?? Applied?.Config; + + // ---- validation / impact ---- + public bool Validating { get; private set; } + public ConfigValidationResultDto? Validation { get; private set; } + public string? ValidationError { get; private set; } + /// The last preview was computed for exactly the current draft content. + public bool ValidationCurrent => Validation is not null && Session is not null + && string.Equals(_validatedJson, ConfigCopy.Canonical(Session.Draft), StringComparison.Ordinal); + public bool CanSave => Session is not null && Session.IsDirty && ValidationCurrent && Validation!.Valid && !Saving && Conflict is null; + + // ---- save / rollback ---- + public bool Saving { get; private set; } + public EditOutcome? LastOutcome { get; private set; } + public ConflictInfo? Conflict { get; private set; } + /// Shown after a confirmed activation: "Applied version v8". + public string? AppliedNotice { get; private set; } + + // ---- history ---- + public List? Versions { get; private set; } + public string? VersionsError { get; private set; } + public bool VersionsLoading { get; private set; } + + /// Field issues: from the last 422 when that is the latest answer, else from the last preview. + public IssueIndex Issues + { + get + { + if (LastOutcome is { Kind: EditOutcomeKind.Invalid } inv) + return new IssueIndex(inv.Errors ?? [], inv.Warnings ?? []); + if (Validation is { } v) return new IssueIndex(v.Errors, v.Warnings); + return IssueIndex.Empty; + } + } + + public Task EnsureLoadedAsync(bool force = false) + { + if (!_state.Connected) return Task.CompletedTask; + if (_loading is { IsCompleted: false } running) return running; + if (!force && Applied is not null) return Task.CompletedTask; + _loading = LoadAsync(); + return _loading; + } + + private async Task LoadAsync() + { + try + { + var env = await _api.GetConfigAsync(); + Applied = env; + LoadError = null; + EndpointMissing = false; + LoadedUtc = DateTimeOffset.UtcNow; + } + catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) + { + EndpointMissing = true; + LoadError = "This Host does not expose versioned configuration (GET /admin/config is missing) — editing is not available."; + } + catch (ApiException ex) when (ex.Status == HttpStatusCode.Unauthorized) + { + // ConsoleSession disconnects. + } + catch (Exception ex) + { + LoadError = "Configuration could not be loaded: " + ex.Message; + } + finally + { + Notify(); + } + } + + /// Starts (or continues) editing for . A clean draft of another page is replaced. + public bool BeginEdit(string owner) + { + if (Applied?.Config is not { } cfg) return false; + if (Session is not null && Owner == owner) return true; + if (Session is not null && Session.IsDirty) return false; // the guard asks before another page takes over + Session = new ConfigDraft(Applied.Version, Applied.Etag, cfg); + Owner = owner; + ResetResults(); + AppliedNotice = null; + Notify(); + return true; + } + + /// Call after mutating : the preview becomes stale (Save needs a fresh preview). + public void Touch() + { + if (LastOutcome is { Kind: not EditOutcomeKind.Stale }) LastOutcome = null; + AppliedNotice = null; + Notify(); + } + + /// Discards the draft (Cancel, or confirmed navigation away). Never touches the server. + public void Discard() + { + Session = null; + Owner = null; + ResetResults(); + Notify(); + } + + /// Releases a CLEAN draft owned by (page left). A dirty draft is kept for the guard. + public void Release(string owner) + { + if (Owner == owner && !IsDirty) Discard(); + } + + private void ResetResults() + { + Validation = null; + ValidationError = null; + _validatedJson = null; + LastOutcome = null; + Conflict = null; + } + + /// POST /admin/config/validate for the current draft. Returns true when the preview is valid. + public async Task ValidateAsync() + { + if (Session is not { } s || Validating) return false; + Validating = true; + ValidationError = null; + Notify(); + var json = ConfigCopy.Canonical(s.Draft); + try + { + var raw = await _api.ValidateConfigRawAsync(new ConfigValidateRequestDto { BaseVersion = s.BaseVersion, Config = ConfigCopy.Deep(s.Draft) }); + if (raw.IsSuccess && Parse(raw.Body, UiJsonContext.Default.ConfigValidationResultDto) is { } result) + { + if (!ReferenceEquals(Session, s)) return false; + Validation = result; + _validatedJson = json; + if (LastOutcome is { Kind: EditOutcomeKind.Invalid }) LastOutcome = null; + if (result.Warnings.Any(w => w.Code == "stale_base_version")) + Conflict = new ConflictInfo(result.ActiveVersion, EditOutcomes.StaleMessage(result.ActiveVersion)); + return result.Valid; + } + ValidationError = raw.Status switch + { + (int)HttpStatusCode.NotFound => "Preview is not available on this Host (POST /admin/config/validate missing).", + (int)HttpStatusCode.Unauthorized => "Admin token rejected.", + _ => "Preview failed: HTTP " + raw.Status.ToString(System.Globalization.CultureInfo.InvariantCulture) + ErrorReason(raw.Body), + }; + return false; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + ValidationError = "Preview failed: " + ex.Message; + return false; + } + finally + { + Validating = false; + Notify(); + } + } + + /// PUT /admin/config with If-Match. Only a 200 with a version is success; then everything reloads. + public async Task SaveAsync(string? summary = null) + { + if (Session is not { } s) return new EditOutcome(EditOutcomeKind.Failed, "Nothing to save."); + if (!CanSave) return new EditOutcome(EditOutcomeKind.Failed, "Preview the impact of the current draft before saving."); + Saving = true; + AppliedNotice = null; + Notify(); + EditOutcome outcome; + try + { + var body = new ConfigPutRequestDto + { + Config = ConfigCopy.Deep(s.Draft), + ChangeSummary = string.IsNullOrWhiteSpace(summary) ? ChangeSummary.Text(s.Base, s.Draft) : summary.Trim(), + }; + var raw = await _api.PutConfigRawAsync(body, s.BaseEtag); + outcome = EditOutcomes.FromResponse(raw.Status, raw.Body); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + outcome = new EditOutcome(EditOutcomeKind.Failed, "Save failed before the Host answered: " + ex.Message + " — nothing is assumed applied. Reload to see the active version."); + } + + LastOutcome = outcome; + if (outcome.Kind == EditOutcomeKind.Stale) + Conflict = new ConflictInfo(outcome.Version, outcome.Message); + + if (outcome.Succeeded) + { + Session = null; + Owner = null; + Validation = null; + _validatedJson = null; + Conflict = null; + await AfterActivationAsync(outcome.Version!.Value, rollback: false); + } + Saving = false; + Notify(); + return outcome; + } + + private async Task AfterActivationAsync(int version, bool rollback) + { + await EnsureLoadedAsync(force: true); + try { await _workspace.RefreshAsync(); } catch (Exception) { /* each source reports its own error */ } + try { await _catalog.RefreshAsync(); } catch (Exception) { /* idem */ } + await _session.TryRefreshAsync(); + if (Versions is not null) await LoadVersionsAsync(); + var v = version.ToString(System.Globalization.CultureInfo.InvariantCulture); + var head = rollback ? "Rollback applied as new version v" + v : "Applied version v" + v; + AppliedNotice = Applied is null + ? head + " (server confirmed). Reloading the configuration view failed: " + (LoadError ?? "unknown error") + : Applied.Version == version + ? head + " — new requests now bind to v" + v + "." + : head + " (server confirmed); the Host now reports v" + Applied.Version.ToString(System.Globalization.CultureInfo.InvariantCulture) + " — another change landed since."; + } + + /// After a conflict: fetch the active version and list what changed there vs. what the draft changes. + /// Nothing is merged or overwritten. + public async Task CompareAsync() + { + if (Session is not { } s || Conflict is not { } c) return; + try + { + var latest = await _api.GetConfigAsync(); + if (latest.Config is not { } lc) return; + Conflict = c with + { + ActiveVersion = latest.Version, + Message = EditOutcomes.StaleMessage(latest.Version), + ServerChanges = ChangeSummary.Lines(s.Base, lc), + YourChanges = ChangeSummary.Lines(s.Base, s.Draft), + }; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Conflict = c with { ServerChanges = ["Could not load the active version: " + ex.Message] }; + } + Notify(); + } + + /// Discards the draft and loads the active version (the conflict's "Reload"). + public async Task ReloadDiscardingDraftAsync() + { + Discard(); + await EnsureLoadedAsync(force: true); + } + + public async Task LoadVersionsAsync() + { + VersionsLoading = true; + VersionsError = null; + Notify(); + try + { + Versions = await _api.GetConfigVersionsAsync(50); + } + catch (ApiException ex) when (ex.Status == HttpStatusCode.NotFound) + { + VersionsError = "Version history is not available on this Host."; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + VersionsError = "Version history could not be loaded: " + ex.Message; + } + finally + { + VersionsLoading = false; + Notify(); + } + } + + /// POST /admin/config/rollback with the expected active version. A 412 means someone applied first. + public async Task RollbackAsync(int targetVersion) + { + if (Applied is null) return new EditOutcome(EditOutcomeKind.Failed, "Configuration not loaded."); + if (IsDirty) return new EditOutcome(EditOutcomeKind.Failed, "Save or cancel your unsaved changes before rolling back."); + Saving = true; + AppliedNotice = null; + Notify(); + EditOutcome outcome; + try + { + var raw = await _api.RollbackConfigRawAsync(targetVersion, Applied.Version); + outcome = EditOutcomes.FromResponse(raw.Status, raw.Body, rollback: true); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + outcome = new EditOutcome(EditOutcomeKind.Failed, "Rollback failed before the Host answered: " + ex.Message + " — nothing is assumed applied."); + } + LastOutcome = outcome; + if (outcome.Succeeded) + { + Discard(); + LastOutcome = outcome; + await AfterActivationAsync(outcome.Version!.Value, rollback: true); + } + else if (outcome.Kind == EditOutcomeKind.Stale) + { + await EnsureLoadedAsync(force: true); + } + Saving = false; + Notify(); + return outcome; + } + + private static T? Parse(string body, System.Text.Json.Serialization.Metadata.JsonTypeInfo info) where T : class + { + try { return JsonSerializer.Deserialize(body, info); } + catch (JsonException) { return null; } + } + + private static string ErrorReason(string body) + { + var err = Parse(body, UiJsonContext.Default.ConfigErrorResponseDto); + var r = err?.Reason ?? err?.Error; + return string.IsNullOrWhiteSpace(r) ? "" : ": " + (r.Length > 300 ? r[..299] + "…" : r); + } + + private void Clear() + { + Applied = null; + LoadError = null; + EndpointMissing = false; + LoadedUtc = null; + _loading = null; + Session = null; + Owner = null; + Versions = null; + VersionsError = null; + AppliedNotice = null; + ResetResults(); + Notify(); + } + + private void Notify() => Changed?.Invoke(); + + public void Dispose() => _state.Disconnected -= Clear; +} diff --git a/src/Covenant.Ui/Services/Fmt.cs b/src/Covenant.Ui/Services/Fmt.cs index 81a94e7..8939a24 100644 --- a/src/Covenant.Ui/Services/Fmt.cs +++ b/src/Covenant.Ui/Services/Fmt.cs @@ -2,16 +2,16 @@ 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. +/// Invariant-culture formatting (the bundle ships no globalization data). Money goes through Logic/Money: +/// significant digits for sub-cent charges (never "$0.00" for a non-zero amount), two decimals for caps. 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 Usd(decimal value) => Covenant.Ui.Logic.Money.Usd(value); - public static string UsdTotal(decimal value) => Usd(value, value == decimal.Truncate(value) ? 2 : 4); + /// Caps and totals: two decimals ("$250.00"); a tiny non-zero cap keeps its significant digits. + public static string UsdTotal(decimal value) => Covenant.Ui.Logic.Money.Cap(value); public static string Int(long value) => value.ToString("N0", Inv); diff --git a/src/Covenant.Ui/Services/Interop.cs b/src/Covenant.Ui/Services/Interop.cs index 25636ec..60f0dc1 100644 --- a/src/Covenant.Ui/Services/Interop.cs +++ b/src/Covenant.Ui/Services/Interop.cs @@ -4,7 +4,8 @@ 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. +/// localStorage for the theme and the allow-listed console preferences (interop.js PREF_KEYS) only — never a +/// credential, prompt, response or server configuration.
    public sealed class Interop(IJSRuntime js) { private const string Prefix = "covenantInterop."; @@ -16,6 +17,10 @@ public sealed class Interop(IJSRuntime js) public ValueTask GetThemeAsync() => js.InvokeAsync(Prefix + "getTheme"); public ValueTask SetThemeAsync(string theme) => js.InvokeAsync(Prefix + "setTheme", theme); + /// Browser-local console preference (allow-listed names only, e.g. "stream-default"); null when unset. + public ValueTask PrefGetAsync(string name) => js.InvokeAsync(Prefix + "prefGet", name); + public ValueTask PrefSetAsync(string name, string value) => js.InvokeAsync(Prefix + "prefSet", name, value); + 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); diff --git a/src/Covenant.Ui/Services/PlaygroundState.cs b/src/Covenant.Ui/Services/PlaygroundState.cs index 7b3d780..177923c 100644 --- a/src/Covenant.Ui/Services/PlaygroundState.cs +++ b/src/Covenant.Ui/Services/PlaygroundState.cs @@ -88,6 +88,17 @@ public PlaygroundState(AppState state, ConsoleInferenceApi inference, EvidenceTr /// Note from the last preset application ("No profile with a Public baseline …"), or null. public string? PresetNote { get; private set; } + /// Browser-local preference (Settings → Console preferences): the response mode a fresh form starts with. + public bool StreamingDefault { get; private set; } = true; + + /// Applies the stored preference to the default and to the form while it holds no request yet. + public void SetStreamingDefault(bool streaming) + { + StreamingDefault = streaming; + if (!Running && string.IsNullOrEmpty(Form.Prompt)) Form.Streaming = streaming; + Notify(); + } + public string? Problem => ComposerRules.Problem(Form, _workspace.Applications); public bool CanRun => !Running && Problem is null; @@ -280,6 +291,7 @@ private void Clear() _runs.Clear(); Selected = null; Form.Clear(); + Form.Streaming = StreamingDefault; PresetNote = null; _sequence = 0; Notify(); diff --git a/src/Covenant.Ui/Services/RequestsViewState.cs b/src/Covenant.Ui/Services/RequestsViewState.cs index cc01ae1..8151851 100644 --- a/src/Covenant.Ui/Services/RequestsViewState.cs +++ b/src/Covenant.Ui/Services/RequestsViewState.cs @@ -3,11 +3,14 @@ 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). +/// Requests browser state that survives navigation: the loaded pages of ONE audit segment (current or an +/// archived one), the cursor for the next older page, the filters and the selected request. Cleared on disconnect. +/// Holds audit records only (no response text). Loading is bounded (). public sealed class RequestsViewState : IDisposable { - public const int SnapshotLimit = 500; + public const int PageSize = 200; + /// Upper bound of records held in the browser; beyond it the operator opens a request by id or narrows the segment. + public const int MaxLoaded = 2000; private readonly AppState _state; @@ -17,18 +20,52 @@ public RequestsViewState(AppState state) _state.Disconnected += Clear; } - public RequestsResponse? Snapshot { get; set; } + /// Segment id requested (null = current segment). + public string? SegmentId { get; set; } + public SegmentInfo? Segment { get; set; } + public List Items { get; } = []; + public string? NextCursor { get; set; } + public bool Loaded { get; set; } public DateTimeOffset? LoadedUtc { get; set; } + + public List? Segments { get; set; } + public string? SegmentsError { 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() + /// Starts over for a (possibly different) segment. + public void ResetPages(string? segmentId) { - Snapshot = null; + SegmentId = segmentId; + Segment = null; + Items.Clear(); + NextCursor = null; + Loaded = false; LoadedUtc = null; + } + + /// Appends a page, de-duplicating by id (a cursor page may overlap after new writes). + public int AddPage(IEnumerable page) + { + var seen = new HashSet(Items.Select(i => i.Id), StringComparer.Ordinal); + int added = 0; + foreach (var r in page) + { + if (Items.Count >= MaxLoaded) break; + if (seen.Add(r.Id)) { Items.Add(r); added++; } + } + return added; + } + + private void Clear() + { + ResetPages(null); + Segments = null; + SegmentsError = null; Criteria = RequestFilterCriteria.None; SelectedId = null; SelectedRecord = null; diff --git a/src/Covenant.Ui/wwwroot/css/app.css b/src/Covenant.Ui/wwwroot/css/app.css index 3208ae1..e77557f 100644 --- a/src/Covenant.Ui/wwwroot/css/app.css +++ b/src/Covenant.Ui/wwwroot/css/app.css @@ -494,3 +494,100 @@ details.tech[open] > summary { margin-bottom: 6px; } .nav-spacer { display: none; } .nav-session { flex-direction: row; align-items: center; border-top: 0; margin: 0; padding: 4px 8px; } } + +/* ---- T08: editors, impact preview, connections, policies, budgets, evidence ---- */ +.editor-bar { gap: 10px; padding: 12px 16px; } +.editor-bar.editing { border-color: var(--accent); } +.editor-row { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px 16px; } +.editor-state { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; min-width: 0; } +.version-chip { font-size: var(--text-secondary); font-weight: 600; padding: 2px 10px; border: 1px solid var(--border); border-radius: 999px; background: var(--surface2); white-space: nowrap; } +.edit-flag { font-size: var(--text-secondary); font-weight: 600; color: var(--accent); } +.edit-flag.dirty { color: var(--amber); } +.version-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; } +.version-list li { display: flex; flex-direction: column; gap: 4px; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--radius-inner); } +.version-list li.active { border-color: var(--green); } +.version-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; } +.confirm-inline { display: flex; flex-direction: column; gap: 8px; padding: 10px; border: 1px solid var(--amber); border-radius: var(--radius-control); background: var(--amber-bg); } + +.impact { display: flex; flex-direction: column; gap: 10px; border-top: 1px solid var(--border); padding-top: 10px; } +.impact-head { display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: baseline; } +.impact-block { display: flex; flex-direction: column; gap: 6px; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--radius-inner); } +.impact-block.bad { border-color: var(--red); background: var(--red-bg); } +.impact-block.bad > strong { color: var(--red); } +.impact-block.warn { border-color: var(--amber); } +.impact-list { font-size: var(--text-secondary); display: flex; flex-wrap: wrap; gap: 4px 8px; } +.impact-list.bad strong { color: var(--red); } +.impact-list.warn strong { color: var(--amber); } +.warn-text { color: var(--amber); } +.bad-text { color: var(--red); } +.field-issues { display: flex; flex-direction: column; gap: 2px; } +.help.warn, .field .help.warn { color: var(--amber); } +.help.bad { color: var(--red); font-size: var(--text-secondary); } + +.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px 16px; align-items: start; } +.static-value { min-height: var(--target-form); display: flex; align-items: center; overflow-wrap: anywhere; } +.field.narrow { flex: 0 1 200px; } +.conn-form { display: flex; flex-direction: column; gap: 14px; } +.conn-form fieldset, .inline-fieldset { border: 1px solid var(--border); border-radius: var(--radius-inner); padding: 12px 14px; margin: 0; display: flex; flex-direction: column; gap: 10px; min-width: 0; } +.conn-form legend { font-weight: 600; padding: 0 4px; } +.inline-fieldset { flex-direction: row; flex-wrap: wrap; gap: 8px 16px; } +.model-rows { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; } +.model-rows li { display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: center; padding: 8px 10px; border: 1px solid var(--border); border-radius: var(--radius-control); } +.model-rows li.selected { border-color: var(--accent); } +.model-pick { display: inline-flex; align-items: center; gap: 8px; min-height: 32px; min-width: 0; } +.price-grid { flex-basis: 100%; display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 8px 12px; align-items: end; } +.problem-list li { color: var(--amber); } + +.conn-list { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 520px), 1fr)); gap: 12px; } +.conn-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-panel); padding: 14px 16px; display: flex; flex-direction: column; gap: 10px; min-width: 0; } +.conn-card.disabled { opacity: .8; border-style: dashed; } +.conn-head, .policy-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; } +.conn-icon { display: inline-flex; width: 32px; height: 32px; align-items: center; justify-content: center; border-radius: var(--radius-control); background: var(--surface2); } +.conn-title { display: flex; flex-direction: column; flex: 1 1 200px; min-width: 0; } +.inline-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; } + +.route-view { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; } +.route-row { display: grid; grid-template-columns: minmax(140px, 220px) auto minmax(0, 1fr); grid-template-areas: "scope arrow targets" "meta meta meta"; gap: 4px 10px; align-items: center; padding: 10px 12px; border: 1px solid var(--border); border-left: 4px solid var(--accent); border-radius: var(--radius-inner); background: var(--surface2); } +.route-row.state-paused { border-left-color: var(--amber); } +.route-row.state-unknown { border-left-color: var(--subtle); opacity: .85; } +.route-scope { grid-area: scope; font-weight: 600; overflow-wrap: anywhere; } +.route-arrow { grid-area: arrow; color: var(--subtle); } +.route-targets { grid-area: targets; display: flex; flex-wrap: wrap; gap: 6px; min-width: 0; } +.route-meta { grid-area: meta; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.route-chip { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; padding: 4px 10px; border-radius: var(--radius-control); border: 1px solid var(--border); background: var(--surface); font-size: var(--text-secondary); min-width: 0; } +.route-chip.local { border-color: var(--local); } +.route-chip.cloud { border-color: var(--cloud); } +.route-chip.excluded { border-style: dashed; color: var(--muted); } +.route-chip.refused { border-color: var(--amber); color: var(--amber); font-weight: 600; } +.route-role { font-size: 12px; color: var(--subtle); text-transform: uppercase; letter-spacing: .03em; } +.route-why { font-size: 12px; color: var(--amber); } +.summary-lines li { overflow-wrap: anywhere; } +.pause-explain { display: flex; flex-direction: column; gap: 4px; padding: 10px 18px; border-bottom: 1px solid var(--border); color: var(--muted); } +.policy-list { list-style: none; margin: 0; padding: 0; } +.policy-item { display: flex; flex-direction: column; gap: 10px; padding: 14px 18px; border-bottom: 1px solid var(--border); } +.policy-item:last-child { border-bottom: 0; } +.target-table td, .target-table th { padding: 6px 10px; } +.row-actions { white-space: nowrap; } +.row-actions .btn { margin-right: 4px; } +.policy-edit { display: flex; flex-direction: column; gap: 10px; } +.sim-result { display: flex; flex-direction: column; gap: 10px; border-top: 1px solid var(--border); padding-top: 10px; } +.state-text.s-skipped { color: var(--muted); } + +.budget-table td { vertical-align: top; } +.budget-table .meter { margin-top: 6px; min-width: 80px; } +.budget-edit-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; } +.budget-edit-list li { display: flex; flex-direction: column; gap: 8px; padding: 12px; border: 1px solid var(--border); border-radius: var(--radius-inner); } + +.segment-field { flex: 0 1 280px; min-width: 200px; } +.decision-list { list-style: none; margin: 0; padding: 0; } +.decision-list li { display: flex; flex-direction: column; gap: 6px; padding: 12px 18px; border-bottom: 1px solid var(--border); } +.decision-list li:last-child { border-bottom: 0; } +.decision-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; } +.facts.compact { gap: 4px 14px; } +.panel.integrity.bad { border-color: var(--red); background: var(--red-bg); } +.panel.maintenance { border-color: var(--amber); } +details.panel > summary { cursor: pointer; font-weight: 600; min-height: 32px; display: flex; align-items: center; } +@media (max-width: 640px) { + .route-row { grid-template-columns: minmax(0, 1fr); grid-template-areas: "scope" "targets" "meta"; } + .route-arrow { display: none; } +} diff --git a/src/Covenant.Ui/wwwroot/js/interop.js b/src/Covenant.Ui/wwwroot/js/interop.js index 0972345..3183fbe 100644 --- a/src/Covenant.Ui/wwwroot/js/interop.js +++ b/src/Covenant.Ui/wwwroot/js/interop.js @@ -1,12 +1,14 @@ // 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 +// Storage rules (TASK 01, T08): localStorage holds ONLY the theme choice and the allow-listed console +// preferences in PREF_KEYS (browser-local presentation defaults; never credentials or server configuration). 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"; + var PREF_KEYS = { "stream-default": true }; function applyTheme(theme) { var t = theme === "light" ? "light" : "dark"; @@ -46,6 +48,15 @@ return t; }, + prefGet: function (name) { + if (!PREF_KEYS[name]) return null; + try { return window.localStorage.getItem("covenant.pref." + name); } catch (e) { return null; } + }, + prefSet: function (name, value) { + if (!PREF_KEYS[name]) return false; + try { window.localStorage.setItem("covenant.pref." + name, String(value)); return true; } catch (e) { return false; } + }, + focusElement: function (id) { var el = document.getElementById(id); if (el && typeof el.focus === "function") { el.focus(); return true; } diff --git a/tests/Covenant.Tests/ConsoleLogicTests.cs b/tests/Covenant.Tests/ConsoleLogicTests.cs index 73ebc92..38f545b 100644 --- a/tests/Covenant.Tests/ConsoleLogicTests.cs +++ b/tests/Covenant.Tests/ConsoleLogicTests.cs @@ -354,7 +354,7 @@ 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.003 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())); @@ -1168,45 +1168,6 @@ public void Normalize_matches_the_catalog_shape(string raw, string expected) public void Authority_is_host_and_port() => Assert.Equal("ollama-host:11434", ConnectionLogic.Authority("http://ollama-host:11434/v1")); - private static CatalogResponse Catalog(string? endpoint, string? model, bool registered, bool configured = true) => new() - { - 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()); @@ -1254,3 +1215,707 @@ public void Launch_link_credentials_expose_no_application_key() Assert.DoesNotContain("secret-app-key", c!.ToString(), StringComparison.Ordinal); } } + +// ---- T08: editable admin pages and evidence workflows ---- + +internal static class Cfg +{ + /// A small hybrid configuration: local Ollama + cloud OpenAI, Public → cloud with local fallback, + /// Internal → local, PII/PHI → local. + public static CovenantConfigDto Hybrid() => new() + { + Version = 3, + Origin = "console", + CreatedUtc = new DateTimeOffset(2026, 10, 16, 9, 0, 0, TimeSpan.Zero), + Mode = "hybrid", + Connections = + [ + new ConnectionDto + { + Id = "ollama", DisplayName = "Ollama", Kind = "Ollama", Boundary = "Local", Endpoint = "http://ollama-host:11434/v1", Enabled = true, + Models = [new ModelDto { ModelId = "qwen2.5-coder:7b", Price = new PriceDto { InputPer1M = 0m, OutputPer1M = 0m, Basis = "zero-marginal-local" } }], + }, + new ConnectionDto + { + Id = "openai", DisplayName = "OpenAI", Kind = "OpenAi", Boundary = "Cloud", Enabled = true, SecretRef = "Secrets:openai", + Models = [new ModelDto { ModelId = "gpt-4o-mini", Price = new PriceDto { InputPer1M = 0.15m, OutputPer1M = 0.60m, Basis = "provider-list" } }], + }, + ], + Policies = + [ + new PolicyDto + { + Id = "public", Name = "Public", Enabled = true, Classifications = ["Public"], Strategy = "fixed", + Targets = [new PolicyTargetDto { ConnectionId = "openai", ModelId = "gpt-4o-mini" }, new PolicyTargetDto { ConnectionId = "ollama", ModelId = "qwen2.5-coder:7b" }], + }, + new PolicyDto + { + Id = "internal", Name = "Internal", Enabled = true, Classifications = ["Internal"], Strategy = "fixed", + Targets = [new PolicyTargetDto { ConnectionId = "ollama", ModelId = "qwen2.5-coder:7b" }], + }, + new PolicyDto + { + Id = "sensitive", Name = "PII/PHI", Enabled = true, Classifications = ["Pii", "Phi"], Strategy = "fixed", + Targets = [new PolicyTargetDto { ConnectionId = "ollama", ModelId = "qwen2.5-coder:7b" }], + }, + ], + Budgets = [new BudgetConfigDto { Id = "global", Scope = "global", CapUsd = 25m, Period = "monthly", WarnAt = [0.8m, 0.95m], Enforcement = "hard" }], + Settings = new OperationalSettingsDto { CacheTtlSeconds = 300, CacheMaxEntries = 1000, PromptPreviewChars = 0, TraceRetentionMinutes = 10 }, + }; +} + +public sealed class MoneyTests +{ + [Theory] + [InlineData("0.000184", "$0.000184")] + [InlineData("0.0012", "$0.0012")] + [InlineData("0.003", "$0.003")] + [InlineData("0.00012345", "$0.000123")] + [InlineData("0.0123", "$0.0123")] + [InlineData("0.5", "$0.50")] + [InlineData("1.234", "$1.23")] + [InlineData("1234.5", "$1,234.50")] + [InlineData("0", "$0.00")] + [InlineData("-1.23", "-$1.23")] + [InlineData("-0.000184", "-$0.000184")] + [InlineData("0.0000001", "<$0.000001")] + public void Usd_uses_significant_digits_for_tiny_amounts(string value, string expected) + => Assert.Equal(expected, Money.Usd(decimal.Parse(value, System.Globalization.CultureInfo.InvariantCulture))); + + [Theory] + [InlineData("0.000184")] + [InlineData("0.0000049")] + [InlineData("0.004999")] + [InlineData("0.0000000001")] + public void A_non_zero_charge_is_never_rendered_as_zero(string value) + { + var text = Money.Usd(decimal.Parse(value, System.Globalization.CultureInfo.InvariantCulture)); + Assert.NotEqual("$0.00", text); + Assert.NotEqual("$0", text); + Assert.DoesNotContain("$0.00 ", text + " ", StringComparison.Ordinal); + } + + [Fact] + public void Null_is_not_reported_and_never_zero() + { + Assert.Equal("Not reported", Money.Usd((decimal?)null)); + Assert.Equal("$0.15", Money.Usd((decimal?)0.15m)); + Assert.Equal("Unpriced", Money.PerMillion(null)); + Assert.Equal("$0.15 / 1M", Money.PerMillion(0.15m)); + Assert.Equal("Unpriced — cost unknown, not zero", Money.Price(0.15m, null)); + Assert.Equal("$0 provider charge (infrastructure excluded)", Money.Price(0m, 0m)); + Assert.Equal("in $0.15 · out $0.60 per 1M tokens", Money.Price(0.15m, 0.60m)); + } + + [Fact] + public void Caps_have_two_decimals_and_tiny_caps_stay_visible() + { + Assert.Equal("$250.00", Money.Cap(250m)); + Assert.Equal("$0.00", Money.Cap(0m)); + Assert.Equal("$0.005", Money.Cap(0.005m)); + Assert.Equal("62%", Money.Share(6.2m, 10m)); + Assert.Equal("n/a", Money.Share(1m, 0m)); + } + + [Fact] + public void Cost_text_now_uses_significant_digits() + => Assert.Equal("$0.000184 (estimated provider charge)", CostText.Cost(Rec.V2(costBasis: "reported", cost: 0.000184m))); +} + +public sealed class ConfigDraftTests +{ + [Fact] + public void Draft_is_a_deep_copy_and_never_aliases_the_applied_configuration() + { + var applied = Cfg.Hybrid(); + var session = new ConfigDraft(3, "\"v3\"", applied); + + session.Draft.Policies[0].Targets.Add(new PolicyTargetDto { ConnectionId = "x", ModelId = "y" }); + session.Draft.Connections[0].Models[0].Price!.InputPer1M = 9m; + session.Draft.Settings!.CacheTtlSeconds = 1; + + Assert.Equal(2, applied.Policies[0].Targets.Count); + Assert.Equal(0m, applied.Connections[0].Models[0].Price!.InputPer1M); + Assert.Equal(300, applied.Settings!.CacheTtlSeconds); + Assert.Equal(2, session.Base.Policies[0].Targets.Count); + Assert.NotSame(applied.Policies[0].Targets, session.Draft.Policies[0].Targets); + } + + [Fact] + public void Dirty_tracking_follows_content_not_touches() + { + var session = new ConfigDraft(3, null, Cfg.Hybrid()); + Assert.False(session.IsDirty); + Assert.Equal("\"v3\"", session.BaseEtag); + + session.Draft.Policies[0].Paused = true; + Assert.True(session.IsDirty); + session.Draft.Policies[0].Paused = false; + Assert.False(session.IsDirty); // toggled back: nothing to save + + Assert.True(PolicyRoutes.MoveDown(session.Draft.Policies[0].Targets, 0)); + Assert.True(session.IsDirty); // order is content + session.Reset(); + Assert.False(session.IsDirty); + Assert.Equal("openai", session.Draft.Policies[0].Targets[0].ConnectionId); + } + + [Fact] + public void Change_summary_names_what_changed_without_values() + { + var before = Cfg.Hybrid(); + var after = ConfigCopy.Deep(before); + after.Mode = "local-only"; + after.Connections[1].Enabled = false; + after.Budgets.Add(new BudgetConfigDto { Id = "team-risk", Scope = "team:risk", CapUsd = 5m }); + after.Policies.RemoveAt(2); + PolicyRoutes.MoveDown(after.Policies[0].Targets, 0); + + var lines = ChangeSummary.Lines(before, after); + Assert.Contains("mode hybrid → local-only", lines); + Assert.Contains("connection openai changed", lines); + Assert.Contains("budget team-risk added", lines); + Assert.Contains("policy sensitive removed", lines); + Assert.Contains("policy public changed", lines); + Assert.DoesNotContain(lines, l => l.Contains("Secrets:", StringComparison.Ordinal)); + Assert.StartsWith("Console: ", ChangeSummary.Text(before, after), StringComparison.Ordinal); + Assert.Equal("Console: no effective change", ChangeSummary.Text(before, ConfigCopy.Deep(before))); + } +} + +public sealed class EditOutcomeTests +{ + [Fact] + public void Only_a_2xx_with_a_version_is_success() + { + var ok = EditOutcomes.FromResponse(200, "{\"version\":8,\"etag\":\"\\\"v8\\\"\"}"); + Assert.Equal(EditOutcomeKind.Applied, ok.Kind); + Assert.True(ok.Succeeded); + Assert.Equal(8, ok.Version); + Assert.Equal("Applied version v8", ok.Message); + + Assert.Equal("Rollback applied as new version v9", EditOutcomes.FromResponse(200, "{\"version\":9}", rollback: true).Message); + + var noVersion = EditOutcomes.FromResponse(200, "{}"); + Assert.Equal(EditOutcomeKind.Failed, noVersion.Kind); + Assert.False(noVersion.Succeeded); + Assert.False(EditOutcomes.FromResponse(200, "not json").Succeeded); + } + + [Fact] + public void Stale_edit_412_keeps_the_draft_and_names_the_new_version() + { + var stale = EditOutcomes.FromResponse(412, "{\"error\":\"stale\",\"reason\":\"the active configuration is v8\",\"active_version\":8}"); + Assert.Equal(EditOutcomeKind.Stale, stale.Kind); + Assert.Equal(8, stale.Version); + Assert.StartsWith("Configuration changed since you started editing (now v8).", stale.Message, StringComparison.Ordinal); + Assert.Contains("kept", stale.Message, StringComparison.Ordinal); + Assert.False(stale.Succeeded); + + Assert.Equal(EditOutcomeKind.Stale, EditOutcomes.FromResponse(409, "").Kind); + Assert.Equal("Configuration changed since you started editing. Your draft was not applied and is kept.", EditOutcomes.StaleMessage(null)); + } + + [Fact] + public void Validation_422_maps_errors_to_fields_and_reports_the_active_version_unchanged() + { + var body = "{\"error\":\"invalid_configuration\",\"active_version\":7,\"errors\":[{\"path\":\"connections[1].secret_ref\",\"code\":\"secret_unavailable\",\"message\":\"secret not set\"},{\"path\":\"policies[0].targets[1]\",\"code\":\"sensitive_cloud_target\",\"message\":\"cloud target for PII\"}],\"warnings\":[{\"path\":\"policies\",\"code\":\"no_route_for_classification\",\"message\":\"Phi has no route\"}]}"; + var invalid = EditOutcomes.FromResponse(422, body); + Assert.Equal(EditOutcomeKind.Invalid, invalid.Kind); + Assert.Equal(7, invalid.Version); + Assert.Equal(2, invalid.Errors!.Count); + Assert.Single(invalid.Warnings!); + Assert.Contains("active version is unchanged", invalid.Message, StringComparison.Ordinal); + + var index = new IssueIndex(invalid.Errors, invalid.Warnings!); + Assert.Single(index.ErrorsAt("connections[1]")); + Assert.Single(index.ErrorsAt("connections[1].secret_ref")); + Assert.Empty(index.ErrorsAt("connections[0]")); + Assert.True(index.HasErrorAt("policies[0]")); + Assert.Single(index.WarningsAt("policies")); + Assert.Single(index.Unclaimed(["connections[1]"])); + Assert.NotNull(IssueHelp.For("secret_unavailable")); + } + + [Theory] + [InlineData(428, EditOutcomeKind.PreconditionRequired)] + [InlineData(401, EditOutcomeKind.Unauthorized)] + [InlineData(404, EditOutcomeKind.NotFound)] + [InlineData(400, EditOutcomeKind.Failed)] + [InlineData(500, EditOutcomeKind.Failed)] + public void Other_answers_are_never_success(int status, EditOutcomeKind kind) + { + var o = EditOutcomes.FromResponse(status, "{\"error\":\"x\",\"reason\":\"y\"}"); + Assert.Equal(kind, o.Kind); + Assert.False(o.Succeeded); + Assert.Null(o.Errors); + } + + [Fact] + public void Issue_paths_match_on_member_and_element_boundaries_only() + { + Assert.True(IssueIndex.Under("connections[1]", "connections[1]")); + Assert.True(IssueIndex.Under("connections[1].endpoint", "connections[1]")); + Assert.True(IssueIndex.Under("connections[1].models[0].price", "connections[1].models[0]")); + Assert.False(IssueIndex.Under("connections[10].endpoint", "connections[1")); + Assert.False(IssueIndex.Under("connections[10]", "connections[1]")); + Assert.False(IssueIndex.Under("settings.cache_ttl_seconds_x", "settings.cache_ttl_seconds_")); + Assert.False(IssueIndex.Under(null, "settings")); + Assert.Equal("policies[2].targets[0]", IssueIndex.Target(2, 0)); + Assert.Equal("connections[0].models[1]", IssueIndex.Model(0, 1)); + Assert.Equal("settings.prompt_preview_chars", IssueIndex.Setting("prompt_preview_chars")); + } +} + +public sealed class ImpactTextTests +{ + private static ConfigImpactDto Impact() => new() + { + Classifications = + [ + new ConfigImpactRowDto { Classification = "Public", Profile = "*", Before = "openai/gpt-4o-mini", After = "ollama/qwen", Changed = true }, + new ConfigImpactRowDto { Classification = "Internal", Profile = "", Before = "ollama/qwen", After = "ollama/qwen", Changed = false }, + new ConfigImpactRowDto { Classification = "Pii", Profile = "customer", Before = "ollama/qwen", After = "refused: no eligible target" }, // no flag, text differs + ], + NewlyRefused = ["Pii/customer"], + PricingGaps = ["vllm/llama"], + }; + + [Fact] + public void Only_changed_routes_are_listed_with_refusals_marked() + { + var lines = ImpactText.ChangedRoutes(Impact()); + Assert.Equal(2, lines.Count); + Assert.Equal("Public", lines[0].Scope); + Assert.Equal("openai/gpt-4o-mini", lines[0].Before); + Assert.Equal("PII · profile customer", lines[1].Scope); + Assert.True(lines[1].NowRefused); + Assert.False(lines[1].WasRefused); + Assert.Empty(ImpactText.ChangedRoutes(null)); + } + + [Fact] + public void Headline_counts_each_kind_of_impact() + { + Assert.Equal("2 routes change · 1 newly refused · 1 pricing gap", ImpactText.Headline(Impact())); + Assert.Equal("No routing change for any classification or profile.", ImpactText.Headline(new ConfigImpactDto())); + Assert.StartsWith("Impact not computed", ImpactText.Headline(null), StringComparison.Ordinal); + Assert.True(ImpactText.NeedsAttention(Impact())); + Assert.False(ImpactText.NeedsAttention(new ConfigImpactDto())); + } +} + +public sealed class PolicyRoutesTests +{ + [Fact] + public void Summary_lines_state_the_effective_route_never_may_use() + { + var cfg = Cfg.Hybrid(); + Assert.Equal("Public → openai/gpt-4o-mini · fallback: ollama/qwen2.5-coder:7b", PolicyRoutes.SummaryLine(cfg.Policies[0], cfg)); + Assert.Equal("Internal → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[1], cfg)); + Assert.Equal("PII + PHI → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[2], cfg)); + foreach (var p in cfg.Policies) + Assert.DoesNotContain("may use", PolicyRoutes.SummaryLine(p, cfg), StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Paused_route_is_skipped_and_paused_policy_refuses() + { + var cfg = Cfg.Hybrid(); + cfg.Policies[0].Targets[0].Paused = true; + Assert.Equal("Public → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[0], cfg)); + Assert.Equal("route paused — skipped", PolicyRoutes.Targets(cfg.Policies[0], cfg)[0].ExcludedReason); + + cfg.Policies[0].Targets[1].Paused = true; + Assert.Equal("Public → refused (no eligible target)", PolicyRoutes.SummaryLine(cfg.Policies[0], cfg)); + + cfg.Policies[1].Paused = true; + Assert.Equal("Internal → refused (policy paused)", PolicyRoutes.SummaryLine(cfg.Policies[1], cfg)); + Assert.Equal("Paused — refuses its traffic", PolicyText.StateText(cfg.Policies[1])); + Assert.Contains(PolicyRoutes.RefusalConditions(cfg.Policies[1], cfg), l => l.Contains("paused", StringComparison.Ordinal)); + } + + [Fact] + public void Cloud_targets_are_never_eligible_or_offered_for_sensitive_policies_or_local_only() + { + var cfg = Cfg.Hybrid(); + cfg.Policies[2].Targets.Add(new PolicyTargetDto { ConnectionId = "openai", ModelId = "gpt-4o-mini" }); + var states = PolicyRoutes.Targets(cfg.Policies[2], cfg); + Assert.False(states[1].Eligible); + Assert.Contains("PII/PHI", states[1].ExcludedReason!, StringComparison.Ordinal); + + cfg.Policies[2].Targets.RemoveAt(1); + var options = PolicyRoutes.Options(cfg.Policies[2], cfg); + var cloud = Assert.Single(options); + Assert.Equal("openai/gpt-4o-mini", cloud.Value); + Assert.Equal(PolicyText.SensitiveNeverCloud, cloud.DisabledReason); + + cfg.Mode = "local-only"; + Assert.Equal("Internal → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[1], cfg)); + Assert.Equal("Public → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[0], cfg)); + Assert.NotNull(Assert.Single(PolicyRoutes.Options(cfg.Policies[1], cfg)).DisabledReason); + } + + [Fact] + public void Disabled_or_unknown_connections_and_unpermitted_models_are_excluded() + { + var cfg = Cfg.Hybrid(); + cfg.Connections[1].Enabled = false; + cfg.Policies[1].Targets.Add(new PolicyTargetDto { ConnectionId = "ghost", ModelId = "m" }); + cfg.Policies[1].Targets.Add(new PolicyTargetDto { ConnectionId = "ollama", ModelId = "not-permitted" }); + Assert.Equal("Public → ollama/qwen2.5-coder:7b · no fallback", PolicyRoutes.SummaryLine(cfg.Policies[0], cfg)); + var states = PolicyRoutes.Targets(cfg.Policies[1], cfg); + Assert.Contains("not configured", states[1].ExcludedReason!, StringComparison.Ordinal); + Assert.Contains("not permitted", states[2].ExcludedReason!, StringComparison.Ordinal); + Assert.Empty(PolicyRoutes.Options(cfg.Policies[0], cfg)); // disabled connection offers nothing; ollama already listed + } + + [Fact] + public void Length_heuristic_is_named_honestly_with_its_threshold() + { + var cfg = Cfg.Hybrid(); + var p = cfg.Policies[0]; + p.Strategy = "length-heuristic"; + p.ThresholdTokens = 750; + Assert.Equal("Length-based heuristic (threshold 750 tokens)", PolicyText.StrategyName(p)); + Assert.Equal("Public → ≤ 750 tokens: openai/gpt-4o-mini · above: ollama/qwen2.5-coder:7b", PolicyRoutes.SummaryLine(p, cfg)); + Assert.Equal("Fixed + fallback", PolicyText.StrategyName(cfg.Policies[1])); + } + + [Fact] + public void Fallback_reorder_moves_one_place_and_stops_at_the_ends() + { + var list = new List + { + new() { ConnectionId = "a", ModelId = "1" }, new() { ConnectionId = "b", ModelId = "2" }, new() { ConnectionId = "c", ModelId = "3" }, + }; + Assert.False(PolicyRoutes.MoveUp(list, 0)); + Assert.False(PolicyRoutes.MoveDown(list, 2)); + Assert.False(PolicyRoutes.MoveUp(list, 7)); + Assert.True(PolicyRoutes.MoveUp(list, 2)); + Assert.Equal(new[] { "a", "c", "b" }, list.Select(t => t.ConnectionId)); + Assert.True(PolicyRoutes.MoveDown(list, 0)); + Assert.Equal(new[] { "c", "a", "b" }, list.Select(t => t.ConnectionId)); + Assert.Equal("Primary", PolicyRoutes.RoleLabel(0)); + Assert.Equal("Fallback 2", PolicyRoutes.RoleLabel(2)); + } + + [Fact] + public void Hybrid_defaults_build_a_restrictive_draft_and_need_a_local_model() + { + var cfg = Cfg.Hybrid(); + cfg.Mode = "legacy-cloud"; + cfg.Policies = [new PolicyDto { Id = "legacy-general", Enabled = true, Classifications = ["Public", "Internal"], Targets = [new PolicyTargetDto { ConnectionId = "openai", ModelId = "gpt-4o-mini" }] }]; + Assert.True(PolicyRoutes.IsLegacy(cfg.Mode)); + + Assert.Null(HybridDefaults.ApplyTo(cfg)); + Assert.Equal("hybrid", cfg.Mode); + Assert.Equal(new[] { "public", "internal", "sensitive" }, cfg.Policies.Select(p => p.Id)); + Assert.Equal(new[] { "openai/gpt-4o-mini", "ollama/qwen2.5-coder:7b" }, cfg.Policies[0].Targets.Select(PolicyRoutes.Key)); + Assert.All(cfg.Policies.Skip(1), p => Assert.Equal(new[] { "ollama/qwen2.5-coder:7b" }, p.Targets.Select(PolicyRoutes.Key))); + Assert.Equal(new[] { "Pii", "Phi" }, cfg.Policies[2].Classifications); + + var noLocal = Cfg.Hybrid(); + noLocal.Connections.RemoveAt(0); + var before = ConfigCopy.Canonical(noLocal); + Assert.NotNull(HybridDefaults.ApplyTo(noLocal)); + Assert.Equal(before, ConfigCopy.Canonical(noLocal)); // untouched when it cannot comply + } +} + +public sealed class SegmentScopeTests +{ + [Fact] + public void Current_segment_is_explicit_then_by_id_then_first() + { + var a = new AuditSegmentDto { Id = "seg-2", Current = true }; + var b = new AuditSegmentDto { Id = "current" }; + var c = new AuditSegmentDto { Id = "2026-10-01" }; + Assert.True(SegmentScope.IsCurrent(a)); + Assert.True(SegmentScope.IsCurrent(b)); + Assert.False(SegmentScope.IsCurrent(new AuditSegmentDto { Id = "x", Current = false })); + var unflagged = new List { new() { Id = "live" }, c }; + Assert.True(SegmentScope.IsCurrent(unflagged[0], unflagged)); + Assert.False(SegmentScope.IsCurrent(c, unflagged)); + Assert.False(SegmentScope.IsCurrent(c, [b, c])); + } + + [Fact] + public void Labels_say_which_segment_and_that_filters_cover_only_loaded_records() + { + var first = new DateTimeOffset(2026, 10, 16, 9, 0, 0, TimeSpan.Zero); + Assert.Equal("Current segment · since 2026-10-16 09:00:00 UTC", SegmentScope.Label(new AuditSegmentDto { Id = "current", FirstUtc = first }, true)); + Assert.Equal("Archived segment Oct 1 · read-only", SegmentScope.Label(new AuditSegmentDto { Id = "a1", Label = "Oct 1" }, false)); + Assert.Equal("Archived · a1 (1,200 records)", SegmentScope.Option(new AuditSegmentDto { Id = "a1", Entries = 1200 }, false)); + + var cov = SegmentScope.Coverage("Current segment", 200, 1500, moreAvailable: true, filtersActive: true); + Assert.Contains("200 of 1,500 records loaded", cov, StringComparison.Ordinal); + Assert.Contains("Load older", cov, StringComparison.Ordinal); + Assert.Contains("only to these loaded records", cov, StringComparison.Ordinal); + Assert.DoesNotContain("all history", cov, StringComparison.OrdinalIgnoreCase); + Assert.Contains("not reachable", SegmentScope.Coverage("Current segment", 200, 1500, moreAvailable: false, filtersActive: false), StringComparison.Ordinal); + } + + [Theory] + [InlineData(false, null, true, EvidenceCompletenessState.Pending)] + [InlineData(false, true, false, EvidenceCompletenessState.Unavailable)] + [InlineData(true, true, false, EvidenceCompletenessState.Verified)] + [InlineData(true, false, false, EvidenceCompletenessState.Unverifiable)] + [InlineData(true, null, true, EvidenceCompletenessState.Recorded)] + public void Evidence_is_verified_only_when_present_in_a_verified_chain(bool found, bool? chainValid, bool pending, EvidenceCompletenessState expected) + { + var s = EvidenceCompleteness.State(found, chainValid, pending); + Assert.Equal(expected, s); + var (label, tone) = EvidenceCompleteness.Text(s); + Assert.Equal(expected == EvidenceCompletenessState.Verified, label.StartsWith("Audit integrity verified", StringComparison.Ordinal)); + Assert.Equal(expected == EvidenceCompletenessState.Verified, tone == "ok"); + } +} + +public sealed class BudgetTextTests +{ + [Fact] + public void Thresholds_parse_as_percentages_and_reject_garbage() + { + Assert.Equal(new[] { 0.8m, 0.95m }, BudgetText.ParseThresholds("95, 80")); + Assert.Equal(new[] { 0.5m }, BudgetText.ParseThresholds("50%")); + Assert.Empty(BudgetText.ParseThresholds("")!); + Assert.Null(BudgetText.ParseThresholds("0")); + Assert.Null(BudgetText.ParseThresholds("120")); + Assert.Null(BudgetText.ParseThresholds("eighty")); + Assert.Equal("80, 95", BudgetText.FormatThresholds([0.8m, 0.95m])); + Assert.Equal("80%, 95%", BudgetText.Thresholds([0.8m, 0.95m])); + } + + [Fact] + public void Server_states_are_worded_and_overrun_is_never_truncated() + { + Assert.Equal(("Cap reached — new paid work blocked", "bad"), BudgetText.Warning("exceeded")); + Assert.Equal("warn", BudgetText.Warning("critical").Tone); + Assert.Equal("Exceeded by $0.000184", BudgetText.Remaining(-0.000184m)); + Assert.Equal("$1.50", BudgetText.Remaining(1.5m)); + Assert.Equal("Monthly (UTC) · 2026-10", BudgetText.Period("monthly", "2026-10")); + Assert.Equal("Team risk", BudgetText.Scope("team:risk")); + Assert.Equal("Application demo-app", BudgetText.Scope("application:demo-app")); + Assert.Equal(100, BudgetText.MeterPercent(5m, 1m, 4m)); + Assert.Equal(100, BudgetText.MeterPercent(0.01m, 0m, 0m)); + Assert.Equal(25, BudgetText.MeterPercent(0.5m, 0.5m, 4m)); + Assert.StartsWith("Warn only", BudgetText.Enforcement("warn-only"), StringComparison.Ordinal); + } + + [Fact] + public void Local_only_zero_spend_is_detected_for_the_explanatory_empty_state() + { + Assert.True(BudgetText.NoSpendAnywhere([new BudgetStateDto { Id = "g", CapUsd = 10m }])); + Assert.False(BudgetText.NoSpendAnywhere([new BudgetStateDto { Id = "g", CapUsd = 10m, ReservedUsd = 0.0001m }])); + Assert.False(BudgetText.NoSpendAnywhere(null)); + } + + [Fact] + public void Contributing_requests_parse_leniently_and_unknown_shapes_are_null() + { + var arr = BudgetRequests.Parse("[{\"request_id\":\"req_1\",\"attempt_id\":\"a1\",\"amount_usd\":0.000184,\"ts_utc\":\"2026-10-16T09:00:00Z\"},{\"nope\":1}]"); + var one = Assert.Single(arr!); + Assert.Equal("req_1", one.RequestId); + Assert.Equal(0.000184m, one.AmountUsd); + Assert.Equal("a1", one.AttemptId); + Assert.NotNull(one.TimestampUtc); + + var wrapped = BudgetRequests.Parse("{\"items\":[{\"id\":\"req_2\",\"settled_usd\":1.5}]}"); + Assert.Equal("req_2", Assert.Single(wrapped!).RequestId); + Assert.Equal(1.5m, wrapped![0].AmountUsd); + + Assert.Null(BudgetRequests.Parse("{\"something\":true}")); + Assert.Null(BudgetRequests.Parse("not json")); + Assert.Null(BudgetRequests.Parse("")); + } +} + +public sealed class ConnectionFormTests +{ + private static readonly Dictionary Secrets = new() + { + ["Secrets:openai"] = new SecretAvailabilityDto { Available = true }, + ["Secrets:anthropic"] = new SecretAvailabilityDto { Available = false }, + }; + + [Fact] + public void Discovery_never_approves_and_local_prices_default_to_explicit_zero_marginal() + { + var f = ConnectionForm.NewOllama(["ollama"]); + Assert.Equal("ollama-2", f.Id); + f.Endpoint = "http://ollama-host:11434/v1"; + f.ApplyDiscovery(["qwen2.5-coder:7b", "llama3:8b"]); + Assert.Equal(2, f.Models.Count); + Assert.All(f.Models, m => Assert.False(m.Selected)); + Assert.All(f.Models, m => Assert.Equal(ConnectionForm.BasisLocal, m.Basis)); + Assert.All(f.Models, m => Assert.Equal(0m, m.InputPer1M)); + + Assert.Contains(f.Problems([], null), p => p.StartsWith("Select at least one", StringComparison.Ordinal)); + f.Models[1].Selected = true; + Assert.Empty(f.Problems(["ollama"], null)); + + var dto = f.ToConnection(); + var model = Assert.Single(dto.Models); // unselected tags are not saved + Assert.Equal("qwen2.5-coder:7b", model.ModelId); + Assert.Equal("zero-marginal-local", model.Price!.Basis); + Assert.Equal("Local", dto.Boundary); + Assert.Null(dto.SecretRef); + } + + [Fact] + public void Editing_prefills_actual_values_and_marks_what_the_endpoint_no_longer_reports() + { + var conn = Cfg.Hybrid().Connections[0]; + var f = ConnectionForm.FromConnection(conn); + Assert.False(f.IsNew); + Assert.Equal("http://ollama-host:11434/v1", f.Endpoint); + var row = Assert.Single(f.Models); + Assert.True(row.Selected); + Assert.True(row.Configured); + + f.ApplyDiscovery(["other:1b"]); + Assert.False(f.Models[0].ReportedByEndpoint); + Assert.False(f.Models[1].Selected); + Assert.Equal(0, f.SentIndex(f.Models[0])); + Assert.Null(f.SentIndex(f.Models[1])); + } + + [Fact] + public void Cloud_needs_prices_and_an_available_secret_reference() + { + var f = ConnectionForm.NewCloud("Anthropic", []); + Assert.Equal("Cloud", f.Boundary); + f.SetKind("OpenAi"); + Assert.Equal("Cloud", f.Boundary); + var m = f.AddModel("gpt-4o-mini"); + Assert.True(m.Selected); + Assert.False(m.Priced); + Assert.Null(m.InputPer1M); // cloud prices are never assumed + + var problems = f.Problems([], Secrets); + Assert.Contains(problems, p => p.Contains("never treated as $0", StringComparison.Ordinal)); + Assert.Contains(problems, p => p.StartsWith("Choose the server-side secret", StringComparison.Ordinal)); + + m.Priced = true; + Assert.Contains(f.Problems([], Secrets), p => p.Contains("enter both input and output prices", StringComparison.Ordinal)); + + m.InputPer1M = 0.15m; + m.OutputPer1M = 0.6m; + f.SecretRef = "Secrets:anthropic"; + Assert.Contains(f.Problems([], Secrets), p => p.Contains("not available on the server", StringComparison.Ordinal)); + f.SecretRef = "Secrets:openai"; + Assert.Empty(f.Problems([], Secrets)); + + m.Priced = false; + Assert.Contains(f.Problems([], Secrets), p => p.Contains("never treated as $0", StringComparison.Ordinal)); + Assert.Null(f.ToConnection().Models[0].Price); // unpriced stays unknown, never $0 + } + + [Fact] + public void Apply_to_draft_replaces_its_own_earlier_copy_even_after_an_id_change() + { + var draft = Cfg.Hybrid(); + var f = ConnectionForm.NewOllama(draft.Connections.Select(c => c.Id)); + f.Endpoint = "http://second:11434/v1"; + f.AddModel("phi3:mini"); + int i = f.ApplyTo(draft); + Assert.Equal(2, i); + f.Id = "ollama-b"; + Assert.Equal(2, f.ApplyTo(draft)); + Assert.Equal(new[] { "ollama", "openai", "ollama-b" }, draft.Connections.Select(c => c.Id)); + + var edit = ConnectionForm.FromConnection(draft.Connections[0]); + edit.Enabled = false; + Assert.Equal(0, edit.ApplyTo(draft)); + Assert.False(draft.Connections[0].Enabled); + Assert.Equal(3, draft.Connections.Count); + } + + [Fact] + public void Removing_a_routed_model_is_called_out_before_preview() + { + var cfg = Cfg.Hybrid(); + var f = ConnectionForm.FromConnection(cfg.Connections[0]); + f.Models[0].Selected = false; + Assert.Equal(new[] { "ollama/qwen2.5-coder:7b" }, f.RemovedModelsStillRouted(cfg)); + } + + [Theory] + [InlineData("Secrets:openai", true)] + [InlineData("OpenAI:ApiKey", true)] + [InlineData("Secrets:", false)] + [InlineData("Env:OPENAI", false)] + [InlineData("Secrets:bad name", false)] + public void Secret_references_are_restricted(string r, bool ok) => Assert.Equal(ok, ConnectionRules.IsValidSecretRef(r)); + + [Fact] + public void Connection_rules_helpers() + { + Assert.Equal("Secrets__openai", ConnectionRules.EnvVarFor("Secrets:openai")); + Assert.Equal("api.openai.com:443", ConnectionRules.AuthorityOf("OpenAi", null)); + Assert.Equal("host:8000", ConnectionRules.AuthorityOf("OpenAiCompatible", "http://host:8000/v1")); + Assert.False(ConnectionRules.IsValidId("has space")); + Assert.True(ConnectionRules.EndpointRequired("Ollama")); + Assert.False(ConnectionRules.EndpointRequired("Anthropic")); + } +} + +public sealed class ConnectionHealthTests +{ + private static readonly DateTimeOffset Now = new(2026, 10, 16, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public void A_newer_failure_wins_and_both_facts_are_stated() + { + var h = new ModelHealth { State = "failed", LastSuccessUtc = Now.AddMinutes(-30), LastFailureUtc = Now.AddMinutes(-2), LastError = "timeout" }; + var v = ConnectionHealth.Summarize(true, [h], null, null, null, Now); + Assert.Equal("bad", v.Tone); + Assert.Equal("Last governed call failed 2 min ago · last success 30 min ago", v.Summary); + Assert.Contains(v.Details, d => d.Label == "Last failed governed call" && d.Value.Contains("timeout", StringComparison.Ordinal)); + } + + [Fact] + public void A_reachable_probe_is_not_called_ready_when_no_call_succeeded() + { + var probe = new ProbeResponse { Allowed = true, Reachable = true, CheckedUtc = Now.AddSeconds(-5) }; + var v = ConnectionHealth.Summarize(true, [new ModelHealth { State = "unknown" }], probe, null, null, Now); + Assert.Equal("Endpoint reachable (probe 5 s ago) · no governed call observed yet", v.Summary); + Assert.DoesNotContain("ready", v.Summary, StringComparison.OrdinalIgnoreCase); + Assert.Equal("hollow", v.Tone); + Assert.Contains(v.Details, d => d.Label == "Last successful governed call" && d.Value == "None observed"); + } + + [Fact] + public void Probe_failure_disabled_and_unobserved_states() + { + var refused = new ProbeResponse { Allowed = false, Reachable = false }; + var v = ConnectionHealth.Summarize(true, [], refused, Now.AddMinutes(-1), null, Now); + Assert.Equal("bad", v.Tone); + Assert.Contains(v.Details, d => d.Value.Contains("not on the probe allow-list", StringComparison.Ordinal)); + + Assert.StartsWith("Disabled", ConnectionHealth.Summarize(false, [], null, null, null, Now).Summary, StringComparison.Ordinal); + Assert.StartsWith("Not observed yet", ConnectionHealth.Summarize(true, [], null, null, null, Now).Summary, StringComparison.Ordinal); + + var ok = ConnectionHealth.Summarize(true, [new ModelHealth { State = "ok", LastSuccessUtc = Now.AddHours(-3) }], null, null, + new ModelHealth { LastFailureUtc = Now.AddHours(-1), LastError = "refused" }, Now); + Assert.Equal("Last successful governed call 3 h ago", ok.Summary); // inference fact first; probe is a separate detail + Assert.Contains(ok.Details, d => d.Label == "Last endpoint probe" && d.Value.StartsWith("Failed", StringComparison.Ordinal)); + } +} + +public sealed class RequestFilterApplicationTests +{ + [Fact] + public void Application_filter_matches_v3_application_id_only() + { + var a = Rec.V2(); + a.ApplicationId = "demo-app"; + var legacy = Rec.Legacy(); + var c = RequestFilterCriteria.None with { Application = "DEMO-APP" }; + Assert.True(c.IsActive); + Assert.True(RequestFilter.Matches(a, c, DateTimeOffset.UtcNow)); + Assert.False(RequestFilter.Matches(legacy, c, DateTimeOffset.UtcNow)); + Assert.Equal(new[] { "demo-app" }, RequestFilter.Applications([a, legacy])); + } +} diff --git a/tests/Covenant.Tests/ContractRoundTripTests.cs b/tests/Covenant.Tests/ContractRoundTripTests.cs index 97cf98e..81b83c2 100644 --- a/tests/Covenant.Tests/ContractRoundTripTests.cs +++ b/tests/Covenant.Tests/ContractRoundTripTests.cs @@ -353,6 +353,262 @@ public void Console_put_body_never_carries_an_allow_sensitive_cloud_switch() Assert.False(p.TryGetProperty("allow_sensitive_cloud", out _)); } + // ---- T08 editors: every other DTO the console reads or writes on the config/simulate/catalog/archive paths ---- + + [Fact] + public void Validate_request_and_response_round_trip_with_impact_and_field_paths() + { + var cfg = Representative(ProviderMode.Hybrid); + var envelope = RoundTrip(cfg).Envelope; + + // console → Host: POST /admin/config/validate + var reqBody = JsonSerializer.Serialize(new UiModels.ConfigValidateRequestDto { BaseVersion = 7, Config = envelope.Config }, + UiModels.UiJsonContext.Default.ConfigValidateRequestDto); + var hostReq = JsonSerializer.Deserialize(reqBody, ConfigJsonContext.Default.ConfigValidateRequest); + Assert.Equal(7, hostReq!.BaseVersion); + Assert.Equal(JsonSerializer.Serialize(cfg, ConfigJsonContext.Default.CovenantConfig), + JsonSerializer.Serialize(hostReq.Config!, ConfigJsonContext.Default.CovenantConfig)); + + // Host → console: the validation result + var respBody = JsonSerializer.Serialize(new ConfigValidateResponse + { + Valid = false, + ActiveVersion = 7, + Errors = [new ConfigIssueView { Path = "connections[2].secret_ref", Code = "secret_unavailable", Message = "secret not set" }], + Warnings = [new ConfigIssueView { Path = "base_version", Code = "stale_base_version", Message = "edited from v6" }], + Impact = new ImpactView + { + Classifications = [new ImpactRowView { Classification = "Public", Profile = "public-tickets", Before = "openai/gpt-x-mini", After = "refused: no eligible target", Changed = true }], + ApplicationsAffected = ["demo-app"], + UnavailableDestinations = ["openai/gpt-x-mini"], + PricingGaps = ["vllm/llama-3.1-8b"], + NewlyRefused = ["Public/public-tickets"], + }, + }, ConfigJsonContext.Default.ConfigValidateResponse); + var ui = JsonSerializer.Deserialize(respBody, UiModels.UiJsonContext.Default.ConfigValidationResultDto)!; + Assert.False(ui.Valid); + Assert.Equal(7, ui.ActiveVersion); + Assert.Equal("connections[2].secret_ref", Assert.Single(ui.Errors).Path); + Assert.Equal("secret_unavailable", ui.Errors[0].Code); + Assert.Equal("stale_base_version", Assert.Single(ui.Warnings).Code); + var row = Assert.Single(ui.Impact!.Classifications); + Assert.True(row.Changed); + Assert.Equal("refused: no eligible target", row.After); + Assert.Equal(new[] { "demo-app" }, ui.Impact.ApplicationsAffected); + Assert.Equal(new[] { "openai/gpt-x-mini" }, ui.Impact.UnavailableDestinations); + Assert.Equal(new[] { "vllm/llama-3.1-8b" }, ui.Impact.PricingGaps); + Assert.Equal(new[] { "Public/public-tickets" }, ui.Impact.NewlyRefused); + Assert.Single(Covenant.Ui.Logic.ImpactText.ChangedRoutes(ui.Impact)); + } + + [Fact] + public void Host_write_answers_map_onto_console_outcomes() + { + string Error(int? active, bool withIssues) => JsonSerializer.Serialize(new ConfigErrorResponse + { + Error = withIssues ? "invalid_configuration" : "stale", + Reason = "x", + ActiveVersion = active, + Errors = withIssues ? [new ConfigIssueView { Path = "policies[0].targets[1]", Code = "sensitive_cloud_target", Message = "no" }] : null, + Warnings = withIssues ? [] : null, + }, ConfigJsonContext.Default.ConfigErrorResponse); + + var stale = Covenant.Ui.Logic.EditOutcomes.FromResponse(412, Error(8, withIssues: false)); + Assert.Equal(Covenant.Ui.Logic.EditOutcomeKind.Stale, stale.Kind); + Assert.Equal(8, stale.Version); + + var invalid = Covenant.Ui.Logic.EditOutcomes.FromResponse(422, Error(7, withIssues: true)); + Assert.Equal(Covenant.Ui.Logic.EditOutcomeKind.Invalid, invalid.Kind); + Assert.Equal("policies[0].targets[1]", Assert.Single(invalid.Errors!).Path); + + var ok = Covenant.Ui.Logic.EditOutcomes.FromResponse(200, + JsonSerializer.Serialize(new ConfigPutResponse { Version = 9, Etag = "\"v9\"" }, ConfigJsonContext.Default.ConfigPutResponse)); + Assert.True(ok.Succeeded); + Assert.Equal(9, ok.Version); + + var err = JsonSerializer.Deserialize(Error(8, withIssues: false), UiModels.UiJsonContext.Default.ConfigErrorResponseDto)!; + Assert.Equal("stale", err.Error); + Assert.Equal(8, err.ActiveVersion); + } + + [Fact] + public void Version_history_and_rollback_request_round_trip() + { + var history = JsonSerializer.Serialize(new List + { + new() { Version = 8, CreatedUtc = Created, Origin = "rollback", BaseVersion = 7, RolledBackFrom = 3, ChangeSummary = "rollback to v3", Active = true }, + new() { Version = 7, CreatedUtc = Created.AddMinutes(-5), Origin = "console", BaseVersion = 6, Active = false }, + }, ConfigJsonContext.Default.ListConfigVersionSummary); + var ui = JsonSerializer.Deserialize(history, UiModels.UiJsonContext.Default.ListConfigVersionDto)!; + Assert.Equal(new[] { 8, 7 }, ui.Select(v => v.Version)); + Assert.True(ui[0].Active); + Assert.Equal(3, ui[0].RolledBackFrom); + Assert.Equal("rollback", ui[0].Origin); + Assert.Equal(Created, ui[0].CreatedUtc); + Assert.Null(ui[1].RolledBackFrom); + + var body = JsonSerializer.Serialize(new UiModels.ConfigRollbackRequestDto { TargetVersion = 3, ExpectedActiveVersion = 8 }, + UiModels.UiJsonContext.Default.ConfigRollbackRequestDto); + var host = JsonSerializer.Deserialize(body, ConfigJsonContext.Default.ConfigRollbackRequest)!; + Assert.Equal(3, host.TargetVersion); + Assert.Equal(8, host.ExpectedActiveVersion); + } + + [Fact] + public void Simulator_request_with_a_draft_candidate_and_dry_run_response_round_trip() + { + var cfg = Representative(ProviderMode.Hybrid); + var envelope = RoundTrip(cfg).Envelope; + var body = JsonSerializer.Serialize(new UiModels.SimulateRequestDto + { + ApplicationId = "demo-app", ProfileId = "public-tickets", Prompt = "Priority: low", Model = "openai/gpt-x-mini", Config = envelope.Config, + }, UiModels.UiJsonContext.Default.SimulateRequestDto); + var host = JsonSerializer.Deserialize(body, ConfigJsonContext.Default.SimulateRequest)!; + Assert.Equal("demo-app", host.ApplicationId); + Assert.Equal("public-tickets", host.ProfileId); + Assert.Equal("openai/gpt-x-mini", host.Model); + Assert.Equal(JsonSerializer.Serialize(cfg, ConfigJsonContext.Default.CovenantConfig), + JsonSerializer.Serialize(host.Config!, ConfigJsonContext.Default.CovenantConfig)); + + // Without a draft the candidate is omitted (the Host simulates the active version). + var noDraft = JsonSerializer.Serialize(new UiModels.SimulateRequestDto { ApplicationId = "demo-app", Prompt = "x" }, UiModels.UiJsonContext.Default.SimulateRequestDto); + Assert.False(Wire(noDraft).TryGetProperty("config", out _)); + Assert.Null(JsonSerializer.Deserialize(noDraft, ConfigJsonContext.Default.SimulateRequest)!.Config); + + var resp = JsonSerializer.Serialize(new SimulateResponse + { + DryRun = true, ConfigVersion = 7, ApplicationId = "demo-app", Profile = "public-tickets", + Classification = "Pii", Baseline = "Public", DetectedSignal = "US SSN pattern", PolicyId = "sensitive", + Eligible = + [ + new SimulatedTarget { Target = "ollama/qwen3:8b", Boundary = "Local" }, + new SimulatedTarget { Target = "openai/gpt-x-mini", Boundary = "Cloud", ExcludedReason = "cloud destination for PII" }, + ], + Decision = "route", Primary = "ollama/qwen3:8b", Fallbacks = [], Reason = "allowed", Explanation = "PII → ollama/qwen3:8b", + }, ConfigJsonContext.Default.SimulateResponse); + var ui = JsonSerializer.Deserialize(resp, UiModels.UiJsonContext.Default.SimulateResponseDto)!; + Assert.True(ui.DryRun); + Assert.Equal(7, ui.ConfigVersion); + Assert.Equal("Pii", ui.Classification); + Assert.Equal("Public", ui.Baseline); + Assert.Equal("US SSN pattern", ui.DetectedSignal); + Assert.Equal("route", ui.Decision); + Assert.Equal("ollama/qwen3:8b", ui.Primary); + Assert.Equal(new[] { "Local", "Cloud" }, ui.Eligible.Select(e => e.Boundary)); + Assert.Null(ui.Eligible[0].ExcludedReason); + Assert.Equal("cloud destination for PII", ui.Eligible[1].ExcludedReason); + Assert.Equal("PII → ollama/qwen3:8b", ui.Explanation); + } + + [Fact] + public void Catalog_connections_carry_health_registration_and_allow_listing_to_the_console() + { + var ok = new HealthView { State = "ok", LastSuccessUtc = Created }; + var body = JsonSerializer.Serialize(new CatalogReport + { + Mode = "hybrid", + Models = [new CatalogModel { Adapter = "ollama", ModelId = "qwen3:8b", Classifications = ["Internal"], Registered = true, PriceBasis = "zero", Health = ok, ConnectionId = "ollama", Boundary = "Local", Key = "ollama:qwen3:8b" }], + Local = new LocalConfigView { Configured = true, Endpoint = "http://ollama-host:11434/v1", ModelId = "qwen3:8b", Registered = true, EndpointHealth = new HealthView { State = "failed", LastFailureUtc = Created, LastError = "refused" } }, + ProbeAllowList = ["ollama-host:11434"], + ConfigVersion = 7, + EgressAllowList = ["api.openai.com:443", "ollama-host:11434"], + Connections = + [ + new CatalogConnection + { + Id = "openai", DisplayName = "OpenAI", Kind = "OpenAi", Boundary = "Cloud", Enabled = true, Endpoint = null, EndpointAllowListed = true, + SecretRef = "Secrets:openai", SecretAvailable = false, + Models = [new CatalogConnectionModel { Key = "openai:gpt-x-mini", ModelId = "gpt-x-mini", Registered = false, PriceBasis = "configured", InPer1M = 0.15m, OutPer1M = 0.60m, Health = new HealthView { State = "unknown" } }], + }, + ], + }, CovenantJsonContext.Default.CatalogReport); + + var ui = JsonSerializer.Deserialize(body, UiModels.UiJsonContext.Default.CatalogResponse)!; + Assert.Equal(7, ui.ConfigVersion); + Assert.Equal(new[] { "api.openai.com:443", "ollama-host:11434" }, ui.EgressAllowList); + Assert.Equal("Local", ui.Models[0].Boundary); + Assert.Equal("ollama", ui.Models[0].ConnectionId); + Assert.Equal("ollama:qwen3:8b", ui.Models[0].Key); + Assert.Equal("refused", ui.Local!.EndpointHealth!.LastError); + var c = Assert.Single(ui.Connections!); + Assert.Equal("OpenAi", c.Kind); + Assert.Equal("Cloud", c.Boundary); + Assert.True(c.EndpointAllowListed); + Assert.False(c.SecretAvailable); + Assert.Equal("Secrets:openai", c.SecretRef); + var m = Assert.Single(c.Models); + Assert.False(m.Registered); + Assert.Equal(0.15m, m.InPer1M); + Assert.Equal("unknown", m.Health!.State); + } + + // T04/T06 read paths. These pin the backend's budget-ledger and audit-archive views (implemented concurrently with + // the console; see docs/console-v2-progress.md "T08 UI" — integration pending until those land and pass). + + [Fact] + public void Budget_state_and_contributions_reach_the_console() + { + var states = JsonSerializer.Serialize(new List + { + new() + { + Id = "global", Scope = "global", Period = "monthly", PeriodId = "2026-10", PeriodStartUtc = Created, PeriodEndUtc = Created.AddDays(16), + CapUsd = 25m, SpentUsd = 0.000184m, ReservedUsd = 0.0021m, RemainingUsd = 24.997716m, WarnAt = [0.8m, 0.95m], Warning = "none", Enforcement = "hard", + }, + }, CovenantJsonContext.Default.ListBudgetStateView); + var ui = Assert.Single(JsonSerializer.Deserialize(states, UiModels.UiJsonContext.Default.ListBudgetStateDto)!); + Assert.Equal("2026-10", ui.PeriodId); + Assert.Equal(0.000184m, ui.SpentUsd); + Assert.Equal(0.0021m, ui.ReservedUsd); + Assert.Equal(Created, ui.PeriodStartUtc); + Assert.Equal(new[] { 0.8m, 0.95m }, ui.WarnAt); + Assert.Equal("$0.000184", Covenant.Ui.Logic.Money.Usd(ui.SpentUsd)); + + var contributions = JsonSerializer.Serialize(new BudgetRequestsView + { + BudgetId = "global", Scope = "global", PeriodId = "2026-10", + Items = + [ + new BudgetContributionView { RequestId = "req_a", AttemptId = "att_2", Kind = "settle", AmountUsd = 0.000184m, TsUtc = Created, Overrun = true }, + new BudgetContributionView { RequestId = "req_b", AttemptId = "att_1", Kind = "settle-recovered", AmountUsd = 0.0021m, TsUtc = Created }, + ], + }, CovenantJsonContext.Default.BudgetRequestsView); + var rows = Covenant.Ui.Logic.BudgetRequests.Parse(contributions)!; + Assert.Equal(new[] { "req_a", "req_b" }, rows.Select(r => r.RequestId)); + Assert.Equal(0.000184m, rows[0].AmountUsd); + Assert.Equal("att_2", rows[0].AttemptId); + Assert.True(rows[0].Overrun); + Assert.Equal("settle-recovered", rows[1].Kind); + Assert.Equal(Created, rows[0].TimestampUtc); + } + + [Fact] + public void Audit_segments_and_cursor_pages_reach_the_console() + { + var segs = JsonSerializer.Serialize(new List + { + new() { Id = "current", Label = "Current", Current = true, Entries = 12, ChainValid = true, FirstUtc = Created }, + new() { Id = "a-0123456789abcdef", Label = "Archived 2026-10-01 09:00", Current = false, Entries = 40, Events = 2, ChainValid = true, ArchivedUtc = Created.AddDays(-15) }, + }, AuditJsonContext.Default.ListSegmentView); + var ui = JsonSerializer.Deserialize(segs, UiModels.UiJsonContext.Default.ListAuditSegmentDto)!; + Assert.True(Covenant.Ui.Logic.SegmentScope.IsCurrent(ui[0], ui)); + Assert.False(Covenant.Ui.Logic.SegmentScope.IsCurrent(ui[1], ui)); + Assert.Equal(40, ui[1].Entries); + Assert.Equal(2, ui[1].Events); + Assert.NotNull(ui[1].ArchivedUtc); + + var page = JsonSerializer.Serialize(new RequestsPage + { + Segment = new SegmentInfo { Path = "/var/covenant/audit.jsonl", Entries = 40, ChainValid = true, Id = "a-0123456789abcdef", Label = "Archived 2026-10-01 09:00" }, + Items = [], + NextCursor = "opaque-token", + }, AuditJsonContext.Default.RequestsPage); + var uiPage = JsonSerializer.Deserialize(page, UiModels.UiJsonContext.Default.RequestsResponse)!; + Assert.Equal("a-0123456789abcdef", uiPage.Segment.Id); // the console refuses to label an unconfirmed segment + Assert.Equal("opaque-token", uiPage.NextCursor); + Assert.Equal(40, uiPage.Segment.Entries); + } + private static JsonElement Wire(string json) { using var doc = JsonDocument.Parse(json); From 1ad07c4cc8f034198f62a839bc09fb64fd6331b3 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Sat, 17 Oct 2026 09:55:04 -0400 Subject: [PATCH 09/14] =?UTF-8?q?fix(backend):=20review=20round=202=20?= =?UTF-8?q?=E2=80=94=20stream=20completion,=20cost=20basis,=20deadline,=20?= =?UTF-8?q?settlement,=20cache=20keys,=20team,=20early=20id,=20paging,=20l?= =?UTF-8?q?edger=20bootstrap/replay,=20health,=20bounds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit B1 incomplete streams fail (no fallback, never cached, partial kept); provider finish reason relayed; completed EMPTY streams are a 200 SSE success (no false 403) on both dialects; B2 'mixed' basis; B3 finite overall deadline; B4 finally-based exactly-once settlement; B5 length-prefixed cache identity incl. original params + every candidate bound, served provenance; B6 active app team on /v1; B7 submissions endpoint for early request id; B8 stable cursors + 410 on rotation; B9 atomic ledger bootstrap with marker; B10 replay validation; B11 runtime connection health; B12 requested vs effective output bounds; B13 NativeAOT blocker documented (not suppressed). Also qualifies Covenant.Governance.LedgerReplay.Validate (CS0104 with Host.LedgerReplay). --- ...ADR-0001-core-engine-and-provider-layer.md | 15 + docs/console-v2-progress.md | 51 +- docs/demo-runbook.md | 16 +- docs/ui-api-contract.md | 62 +- src/Covenant.Adapters/ProviderLayer.cs | 75 +- src/Covenant.Core/CanonicalModel.cs | 7 +- src/Covenant.Core/Decisions.cs | 12 +- src/Covenant.Core/Execution.cs | 39 +- src/Covenant.Core/InferenceContext.cs | 6 +- src/Covenant.Governance/Audit.cs | 12 +- src/Covenant.Governance/Auth.cs | 5 + src/Covenant.Governance/BudgetGate.cs | 86 +- src/Covenant.Governance/BudgetLedger.cs | 139 ++- src/Covenant.Governance/Cache.cs | 114 ++- src/Covenant.Host/AuditSegments.cs | 73 +- src/Covenant.Host/BudgetLedgerStore.cs | 165 ++- src/Covenant.Host/ConsoleBackend.cs | 20 + src/Covenant.Host/InferenceEndpoints.cs | 73 +- src/Covenant.Host/Program.cs | 97 +- src/Covenant.Host/StatusContracts.cs | 4 +- src/Covenant.Host/Trace.cs | 53 + tests/Covenant.Tests/AccountingTests.cs | 1 + tests/Covenant.Tests/ConfigV2TestKit.cs | 1 + .../Covenant.Tests/ConsolePlaygroundTests.cs | 7 +- .../CorrelationAndEvidenceTests.cs | 1 + tests/Covenant.Tests/PipelineSliceTests.cs | 3 +- tests/Covenant.Tests/ReviewRound2Tests.cs | 949 ++++++++++++++++++ tests/Covenant.Tests/RuntimeV2TestKit.cs | 38 +- tests/Covenant.Tests/ServedPathTests.cs | 1 + tests/Covenant.Tests/WireShapeTests.cs | 2 +- 30 files changed, 1951 insertions(+), 176 deletions(-) create mode 100644 tests/Covenant.Tests/ReviewRound2Tests.cs diff --git a/docs/adr/ADR-0001-core-engine-and-provider-layer.md b/docs/adr/ADR-0001-core-engine-and-provider-layer.md index a8b5efe..376fc6f 100644 --- a/docs/adr/ADR-0001-core-engine-and-provider-layer.md +++ b/docs/adr/ADR-0001-core-engine-and-provider-layer.md @@ -38,3 +38,18 @@ Patterns we **study as influences** (logged in `docs/PROVENANCE.md`; not code we ## Follow-ups - **Spike:** NativeAOT vs self-contained single-file publish for the required connectors (feeds `deploy/`, may warrant its own ADR). - **ADR-0002 candidate:** single-tenant vs multi-tenant control plane (already flagged in the PRD). + +## Status update 2026-10-17 — NativeAOT spike result +- **Result:** self-contained single-file publish (`PublishSingleFile=true`, `--self-contained`) is the **supported** + appliance artifact; it was verified on osx-arm64 (process start, `/ui` and framework assets served — see + `docs/verification-2026-10-16/v2/CODEX-REVIEW.txt`). This is the fallback this ADR anticipated and still satisfies + "one deployable". +- **NativeAOT is blocked by dependencies, not by our code:** an AOT publish emits **IL2104** ("assembly produced trim + warnings") and **IL3053** ("assembly produced AOT analysis warnings") for **Anthropic 12.8.0** (the Anthropic + connector) and **Neo4j.Driver 6.2.1** (the optional evidence-graph projector, ADR-0006). The warnings are **not + suppressed** and the artifact is **not** claimed AOT-verified. Our own projects keep `IsAotCompatible=true` and + source-generated JSON only, so the path stays honest. +- **What would unblock it:** (1) AOT/trim-clean releases of both libraries (re-run the publish; zero IL2104/IL3053), or + (2) an AOT-clean in-house `IChatClient` for Anthropic's Messages API (small, already-owned wire surface) and shipping + the Neo4j projector as a separate optional component outside the appliance binary; then (3) a CI gate on + `PublishAot=true` with warnings-as-errors. Until then `deploy/` targets the single-file artifact. diff --git a/docs/console-v2-progress.md b/docs/console-v2-progress.md index 1d0c8d3..afcde3f 100644 --- a/docs/console-v2-progress.md +++ b/docs/console-v2-progress.md @@ -655,9 +655,9 @@ None. No existing test file was edited. Behaviour changes that existing tests co 2. **Every request is traced** (`/v1` too), not only console requests — same bounded hub. 3. **Failed / cancelled attempts are charged their full reservation bound** (input bound + full output bound), the conservative "possibly billed" estimate the task specifies — higher than the pre-v2 chars/4 estimate. -4. **Deadline semantics:** no attempt starts after `deadline_ms`; an attempt still waiting for its response (or, streaming, - its first content) at the deadline is cancelled as `timeout`; once streamed content flows the deadline stops applying - (a delivered answer is not cut off; the connection timeout governs). +4. **Deadline semantics:** *superseded by review round 2 (B3)* — `deadline_ms` is one finite deadline for the whole + execution, also after streamed content: a hit after content ⇒ partial output kept + terminal failure `timeout`, no + fallback. (Originally: the deadline stopped applying once content flowed.) 5. **Cache key** includes the ordered approved candidate list (stricter than "connection + model": a response is reused only for the same eligible route set). Keyed on the primary's enforced output bound. 6. **Ledger file failure** halts the process (`Environment.FailFast`), consistent with the audit sink. @@ -893,3 +893,48 @@ Browser (isolated port, `Config:Seed=demo-hybrid` on a fresh `Audit:Path`; both - [ ] Every page: loading skeleton, error banner with Retry (stop the Host), empty states, disabled controls with reasons; keyboard-only: Tab through editor bar, drawers trap focus, Esc closes, focus returns to the opener. - [ ] No horizontal page scroll at 1280×720 / ~900 px; long model ids and errors wrap. + +## Review fixes round 2 (backend) — 2026-10-17 + +Source: `docs/verification-2026-10-16/v2/CODEX-REVIEW.txt` (+ `cache-collision-probe.cs.txt`/`.log`, `http-archive.log`). +Not compiled here (no SDK in this environment); every touched file was re-read. New tests: `tests/Covenant.Tests/ReviewRound2Tests.cs`. + +| # | Defect | Fix | Regression test(s) | +|---|---|---|---| +| B1 | Stream with partial text then EOF / swallowed SSE error served as Allow + `finish_reason:stop` | `ProviderCallStage`: a stream is served only if an update with non-null `FinishReason` was observed and no error; otherwise provider failure `incomplete_stream` (health failed, partial kept → audit `PartialOutputChars`, attempt settled at its estimate, terminal — no fallback, not cached). Buffered `Length` ⇒ served, `Attempts[].Truncated=true`. `InferenceResponse.FinishReason` (additive) relayed as the final SSE chunk's finish reason. | `StreamCompletionTests.*` (no-finish, throw mid-stream, `length` buffered+streamed, Host SSE: `upstream_error`, no `finish_reason:"stop"`) | +| B2 | Aggregate `CostBasis` "reported" for totals containing estimates | `CostBases.Aggregate` (Core) applied by the audit stage: reported only if every charged attempt is reported; shared basis kept; else `mixed`. FinOps counts `mixed` as estimated. | `AggregateCostBasisTests.*` | +| B3 | Deadline disabled after first streamed text | Removed `CancelAfter(Infinite)`; `deadline_ms` bounds the whole execution; a hit after content ⇒ `timeout`, partial kept, no fallback. Contract + note 4 above updated. | `DeadlineAfterContentTests.Deadline_after_streamed_content_is_a_timeout_with_partial_output_and_no_fallback` | +| B4 | Settlement not exception-safe; gate closed slot before durable write | Provider stage settles the served attempt in `finally` after downstream stages. `BudgetAttemptGate.Settle/Release` mark a slot closed only after the ledger write succeeded (in-flight flag, idempotent); `Finish` retries every open slot and rethrows the first failure. Production `FileLedgerStore` write failure still `FailFast`. | `SettlementRobustnessTests.*` (failed settle/release then retry, pipeline unwind retry, persistent failure → boot recovery settles once, exception after attribution) | +| B5 | Cache key delimiter collisions; bound/provenance | `CacheKeyBuilder`: SHA-256 over length-prefixed UTF-8 fields (presence byte + 4-byte BE length), message count + per-message role/content; identity = config version, application, team, profile, final classification, requested model + requested max_tokens (stream-independent), every candidate (connection, model, effective output bound) in order. Entry stores the ACTUAL served target; a hit sets `ServedTarget` → audit `ServedConnectionId`/`ServedByModel`. | `CacheKeyCollisionTests.*` (reviewer probe both cases, boundary shift, control chars, role, provenance of a fallback-served entry) | +| B6 | /v1 team from startup key vs console app team | `AuthStage`: with a configuration, identity team = active `ApplicationConfig.Team` (key only resolves the application). Ledger scopes captured at reservation keep history. | `TeamConsistencyTests.*` | +| B7 | Console request id only with first content | `client_request_id` REQUIRED (1–64 `[A-Za-z0-9_-]`); registered in `TraceHub` before the pipeline (trace TTL); `GET /admin/playground/submissions/{client_request_id}` → `{client_request_id, request_id, state}` / 404. | `EarlyRequestIdTests.*`; `ConsolePlaygroundTests.Invalid_body_*` (new rows); `Playground.Body` now always sends an id | +| B8 | Pagination duplicates after insert; rotation redirect | Cursor `c2` = {segment id, generation, absolute index from oldest (exclusive)}; newest-first by absolute index; generation mismatch/segment gone/legacy cursor ⇒ 410 `cursor_expired`; `segment.is_current` always present. | `StablePaginationTests.*` | +| B9 | Ledger created before legacy import (crash window) | `FileLedgerStore.Bootstrap`: legacy-import lines + `bootstrap-complete` marker → temp, fsync, rename. `LedgerBootstrap.OpenOrBootstrap` used by Program. A journal without the marker refuses start (pre-marker journals that already contain post-bootstrap operations are accepted once with a warning and get the marker appended). legacy-import idempotent per (legacy-import, team:x). `EnsureCreated` now writes a marker-only ledger atomically. | `LedgerBootstrapAndReplayTests.Fresh_bootstrap_*`, `Interruption_after_create_*`, `Partway_through_*`, `Interruption_before_the_rename_*`, `Duplicate_legacy_import_*`, `Pre_marker_journal_*` | +| B10 | Replay accepted unknown ops / negative amounts / bad lifecycle | `LedgerReplay.Validate` (vocabulary, amount ≥ 0, ids, scope syntax, timestamp, lifecycle, marker rules) run by `FileLedgerStore.Open` → refuse start with `line N is invalid: …`; `BudgetLedger` replay throws on unknown ops. Torn tail unchanged (quarantine + rewrite). | `LedgerBootstrapAndReplayTests.A_violation_in_a_non_tail_line_*` (16 rows), `Non_iso_timestamp_*`, `A_valid_full_lifecycle_*` | +| B11 | Header "local not yet observed" after a successful local call | `/admin/catalog.local` selects the observed/routed local connection (never shadowed by a legacy `local`), adds `connection_id` + `health` (runtime health of that `connection:model`); `/admin/status.connection_health[]`. | `LocalHealthTests.*` | +| B12 | Requested vs effective bound | Audit v3 `RequestedMaxOutputTokens`, `EffectiveMaxOutputTokens` (served attempt); `Attempts[].EffectiveMaxOutputTokens`; trace attempt events `requested_max_output_tokens` / `effective_max_output_tokens`. | `OutputBoundEvidenceTests.*`; `EarlyRequestIdTests` (trace fields) | +| B13 | NativeAOT IL2104/IL3053 (Anthropic 12.8.0, Neo4j.Driver 6.2.1) | Not suppressed. ADR-0001 "Status update 2026-10-17" + `docs/demo-runbook.md` §1a: supported artifact = self-contained single-file; unblock path listed. | — (docs) | + +Test-kit changes (not weakening): every streaming stub that represents a SUCCESSFUL stream now ends with a terminal +`FinishReason = Stop` update, as real providers do (`StubChatClient`, `GatedChatClient`, `ScriptedChatClient`, +`AccountingClient`, PipelineSlice/ServedPath/WireShape stubs). `StubChatClient` gains `StreamNoFinish`, `ServeLength`, +`Gated` modes. + +UI-facing contract changes (docs/ui-api-contract.md): `client_request_id` required + submissions endpoint; SSE terminal +failure semantics; deadline note; `incomplete_stream` reason/error class; trace attempt bound fields; `CostBasis` +`mixed`; audit v3 `RequestedMaxOutputTokens`/`EffectiveMaxOutputTokens`/`PartialOutputChars`/`ServedConnectionId`, +`Attempts[].EffectiveMaxOutputTokens`/`Truncated`; cursor v2 + 410 `cursor_expired` + `segment.is_current`; +`catalog.local.connection_id`/`health`, `status.connection_health`. + +### Verifier commands (not executed here) + +``` +dotnet build Covenant.sln -c Release --disable-build-servers +dotnet test tests/Covenant.Tests -c Release --disable-build-servers --filter "FullyQualifiedName~StreamCompletionTests|FullyQualifiedName~AggregateCostBasisTests|FullyQualifiedName~DeadlineAfterContentTests|FullyQualifiedName~SettlementRobustnessTests|FullyQualifiedName~CacheKeyCollisionTests|FullyQualifiedName~TeamConsistencyTests|FullyQualifiedName~EarlyRequestIdTests|FullyQualifiedName~StablePaginationTests|FullyQualifiedName~LedgerBootstrapAndReplayTests|FullyQualifiedName~LocalHealthTests|FullyQualifiedName~OutputBoundEvidenceTests" +dotnet test tests/Covenant.Tests -c Release --disable-build-servers # full suite (stream stubs, ledger, cache, paging regressions) +dotnet publish src/Covenant.Host -c Release -r osx-arm64 --self-contained true -p:PublishSingleFile=true +``` +Reviewer reproducers to re-run: `cache-collision-probe.cs.txt` (expect `calls=2`, `secondCacheHit=False` twice — the +probe source compiles unchanged); `ledger-migration-crash.py.txt` (empty/unmarked ledger ⇒ refuse start); HTTP archive +paging (page1 limit 2, insert, follow `next_cursor` ⇒ no duplicate); SDK stream partial-then-EOF against +`provider_stub.py` ⇒ SSE `upstream_error`, audit Deny/UpstreamFailure. diff --git a/docs/demo-runbook.md b/docs/demo-runbook.md index 51ade66..23d31a4 100644 --- a/docs/demo-runbook.md +++ b/docs/demo-runbook.md @@ -19,6 +19,20 @@ Optional: `Covenant:Environment` (header label, e.g. `vslive-demo`), `Providers: `Local:Endpoint` is as seen **from the Covenant host** (`http://localhost:11434/v1` only if Ollama runs on the same machine/container as Covenant). `Local:ModelId` is the exact installed tag (`ollama list`) — nothing guesses it. +## 1a. Supported artifact (2026-10-17) + +The supported appliance artifact is a **self-contained single-file publish** (one deployable, no runtime install): + +``` +dotnet publish src/Covenant.Host -c Release -r --self-contained true -p:PublishSingleFile=true +``` + +**NativeAOT is not supported yet.** An AOT publish reports IL2104 (trim analysis warnings inside the assembly) / +IL3053 (AOT analysis warnings inside the assembly) for **Anthropic 12.8.0** and **Neo4j.Driver 6.2.1**. These are not +suppressed and the build is not claimed AOT-verified. Unblocking needs an AOT-clean release of each library (or +replacing the Anthropic connector with an AOT-clean `IChatClient`, and moving the optional Neo4j projector out of the +appliance image), then a clean `PublishAot=true` run. See ADR-0001 "Status update 2026-10-17". + ## 2. Startup and preflight (before the audience arrives) ``` @@ -31,7 +45,7 @@ dotnet run --project src/Covenant.Host -c Release # or the published bina (first Ollama load can take 10–60 s; do it before the talk). 4. Evidence: chain "Internal consistency verified". If anchoring is configured, anchors written > 0. 5. Settings → note prompt retention (`prompt_preview_chars`). Do **not** use Maintenance → Archive & reset as - a demo step; it archives evidence and reopens budgets. + a demo step; it archives evidence (budgets are NOT reopened — the ledger is independent of audit segments). ## 3. The A / B / C / D sequence (Playground, optionally Presentation mode) diff --git a/docs/ui-api-contract.md b/docs/ui-api-contract.md index b2f8c60..616be23 100644 --- a/docs/ui-api-contract.md +++ b/docs/ui-api-contract.md @@ -135,13 +135,32 @@ Implementation details (T05, binding): are the ORIGINAL request's id (the duplicate is not run; window 10 min, claimed atomically before the pipeline runs). - 400 rules: malformed JSON; `application_id` missing/blank or > 64 chars; `profile_id` > 64; `messages` missing/empty or > 200; a null message; `role` not `system|user|assistant`; `content` not a string; total content > 200 000 chars; - `max_tokens` < 1; `model` > 200 chars; `client_request_id` not 1–128 chars of `[A-Za-z0-9-_.:]`. Body: + `max_tokens` < 1; `model` > 200 chars; `client_request_id` **missing** or not 1–64 chars of `[A-Za-z0-9_-]` + (review round 2: REQUIRED). Body: `{ "error":"invalid_request", "reason":"… — rejected before governance; no evidence record" }`. - An unknown `application_id` is a governed 403 at `auth` ("application 'x' is not configured"), audited. - Audit: `EntryPoint="console"`, `OperatorRef="shared-admin-token"`, `ApplicationId`, `Tags.Team` = the application's team, `Principal="console:"`, `Tags.Workflow`/`UseCase` from the body (default `console`/`playground`, bounded to 64 chars). - Cancellation (client disconnect) propagates to the provider call (`RequestAborted`); the record is `Cancelled`. +- **Early request id (review round 2, B7, binding).** `client_request_id` is required. Before the pipeline starts the Host + registers `client_request_id → request_id` (kept for the trace TTL). The console may poll + `GET /admin/playground/submissions/{client_request_id}` (admin token; 401 otherwise) right after submitting: + - 200 `{ "client_request_id": "...", "request_id": "req_<32 hex>", "state": "running" | "completed" }` + - 404 `{ "error": "not_found", "reason": "..." }` — unknown, never registered, past the trace TTL, or malformed id. + With the `request_id` it subscribes to `/admin/requests/{id}/trace/stream` while the provider is still waiting (no + faked timings). `/v1` is unchanged. +- **Stream completion (review round 2, B1).** A stream is served ONLY when the provider sent a terminal completion (a + finish reason) and no error occurred. Otherwise (stream just ended, SDK swallowed the SSE error, error mid-stream, + deadline hit) the SSE ends with the existing `data: {"error":"upstream_error","reason":…,"request_id":…}` event and + `data: [DONE]` — **no** chunk with `finish_reason:"stop"`; the record is `Effect=Deny`, `DenialKind=UpstreamFailure`, + `ErrorClass` `incomplete_stream` (or the failure class), `PartialOutputChars` set, never cached, never continued by a + fallback, the attempt charged its estimate. A completed stream's last chunk carries the provider's own finish reason + (`"stop"`, or `"length"` when truncated at the output bound). +- **Deadline (review round 2, B3; supersedes the earlier "the deadline stops applying once content flows").** The + policy `retry.deadline_ms` is ONE finite deadline for the whole execution (all attempts, before AND after the first + streamed content). If it fires after content was emitted: partial output kept and recorded, terminal failure with + `ErrorClass`/`reason_code` `timeout`, SSE ends with `upstream_error`, no fallback. ## Trace (ADR-0013) `GET /admin/requests/{id}/trace` → `{ "request_id","config_version","complete":bool,"events":[TraceEvent] }`; @@ -165,7 +184,10 @@ Implementation details (T05, binding — supersedes "404 unknown/expired" above) - `reason_code` vocabulary (bounded, never provider text or content): `cache_hit`, `not_reached`, `paused`, `budget_exceeded`, `governance_denied`, `unauthenticated`, `rate_limited`, `unsupported`, `upstream_failure`, `client_cancelled`, `client_disconnected`, `no_client`, `error`, and the failure classes `connect`, `timeout`, `429`, - `5xx`, `non_retryable`. + `5xx`, `non_retryable`, `incomplete_stream` (review round 2: stream ended without a terminal completion). +- Provider attempt events (`attempt_id` set) additionally carry `requested_max_output_tokens` (the request's own + `max_tokens`; omitted when the caller sent none) and `effective_max_output_tokens` (the bound actually sent to the + provider for that attempt = min(request, application, model)) — review round 2, B12. - Stream: replay of `seq > Last-Event-ID`, then live; `: keep-alive` comment every 15 s while idle; `event: end` + `data: {}` once complete. Clients de-duplicate by `seq`. - Bounds: ≤ 64 events/request, ≤ 2 000 requests (oldest completed evicted first), retention = the request's configuration @@ -214,8 +236,15 @@ Implementation details (T06, binding): `archived_utc`. No paths. Archived chains are verified with their archived anchor file when one exists. - `GET /admin/requests`: `segment` default `current`; an id outside the enumerated set (path, `..`, unknown) → **400** `{error:"unknown_segment"}`. `limit` 1–1000 (default 200). Response = the existing `RequestsPage` plus - `segment.id`, `segment.label` and `next_cursor` (null on the last page). A cursor encodes its segment; `cursor` alone is - enough for the next page; a malformed cursor or one for another segment → **400** `{error:"invalid_cursor"}`. + `segment.id`, `segment.label`, **`segment.is_current`** (always present — never infer the segment from the first row) + and `next_cursor` (null on the last page). A cursor encodes its segment; `cursor` alone is enough for the next page. +- **Stable paging (review round 2, B8, binding).** `next_cursor` is opaque base64url of {segment id, segment generation, + absolute index counted from the OLDEST request record of the segment (exclusive upper bound)}. Pages are newest-first by + absolute index, so records appended between pages never shift a page: no duplicates, no gaps (new records appear on a + fresh first page). Errors: malformed cursor or one for another `segment` → **400** `{error:"invalid_cursor"}`; the + segment was rotated/replaced since the cursor was issued (generation mismatch, segment gone, or a pre-round-2 cursor) → + **410** `{error:"cursor_expired"}` — the client reloads the first page; a cursor is never silently redirected to another + segment. - `GET /admin/requests/{id}/export?segment=` (default: search current, then archived newest first) → `{ "exported_utc", "request_id", "segment": SegmentView, "config_version", "record": AuditEntry (PascalCase, `PromptPreview` removed), "attempts", "trace", "integrity": { "segment_id","chain_valid","chain_failure","line","previous_hash","entry_hash", @@ -244,8 +273,33 @@ Implementation details (T04–T06, binding): produced the response (a fallback when one served). `CostBasis` (v2 meaning): `estimated_from_text` = served, usage not reported, charged the reservation bound; `estimated_failed_call` = failed/cancelled attempt charged its reservation bound; `no_call`, `reported`, `zero_priced`, `unpriced`, `unknown_failed_call` unchanged. +- **Request-level `CostBasis` (review round 2, B2):** describes the TOTAL (`Usage.CostUsd` = `SettledUsd`) over the + charged attempts (cost > 0): `reported` only if every charged attempt is `reported`; if all charged attempts share one + basis (e.g. all `estimated_failed_call`) that basis; if they differ → **`mixed`** (new value: e.g. a failed attempt's + estimate plus a reported fallback). With no positive charge the served/last attempt's basis stands. FinOps counts + `mixed` as an estimated-cost request and excludes it from savings claims; the UI labels it "Mixed (includes estimates)". +- **Additive v3 fields (review round 2, nullable, absent on older lines ⇒ Not recorded):** + `RequestedMaxOutputTokens` (the request's own max_tokens, null when none was sent), `EffectiveMaxOutputTokens` (the + bound sent to the provider for the SERVED attempt; null when nothing served), `PartialOutputChars` (characters already + emitted to the client before a stream failed; only on non-served records), `ServedConnectionId` (connection of the + attempt that served — a fallback when one served; on a cache hit the connection that produced the cached entry, so + `ServedConnectionId`/`ServedByModel` of a hit are the ACTUAL served provenance, not the policy primary). + `Attempts[]` items add `EffectiveMaxOutputTokens` (bound sent for that attempt) and `Truncated` (true when the provider + finished with `length`). `ErrorClass` vocabulary adds `incomplete_stream`. Label requested vs effective explicitly + (e.g. "Requested 256 · enforced 64"). - `budget.recovered` events record reservations a crash left open, settled at boot at their reserved amount. +## Header local health (review round 2, B11, binding) +- `/admin/catalog.local` adds `connection_id` (the local-boundary connection it describes) and `health` + (`{state, last_success_utc, last_failure_utc, last_error}` — CURRENT runtime health of exactly + `connection_id:model_id`, from real governed attempts). Selection: the enabled local connection/model most recently + observed by a real attempt or probe; else the first one routed by an enabled, unpaused policy target; else a connection + named `local`; else the first enabled local one. A stale legacy `local` connection never shadows the one that served. + The header uses `local.health` (fall back to `local.endpoint_health` only when `health.state` is `unknown`); it must not + match on an adapter literally named `local`. +- `/admin/status` adds `connection_health: [{ "key":"connection_id:model_id", "connection_id", "model_id", "boundary", + "enabled", "health": {…} }]` for every configured connection model. + ## Status FinOps savings (T06) `/admin/status.finops.savings` = `{ "label":"Estimated provider charge avoided", "baseline":"connection/model", "route_avoided_usd","cache_avoided_usd","total_usd","excluded_records" }` **only** when the active configuration's diff --git a/src/Covenant.Adapters/ProviderLayer.cs b/src/Covenant.Adapters/ProviderLayer.cs index 64435b1..8acbc8d 100644 --- a/src/Covenant.Adapters/ProviderLayer.cs +++ b/src/Covenant.Adapters/ProviderLayer.cs @@ -80,10 +80,18 @@ public virtual string Classify(Exception exception) /// retry.on, within maxAttempts and deadlineMs, and NEVER after any content reached the client; /// never on caller cancellation (rethrown) or non-retryable errors. Every started attempt is recorded /// () and settled exactly once; health is recorded per connection:model. -/// Deadline semantics: no attempt starts after deadlineMs; an attempt still waiting for its response (or, -/// streaming, its first content) at the deadline is cancelled and classified timeout. Once streamed content is -/// flowing the deadline no longer applies (the connection timeout does) — a delivered answer is never cut off by the -/// fallback budget.
    +/// Deadline semantics (review round 2): deadlineMs is ONE finite deadline for the whole execution — every +/// attempt, buffered or streamed, before or after the first content. No attempt starts after it; an attempt still running +/// when it fires is cancelled and classified timeout. If content was already emitted, the partial output is +/// preserved and recorded and the request ends with a terminal failure (no fallback — content is never continued by a +/// second provider). +/// Stream completion (review round 2): a streamed attempt counts as served ONLY when a terminal update with a +/// non-null finish reason was observed and no error occurred. A stream that just ends (or whose SSE error the SDK +/// swallowed) is a provider failure incomplete_stream: partial output kept, attempt charged its estimate, never +/// cached, no fallback. Finish reason length (buffered or streamed) is served and recorded as truncated. +/// Settlement (review round 2): the served attempt is settled in a finally after the downstream stages, so an +/// exception in attribution (or anything after it) still settles it exactly once (at its estimate when no priced cost +/// exists); the budget stage's unwind is the second, idempotent backstop.
    /// ADR-0011: resolve against the provider clients compiled into the request's /// bound configuration snapshot (so a request keeps the clients of the version it started on). The Host sets it /// only when its own snapshot-backed registry is the DI registration; a test-substituted registry always wins. @@ -157,14 +165,23 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance ConnectionId = target.AdapterKey, ModelId = target.ModelId, ReservedUsd = ctx.AttemptGate is null ? null : ctx.ActiveReservationUsd, + EffectiveMaxOutputTokens = RequestBounds.OutputTokenBound(ctx, target), }; ctx.Attempts.Add(attempt); var (end, errorClass, message) = await AttemptAsync(ctx, client, target, attempt, messages, deadline, ct); if (end == AttemptEnd.Served) { - await next(ctx, ct); - SettleServed(ctx, attempt); + try + { + await next(ctx, ct); + } + finally + { + // Exactly once even when attribution (or anything downstream) throws: without a priced cost the + // attempt settles at its conservative estimate. The gate is idempotent per attempt id. + SettleServed(ctx, attempt); + } return; } if (end == AttemptEnd.ClientGone) @@ -197,9 +214,10 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance var targetLabel = $"{target.AdapterKey}/{target.ModelId}"; var callToken = deadline?.Token ?? ct; ctx.AttemptedModel = target.ModelId; // a call is now actually started (not merely selected) - ctx.Trace(Stage, TraceStates.Running, attemptId: attempt.AttemptId, target: targetLabel); + ctx.Trace(Stage, TraceStates.Running, attemptId: attempt.AttemptId, target: targetLabel, + requestedMaxOutputTokens: ctx.Request.MaxOutputTokens, effectiveMaxOutputTokens: attempt.EffectiveMaxOutputTokens); var watch = System.Diagnostics.Stopwatch.StartNew(); - var options = new MEAI.ChatOptions { ModelId = target.ModelId, MaxOutputTokens = RequestBounds.OutputTokenBound(ctx, target) }; + var options = new MEAI.ChatOptions { ModelId = target.ModelId, MaxOutputTokens = attempt.EffectiveMaxOutputTokens }; try { @@ -209,14 +227,16 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance { var text = new StringBuilder(); MEAI.UsageDetails? usageDetails = null; + MEAI.ChatFinishReason? finish = null; + // No deadline relaxation once content flows (review round 2): the policy deadline bounds the whole stream. await foreach (var update in client.GetStreamingResponseAsync(messages, options, callToken)) { foreach (var uc in update.Contents.OfType()) usageDetails = uc.Details; + if (update.FinishReason is { } fr) finish = fr; if (update.Text is { Length: > 0 } fragment) { - if (text.Length == 0) deadline?.CancelAfter(Timeout.Infinite); // content flowing: deadline no longer applies text.Append(fragment); ctx.PartialOutputChars = text.Length; try @@ -232,18 +252,34 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance } } + if (finish is not { } completed) + { + // The stream ended without a terminal completion (or the SDK swallowed the SSE error): a provider + // failure — never "served" with a synthesized finish_reason. Partial output stays recorded. + const string why = "stream ended without a terminal completion (no finish reason)"; + health?.RecordFailure(target.AdapterKey, target.ModelId, why); + End(ctx, attempt, watch, TraceStates.Failed, TraceReasons.IncompleteStream, targetLabel); + SettleIncomplete(ctx, attempt); + return (AttemptEnd.Failed, TraceReasons.IncompleteStream, + $"provider '{target.AdapterKey}' {why}; {text.Length.ToString(System.Globalization.CultureInfo.InvariantCulture)} chars were emitted"); + } + health?.RecordSuccess(target.AdapterKey, target.ModelId); + attempt.Truncated = completed == MEAI.ChatFinishReason.Length ? true : null; ctx.ServedTarget = target; ctx.Response = new InferenceResponse( Message: new ChatMessage(ChatRole.Assistant, text.ToString()), Usage: new Usage(usageDetails?.InputTokenCount ?? 0, usageDetails?.OutputTokenCount ?? 0, 0m), ServedByModel: target.ModelId, - UsageReported: usageDetails?.InputTokenCount is not null && usageDetails.OutputTokenCount is not null); + UsageReported: usageDetails?.InputTokenCount is not null && usageDetails.OutputTokenCount is not null, + FinishReason: completed.Value); } else { + // Buffered SDK responses either complete or throw; a "length" finish is served and flagged truncated. var response = await client.GetResponseAsync(messages, options, callToken); health?.RecordSuccess(target.AdapterKey, target.ModelId); + attempt.Truncated = response.FinishReason == MEAI.ChatFinishReason.Length ? true : null; ctx.ServedTarget = target; ctx.Response = new InferenceResponse( Message: new ChatMessage(ChatRole.Assistant, response.Text ?? string.Empty), @@ -252,7 +288,8 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance OutputTokens: response.Usage?.OutputTokenCount ?? 0, CostUsd: 0m), // cost is computed by the attribution stage ServedByModel: target.ModelId, - UsageReported: response.Usage?.InputTokenCount is not null && response.Usage.OutputTokenCount is not null); + UsageReported: response.Usage?.InputTokenCount is not null && response.Usage.OutputTokenCount is not null, + FinishReason: response.FinishReason?.Value); } } catch (OperationCanceledException) when (ct.IsCancellationRequested) @@ -266,11 +303,13 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance { // Adapter contract: error mapping (src/CLAUDE.md). An upstream failure is a governed, audited outcome — // never an unhandled exception escaping the pipeline as a 500. The deadline firing is a timeout. - var errorClass = deadline is { IsCancellationRequested: true } && !ct.IsCancellationRequested - ? TraceReasons.Timeout - : _classifier.Classify(ex); + bool deadlineHit = deadline is { IsCancellationRequested: true } && !ct.IsCancellationRequested; + var errorClass = deadlineHit ? TraceReasons.Timeout : _classifier.Classify(ex); var verb = ctx.Request.Stream && ctx.DeltaSink is not null ? "stream failed" : "call failed"; - var message = $"provider '{target.AdapterKey}' {verb}: {Bound(ex.Message)}"; + var message = deadlineHit + ? $"provider '{target.AdapterKey}' {verb}: the policy deadline (deadline_ms) was exceeded" + + (ctx.PartialOutputChars > 0 ? $" after {ctx.PartialOutputChars.ToString(System.Globalization.CultureInfo.InvariantCulture)} chars were emitted" : "") + : $"provider '{target.AdapterKey}' {verb}: {Bound(ex.Message)}"; health?.RecordFailure(target.AdapterKey, target.ModelId, Bound(ex.Message)); End(ctx, attempt, watch, TraceStates.Failed, errorClass, targetLabel); SettleIncomplete(ctx, attempt); @@ -279,7 +318,8 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance attempt.Outcome = "served"; attempt.DurationMs = watch.Elapsed.TotalMilliseconds; - ctx.Trace(Stage, TraceStates.Passed, attempt.DurationMs, attemptId: attempt.AttemptId, target: targetLabel); + ctx.Trace(Stage, TraceStates.Passed, attempt.DurationMs, attemptId: attempt.AttemptId, target: targetLabel, + requestedMaxOutputTokens: ctx.Request.MaxOutputTokens, effectiveMaxOutputTokens: attempt.EffectiveMaxOutputTokens); return (AttemptEnd.Served, null, "served"); } @@ -288,7 +328,8 @@ private static void End(InferenceContext ctx, AttemptRecord attempt, System.Diag attempt.Outcome = state == TraceStates.Cancelled ? "cancelled" : "failed"; attempt.ErrorClass = errorClass; attempt.DurationMs = watch.Elapsed.TotalMilliseconds; - ctx.Trace(Stage, state, attempt.DurationMs, errorClass, attempt.AttemptId, target); + ctx.Trace(Stage, state, attempt.DurationMs, errorClass, attempt.AttemptId, target, + ctx.Request.MaxOutputTokens, attempt.EffectiveMaxOutputTokens); } /// A started attempt that produced no complete response may still be billed (ADR-0009/0014): settled at the diff --git a/src/Covenant.Core/CanonicalModel.cs b/src/Covenant.Core/CanonicalModel.cs index 27c0860..0fe8a48 100644 --- a/src/Covenant.Core/CanonicalModel.cs +++ b/src/Covenant.Core/CanonicalModel.cs @@ -51,5 +51,8 @@ public sealed record Usage(long InputTokens, long OutputTokens, decimal CostUsd) } /// The canonical inference response. UsageReported=false means the provider returned no (or -/// partial) token counts: Usage tokens are then NOT a real zero (ADR-0009). -public sealed record InferenceResponse(ChatMessage Message, Usage Usage, string ServedByModel, bool UsageReported = true); +/// partial) token counts: Usage tokens are then NOT a real zero (ADR-0009). +/// FinishReason (additive): the provider's terminal finish reason in OpenAI vocabulary ("stop", "length", +/// "content_filter", "tool_calls"), null when not reported (legacy compositions, buffered SDK responses without one). +/// "length" ⇒ the answer was truncated at the enforced output bound. +public sealed record InferenceResponse(ChatMessage Message, Usage Usage, string ServedByModel, bool UsageReported = true, string? FinishReason = null); diff --git a/src/Covenant.Core/Decisions.cs b/src/Covenant.Core/Decisions.cs index 1676748..bea81a8 100644 --- a/src/Covenant.Core/Decisions.cs +++ b/src/Covenant.Core/Decisions.cs @@ -78,7 +78,13 @@ public sealed record AuditEntry( IReadOnlyList? Attempts = null, IReadOnlyList? Trace = null, decimal? ReservedUsd = null, - decimal? SettledUsd = null); + decimal? SettledUsd = null, + // ---- v3 continued (review round 2, additive, nullable): requested vs effective output bound, emitted partial + // output of a failed stream, and the connection that actually served (primary, fallback or the cached entry's). + int? RequestedMaxOutputTokens = null, + int? EffectiveMaxOutputTokens = null, + int? PartialOutputChars = null, + string? ServedConnectionId = null); /// One provider attempt in an audit v3 record (ADR-0013): which connection/model was called, how it ended, /// the bounded error class, its measured duration and its charge (ADR-0014). Outcome ∈ served | failed | cancelled. @@ -94,7 +100,9 @@ public sealed record AuditAttempt( decimal? CostUsd, string? CostBasis, decimal? ReservedUsd = null, - bool? Overrun = null); + bool? Overrun = null, + int? EffectiveMaxOutputTokens = null, + bool? Truncated = null); /// Compact persisted trace step (ADR-0013): stage, terminal state and measured duration. Provider steps are /// per attempt (AttemptId). No content, no credentials, no provider free text — ReasonCode is a bounded code. diff --git a/src/Covenant.Core/Execution.cs b/src/Covenant.Core/Execution.cs index 6dbb6b1..6cce6d7 100644 --- a/src/Covenant.Core/Execution.cs +++ b/src/Covenant.Core/Execution.cs @@ -40,6 +40,11 @@ public static class TraceReasons public const string ServerError5xx = "5xx"; public const string NonRetryable = "non_retryable"; + /// A provider stream that ended (or whose SSE error was swallowed by the SDK) WITHOUT a terminal update + /// carrying a finish reason: a provider failure, never a served answer. Not a retry class (content may already have + /// been emitted; never continued by another provider). + public const string IncompleteStream = "incomplete_stream"; + /// Default code of a denial when the denying stage did not name a finer one. public static string ForDenial(DenialKind kind) => kind switch { @@ -62,7 +67,9 @@ public sealed record PipelineTraceEvent( double? DurationMs = null, string? ReasonCode = null, string? AttemptId = null, - string? Target = null); + string? Target = null, + int? RequestedMaxOutputTokens = null, + int? EffectiveMaxOutputTokens = null); /// Mutable record of one provider attempt while the request runs; the audit stage freezes it into an /// . Created immediately before the provider call starts (Started = true). @@ -79,8 +86,36 @@ public sealed class AttemptRecord public string? CostBasis { get; set; } public decimal? ReservedUsd { get; set; } public bool? Overrun { get; set; } + /// The output bound actually SENT to the provider for this attempt (ADR-0014): min(request max_tokens, + /// application max, model max). Null on legacy compositions without a bound. + public int? EffectiveMaxOutputTokens { get; set; } + /// True when the provider finished with reason "length" (answer cut at the output bound). + public bool? Truncated { get; set; } + + public AuditAttempt ToAudit() => new(AttemptId, ConnectionId, ModelId, Outcome, ErrorClass, DurationMs, CostUsd, CostBasis, ReservedUsd, Overrun, + EffectiveMaxOutputTokens, Truncated); +} + +/// Request-level cost basis over the CHARGED attempts (ADR-0014, review round 2): a request's total is +/// "reported" only when every attempt that was charged (cost > 0) is "reported"; when all charged attempts share one +/// basis that basis is the request's; when they differ the total is "mixed" (e.g. a failed attempt's estimate plus a +/// reported fallback). With no positive charge the served/last attempt's basis stands. +public static class CostBases +{ + public const string Mixed = "mixed"; - public AuditAttempt ToAudit() => new(AttemptId, ConnectionId, ModelId, Outcome, ErrorClass, DurationMs, CostUsd, CostBasis, ReservedUsd, Overrun); + public static string? Aggregate(IReadOnlyList attempts, string? current) + { + string? single = null; + bool any = false; + foreach (var a in attempts) + { + if (a.CostUsd is not > 0m || a.CostBasis is null) continue; + if (!any) { single = a.CostBasis; any = true; } + else if (!string.Equals(single, a.CostBasis, StringComparison.Ordinal)) return Mixed; + } + return any ? single : current; + } } /// Result of asking the gate whether an attempt may start. diff --git a/src/Covenant.Core/InferenceContext.cs b/src/Covenant.Core/InferenceContext.cs index 5741a3f..5291639 100644 --- a/src/Covenant.Core/InferenceContext.cs +++ b/src/Covenant.Core/InferenceContext.cs @@ -167,10 +167,12 @@ public void Deny(string reason, DenialKind kind = DenialKind.Governance, string? public void MarkStageEntered(string stage) => _enteredStages.Add(stage); /// Emits one trace event (server UTC time). Bounded: events beyond are dropped. - public void Trace(string stage, string state, double? durationMs = null, string? reasonCode = null, string? attemptId = null, string? target = null) + public void Trace(string stage, string state, double? durationMs = null, string? reasonCode = null, string? attemptId = null, string? target = null, + int? requestedMaxOutputTokens = null, int? effectiveMaxOutputTokens = null) { if (_trace.Count >= MaxTraceEvents) return; - var ev = new PipelineTraceEvent(stage, state, DateTimeOffset.UtcNow, durationMs, reasonCode, attemptId, target); + var ev = new PipelineTraceEvent(stage, state, DateTimeOffset.UtcNow, durationMs, reasonCode, attemptId, target, + requestedMaxOutputTokens, effectiveMaxOutputTokens); _trace.Add(ev); if (TraceSink is { } sink) { diff --git a/src/Covenant.Governance/Audit.cs b/src/Covenant.Governance/Audit.cs index c7aa948..b8d00d2 100644 --- a/src/Covenant.Governance/Audit.cs +++ b/src/Covenant.Governance/Audit.cs @@ -36,6 +36,12 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance // fallback), not only the served attempt; Attempts[] carries the breakdown. if (ctx.SettledUsd is { } settled && ctx.Attempts.Count > 0) usage = usage with { CostUsd = settled }; bool v3 = ctx.Configuration is not null; + // Review round 2 (B2): the request-level basis describes the TOTAL — "reported" only when every charged + // attempt is reported; one shared estimated basis stays that basis; differing bases are "mixed". + if (ctx.Attempts.Count > 0) ctx.CostBasis = CostBases.Aggregate(ctx.Attempts, ctx.CostBasis); + var servedAttempt = ctx.ServedTarget is { } st + ? ctx.Attempts.LastOrDefault(a => a.Outcome == "served" && a.ConnectionId == st.AdapterKey && a.ModelId == st.ModelId) + : null; var entry = new AuditEntry( Id: id, TimestampUtc: _clock.GetUtcNow(), @@ -80,7 +86,11 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance Attempts: v3 ? ctx.Attempts.Select(a => a.ToAudit()).ToList() : null, Trace: v3 ? ctx.CompactTrace() : null, ReservedUsd: v3 ? ctx.ReservedUsd : null, - SettledUsd: v3 ? ctx.SettledUsd : null); + SettledUsd: v3 ? ctx.SettledUsd : null, + RequestedMaxOutputTokens: v3 ? ctx.Request.MaxOutputTokens : null, + EffectiveMaxOutputTokens: v3 ? servedAttempt?.EffectiveMaxOutputTokens : null, + PartialOutputChars: v3 && !served && ctx.PartialOutputChars > 0 ? ctx.PartialOutputChars : null, + ServedConnectionId: v3 && served ? ctx.ServedTarget?.AdapterKey : null); // CancellationToken.None: a cancelled request must still produce its audit record. await sink.EnqueueAsync(entry, CancellationToken.None); diff --git a/src/Covenant.Governance/Auth.cs b/src/Covenant.Governance/Auth.cs index 670db1b..8fb958b 100644 --- a/src/Covenant.Governance/Auth.cs +++ b/src/Covenant.Governance/Auth.cs @@ -100,6 +100,11 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance return; } ctx.ApplicationId = app.Id; + // Review round 2 (B6): once a configuration governs, the key only RESOLVES the application; the + // identity's team is the ACTIVE application's team — exactly like the console entry point — so a + // team change applied through configuration governs new charges on both entry points. Historical + // charges keep the scopes recorded at reservation time in the ledger. + ctx.Identity = new CallerIdentity(record.Principal, ctx.Request.Attribution with { Team = app.Team }); if (!app.Enabled) { ctx.Deny($"application '{app.Id}' disabled"); return; } if (!ResolveProfile(ctx, cfg, app)) return; } diff --git a/src/Covenant.Governance/BudgetGate.cs b/src/Covenant.Governance/BudgetGate.cs index e184c74..7ef7db6 100644 --- a/src/Covenant.Governance/BudgetGate.cs +++ b/src/Covenant.Governance/BudgetGate.cs @@ -52,6 +52,8 @@ private sealed class Slot public required decimal Reserved { get; init; } public required bool Priced { get; init; } public bool Closed { get; set; } + /// A durable settle/release write is in progress (closed only after it succeeded). + public bool InFlight { get; set; } public AttemptCharge? Charge { get; set; } } @@ -122,6 +124,10 @@ private AttemptAdmission Reserve(InferenceContext ctx, RouteTarget target, strin return AttemptAdmission.Ok(amount); } + /// Settles a started attempt exactly once. The slot is marked closed only AFTER the durable ledger write + /// succeeded (review round 2, B4): a failed write leaves the slot — and the ledger reservation — open, so a later call + /// (the budget stage's unwind) or boot recovery settles it; it is never silently lost. A concurrent duplicate while a + /// write is in flight is answered as a duplicate (Settled = false) and writes nothing. public AttemptCharge Settle(InferenceContext ctx, string attemptId, decimal? costUsd) { Slot? slot; @@ -129,45 +135,90 @@ public AttemptCharge Settle(InferenceContext ctx, string attemptId, decimal? cos { _slots.TryGetValue(attemptId, out slot); if (slot is { Closed: true }) return slot.Charge is { } c ? c with { Settled = false } : new AttemptCharge(0m, "no_call", false, false); - if (slot is not null) slot.Closed = true; + if (slot is { InFlight: true }) return new AttemptCharge(0m, "no_call", false, false); + if (slot is not null) slot.InFlight = true; } bool priced = slot?.Priced ?? false; decimal reserved = slot?.Reserved ?? 0m; decimal amount = costUsd ?? reserved; string basis = costUsd is not null ? "reported" : priced ? "estimated_failed_call" : "unknown_failed_call"; - var result = _ledger.Settle(_requestId, attemptId, amount, _scopes); + SettleResult result; + try + { + result = _ledger.Settle(_requestId, attemptId, amount, _scopes); + } + catch + { + lock (_gate) + if (slot is not null) slot.InFlight = false; // still open: retried by Finish, or settled by boot recovery + throw; + } var charge = new AttemptCharge(amount, basis, result.Overrun || (costUsd is { } c2 && c2 > reserved && reserved > 0m), result.Settled || amount == 0m); lock (_gate) - if (slot is not null) slot.Charge = charge; - ctx.SettledUsd = (ctx.SettledUsd ?? 0m) + amount; + { + if (slot is not null) + { + slot.Charge = charge; + slot.Closed = true; + slot.InFlight = false; + } + } + if (charge.Settled) ctx.SettledUsd = (ctx.SettledUsd ?? 0m) + amount; return charge; } + /// Releases an admitted attempt that never started; closed only after the durable release succeeded. public void Release(InferenceContext ctx, string attemptId) { + Slot? slot; lock (_gate) { - if (!_slots.TryGetValue(attemptId, out var slot) || slot.Closed) return; - slot.Closed = true; + if (!_slots.TryGetValue(attemptId, out slot) || slot.Closed || slot.InFlight) return; + slot.InFlight = true; + } + try + { + _ledger.Release(_requestId, attemptId); + } + catch + { + lock (_gate) slot!.InFlight = false; + throw; + } + lock (_gate) + { + slot!.Closed = true; + slot.InFlight = false; } - _ledger.Release(_requestId, attemptId); } /// Unwind safety net (budget stage finally): an attempt that started but was never settled (an exception - /// escaped) is settled at its estimate; an admitted attempt that never started is released. Then the request-level - /// failed-call charge and cost basis are derived from the attempts (never a silent $0). + /// escaped, or an earlier durable write failed) is settled at its estimate; an admitted attempt that never started is + /// released. Every open slot is tried even if one write fails (the first failure is rethrown afterwards). Then the + /// request-level failed-call charge and cost basis are derived from the attempts (never a silent $0). public void Finish(InferenceContext ctx) { List open; lock (_gate) open = _slots.Where(kv => !kv.Value.Closed).Select(kv => kv.Key).ToList(); + System.Runtime.ExceptionServices.ExceptionDispatchInfo? failure = null; foreach (var id in open) { - var started = ctx.Attempts.FirstOrDefault(a => a.AttemptId == id); - if (started is null) { Release(ctx, id); continue; } - var charge = Settle(ctx, id, null); - started.CostUsd ??= charge.CostUsd; - started.CostBasis ??= charge.CostBasis; + try + { + var started = ctx.Attempts.FirstOrDefault(a => a.AttemptId == id); + if (started is null) { Release(ctx, id); continue; } + var charge = Settle(ctx, id, null); + if (charge.Settled) + { + started.CostUsd ??= charge.CostUsd; + started.CostBasis ??= charge.CostBasis; + } + } + catch (Exception ex) + { + failure ??= System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex); + } } if (ctx.Response is null && ctx.Attempts.Count > 0) @@ -175,5 +226,12 @@ public void Finish(InferenceContext ctx) ctx.FailedCallUsage ??= new Usage(0, 0, ctx.SettledUsd ?? 0m); // tokens NOT reported; cost is an estimate ctx.CostBasis ??= ctx.Attempts[^1].CostBasis ?? "unknown_failed_call"; } + failure?.Throw(); + } + + /// Open (unsettled, unreleased) slots — diagnostics/tests. + public int OpenSlots + { + get { lock (_gate) return _slots.Count(kv => !kv.Value.Closed); } } } diff --git a/src/Covenant.Governance/BudgetLedger.cs b/src/Covenant.Governance/BudgetLedger.cs index e5cfe0f..bb724a7 100644 --- a/src/Covenant.Governance/BudgetLedger.cs +++ b/src/Covenant.Governance/BudgetLedger.cs @@ -13,8 +13,108 @@ public static class LedgerOps public const string Release = "release"; public const string SettleRecovered = "settle-recovered"; public const string LegacyImport = "legacy-import"; + /// Review round 2 (B9): the last line of the atomically written initial ledger. A journal without it is an + /// interrupted bootstrap ⇒ refuse to start (never silently restore capacity). + public const string BootstrapComplete = "bootstrap-complete"; + public const string BootstrapRequestId = "bootstrap"; public static bool IsCharge(string op) => op is Settle or SettleRecovered or LegacyImport; + + public static bool IsKnown(string op) => op is Reserve or Settle or Release or SettleRecovered or LegacyImport or BootstrapComplete; +} + +/// Replay validation of a ledger journal (review round 2, B10). Corrupt accounting must never silently disappear: +/// every record is checked for the op vocabulary, non-negative amounts, non-empty ids, scope syntax, a real timestamp, and +/// the per-(request, attempt) lifecycle — reserve once; settle once (after a reserve, or a direct overrun settle of an +/// unreserved zero-bound attempt); release once (after a reserve, possibly after its settle); settle-recovered once, only +/// for an open reservation; nothing after release/settle-recovered. legacy-import is idempotent per scope key and never +/// after the bootstrap-complete marker; the marker appears at most once. +public static class LedgerReplay +{ + private enum State { Reserved, Settled, Closed } + + /// Null when valid, else (record index, diagnostic) of the FIRST violation. + public static (int Index, string Error)? Validate(IReadOnlyList records) + { + var states = new Dictionary<(string, string), State>(); + bool marker = false; + for (int i = 0; i < records.Count; i++) + { + var r = records[i]; + if (Check(r, states, ref marker) is { } error) return (i, error); + } + return null; + } + + public static bool IsValidScope(string? scope) + { + if (scope is null) return false; + foreach (var ch in scope) if (char.IsControl(ch)) return false; + if (scope == BudgetScopes.Global) return true; + foreach (var prefix in new[] { "team:", "application:" }) + if (scope.StartsWith(prefix, StringComparison.Ordinal) && scope.Length > prefix.Length && scope.Length <= 200) return true; + return false; + } + + private static string? Check(LedgerRecord r, Dictionary<(string, string), State> states, ref bool marker) + { + if (r.Op is null || !LedgerOps.IsKnown(r.Op)) return $"unknown op '{Evidence.Bounded(r.Op)}'"; + if (r.AmountUsd < 0m) return $"negative amount {r.AmountUsd.ToString(CultureInfo.InvariantCulture)}"; + if (string.IsNullOrWhiteSpace(r.RequestId)) return "empty request_id"; + if (string.IsNullOrWhiteSpace(r.AttemptId)) return "empty attempt_id"; + if (r.TsUtc == default || r.TsUtc.Year < 2000) return "missing or invalid ts_utc"; + if (r.Scopes is null) return "missing scopes"; + + if (r.Op == LedgerOps.BootstrapComplete) + { + if (marker) return "duplicate bootstrap-complete marker"; + if (r.AmountUsd != 0m || r.Scopes.Count != 0) return "bootstrap-complete marker must carry no amount and no scopes"; + marker = true; + return null; + } + if (r.Scopes.Count == 0) return $"{r.Op} without scopes"; + foreach (var scope in r.Scopes) + if (!IsValidScope(scope)) return $"invalid scope '{Evidence.Bounded(scope)}'"; + + var key = (r.RequestId, r.AttemptId); + bool known = states.TryGetValue(key, out var state); + switch (r.Op) + { + case LedgerOps.LegacyImport: + if (marker) return "legacy-import after the bootstrap-complete marker"; + if (r.RequestId != LedgerOps.LegacyImport) return "legacy-import must use request_id 'legacy-import'"; + states[key] = State.Closed; // idempotent per scope key (a duplicate is ignored on replay) + return null; + case LedgerOps.Reserve: + if (known) return $"second reserve for {Describe(key)}"; + states[key] = State.Reserved; + return null; + case LedgerOps.Settle: + if (!known) + { + if (r.Overrun != true) return $"settle without a reservation for {Describe(key)}"; + states[key] = State.Closed; // direct overrun settle of an unreserved (zero-bound) attempt + return null; + } + if (state != State.Reserved) return $"second settle for {Describe(key)}"; + states[key] = State.Settled; + return null; + case LedgerOps.Release: + if (!known) return $"release without a reservation for {Describe(key)}"; + if (state == State.Closed) return $"release after the attempt was closed for {Describe(key)}"; + states[key] = State.Closed; + return null; + case LedgerOps.SettleRecovered: + if (!known) return $"settle-recovered without a reservation for {Describe(key)}"; + if (state != State.Reserved) return $"settle-recovered of an already settled attempt {Describe(key)}"; + states[key] = State.Closed; + return null; + default: + return $"unknown op '{Evidence.Bounded(r.Op)}'"; + } + } + + private static string Describe((string Req, string Att) key) => $"({Evidence.Bounded(key.Req)}, {Evidence.Bounded(key.Att)})"; } /// One append-only ledger line. Keyed by (RequestId, AttemptId); records the SCOPES charged (global, @@ -131,9 +231,34 @@ public BudgetLedger(ILedgerStore store, IEnumerable? existing = nu _store = store; _clock = clock ?? TimeProvider.System; if (existing is not null) - foreach (var r in existing) Apply(r); + foreach (var r in existing) + { + // Replay never silently drops accounting (B10): an unknown operation is corruption, not a no-op. + if (!LedgerOps.IsKnown(r.Op)) throw new InvalidDataException($"budget ledger: unknown operation '{Evidence.Bounded(r.Op)}' on replay"); + Apply(r); + } } + /// The one-time legacy import records (B9): one per team with spend, charged to global + team, keyed + /// (legacy-import, team:<t>) so a replayed duplicate is idempotent. Built by the Host into the atomic bootstrap. + public static IReadOnlyList LegacyImportRecords(IEnumerable<(string Team, decimal AmountUsd)> spendByTeam, DateTimeOffset now) + => spendByTeam + .Where(t => t.AmountUsd > 0m) + .GroupBy(t => t.Team, StringComparer.OrdinalIgnoreCase) + .Select(g => new LedgerRecord + { + Op = LedgerOps.LegacyImport, RequestId = LedgerOps.LegacyImport, AttemptId = "team:" + g.First().Team, + Scopes = [BudgetScopes.Global, "team:" + g.First().Team], AmountUsd = g.Sum(t => t.AmountUsd), TsUtc = now, + }) + .ToList(); + + /// The bootstrap-complete marker record (B9). + public static LedgerRecord BootstrapMarker(DateTimeOffset now) => new() + { + Op = LedgerOps.BootstrapComplete, RequestId = LedgerOps.BootstrapRequestId, AttemptId = LedgerOps.BootstrapComplete, + Scopes = [], AmountUsd = 0m, TsUtc = now, + }; + public TimeProvider Clock => _clock; /// Open reservations (diagnostics/tests). @@ -258,11 +383,9 @@ public IReadOnlyList ImportLegacy(IEnumerable<(string Team, decima lock (_gate) { var now = _clock.GetUtcNow(); - var records = spendByTeam.Where(t => t.AmountUsd > 0m).Select(t => new LedgerRecord - { - Op = LedgerOps.LegacyImport, RequestId = LedgerOps.LegacyImport, AttemptId = "team:" + t.Team, - Scopes = ["global", "team:" + t.Team], AmountUsd = t.AmountUsd, TsUtc = now, - }).ToList(); + var records = LegacyImportRecords(spendByTeam, now) + .Where(r => !_closed.Contains((r.RequestId, r.AttemptId))) // idempotent per scope key + .ToList(); if (records.Count == 0) return []; _store.Append(records); foreach (var r in records) Apply(r); @@ -338,8 +461,12 @@ private void Apply(LedgerRecord r) Close(key); return; case LedgerOps.LegacyImport: + if (_closed.Contains(key)) return; // idempotent per (legacy-import, team:) — B9 Charge(r); + Close(key); return; + case LedgerOps.BootstrapComplete: + return; // marker only } } diff --git a/src/Covenant.Governance/Cache.cs b/src/Covenant.Governance/Cache.cs index 0d0d20f..e039f12 100644 --- a/src/Covenant.Governance/Cache.cs +++ b/src/Covenant.Governance/Cache.cs @@ -1,3 +1,5 @@ +using System.Buffers.Binary; +using System.Globalization; using System.Security.Cryptography; using System.Text; using Covenant.Core; @@ -11,29 +13,37 @@ public sealed class CacheConfig public int MaxEntries { get; init; } = 1_000; } -/// In-memory, TTL-bound response cache. Never persisted; entries die with the process. +/// In-memory, TTL-bound response cache. Never persisted; entries die with the process. Each entry keeps the +/// provenance of the attempt that actually produced it (connection + model — possibly an approved fallback). public sealed class ResponseCache(TimeProvider? clock = null) { private readonly TimeProvider _clock = clock ?? TimeProvider.System; private readonly object _gate = new(); - private readonly Dictionary _entries = new(); + private readonly Dictionary _entries = new(); - public bool TryGet(string key, out InferenceResponse response) + public bool TryGet(string key, out InferenceResponse response) => TryGet(key, out response, out _); + + public bool TryGet(string key, out InferenceResponse response, out RouteTarget? servedTarget) { lock (_gate) { if (_entries.TryGetValue(key, out var e) && e.Expires > _clock.GetUtcNow()) { response = e.Response; + servedTarget = e.ServedTarget; return true; } _entries.Remove(key); response = null!; + servedTarget = null; return false; } } public void Store(string key, InferenceResponse response, TimeSpan ttl, int maxEntries) + => Store(key, response, ttl, maxEntries, null); + + public void Store(string key, InferenceResponse response, TimeSpan ttl, int maxEntries, RouteTarget? servedTarget) { lock (_gate) { @@ -45,11 +55,59 @@ public void Store(string key, InferenceResponse response, TimeSpan ttl, int maxE if (_entries.Count >= maxEntries) _entries.Remove(_entries.OrderBy(kv => kv.Value.Expires).First().Key); } - _entries[key] = (response, _clock.GetUtcNow() + ttl); + _entries[key] = (response, servedTarget, _clock.GetUtcNow() + ttl); } } } +/// Unambiguous canonical cache-key encoding (review round 2, B5): every field is written into an incremental +/// SHA-256 as a presence byte (0 = null, 1 = value) followed by a 4-byte big-endian length and the UTF-8 bytes. No +/// delimiter can be forged by content: "x\u001fAssistant:y" in one message and ["x","y"] in two messages, or a shifted +/// message boundary, always hash differently. Lists are prefixed with their count. +public sealed class CacheKeyBuilder : IDisposable +{ + private readonly IncrementalHash _hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + + public CacheKeyBuilder(string domain) => Add(domain); + + public CacheKeyBuilder Add(string? value) + { + Span header = stackalloc byte[5]; + if (value is null) + { + header[0] = 0; + BinaryPrimitives.WriteInt32BigEndian(header[1..], 0); + _hash.AppendData(header); + return this; + } + var bytes = Encoding.UTF8.GetBytes(value); + header[0] = 1; + BinaryPrimitives.WriteInt32BigEndian(header[1..], bytes.Length); + _hash.AppendData(header); + _hash.AppendData(bytes); + return this; + } + + public CacheKeyBuilder Add(int? value) => Add(value?.ToString(CultureInfo.InvariantCulture)); + + public CacheKeyBuilder Count(int count) => Add(count); + + public CacheKeyBuilder Messages(IReadOnlyList messages) + { + Count(messages.Count); + foreach (var m in messages) + { + Add(m.Role.ToString()); + Add(m.Content); + } + return this; + } + + public string Finish() => Convert.ToHexString(_hash.GetHashAndReset()); + + public void Dispose() => _hash.Dispose(); +} + /// Cache stage (src/CLAUDE.md ordering: cache before budget/provider — a hit skips the model call). /// Keys are team-scoped so responses never leak across teams; only successful responses are cached; hits cost $0. public sealed class CacheStage(ResponseCache cache, CacheConfig config) : IPipelineStage @@ -66,20 +124,12 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance return; } - // v2 key (ADR-0013): SHA-256 over application, team, profile, FINAL classification, configuration version, the - // ordered approved candidates (connection id + model id), the enforced output bound sent to the provider and the - // message content — so a new activation, another identity or another eligible route set never reuses an entry. - IReadOnlyList candidates = ctx.Policy!.Candidates.Count > 0 ? ctx.Policy.Candidates : new[] { route }; - var key = ctx.Configuration is { } cfg - ? Key(string.Join('\u001e', "v3", cfg.Version.ToString(System.Globalization.CultureInfo.InvariantCulture), - ctx.ApplicationId ?? "", ctx.ProfileId ?? "", ctx.Classification.ToString(), ctx.Identity.Tags.Team, - string.Join('\u001d', candidates.Select(c => c.AdapterKey + "/" + c.ModelId))), - route.ModelId, ctx.Request.Messages, RequestBounds.OutputTokenBound(ctx, route)) - : Key(ctx.Identity.Tags.Team, route.ModelId, ctx.Request.Messages, ctx.Request.MaxOutputTokens); - if (cache.TryGet(key, out var hit)) + var key = KeyFor(ctx, route); + if (cache.TryGet(key, out var hit, out var servedTarget)) { ctx.ServedFromCache = true; ctx.CostBasis = "no_call"; + ctx.ServedTarget = servedTarget; // provenance: the attempt that produced the entry (maybe a fallback) ctx.Response = hit with { Usage = hit.Usage with { CostUsd = 0m } }; if (ctx.Request.Stream && ctx.DeltaSink is { } sink) await sink(new ChatDelta(hit.Message.Content), ct); // one delta: the cached text @@ -88,15 +138,37 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance await next(ctx, ct); - if (!ctx.IsDenied && ctx.Response is { } fresh) - cache.Store(key, fresh, TimeSpan.FromSeconds(ttl), Math.Max(1, maxEntries)); + if (!ctx.IsDenied && ctx.Response is { } fresh && !ctx.ServedFromCache) + cache.Store(key, fresh, TimeSpan.FromSeconds(ttl), Math.Max(1, maxEntries), ctx.ServedTarget ?? route); } - private static string Key(string team, string modelId, IReadOnlyList messages, int? maxOutputTokens) + /// v4 key (review round 2). Configured: application, team, profile, FINAL classification, configuration + /// version, the ORIGINAL request parameters (requested model override, requested max_tokens — stream-independent), + /// every candidate target in order with its EFFECTIVE output bound, then the messages (count, role, content). + /// Legacy (no configuration): team, route model, requested max_tokens, messages. + public static string KeyFor(InferenceContext ctx, RouteTarget route) { + if (ctx.Configuration is { } cfg) + { + IReadOnlyList candidates = ctx.Policy!.Candidates.Count > 0 ? ctx.Policy.Candidates : new[] { route }; + using var k = new CacheKeyBuilder("covenant-cache-v4"); + k.Add(cfg.Version) + .Add(ctx.ApplicationId) + .Add(ctx.Identity.Tags.Team) + .Add(ctx.ProfileId) + .Add(ctx.Classification.ToString()) + .Add(ctx.Request.RequestedModel) + .Add(ctx.Request.MaxOutputTokens) + .Count(candidates.Count); + foreach (var c in candidates) + k.Add(c.AdapterKey).Add(c.ModelId).Add(RequestBounds.OutputTokenBound(ctx, c)); + k.Messages(ctx.Request.Messages); + return k.Finish(); + } + // max_tokens is part of the contract: a 400-token cached answer must not serve a max_tokens=5 ask. - var sb = new StringBuilder(team).Append('\u001f').Append(modelId).Append('\u001f').Append(maxOutputTokens?.ToString() ?? ""); - foreach (var m in messages) sb.Append('\u001f').Append(m.Role).Append(':').Append(m.Content); - return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sb.ToString()))); + using var legacy = new CacheKeyBuilder("covenant-cache-legacy-v2"); + legacy.Add(ctx.Identity.Tags.Team).Add(route.ModelId).Add(ctx.Request.MaxOutputTokens).Messages(ctx.Request.Messages); + return legacy.Finish(); } } diff --git a/src/Covenant.Host/AuditSegments.cs b/src/Covenant.Host/AuditSegments.cs index 4725a7b..3980dfb 100644 --- a/src/Covenant.Host/AuditSegments.cs +++ b/src/Covenant.Host/AuditSegments.cs @@ -116,25 +116,46 @@ public static SegmentView View(AuditSegment segment, ChainVerification verificat }; } - public static string Cursor(string segmentId, int offset) - => Base64Url(Encoding.UTF8.GetBytes($"c1|{segmentId}|{offset.ToString(CultureInfo.InvariantCulture)}")); + /// Segment generation (review round 2, B8): identifies the FILE a cursor was issued for, so a rotation (the + /// current segment archived and a new one started) or a different archive can never be silently substituted. Current: + /// derived from the first entry's id + timestamp ("empty" while it has none); archived: also the archive file name. + /// 16 hex of SHA-256 — opaque, no path. + public static string Generation(AuditSegment segment, IReadOnlyList all) + { + var basis = all.Count == 0 + ? "empty" + : all[0].Id + "|" + all[0].TimestampUtc.ToString("O", CultureInfo.InvariantCulture); + if (!segment.Current) basis += "|" + Path.GetFileName(segment.FilePath); + return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(basis))).ToLowerInvariant()[..16]; + } + + /// Opaque cursor v2: segment id, segment generation and the ABSOLUTE index (from the OLDEST request record of + /// the segment, exclusive upper bound) of the next page. Appends never shift it. + public static string Cursor(string segmentId, string generation, int beforeIndex) + => Base64Url(Encoding.UTF8.GetBytes($"c2|{segmentId}|{generation}|{beforeIndex.ToString(CultureInfo.InvariantCulture)}")); - /// Opaque newest-first position: (segment id, number of newest items already returned). Null when malformed. - public static (string SegmentId, int Offset)? ParseCursor(string? cursor) + public enum CursorKind { Valid, Malformed, Legacy } + + /// Parses a cursor. A well-formed pre-round-2 "c1" (offset) cursor is reported as + /// (answered 410 cursor_expired — it cannot be anchored safely). + public static (CursorKind Kind, string SegmentId, string Generation, int Before) ParseCursor(string? cursor) { - if (string.IsNullOrEmpty(cursor) || cursor.Length > 200) return null; + var bad = (CursorKind.Malformed, "", "", 0); + if (string.IsNullOrEmpty(cursor) || cursor.Length > 300) return bad; try { var s = cursor.Replace('-', '+').Replace('_', '/'); s = s.PadRight(s.Length + (4 - s.Length % 4) % 4, '='); var parts = Encoding.UTF8.GetString(Convert.FromBase64String(s)).Split('|'); - if (parts.Length != 3 || parts[0] != "c1") return null; - if (!int.TryParse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture, out var offset) || offset < 0) return null; - return (parts[1], offset); + if (parts.Length == 3 && parts[0] == "c1") + return int.TryParse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture, out _) ? (CursorKind.Legacy, parts[1], "", 0) : bad; + if (parts.Length != 4 || parts[0] != "c2" || parts[1].Length == 0 || parts[2].Length != 16) return bad; + if (!int.TryParse(parts[3], NumberStyles.None, CultureInfo.InvariantCulture, out var before) || before < 0) return bad; + return (CursorKind.Valid, parts[1], parts[2], before); } catch (FormatException) { - return null; + return bad; } } @@ -188,24 +209,43 @@ public static void MapArchive(this WebApplication app, AuditSegments segments, F { if (!authorized(http)) return Error("unauthorized", "invalid admin token", StatusCodes.Status401Unauthorized); http.Response.Headers.CacheControl = "no-store"; - int offset = 0; string? segmentId = segment; + var parsed = cursor is null ? default : AuditSegments.ParseCursor(cursor); if (cursor is not null) { - if (AuditSegments.ParseCursor(cursor) is not { } c) + if (parsed.Kind == AuditSegments.CursorKind.Malformed) return Error("invalid_cursor", "cursor is malformed (use next_cursor from a previous page)", StatusCodes.Status400BadRequest); - if (segmentId is not null && segmentId != c.SegmentId) + if (segmentId is not null && segmentId != parsed.SegmentId) return Error("invalid_cursor", "cursor belongs to another segment", StatusCodes.Status400BadRequest); - segmentId = c.SegmentId; - offset = c.Offset; + if (parsed.Kind == AuditSegments.CursorKind.Legacy) + return Error("cursor_expired", "this cursor predates stable paging; reload the first page", StatusCodes.Status410Gone); + segmentId = parsed.SegmentId; } if (segments.Resolve(segmentId) is not { } seg) + { + // A cursor naming a segment that no longer exists (e.g. "current" was archived and a new one started is + // still "current"; an archive removed) is expired, never redirected. + if (cursor is not null) + return Error("cursor_expired", "the segment this cursor was issued for no longer exists; reload the first page", StatusCodes.Status410Gone); return Error("unknown_segment", "segment must be an id from GET /admin/audit/segments", StatusCodes.Status400BadRequest); + } var (verification, all) = AuditSegments.Read(seg); var entries = all.Where(e => e.IsRequest()).ToList(); // v3: control-plane events → GET /admin/config/versions + var generation = AuditSegments.Generation(seg, all); + int upper = entries.Count; // exclusive upper bound, absolute index from the OLDEST request record + if (cursor is not null) + { + if (!string.Equals(parsed.Generation, generation, StringComparison.Ordinal)) + return Error("cursor_expired", "the segment was rotated or replaced since this cursor was issued; reload the first page", StatusCodes.Status410Gone); + if (parsed.Before > entries.Count) + return Error("invalid_cursor", "cursor position is outside this segment", StatusCodes.Status400BadRequest); + upper = parsed.Before; + } int take = Math.Clamp(limit ?? 200, 1, 1000); - var items = Enumerable.Reverse(entries).Skip(offset).Take(take).ToList(); + int start = Math.Max(0, upper - take); + var items = new List(upper - start); + for (int i = upper - 1; i >= start; i--) items.Add(entries[i]); // newest first within the page var view = AuditSegments.View(seg, verification, all); var page = new RequestsPage { @@ -219,9 +259,10 @@ public static void MapArchive(this WebApplication app, AuditSegments segments, F Events = view.Events, Id = seg.Id, Label = seg.Label, + IsCurrent = seg.Current, }, Items = items, - NextCursor = offset + items.Count < entries.Count ? AuditSegments.Cursor(seg.Id, offset + items.Count) : null, + NextCursor = start > 0 ? AuditSegments.Cursor(seg.Id, generation, start) : null, }; return Results.Json(page, AuditJsonContext.Default.RequestsPage); }); diff --git a/src/Covenant.Host/BudgetLedgerStore.cs b/src/Covenant.Host/BudgetLedgerStore.cs index 65b8eb9..417d71e 100644 --- a/src/Covenant.Host/BudgetLedgerStore.cs +++ b/src/Covenant.Host/BudgetLedgerStore.cs @@ -13,18 +13,26 @@ public sealed class LedgerOpenResult public List Records { get; } = []; public List Errors { get; } = []; public List Warnings { get; } = []; - /// False when no journal file existed before this boot (⇒ the one-time legacy import runs). + /// False when no journal file existed before this boot (⇒ the one-time bootstrap/legacy import runs). public bool Existed { get; init; } } /// Append-only JSONL journal of the budget ledger (ADR-0014), Budget:LedgerPath (default /// <Audit:Path>.ledger.jsonl), independent of audit segments (an audit archive never touches it). -/// Torn-tail handling mirrors the configuration activation journal (ADR-0011): a final line without its newline that does -/// not parse (an interrupted append) is quarantined to …ledger.jsonl.torn-<utc> and the journal is rewritten -/// atomically with only the complete lines BEFORE anything can append; a complete last line whose newline never landed -/// is terminated; any other corrupt line refuses start. Appends are refused onto an unterminated line, and every append -/// is flushed to disk before it returns. A failed append halts the process (like a failed audit write): an appliance -/// that cannot record spend must not keep spending. +/// Bootstrap (review round 2, B9): a ledger is born ATOMICALLY — the complete initial content (every legacy-import +/// line + a final bootstrap-complete marker) is written to a temp file, fsynced and renamed into place. A crash +/// before the rename leaves no ledger (the next boot simply bootstraps again); a journal that exists WITHOUT the marker is +/// an interrupted pre-marker bootstrap and refuses start — it never silently restores capacity. Exception (upgrade from +/// the unreleased pre-marker build): a journal that already contains post-bootstrap operations (reserve/settle/…) proves +/// the old bootstrap finished; it is accepted with a warning and the marker is appended. +/// Replay validation (B10): every complete line must parse AND pass (op vocabulary, +/// non-negative amounts, ids, scopes, timestamps, lifecycle); any violation refuses start with the line number. +/// Torn-tail handling mirrors the configuration activation journal (ADR-0011): a final line without its newline +/// that does not parse (an interrupted append) is quarantined to …ledger.jsonl.torn-<utc> and the journal is +/// rewritten atomically with only the complete lines BEFORE anything can append; a complete last line whose newline never +/// landed is terminated. Appends are refused onto an unterminated line, and every append is flushed to disk before it +/// returns. A failed append halts the process (like a failed audit write): an appliance that cannot record spend must not +/// keep spending. public sealed class FileLedgerStore : ILedgerStore { private readonly object _gate = new(); @@ -47,6 +55,7 @@ public LedgerOpenResult Open() while (last >= 0 && lines[last].Trim().Length == 0) last--; string? tornTail = null; var good = new StringBuilder(); + var lineNumbers = new List(); for (int i = 0; i <= last; i++) { var raw = lines[i]; @@ -55,19 +64,45 @@ public LedgerOpenResult Open() LedgerRecord? rec = null; try { rec = JsonSerializer.Deserialize(line, LedgerJsonContext.Default.LedgerRecord); } catch (JsonException) { } - if (rec is { Op.Length: > 0, RequestId.Length: > 0, AttemptId: not null, Scopes: not null }) + if (rec is { Op: not null, RequestId: not null, AttemptId: not null, Scopes: not null }) { result.Records.Add(rec); + lineNumbers.Add(i + 1); good.Append(line).Append('\n'); continue; } if (i == last && !endsWithNewline) tornTail = raw; else { - result.Errors.Add($"Budget:LedgerPath {Path} — line {i + 1} is corrupt; accrued spend cannot be trusted. Restore the ledger from backup (never delete it)."); + result.Errors.Add($"Budget:LedgerPath {Path} — line {i + 1} is corrupt (not a ledger record); accrued spend cannot be trusted. Restore the ledger from backup (never delete it)."); return result; } } + + // B10: semantic replay validation of every complete record — corrupt accounting refuses start, precisely. + if (Covenant.Governance.LedgerReplay.Validate(result.Records) is { } violation) + { + result.Errors.Add($"Budget:LedgerPath {Path} — line {lineNumbers[violation.Index]} is invalid: {violation.Error}; accrued spend cannot be trusted. Restore the ledger from backup (never delete or hand-edit it)."); + return result; + } + + // B9: the bootstrap-complete marker must be present. + bool marked = result.Records.Any(r => r.Op == LedgerOps.BootstrapComplete); + bool appendMarker = false; + if (!marked) + { + bool postBootstrap = result.Records.Any(r => r.Op is not LedgerOps.LegacyImport); + if (!postBootstrap) + { + result.Errors.Add($"Budget:LedgerPath {Path} — the ledger has no bootstrap-complete marker: its one-time legacy import was interrupted " + + "(created but not completed). Refusing to start rather than silently restoring budget capacity. Move the file aside (keep it as evidence) " + + "and restart: the import is rebuilt atomically from the current audit segment."); + return result; + } + result.Warnings.Add("budget ledger: pre-marker journal with recorded operations accepted (its bootstrap evidently completed); bootstrap-complete marker appended"); + appendMarker = true; + } + if (tornTail is null && !endsWithNewline && last >= 0) tornTail = ""; // parsed, but its newline never landed if (tornTail is not null) { @@ -86,58 +121,86 @@ public LedgerOpenResult Open() catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { result.Errors.Add($"Budget:LedgerPath {Path} — torn tail could not be repaired ({ex.Message}); refusing to start."); + return result; } } _terminated = true; + if (appendMarker) + { + var m = BudgetLedger.BootstrapMarker(DateTimeOffset.UtcNow); + AppendLocked(Serialize([m])); + result.Records.Add(m); + } return result; } } - /// Creates an empty journal (marks the one-time legacy import as done). - public void EnsureCreated() + /// Atomic bootstrap (B9): writes (legacy-import records) plus the bootstrap-complete + /// marker to <path>.bootstrap.tmp, fsyncs, then renames it into place. Refuses (throws) when a ledger + /// already exists — never overwrites accounting. + public void Bootstrap(IReadOnlyList initial, DateTimeOffset now) { lock (_gate) { - if (File.Exists(Path)) return; + if (File.Exists(Path)) throw new IOException($"budget ledger {Path} already exists; refusing to bootstrap over it"); if (System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(Path)) is { Length: > 0 } dir) Directory.CreateDirectory(dir); - WriteDurable(Path, []); + var records = initial.Where(r => r.Op == LedgerOps.LegacyImport).Append(BudgetLedger.BootstrapMarker(now)).ToList(); + var tmp = Path + ".bootstrap.tmp"; + WriteDurable(tmp, Serialize(records)); + File.Move(tmp, Path, overwrite: false); + _terminated = true; } } + /// Creates an empty, COMPLETE journal (marker only) atomically — kept for callers that need a fresh ledger + /// with no legacy spend. + public void EnsureCreated() + { + if (File.Exists(Path)) return; + Bootstrap([], DateTimeOffset.UtcNow); + } + public void Append(IReadOnlyList records) { if (records.Count == 0) return; + var bytes = Serialize(records); + lock (_gate) AppendLocked(bytes); + } + + private static byte[] Serialize(IReadOnlyList records) + { var sb = new StringBuilder(); foreach (var r in records) sb.Append(JsonSerializer.Serialize(r, LedgerJsonContext.Default.LedgerRecord)).Append('\n'); - var bytes = Encoding.UTF8.GetBytes(sb.ToString()); - lock (_gate) + return Encoding.UTF8.GetBytes(sb.ToString()); + } + + private void AppendLocked(byte[] bytes) + { + try { - try + // Defence in depth: never append onto an unterminated line (Open() repairs torn tails first). + if (!_terminated && File.Exists(Path)) { - // Defence in depth: never append onto an unterminated line (Open() repairs torn tails first). - if (!_terminated && File.Exists(Path)) + var info = new FileInfo(Path); + if (info.Length > 0) { - var info = new FileInfo(Path); - if (info.Length > 0) - { - using var check = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - check.Seek(-1, SeekOrigin.End); - if (check.ReadByte() != '\n') - throw new IOException("ledger does not end with a newline; refusing to append (restart to repair the torn tail)"); - } + using var check = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + check.Seek(-1, SeekOrigin.End); + if (check.ReadByte() != '\n') + throw new IOException("ledger does not end with a newline; refusing to append (restart to repair the torn tail)"); } - _terminated = false; - using (var fs = new FileStream(Path, FileMode.Append, FileAccess.Write, FileShare.Read)) - { - fs.Write(bytes); - fs.Flush(flushToDisk: true); - } - _terminated = true; } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + _terminated = false; + using (var fs = new FileStream(Path, FileMode.Append, FileAccess.Write, FileShare.Read)) { - Environment.FailFast($"covenant: budget ledger write failed ({ex.Message}) — halting rather than spending unrecorded."); + fs.Write(bytes); + fs.Flush(flushToDisk: true); } + _terminated = true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Environment.FailFast($"covenant: budget ledger write failed ({ex.Message}) — halting rather than spending unrecorded."); } } @@ -149,6 +212,38 @@ private static void WriteDurable(string path, byte[] content) } } +/// Boot sequence of the ledger (B9), shared by Program and the tests: open; when no journal exists, build the +/// complete initial content from the current audit segment's recorded spend and bootstrap it atomically, then reopen. +/// Errors ⇒ the caller refuses to start. +public static class LedgerBootstrap +{ + public static LedgerOpenResult OpenOrBootstrap(FileLedgerStore store, Func> legacySpend, DateTimeOffset now) + { + var opened = store.Open(); + if (opened.Errors.Count > 0 || opened.Existed) return opened; + try + { + store.Bootstrap(BudgetLedger.LegacyImportRecords(legacySpend(), now), now); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + var failed = new LedgerOpenResult { Existed = false }; + failed.Errors.Add($"Budget:LedgerPath {store.Path} — the initial ledger could not be written atomically ({ex.Message}); refusing to start."); + return failed; + } + var reopened = store.Open(); + return new LedgerOpenResult { Existed = false }.With(reopened); + } + + private static LedgerOpenResult With(this LedgerOpenResult target, LedgerOpenResult source) + { + target.Records.AddRange(source.Records); + target.Errors.AddRange(source.Errors); + target.Warnings.AddRange(source.Warnings); + return target; + } +} + [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] [JsonSerializable(typeof(LedgerRecord))] diff --git a/src/Covenant.Host/ConsoleBackend.cs b/src/Covenant.Host/ConsoleBackend.cs index fe3804b..dfcbca3 100644 --- a/src/Covenant.Host/ConsoleBackend.cs +++ b/src/Covenant.Host/ConsoleBackend.cs @@ -276,6 +276,9 @@ public sealed class SegmentInfo /// Opaque segment id (GET /admin/audit/segments): "current" or an archived segment's id. [JsonPropertyName("id")] public string? Id { get; init; } [JsonPropertyName("label")] public string? Label { get; init; } + /// Always present (review round 2, B8): whether this page belongs to the current segment — the UI never infers + /// the segment from the first row. + [JsonPropertyName("is_current")] public bool IsCurrent { get; init; } } public sealed class CatalogReport @@ -316,4 +319,21 @@ public sealed class LocalConfigView [JsonPropertyName("model_id")] public string? ModelId { get; init; } [JsonPropertyName("registered")] public required bool Registered { get; init; } [JsonPropertyName("endpoint_health")] public required HealthView EndpointHealth { get; init; } + /// Review round 2 (B11): the local-boundary connection this view describes (connection id) and the CURRENT + /// runtime health of exactly that connection + model, observed from real governed attempts (key + /// "connection_id:model_id"). Use this — not a legacy "local" adapter name — for the header. + [JsonPropertyName("connection_id")] public string? ConnectionId { get; init; } + [JsonPropertyName("health")] public HealthView? Health { get; init; } +} + +/// Current runtime health of one configured connection + model (review round 2, B11): /admin/status +/// connection_health. Observed from real attempts and probes; "unknown" until observed. +public sealed class ConnectionHealthView +{ + [JsonPropertyName("key")] public required string Key { get; init; } + [JsonPropertyName("connection_id")] public required string ConnectionId { get; init; } + [JsonPropertyName("model_id")] public required string ModelId { get; init; } + [JsonPropertyName("boundary")] public required string Boundary { get; init; } + [JsonPropertyName("enabled")] public required bool Enabled { get; init; } + [JsonPropertyName("health")] public required HealthView Health { get; init; } } diff --git a/src/Covenant.Host/InferenceEndpoints.cs b/src/Covenant.Host/InferenceEndpoints.cs index c05970b..7e50293 100644 --- a/src/Covenant.Host/InferenceEndpoints.cs +++ b/src/Covenant.Host/InferenceEndpoints.cs @@ -15,11 +15,18 @@ public static class ChatCompletions /// Runs the pipeline for and writes the response. The per-request trace buffer is /// created BEFORE the pipeline starts (ADR-0013) so a subscriber that connects after submission still gets the /// earliest events; it is completed when the pipeline has finished. - public static async Task RunAsync(HttpContext http, InferencePipeline pipe, InferenceContext ctx, TraceHub? traces, CancellationToken ct) + /// Console inference only (B7): registered → request id in the trace hub BEFORE the + /// pipeline starts, so GET /admin/playground/submissions/{id} can answer while the provider is still waiting. + public static async Task RunAsync(HttpContext http, InferencePipeline pipe, InferenceContext ctx, TraceHub? traces, CancellationToken ct, + string? clientRequestId = null) { var request = ctx.Request; var buffer = traces?.Begin(request.RequestId!, ctx.ConfigVersion, ctx.Configuration?.Config.Settings.TraceRetentionMinutes ?? 10); - if (buffer is not null) ctx.TraceSink = buffer.Append; + if (buffer is not null) + { + ctx.TraceSink = buffer.Append; + if (clientRequestId is not null) traces!.RegisterSubmission(clientRequestId, buffer); + } try { return await RunCoreAsync(http, pipe, ctx, ct); @@ -57,16 +64,18 @@ async ValueTask WriteChunkAsync(OpenAiChatChunk chunk, CancellationToken token) Usage = usage, }; + async ValueTask StartSseAsync(CancellationToken token) + { + sseStarted = true; + resp.StatusCode = StatusCodes.Status200OK; + resp.ContentType = "text/event-stream"; + resp.Headers.CacheControl = "no-cache"; + await WriteChunkAsync(Chunk("assistant", null, null, null), token); + } + ctx.DeltaSink = async (delta, token) => { - if (!sseStarted) - { - sseStarted = true; - resp.StatusCode = StatusCodes.Status200OK; - resp.ContentType = "text/event-stream"; - resp.Headers.CacheControl = "no-cache"; - await WriteChunkAsync(Chunk("assistant", null, null, null), token); - } + if (!sseStarted) await StartSseAsync(token); await WriteChunkAsync(Chunk(null, delta.Content, null, null), token); }; @@ -74,8 +83,11 @@ async ValueTask WriteChunkAsync(OpenAiChatChunk chunk, CancellationToken token) if (!sseStarted) { - // Denied before the first byte — same JSON error contract as buffered mode. - return DenialResult(ctx); + // No byte sent yet. Refused/no response → same JSON error contract as buffered mode. A legitimately + // COMPLETED stream with empty content (no deltas) is a success: open the SSE and send its terminal chunk. + if (ctx.IsDenied || ctx.Response is null) + return DenialResult(ctx); + await StartSseAsync(ct); } if (ctx.IsDenied) @@ -88,7 +100,9 @@ async ValueTask WriteChunkAsync(OpenAiChatChunk chunk, CancellationToken token) } else if (ctx.Response is { } finalResp) { - await WriteChunkAsync(Chunk(null, null, "stop", new OpenAiUsage + // Only a provider-completed stream reaches here (B1); its own finish reason is relayed ("length" when + // truncated at the output bound). A cache hit has none recorded: "stop". + await WriteChunkAsync(Chunk(null, null, finalResp.FinishReason ?? "stop", new OpenAiUsage { PromptTokens = finalResp.Usage.InputTokens, CompletionTokens = finalResp.Usage.OutputTokens, @@ -201,7 +215,7 @@ public static class PlaygroundApi { public const int MaxMessages = 200; public const int MaxContentChars = 200_000; - public const int MaxClientRequestIdChars = 128; + public const int MaxClientRequestIdChars = 64; private const int MaxTagChars = 64; /// Body validation BEFORE governance (no audit record, 400). Returns the reason or null when valid. @@ -224,12 +238,16 @@ public static class PlaygroundApi if (chars > MaxContentChars) return $"messages exceed {MaxContentChars} characters"; if (body.MaxTokens is < 1) return "max_tokens must be a positive integer"; if (body.Model is { Length: > 200 }) return "model is too long"; - if (body.ClientRequestId is { } crid - && (crid.Length is 0 or > MaxClientRequestIdChars || !crid.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.' or ':'))) - return $"client_request_id must be 1–{MaxClientRequestIdChars} chars of [A-Za-z0-9-_.:]"; + // Review round 2 (B7): client_request_id is REQUIRED — it is the handle the console uses to learn the request id + // (and subscribe to the live trace) before the first response byte. + if (!IsValidClientRequestId(body.ClientRequestId)) + return $"client_request_id is required: 1–{MaxClientRequestIdChars} chars of [A-Za-z0-9_-]"; return null; } + public static bool IsValidClientRequestId(string? id) + => id is { Length: > 0 and <= MaxClientRequestIdChars } && id.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_'); + private static string Tag(string? value, string fallback) { var v = Evidence.Bounded(value); @@ -274,7 +292,8 @@ public static void MapPlayground(this WebApplication app, IRuntimeConfig runtime return Error("invalid_request", (invalid ?? "request body is required") + " — rejected before governance; no evidence record", StatusCodes.Status400BadRequest); - if (body.ClientRequestId is { } clientRequestId && !submissions.TryClaim(clientRequestId, requestId, out var original)) + var clientRequestId = body.ClientRequestId!; + if (!submissions.TryClaim(clientRequestId, requestId, out var original)) { http.Response.Headers[RequestCorrelation.Header] = original; return Error("duplicate_submission", "this client_request_id was already submitted; it is not run again", StatusCodes.Status409Conflict, original); @@ -295,7 +314,23 @@ public static void MapPlayground(this WebApplication app, IRuntimeConfig runtime using var lease = SnapshotLease.Bind(runtime, ctx); // ADR-0011: one configuration version for the whole request var team = ctx.Configuration?.FindApplication(appId)?.Team ?? "unknown"; ctx.BindConsoleIdentity(new PreAuthenticatedIdentity(appId, team, "console:" + appId), ConfigAuditEvents.SharedAdminOperator); - return await ChatCompletions.RunAsync(http, pipe, ctx, traces, ct); + return await ChatCompletions.RunAsync(http, pipe, ctx, traces, ct, clientRequestId); + }); + + // Review round 2 (B7): early request id for the live trace. 404 = unknown, never registered, past the trace TTL + // or not a well-formed client_request_id (names nothing). + app.MapGet("/admin/playground/submissions/{clientRequestId}", (HttpContext http, string clientRequestId) => + { + if (!authorized(http)) return Error("unauthorized", "invalid admin token", StatusCodes.Status401Unauthorized); + http.Response.Headers.CacheControl = "no-store"; + if (!IsValidClientRequestId(clientRequestId) || !traces.TryGetSubmission(clientRequestId, out var requestId, out var complete)) + return Error("not_found", "no console submission with this client_request_id (unknown or expired)", StatusCodes.Status404NotFound); + return Results.Json(new PlaygroundSubmissionView + { + ClientRequestId = clientRequestId, + RequestId = requestId, + State = complete ? "completed" : "running", + }, TraceJsonContext.Default.PlaygroundSubmissionView); }); } } diff --git a/src/Covenant.Host/Program.cs b/src/Covenant.Host/Program.cs index 7c9e3b2..8d711ea 100644 --- a/src/Covenant.Host/Program.cs +++ b/src/Covenant.Host/Program.cs @@ -213,21 +213,18 @@ RuntimeSnapshot CompileSnapshot(CovenantConfig c) // open by a crash are settled at their reserved amount (settle-recovered) — never free capacity. --- string ledgerPath = StartupValidation.Trimmed(builder.Configuration["Budget:LedgerPath"]) is { Length: > 0 } lp ? lp : auditPath + ".ledger.jsonl"; var ledgerStore = new FileLedgerStore(ledgerPath); -var ledgerOpened = ledgerStore.Open(); +// Review round 2 (B9): no journal ⇒ the complete initial ledger (legacy-import per team + bootstrap-complete marker) is +// written to a temp file, fsynced and renamed into place in ONE step; a journal without the marker refuses start. +var ledgerOpened = LedgerBootstrap.OpenOrBootstrap(ledgerStore, () => priorEntries + .Where(e => e.IsRequest() && e.Usage.CostUsd > 0m) // control-plane events never carry spend + .GroupBy(e => e.Tags.Team, StringComparer.OrdinalIgnoreCase) + .Select(g => (Team: g.Key, AmountUsd: g.Sum(e => e.Usage.CostUsd))) + .ToList(), + DateTimeOffset.UtcNow); configErrors.AddRange(ledgerOpened.Errors); FailIfConfigErrors(); foreach (var w in ledgerOpened.Warnings) Console.Error.WriteLine($"covenant: warning — {w}"); var budgetLedger = new BudgetLedger(ledgerStore, ledgerOpened.Records); -if (!ledgerOpened.Existed) -{ - var legacySpend = priorEntries - .Where(e => e.IsRequest() && e.Usage.CostUsd > 0m) // control-plane events never carry spend - .GroupBy(e => e.Tags.Team, StringComparer.OrdinalIgnoreCase) - .Select(g => (Team: g.Key, AmountUsd: g.Sum(e => e.Usage.CostUsd))) - .ToList(); - ledgerStore.EnsureCreated(); - budgetLedger.ImportLegacy(legacySpend); -} var recoveredReservations = budgetLedger.RecoverUnsettled(); if (recoveredReservations.Count > 0) auditSink.TryWrite(new AuditEntry( @@ -365,24 +362,31 @@ async ValueTask WriteEventAsync(string evt, string json, CancellationToken token await resp.Body.FlushAsync(token); } + async ValueTask StartSseAsync(CancellationToken token) + { + sseStarted = true; + resp.StatusCode = StatusCodes.Status200OK; + resp.ContentType = "text/event-stream"; + resp.Headers.CacheControl = "no-cache"; + await WriteEventAsync("message_start", AnthropicWire.MessageStartEvent(msgId, ctx.Response?.ServedByModel ?? ctx.AttemptedModel ?? ctx.Policy?.Route?.ModelId ?? ""), token); + await WriteEventAsync("content_block_start", AnthropicWire.ContentBlockStartEvent, token); + } + ctx.DeltaSink = async (delta, token) => { - if (!sseStarted) - { - sseStarted = true; - resp.StatusCode = StatusCodes.Status200OK; - resp.ContentType = "text/event-stream"; - resp.Headers.CacheControl = "no-cache"; - await WriteEventAsync("message_start", AnthropicWire.MessageStartEvent(msgId, ctx.AttemptedModel ?? ctx.Policy?.Route?.ModelId ?? ""), token); - await WriteEventAsync("content_block_start", AnthropicWire.ContentBlockStartEvent, token); - } + if (!sseStarted) await StartSseAsync(token); await WriteEventAsync("content_block_delta", AnthropicWire.ContentBlockDeltaEvent(delta.Content), token); }; await pipe.ExecuteAsync(ctx, ct); if (!sseStarted) - return AnthropicDenial(ctx); // denied before the first byte — plain JSON error + { + // Refused/no response → plain JSON error. A completed stream with empty content is a success: open the SSE. + if (ctx.IsDenied || ctx.Response is null) + return AnthropicDenial(ctx); + await StartSseAsync(ct); + } if (ctx.IsDenied) { @@ -613,9 +617,52 @@ StatusReport BuildStatus() }, Version = typeof(Program).Assembly.GetName().Version?.ToString(), ConfigVersion = cfg.Version, + ConnectionHealth = ConnectionHealthOf(cfg), }; } +// Review round 2 (B11): current runtime health per configured connection + model ("connection_id:model_id"), from real +// governed attempts and probes — the header reads this (or catalog.local.health), never a legacy model-name key. +List ConnectionHealthOf(CovenantConfig c) + => c.Connections.SelectMany(conn => conn.Models.Select(m => new ConnectionHealthView + { + Key = $"{conn.Id}:{m.ModelId}", + ConnectionId = conn.Id, + ModelId = m.ModelId, + Boundary = conn.Boundary.ToString(), + Enabled = conn.Enabled, + Health = providerHealth.Get($"{conn.Id}:{m.ModelId}"), + })).ToList(); + +// Review round 2 (B11): which local connection/model the console's "local route" describes. Order: the enabled +// local-boundary connection/model most recently OBSERVED by a real attempt or probe; else the first one an enabled, +// unpaused policy target routes to; else a connection named "local" (legacy import); else the first enabled local one. +// A stale legacy "local" connection therefore never shadows the connection that actually served. +(ConnectionConfig? Conn, string? ModelId) SelectLocal(CovenantConfig c) +{ + var candidates = c.Connections.Where(x => x.Boundary == Boundary.Local && x.Enabled) + .SelectMany(x => x.Models.Select(m => (Conn: x, ModelId: m.ModelId))).ToList(); + if (candidates.Count == 0) + { + var any = c.Connections.FirstOrDefault(x => x.Id == "local") ?? c.Connections.FirstOrDefault(x => x.Boundary == Boundary.Local); + return (any, any?.Models.FirstOrDefault()?.ModelId); + } + DateTimeOffset? Observed(HealthView h) => h.LastFailureUtc is { } f && (h.LastSuccessUtc is not { } s0 || f > s0) ? f : h.LastSuccessUtc; + var observed = candidates + .Select(k => (k.Conn, k.ModelId, At: Observed(providerHealth.Get($"{k.Conn.Id}:{k.ModelId}")))) + .Where(k => k.At is not null) + .OrderByDescending(k => k.At) + .FirstOrDefault(); + if (observed.Conn is not null) return (observed.Conn, observed.ModelId); + foreach (var policy in c.Policies.Where(p => p.Enabled && !p.Paused)) + foreach (var t in policy.Targets.Where(t => !t.Paused)) + if (candidates.FirstOrDefault(k => k.Conn.Id == t.ConnectionId && k.ModelId == t.ModelId) is { Conn: not null } routed) + return (routed.Conn, routed.ModelId); + var named = candidates.FirstOrDefault(k => k.Conn.Id == "local"); + var pick = named.Conn is not null ? named : candidates[0]; + return (pick.Conn, pick.ModelId); +} + app.MapGet("/admin/status", (HttpContext http) => { if (!Authorized(http)) return Unauthorized(); @@ -760,10 +807,10 @@ StatusReport BuildStatus() }; }).ToList(); - // Pre-v2 "local" view: the connection named "local" (legacy import), else the first local-boundary one. - var local = snapshot.FindConnection("local") ?? cfg.Connections.FirstOrDefault(c => c.Boundary == Boundary.Local); + // "local" view (review round 2, B11): the local connection/model actually observed or routed (see SelectLocal), + // with the CURRENT runtime health of exactly that connection:model. + var (local, localModelId) = SelectLocal(cfg); var localAuthority = EndpointSummary(local?.Endpoint); - var localModelId = local?.Models.FirstOrDefault()?.ModelId; var report = new CatalogReport { Mode = StartupEgress.ModeString(cfg.Mode), @@ -775,6 +822,8 @@ StatusReport BuildStatus() ModelId = localModelId, Registered = local is not null && localModelId is not null && liveRegistry.TryResolve(local.Id, localModelId, out _), EndpointHealth = providerHealth.Get($"endpoint:{localAuthority}"), + ConnectionId = local?.Id, + Health = local is not null && localModelId is not null ? providerHealth.Get($"{local.Id}:{localModelId}") : null, }, ProbeAllowList = probeAllowList.OrderBy(x => x, StringComparer.Ordinal).ToList(), ConfigVersion = cfg.Version, diff --git a/src/Covenant.Host/StatusContracts.cs b/src/Covenant.Host/StatusContracts.cs index da3dac3..1306d63 100644 --- a/src/Covenant.Host/StatusContracts.cs +++ b/src/Covenant.Host/StatusContracts.cs @@ -29,6 +29,8 @@ public sealed class StatusReport [JsonPropertyName("version")] public string? Version { get; init; } // v2 (ADR-0011): the active configuration version every new request binds to. [JsonPropertyName("config_version")] public int? ConfigVersion { get; init; } + // Review round 2 (B11): current runtime health of every configured connection + model, keyed "connection_id:model_id". + [JsonPropertyName("connection_health")] public List? ConnectionHealth { get; init; } } public sealed class AnchorStatus @@ -229,7 +231,7 @@ public static FinOpsSummary Build( // saving are the same error). Legacy records (no CostBasis) keep their old treatment. bool usageKnown = e.CostBasis is null or "reported" or "zero_priced" or "no_call"; if (e.CostBasis is "unpriced" or "unknown_failed_call") unknownCost++; - if (e.CostBasis is "estimated_from_text" or "estimated_failed_call") estimatedCost++; + if (e.CostBasis is "estimated_from_text" or "estimated_failed_call" or "mixed") estimatedCost++; // "mixed": the total contains an estimate if (e.Effect == PolicyEffect.Allow && !usageKnown) { diff --git a/src/Covenant.Host/Trace.cs b/src/Covenant.Host/Trace.cs index c6adef0..53e05fa 100644 --- a/src/Covenant.Host/Trace.cs +++ b/src/Covenant.Host/Trace.cs @@ -19,6 +19,19 @@ public sealed class TraceEventView [JsonPropertyName("duration_ms")] public double? DurationMs { get; init; } [JsonPropertyName("reason_code")] public string? ReasonCode { get; init; } [JsonPropertyName("target")] public string? Target { get; init; } + /// Provider attempt events only: the request's own max_tokens (null when the caller sent none). + [JsonPropertyName("requested_max_output_tokens")] public int? RequestedMaxOutputTokens { get; init; } + /// Provider attempt events only: the bound actually sent to the provider for this attempt. + [JsonPropertyName("effective_max_output_tokens")] public int? EffectiveMaxOutputTokens { get; init; } +} + +/// GET /admin/playground/submissions/{client_request_id} (review round 2, B7). +public sealed class PlaygroundSubmissionView +{ + [JsonPropertyName("client_request_id")] public required string ClientRequestId { get; init; } + [JsonPropertyName("request_id")] public required string RequestId { get; init; } + /// running | completed. + [JsonPropertyName("state")] public required string State { get; init; } } public sealed class TraceSnapshotView @@ -34,6 +47,7 @@ public sealed class TraceSnapshotView [JsonSourceGenerationOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] [JsonSerializable(typeof(TraceEventView))] [JsonSerializable(typeof(TraceSnapshotView))] +[JsonSerializable(typeof(PlaygroundSubmissionView))] public partial class TraceJsonContext : JsonSerializerContext; /// Per-request event buffer. Created by the Host BEFORE the pipeline starts, so the earliest stage events are @@ -86,6 +100,8 @@ public void Append(PipelineTraceEvent e) DurationMs = e.DurationMs is { } d ? Math.Round(d, 3) : null, ReasonCode = e.ReasonCode, Target = e.Target, + RequestedMaxOutputTokens = e.RequestedMaxOutputTokens, + EffectiveMaxOutputTokens = e.EffectiveMaxOutputTokens, }); signal = _changed; _changed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -162,6 +178,43 @@ public TraceBuffer Begin(string requestId, int? configVersion, int retentionMinu public enum Lookup { Found, Unknown, Expired } + private const int MaxSubmissions = 4000; + private readonly Dictionary _submissions = new(StringComparer.Ordinal); + private readonly Queue _submissionOrder = new(); + + /// Console inference (review round 2, B7): maps the browser's client_request_id to the server request id + /// BEFORE the pipeline starts, so the console can subscribe to the live trace while the provider is still waiting. + /// Kept for the trace TTL (until the buffer expires after completion); bounded (oldest dropped first). + public void RegisterSubmission(string clientRequestId, TraceBuffer buffer) + { + lock (_gate) + { + if (!_submissions.ContainsKey(clientRequestId)) _submissionOrder.Enqueue(clientRequestId); + _submissions[clientRequestId] = buffer; + while (_submissions.Count > MaxSubmissions && _submissionOrder.Count > 0) _submissions.Remove(_submissionOrder.Dequeue()); + } + } + + /// The request a client_request_id was registered for, and whether it is still running. False when unknown + /// or past the trace retention. + public bool TryGetSubmission(string clientRequestId, out string requestId, out bool complete) + { + lock (_gate) + { + var now = _clock.GetUtcNow(); + if (_submissions.TryGetValue(clientRequestId, out var buffer) && !buffer.IsExpired(now)) + { + requestId = buffer.RequestId; + complete = buffer.IsComplete; + return true; + } + _submissions.Remove(clientRequestId); + requestId = ""; + complete = false; + return false; + } + } + public Lookup TryGet(string requestId, out TraceBuffer? buffer) { lock (_gate) diff --git a/tests/Covenant.Tests/AccountingTests.cs b/tests/Covenant.Tests/AccountingTests.cs index a397a8a..ce9d6cd 100644 --- a/tests/Covenant.Tests/AccountingTests.cs +++ b/tests/Covenant.Tests/AccountingTests.cs @@ -50,6 +50,7 @@ private sealed class AccountingClient(string reply, UsageMode usage = UsageMode. } yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply); if (Usage() is { } u) yield return new MEAI.ChatResponseUpdate { Contents = [new MEAI.UsageContent(u)] }; + yield return new MEAI.ChatResponseUpdate { FinishReason = MEAI.ChatFinishReason.Stop }; // terminal completion (real providers send one) } public object? GetService(Type serviceType, object? serviceKey = null) => null; diff --git a/tests/Covenant.Tests/ConfigV2TestKit.cs b/tests/Covenant.Tests/ConfigV2TestKit.cs index f883d70..88e055c 100644 --- a/tests/Covenant.Tests/ConfigV2TestKit.cs +++ b/tests/Covenant.Tests/ConfigV2TestKit.cs @@ -145,6 +145,7 @@ internal sealed class GatedChatClient(string reply = "gated reply") : MEAI.IChat Interlocked.Increment(ref _calls); await Task.Yield(); yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply); + yield return new MEAI.ChatResponseUpdate { FinishReason = MEAI.ChatFinishReason.Stop }; // terminal completion (real providers send one) } public object? GetService(Type serviceType, object? serviceKey = null) => null; diff --git a/tests/Covenant.Tests/ConsolePlaygroundTests.cs b/tests/Covenant.Tests/ConsolePlaygroundTests.cs index 1d8ce06..c41a90e 100644 --- a/tests/Covenant.Tests/ConsolePlaygroundTests.cs +++ b/tests/Covenant.Tests/ConsolePlaygroundTests.cs @@ -18,7 +18,9 @@ public static string Body(string applicationId, string prompt, string? profile = if (profile is not null) sb.Append(",\"profile_id\":").Append(JsonSerializer.Serialize(profile, CovenantJsonContext.Default.String)); sb.Append(",\"messages\":[{\"role\":\"user\",\"content\":").Append(JsonSerializer.Serialize(prompt, CovenantJsonContext.Default.String)).Append("}]"); sb.Append(",\"stream\":").Append(stream ? "true" : "false"); - if (clientRequestId is not null) sb.Append(",\"client_request_id\":\"").Append(clientRequestId).Append('"'); + // Review round 2 (B7): client_request_id is required by the console endpoint — generated when the test names none. + clientRequestId ??= "t-" + Guid.NewGuid().ToString("n"); + sb.Append(",\"client_request_id\":\"").Append(clientRequestId).Append('"'); if (maxTokens is not null) sb.Append(",\"max_tokens\":").Append(maxTokens.Value); if (model is not null) sb.Append(",\"model\":").Append(JsonSerializer.Serialize(model, CovenantJsonContext.Default.String)); return sb.Append('}').ToString(); @@ -134,6 +136,9 @@ public async Task Refused_identities_are_governed_403_with_an_audit_record_and_n [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":null}]}""")] [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}],"max_tokens":0}""")] [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}],"client_request_id":"bad id with spaces"}""")] + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}]}""")] // B7: client_request_id required + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}],"client_request_id":"a.b:c"}""")] // B7: [A-Za-z0-9_-] only + [InlineData("""{"application_id":"demo-app","messages":[{"role":"user","content":"x"}],"client_request_id":"0123456789012345678901234567890123456789012345678901234567890123x"}""")] // 65 chars public async Task Invalid_body_is_400_before_governance_with_no_audit_record(string json) { await V2Admin.AuditAsync(_factory.AuditPath, l => l.Count >= 1); // bootstrap event is on disk diff --git a/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs b/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs index f61027c..569894a 100644 --- a/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs +++ b/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs @@ -117,6 +117,7 @@ internal sealed class ScriptedChatClient : MEAI.IChatClient if (fail) throw new HttpRequestException("connection reset mid-stream"); yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, "rest"); yield return new MEAI.ChatResponseUpdate { Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 7, OutputTokenCount = 3 })] }; + yield return new MEAI.ChatResponseUpdate { FinishReason = MEAI.ChatFinishReason.Stop }; // terminal completion (real providers send one) } public object? GetService(Type serviceType, object? serviceKey = null) => null; diff --git a/tests/Covenant.Tests/PipelineSliceTests.cs b/tests/Covenant.Tests/PipelineSliceTests.cs index 774729d..2a7a95a 100644 --- a/tests/Covenant.Tests/PipelineSliceTests.cs +++ b/tests/Covenant.Tests/PipelineSliceTests.cs @@ -27,7 +27,8 @@ private sealed class StubChatClient(string reply) : MEAI.IChatClient yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply[half..]); yield return new MEAI.ChatResponseUpdate { - Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 })] + Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 })], + FinishReason = MEAI.ChatFinishReason.Stop, // terminal completion (review round 2: required for "served") }; } diff --git a/tests/Covenant.Tests/ReviewRound2Tests.cs b/tests/Covenant.Tests/ReviewRound2Tests.cs new file mode 100644 index 0000000..4b3ed89 --- /dev/null +++ b/tests/Covenant.Tests/ReviewRound2Tests.cs @@ -0,0 +1,949 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; +using MEAI = Microsoft.Extensions.AI; + +namespace Covenant.Tests; + +// Review round 2 (backend) regressions — docs/verification-2026-10-16/v2/CODEX-REVIEW.txt. Every test here FAILS on +// 96deed5 (behaviourally, or because the evidence field it asserts did not exist) and passes with the fix. + +/// Ledger store whose appends can be made to fail (injected IOException) — B4. +internal sealed class FlakyLedgerStore : ILedgerStore +{ + public InMemoryLedgerStore Inner { get; } = new(); + public Func, bool> Fail { get; set; } = _ => false; + public int Failures { get; private set; } + + public IReadOnlyList Records => Inner.Records; + + public void Append(IReadOnlyList records) + { + if (Fail(records)) + { + Failures++; + throw new IOException("injected ledger write failure"); + } + Inner.Append(records); + } + + /// Fails the next appends that contain a record with . + public void FailNext(string op, int count = 1) + { + int left = count; + Fail = recs => recs.Any(r => r.Op == op) && left-- > 0; + } +} + +internal sealed class ThrowingStage : IPipelineStage +{ + public Task InvokeAsync(InferenceContext context, PipelineDelegate next, CancellationToken cancellationToken) + => throw new InvalidOperationException("downstream stage failure (injected)"); +} + +internal static class Round2 +{ + public static StubChatClient Mini() => new("mini reply"); + + /// Hybrid fallback config (Public → openai/gpt-4o-mini, openai/gpt-4o, ollama/qwen3:8b), cache optional. + public static CovenantConfig Config(int maxAttempts = 3, int deadlineMs = 60_000, int cacheTtl = 0, Func? tweak = null) + => V2Rig.FallbackConfig(new RetrySettings { MaxAttempts = maxAttempts, DeadlineMs = deadlineMs }, tweak: c => + { + var x = c with { Settings = new OperationalSettings { CacheTtlSeconds = cacheTtl } }; + return tweak is null ? x : tweak(x); + }); + + /// The Host's stage order with optional extra stages appended after attribution. + public static (InferencePipeline Pipeline, V2Rig.ListSink Sink) Pipeline(BudgetLedger ledger, IReadOnlyDictionary clients, + params IPipelineStage[] after) + { + var sink = new V2Rig.ListSink(); + var kill = new KillSwitch(); + var stages = new List + { + new AuditStage(sink), + new AuthStage(new AuthConfig { AllowAnonymous = false, Keys = [new ApiKeyRecord("demo-key", "demo-service", "platform", "demo-app")] }), + new ShapeStage(), + new ClassifyStage(new RegexDataClassifier()), + new PolicyStage(new PolicyEngine(new PolicyConfig { AllowedRoutes = new Dictionary>() })), + new CacheStage(new ResponseCache(), new CacheConfig()), + new RateLimitStage(new RateCounter(), new RateCounter(), new RateLimitConfig()), + new PauseStage(kill), + new BudgetStage(kill, ledger), + new ProviderCallStage(new Covenant.Adapters.ChatClientRegistry(clients), new ProviderHealth(), classifier: SdkProviderFailureClassifier.Shared), + new AttributionStage(new PriceBook(new Dictionary())), + }; + stages.AddRange(after); + return (new InferencePipeline(stages), sink); + } + + public static InferenceContext Ctx(RuntimeSnapshot snapshot, string prompt, string profile = "public-demo", bool stream = false) + { + var ctx = new InferenceContext(new InferenceRequest("caller", [new ChatMessage(ChatRole.User, prompt)], null, + new AttributionTags("self-declared", "wf", "uc"), Stream: stream, Credential: "demo-key", + RequestId: $"req_{Guid.NewGuid():n}", RequestedProfile: profile)); + ctx.Configuration = snapshot; + ctx.ConfigVersion = snapshot.Version; + return ctx; + } +} + +/// B1 — a stream counts as served ONLY with a terminal finish reason and no error. +public sealed class StreamCompletionTests +{ + private readonly StubChatClient _mini = new("mini reply"); + private readonly StubChatClient _strong = new("strong reply"); + private readonly StubChatClient _local = new("local reply"); + private readonly ResponseCache _cache = new(); + + private V2Rig Rig() => V2Rig.Build(Round2.Config(cacheTtl: 300), new Dictionary + { + [$"openai:{V2.CloudModel}"] = _mini, + ["openai:gpt-4o"] = _strong, + [$"ollama:{V2.LocalTag}"] = _local, + }, cache: _cache); + + [Fact] + public async Task Stream_ending_without_a_finish_reason_is_an_incomplete_stream_provider_failure_never_served_cached_or_continued() + { + _mini.Then(StubChatClient.Mode.StreamNoFinish).Then(StubChatClient.Mode.Serve); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + + Assert.True(ctx.IsDenied); + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(TraceReasons.IncompleteStream, ctx.DenialCode); + Assert.Null(ctx.Response); + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.Equal("UpstreamFailure", e.DenialKind); + Assert.Null(e.ServedByModel); + Assert.Equal(0, _strong.Calls + _local.Calls); // no fallback: content was emitted + Assert.Equal("partial mini reply".Length, ctx.PartialOutputChars); + Assert.Equal("partial mini reply".Length, e.PartialOutputChars); // partial output recorded + var a = Assert.Single(e.Attempts!); + Assert.Equal("failed", a.Outcome); + Assert.Equal("incomplete_stream", a.ErrorClass); + Assert.Equal("estimated_failed_call", a.CostBasis); // charged its estimate + Assert.True(a.CostUsd > 0m); + Assert.Equal(a.ReservedUsd, a.CostUsd); + Assert.Equal(0, rig.Ledger.OpenReservations); + Assert.Equal("failed", rig.Health.Get($"openai:{V2.CloudModel}").State); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "provider" && t.AttemptId == "att_1" && t.State == TraceStates.Failed + && t.ReasonCode == TraceReasons.IncompleteStream); + + // Never cached: the identical request calls the provider again. + var (again, e2) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + Assert.False(again.IsDenied, again.DenialReason); + Assert.False(e2.CacheHit); + Assert.Equal(2, _mini.Calls); + } + + [Fact] + public async Task Stream_throwing_mid_stream_is_terminal_partial_recorded_and_never_cached() + { + _mini.Then(StubChatClient.Mode.StreamThenThrow).Then(StubChatClient.Mode.Serve); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + Assert.Equal(0, _strong.Calls + _local.Calls); + Assert.Equal("partial ".Length, e.PartialOutputChars); + Assert.Equal("5xx", Assert.Single(e.Attempts!).ErrorClass); + var (_, e2) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true); + Assert.False(e2.CacheHit); + Assert.Equal(2, _mini.Calls); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Finish_reason_length_is_served_and_recorded_as_truncated(bool stream) + { + _mini.Then(StubChatClient.Mode.ServeLength); + var rig = Rig(); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: stream); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal("length", ctx.Response!.FinishReason); + Assert.True(Assert.Single(e.Attempts!).Truncated); + Assert.Null(e.PartialOutputChars); + } + + [Fact] + public async Task Host_SSE_relays_the_incomplete_stream_as_upstream_error_and_never_finish_reason_stop() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + factory.Cloud.Then(StubChatClient.Mode.StreamNoFinish).Then(StubChatClient.Mode.Serve); + using var app = factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + app.DefaultRequestHeaders.Add("X-Covenant-Profile", "public-demo"); + + using var resp = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this public announcement.", stream: true)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); // headers committed with the first delta + var body = await resp.Content.ReadAsStringAsync(); + Assert.Contains("partial ", body, StringComparison.Ordinal); + Assert.Contains("\"upstream_error\"", body, StringComparison.Ordinal); + Assert.DoesNotContain("\"finish_reason\":\"stop\"", body, StringComparison.Ordinal); + Assert.EndsWith("data: [DONE]\n\n", body, StringComparison.Ordinal); + var e = await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(resp)); + Assert.Equal(PolicyEffect.Deny, e.Effect); + Assert.Equal("UpstreamFailure", e.DenialKind); + Assert.Equal(0, factory.Local.Calls); // no fallback after content + + // The completed stream still ends with the provider's own finish reason. + using var ok = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this public announcement.", stream: true)); + var okBody = await ok.Content.ReadAsStringAsync(); + Assert.Contains("\"finish_reason\":\"stop\"", okBody, StringComparison.Ordinal); + Assert.DoesNotContain("upstream_error", okBody, StringComparison.Ordinal); + } + + // Reviewer HTTP finding: a legitimately completed EMPTY stream was audited Allow/served but answered 403 "no response", + // because the endpoint treated "no delta written" as "denied". It must be a 200 SSE with the terminal chunk + [DONE]. + [Fact] + public async Task Host_SSE_completed_empty_stream_is_a_successful_200_not_a_denial() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + factory.Cloud.Then(StubChatClient.Mode.StreamEmptyComplete); + using var app = factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + app.DefaultRequestHeaders.Add("X-Covenant-Profile", "public-demo"); + + using var resp = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this public announcement.", stream: true)); + var body = await resp.Content.ReadAsStringAsync(); + + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + Assert.Equal("text/event-stream", resp.Content.Headers.ContentType?.MediaType); + Assert.Contains("\"finish_reason\":\"stop\"", body, StringComparison.Ordinal); + Assert.DoesNotContain("upstream_error", body, StringComparison.Ordinal); + Assert.EndsWith("data: [DONE]\n\n", body, StringComparison.Ordinal); + var e = await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(resp)); + Assert.Equal(PolicyEffect.Allow, e.Effect); // evidence and HTTP outcome agree + } +} + +/// B2 — request-level CostBasis over the charged attempts. +public sealed class AggregateCostBasisTests +{ + private static AttemptRecord A(string basis, decimal cost) => new() { AttemptId = "a", ConnectionId = "c", ModelId = "m", CostBasis = basis, CostUsd = cost }; + + [Fact] + public void Reported_only_when_every_charged_attempt_is_reported_else_the_shared_basis_else_mixed() + { + Assert.Equal("reported", CostBases.Aggregate([A("reported", 0.1m)], "reported")); + Assert.Equal("estimated_failed_call", CostBases.Aggregate([A("estimated_failed_call", 0.1m), A("estimated_failed_call", 0.2m)], "estimated_failed_call")); + Assert.Equal("mixed", CostBases.Aggregate([A("estimated_failed_call", 0.1m), A("reported", 0.2m)], "reported")); + Assert.Equal("reported", CostBases.Aggregate([A("estimated_failed_call", 0m), A("reported", 0.2m)], "reported")); // $0 is not a charge + Assert.Equal("zero_priced", CostBases.Aggregate([A("zero_priced", 0m)], "zero_priced")); // nothing charged + } + + [Fact] + public async Task Failed_estimated_attempt_plus_reported_fallback_is_mixed_in_the_audit_record() + { + var mini = new StubChatClient("mini reply"); + var strong = new StubChatClient("strong reply"); + mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)); + var rig = V2Rig.Build(Round2.Config(), new Dictionary + { + [$"openai:{V2.CloudModel}"] = mini, + ["openai:gpt-4o"] = strong, + }); + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal("estimated_failed_call", e.Attempts![0].CostBasis); + Assert.Equal("reported", e.Attempts[1].CostBasis); + Assert.Equal("mixed", e.CostBasis); // was "reported" for a total containing an estimate + + // FinOps counts it as an estimated-cost request and keeps it out of savings claims. + var f = FinOps.Build([e], V2.LocalTag, V2.LocalTag, new Dictionary(), null); + Assert.Equal(1, f.EstimatedCostRequests); + } +} + +/// B3 — one finite deadline for the whole execution, also after content. +public sealed class DeadlineAfterContentTests +{ + [Fact] + public async Task Deadline_after_streamed_content_is_a_timeout_with_partial_output_and_no_fallback() + { + var mini = new StubChatClient("mini reply") { Gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) }; // never released + var strong = new StubChatClient("strong reply"); + mini.Then(StubChatClient.Mode.StreamGated); + var rig = V2Rig.Build(Round2.Config(deadlineMs: 300), new Dictionary + { + [$"openai:{V2.CloudModel}"] = mini, + ["openai:gpt-4o"] = strong, + }); + using var safety = new CancellationTokenSource(TimeSpan.FromSeconds(5)); // pre-fix: the stream hangs until this fires + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", stream: true, ct: safety.Token); + + Assert.False(safety.IsCancellationRequested); + Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); + var a = Assert.Single(e.Attempts!); + Assert.Equal("failed", a.Outcome); + Assert.Equal("timeout", a.ErrorClass); + Assert.Equal("partial ".Length, e.PartialOutputChars); + Assert.Equal(0, strong.Calls); + Assert.True(a.CostUsd > 0m); + Assert.Contains("deadline", e.Reason, StringComparison.Ordinal); + Assert.Equal(0, rig.Ledger.OpenReservations); + } +} + +/// B4 — every admitted attempt settled/released exactly once; a slot closes only after the durable write. +public sealed class SettlementRobustnessTests +{ + private static readonly RouteTarget Mini = new("openai", V2.CloudModel); + + [Fact] + public void A_failed_settle_write_leaves_the_slot_open_and_a_retry_settles_exactly_once() + { + var store = new FlakyLedgerStore(); + var ledger = new BudgetLedger(store); + var snapshot = new RuntimeSnapshot(Round2.Config()); + var ctx = Round2.Ctx(snapshot, V2Rig.PublicPrompt); + var gate = new BudgetAttemptGate(ledger, new KillSwitch(), snapshot, ctx); + Assert.True(gate.ReserveFirst(ctx, Mini).Admitted); + Assert.Equal(1, ledger.OpenReservations); + + store.FailNext(LedgerOps.Settle); + Assert.Throws(() => gate.Settle(ctx, "att_1", null)); + Assert.Equal(1, gate.OpenSlots); // NOT marked closed before the durable write succeeded + Assert.Equal(1, ledger.OpenReservations); // reservation still held (never silently lost) + Assert.Null(ctx.SettledUsd); + + var charge = gate.Settle(ctx, "att_1", null); + Assert.True(charge.Settled); + Assert.Equal(0, gate.OpenSlots); + Assert.Equal(0, ledger.OpenReservations); + Assert.False(gate.Settle(ctx, "att_1", null).Settled); // idempotent afterwards + Assert.Equal(new[] { LedgerOps.Reserve, LedgerOps.Settle, LedgerOps.Release }, store.Records.Select(r => r.Op)); + Assert.Equal(charge.CostUsd, ctx.SettledUsd); + } + + [Fact] + public void A_failed_release_write_leaves_the_slot_open_and_a_retry_releases_once() + { + var store = new FlakyLedgerStore(); + var ledger = new BudgetLedger(store); + var snapshot = new RuntimeSnapshot(Round2.Config()); + var ctx = Round2.Ctx(snapshot, V2Rig.PublicPrompt); + var gate = new BudgetAttemptGate(ledger, new KillSwitch(), snapshot, ctx); + gate.ReserveFirst(ctx, Mini); + store.FailNext(LedgerOps.Release); + Assert.Throws(() => gate.Release(ctx, "att_1")); + Assert.Equal(1, gate.OpenSlots); + gate.Finish(ctx); // the unwind backstop releases it + Assert.Equal(0, gate.OpenSlots); + Assert.Equal(0, ledger.OpenReservations); + Assert.Equal(new[] { LedgerOps.Reserve, LedgerOps.Release }, store.Records.Select(r => r.Op)); + } + + [Fact] + public async Task Pipeline_settle_failure_is_retried_by_the_unwind_and_settles_exactly_once() + { + var store = new FlakyLedgerStore(); + var ledger = new BudgetLedger(store); + var (pipeline, sink) = Round2.Pipeline(ledger, new Dictionary { [$"openai:{V2.CloudModel}"] = new StubChatClient("mini") }); + var ctx = Round2.Ctx(new RuntimeSnapshot(Round2.Config()), V2Rig.PublicPrompt); + store.FailNext(LedgerOps.Settle); + + await Assert.ThrowsAsync(() => pipeline.ExecuteAsync(ctx, CancellationToken.None)); + Assert.Equal(1, store.Failures); + Assert.Equal(0, ledger.OpenReservations); // pre-fix: the slot was closed before the failed write ⇒ stuck open + Assert.Equal(0m, ledger.Reserved("global")); + Assert.Single(store.Records, r => r.Op == LedgerOps.Settle); + Assert.Single(sink.Entries); // the request is still evidenced + } + + [Fact] + public async Task Persistent_write_failure_keeps_state_consistent_and_boot_recovery_settles_once() + { + var store = new FlakyLedgerStore(); + var ledger = new BudgetLedger(store); + var (pipeline, _) = Round2.Pipeline(ledger, new Dictionary { [$"openai:{V2.CloudModel}"] = new StubChatClient("mini") }); + var ctx = Round2.Ctx(new RuntimeSnapshot(Round2.Config()), V2Rig.PublicPrompt); + store.FailNext(LedgerOps.Settle, count: int.MaxValue); + + await Assert.ThrowsAsync(() => pipeline.ExecuteAsync(ctx, CancellationToken.None)); + Assert.Equal(1, ledger.OpenReservations); // held, uncharged: the durable state the next boot sees + var reserved = store.Records.Single(r => r.Op == LedgerOps.Reserve).AmountUsd; + + // "Restart": replay what was durably written; recovery settles the open reservation exactly once. + var after = new BudgetLedger(new InMemoryLedgerStore(), store.Records); + var recovered = Assert.Single(after.RecoverUnsettled()); + Assert.Equal(LedgerOps.SettleRecovered, recovered.Op); + Assert.Equal(reserved, after.Spent("global", BudgetPeriod.Monthly)); + Assert.Empty(after.RecoverUnsettled()); + } + + [Fact] + public async Task Exception_after_attribution_still_settles_the_served_attempt_exactly_once_at_its_priced_cost() + { + var store = new FlakyLedgerStore(); + var ledger = new BudgetLedger(store); + var (pipeline, sink) = Round2.Pipeline(ledger, new Dictionary { [$"openai:{V2.CloudModel}"] = new StubChatClient("mini") }, + new ThrowingStage()); + var ctx = Round2.Ctx(new RuntimeSnapshot(Round2.Config()), V2Rig.PublicPrompt); + + await Assert.ThrowsAsync(() => pipeline.ExecuteAsync(ctx, CancellationToken.None)); + Assert.Equal(new[] { LedgerOps.Reserve, LedgerOps.Settle, LedgerOps.Release }, store.Records.Select(r => r.Op)); + Assert.Equal(0, ledger.OpenReservations); + var a = Assert.Single(ctx.Attempts); + Assert.Equal("reported", a.CostBasis); // settled by the provider stage's finally with the priced cost + Assert.Equal(10 / 1_000_000m * 0.15m + 5 / 1_000_000m * 0.60m, a.CostUsd); + Assert.Single(sink.Entries); // still exactly one evidence record + } +} + +/// B5 — unambiguous cache keys and served provenance (reviewer probe cache-collision-probe.cs.txt). +public sealed class CacheKeyCollisionTests +{ + private static async Task<(int Calls, bool SecondHit)> TwoRunsAsync(Func first, Func second) + { + var cache = new CacheStage(new ResponseCache(), new CacheConfig { TtlSeconds = 60 }); + int calls = 0; + Task Next(InferenceContext c, CancellationToken t) + { + calls++; + c.Response = new(new(ChatRole.Assistant, "response-" + calls), Usage.Empty, "model"); + return Task.CompletedTask; + } + await cache.InvokeAsync(first(), Next, default); + var b = second(); + await cache.InvokeAsync(b, Next, default); + return (calls, b.ServedFromCache); + } + + private static InferenceContext Legacy(params ChatMessage[] messages) + => new(new InferenceRequest("app", messages, "model", new("team", "flow", "case"))) { Policy = PolicyOutcome.Allow(new("connection", "model")) }; + + private static readonly RuntimeSnapshot Snapshot = new(V2.Hybrid(tweak: c => c with { Settings = new OperationalSettings { CacheTtlSeconds = 60 } })); + + private static InferenceContext Configured(params ChatMessage[] messages) + { + var ctx = new InferenceContext(new InferenceRequest("app", messages, null, new("platform", "flow", "case"))) { Configuration = Snapshot, ApplicationId = "demo-app" }; + ctx.Policy = PolicyOutcome.Allow(new("openai", V2.CloudModel)) with { Candidates = [new("openai", V2.CloudModel), new("ollama", V2.LocalTag)] }; + return ctx; + } + + public static TheoryData Shapes => new() { "delimiter-in-content", "boundary-shift", "control-chars", "role", "empty-vs-absent" }; + + private static ChatMessage U(string content) => new(ChatRole.User, content); + + private static (ChatMessage[] A, ChatMessage[] B) Pair(string shape) + { + switch (shape) + { + case "delimiter-in-content": return (new[] { U("x\u001fAssistant:y") }, new[] { U("x"), new ChatMessage(ChatRole.Assistant, "y") }); + case "boundary-shift": return (new[] { U("ab"), U("c") }, new[] { U("a"), U("bc") }); + case "control-chars": return (new[] { U("a\u001e"), U("b") }, new[] { U("a"), U("\u001eb") }); + case "role": return (new[] { new ChatMessage(ChatRole.System, "x") }, new[] { U("x") }); + case "empty-vs-absent": return (new[] { U("x"), U("") }, new[] { U("x") }); + default: throw new ArgumentOutOfRangeException(nameof(shape)); + } + } + + [Theory] + [MemberData(nameof(Shapes))] + public async Task Different_message_structures_never_collide_legacy_key(string shape) + { + var (a, b) = Pair(shape); + var (calls, hit) = await TwoRunsAsync(() => Legacy(a), () => Legacy(b)); + Assert.Equal(2, calls); + Assert.False(hit); + } + + [Theory] + [MemberData(nameof(Shapes))] + public async Task Different_message_structures_never_collide_configured_key(string shape) + { + var (a, b) = Pair(shape); + var (calls, hit) = await TwoRunsAsync(() => Configured(a), () => Configured(b)); + Assert.Equal(2, calls); + Assert.False(hit); + } + + [Fact] + public async Task Exact_repeat_still_hits() + { + var (calls, hit) = await TwoRunsAsync(() => Configured(new ChatMessage(ChatRole.User, "same")), () => Configured(new ChatMessage(ChatRole.User, "same"))); + Assert.Equal(1, calls); + Assert.True(hit); + } + + [Fact] + public async Task Reviewer_probe_capped_primary_and_less_capped_fallback_with_max_tokens_20_then_10_are_two_calls() + { + var config = new CovenantConfig + { + Version = 1, Origin = "probe", CreatedUtc = DateTimeOffset.UtcNow, Mode = ProviderMode.LocalOnly, + Connections = [new ConnectionConfig { Id = "local", DisplayName = "Fixture", Kind = ProviderKind.Ollama, Boundary = Boundary.Local, Enabled = true, + Models = [new ModelConfig { ModelId = "primary", MaxOutputTokens = 2 }, new ModelConfig { ModelId = "fallback", MaxOutputTokens = 100 }] }], + Applications = [new ApplicationConfig { Id = "app", Team = "team", Enabled = true, ConsoleTesting = true, GrantedProfiles = [], MaxOutputTokens = 100 }], + Profiles = [], Policies = [], Budgets = [], Settings = new OperationalSettings { CacheTtlSeconds = 60 }, + }; + var snapshot = new RuntimeSnapshot(config); + InferenceContext B(int max) => new(new InferenceRequest("app", [new(ChatRole.User, "test")], null, new("team", "flow", "case"), MaxOutputTokens: max)) + { + Configuration = snapshot, ApplicationId = "app", + Policy = PolicyOutcome.Allow(new("local", "primary")) with { Candidates = [new("local", "primary"), new("local", "fallback")] }, + }; + var (calls, hit) = await TwoRunsAsync(() => B(20), () => B(10)); + Assert.Equal(2, calls); + Assert.False(hit); + } + + [Fact] + public async Task A_hit_reports_the_connection_and_model_that_actually_served_not_the_primary() + { + var mini = new StubChatClient("mini reply"); + var strong = new StubChatClient("strong reply"); + var local = new StubChatClient("local reply"); + mini.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)).Then(StubChatClient.Mode.Serve); + strong.Then(StubChatClient.Mode.Throw, () => Failures.Status(HttpStatusCode.ServiceUnavailable)).Then(StubChatClient.Mode.Serve); + var rig = V2Rig.Build(Round2.Config(cacheTtl: 300), new Dictionary + { + [$"openai:{V2.CloudModel}"] = mini, + ["openai:gpt-4o"] = strong, + [$"ollama:{V2.LocalTag}"] = local, + }); + var (_, first) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal("ollama", first.ServedConnectionId); + Assert.Equal(V2.LocalTag, first.ServedByModel); + + var (hitCtx, hit) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.True(hit.CacheHit); + Assert.Equal(1, local.Calls); + Assert.Equal(new RouteTarget("ollama", V2.LocalTag), hitCtx.ServedTarget); + Assert.Equal("ollama", hit.ServedConnectionId); + Assert.Equal(V2.LocalTag, hit.ServedByModel); + Assert.Equal(V2.CloudModel, hit.SelectedModel); // the policy's primary stays visible as "selected" + } +} + +/// B6 — identity team = the ACTIVE application's team on both entry points. +public sealed class TeamConsistencyTests +{ + private const decimal OneRequest = 10 / 1_000_000m * 0.15m + 5 / 1_000_000m * 0.60m; + + [Fact] + public async Task Team_change_applied_through_configuration_governs_new_v1_and_console_charges_and_history_stays() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + using var app = factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); // key's startup team: platform + app.DefaultRequestHeaders.Add("X-Covenant-Profile", "public-demo"); + + using (var before = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this public announcement."))) + Assert.Equal("platform", (await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(before))).Tags.Team); + + var (version, cfg, _) = await V2Admin.GetConfigAsync(admin); + await V2Admin.ApplyAsync(admin, cfg with + { + Applications = cfg.Applications.Select(a => a.Id == "demo-app" ? a with { Team = "payments" } : a).ToList(), + }, version, "move demo-app to payments"); + + using var v1 = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("Summarize this other public announcement.")); + Assert.Equal(HttpStatusCode.OK, v1.StatusCode); + Assert.Equal("payments", (await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(v1))).Tags.Team); // pre-fix: platform + + using var console = await Playground.PostAsync(admin, Playground.Body("demo-app", "Summarize a third public announcement.", profile: "public-demo")); + Assert.Equal(HttpStatusCode.OK, console.StatusCode); + Assert.Equal("payments", (await CorrelationTestKit.LookupAsync(admin, CorrelationTestKit.HeaderId(console))).Tags.Team); + + var (_, status, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/status"); + var teams = status.GetProperty("budget").GetProperty("teams").EnumerateArray() + .ToDictionary(t => t.GetProperty("team").GetString()!, t => t.GetProperty("spend_usd").GetDecimal(), StringComparer.OrdinalIgnoreCase); + Assert.Equal(OneRequest, teams["platform"]); // historical charge stays where it was recorded + Assert.Equal(2 * OneRequest, teams["payments"]); // both entry points charge the new team + } +} + +/// B7 — console request id available before the first response byte. +public sealed class EarlyRequestIdTests +{ + [Fact] + public async Task Submission_lookup_returns_the_request_id_while_the_provider_blocks_and_the_trace_shows_provider_running() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + factory.Cloud.Gate = gate; + factory.Cloud.Then(StubChatClient.Mode.Gated).Then(StubChatClient.Mode.Serve); + const string crid = "crid-early-7f3a"; + + var post = Playground.PostAsync(admin, Playground.Body("demo-app", "Summarize this public announcement.", profile: "public-demo", + clientRequestId: crid, maxTokens: 256)); + await factory.Cloud.Entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + + var (status, sub, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, $"/admin/playground/submissions/{crid}"); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(crid, sub.GetProperty("client_request_id").GetString()); + Assert.Equal("running", sub.GetProperty("state").GetString()); + var requestId = sub.GetProperty("request_id").GetString()!; + Assert.True(RequestCorrelation.IsWellFormed(requestId)); + + var (traceStatus, trace, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, $"/admin/requests/{requestId}/trace"); + Assert.Equal(HttpStatusCode.OK, traceStatus); + Assert.False(trace.GetProperty("complete").GetBoolean()); + var events = trace.GetProperty("events").EnumerateArray().ToList(); + var running = events.Last(e => e.GetProperty("stage").GetString() == "provider"); + Assert.Equal("running", running.GetProperty("state").GetString()); + Assert.Equal("att_1", running.GetProperty("attempt_id").GetString()); + Assert.Equal(256, running.GetProperty("requested_max_output_tokens").GetInt32()); // B12 on trace attempt events + Assert.Equal(256, running.GetProperty("effective_max_output_tokens").GetInt32()); + + gate.SetResult(); + using var resp = await post; + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + Assert.Equal(requestId, CorrelationTestKit.HeaderId(resp)); + var (_, done, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, $"/admin/playground/submissions/{crid}"); + Assert.Equal("completed", done.GetProperty("state").GetString()); + + var (missing, missingBody, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/playground/submissions/never-submitted"); + Assert.Equal(HttpStatusCode.NotFound, missing); + Assert.Equal("not_found", missingBody.GetProperty("error").GetString()); + using var noToken = await admin.GetAsync($"/admin/playground/submissions/{crid}"); + Assert.Equal(HttpStatusCode.Unauthorized, noToken.StatusCode); + } + + [Fact] + public void Client_request_id_is_required_and_bounded() + { + PlaygroundRequest Body(string? crid) => new() + { + ApplicationId = "demo-app", Messages = [new PlaygroundMessage { Role = "user", Content = "x" }], ClientRequestId = crid, + }; + Assert.NotNull(PlaygroundApi.Validate(Body(null))); + Assert.NotNull(PlaygroundApi.Validate(Body(""))); + Assert.NotNull(PlaygroundApi.Validate(Body(new string('a', 65)))); + Assert.NotNull(PlaygroundApi.Validate(Body("a.b"))); + Assert.Null(PlaygroundApi.Validate(Body(new string('a', 64)))); + Assert.Null(PlaygroundApi.Validate(Body("run_7f3a-B"))); + } +} + +/// B8 — stable newest-first paging anchored by absolute index; rotation ⇒ 410. +public sealed class StablePaginationTests : IDisposable +{ + private readonly RestartableHybridFactory _factory = new(RestartableHybridFactory.NewAuditPath()); + private readonly HttpClient _admin; + + public StablePaginationTests() => _admin = _factory.CreateClient(); + + public void Dispose() => _factory.Dispose(); + + private async Task RunAsync(string prompt) + { + using var resp = await Playground.PostAsync(_admin, Playground.Body("demo-app", prompt)); + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + var id = CorrelationTestKit.HeaderId(resp); + await CorrelationTestKit.LookupAsync(_admin, id); + return id; + } + + private async Task<(HttpStatusCode Status, JsonElement Body)> GetAsync(string path) + { + var (status, body, _) = await V2Admin.SendAsync(_admin, HttpMethod.Get, path); + return (status, body); + } + + private static List Ids(JsonElement page) => page.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("Id").GetString()!).ToList(); + + [Fact] + public async Task Insert_between_pages_causes_no_duplicates_and_no_gaps() + { + var r1 = await RunAsync("first internal question"); + var r2 = await RunAsync("second internal question"); + var r3 = await RunAsync("third internal question"); + + var (_, page1) = await GetAsync("/admin/requests?limit=2"); + Assert.Equal(new[] { r3, r2 }, Ids(page1)); + var segment = page1.GetProperty("segment"); + Assert.Equal("current", segment.GetProperty("id").GetString()); + Assert.True(segment.GetProperty("is_current").GetBoolean()); + Assert.False(string.IsNullOrEmpty(segment.GetProperty("label").GetString())); + var cursor = page1.GetProperty("next_cursor").GetString()!; + + var r4 = await RunAsync("a newer internal question arrives between pages"); + + var (status, page2) = await GetAsync($"/admin/requests?limit=2&cursor={Uri.EscapeDataString(cursor)}"); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(new[] { r1 }, Ids(page2)); // pre-fix: r2 again (offset shifted by the insert) + Assert.Equal(JsonValueKind.Null, page2.GetProperty("next_cursor").ValueKind); + Assert.True(page2.GetProperty("segment").GetProperty("is_current").GetBoolean()); + + var (_, fresh) = await GetAsync("/admin/requests?limit=2"); + Assert.Equal(new[] { r4, r3 }, Ids(fresh)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task A_cursor_issued_before_a_rotation_is_410_cursor_expired_never_redirected(bool newRecordAfterRotation) + { + await RunAsync("first internal question"); + await RunAsync("second internal question"); + var (_, page1) = await GetAsync("/admin/requests?limit=1"); + var cursor = page1.GetProperty("next_cursor").GetString()!; + + var (resetStatus, _, _) = await V2Admin.SendAsync(_admin, HttpMethod.Post, "/admin/reset"); + Assert.Equal(HttpStatusCode.OK, resetStatus); + if (newRecordAfterRotation) await RunAsync("after the rotation"); + + var (status, body) = await GetAsync($"/admin/requests?limit=1&cursor={Uri.EscapeDataString(cursor)}"); + Assert.Equal(HttpStatusCode.Gone, status); + Assert.Equal("cursor_expired", body.GetProperty("error").GetString()); + } + + [Fact] + public async Task Archived_segment_pages_carry_their_descriptor() + { + await RunAsync("first internal question"); + await RunAsync("second internal question"); + await V2Admin.SendAsync(_admin, HttpMethod.Post, "/admin/reset"); + var (_, segments) = await GetAsync("/admin/audit/segments"); + var archivedId = segments.EnumerateArray().Single(s => !s.GetProperty("current").GetBoolean()).GetProperty("id").GetString()!; + var (_, page1) = await GetAsync($"/admin/requests?segment={archivedId}&limit=1"); + Assert.False(page1.GetProperty("segment").GetProperty("is_current").GetBoolean()); + Assert.Equal(archivedId, page1.GetProperty("segment").GetProperty("id").GetString()); + var (status, page2) = await GetAsync($"/admin/requests?cursor={Uri.EscapeDataString(page1.GetProperty("next_cursor").GetString()!)}"); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Single(Ids(page2)); + } +} + +/// B9 — atomic ledger bootstrap with a completion marker; B10 — replay validation. +public sealed class LedgerBootstrapAndReplayTests : IDisposable +{ + private readonly string _path = Path.Combine(Path.GetTempPath(), $"covenant-ledger-r2-{Guid.NewGuid():n}.jsonl"); + + public void Dispose() => CorrelationTestKit.DeleteWithSiblings(_path); + + private static readonly DateTimeOffset Now = DateTimeOffset.Parse("2026-10-17T12:00:00Z"); + private static readonly (string, decimal)[] TwoTeams = [("payments", 1.5m), ("data", 0.5m)]; + + private static string Line(string op, string req, string att, string scopes, string amount = "0.1", string ts = "2026-10-17T10:00:00+00:00", bool overrun = false) + => $"{{\"op\":\"{op}\",\"request_id\":\"{req}\",\"attempt_id\":\"{att}\",\"scopes\":[{scopes}],\"amount_usd\":{amount},\"ts_utc\":\"{ts}\"{(overrun ? ",\"overrun\":true" : "")}}}"; + + private const string G = "\"global\",\"team:platform\""; + private static readonly string Marker = Line("bootstrap-complete", "bootstrap", "bootstrap-complete", "", "0"); + + [Fact] + public void Fresh_bootstrap_imports_every_team_once_atomically_with_the_marker_and_is_never_repeated() + { + int calls = 0; + var opened = LedgerBootstrap.OpenOrBootstrap(new FileLedgerStore(_path), () => { calls++; return TwoTeams; }, Now); + Assert.Empty(opened.Errors); + Assert.False(opened.Existed); + Assert.Equal(new[] { LedgerOps.LegacyImport, LedgerOps.LegacyImport, LedgerOps.BootstrapComplete }, opened.Records.Select(r => r.Op)); + Assert.False(File.Exists(_path + ".bootstrap.tmp")); + var ledger = new BudgetLedger(new FileLedgerStore(_path), opened.Records, new SettableClock(Now)); + Assert.Equal(2m, ledger.Spent("global", BudgetPeriod.Monthly)); + + var again = LedgerBootstrap.OpenOrBootstrap(new FileLedgerStore(_path), () => { calls++; return TwoTeams; }, Now); + Assert.Empty(again.Errors); + Assert.True(again.Existed); + Assert.Equal(1, calls); // the import never runs twice + Assert.Equal(2m, new BudgetLedger(new InMemoryLedgerStore(), again.Records, new SettableClock(Now)).Spent("global", BudgetPeriod.Monthly)); + } + + [Fact] + public void Interruption_after_create_before_import_refuses_start_and_never_restores_capacity() + { + File.WriteAllText(_path, ""); // what the pre-fix EnsureCreated left behind + Assert.NotEmpty(new FileLedgerStore(_path).Open().Errors); // pre-fix: accepted silently ⇒ legacy spend lost + int calls = 0; + var opened = LedgerBootstrap.OpenOrBootstrap(new FileLedgerStore(_path), () => { calls++; return TwoTeams; }, Now); + Assert.Contains(opened.Errors, e => e.Contains("bootstrap-complete", StringComparison.Ordinal)); + Assert.Equal(0, calls); + Assert.Equal("", File.ReadAllText(_path)); // evidence untouched + } + + [Fact] + public void Partway_through_a_multi_team_import_refuses_start() + { + var oneOfTwo = Line("legacy-import", "legacy-import", "team:payments", "\"global\",\"team:payments\"", "1.5"); + File.WriteAllText(_path, oneOfTwo + "\n"); + Assert.NotEmpty(new FileLedgerStore(_path).Open().Errors); + + // Same with the second team's line torn mid-write: never quarantine-and-continue on a half import. + File.WriteAllText(_path, oneOfTwo + "\n{\"op\":\"legacy-import\",\"request_id\":\"legacy-imp"); + Assert.NotEmpty(new FileLedgerStore(_path).Open().Errors); + } + + [Fact] + public void Interruption_before_the_rename_leaves_no_ledger_and_the_next_boot_bootstraps_once() + { + File.WriteAllText(_path + ".bootstrap.tmp", Line("legacy-import", "legacy-import", "team:payments", "\"global\",\"team:payments\"", "1.5") + "\n"); + var opened = LedgerBootstrap.OpenOrBootstrap(new FileLedgerStore(_path), () => TwoTeams, Now); + Assert.Empty(opened.Errors); + Assert.Equal(2m, new BudgetLedger(new InMemoryLedgerStore(), opened.Records, new SettableClock(Now)).Spent("global", BudgetPeriod.Monthly)); + } + + [Fact] + public void Duplicate_legacy_import_lines_are_idempotent_per_scope() + { + var imp = Line("legacy-import", "legacy-import", "team:payments", "\"global\",\"team:payments\"", "1.5", "2026-10-17T10:00:00+00:00"); + File.WriteAllText(_path, imp + "\n" + imp + "\n" + Marker + "\n"); + var opened = new FileLedgerStore(_path).Open(); + Assert.Empty(opened.Errors); + var ledger = new BudgetLedger(new InMemoryLedgerStore(), opened.Records, new SettableClock(Now)); + Assert.Equal(1.5m, ledger.Spent("team:payments", BudgetPeriod.Monthly)); + Assert.Empty(ledger.ImportLegacy([("payments", 1.5m)])); // a replayed import adds nothing + } + + [Fact] + public void Pre_marker_journal_with_recorded_operations_is_accepted_once_with_the_marker_appended() + { + File.WriteAllText(_path, Line("reserve", "r1", "att_1", G) + "\n" + Line("settle", "r1", "att_1", G) + "\n" + Line("release", "r1", "att_1", G, "0") + "\n"); + var first = new FileLedgerStore(_path).Open(); + Assert.Empty(first.Errors); + Assert.NotEmpty(first.Warnings); + var second = new FileLedgerStore(_path).Open(); + Assert.Empty(second.Errors); + Assert.Empty(second.Warnings); + Assert.Single(second.Records, r => r.Op == LedgerOps.BootstrapComplete); + } + + public static TheoryData Violations => new() + { + { "unknown-op", Line("refund", "r1", "att_1", G), "unknown op" }, + { "negative", Line("reserve", "r1", "att_1", G, "-1"), "negative amount" }, + { "empty-request", Line("reserve", "", "att_1", G), "empty request_id" }, + { "empty-attempt", Line("reserve", "r1", "", G), "empty attempt_id" }, + { "bad-scope", Line("reserve", "r1", "att_1", "\"teamx\""), "invalid scope" }, + { "empty-team", Line("reserve", "r1", "att_1", "\"global\",\"team:\""), "invalid scope" }, + { "no-scopes", Line("reserve", "r1", "att_1", ""), "without scopes" }, + { "min-ts", Line("reserve", "r1", "att_1", G, ts: "0001-01-01T00:00:00+00:00"), "ts_utc" }, + { "settle-unreserved", Line("settle", "r9", "att_1", G), "settle without a reservation" }, + { "release-unreserved", Line("release", "r9", "att_1", G), "release without a reservation" }, + { "recover-unreserved", Line("settle-recovered", "r9", "att_1", G), "settle-recovered without a reservation" }, + { "double-settle", Line("settle", "r0", "att_1", G), "second settle" }, + { "double-reserve", Line("reserve", "r0", "att_1", G), "second reserve" }, + { "release-after-close", Line("release", "rc", "att_1", G, "0"), "release after the attempt was closed" }, + { "import-after-marker", Line("legacy-import", "legacy-import", "team:x", "\"global\",\"team:x\"", "1"), "after the bootstrap-complete marker" }, + { "second-marker", Marker, "duplicate bootstrap-complete" }, + }; + + [Theory] + [MemberData(nameof(Violations))] + public void A_violation_in_a_non_tail_line_refuses_start_with_a_precise_diagnostic(string name, string bad, string expected) + { + Assert.NotNull(name); + var prefix = new[] + { + Marker, + Line("reserve", "r0", "att_1", G), Line("settle", "r0", "att_1", G), // r0 settled + Line("reserve", "rc", "att_1", G), Line("settle-recovered", "rc", "att_1", G), // rc closed + }; + var lines = prefix.Append(bad).Append(Line("reserve", "tail", "att_1", G)).ToArray(); // valid tail after it + File.WriteAllText(_path, string.Join("\n", lines) + "\n"); + var opened = new FileLedgerStore(_path).Open(); + var error = Assert.Single(opened.Errors); + Assert.Contains($"line {prefix.Length + 1} ", error, StringComparison.Ordinal); + Assert.Contains(expected, error, StringComparison.Ordinal); + } + + [Fact] + public void Non_iso_timestamp_is_a_corrupt_line() + { + File.WriteAllText(_path, Marker + "\n" + Line("reserve", "r1", "att_1", G, ts: "yesterday") + "\n" + Line("reserve", "r2", "att_1", G) + "\n"); + Assert.Contains(new FileLedgerStore(_path).Open().Errors, e => e.Contains("line 2 ", StringComparison.Ordinal)); + } + + [Fact] + public void A_valid_full_lifecycle_replays_cleanly_and_an_unknown_op_never_silently_disappears_in_memory() + { + File.WriteAllText(_path, string.Join("\n", + Marker, + Line("reserve", "r1", "att_1", G), Line("settle", "r1", "att_1", G, "0.05"), Line("release", "r1", "att_1", G, "0.05"), + Line("reserve", "r2", "att_1", G), Line("release", "r2", "att_1", G), + Line("settle", "r3", "att_1", G, "0.2", overrun: true), + Line("reserve", "r4", "att_1", G), Line("settle-recovered", "r4", "att_1", G)) + "\n"); + var opened = new FileLedgerStore(_path).Open(); + Assert.Empty(opened.Errors); + Assert.Equal(0.05m + 0.2m + 0.1m, new BudgetLedger(new InMemoryLedgerStore(), opened.Records, new SettableClock(Now)).Spent("global", BudgetPeriod.None)); + + var bogus = new LedgerRecord { Op = "refund", RequestId = "r", AttemptId = "a", Scopes = ["global"], AmountUsd = 1m, TsUtc = Now }; + Assert.Throws(() => new BudgetLedger(new InMemoryLedgerStore(), [bogus])); + } +} + +/// B11 — header local health from CURRENT runtime connection health. +public sealed class LocalHealthTests +{ + [Fact] + public async Task After_a_successful_governed_local_call_catalog_and_status_show_that_connection_model_ok_and_a_legacy_local_connection_does_not_shadow_it() + { + using var factory = new RestartableHybridFactory(RestartableHybridFactory.NewAuditPath()); + var admin = factory.CreateClient(); + + // A stale legacy-style connection literally named "local" (pre-fix: catalog.local always picked it). + var (version, cfg, _) = await V2Admin.GetConfigAsync(admin); + await V2Admin.ApplyAsync(admin, cfg with + { + Connections = cfg.Connections.Append(new ConnectionConfig + { + Id = "local", DisplayName = "Legacy local", Kind = ProviderKind.Ollama, Boundary = Boundary.Local, + Endpoint = "http://127.0.0.1:11434/v1", Enabled = true, + Models = [new ModelConfig { ModelId = "legacy-model", Price = new PriceConfig { InputPer1M = 0m, OutputPer1M = 0m, Basis = "zero-marginal-local" } }], + }).ToList(), + }, version, "legacy local connection"); + + using var app = factory.CreateClient(); + app.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "demo-key"); + using var resp = await app.PostAsync("/v1/chat/completions", CorrelationTestKit.Chat("an internal question")); // Internal → ollama + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + Assert.Equal(1, factory.Local.Calls); + + var (_, catalog, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/catalog"); + var local = catalog.GetProperty("local"); + Assert.Equal("ollama", local.GetProperty("connection_id").GetString()); + Assert.Equal(V2.LocalTag, local.GetProperty("model_id").GetString()); + Assert.Equal("ok", local.GetProperty("health").GetProperty("state").GetString()); + var conn = catalog.GetProperty("connections").EnumerateArray().Single(c => c.GetProperty("id").GetString() == "ollama"); + Assert.Equal("ok", conn.GetProperty("models")[0].GetProperty("health").GetProperty("state").GetString()); + + var (_, status, _) = await V2Admin.SendAsync(admin, HttpMethod.Get, "/admin/status"); + var health = status.GetProperty("connection_health").EnumerateArray().ToList(); + Assert.Equal("ok", health.Single(h => h.GetProperty("key").GetString() == $"ollama:{V2.LocalTag}").GetProperty("health").GetProperty("state").GetString()); + Assert.Equal("unknown", health.Single(h => h.GetProperty("key").GetString() == "local:legacy-model").GetProperty("health").GetProperty("state").GetString()); + } +} + +/// B12 — requested vs effective output bound in audit v3 and on attempts. +public sealed class OutputBoundEvidenceTests +{ + [Fact] + public async Task Audit_records_requested_and_effective_bounds_per_attempt_and_on_the_record() + { + var mini = new StubChatClient("mini reply"); + var rig = V2Rig.Build(Round2.Config(tweak: c => c with + { + Connections = c.Connections.Select(x => x.Id != "openai" ? x : x with + { + Models = x.Models.Select(m => m.ModelId == V2.CloudModel ? m with { MaxOutputTokens = 64 } : m).ToList(), + }).ToList(), + }), new Dictionary { [$"openai:{V2.CloudModel}"] = mini }); + + var (ctx, e) = await rig.RunAsync(V2Rig.PublicPrompt, profile: "public-demo", maxTokens: 256); + Assert.False(ctx.IsDenied, ctx.DenialReason); + Assert.Equal(256, e.RequestedMaxOutputTokens); + Assert.Equal(64, e.EffectiveMaxOutputTokens); + Assert.Equal(64, Assert.Single(e.Attempts!).EffectiveMaxOutputTokens); + Assert.Equal(64, mini.LastOptions?.MaxOutputTokens); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "provider" && t.AttemptId == "att_1" && t.RequestedMaxOutputTokens == 256 && t.EffectiveMaxOutputTokens == 64); + + var (_, noMax) = await rig.RunAsync(V2Rig.PublicPrompt + " again", profile: "public-demo"); + Assert.Null(noMax.RequestedMaxOutputTokens); + Assert.Equal(64, noMax.EffectiveMaxOutputTokens); + } +} diff --git a/tests/Covenant.Tests/RuntimeV2TestKit.cs b/tests/Covenant.Tests/RuntimeV2TestKit.cs index 0146919..38c1c67 100644 --- a/tests/Covenant.Tests/RuntimeV2TestKit.cs +++ b/tests/Covenant.Tests/RuntimeV2TestKit.cs @@ -25,7 +25,18 @@ internal sealed class SettableClock(DateTimeOffset start) : TimeProvider /// behaviour (the last one repeats). Records the ChatOptions it saw. internal sealed class StubChatClient(string reply = "stub reply") : MEAI.IChatClient { - public enum Mode { Serve, ServeNoUsage, Throw, Hang, StreamThenThrow, ServeHugeUsage, StreamGated } + public enum Mode + { + Serve, ServeNoUsage, Throw, Hang, StreamThenThrow, ServeHugeUsage, StreamGated, + /// Streams text, then ends WITHOUT a terminal update carrying a finish reason (review round 2, B1). + StreamNoFinish, + /// Buffered/streamed: served with finish reason "length" (truncated at the output bound). + ServeLength, + /// Buffered: waits for before serving (B7 early request id). + Gated, + /// Streamed: a legitimately COMPLETED stream with no text at all (terminal update only). + StreamEmptyComplete, + } /// StreamGated: the first chunk is sent, then the stream waits for this gate before finishing. public TaskCompletionSource? Gate { get; set; } @@ -69,6 +80,9 @@ public StubChatClient Then(Mode mode, Func? error = null) case Mode.Hang: await Task.Delay(Timeout.Infinite, cancellationToken); break; + case Mode.Gated when Gate is { } g: + await g.Task.WaitAsync(cancellationToken); + break; } var usage = mode switch { @@ -76,7 +90,11 @@ public StubChatClient Then(Mode mode, Func? error = null) Mode.ServeHugeUsage => new MEAI.UsageDetails { InputTokenCount = 1_000_000, OutputTokenCount = 1_000_000 }, _ => new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 }, }; - return new MEAI.ChatResponse(new MEAI.ChatMessage(MEAI.ChatRole.Assistant, reply)) { Usage = usage }; + return new MEAI.ChatResponse(new MEAI.ChatMessage(MEAI.ChatRole.Assistant, reply)) + { + Usage = usage, + FinishReason = mode == Mode.ServeLength ? MEAI.ChatFinishReason.Length : MEAI.ChatFinishReason.Stop, + }; } public async IAsyncEnumerable GetStreamingResponseAsync(IEnumerable messages, MEAI.ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) @@ -89,11 +107,25 @@ public StubChatClient Then(Mode mode, Func? error = null) await Task.Yield(); if (mode == Mode.Throw) throw error?.Invoke() ?? new HttpRequestException("stub failure"); if (mode == Mode.Hang) await Task.Delay(Timeout.Infinite, cancellationToken); + if (mode == Mode.StreamEmptyComplete) + { + yield return new MEAI.ChatResponseUpdate + { + Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 0 })], + FinishReason = MEAI.ChatFinishReason.Stop, + }; + yield break; + } yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, "partial "); if (mode == Mode.StreamGated && Gate is { } gate) await gate.Task.WaitAsync(cancellationToken); if (mode == Mode.StreamThenThrow) throw error?.Invoke() ?? new HttpRequestException("connection reset mid-stream", null, HttpStatusCode.ServiceUnavailable); yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply); - yield return new MEAI.ChatResponseUpdate { Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 })] }; + if (mode == Mode.StreamNoFinish) yield break; // EOF with no terminal completion (e.g. a swallowed SSE error) + yield return new MEAI.ChatResponseUpdate + { + Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 10, OutputTokenCount = 5 })], + FinishReason = mode == Mode.ServeLength ? MEAI.ChatFinishReason.Length : MEAI.ChatFinishReason.Stop, + }; } public object? GetService(Type serviceType, object? serviceKey = null) => null; diff --git a/tests/Covenant.Tests/ServedPathTests.cs b/tests/Covenant.Tests/ServedPathTests.cs index 1030270..3b3f980 100644 --- a/tests/Covenant.Tests/ServedPathTests.cs +++ b/tests/Covenant.Tests/ServedPathTests.cs @@ -67,6 +67,7 @@ private sealed class StubChatClient(string reply) : MEAI.IChatClient yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply[..6]); yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, reply[6..]); yield return new MEAI.ChatResponseUpdate { Contents = [new MEAI.UsageContent(new MEAI.UsageDetails { InputTokenCount = 7, OutputTokenCount = 4 })] }; + yield return new MEAI.ChatResponseUpdate { FinishReason = MEAI.ChatFinishReason.Stop }; // terminal completion (real providers send one) } public object? GetService(Type t, object? key = null) => null; diff --git a/tests/Covenant.Tests/WireShapeTests.cs b/tests/Covenant.Tests/WireShapeTests.cs index a4b2015..f5c9fbe 100644 --- a/tests/Covenant.Tests/WireShapeTests.cs +++ b/tests/Covenant.Tests/WireShapeTests.cs @@ -167,7 +167,7 @@ private sealed class CapturingClient : MEAI.IChatClient public Task GetResponseAsync(IEnumerable m, MEAI.ChatOptions? o = null, CancellationToken ct = default) { Seen = o; return Task.FromResult(new MEAI.ChatResponse(new MEAI.ChatMessage(MEAI.ChatRole.Assistant, "ok")) { Usage = new MEAI.UsageDetails { InputTokenCount = 1, OutputTokenCount = 1 } }); } public async IAsyncEnumerable GetStreamingResponseAsync(IEnumerable m, MEAI.ChatOptions? o = null, [EnumeratorCancellation] CancellationToken ct = default) - { Seen = o; await Task.Yield(); yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, "ok"); } + { Seen = o; await Task.Yield(); yield return new MEAI.ChatResponseUpdate(MEAI.ChatRole.Assistant, "ok"); yield return new MEAI.ChatResponseUpdate { FinishReason = MEAI.ChatFinishReason.Stop }; } public object? GetService(Type t, object? k = null) => null; public void Dispose() { } } From 959ce139c7ca1aa55865b5d6b490ff7324bb5b33 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Sat, 17 Oct 2026 10:20:20 -0400 Subject: [PATCH 10/14] fix(ui,tests): UI review round 2 (single contract, live trace via submissions, policy create/split, presentation focus, health, bounds, paging) + test-only name fixes Applies the reviewer's two test compile fixes (Covenant.Host.LedgerReplay qualification; using Covenant.Adapters in ReviewRound2Tests). --- docs/console-v2-progress.md | 28 + src/Covenant.Ui/Components/RunDetails.razor | 12 +- src/Covenant.Ui/Components/TraceBar.razor | 7 +- src/Covenant.Ui/Layout/StatusHeader.razor | 4 +- src/Covenant.Ui/Logic/BudgetView.cs | 63 +- src/Covenant.Ui/Logic/ConnectionDrafts.cs | 5 +- src/Covenant.Ui/Logic/CostText.cs | 10 +- src/Covenant.Ui/Logic/LocalHealth.cs | 57 ++ src/Covenant.Ui/Logic/ModelFacts.cs | 33 +- src/Covenant.Ui/Logic/PolicyEditing.cs | 261 +++++++ src/Covenant.Ui/Logic/PolicyRoutes.cs | 17 +- src/Covenant.Ui/Logic/RecordFacts.cs | 79 +++ src/Covenant.Ui/Logic/RequestPaging.cs | 92 +++ src/Covenant.Ui/Logic/SegmentScope.cs | 37 +- src/Covenant.Ui/Logic/ShellStatus.cs | 37 +- src/Covenant.Ui/Logic/SubmissionPoll.cs | 78 +++ src/Covenant.Ui/Logic/TraceModel.cs | 78 +-- src/Covenant.Ui/Models/ConfigContracts.cs | 96 ++- src/Covenant.Ui/Models/Contracts.cs | 111 ++- src/Covenant.Ui/Pages/Budgets.razor | 9 +- src/Covenant.Ui/Pages/Connections.razor | 4 +- src/Covenant.Ui/Pages/Evidence.razor | 6 +- src/Covenant.Ui/Pages/Overview.razor | 72 +- src/Covenant.Ui/Pages/Playground.razor | 94 ++- src/Covenant.Ui/Pages/Policies.razor | 261 ++++++- src/Covenant.Ui/Pages/Requests.razor | 114 +++- src/Covenant.Ui/Services/AdminApi.cs | 30 +- src/Covenant.Ui/Services/Interop.cs | 7 + src/Covenant.Ui/Services/PlaygroundState.cs | 72 +- src/Covenant.Ui/Services/RequestsViewState.cs | 19 +- src/Covenant.Ui/Services/RouteHealth.cs | 81 +-- src/Covenant.Ui/Services/TraceClient.cs | 5 +- src/Covenant.Ui/wwwroot/css/app.css | 21 +- src/Covenant.Ui/wwwroot/js/interop.js | 23 + tests/Covenant.Tests/ConsoleLogicTests.cs | 538 +++++++++++++-- .../Covenant.Tests/ContractRoundTripTests.cs | 635 +++++++++++++++++- .../CorrelationAndEvidenceTests.cs | 2 +- tests/Covenant.Tests/ReviewRound2Tests.cs | 1 + 38 files changed, 2651 insertions(+), 448 deletions(-) create mode 100644 src/Covenant.Ui/Logic/LocalHealth.cs create mode 100644 src/Covenant.Ui/Logic/PolicyEditing.cs create mode 100644 src/Covenant.Ui/Logic/RecordFacts.cs create mode 100644 src/Covenant.Ui/Logic/RequestPaging.cs create mode 100644 src/Covenant.Ui/Logic/SubmissionPoll.cs diff --git a/docs/console-v2-progress.md b/docs/console-v2-progress.md index afcde3f..a06e32e 100644 --- a/docs/console-v2-progress.md +++ b/docs/console-v2-progress.md @@ -938,3 +938,31 @@ Reviewer reproducers to re-run: `cache-collision-probe.cs.txt` (expect `calls=2` probe source compiles unchanged); `ledger-migration-crash.py.txt` (empty/unmarked ledger ⇒ refuse start); HTTP archive paging (page1 limit 2, insert, follow `next_cursor` ⇒ no duplicate); SDK stream partial-then-EOF against `provider_stub.py` ⇒ SSE `upstream_error`, audit Deny/UpstreamFailure. + +## Review fixes round 2 (UI) — 2026-10-17 + +Source: `docs/verification-2026-10-16/v2/CODEX-REVIEW.txt` (browser findings + `dashboard-1280-dark.png`), backend contract +as of `1ad07c4` (`docs/ui-api-contract.md`). Not compiled here (no SDK in this environment); every touched file was re-read, +every `[JsonSerializable(typeof(X))]` in `src/Covenant.Ui` names a declared type, every `AdminApi` method the pages call +exists. New pure logic: `Logic/{SubmissionPoll,RequestPaging,PolicyEditing,LocalHealth,RecordFacts}.cs`. + +| # | Defect | Fix | Test(s) | Browser verification step | +|---|---|---|---|---| +| U1 | UI DTOs/services carried "alternative shape" fallbacks (lenient budget-requests parser, JSON-element trace summary reading objects OR strings, enum-name mode spellings, `canceled`, `warnonly`, `success/ok` attempt outcomes, segment "current" inferred from id/first row, catalog `ConnectionId ?? Adapter`, header matching an adapter literally named `local`) | One shape per endpoint matching the Host DTOs exactly: `BudgetRequestsDto`/`BudgetContributionDto`, `AuditTraceStepView`, `AuditSegmentDto.current` (bool, required), `SegmentInfo.is_current`, `RequestExportDto`/`ExportIntegrityDto`, `PlaygroundSubmissionDto`, `ConnectionHealthDto`, `SavingsSummaryDto`, `LocalRouteInfo.connection_id/health`, audit v3 `RequestedMaxOutputTokens/EffectiveMaxOutputTokens/PartialOutputChars/ServedConnectionId`, attempts `EffectiveMaxOutputTokens/Truncated`, trace events `requested/effective_max_output_tokens`, snapshot `truncated`, finops `unknown/estimated_cost_requests`, recent `cost_basis`, evidence `events`. Fallback parsers deleted; contract spellings only (`ShellStatus.Mode`, `PolicyRoutes.IsLocalOnly/IsLegacy/IsLengthHeuristic`, `TraceModel.ParseState`, `BudgetText.Enforcement`, `AttemptFacts.IsSuccess`). `ApiException.ErrorCode` carries the Host `error` code. | `ContractRoundTripTests`: Host→UI field-by-field for config (existing), validate, versions, rollback + config errors + version snapshot, applications, simulate, catalog incl. `local.connection_id/health`, status incl. `connection_health`/savings/recent, budgets + budget requests, requests page incl. segment descriptor + `next_cursor` + `is_current` always present, by-id record (all v3 round-2 fields), segments, export, trace snapshot + event, playground submission, probe, evidence, kill switch, reset, error body; UI→Host playground body (client_request_id accepted by `PlaygroundApi.Validate`). `ConsoleLogicTests` updated for strict spellings. | — (contract) | +| U2 | Live trace stayed Pending / "No trace yet" while the provider waited | `PlaygroundState.RunAsync` starts the POST and concurrently polls `GET /admin/playground/submissions/{client_request_id}` every 250 ms (`SubmissionPoll`: 404 → again, 200 → subscribe once, 401/bound → stop; response id is only a backstop), then follows `/admin/requests/{id}/trace/stream`. New `TraceFeedState.Locating` ("Submitted — locating the request id…"); provider attempt popover shows requested vs enforced bound. No client timings. | `SubmissionPollTests.*`, `LiveTraceStartTests.*`, `ContractRoundTripTests.Trace_snapshot_event_and_playground_submission_reach_the_console` | Playground → run against a slow local model: within ~0.5 s the trace shows Auth…Budget passed and Provider **Running** before any text; network tab shows submissions 404→200 then the trace stream. | +| U3 | Escape after Run in presentation mode did nothing (focus fell to ``) | Document-level `keydown` listener via `Interop.WatchEscapeAsync` (DotNetObjectReference → `[JSInvokable] OnEscapePressed`) while presentation mode is active, removed on exit/dispose; ignores Escape inside `[role=dialog]`/`.popover`. Run → focus moves to Cancel (`#pg-present-cancel`); when the run finishes → result region (`#pg-present-result`, tabindex −1). Exit still restores focus to `#pg-present-toggle`. | — (interop; logic unchanged) | 1280×720 presentation: Tab to Run, Enter, press Escape while running and after completion → presentation closes, focus on "Presentation mode" toggle. | +| U4 | Policies could not be created/removed, applicability not editable, all-classes imported policy could not be split | `Policies.razor` + `PolicyEditing`: Create policy (id, name, classifications, optional profiles, ordered targets, strategy; PII/PHI never offered cloud), Remove policy… (impact lines first: classes no other policy covers → REFUSED), per-policy classification/profile checkboxes (refuses adding PII/PHI while a cloud target is listed), "Split this policy…" (Public → policy's cloud targets else first priced cloud model, + local fallback; Internal/PII/PHI → local only; Local-only mode keeps Public local). Every action edits the draft then runs the Host impact preview; Save & apply via ConfigEditor. | `PolicyEditingTests.*` | Policies → Edit → on an imported all-classes policy choose "Split this policy…" → preview shows `x-public` (cloud → local) and `x-restricted` (local only) → Save & apply → simulator: Public → cloud, PII → local; create a PII policy: cloud models disabled in the target list. | +| U5 | Setup checks wrapped mid-word at 1280 ("Registere/d") | Short status values (`Not yet observed`, `warn · 92%`), long text moved to `title`, ids (connection/model, budget scope) on their own line — the only part with `overflow-wrap:anywhere`; `.check-name/.check-status/.check-action` nowrap; grid columns re-balanced; panel sub-text shortened. | — (CSS/markup) | Overview at 1280×720 dark: no value breaks inside a word; compare with `dashboard-1280-dark.png`. | +| U6 | New connection TimeoutSeconds blank → first Preview failed 1–600 validation | `ConnectionForm.DefaultTimeoutSeconds = 120` for `NewOllama` and `NewCloud` (every kind). | `RoundTwoCostAndFactsTests.New_connections_start_with_a_120_second_timeout` (4 kinds) | Models & connections → Add Ollama → timeout shows 120 → Preview impact succeeds. | +| U7 | Header "local not yet observed" after a successful governed local call | `LocalHealth.Derive`: the catalog's `local.connection_id`/`model_id` with the freshest health — `status.connection_health[key]` (stream, 2 s), else `catalog.local.health`, `local.endpoint_health` only when both unknown; never an adapter named `local`. Header, Overview and SideNav share it; catalog refreshed after each Playground run and Connections test. | `HeaderLocalHealthTests.*`; contract tests for catalog + status | Run a governed local request → header shows "Chain verified · local ready" on every page within one status tick. | +| U8 | Drawer showed requested max 256 while 64 was enforced | `RecordFacts`: "Requested max output tokens" vs "Effective (enforced) max output tokens" ("Not recorded" for older records, "None requested — the application/model bound applies"), Truncated (alert when the served attempt ended with `length`), `incomplete_stream` alert with partial characters, "Served connection" (`ServedConnectionId`, cache-hit provenance); per-attempt bound/truncation in the attempt list. Requests drawer and Playground details. | `RoundTwoCostAndFactsTests.*` | Playground with max tokens 256 on an app bound to 64 → Details: Requested 256 · Effective 64; Requests drawer identical. | +| U9 | Paging/scope | `RequestPaging`: "Load older" follows `next_cursor` only; the scope label and archived/current heading come from the page's `segment` descriptor (`is_current`, `label`, `id`), never the first row; a page for another segment is refused; 410 `cursor_expired` → banner "The audit segment changed (archived) — reload the list" + Reload, Load older disabled; the next page is requested with the cursor alone. Export shows a one-line integrity summary parsed with `RequestExportDto` (download stays byte-for-byte). | `RequestPagingTests.*`, `ContractRoundTripTests.Audit_segments_and_cursor_pages_reach_the_console` | Requests → load 2 pages; archive the segment (Settings/reset) → Load older → banner + Reload; archived segment selector labels from the descriptor. | +| U10 | ConsoleLogicTests vs current Logic | Verified every Logic/Models type and static member referenced exists (script over the test file); updated tests for removed APIs (lenient budget parser, JSON-element trace summary, inferred current segment, enum-name mode spellings). `CostText` handles `mixed` ("≈ $x · Mixed (includes estimates)", short "≈ $x mixed", basis description). | `RoundTwoCostAndFactsTests.Mixed_cost_basis_is_labelled_as_including_estimates`, updated `ShellStatusTests`, `SegmentScopeTests`, `TraceModelTests` | — | + +### Verifier commands (not executed here) + +``` +dotnet build Covenant.sln -c Release --disable-build-servers +dotnet test tests/Covenant.Tests -c Release --disable-build-servers --filter "FullyQualifiedName~ContractRoundTripTests|FullyQualifiedName~SubmissionPollTests|FullyQualifiedName~LiveTraceStartTests|FullyQualifiedName~PolicyEditingTests|FullyQualifiedName~RoundTwoCostAndFactsTests|FullyQualifiedName~RequestPagingTests|FullyQualifiedName~HeaderLocalHealthTests|FullyQualifiedName~SegmentScopeTests|FullyQualifiedName~ShellStatusTests|FullyQualifiedName~TraceModelTests" +dotnet test tests/Covenant.Tests -c Release --disable-build-servers +``` diff --git a/src/Covenant.Ui/Components/RunDetails.razor b/src/Covenant.Ui/Components/RunDetails.razor index 4b17e0c..c5efdda 100644 --- a/src/Covenant.Ui/Components/RunDetails.razor +++ b/src/Covenant.Ui/Components/RunDetails.razor @@ -32,7 +32,9 @@
    Run as
    @(Run.Snapshot.ApplicationId ?? "Not set")
    Workload profile
    @(Run.Snapshot.ProfileId is { } pid ? ComposerRules.ProfileLabel(Ws.Profiles, pid) : "Application default (server-side)")
    Model
    @(Run.Snapshot.RoutingLabel + (Run.Snapshot.Mode == RouteMode.Explicit ? " (test input)" : ""))
    -
    Mode
    @(Run.Snapshot.Streaming ? "Streamed" : "Buffered") · max output @(Run.Snapshot.MaxTokens?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "application bound")
    +
    Mode
    @(Run.Snapshot.Streaming ? "Streamed" : "Buffered")
    +
    Requested max output tokens
    @(Run.Evidence.Record is { } rr ? RecordFacts.RequestedMaxOutputTokens(rr) : Run.Snapshot.MaxTokens?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "None requested — the application/model bound applies")
    +
    Effective (enforced) max output tokens
    @(Run.Evidence.Record is { } er2 ? RecordFacts.EffectiveMaxOutputTokens(er2) : "Known once the audit record is found")
    Labels
    @(Run.Snapshot.Workflow ?? "—") · @(Run.Snapshot.UseCase ?? "—")
    Submitted
    @Fmt.Utc(Run.Snapshot.SubmittedUtc)
    Client request id
    @Run.Snapshot.ClientRequestId
    @@ -58,8 +60,14 @@
    Actual destination
    @dest.Text @if (!rec.CacheHit && dest.Text != ModelFacts.NoProviderCall) { }
    Served
    @ModelFacts.Served(rec)
    +
    Served connection
    @RecordFacts.ServedConnection(rec)
    +
    Truncated
    @RecordFacts.TruncatedText(rec)
    Config version
    @(rec.ConfigVersion?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? ModelFacts.NotRecorded)
    + @if (RecordFacts.IncompleteStreamText(rec) is { } incomplete) + { +
    Stream incomplete — not served@incomplete
    + } @{ var lines = AttemptFacts.Lines(rec, Ws.Connections); } @if (lines.Count > 0) { @@ -71,7 +79,7 @@ @a.Target @(a.Outcome + (a.ErrorClass is { } ec ? " · " + ec : "")) - @a.Duration · @a.Cost + @AttemptFacts.Detail(a) } diff --git a/src/Covenant.Ui/Components/TraceBar.razor b/src/Covenant.Ui/Components/TraceBar.razor index b5a006d..722dad1 100644 --- a/src/Covenant.Ui/Components/TraceBar.razor +++ b/src/Covenant.Ui/Components/TraceBar.razor @@ -48,6 +48,10 @@ @(a.Target ?? "target not reported") @TraceModel.StateText(a.State) @(a.DurationMs is { } ad ? Fmt.Ms(ad) : "duration not reported") + @if (a.EffectiveMaxOutputTokens is { } eff) + { + output bound: requested @(a.RequestedMaxOutputTokens?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "none") · enforced @eff.ToString(System.Globalization.CultureInfo.InvariantCulture) + } @if (a.ReasonCode is { Length: > 0 } rc) { @rc @@ -117,7 +121,8 @@ if (Trace.Source == "audit summary") return "From the audit record (live trace no longer retained)" + version; return FeedState switch { - TraceFeedState.Connecting => "Connecting to the trace…", + TraceFeedState.Locating => "Submitted — locating the request id to follow its live trace…", + TraceFeedState.Connecting => "Connecting to the live trace…", TraceFeedState.Live => (Trace.Complete ? "Trace complete" : "Live trace") + version, TraceFeedState.Reconnecting => "Trace connection dropped — reconnecting (resumes after the last event)" + version, TraceFeedState.Snapshot => "Trace snapshot (stream unavailable)" + version, diff --git a/src/Covenant.Ui/Layout/StatusHeader.razor b/src/Covenant.Ui/Layout/StatusHeader.razor index 7150e05..5b4e1c7 100644 --- a/src/Covenant.Ui/Layout/StatusHeader.razor +++ b/src/Covenant.Ui/Layout/StatusHeader.razor @@ -104,7 +104,9 @@ var s = State.LastStatus; if (s is not null && !s.ChainValid) return new("Audit chain failed", "bad", "evidence", "The current audit segment's hash chain does not verify"); - var local = RouteHealth.LocalRoute(State.Catalog, DateTimeOffset.UtcNow); + // Review round 2 (B11): the CURRENT runtime connection's health (catalog.local.connection_id + status + // connection_health, pushed every 2 s) — never an adapter that merely happens to be named "local". + var local = RouteHealth.LocalRoute(State.Catalog, s, DateTimeOffset.UtcNow); var title = local.Text + (local.LastError is { Length: > 0 } e ? " · last error: " + e : ""); return local.State switch { diff --git a/src/Covenant.Ui/Logic/BudgetView.cs b/src/Covenant.Ui/Logic/BudgetView.cs index 9f39ca6..c778dd7 100644 --- a/src/Covenant.Ui/Logic/BudgetView.cs +++ b/src/Covenant.Ui/Logic/BudgetView.cs @@ -1,5 +1,4 @@ using System.Globalization; -using System.Text.Json; using Covenant.Ui.Models; namespace Covenant.Ui.Logic; @@ -45,7 +44,7 @@ public static string Scope(string? scope) public static string Enforcement(string? enforcement) => (enforcement ?? "").Trim().ToLowerInvariant() switch { "hard" => "Hard — refuses paid work that would exceed the cap (estimated bound)", - "warn-only" or "warnonly" => "Warn only — never blocks", + "warn-only" => "Warn only — never blocks", "" => "Enforcement not reported", _ => enforcement!.Trim(), }; @@ -88,63 +87,3 @@ public static bool NoSpendAnywhere(IReadOnlyList? budgets) public static string FormatThresholds(IReadOnlyList? warnAt) => warnAt is null ? "" : string.Join(", ", warnAt.Select(w => (w * 100m).ToString("0.##", CultureInfo.InvariantCulture))); } - -/// Lenient reader for GET /admin/budgets/{id}/requests ("contributing settled request ids and amounts"): -/// accepts a bare array or {"items":[…]} and the obvious alternative field names, so a small backend naming -/// difference degrades to "Not reported" values instead of a broken page. Unknown shapes return null. -public static class BudgetRequests -{ - public static List? Parse(string? json) - { - if (string.IsNullOrWhiteSpace(json)) return null; - try - { - using var doc = JsonDocument.Parse(json); - var root = doc.RootElement; - JsonElement array; - if (root.ValueKind == JsonValueKind.Array) array = root; - else if (root.ValueKind == JsonValueKind.Object && TryGet(root, out array, "items", "requests") && array.ValueKind == JsonValueKind.Array) { } - else return null; - - var list = new List(); - foreach (var e in array.EnumerateArray()) - { - if (e.ValueKind != JsonValueKind.Object) continue; - var id = Str(e, "request_id", "id", "requestId"); - if (string.IsNullOrWhiteSpace(id)) continue; - list.Add(new BudgetRequestDto - { - RequestId = id, - AttemptId = Str(e, "attempt_id", "attemptId"), - AmountUsd = Dec(e, "amount_usd", "settled_usd", "cost_usd", "amount"), - TimestampUtc = Time(e, "ts_utc", "settled_utc", "timestamp_utc", "utc"), - Scope = Str(e, "scope"), - Kind = Str(e, "kind", "op"), - Overrun = TryGet(e, out var ov, "overrun") && ov.ValueKind == JsonValueKind.True, - }); - } - return list; - } - catch (JsonException) - { - return null; - } - } - - private static bool TryGet(JsonElement o, out JsonElement value, params string[] names) - { - foreach (var n in names) - if (o.TryGetProperty(n, out value)) return true; - value = default; - return false; - } - - private static string? Str(JsonElement o, params string[] names) - => TryGet(o, out var v, names) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; - - private static decimal? Dec(JsonElement o, params string[] names) - => TryGet(o, out var v, names) && v.ValueKind == JsonValueKind.Number && v.TryGetDecimal(out var d) ? d : null; - - private static DateTimeOffset? Time(JsonElement o, params string[] names) - => TryGet(o, out var v, names) && v.ValueKind == JsonValueKind.String && v.TryGetDateTimeOffset(out var t) ? t : null; -} diff --git a/src/Covenant.Ui/Logic/ConnectionDrafts.cs b/src/Covenant.Ui/Logic/ConnectionDrafts.cs index 6b0ba1b..d000ee5 100644 --- a/src/Covenant.Ui/Logic/ConnectionDrafts.cs +++ b/src/Covenant.Ui/Logic/ConnectionDrafts.cs @@ -30,6 +30,8 @@ public sealed class ConnectionForm public const string BasisLocal = "zero-marginal-local"; public const string BasisList = "provider-list"; public const string BasisContract = "contract"; + /// Provider call timeout a NEW connection starts with, for every kind (the Host's own default; 1–600). + public const int DefaultTimeoutSeconds = 120; public bool IsNew { get; init; } /// Id of the saved connection being edited (immutable on edit: policies reference it). @@ -56,11 +58,12 @@ public sealed class ConnectionForm Boundary = "Local", DisplayName = "Ollama (in perimeter)", Id = ConnectionRules.UniqueId("ollama", existingIds), + TimeoutSeconds = DefaultTimeoutSeconds, }; public static ConnectionForm NewCloud(string kind, IEnumerable existingIds) { - var f = new ConnectionForm { IsNew = true }; + var f = new ConnectionForm { IsNew = true, TimeoutSeconds = DefaultTimeoutSeconds }; f.SetKind(kind); f.DisplayName = ConnectionRules.KindLabel(kind); f.Id = ConnectionRules.UniqueId(kind.ToLowerInvariant(), existingIds); diff --git a/src/Covenant.Ui/Logic/CostText.cs b/src/Covenant.Ui/Logic/CostText.cs index b25eadf..e3647b5 100644 --- a/src/Covenant.Ui/Logic/CostText.cs +++ b/src/Covenant.Ui/Logic/CostText.cs @@ -4,7 +4,9 @@ namespace Covenant.Ui.Logic; /// Cost and token wording driven by the recorded CostBasis (ADR-0009). Unknown is never rendered as -/// "$0": only no_call and zero_priced may show a zero, and both say why. +/// "$0": only no_call and zero_priced may show a zero, and both say why. "mixed" (review round 2, B2) = the +/// request total combines charges of different bases (e.g. a failed attempt's estimate plus a reported fallback): +/// labelled "Mixed (includes estimates)", never as a plain reported figure. public static class CostText { public const string NotReported = "Not reported"; @@ -14,9 +16,12 @@ public static class CostText /// Significant-digit USD (Logic/Money): a non-zero charge is never shown as $0.00. public static string Usd(decimal value) => Money.Usd(value); + public const string MixedLabel = "Mixed (includes estimates)"; + public static string Cost(AuditEntryView r) => r.CostBasis switch { "reported" => Usd(r.Usage.CostUsd) + " (estimated provider charge)", + "mixed" => "≈ " + Usd(r.Usage.CostUsd) + " · " + MixedLabel, "zero_priced" => "$0.00 configured provider charge · infrastructure excluded", "estimated_from_text" or "estimated_failed_call" => "≈ " + Usd(r.Usage.CostUsd) + " estimated from text length", "unknown_failed_call" or "unpriced" => NotReported, @@ -31,6 +36,7 @@ public static class CostText "reported" => Usd(cost) + " reported usage", "zero_priced" => "$0.00 configured", "estimated_from_text" or "estimated_failed_call" => "≈ " + Usd(cost) + " estimated", + "mixed" => "≈ " + Usd(cost) + " " + MixedLabel, "no_call" => "$0.00 — no provider call", _ => NotReported, }; @@ -39,6 +45,7 @@ public static class CostText public static string CostShort(AuditEntryView r) => r.CostBasis switch { "reported" => Usd(r.Usage.CostUsd), + "mixed" => "≈ " + Usd(r.Usage.CostUsd) + " mixed", "zero_priced" => "$0.00 configured", "estimated_from_text" or "estimated_failed_call" => "≈ " + Usd(r.Usage.CostUsd), "unknown_failed_call" or "unpriced" => NotReported, @@ -71,6 +78,7 @@ private static string Counts(UsageView u) "estimated_failed_call" => "A provider call started but failed: estimated from text length and charged to the budget", "unknown_failed_call" => "A provider call started but its cost could not be estimated", "unpriced" => "Model has no configured price — cost unknown, not zero", + "mixed" => "Total of attempts with different cost bases (e.g. a failed attempt's estimate plus a reported fallback) — includes estimates, so it is not a reported figure", "no_call" => "No provider call was made", null => "Not recorded (legacy record)", _ => "Unrecognised basis: " + basis, diff --git a/src/Covenant.Ui/Logic/LocalHealth.cs b/src/Covenant.Ui/Logic/LocalHealth.cs new file mode 100644 index 0000000..f873d45 --- /dev/null +++ b/src/Covenant.Ui/Logic/LocalHealth.cs @@ -0,0 +1,57 @@ +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +public enum LocalRouteState { Unknown, NotConfigured, NotRegistered, NotObserved, Ready, Degraded } + +/// The header/Overview answer to "is the local route usable?" (review round 2, B11). is +/// the health actually used, says where it came from. +public sealed record LocalHealthView( + LocalRouteState State, + string? ConnectionId, + string? ModelId, + ModelHealth? Health, + string Source); + +/// Derives local-route health from the server only (docs/ui-api-contract.md "Header local health"): the +/// connection the catalog's local view names (local.connection_id + local.model_id — the one the +/// Host observed or routes, never a connection merely named "local"), with its CURRENT runtime health. The freshest +/// source wins: /admin/status.connection_health for exactly that key (pushed every 2 s), else +/// catalog.local.health; local.endpoint_health only when both say "unknown". A failure newer than the +/// last success is Degraded even if an older success exists. Pure. +public static class LocalHealth +{ + public static LocalHealthView Derive(CatalogResponse? catalog, IReadOnlyList? statusHealth) + { + if (catalog is null) return new(LocalRouteState.Unknown, null, null, null, "catalog not loaded"); + var local = catalog.Local; + if (local is null || !local.Configured) return new(LocalRouteState.NotConfigured, local?.ConnectionId, local?.ModelId, null, "catalog"); + if (!local.Registered) return new(LocalRouteState.NotRegistered, local.ConnectionId, local.ModelId, null, "catalog"); + + ModelHealth? health = null; + string source = "none"; + if (local.ConnectionId is { Length: > 0 } cid && local.ModelId is { Length: > 0 } mid && statusHealth is not null) + { + var key = cid + ":" + mid; + var row = statusHealth.FirstOrDefault(h => string.Equals(h.Key, key, StringComparison.Ordinal)); + if (row is not null && Known(row.Health)) { health = row.Health; source = "status connection_health"; } + } + if (health is null && Known(local.Health)) { health = local.Health; source = "catalog local.health"; } + if (health is null && Known(local.EndpointHealth)) { health = local.EndpointHealth; source = "catalog local.endpoint_health"; } + + return new(Classify(health), local.ConnectionId, local.ModelId, health, source); + } + + /// ok/failed (or any recorded time) is an observation; "unknown" with no times is not. + public static bool Known(ModelHealth? h) + => h is not null && (h.State is "ok" or "failed" || h.LastSuccessUtc is not null || h.LastFailureUtc is not null); + + public static LocalRouteState Classify(ModelHealth? h) + { + if (h is null || !Known(h)) return LocalRouteState.NotObserved; + var success = h.LastSuccessUtc; + var failure = h.LastFailureUtc; + if (h.State == "failed" || (failure is not null && (success is null || failure > success))) return LocalRouteState.Degraded; + return LocalRouteState.Ready; + } +} diff --git a/src/Covenant.Ui/Logic/ModelFacts.cs b/src/Covenant.Ui/Logic/ModelFacts.cs index 793b810..00efaaf 100644 --- a/src/Covenant.Ui/Logic/ModelFacts.cs +++ b/src/Covenant.Ui/Logic/ModelFacts.cs @@ -113,17 +113,20 @@ public static string SelectedToServed(AuditEntryView r) /// "Local", "Cloud" or null when the connection's boundary is not known (shown as text, never guessed). public sealed record DestinationView(string Text, string? Boundary, bool Served); -/// One recorded provider attempt, ready to display. -public sealed record AttemptLine(int Number, string Target, string Outcome, string? ErrorClass, string Duration, string Cost, string? Boundary); +/// One recorded provider attempt, ready to display. = the output bound +/// sent for this attempt; = it finished with "length" (review round 2). +public sealed record AttemptLine(int Number, string Target, string Outcome, string? ErrorClass, string Duration, string Cost, string? Boundary) +{ + public int? EffectiveMaxOutputTokens { get; init; } + public bool Truncated { get; init; } +} /// Attempt-level evidence (audit v3 Attempts[], ADR-0013): fallback is shown as what it was — /// a second, approved attempt after a transient failure — never as a silent retry. public static class AttemptFacts { - private static readonly string[] SuccessWords = ["served", "success", "succeeded", "ok", "passed", "completed"]; - - public static bool IsSuccess(AuditAttemptView a) - => a.Outcome is { } o && SuccessWords.Contains(o.Trim().ToLowerInvariant()); + /// Contract vocabulary: Outcome ∈ served | failed | cancelled. + public static bool IsSuccess(AuditAttemptView a) => string.Equals(a.Outcome, "served", StringComparison.Ordinal); public static IReadOnlyList Lines(AuditEntryView r, IReadOnlyList? connections = null) { @@ -136,15 +139,25 @@ public static IReadOnlyList Lines(AuditEntryView r, IReadOnlyList"1.20 s · ≈ $0.0004 estimated · bound 64 · truncated (length)". + public static string Detail(AttemptLine a) + => a.Duration + " · " + a.Cost + + (a.EffectiveMaxOutputTokens is { } b ? " · bound " + b.ToString(System.Globalization.CultureInfo.InvariantCulture) : "") + + (a.Truncated ? " · truncated (length)" : ""); + /// "Attempt 1 (openai/gpt-x) failed: timeout; attempt 2 served." — only when more than one attempt /// was recorded and the last one served. Null otherwise. public static string? FallbackSentence(AuditEntryView r) @@ -154,7 +167,7 @@ public static IReadOnlyList Lines(AuditEntryView r, IReadOnlyListThe "Create policy" form (spec §5 Policies). Nothing here is applied: puts the +/// built policy into the configuration DRAFT; the Host validates it on Preview impact and activates it on Save & apply. +public sealed class NewPolicyForm +{ + public string Id { get; set; } = ""; + public string Name { get; set; } = ""; + /// Wire spellings: Public | Internal | Pii | Phi. + public List Classifications { get; set; } = []; + /// Optional workload-profile applicability (empty = every profile). + public List Profiles { get; set; } = []; + /// Ordered "connection/model" keys: primary first, then approved fallbacks. + public List Targets { get; set; } = []; + /// fixed | length-heuristic + public string Strategy { get; set; } = "fixed"; +} + +/// Result of planning a split: the two draft policies, or why it cannot be done. +public sealed record PolicySplitPlan(string? Problem, PolicyDto? PublicPolicy, PolicyDto? RestrictedPolicy, IReadOnlyList Notes); + +/// Draft-only policy edits (create, remove with impact, applicability, split). PII/PHI never get a cloud target: +/// every helper refuses to produce one, and the Host rejects one anyway (sensitive_cloud_target). Pure. +public static class PolicyEditing +{ + /// Contract spellings of DataClassification, in display order. + public static readonly IReadOnlyList AllClassifications = ["Public", "Internal", "Pii", "Phi"]; + + public static bool IsValidId(string? id) => ConnectionRules.IsValidId(id); + + /// A free policy id derived from . + public static string UniqueId(string seed, CovenantConfigDto cfg) + => ConnectionRules.UniqueId(seed, cfg.Policies.Select(p => p.Id)); + + /// Targets that may be chosen for a policy covering : enabled connections' + /// permitted models; cloud models carry a disabled reason for PII/PHI or in Local-only mode. + public static IReadOnlyList TargetOptions(IEnumerable classifications, CovenantConfigDto cfg) + => PolicyRoutes.Options(new PolicyDto { Classifications = classifications.ToList() }, cfg); + + /// Every reason the form cannot be added to the draft (empty = ready). + public static IReadOnlyList Problems(NewPolicyForm f, CovenantConfigDto cfg) + { + var p = new List(); + if (!IsValidId(f.Id)) p.Add("Policy id must be 1–64 characters of letters, digits, '.', '_' or '-'."); + else if (cfg.Policies.Any(x => string.Equals(x.Id, f.Id, StringComparison.Ordinal))) p.Add("A policy with id '" + f.Id + "' already exists."); + if (string.IsNullOrWhiteSpace(f.Name)) p.Add("Enter a policy name."); + if (f.Classifications.Count == 0) p.Add("Choose at least one classification."); + foreach (var unknown in f.Classifications.Where(c => !AllClassifications.Contains(c))) + p.Add("Unknown classification '" + unknown + "'."); + foreach (var missing in f.Profiles.Where(id => !cfg.Profiles.Any(x => string.Equals(x.Id, id, StringComparison.Ordinal)))) + p.Add("Workload profile '" + missing + "' does not exist."); + if (f.Strategy is not ("fixed" or "length-heuristic")) p.Add("Choose a routing strategy."); + if (f.Targets.Count == 0) p.Add("Choose at least one approved target (the primary)."); + var options = TargetOptions(f.Classifications, cfg); + foreach (var t in f.Targets) + { + var o = options.FirstOrDefault(x => x.Value == t); + if (o is null) p.Add(t + " is not an enabled, permitted model."); + else if (o.DisabledReason is { } why) p.Add(t + ": " + why); + } + if (f.Targets.Distinct(StringComparer.Ordinal).Count() != f.Targets.Count) p.Add("A target is listed twice."); + return p; + } + + public static PolicyDto Build(NewPolicyForm f) => new() + { + Id = f.Id.Trim(), + Name = f.Name.Trim(), + Enabled = true, + Classifications = AllClassifications.Where(c => f.Classifications.Contains(c)).ToList(), + Profiles = f.Profiles.ToList(), + Targets = f.Targets.Select(ToTarget).ToList(), + Strategy = f.Strategy, + ThresholdTokens = f.Strategy == "length-heuristic" ? 400 : null, + }; + + /// Adds the form's policy to . Returns the problems (draft untouched) or an empty list. + public static IReadOnlyList Add(CovenantConfigDto draft, NewPolicyForm f) + { + var problems = Problems(f, draft); + if (problems.Count == 0) draft.Policies.Add(Build(f)); + return problems; + } + + /// What removing changes, judged from the configuration: which classification × + /// profile combinations it serves that no other enabled policy covers (those become refused — fail-closed). The + /// Host's impact preview (Preview impact) is the authority; this is the immediate warning. + public static IReadOnlyList RemovalImpact(PolicyDto policy, CovenantConfigDto cfg) + { + var lines = new List(); + if (!policy.Enabled) + { + lines.Add("The policy is disabled: removing it changes no route."); + return lines; + } + var others = cfg.Policies.Where(p => !ReferenceEquals(p, policy) && p.Enabled).ToList(); + foreach (var c in AllClassifications.Where(c => policy.Classifications.Contains(c))) + { + bool covered = others.Any(o => o.Classifications.Contains(c) + && (o.Profiles.Count == 0 || (policy.Profiles.Count > 0 && policy.Profiles.All(o.Profiles.Contains)))); + var scope = PolicyText.ClassificationLabel(c) + (policy.Profiles.Count == 0 ? "" : " · profile " + string.Join(", ", policy.Profiles)); + lines.Add(covered + ? scope + ": another enabled policy still matches." + : scope + ": no other policy matches — these requests will be REFUSED (fail-closed)."); + } + return lines; + } + + /// Removes the policy with from the draft. False when not found. + public static bool Remove(CovenantConfigDto draft, string policyId) + { + var p = draft.Policies.FirstOrDefault(x => string.Equals(x.Id, policyId, StringComparison.Ordinal)); + return p is not null && draft.Policies.Remove(p); + } + + /// Changes which classifications a policy covers. Refused (returns why, policy untouched) when the set is empty, + /// unknown, or would put PII/PHI behind a cloud target. + public static string? SetClassifications(PolicyDto policy, IEnumerable classifications, CovenantConfigDto cfg) + { + var wanted = classifications.ToHashSet(StringComparer.Ordinal); + var next = AllClassifications.Where(wanted.Contains).ToList(); + if (next.Count == 0) return "A policy must cover at least one classification."; + if (next.Any(PolicyText.IsSensitive) && CloudTargets(policy, cfg).FirstOrDefault() is { } cloud) + return "Remove the cloud target " + cloud + " first: " + PolicyText.SensitiveNeverCloud; + policy.Classifications = next; + return null; + } + + /// Changes the workload-profile applicability (empty = every profile). Refused for an unknown profile. + public static string? SetProfiles(PolicyDto policy, IEnumerable profiles, CovenantConfigDto cfg) + { + var next = profiles.Distinct(StringComparer.Ordinal).ToList(); + if (next.FirstOrDefault(pr => !cfg.Profiles.Any(x => string.Equals(x.Id, pr, StringComparison.Ordinal))) is { } missing) + return "Workload profile '" + missing + "' does not exist."; + policy.Profiles = next; + return null; + } + + /// Split is offered for a policy that covers Public AND at least one of Internal/PII/PHI. + public static bool CanSplit(PolicyDto p) + => p.Classifications.Contains("Public") && p.Classifications.Any(c => c is "Internal" or "Pii" or "Phi"); + + /// Plans "Split this policy": Public → an approved cloud model with the local model as fallback; + /// Internal/PII/PHI → local only. Cloud targets come from the policy itself, else the first enabled, priced cloud + /// model; local targets from the policy, else the first enabled local model. The restricted policy NEVER receives a + /// cloud target. In Local-only mode Public stays local (cloud cannot execute there). + public static PolicySplitPlan PlanSplit(PolicyDto p, CovenantConfigDto cfg) + { + var notes = new List(); + if (!CanSplit(p)) + return new PolicySplitPlan("Split needs a policy that covers Public and at least one of Internal, PII or PHI.", null, null, notes); + + var local = LocalTargets(p, cfg).ToList(); + if (local.Count == 0 && FirstModel(cfg, "Local", requirePrice: false) is { } anyLocal) + { + local.Add(anyLocal); + notes.Add("The policy had no local target; " + anyLocal + " (first enabled local model) serves Internal/PII/PHI."); + } + if (local.Count == 0) + return new PolicySplitPlan("Split needs an enabled Local connection with a permitted model (add one under Models & connections).", null, null, notes); + + var cloud = new List(); + if (PolicyRoutes.IsLocalOnly(cfg.Mode)) + notes.Add("Local-only mode: cloud destinations cannot execute, so Public stays on the local model."); + else + { + cloud.AddRange(CloudTargets(p, cfg)); + if (cloud.Count == 0 && FirstModel(cfg, "Cloud", requirePrice: true) is { } anyCloud) + { + cloud.Add(anyCloud); + notes.Add("The policy had no cloud target; " + anyCloud + " (first enabled, priced cloud model) is proposed for Public."); + } + if (cloud.Count == 0) notes.Add("No enabled, priced cloud model is configured: Public stays on the local model."); + } + + var restrictedClasses = AllClassifications.Where(c => c != "Public" && p.Classifications.Contains(c)).ToList(); + var publicPolicy = new PolicyDto + { + Id = UniqueIdExcluding(p.Id + "-public", cfg, p.Id), + Name = "Public: " + (cloud.Count > 0 ? "approved cloud model, local fallback" : "local model"), + Enabled = p.Enabled, + Paused = p.Paused, + Classifications = ["Public"], + Profiles = p.Profiles.ToList(), + Targets = cloud.Concat(local).Select(ToTarget).ToList(), + Strategy = "fixed", + Retry = CopyRetry(p.Retry), + Explanation = "Split from policy '" + p.Id + "': Public content may use the approved cloud model; the local model is the approved fallback.", + }; + var restricted = new PolicyDto + { + Id = UniqueIdExcluding(p.Id + "-restricted", cfg, p.Id, publicPolicy.Id), + Name = string.Join("/", restrictedClasses.Select(PolicyText.ClassificationLabel)) + ": local only", + Enabled = p.Enabled, + Paused = p.Paused, + Classifications = restrictedClasses, + Profiles = p.Profiles.ToList(), + Targets = local.Select(ToTarget).ToList(), // never a cloud target + Strategy = "fixed", + Retry = CopyRetry(p.Retry), + Explanation = "Split from policy '" + p.Id + "'. " + PolicyText.SensitiveNeverCloud, + }; + return new PolicySplitPlan(null, publicPolicy, restricted, notes); + } + + /// Replaces the policy with the two planned drafts (same position). Returns the problem (draft untouched) or null. + public static string? ApplySplit(CovenantConfigDto draft, string policyId) + { + var p = draft.Policies.FirstOrDefault(x => string.Equals(x.Id, policyId, StringComparison.Ordinal)); + if (p is null) return "Policy '" + policyId + "' is not in the draft."; + var plan = PlanSplit(p, draft); + if (plan.Problem is not null || plan.PublicPolicy is null || plan.RestrictedPolicy is null) return plan.Problem ?? "Split could not be planned."; + int i = draft.Policies.IndexOf(p); + draft.Policies.RemoveAt(i); + draft.Policies.Insert(i, plan.RestrictedPolicy); + draft.Policies.Insert(i, plan.PublicPolicy); + return null; + } + + private static IEnumerable LocalTargets(PolicyDto p, CovenantConfigDto cfg) + => PolicyRoutes.Targets(p, cfg).Where(t => t.Boundary == "Local" && !t.Target.Paused && t.ExcludedReason is null).Select(t => t.Key); + + /// Enabled, permitted cloud targets of the policy (ignoring the PII/PHI exclusion so a split can move them to Public). + private static IEnumerable CloudTargets(PolicyDto p, CovenantConfigDto cfg) + { + foreach (var t in p.Targets) + { + if (t.Paused) continue; + var conn = cfg.Connections.FirstOrDefault(c => string.Equals(c.Id, t.ConnectionId, StringComparison.Ordinal)); + if (conn is null || !conn.Enabled || ComposerRules.BoundaryLabel(conn.Boundary) != "Cloud") continue; + if (!conn.Models.Any(m => string.Equals(m.ModelId, t.ModelId, StringComparison.Ordinal))) continue; + yield return PolicyRoutes.Key(t); + } + } + + private static string? FirstModel(CovenantConfigDto cfg, string boundary, bool requirePrice) + { + foreach (var c in cfg.Connections) + { + if (!c.Enabled || ComposerRules.BoundaryLabel(c.Boundary) != boundary) continue; + foreach (var m in c.Models) + if (!requirePrice || m.Price is { InputPer1M: not null, OutputPer1M: not null }) + return c.Id + "/" + m.ModelId; + } + return null; + } + + private static string UniqueIdExcluding(string seed, CovenantConfigDto cfg, params string[] alsoTaken) + => ConnectionRules.UniqueId(seed, cfg.Policies.Select(p => p.Id).Concat(alsoTaken)); + + private static RetrySettingsDto? CopyRetry(RetrySettingsDto? r) + => r is null ? null : new RetrySettingsDto { MaxAttempts = r.MaxAttempts, DeadlineMs = r.DeadlineMs, On = r.On?.ToList() }; + + private static PolicyTargetDto ToTarget(string key) + { + int slash = key.IndexOf('/'); + return slash <= 0 ? new PolicyTargetDto { ConnectionId = key } : new PolicyTargetDto { ConnectionId = key[..slash], ModelId = key[(slash + 1)..] }; + } +} diff --git a/src/Covenant.Ui/Logic/PolicyRoutes.cs b/src/Covenant.Ui/Logic/PolicyRoutes.cs index dbeaffb..138e9be 100644 --- a/src/Covenant.Ui/Logic/PolicyRoutes.cs +++ b/src/Covenant.Ui/Logic/PolicyRoutes.cs @@ -48,8 +48,7 @@ public static string StrategyName(PolicyDto p) ? "Length-based heuristic (threshold " + (p.ThresholdTokens ?? 400).ToString("N0", CultureInfo.InvariantCulture) + " tokens)" : "Fixed + fallback"; - public static bool IsLengthHeuristic(PolicyDto p) => string.Equals(p.Strategy, "length-heuristic", StringComparison.OrdinalIgnoreCase) - || string.Equals(p.Strategy, "LengthHeuristic", StringComparison.OrdinalIgnoreCase); + public static bool IsLengthHeuristic(PolicyDto p) => string.Equals(p.Strategy, "length-heuristic", StringComparison.Ordinal); /// "Public", "PII + PHI", "Internal · profile internal-docs". public static string Applicability(PolicyDto p) @@ -79,17 +78,11 @@ public static class PolicyRoutes { public static string Key(PolicyTargetDto t) => t.ConnectionId + "/" + t.ModelId; - public static bool IsLocalOnly(string? mode) - { - var m = (mode ?? "").Trim().ToLowerInvariant().Replace("-", "", StringComparison.Ordinal).Replace("_", "", StringComparison.Ordinal); - return m is "localonly"; - } + /// Contract spelling only ("local-only"). + public static bool IsLocalOnly(string? mode) => string.Equals(mode, ShellStatus.LocalOnly, StringComparison.Ordinal); - public static bool IsLegacy(string? mode) - { - var m = (mode ?? "").Trim().ToLowerInvariant().Replace("-", "", StringComparison.Ordinal).Replace("_", "", StringComparison.Ordinal); - return m is "legacycloud" or "cloud"; - } + /// Contract spelling only ("legacy-cloud"). + public static bool IsLegacy(string? mode) => string.Equals(mode, ShellStatus.LegacyCloud, StringComparison.Ordinal); /// The configured target list with each target's structural eligibility. public static IReadOnlyList Targets(PolicyDto p, CovenantConfigDto cfg) diff --git a/src/Covenant.Ui/Logic/RecordFacts.cs b/src/Covenant.Ui/Logic/RecordFacts.cs new file mode 100644 index 0000000..f2d12f9 --- /dev/null +++ b/src/Covenant.Ui/Logic/RecordFacts.cs @@ -0,0 +1,79 @@ +using System.Globalization; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// Review-round-2 facts of one audit record (docs/ui-api-contract.md "Additive v3 fields"): the requested vs +/// the effective (enforced) output bound, truncation at the bound, a stream that ended without a terminal completion +/// (incomplete_stream) and the connection that actually served. Older records lack these fields → "Not +/// recorded", never a guess. +public static class RecordFacts +{ + public const string NotRecorded = "Not recorded"; + public const string IncompleteStream = "incomplete_stream"; + + /// True when the record carries any review-round-2 field, so an absent requested bound means "none + /// requested" rather than "older record". + public static bool HasBoundFields(AuditEntryView r) + => r.EffectiveMaxOutputTokens is not null || r.RequestedMaxOutputTokens is not null || r.PartialOutputChars is not null + || r.ServedConnectionId is not null || r.Attempts?.Any(a => a.EffectiveMaxOutputTokens is not null || a.Truncated is not null) == true; + + /// "256", "None requested — application/model bound applies", or "Not recorded" (older record). + public static string RequestedMaxOutputTokens(AuditEntryView r) + { + if (r.RequestedMaxOutputTokens is { } n) return Int(n); + return HasBoundFields(r) ? "None requested — the application/model bound applies" : NotRecorded; + } + + /// The bound Covenant sent to the provider for the SERVED attempt; for a request nothing served, the last + /// started attempt's bound (labelled). "Not recorded" for older records or when no attempt started. + public static string EffectiveMaxOutputTokens(AuditEntryView r) + { + if (r.EffectiveMaxOutputTokens is { } n) return Int(n); + if (r.Attempts is { Count: > 0 } attempts && attempts[^1].EffectiveMaxOutputTokens is { } last) + return Int(last) + " (last attempt — not served)"; + return NotRecorded; + } + + /// "Requested 256 · enforced 64" — the compact form for one line. + public static string BoundsLine(AuditEntryView r) + => "Requested " + RequestedMaxOutputTokens(r) + " · enforced " + EffectiveMaxOutputTokens(r); + + /// The attempt that served finished with "length" (output cut at the enforced bound). + public static bool Truncated(AuditEntryView r) + => r.Attempts?.Any(a => a.Truncated == true && AttemptFacts.IsSuccess(a)) == true; + + /// "Yes — …" / "No" / "Not recorded" for the drawer. + public static string TruncatedText(AuditEntryView r) + { + if (Truncated(r)) + return "Yes — the provider stopped at the enforced output bound (finish_reason length); the answer is cut short"; + return r.Attempts is { Count: > 0 } && HasBoundFields(r) ? "No" : NotRecorded; + } + + /// A stream that ended without the provider's terminal completion (review round 2, B1): never served. + public static bool IsIncompleteStream(AuditEntryView r) + => r.Attempts?.Any(a => string.Equals(a.ErrorClass, IncompleteStream, StringComparison.Ordinal)) == true; + + /// Plain-language explanation of an incomplete stream, with the partial output the client already saw. + public static string? IncompleteStreamText(AuditEntryView r) + { + if (!IsIncompleteStream(r)) return null; + var partial = r.PartialOutputChars is { } c + ? " " + Int(c) + " characters had already been streamed to the client before it ended." + : ""; + return "The provider stream ended without a terminal completion (incomplete_stream): the request is NOT served, never cached and not continued by a fallback; the attempt was charged its estimate." + partial; + } + + /// "N characters" emitted before a stream failed, or "None" / "Not recorded". + public static string PartialOutput(AuditEntryView r) + => r.PartialOutputChars is { } c ? Int(c) + " characters streamed before the failure" : NotRecorded; + + /// The connection of the attempt that served (a fallback when one served; a cache hit's ORIGINAL + /// provenance), or "Not recorded". + public static string ServedConnection(AuditEntryView r) + => string.IsNullOrWhiteSpace(r.ServedConnectionId) ? NotRecorded + : r.CacheHit ? r.ServedConnectionId + " (produced the cached entry)" : r.ServedConnectionId; + + private static string Int(int n) => n.ToString("N0", CultureInfo.InvariantCulture); +} diff --git a/src/Covenant.Ui/Logic/RequestPaging.cs b/src/Covenant.Ui/Logic/RequestPaging.cs new file mode 100644 index 0000000..ab9b9f7 --- /dev/null +++ b/src/Covenant.Ui/Logic/RequestPaging.cs @@ -0,0 +1,92 @@ +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// What happened when a page or an error was applied to . +public enum PageResult +{ + /// The page belongs to the requested segment; its records may be shown. + Accepted, + /// The Host answered for another segment than the one requested (or a different one than the earlier + /// pages): nothing is shown rather than mislabelled records. + SegmentMismatch, + /// 410 cursor_expired: the segment was rotated (archived) or replaced since the cursor was issued. The + /// list must be reloaded from the first page; the cursor is dropped, never redirected. + CursorExpired, + /// Any other failure (400 invalid_cursor / unknown_segment, 5xx, transport). + Failed, +} + +/// Stable, cursor-based paging of ONE audit segment (docs/ui-api-contract.md "Stable paging", review round 2 +/// B8). The scope always comes from the page's segment descriptor (segment.id, segment.label, +/// segment.is_current) — never from the first row and never from what the console asked for. "Load older" +/// follows next_cursor exactly; a 410 cursor_expired stops paging and asks for a reload. Pure (no I/O). +public sealed class RequestPaging +{ + public const string CursorExpiredMessage = "The audit segment changed (archived) — reload the list."; + + /// Segment id the operator chose (null = the current segment). + public string? RequestedSegmentId { get; private set; } + /// Descriptor of the loaded pages, exactly as the Host sent it with the last accepted page. + public SegmentInfo? Segment { get; private set; } + public string? NextCursor { get; private set; } + public bool Loaded { get; private set; } + /// The cursor expired (410): Load older is disabled until the list is reloaded. + public bool Expired { get; private set; } + /// Operator-facing text of the last failure, or null. + public string? Problem { get; private set; } + + public bool CanLoadOlder => Loaded && !Expired && NextCursor is not null; + + /// Starts over for a (possibly different) segment. + public void Reset(string? segmentId) + { + RequestedSegmentId = string.IsNullOrWhiteSpace(segmentId) ? null : segmentId; + Segment = null; + NextCursor = null; + Loaded = false; + Expired = false; + Problem = null; + } + + /// Validates and applies one page. = this page was fetched with + /// (it must belong to the same segment as the pages already loaded). + public PageResult ApplyPage(RequestsResponse page, bool older) + { + var seg = page.Segment; + bool matches = RequestedSegmentId is null + ? seg.IsCurrent + : string.Equals(seg.Id, RequestedSegmentId, StringComparison.Ordinal) && !seg.IsCurrent; + if (older && Segment is { } had && !string.Equals(had.Id, seg.Id, StringComparison.Ordinal)) matches = false; + if (!matches) + { + Problem = "The Host answered for " + SegmentScope.Label(seg) + ", not the requested " + + (RequestedSegmentId is null ? "current segment" : "archived segment " + RequestedSegmentId) + + " — nothing is shown rather than mislabelled records."; + NextCursor = null; + return PageResult.SegmentMismatch; + } + Segment = seg; + NextCursor = page.Items.Count == 0 ? null : page.NextCursor; + Loaded = true; + Expired = false; + Problem = null; + return PageResult.Accepted; + } + + /// Applies a failed page request: HTTP and the Host's error code. + public PageResult ApplyError(int? status, string? errorCode, string? message) + { + if (status == 410 && string.Equals(errorCode, "cursor_expired", StringComparison.Ordinal)) + { + Expired = true; + NextCursor = null; + Problem = CursorExpiredMessage; + return PageResult.CursorExpired; + } + Problem = status == 400 && string.Equals(errorCode, "invalid_cursor", StringComparison.Ordinal) + ? "The Host rejected the paging cursor (invalid_cursor) — reload the list." + : string.IsNullOrWhiteSpace(message) ? "Could not load requests." : message; + return PageResult.Failed; + } +} diff --git a/src/Covenant.Ui/Logic/SegmentScope.cs b/src/Covenant.Ui/Logic/SegmentScope.cs index 905eba5..46f8c8e 100644 --- a/src/Covenant.Ui/Logic/SegmentScope.cs +++ b/src/Covenant.Ui/Logic/SegmentScope.cs @@ -3,35 +3,34 @@ namespace Covenant.Ui.Logic; -/// Scope wording for request lists (spec §5 Requests): which audit segment a list covers, and that -/// filtering applies only to what was loaded — never "all history". +/// Scope wording for request lists (spec §5 Requests): which audit segment a list covers (from the Host's +/// descriptor), and that filtering applies only to what was loaded — never "all history". public static class SegmentScope { public const string CurrentId = "current"; - /// Explicit flag first; else id "current"; else the first row the Host listed. - public static bool IsCurrent(AuditSegmentDto seg, IReadOnlyList? all = null) - { - if (seg.Current is { } flag) return flag; - if (string.Equals(seg.Id, CurrentId, StringComparison.OrdinalIgnoreCase)) return true; - if (all is null || all.Count == 0 || all.Any(s => s.Current == true || string.Equals(s.Id, CurrentId, StringComparison.OrdinalIgnoreCase))) - return false; - return ReferenceEquals(all[0], seg); - } + /// The Host's explicit flag (SegmentView.current) — never inferred from the id or the list order. + public static bool IsCurrent(AuditSegmentDto seg) => seg.Current; /// "Current segment · since 2026-10-16 09:00:00 UTC" or "Archived segment 2026-10-01 · read-only". - public static string Label(AuditSegmentDto seg, bool current) + public static string Label(AuditSegmentDto seg) => Label(seg.Current, seg.Label, seg.Id, seg.FirstUtc); + + /// Scope of a requests PAGE, from the page's own segment descriptor (Host SegmentInfo: id, label, + /// is_current) — never from the first row or from what the console asked for. + public static string Label(SegmentInfo seg) => Label(seg.IsCurrent, seg.Label, seg.Id, seg.FirstUtc); + + private static string Label(bool current, string? label, string? id, DateTimeOffset? firstUtc) { - if (current) return "Current segment" + (seg.FirstUtc is { } f ? " · since " + Utc(f) : ""); - var name = string.IsNullOrWhiteSpace(seg.Label) ? seg.Id : seg.Label!; + if (current) return "Current segment" + (firstUtc is { } f ? " · since " + Utc(f) : ""); + var name = !string.IsNullOrWhiteSpace(label) ? label! : !string.IsNullOrWhiteSpace(id) ? id! : "(unidentified)"; return "Archived segment " + name + " · read-only"; } - /// Selector option text with the entry count when known. - public static string Option(AuditSegmentDto seg, bool current) + /// Selector option text with the entry count. + public static string Option(AuditSegmentDto seg) { - var label = current ? "Current segment" : "Archived · " + (string.IsNullOrWhiteSpace(seg.Label) ? seg.Id : seg.Label!); - return seg.Entries is { } n ? label + " (" + n.ToString("N0", CultureInfo.InvariantCulture) + " records)" : label; + var label = seg.Current ? "Current segment" : "Archived · " + (string.IsNullOrWhiteSpace(seg.Label) ? seg.Id : seg.Label); + return label + " (" + seg.Entries.ToString("N0", CultureInfo.InvariantCulture) + " records)"; } /// The coverage sentence above the table. @@ -39,7 +38,7 @@ public static string Coverage(string scopeLabel, int loaded, int? segmentEntries { var n = loaded.ToString("N0", CultureInfo.InvariantCulture); var of = segmentEntries is { } total && total > loaded ? " of " + total.ToString("N0", CultureInfo.InvariantCulture) : ""; - var more = moreAvailable ? " Older records: use “Load older”." : loaded > 0 && segmentEntries is { } t2 && t2 > loaded ? " Older records are not reachable from this Host (no cursor)." : ""; + var more = moreAvailable ? " Older records: use “Load older”." : ""; var filter = filtersActive ? " Filters apply only to these loaded records, not to the whole segment or other segments." : ""; return scopeLabel + ": " + n + of + " records loaded, newest first." + more + filter; } diff --git a/src/Covenant.Ui/Logic/ShellStatus.cs b/src/Covenant.Ui/Logic/ShellStatus.cs index 5815ab1..5930bcb 100644 --- a/src/Covenant.Ui/Logic/ShellStatus.cs +++ b/src/Covenant.Ui/Logic/ShellStatus.cs @@ -14,30 +14,23 @@ public static class ShellStatus { public const string ModeNotReported = "Mode not reported"; - /// Maps the status/config mode value onto the badge. Accepts the v2 spellings - /// (local-only | hybrid | legacy-cloud), the enum names (LocalOnly | Hybrid | LegacyCloud) and the pre-v2 - /// "cloud". Anything else — including null — is "Mode not reported", never a guess. - public static ModeBadge Mode(string? mode) - { - var key = Normalize(mode); - return key switch - { - "localonly" or "local" => new("Local-only", "local", - "Only in-perimeter (local) connections can execute; cloud configuration cannot run."), - "hybrid" => new("Hybrid", "hybrid", - "Local and approved cloud routes; PII/PHI never route to cloud destinations."), - "legacycloud" or "cloud" => new("Legacy cloud", "legacy", - "Imported pre-v2 routing (cloud default). Review the effective rules before relying on it."), - _ => new(ModeNotReported, "unknown", "The Host did not report a provider mode."), - }; - } + public const string LocalOnly = "local-only"; + public const string Hybrid = "hybrid"; + public const string LegacyCloud = "legacy-cloud"; - private static string Normalize(string? s) + /// Maps the status/catalog/config mode value onto the badge. Exactly the contract spellings + /// (docs/ui-api-contract.md "Wire spellings"): local-only | hybrid | legacy-cloud. Anything else — including null + /// — is "Mode not reported", never a guess. + public static ModeBadge Mode(string? mode) => mode switch { - if (string.IsNullOrWhiteSpace(s)) return ""; - var chars = s.Trim().ToLowerInvariant().Where(c => c != '-' && c != '_' && c != ' ').ToArray(); - return new string(chars); - } + LocalOnly => new("Local-only", "local", + "Only in-perimeter (local) connections can execute; cloud configuration cannot run."), + Hybrid => new("Hybrid", "hybrid", + "Local and approved cloud routes; PII/PHI never route to cloud destinations."), + LegacyCloud => new("Legacy cloud", "legacy", + "Imported pre-v2 routing (cloud default). Review the effective rules before relying on it."), + _ => new(ModeNotReported, "unknown", "The Host did not report a provider mode."), + }; /// Freshness label for the header. Never a ticking seconds counter while live. public static FreshnessView Freshness(bool connected, bool stale, DateTimeOffset? lastUpdateUtc, DateTimeOffset nowUtc, string? feedError) diff --git a/src/Covenant.Ui/Logic/SubmissionPoll.cs b/src/Covenant.Ui/Logic/SubmissionPoll.cs new file mode 100644 index 0000000..166f0dc --- /dev/null +++ b/src/Covenant.Ui/Logic/SubmissionPoll.cs @@ -0,0 +1,78 @@ +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// What the console does next while it locates a console submission's request id. +public enum SubmissionPollAction +{ + /// Not registered yet (404) or a transient failure: ask again after . + PollAgain, + /// The request id is known for the first time: subscribe to its live trace NOW (exactly once). + Subscribe, + /// Stop polling (id already known, admin token rejected, the POST finished without one, or the bound). + Stop, +} + +/// Locates the server request id of one console submission BEFORE the first response byte (review round 2, +/// B7; docs/ui-api-contract.md "Early request id"): the console creates client_request_id (GUID "N"), starts the +/// POST and concurrently polls GET /admin/playground/submissions/{client_request_id} every 250 ms until it +/// answers 200 with the request id (404 = not registered yet). The first id known — from the poll or, as a backstop, +/// from the POST's response — yields exactly one . Nothing here invents an +/// id or a timing. Pure state machine (no I/O, no clock). +public sealed class SubmissionPoll(string clientRequestId) +{ + public static readonly TimeSpan Interval = TimeSpan.FromMilliseconds(250); + /// Bound: 240 polls ≈ 60 s. The Host registers the id before the pipeline starts, so it normally answers + /// on the first or second poll; past the bound the response headers still carry the id. + public const int MaxPolls = 240; + + public string ClientRequestId { get; } = clientRequestId; + /// The server request id once known (poll or response). + public string? RequestId { get; private set; } + /// Where the id came from: "submission lookup" | "response" | null. + public string? Source { get; private set; } + public int Polls { get; private set; } + public bool Stopped { get; private set; } + public string? StopReason { get; private set; } + + /// True while another GET should be sent. + public bool ShouldPoll => !Stopped && RequestId is null && Polls < MaxPolls; + + /// Applies one GET answer: HTTP (null = transport failure) and the 200 body. + public SubmissionPollAction OnPollResult(int? status, PlaygroundSubmissionDto? body) + { + if (Stopped || RequestId is not null) return SubmissionPollAction.Stop; + Polls++; + if (status == 200 && body is not null && body.RequestId.Length > 0 + && string.Equals(body.ClientRequestId, ClientRequestId, StringComparison.Ordinal)) + { + RequestId = body.RequestId; + Source = "submission lookup"; + return SubmissionPollAction.Subscribe; + } + if (status == 401) return StopWith("admin token rejected"); + if (Polls >= MaxPolls) return StopWith("request id not reported within the polling bound"); + return SubmissionPollAction.PollAgain; + } + + /// The POST finished. = X-Covenant-Request-Id (or the error body's + /// request_id). Subscribe only if polling had not already found the id; then polling stops. + public SubmissionPollAction OnSendCompleted(string? responseRequestId) + { + if (RequestId is null && !string.IsNullOrWhiteSpace(responseRequestId)) + { + RequestId = responseRequestId; + Source = "response"; + StopWith("request finished"); + return SubmissionPollAction.Subscribe; + } + StopWith(RequestId is null ? "request finished without a request id" : "request finished"); + return SubmissionPollAction.Stop; + } + + private SubmissionPollAction StopWith(string reason) + { + if (!Stopped) { Stopped = true; StopReason = reason; } + return SubmissionPollAction.Stop; + } +} diff --git a/src/Covenant.Ui/Logic/TraceModel.cs b/src/Covenant.Ui/Logic/TraceModel.cs index 044550e..7112dc6 100644 --- a/src/Covenant.Ui/Logic/TraceModel.cs +++ b/src/Covenant.Ui/Logic/TraceModel.cs @@ -1,5 +1,3 @@ -using System.Globalization; -using System.Text.Json; using Covenant.Ui.Models; namespace Covenant.Ui.Logic; @@ -10,14 +8,20 @@ namespace Covenant.Ui.Logic; public enum TraceStepState { Pending, Running, Passed, Refused, Failed, Cancelled, Skipped, NotReported } -/// One provider attempt (fallback is a second attempt, never a hidden retry). +/// One provider attempt (fallback is a second attempt, never a hidden retry). The output bounds come from +/// the attempt's trace events (review round 2, B12): requested = the request's own max_tokens, effective = the bound +/// actually sent to the provider for this attempt. Null = not reported. public sealed record TraceAttemptView( int Number, string? AttemptId, TraceStepState State, string? Target, double? DurationMs, - string? ReasonCode); + string? ReasonCode) +{ + public int? RequestedMaxOutputTokens { get; init; } + public int? EffectiveMaxOutputTokens { get; init; } +} /// One pipeline stage as reported. is non-empty only for the provider stage. public sealed record TraceStepView( @@ -58,14 +62,14 @@ public static class TraceModel _ => stage, }; - public static TraceStepState ParseState(string? state) => (state ?? "").Trim().ToLowerInvariant() switch + public static TraceStepState ParseState(string? state) => state switch { "pending" => TraceStepState.Pending, "running" => TraceStepState.Running, "passed" => TraceStepState.Passed, "refused" => TraceStepState.Refused, "failed" => TraceStepState.Failed, - "cancelled" or "canceled" => TraceStepState.Cancelled, + "cancelled" => TraceStepState.Cancelled, "skipped" => TraceStepState.Skipped, _ => TraceStepState.NotReported, }; @@ -165,7 +169,17 @@ private static TraceStepView ReduceProvider(List evs) foreach (var id in ids) { var r = ReduceStage("provider", byId[id]); - attempts.Add(new TraceAttemptView(attempts.Count + 1, id, r.State, r.Target, r.DurationMs, r.ReasonCode)); + int? requested = null, effective = null; + foreach (var e in byId[id]) + { + if (e.RequestedMaxOutputTokens is { } rq) requested = rq; + if (e.EffectiveMaxOutputTokens is { } ef) effective = ef; + } + attempts.Add(new TraceAttemptView(attempts.Count + 1, id, r.State, r.Target, r.DurationMs, r.ReasonCode) + { + RequestedMaxOutputTokens = requested, + EffectiveMaxOutputTokens = effective, + }); } if (attempts.Count == 0 && stageLevel.Count > 0) { @@ -194,44 +208,24 @@ private static TraceStepView ReduceProvider(List evs) return new TraceStepView("provider", Label("provider"), state, total, reason, lastAttempt?.Target, evs[0].TsUtc, attempts); } - /// Builds a view from the compact trace persisted on the audit record (audit v3 Trace[]) when the - /// live trace has expired. Accepts objects {Stage, State, DurationMs} or "stage:state:ms" strings; - /// anything else is ignored. Provider entries in order become attempts. - public static TraceView? FromAuditSummary(IReadOnlyList? summary, IReadOnlyList? attempts = null, int? configVersion = null) + /// Builds a view from the compact trace persisted on the audit record (audit v3 Trace[], Core + /// AuditTraceStep) when the live trace has expired. Provider steps carry their AttemptId; the matching + /// Attempts[] entry supplies the target. + public static TraceView? FromAuditSummary(IReadOnlyList? summary, IReadOnlyList? attempts = null, int? configVersion = null) { if (summary is null || summary.Count == 0) return null; - var events = new List(); + var events = new List(summary.Count); long seq = 0; - int providerIndex = 0; - foreach (var el in summary) + foreach (var step in summary) { - string? stage = null, state = null; - double? ms = null; - if (el.ValueKind == JsonValueKind.Object) - { - stage = Str(el, "Stage") ?? Str(el, "stage"); - state = Str(el, "State") ?? Str(el, "state"); - ms = Num(el, "DurationMs") ?? Num(el, "duration_ms"); - } - else if (el.ValueKind == JsonValueKind.String && el.GetString() is { } text) - { - var parts = text.Split(':'); - if (parts.Length >= 2) { stage = parts[0]; state = parts[1]; } - if (parts.Length >= 3 && double.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var d)) ms = d; - } - if (string.IsNullOrWhiteSpace(stage) || string.IsNullOrWhiteSpace(state)) continue; - - string? attemptId = null, target = null; - if (string.Equals(stage, "provider", StringComparison.OrdinalIgnoreCase)) - { - providerIndex++; - var a = attempts is not null && providerIndex <= attempts.Count ? attempts[providerIndex - 1] : null; - attemptId = a?.AttemptId ?? ("attempt-" + providerIndex.ToString(CultureInfo.InvariantCulture)); - target = a is null ? null : Target(a); - } + if (string.IsNullOrWhiteSpace(step.Stage) || string.IsNullOrWhiteSpace(step.State)) continue; + string? target = null; + if (step.AttemptId is { Length: > 0 } aid && attempts?.FirstOrDefault(a => string.Equals(a.AttemptId, aid, StringComparison.Ordinal)) is { } attempt) + target = Target(attempt); events.Add(new TraceEventDto { - Seq = ++seq, Stage = stage, State = state, DurationMs = ms, AttemptId = attemptId, Target = target, + Seq = ++seq, Stage = step.Stage, State = step.State, DurationMs = step.DurationMs, + AttemptId = step.AttemptId, ReasonCode = step.ReasonCode, Target = target, }); } return events.Count == 0 ? null : Reduce(events, complete: true, configVersion, source: "audit summary"); @@ -245,12 +239,6 @@ private static TraceStepView ReduceProvider(List evs) if (c is null && m is null) return null; return c is null ? m : m is null ? c : c + "/" + m; } - - private static string? Str(JsonElement el, string name) - => el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; - - private static double? Num(JsonElement el, string name) - => el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out var d) ? d : null; } /// Collects trace events for one request as they arrive (live stream, replay after reconnect, snapshot) diff --git a/src/Covenant.Ui/Models/ConfigContracts.cs b/src/Covenant.Ui/Models/ConfigContracts.cs index f5f240b..1c84256 100644 --- a/src/Covenant.Ui/Models/ConfigContracts.cs +++ b/src/Covenant.Ui/Models/ConfigContracts.cs @@ -6,9 +6,10 @@ namespace Covenant.Ui.Models; // src/Covenant.Core/Configuration.cs as console DTOs. Plain C#: linked into tests/Covenant.Tests, so no Blazor types. // // Naming: every type ends in "Dto" so nothing collides with Covenant.Core's ApplicationConfig/ConnectionConfig/… -// when both namespaces are imported (the tests do). Enums travel as strings ("local-only", "Public", …) and are -// kept as strings here: an older or newer Host with an unexpected value must still deserialize, and the console -// renders unknown values verbatim rather than guessing. Like Contracts.cs, nothing is `required`. +// when both namespaces are imported (the tests do). Enums travel as strings in EXACTLY the contract spellings +// (docs/ui-api-contract.md "Wire spellings": "local-only", "length-heuristic", "warn-only", "Public", "Local", …); +// the console compares against those spellings only — there is no alternative-spelling fallback. One shape per +// endpoint; tests/Covenant.Tests/ContractRoundTripTests.cs pins every one against the Host serializer. // ---- Configuration (ADR-0011) ---- @@ -281,6 +282,10 @@ public sealed class TraceEventDto [JsonPropertyName("duration_ms")] public double? DurationMs { get; set; } [JsonPropertyName("reason_code")] public string? ReasonCode { get; set; } [JsonPropertyName("target")] public string? Target { get; set; } + /// Provider attempt events only: the request's own max_tokens (absent when the caller sent none). + [JsonPropertyName("requested_max_output_tokens")] public int? RequestedMaxOutputTokens { get; set; } + /// Provider attempt events only: the bound actually sent to the provider for this attempt. + [JsonPropertyName("effective_max_output_tokens")] public int? EffectiveMaxOutputTokens { get; set; } } public sealed class TraceSnapshotDto @@ -288,9 +293,21 @@ public sealed class TraceSnapshotDto [JsonPropertyName("request_id")] public string? RequestId { get; set; } [JsonPropertyName("config_version")] public int? ConfigVersion { get; set; } [JsonPropertyName("complete")] public bool Complete { get; set; } + /// More than the per-request bound of events was emitted; later ones were dropped by the Host. + [JsonPropertyName("truncated")] public bool Truncated { get; set; } [JsonPropertyName("events")] public List Events { get; set; } = []; } +/// GET /admin/playground/submissions/{client_request_id} (review round 2, B7): the server request id of a +/// console submission, known BEFORE the first response byte. 404 = not registered (yet), or expired. +public sealed class PlaygroundSubmissionDto +{ + [JsonPropertyName("client_request_id")] public string ClientRequestId { get; set; } = ""; + [JsonPropertyName("request_id")] public string RequestId { get; set; } = ""; + /// running | completed + [JsonPropertyName("state")] public string State { get; set; } = ""; +} + // ---- Budgets (ADR-0014) and the policy simulator — read-only shapes ---- public sealed class BudgetStateDto @@ -348,35 +365,70 @@ public sealed class SimulateResponseDto [JsonPropertyName("explanation")] public string? Explanation { get; set; } } -// ---- Budget drill-down and audit archive (ADR-0014, spec §5) — integration pending on the backend ---- +// ---- Budget drill-down and audit archive (ADR-0014, spec §5) ---- + +/// GET /admin/budgets/{id}/requests (Host BudgetRequestsView, CovenantJsonContext). +public sealed class BudgetRequestsDto +{ + [JsonPropertyName("budget_id")] public string BudgetId { get; set; } = ""; + [JsonPropertyName("scope")] public string Scope { get; set; } = ""; + [JsonPropertyName("period_id")] public string PeriodId { get; set; } = ""; + [JsonPropertyName("items")] public List Items { get; set; } = []; +} -/// One settled contribution to a budget (GET /admin/budgets/{id}/requests → {budget_id, scope, period_id, -/// items:[{request_id, attempt_id, kind, amount_usd, ts_utc, overrun}]}). Parsed leniently by Logic/BudgetRequests -/// (also a bare array and a few alternative field names) so a naming difference degrades to "Not reported". -public sealed class BudgetRequestDto +/// One settled contribution to a budget's scope (Host BudgetContributionView), newest first. +public sealed class BudgetContributionDto { - public string RequestId { get; set; } = ""; - public string? AttemptId { get; set; } - public decimal? AmountUsd { get; set; } - public DateTimeOffset? TimestampUtc { get; set; } - public string? Scope { get; set; } + [JsonPropertyName("request_id")] public string RequestId { get; set; } = ""; + [JsonPropertyName("attempt_id")] public string AttemptId { get; set; } = ""; /// settle | settle-recovered | legacy-import. - public string? Kind { get; set; } + [JsonPropertyName("kind")] public string Kind { get; set; } = ""; + [JsonPropertyName("amount_usd")] public decimal AmountUsd { get; set; } + [JsonPropertyName("ts_utc")] public DateTimeOffset TsUtc { get; set; } /// Reported charge exceeded the reservation (settled in full, never truncated). - public bool Overrun { get; set; } + [JsonPropertyName("overrun")] public bool Overrun { get; set; } } -/// GET /admin/audit/segments row: the current segment plus archived siblings (ids only, never paths). +/// GET /admin/audit/segments row (Host SegmentView): the current segment plus archived siblings (ids only, +/// never paths). is always present — the console never infers which segment is current. public sealed class AuditSegmentDto { [JsonPropertyName("id")] public string Id { get; set; } = ""; - [JsonPropertyName("label")] public string? Label { get; set; } - [JsonPropertyName("entries")] public int? Entries { get; set; } + [JsonPropertyName("label")] public string Label { get; set; } = ""; + [JsonPropertyName("current")] public bool Current { get; set; } + [JsonPropertyName("entries")] public int Entries { get; set; } + [JsonPropertyName("events")] public int Events { get; set; } [JsonPropertyName("first_utc")] public DateTimeOffset? FirstUtc { get; set; } [JsonPropertyName("last_utc")] public DateTimeOffset? LastUtc { get; set; } - [JsonPropertyName("chain_valid")] public bool? ChainValid { get; set; } - [JsonPropertyName("events")] public int? Events { get; set; } + [JsonPropertyName("chain_valid")] public bool ChainValid { get; set; } [JsonPropertyName("archived_utc")] public DateTimeOffset? ArchivedUtc { get; set; } - /// Optional explicit flag; when absent the console treats id "current" (else the first row) as current. - [JsonPropertyName("current")] public bool? Current { get; set; } +} + +/// GET /admin/requests/{id}/export (Host RequestExport, AuditJsonContext): one request's evidence — never prompt +/// or response content. The console downloads the server's bytes verbatim; this typed view is what it may show. +public sealed class RequestExportDto +{ + [JsonPropertyName("exported_utc")] public DateTimeOffset ExportedUtc { get; set; } + [JsonPropertyName("request_id")] public string RequestId { get; set; } = ""; + [JsonPropertyName("segment")] public AuditSegmentDto Segment { get; set; } = new(); + [JsonPropertyName("config_version")] public int? ConfigVersion { get; set; } + [JsonPropertyName("record")] public AuditEntryView Record { get; set; } = new(); + [JsonPropertyName("attempts")] public List? Attempts { get; set; } + [JsonPropertyName("trace")] public List? Trace { get; set; } + [JsonPropertyName("integrity")] public ExportIntegrityDto Integrity { get; set; } = new(); + [JsonPropertyName("content_included")] public bool ContentIncluded { get; set; } +} + +public sealed class ExportIntegrityDto +{ + [JsonPropertyName("segment_id")] public string SegmentId { get; set; } = ""; + [JsonPropertyName("chain_valid")] public bool ChainValid { get; set; } + [JsonPropertyName("chain_failure")] public string? ChainFailure { get; set; } + /// 1-based line of the record in its segment. + [JsonPropertyName("line")] public int? Line { get; set; } + [JsonPropertyName("previous_hash")] public string? PreviousHash { get; set; } + [JsonPropertyName("entry_hash")] public string? EntryHash { get; set; } + [JsonPropertyName("anchor_configured")] public bool AnchorConfigured { get; set; } + /// verified | unverified + [JsonPropertyName("status")] public string Status { get; set; } = ""; } diff --git a/src/Covenant.Ui/Models/Contracts.cs b/src/Covenant.Ui/Models/Contracts.cs index d24d00c..38d1aca 100644 --- a/src/Covenant.Ui/Models/Contracts.cs +++ b/src/Covenant.Ui/Models/Contracts.cs @@ -2,10 +2,11 @@ namespace Covenant.Ui.Models; -// Wire shapes the console reads, mirrored from docs/ui-api-contract.md and the Host's StatusContracts.cs / -// Evidence.cs / OpenAiContracts.cs. Deliberately lenient: nothing is `required`, fields added by later tasks are -// nullable, unknown members are ignored — the console must render an older or newer Host truthfully -// ("Not recorded") rather than fail to deserialize. +// Wire shapes the console reads, mirrored one-to-one from the Host DTOs (StatusContracts.cs, Evidence.cs, +// OpenAiContracts.cs, ConsoleBackend.cs, AuditSegments.cs, Covenant.Core AuditEntry) and docs/ui-api-contract.md. +// ONE shape per endpoint: no alternative field names, no shape sniffing. The only intentional variance is the +// documented audit-record evolution (legacy lines lack the v2/v3 fields → nullable here → "Not recorded"). +// tests/Covenant.Tests/ContractRoundTripTests.cs serializes the Host types and reads them with UiJsonContext. public sealed class StatusReport { @@ -21,7 +22,6 @@ public sealed class StatusReport [JsonPropertyName("otel_enabled")] public bool OtelEnabled { get; set; } [JsonPropertyName("routing_threshold_tokens")] public long RoutingThresholdTokens { get; set; } - // Task 07 additions (nullable until the Host ships them). [JsonPropertyName("environment")] public string? Environment { get; set; } [JsonPropertyName("mode")] public string? Mode { get; set; } [JsonPropertyName("audit_path")] public string? AuditPath { get; set; } @@ -31,6 +31,21 @@ public sealed class StatusReport [JsonPropertyName("version")] public string? Version { get; set; } // v2: the active configuration version every new request binds to. [JsonPropertyName("config_version")] public int? ConfigVersion { get; set; } + /// Review round 2 (B11): CURRENT runtime health of every configured connection + model. + [JsonPropertyName("connection_health")] public List? ConnectionHealth { get; set; } +} + +/// /admin/status connection_health[] row (Host ConnectionHealthView). +public sealed class ConnectionHealthDto +{ + /// "connection_id:model_id". + [JsonPropertyName("key")] public string Key { get; set; } = ""; + [JsonPropertyName("connection_id")] public string ConnectionId { get; set; } = ""; + [JsonPropertyName("model_id")] public string ModelId { get; set; } = ""; + /// Local | Cloud. + [JsonPropertyName("boundary")] public string Boundary { get; set; } = ""; + [JsonPropertyName("enabled")] public bool Enabled { get; set; } + [JsonPropertyName("health")] public ModelHealth Health { get; set; } = new(); } public sealed class AnchorStatus @@ -81,11 +96,27 @@ public sealed class FinOpsSummary [JsonPropertyName("savings_router_usd")] public decimal SavingsRouterUsd { get; set; } [JsonPropertyName("savings_cache_usd")] public decimal SavingsCacheUsd { get; set; } [JsonPropertyName("cache_hits")] public int CacheHits { get; set; } + [JsonPropertyName("unknown_cost_requests")] public int UnknownCostRequests { get; set; } + /// Requests whose total includes an estimate (estimated_from_text / estimated_failed_call / mixed). + [JsonPropertyName("estimated_cost_requests")] public int EstimatedCostRequests { get; set; } [JsonPropertyName("cost_by_team_usd")] public Dictionary CostByTeamUsd { get; set; } = new(); [JsonPropertyName("denials_by_reason")] public Dictionary DenialsByReason { get; set; } = new(); [JsonPropertyName("activity")] public List Activity { get; set; } = []; [JsonPropertyName("requests_by_model")] public Dictionary RequestsByModel { get; set; } = new(); [JsonPropertyName("recent")] public List Recent { get; set; } = []; + /// Present only when the active configuration names a priced savings baseline; null otherwise. + [JsonPropertyName("savings")] public SavingsSummaryDto? Savings { get; set; } +} + +public sealed class SavingsSummaryDto +{ + [JsonPropertyName("label")] public string Label { get; set; } = ""; + /// "connection/model" of the configured baseline. + [JsonPropertyName("baseline")] public string Baseline { get; set; } = ""; + [JsonPropertyName("route_avoided_usd")] public decimal RouteAvoidedUsd { get; set; } + [JsonPropertyName("cache_avoided_usd")] public decimal CacheAvoidedUsd { get; set; } + [JsonPropertyName("total_usd")] public decimal TotalUsd { get; set; } + [JsonPropertyName("excluded_records")] public int ExcludedRecords { get; set; } } public sealed class ActivityBucket @@ -119,6 +150,7 @@ public sealed class RecentRequest [JsonPropertyName("signal")] public string? Signal { get; set; } [JsonPropertyName("prompt_preview")] public string? PromptPreview { get; set; } [JsonPropertyName("cache")] public bool CacheHit { get; set; } + [JsonPropertyName("cost_basis")] public string? CostBasis { get; set; } } public sealed class KillSwitchRequest @@ -154,6 +186,8 @@ public sealed class EvidenceReport [JsonPropertyName("chain_failure")] public string? ChainFailure { get; set; } [JsonPropertyName("first_invalid_line")] public int? FirstInvalidLine { get; set; } [JsonPropertyName("entries")] public int Entries { get; set; } + /// Control-plane events in the chain (config.activated, …) — not requests. + [JsonPropertyName("events")] public int Events { get; set; } [JsonPropertyName("allowed")] public int Allowed { get; set; } [JsonPropertyName("denied")] public int Denied { get; set; } [JsonPropertyName("first_entry_utc")] public DateTimeOffset? FirstEntryUtc { get; set; } @@ -162,7 +196,6 @@ public sealed class EvidenceReport [JsonPropertyName("cost_by_team_usd")] public Dictionary CostByTeamUsd { get; set; } = new(); [JsonPropertyName("requests_by_classification")] public Dictionary RequestsByClassification { get; set; } = new(); - // Task 07 additions. [JsonPropertyName("anchor_configured")] public bool? AnchorConfigured { get; set; } [JsonPropertyName("anchor_count")] public long? AnchorCount { get; set; } [JsonPropertyName("last_anchor_utc")] public DateTimeOffset? LastAnchorUtc { get; set; } @@ -170,21 +203,24 @@ public sealed class EvidenceReport // ---- Admin lookups (Task 02): audit records are serialized with their C# names (AuditJsonContext). ---- +/// GET /admin/requests page (Host RequestsPage, AuditJsonContext). public sealed class RequestsResponse { [JsonPropertyName("segment")] public SegmentInfo Segment { get; set; } = new(); [JsonPropertyName("items")] public List Items { get; set; } = []; - /// Opaque newest-first position of the next (older) page; null/absent = no older page from this Host. + /// Opaque cursor of the next (older) page of the SAME segment; null on the last page. [JsonPropertyName("next_cursor")] public string? NextCursor { get; set; } } +/// Segment descriptor of a requests page (Host SegmentInfo). , and +/// come from the server on every page — the console never infers the current segment. public sealed class SegmentInfo { - /// Segment id (GET /admin/audit/segments). Required to confirm an archived-segment answer. [JsonPropertyName("id")] public string? Id { get; set; } [JsonPropertyName("label")] public string? Label { get; set; } - [JsonPropertyName("path")] public string? Path { get; set; } - [JsonPropertyName("events")] public int? Events { get; set; } + [JsonPropertyName("is_current")] public bool IsCurrent { get; set; } + [JsonPropertyName("path")] public string Path { get; set; } = ""; + [JsonPropertyName("events")] public int Events { get; set; } [JsonPropertyName("entries")] public int Entries { get; set; } [JsonPropertyName("chain_valid")] public bool ChainValid { get; set; } [JsonPropertyName("first_utc")] public DateTimeOffset? FirstUtc { get; set; } @@ -230,28 +266,50 @@ public sealed class AuditEntryView [JsonPropertyName("ProfileId")] public string? ProfileId { get; set; } [JsonPropertyName("BaselineClassification")] public string? BaselineClassification { get; set; } [JsonPropertyName("Attempts")] public List? Attempts { get; set; } - /// Compact persisted trace. Kept as raw JSON elements because the summary may be objects - /// ({Stage, State, DurationMs}) or "stage:state:ms" strings; Logic/TraceModel.FromAuditSummary reads both, so an - /// unexpected shape degrades to "Not recorded" instead of breaking the whole record. - [JsonPropertyName("Trace")] public List? Trace { get; set; } + /// Compact persisted trace (Core AuditTraceStep): terminal states only, one provider step per attempt. + [JsonPropertyName("Trace")] public List? Trace { get; set; } [JsonPropertyName("ReservedUsd")] public decimal? ReservedUsd { get; set; } [JsonPropertyName("SettledUsd")] public decimal? SettledUsd { get; set; } + /// max_tokens as the caller asked (null = none asked, or a record older than this field). + [JsonPropertyName("RequestedMaxOutputTokens")] public int? RequestedMaxOutputTokens { get; set; } + /// The output bound Covenant enforced (sent to the provider and used for the reservation). + [JsonPropertyName("EffectiveMaxOutputTokens")] public int? EffectiveMaxOutputTokens { get; set; } + /// Characters already emitted to the client before a stream failed (non-served records only). + [JsonPropertyName("PartialOutputChars")] public int? PartialOutputChars { get; set; } + /// Connection of the attempt that served (a fallback when one served; on a cache hit the connection that + /// produced the cached entry). + [JsonPropertyName("ServedConnectionId")] public string? ServedConnectionId { get; set; } +} + +/// One step of the compact persisted trace (Core AuditTraceStep). +public sealed class AuditTraceStepView +{ + [JsonPropertyName("Stage")] public string Stage { get; set; } = ""; + [JsonPropertyName("State")] public string State { get; set; } = ""; + [JsonPropertyName("DurationMs")] public double? DurationMs { get; set; } + [JsonPropertyName("AttemptId")] public string? AttemptId { get; set; } + [JsonPropertyName("ReasonCode")] public string? ReasonCode { get; set; } } -/// One provider attempt recorded on an audit v3 record (fallback evidence). +/// One provider attempt recorded on an audit v3 record (Core AuditAttempt). Outcome ∈ served | failed | cancelled; +/// ErrorClass ∈ connect | timeout | 429 | 5xx | non_retryable | client_cancelled | client_disconnected | incomplete_stream. public sealed class AuditAttemptView { - [JsonPropertyName("AttemptId")] public string? AttemptId { get; set; } - [JsonPropertyName("ConnectionId")] public string? ConnectionId { get; set; } - [JsonPropertyName("ModelId")] public string? ModelId { get; set; } - [JsonPropertyName("Outcome")] public string? Outcome { get; set; } + [JsonPropertyName("AttemptId")] public string AttemptId { get; set; } = ""; + [JsonPropertyName("ConnectionId")] public string ConnectionId { get; set; } = ""; + [JsonPropertyName("ModelId")] public string ModelId { get; set; } = ""; + [JsonPropertyName("Outcome")] public string Outcome { get; set; } = ""; [JsonPropertyName("ErrorClass")] public string? ErrorClass { get; set; } - [JsonPropertyName("DurationMs")] public double? DurationMs { get; set; } + [JsonPropertyName("DurationMs")] public double DurationMs { get; set; } [JsonPropertyName("CostUsd")] public decimal? CostUsd { get; set; } [JsonPropertyName("CostBasis")] public string? CostBasis { get; set; } // T04/T06 additive: the attempt's reservation and whether the reported charge exceeded it (settled in full). [JsonPropertyName("ReservedUsd")] public decimal? ReservedUsd { get; set; } [JsonPropertyName("Overrun")] public bool? Overrun { get; set; } + /// The output bound enforced for THIS attempt (a fallback model may have a lower model bound). + [JsonPropertyName("EffectiveMaxOutputTokens")] public int? EffectiveMaxOutputTokens { get; set; } + /// True when the provider finished with "length" (output cut at the bound). + [JsonPropertyName("Truncated")] public bool? Truncated { get; set; } } public sealed class AttributionTagsView @@ -327,9 +385,10 @@ public sealed class CatalogModel [JsonPropertyName("key")] public string? Key { get; set; } } +/// Host HealthView: state ∈ unknown | ok | failed. public sealed class ModelHealth { - [JsonPropertyName("state")] public string? State { get; set; } + [JsonPropertyName("state")] public string State { get; set; } = "unknown"; [JsonPropertyName("last_success_utc")] public DateTimeOffset? LastSuccessUtc { get; set; } [JsonPropertyName("last_failure_utc")] public DateTimeOffset? LastFailureUtc { get; set; } [JsonPropertyName("last_error")] public string? LastError { get; set; } @@ -341,7 +400,11 @@ public sealed class LocalRouteInfo [JsonPropertyName("endpoint")] public string? Endpoint { get; set; } [JsonPropertyName("model_id")] public string? ModelId { get; set; } [JsonPropertyName("registered")] public bool Registered { get; set; } - [JsonPropertyName("endpoint_health")] public ModelHealth? EndpointHealth { get; set; } + [JsonPropertyName("endpoint_health")] public ModelHealth EndpointHealth { get; set; } = new(); + /// Review round 2 (B11): the local-boundary connection this view describes. + [JsonPropertyName("connection_id")] public string? ConnectionId { get; set; } + /// CURRENT runtime health of exactly : (real governed attempts). + [JsonPropertyName("health")] public ModelHealth? Health { get; set; } } public sealed class ProbeRequest @@ -455,4 +518,8 @@ public sealed class StreamFrameDto // T08 editors and evidence [JsonSerializable(typeof(ConfigErrorResponseDto))] [JsonSerializable(typeof(List))] +// Review round 2: typed budget drill-down, request export, early console request id. +[JsonSerializable(typeof(BudgetRequestsDto))] +[JsonSerializable(typeof(RequestExportDto))] +[JsonSerializable(typeof(PlaygroundSubmissionDto))] public partial class UiJsonContext : JsonSerializerContext; diff --git a/src/Covenant.Ui/Pages/Budgets.razor b/src/Covenant.Ui/Pages/Budgets.razor index b1b39a2..5f7bac3 100644 --- a/src/Covenant.Ui/Pages/Budgets.razor +++ b/src/Covenant.Ui/Pages/Budgets.razor @@ -244,7 +244,7 @@
  • @req.RequestId @Money.Usd(req.AmountUsd) - @(req.TimestampUtc is { } ts ? Fmt.Utc(ts) : "time not reported")@(req.AttemptId is { Length: > 0 } at ? " · attempt " + at : "")@(req.Kind is { Length: > 0 } k && k != "settle" ? " · " + k : "") + @(Fmt.Utc(req.TsUtc) + (req.AttemptId.Length > 0 ? " · attempt " + req.AttemptId : "") + (req.Kind != "settle" && req.Kind.Length > 0 ? " · " + req.Kind : "")) @if (req.Overrun) { Reported charge exceeded the reservation — settled in full. @@ -269,7 +269,7 @@ private BudgetStateDto? _drill; private bool _drillLoading; private string? _drillError; - private List? _drillRows; + private List? _drillRows; private string _newKind = "team"; private string? _newName; @@ -399,10 +399,9 @@ StateHasChanged(); try { - var json = await Api.GetBudgetRequestsJsonAsync(b.Id); + var page = await Api.GetBudgetRequestsAsync(b.Id); if (!ReferenceEquals(_drill, b)) return; - _drillRows = BudgetRequests.Parse(json); - if (_drillRows is null) _drillError = "The Host answered in an unrecognised shape — nothing is shown rather than a guess."; + _drillRows = page.Items; } catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.NotFound) { diff --git a/src/Covenant.Ui/Pages/Connections.razor b/src/Covenant.Ui/Pages/Connections.razor index 4cdce3e..7f28e9c 100644 --- a/src/Covenant.Ui/Pages/Connections.razor +++ b/src/Covenant.Ui/Pages/Connections.razor @@ -233,9 +233,9 @@ private ConnectionHealthView HealthFor(ConnectionDto conn, CatalogConnectionDto? cat) { + // One shape: the catalog's connection-scoped view (catalog.connections[].models[].health). A connection the + // catalog does not list has no observed health yet. var models = cat?.Models.Select(m => m.Health).ToList() ?? new List(); - if (cat is null && State.Catalog is { } legacy) - models = legacy.Models.Where(m => string.Equals(m.ConnectionId ?? m.Adapter, conn.Id, StringComparison.Ordinal)).Select(m => m.Health).ToList(); ModelHealth? endpointHealth = null; if (State.Catalog?.Local is { } local && ConnectionLogic.SameEndpoint(local.Endpoint, conn.Endpoint)) endpointHealth = local.EndpointHealth; _probes.TryGetValue(conn.Id, out var probe); diff --git a/src/Covenant.Ui/Pages/Evidence.razor b/src/Covenant.Ui/Pages/Evidence.razor index df76e0a..ddca3d9 100644 --- a/src/Covenant.Ui/Pages/Evidence.razor +++ b/src/Covenant.Ui/Pages/Evidence.razor @@ -168,11 +168,11 @@ @foreach (var sg in segs) { - var current = SegmentScope.IsCurrent(sg, segs); + var current = SegmentScope.IsCurrent(sg); - @(current ? "Current" : "Archived · " + (sg.Label ?? sg.Id)) + @(current ? "Current" : "Archived · " + (string.IsNullOrWhiteSpace(sg.Label) ? sg.Id : sg.Label)) @(sg.FirstUtc is null ? "No records" : Fmt.Utc(sg.FirstUtc) + " → " + Fmt.Utc(sg.LastUtc)) - @(sg.Entries is { } n ? Fmt.Int(n) : "—") + @Fmt.Int(sg.Entries) @ChainLabel(sg.ChainValid) } diff --git a/src/Covenant.Ui/Pages/Overview.razor b/src/Covenant.Ui/Pages/Overview.razor index c373983..1d59ab8 100644 --- a/src/Covenant.Ui/Pages/Overview.razor +++ b/src/Covenant.Ui/Pages/Overview.razor @@ -32,22 +32,28 @@

    Setup checks

    - Individual checks — not a readiness verdict + Each check stands alone
      @foreach (var c in Checks(s)) { -
    • +
    • @c.Name - @c.Value + + @c.Value + @if (c.Id is { Length: > 0 } cid) + { + @cid + } + @if (c.ActionText is not null && c.Href is not null) { - @c.ActionText + @c.ActionText } else if (c.ActionText is not null && c.Resume) { - + }
    • } @@ -184,7 +190,10 @@ @code { - private sealed record Check(string Name, string Value, string Tone, string? ActionText = null, string? Href = null, bool Resume = false); + /// One setup check. is a short status (no ids); (a scope or connection id) + /// is rendered separately and is the only part allowed to break anywhere; holds the long form. + private sealed record Check(string Name, string Value, string Tone, string? ActionText = null, string? Href = null, bool Resume = false, + string? Id = null, string? Title = null); private bool _busy; @@ -200,44 +209,44 @@ { var fresh = ShellStatus.Freshness(State.Connected, State.IsStale, State.LastUpdatedUtc, DateTimeOffset.UtcNow, State.FeedError); yield return fresh.Stale - ? new Check("Console", "Connected · status " + fresh.Label.ToLowerInvariant() + " (retrying)", "warn") - : new Check("Console", "Connected · live status", "ok"); + ? new Check("Console", "Status " + fresh.Label.ToLowerInvariant(), "warn", Title: "Connected; the status feed is stale and retrying") + : new Check("Console", "Live", "ok", Title: "Connected · live status"); var mode = ShellStatus.Mode(s.Mode); yield return mode.Tone == "unknown" - ? new Check("Mode", ShellStatus.ModeNotReported, "warn", "Models & connections", "connections") - : new Check("Mode", mode.Label, mode.Tone == "legacy" ? "warn" : "ok", mode.Tone == "legacy" ? "Review policies" : null, mode.Tone == "legacy" ? "policies" : null); + ? new Check("Mode", "Not reported", "warn", "Open", "connections", Title: ShellStatus.ModeNotReported) + : new Check("Mode", mode.Label, mode.Tone == "legacy" ? "warn" : "ok", mode.Tone == "legacy" ? "Review" : null, mode.Tone == "legacy" ? "policies" : null, Title: mode.Description); - var local = RouteHealth.LocalRoute(State.Catalog, DateTimeOffset.UtcNow); + var local = RouteHealth.LocalRoute(State.Catalog, State.LastStatus, DateTimeOffset.UtcNow); yield return local.State switch { - LocalRouteState.Ready => new Check("Local route", "Ready", "ok"), - LocalRouteState.Degraded => new Check("Local route", "Degraded — last call or probe failed", "warn", "Review connection", "connections"), - LocalRouteState.NotRegistered => new Check("Local route", "Configured, not registered", "bad", "Fix connection", "connections"), - LocalRouteState.NotConfigured => new Check("Local route", "Not configured — sensitive requests will be refused", "warn", "Add a local connection", "connections"), - LocalRouteState.NotObserved => new Check("Local route", "Registered, not yet observed", "hollow", "Test connection", "connections"), - _ => new Check("Local route", State.CatalogError is { } ce ? "Unknown — " + ce : "Unknown (catalog not loaded)", "hollow", "Models & connections", "connections"), + LocalRouteState.Ready => new Check("Local route", "Ready", "ok", Id: local.Target, Title: local.Text), + LocalRouteState.Degraded => new Check("Local route", "Degraded", "warn", "Review", "connections", Id: local.Target, Title: local.Text + (local.LastError is { Length: > 0 } le ? " · " + le : "")), + LocalRouteState.NotRegistered => new Check("Local route", "Not registered", "bad", "Fix", "connections", Id: local.Target, Title: local.Text), + LocalRouteState.NotConfigured => new Check("Local route", "Not configured", "warn", "Add", "connections", Title: "No local connection — sensitive requests will be refused"), + LocalRouteState.NotObserved => new Check("Local route", "Not yet observed", "hollow", "Test", "connections", Id: local.Target, Title: local.Text), + _ => new Check("Local route", "Unknown", "hollow", "Open", "connections", Title: State.CatalogError ?? local.Text), }; yield return State.Paused - ? new Check("Provider calls", "Paused" + (string.IsNullOrWhiteSpace(s.KillSwitch.Reason) ? "" : " — " + s.KillSwitch.Reason), "warn", "Resume provider calls", Resume: true) + ? new Check("Provider calls", "Paused", "warn", "Resume", Resume: true, Title: string.IsNullOrWhiteSpace(s.KillSwitch.Reason) ? "Paused" : "Paused — " + s.KillSwitch.Reason) : new Check("Provider calls", "Accepted", "ok"); yield return BudgetCheck(s); if (Ws.ApplicationsError is { } ae) - yield return new Check("Test applications", ae, "warn"); + yield return new Check("Test applications", "Unavailable", "warn", Title: ae); else if (Ws.Applications is { } apps) { int testable = apps.Count(a => ComposerRules.WhyNotSelectable(a) is null); yield return testable == 0 - ? new Check("Test applications", "None enabled for console testing", "warn", "Settings", "settings") - : new Check("Test applications", testable.ToString(System.Globalization.CultureInfo.InvariantCulture) + " available to run as", "ok"); + ? new Check("Test applications", "None testable", "warn", "Settings", "settings", Title: "No application is enabled for console testing") + : new Check("Test applications", testable.ToString(System.Globalization.CultureInfo.InvariantCulture) + " available", "ok", Title: "Applications the console can run as"); } yield return s.ChainValid - ? new Check("Audit chain", "Verifies (current segment)", "ok") - : new Check("Audit chain", "Verification failed", "bad", "Open audit & evidence", "evidence"); + ? new Check("Audit chain", "Verifies", "ok", Title: "The current segment's hash chain verifies") + : new Check("Audit chain", "Fails", "bad", "Open", "evidence", Title: "The current segment's hash chain does not verify"); } private Check BudgetCheck(StatusReport s) @@ -247,17 +256,20 @@ var worst = budgets.FirstOrDefault(b => string.Equals(b.Warning, "exceeded", StringComparison.OrdinalIgnoreCase)) ?? budgets.FirstOrDefault(b => string.Equals(b.Warning, "critical", StringComparison.OrdinalIgnoreCase)) ?? budgets.FirstOrDefault(b => string.Equals(b.Warning, "warn", StringComparison.OrdinalIgnoreCase)); - if (worst is null) return new Check("Budgets", "No budget warning", "ok"); - var tone = string.Equals(worst.Warning, "warn", StringComparison.OrdinalIgnoreCase) ? "warn" : "bad"; - return new Check("Budgets", worst.Scope + ": " + worst.Warning + " · " + Fmt.Usd(worst.SpentUsd) + " of " + Fmt.UsdTotal(worst.CapUsd), tone, "Open budgets", "budgets"); + if (worst is null) return new Check("Budgets", "No warning", "ok", Title: "No budget has reached a warning threshold"); + var tone = string.Equals(worst.Warning, "warn", StringComparison.Ordinal) ? "warn" : "bad"; + return new Check("Budgets", worst.Warning + " · " + Fmt.Percent(worst.SpentUsd, worst.CapUsd), tone, "Open", "budgets", Id: worst.Scope, + Title: worst.Scope + ": " + worst.Warning + " · " + Fmt.Usd(worst.SpentUsd) + " of " + Fmt.UsdTotal(worst.CapUsd)); } var pct = Fmt.PercentClamped(s.Budget.GlobalSpendUsd, s.Budget.GlobalCapUsd); - if (s.Budget.GlobalCapUsd <= 0) return new Check("Budgets", "No global cap reported", "hollow", "Open budgets", "budgets"); + if (s.Budget.GlobalCapUsd <= 0) return new Check("Budgets", "No global cap", "hollow", "Open", "budgets"); + var used = Fmt.Percent(s.Budget.GlobalSpendUsd, s.Budget.GlobalCapUsd) + " of global"; + var title = Fmt.Usd(s.Budget.GlobalSpendUsd) + " of " + Fmt.UsdTotal(s.Budget.GlobalCapUsd); return pct >= 95 - ? new Check("Budgets", "Global cap " + Fmt.Percent(s.Budget.GlobalSpendUsd, s.Budget.GlobalCapUsd) + " used", "bad", "Open budgets", "budgets") + ? new Check("Budgets", used, "bad", "Open", "budgets", Title: title) : pct >= 80 - ? new Check("Budgets", "Global cap " + Fmt.Percent(s.Budget.GlobalSpendUsd, s.Budget.GlobalCapUsd) + " used", "warn", "Open budgets", "budgets") - : new Check("Budgets", "Global cap " + Fmt.Percent(s.Budget.GlobalSpendUsd, s.Budget.GlobalCapUsd) + " used", "ok"); + ? new Check("Budgets", used, "warn", "Open", "budgets", Title: title) + : new Check("Budgets", used, "ok", Title: title); } private static int Pct(int value, int peak) => peak <= 0 ? 0 : (int)Math.Round(value * 100.0 / peak); diff --git a/src/Covenant.Ui/Pages/Playground.razor b/src/Covenant.Ui/Pages/Playground.razor index f138996..a4ae443 100644 --- a/src/Covenant.Ui/Pages/Playground.razor +++ b/src/Covenant.Ui/Pages/Playground.razor @@ -5,7 +5,7 @@ @inject WorkspaceConfig Ws @inject Interop Interop @inject NavigationManager Nav -@implements IDisposable +@implements IAsyncDisposable Playground · Covenant @@ -20,7 +20,9 @@ @if (_present) { -
      + @* Escape is a document-level listener (Interop.WatchEscapeAsync) while presentation mode is active: after Run the + Run button disables itself and focus would otherwise fall to , outside any element handler. *@ +
      Covenant @State.EnvironmentLabel @@ -43,7 +45,7 @@ - + @if (!Pg.Running && Pg.Problem is { } pr) { @pr @@ -51,7 +53,7 @@
    -
    +
    @if (Pg.Selected is { } prun) {
    @@ -192,6 +194,12 @@ else private bool _present; private bool _wasPresent; private bool _focusPending; + private DotNetObjectReference? _self; + private string? _escapeWatch; + private bool _escapeBusy; + // Run disables itself while the request runs: focus moves to Cancel, then to the result region when it finishes. + private bool _focusCancelPending; + private bool _cancelFocused; private string? _appliedScenario; private bool _detailsOpen; private bool _raw; @@ -220,12 +228,63 @@ else protected override async Task OnAfterRenderAsync(bool firstRender) { - if (!_focusPending) return; - _focusPending = false; - try { await Interop.FocusElementAsync(_present ? "pg-present-root" : "pg-present-toggle"); } + await SyncEscapeWatchAsync(); + if (_focusPending) + { + _focusPending = false; + await FocusAsync(_present ? "pg-present-root" : "pg-present-toggle"); + } + if (!_present) + { + _focusCancelPending = false; + _cancelFocused = false; + return; + } + if (_focusCancelPending && Pg.Running) + { + _focusCancelPending = false; + _cancelFocused = true; + await FocusAsync("pg-present-cancel"); + } + else if (_cancelFocused && !Pg.Running) + { + _cancelFocused = false; + await FocusAsync("pg-present-result"); + } + } + + private async Task FocusAsync(string id) + { + try { await Interop.FocusElementAsync(id); } catch (JSException) { /* focus is best effort */ } } + /// Starts the document-level Escape listener while presentation mode is active; disposes it on exit. + private async Task SyncEscapeWatchAsync() + { + if (_escapeBusy) return; + _escapeBusy = true; + try + { + if (_present && _escapeWatch is null) + { + _self ??= DotNetObjectReference.Create(this); + _escapeWatch = await Interop.WatchEscapeAsync(_self, nameof(OnEscapePressed)); + } + else if (!_present && _escapeWatch is { } id) + { + _escapeWatch = null; + await Interop.UnwatchEscapeAsync(id); + } + } + catch (JSException) { /* keyboard exit stays available through the Exit button */ } + finally { _escapeBusy = false; } + } + + /// Called by the document-level Escape listener (presentation mode only). + [JSInvokable] + public Task OnEscapePressed() => InvokeAsync(() => { if (_present) ExitPresent(); }); + /// A scenario in the URL only fills the composer, like clicking the preset — never runs it. private void ApplyScenarioFromRoute() { @@ -237,7 +296,11 @@ else if (!Pg.Running && ScenarioPresets.Find(Scenario) is { } preset) Pg.ApplyPreset(preset); } - private Task RunAsync() => Pg.RunAsync(); + private Task RunAsync() + { + if (_present && Pg.CanRun) _focusCancelPending = true; + return Pg.RunAsync(); + } private void EnterPresent() { @@ -247,11 +310,6 @@ else private void ExitPresent() => Nav.NavigateTo(Nav.GetUriWithQueryParameter("present", (string?)null)); - private void OnPresentKeyDown(KeyboardEventArgs e) - { - if (e.Key == "Escape") ExitPresent(); - } - private void OpenDetails() => _detailsOpen = true; private void CloseDetails() => _detailsOpen = false; @@ -289,10 +347,18 @@ else }); } - public void Dispose() + public async ValueTask DisposeAsync() { State.Changed -= OnChanged; Pg.Changed -= OnChanged; Ws.Changed -= OnChanged; + if (_escapeWatch is { } id) + { + _escapeWatch = null; + try { await Interop.UnwatchEscapeAsync(id); } + catch (JSException) { /* page is going away */ } + catch (JSDisconnectedException) { /* idem */ } + } + _self?.Dispose(); } } diff --git a/src/Covenant.Ui/Pages/Policies.razor b/src/Covenant.Ui/Pages/Policies.razor index f49f4fa..c5d2efc 100644 --- a/src/Covenant.Ui/Pages/Policies.razor +++ b/src/Covenant.Ui/Pages/Policies.razor @@ -7,9 +7,11 @@ Policies · Covenant @* - T08. Routing policies from the versioned configuration (ADR-0013): a coloured route view (classification/profile → - primary → approved fallbacks, Local/Cloud, state, strategy) and a compact editable list (targets, order, pause/resume - route and policy, retry), Preview impact → Save & apply via ConfigEditor. Simulator = real engine, dry run. + T08 + review round 2 (U4). Routing policies from the versioned configuration (ADR-0013): a coloured route view + (classification/profile → primary → approved fallbacks, Local/Cloud, state, strategy) and an editable list: create a + policy, remove one (impact shown first), edit classification/profile applicability, targets, order, pause/resume, retry, + and "Split this policy" (Public → cloud + local fallback; Internal/PII/PHI → local). Every change edits the DRAFT only; + Preview impact → Save & apply via ConfigEditor. Cloud targets are never offered for PII/PHI. Simulator = dry run. *@
    @@ -132,7 +134,91 @@

    Policies

    @(Editing ? "Editing the draft" : "Read-only — choose Edit above") + @if (Editing && _newPolicy is null) + { + + + }
    + @if (Editing && _newPolicy is { } np) + { + var npOptions = PolicyEditing.TargetOptions(np.Classifications, cfg); + var npProblems = PolicyEditing.Problems(np, cfg); +
    +

    New policy (draft)

    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    + Classifications it applies to + @foreach (var c in PolicyEditing.AllClassifications) + { + var cls = c; + + } +
    +
    + Workload profiles (optional — none checked = every profile) + @foreach (var pr in cfg.Profiles) + { + var prof = pr; + + } +
    +
    +
    + + +
    + +
    + @if (np.Targets.Count > 0) + { +
      + @foreach (var (t, ti) in np.Targets.Select((x, n) => (x, n))) + { + var key = t; +
    1. @PolicyRoutes.RoleLabel(ti) @key +
    2. + } +
    + } + @if (np.Classifications.Any(PolicyText.IsSensitive)) + { + @PolicyText.SensitiveNeverCloud Cloud models are not offered. + } + @if (npProblems.Count > 0) + { +
      + @foreach (var pp in npProblems) {
    • @pp
    • } +
    + } +
    + + +
    +
    + }
    Pause policy: @PolicyText.PausedPolicyExplained Pause route: @PolicyText.PausedRouteExplained @@ -156,9 +242,79 @@ + + } + @if (PolicyEditing.CanSplit(pol)) + { + }
    @PolicyText.PausedPolicyExplained + @if (Editing && _removeAsk == pol.Id) + { +
    +
    + Remove policy @pol.Id from the draft? +
      + @foreach (var line in PolicyEditing.RemovalImpact(pol, cfg)) {
    • @line
    • } +
    + The Host's impact preview runs right after; nothing is applied until Save & apply. +
    +
    + + +
    +
    + } + @if (_splitAsk == pol.Id) + { + var plan = PolicyEditing.PlanSplit(pol, cfg); +
    +
    + Split @pol.Id into two draft policies + @if (plan.Problem is { } spProblem) + { + @spProblem + } + else if (plan.PublicPolicy is { } pp && plan.RestrictedPolicy is { } rp) + { +
      +
    • @pp.Id — @PolicyText.Applicability(pp) → @(string.Join(" → ", pp.Targets.Select(PolicyRoutes.Key)))
    • +
    • @rp.Id — @PolicyText.Applicability(rp) → @(string.Join(" → ", rp.Targets.Select(PolicyRoutes.Key))) (local only)
    • + @foreach (var n in plan.Notes) {
    • @n
    • } +
    + @PolicyText.SensitiveNeverCloud The impact preview runs right after; nothing is applied until Save & apply. + } +
    +
    + + +
    +
    + } + @if (Editing) + { +
    + Applies to classifications + @foreach (var c in PolicyEditing.AllClassifications) + { + var cls = c; + + } +
    +
    + Workload profiles (none checked = every profile) + @foreach (var pr in cfg.Profiles) + { + var prof = pr; + + } +
    + @if (_applicabilityError.TryGetValue(pol.Id, out var apErr)) + { + @apErr + } + } @if (Editing) { } @@ -285,7 +441,12 @@ private static readonly string[] DefaultRetryOn = ["connect", "timeout", "429", "5xx"]; private readonly Dictionary _add = new(StringComparer.Ordinal); + private readonly Dictionary _applicabilityError = new(StringComparer.Ordinal); private string? _hybridProblem; + private NewPolicyForm? _newPolicy; + private string _newTargetPick = ""; + private string? _removeAsk; + private string? _splitAsk; private bool Editing => Editor.Editing && Editor.Owner == "policies"; private bool CanStartEdit => Editor.Applied is not null && !Editor.Saving && (!Editor.IsDirty || Editor.Owner == "policies"); @@ -340,6 +501,100 @@ await Editor.ValidateAsync(); } + private void StartCreate(CovenantConfigDto cfg) + { + _newPolicy = new NewPolicyForm { Id = PolicyEditing.UniqueId("policy", cfg), Name = "", Classifications = ["Public"] }; + _newTargetPick = ""; + } + + private void CancelCreate() + { + _newPolicy = null; + _newTargetPick = ""; + } + + private static void ToggleNew(List list, string value, ChangeEventArgs e) + { + list.Remove(value); + if (e.Value is bool b && b) list.Add(value); + } + + private void AddNewTarget(NewPolicyForm f, IReadOnlyList options) + { + var o = options.FirstOrDefault(x => x.Value == _newTargetPick && x.DisabledReason is null); + if (o is not null && !f.Targets.Contains(o.Value)) f.Targets.Add(o.Value); + _newTargetPick = ""; + } + + private async Task AddPolicyAsync(NewPolicyForm f) + { + if (!Editing || Editor.Draft is not { } d) return; + if (PolicyEditing.Add(d, f).Count > 0) return; + _newPolicy = null; + Editor.Touch(); + await Editor.ValidateAsync(); + } + + private void AskRemove(PolicyDto p) + { + _removeAsk = p.Id; + _splitAsk = null; + } + + private async Task RemovePolicyAsync(PolicyDto p) + { + _removeAsk = null; + if (!Editing || Editor.Draft is not { } d || !PolicyEditing.Remove(d, p.Id)) return; + Editor.Touch(); + await Editor.ValidateAsync(); + } + + private void AskSplit(PolicyDto p) + { + // The split edits the draft: start editing here when nobody else holds an unsaved draft. + if (!Editing && !Editor.BeginEdit("policies")) return; + _splitAsk = p.Id; + _removeAsk = null; + } + + private async Task SplitAsync(PolicyDto p) + { + _splitAsk = null; + if (!Editing || Editor.Draft is not { } d) return; + var problem = PolicyEditing.ApplySplit(d, p.Id); + if (problem is not null) + { + _applicabilityError[p.Id] = problem; + return; + } + Editor.Touch(); + await Editor.ValidateAsync(); + } + + private void ToggleClassification(PolicyDto p, string cls, ChangeEventArgs e) + { + var next = p.Classifications.Where(c => c != cls).ToList(); + if (e.Value is bool b && b) next.Add(cls); + ApplyApplicability(p, Editor.Draft is { } d ? PolicyEditing.SetClassifications(p, next, d) : "Not editing."); + } + + private void ToggleProfile(PolicyDto p, string profile, ChangeEventArgs e) + { + var next = p.Profiles.Where(x => x != profile).ToList(); + if (e.Value is bool b && b) next.Add(profile); + ApplyApplicability(p, Editor.Draft is { } d ? PolicyEditing.SetProfiles(p, next, d) : "Not editing."); + } + + private void ApplyApplicability(PolicyDto p, string? error) + { + if (error is null) + { + _applicabilityError.Remove(p.Id); + Editor.Touch(); + } + else _applicabilityError[p.Id] = error; + } + private void TogglePolicyPause(PolicyDto p) { p.Paused = !p.Paused; diff --git a/src/Covenant.Ui/Pages/Requests.razor b/src/Covenant.Ui/Pages/Requests.razor index 8f9287d..4679b65 100644 --- a/src/Covenant.Ui/Pages/Requests.razor +++ b/src/Covenant.Ui/Pages/Requests.razor @@ -13,9 +13,11 @@ Requests · Covenant @* - T08. Audit records of ONE segment (current, or an archived one chosen from GET /admin/audit/segments), loaded in - bounded newest-first pages (GET /admin/requests?limit=&cursor=&segment=) with "Load older". Filters apply only to - what is loaded — the page says so. Deep links (/requests/{id}) fetch the exact record (current segment). The drawer + T08 + review round 2 (U9). Audit records of ONE segment (current, or an archived one chosen from GET + /admin/audit/segments), loaded in bounded newest-first pages (GET /admin/requests?limit=&cursor=&segment=) with "Load + older" following next_cursor (stable: appends never shift a page). The scope label comes from the page's segment + descriptor (segment.is_current/id/label) — never from the first row. 410 cursor_expired (the segment was archived) + stops paging and asks for a reload. Filters apply only to what is loaded — the page says so. Deep links (/requests/{id}) fetch the exact record (current segment). The drawer shows attempts, trace summary, config version and identity, and exports the per-request evidence report (GET /admin/requests/{id}/export — no prompt/response content). *@ @@ -33,7 +35,7 @@ @foreach (var seg in ArchivedSegments) { - + } @(View.SegmentsError ?? (View.Segments is null ? "Loading segments…" : ArchivedSegments.Count == 0 ? "No archived segments." : "Archived segments are read-only.")) @@ -42,6 +44,16 @@ + @if (View.Paging.Expired) + { + + } @o.Explanation Recorded when the request was processed. Today's pause, policy or model health does not change it. + @if (incomplete is not null) + { +
    Stream incomplete — not served@incomplete
    + } + @if (RecordFacts.Truncated(rec)) + { +
    Truncated at the output bound@RecordFacts.TruncatedText(rec) (enforced bound @RecordFacts.EffectiveMaxOutputTokens(rec) tokens).
    + }
    + @if (_exportNote is not null) + { + @_exportNote + }
    @@ -284,8 +309,16 @@
    Selected route
    @mf.Selected
    Attempted
    @mf.Attempted
    Served
    @mf.Served
    +
    Served connection
    @RecordFacts.ServedConnection(rec)
    Destination
    @dest.Text @if (!rec.CacheHit && dest.Text != ModelFacts.NoProviderCall && dest.Text != ModelFacts.NotRecorded) { }
    Streamed
    @(rec.Stream is { } st ? (st ? "Yes" : "No") : "Not recorded")
    +
    Requested max output tokens
    @RecordFacts.RequestedMaxOutputTokens(rec)
    +
    Effective (enforced) max output tokens
    @RecordFacts.EffectiveMaxOutputTokens(rec)
    +
    Truncated
    @RecordFacts.TruncatedText(rec)
    + @if (rec.PartialOutputChars is not null) + { +
    Partial output
    @RecordFacts.PartialOutput(rec)
    + } @{ var lines = AttemptFacts.Lines(rec, Ws.Connections); } @if (lines.Count > 0) @@ -298,7 +331,7 @@ @a.Target @(a.Outcome + (a.ErrorClass is { } ec ? " · " + ec : "")) - @a.Duration · @a.Cost + @AttemptFacts.Detail(a) } @@ -347,7 +380,7 @@

    Audit evidence

    -
    Segment
    @(View.SegmentId is null ? "Current segment" : "Archived segment " + View.SegmentId)@(SegmentChain is { } cv2 ? (cv2 ? " · chain verified" : " · chain verification FAILS") : "")
    +
    Segment
    @(View.Segment is { } ds && IsInLoaded(rec) ? SegmentScope.Label(ds) : "Current segment (exact lookup by id)")@(SegmentChain is { } cv2 && IsInLoaded(rec) ? (cv2 ? " · chain verified" : " · chain verification FAILS") : "")
    Prompt SHA-256
    @Fmt.OrNotRecorded(rec.PromptSha256)
    Prompt length
    @rec.PromptChars chars
    Schema version
    @(rec.SchemaVersion?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "1 (legacy)")
    @@ -389,12 +422,15 @@ private string? _paramId; private bool _exporting; private string? _exportError; + private string? _exportNote; private IReadOnlyList Items => View.Items; private IReadOnlyList Filtered => RequestFilter.Apply(Items, View.Criteria, DateTimeOffset.UtcNow); private IReadOnlyList ArchivedSegments - => View.Segments is { } all ? all.Where(s => !SegmentScope.IsCurrent(s, all)).ToList() : []; + => View.Segments is { } all ? all.Where(s => !SegmentScope.IsCurrent(s)).ToList() : []; + + private bool IsInLoaded(AuditEntryView rec) => View.Items.Any(i => string.Equals(i.Id, rec.Id, StringComparison.Ordinal)); private bool? SegmentChain => View.Segment?.ChainValid; @@ -415,20 +451,16 @@ private bool DrawerOpen => Id is not null; private string DrawerTitle => Id is null ? "Request" : "Request " + Truncate(Id); + /// From the Host's segment descriptor of the loaded pages (segment.is_current/label/id); before the first + /// page arrives, only what was asked for. private string ScopeLabel - { - get - { - if (View.SegmentId is null) - return View.Segment is { } cur ? SegmentScope.Label(new AuditSegmentDto { Id = SegmentScope.CurrentId, FirstUtc = cur.FirstUtc }, true) : "Current segment"; - var listed = View.Segments?.FirstOrDefault(s => s.Id == View.SegmentId) ?? new AuditSegmentDto { Id = View.SegmentId }; - return SegmentScope.Label(listed, false); - } - } + => View.Segment is { } seg + ? SegmentScope.Label(seg) + : View.SegmentId is null ? "Current segment" : "Archived segment " + View.SegmentId + " (loading)"; private string CoverageText => View.Loaded - ? SegmentScope.Coverage(ScopeLabel, View.Items.Count, View.Segment?.Entries, View.NextCursor is not null, View.Criteria.IsActive) + ? SegmentScope.Coverage(ScopeLabel, View.Items.Count, View.Segment?.Entries, View.Paging.CanLoadOlder, View.Criteria.IsActive) : "Filters apply only to the records loaded from the selected segment — never to the whole audit history."; private string CountLabel @@ -531,7 +563,7 @@ private async Task LoadOlderAsync() { - if (View.NextCursor is not { } cursor || _loadingMore) return; + if (!View.Paging.CanLoadOlder || View.NextCursor is not { } cursor || _loadingMore) return; await LoadPageAsync(cursor, first: false); } @@ -550,24 +582,29 @@ _loadError = "Archived segments cannot be browsed on this Host."; return; } - var page = await Api.GetRequestsPageAsync(RequestsViewState.PageSize, cursor, requested); + // A cursor encodes its segment: the next page is requested with the cursor alone (segment= would only be + // re-checked against it by the Host). + var page = await Api.GetRequestsPageAsync(RequestsViewState.PageSize, cursor, cursor is null ? requested : null); if (!string.Equals(View.SegmentId, requested, StringComparison.Ordinal)) return; // selection changed meanwhile - if (requested is not null && !string.Equals(page.Segment.Id, requested, StringComparison.Ordinal)) + if (View.Paging.ApplyPage(page, older: cursor is not null) != PageResult.Accepted) { - _loadError = "The Host did not confirm the requested archived segment (it answered for " - + (page.Segment.Id ?? "an unidentified segment") + "), so nothing is shown rather than mislabelled records."; + _loadError = View.Paging.Problem; return; } - View.Segment = page.Segment; View.AddPage(page.Items); - View.NextCursor = page.Items.Count == 0 ? null : page.NextCursor; - View.Loaded = true; View.LoadedUtc = DateTimeOffset.UtcNow; } catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.Unauthorized) { // ConsoleSession disconnects and routes to /connect. } + catch (ApiException ex) + { + if (!string.Equals(View.SegmentId, requested, StringComparison.Ordinal)) return; + // 410 cursor_expired: the segment was archived/replaced since the cursor was issued → banner + reload. + if (View.Paging.ApplyError((int?)ex.Status, ex.ErrorCode, ex.Message) != PageResult.CursorExpired) + _loadError = View.Paging.Problem; + } catch (Exception ex) { _loadError = ex.Message; @@ -637,8 +674,10 @@ _exportError = null; try { - var json = await Api.GetRequestExportJsonAsync(id, View.SegmentId); + _exportNote = null; + var json = await Api.GetRequestExportJsonAsync(id, View.Segment is { IsCurrent: false, Id: { } sid } ? sid : null); await Interop.DownloadTextAsync("covenant-request-" + id + ".json", "application/json", json); + _exportNote = ExportSummary(json); } catch (ApiException ex) when (ex.Status == System.Net.HttpStatusCode.NotFound) { @@ -658,6 +697,19 @@ } } + /// One line about the downloaded export (the file itself is the server's bytes, unmodified). + private static string? ExportSummary(string json) + { + RequestExportDto? e; + try { e = JsonSerializer.Deserialize(json, UiJsonContext.Default.RequestExportDto); } + catch (JsonException) { return "Downloaded. The export could not be summarised (unexpected shape)."; } + if (e is null) return null; + var integrity = e.Integrity.Status == "verified" ? "integrity verified" : "integrity UNVERIFIED (" + (e.Integrity.ChainFailure ?? "chain broken") + ")"; + return "Downloaded " + e.RequestId + " · " + SegmentScope.Label(e.Segment) + " · " + integrity + + (e.Integrity.Line is { } line ? " · line " + line.ToString(System.Globalization.CultureInfo.InvariantCulture) : "") + + (e.ContentIncluded ? " · CONTAINS content" : " · no prompt/response content"); + } + private void Open(AuditEntryView r) { View.SelectedId = r.Id; diff --git a/src/Covenant.Ui/Services/AdminApi.cs b/src/Covenant.Ui/Services/AdminApi.cs index 095dd5e..3396e47 100644 --- a/src/Covenant.Ui/Services/AdminApi.cs +++ b/src/Covenant.Ui/Services/AdminApi.cs @@ -5,11 +5,12 @@ 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) +/// A failed admin call, with the HTTP status, the server's error code (error, e.g. "cursor_expired") and +/// its 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, string? errorCode = null) : Exception(message) { public HttpStatusCode? Status { get; } = status; + public string? ErrorCode { get; } = errorCode; } /// Status, body text and ETag of a raw admin call (body never contains a secret: config payloads carry @@ -123,10 +124,21 @@ public Task GetConfigVersionAsync(int version, CancellationTo public Task SimulateAsync(SimulateRequestDto body, CancellationToken ct = default) => PostAsync("/admin/policies/simulate", body, UiJsonContext.Default.SimulateRequestDto, UiJsonContext.Default.SimulateResponseDto, ct); - /// GET /admin/budgets/{id}/requests as raw JSON (parsed leniently by Logic/BudgetRequests). - public Task GetBudgetRequestsJsonAsync(string budgetId, int limit = 100, CancellationToken ct = default) - => GetTextAsync("/admin/budgets/" + Uri.EscapeDataString(budgetId) + "/requests?limit=" - + limit.ToString(System.Globalization.CultureInfo.InvariantCulture), ct); + /// GET /admin/budgets/{id}/requests — settled contributions of the budget's scope in its current period. + public Task GetBudgetRequestsAsync(string budgetId, int limit = 100, CancellationToken ct = default) + => GetAsync("/admin/budgets/" + Uri.EscapeDataString(budgetId) + "/requests?limit=" + + limit.ToString(System.Globalization.CultureInfo.InvariantCulture), UiJsonContext.Default.BudgetRequestsDto, ct); + + /// GET /admin/playground/submissions/{client_request_id} (review round 2, B7). Returns the HTTP status and, + /// on 200, the submission (request id + running|completed). 404 = not registered yet / expired. A 401 raises + /// like every admin call. Transport failures throw. + public async Task<(int Status, PlaygroundSubmissionDto? Submission)> GetPlaygroundSubmissionAsync(string clientRequestId, CancellationToken ct = default) + { + var raw = await SendRawAsync(HttpMethod.Get, "/admin/playground/submissions/" + Uri.EscapeDataString(clientRequestId), null, null, ct); + if (raw.Status != 200) return (raw.Status, null); + try { return (raw.Status, JsonSerializer.Deserialize(raw.Body, UiJsonContext.Default.PlaygroundSubmissionDto)); } + catch (JsonException) { return (raw.Status, null); } + } /// GET /admin/audit/segments — the current segment plus archived siblings (ids only). public Task> GetSegmentsAsync(CancellationToken ct = default) @@ -249,12 +261,14 @@ private async Task EnsureSuccessAsync(HttpResponseMessage response, Cancellation } string? reason = null; + string? code = null; try { var text = await response.Content.ReadAsStringAsync(ct); if (text.Length > 0) { var err = JsonSerializer.Deserialize(text, UiJsonContext.Default.ErrorResponse); + code = err?.Error; reason = err?.Reason ?? err?.Error; if (err?.Error == "not_found" && err.Scanned is { } scanned) reason = $"not found (scanned {scanned} records)"; @@ -263,6 +277,6 @@ private async Task EnsureSuccessAsync(HttpResponseMessage response, Cancellation 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}"); + reason is { Length: > 0 } ? $"{(int)response.StatusCode}: {reason}" : $"HTTP {(int)response.StatusCode} {response.ReasonPhrase}", code); } } diff --git a/src/Covenant.Ui/Services/Interop.cs b/src/Covenant.Ui/Services/Interop.cs index 60f0dc1..955f1ce 100644 --- a/src/Covenant.Ui/Services/Interop.cs +++ b/src/Covenant.Ui/Services/Interop.cs @@ -25,6 +25,13 @@ public sealed class Interop(IJSRuntime js) public ValueTask TrapFocusAsync(string containerId) => js.InvokeVoidAsync(Prefix + "trapFocus", containerId); public ValueTask ReleaseFocusAsync(string containerId) => js.InvokeVoidAsync(Prefix + "releaseFocus", containerId); + /// Document-level Escape listener (presentation mode): calls on + /// . Returns a watch id for . + public ValueTask WatchEscapeAsync(DotNetObjectReference target, string method) where T : class + => js.InvokeAsync(Prefix + "watchEscape", target, method); + + public ValueTask UnwatchEscapeAsync(string watchId) => js.InvokeVoidAsync(Prefix + "unwatchEscape", watchId); + /// Copies text the operator explicitly chose to copy (a request id or the response shown on screen — /// never a credential) to the clipboard. Returns false if the browser refused. public ValueTask CopyTextAsync(string text) => js.InvokeAsync(Prefix + "copyText", text); diff --git a/src/Covenant.Ui/Services/PlaygroundState.cs b/src/Covenant.Ui/Services/PlaygroundState.cs index 177923c..6b2b881 100644 --- a/src/Covenant.Ui/Services/PlaygroundState.cs +++ b/src/Covenant.Ui/Services/PlaygroundState.cs @@ -1,6 +1,7 @@ using System.Diagnostics; using System.Text; using Covenant.Ui.Logic; +using Covenant.Ui.Models; namespace Covenant.Ui.Services; @@ -14,8 +15,11 @@ public sealed class PlaygroundRun(RequestSnapshot snapshot) public bool InFlight { get; internal set; } = true; public InferenceResult? Result { get; internal set; } public EvidenceStatus Evidence { get; internal set; } = EvidenceStatus.Idle; - /// Request id as soon as it is known (streaming: at the response headers). + /// Request id as soon as it is known: from GET /admin/playground/submissions/{client_request_id} while the + /// request is still running (review round 2, B7), or from the response as a backstop. public string? RequestId { get; internal set; } + /// Locates the request id of this run before the first response byte (polled every 250 ms). + public SubmissionPoll Submission { get; } = new(snapshot.ClientRequestId); /// Elapsed client wall time while in flight, final once done. public Stopwatch Clock { get; } = Stopwatch.StartNew(); @@ -56,6 +60,7 @@ public sealed class PlaygroundState : IDisposable public const int MaxHistory = 30; private readonly AppState _state; + private readonly AdminApi _admin; private readonly ConsoleInferenceApi _inference; private readonly EvidenceTracker _evidence; private readonly CatalogState _catalog; @@ -65,10 +70,11 @@ public sealed class PlaygroundState : IDisposable private CancellationTokenSource? _runCts; private int _sequence; - public PlaygroundState(AppState state, ConsoleInferenceApi inference, EvidenceTracker evidence, CatalogState catalog, + public PlaygroundState(AppState state, AdminApi admin, ConsoleInferenceApi inference, EvidenceTracker evidence, CatalogState catalog, TraceClient traces, WorkspaceConfig workspace) { _state = state; + _admin = admin; _inference = inference; _evidence = evidence; _catalog = catalog; @@ -163,15 +169,24 @@ public async Task RunAsync() Selected = run; var cts = new CancellationTokenSource(); _runCts = cts; + run.TraceState = TraceFeedState.Locating; Notify(); + // Start the POST, then — concurrently — locate its request id via the submission lookup so the live trace + // (provider "running" while it waits) is followed before the first response byte (review round 2, B7). + var bg = run.Background!.Token; + using var pollCts = CancellationTokenSource.CreateLinkedTokenSource(bg); InferenceResult result; try { - result = await _inference.SendAsync(snapshot, + var send = _inference.SendAsync(snapshot, delta => { run.Append(delta); Notify(); }, - id => { run.RequestId = id; StartTrace(run); Notify(); }, + id => OnResponseRequestId(run, id), cts.Token); + var poll = PollSubmissionAsync(run, send, pollCts.Token); + result = await send; + pollCts.Cancel(); + await poll; } finally { @@ -180,7 +195,10 @@ public async Task RunAsync() } run.Clock.Stop(); run.Result = result; + if (run.Submission.OnSendCompleted(result.RequestId) == SubmissionPollAction.Subscribe) + run.RequestId ??= run.Submission.RequestId; run.RequestId ??= result.RequestId; + if (run.TraceState == TraceFeedState.Locating) run.TraceState = TraceFeedState.Idle; run.InFlight = false; Notify(); @@ -220,6 +238,52 @@ public void ClearOutput() Notify(); } + /// Polls GET /admin/playground/submissions/{client_request_id} every 250 ms while the POST runs, until the + /// Host reports the request id (404 = not registered yet), then subscribes to the live trace. Never throws. + private async Task PollSubmissionAsync(PlaygroundRun run, Task send, CancellationToken ct) + { + var poll = run.Submission; + while (poll.ShouldPoll && !ct.IsCancellationRequested && !send.IsCompleted) + { + int? status; + PlaygroundSubmissionDto? body; + try + { + var answer = await _admin.GetPlaygroundSubmissionAsync(poll.ClientRequestId, ct); + status = answer.Status; + body = answer.Submission; + } + catch (OperationCanceledException) { return; } + catch (Exception) { status = null; body = null; } // transient: bounded retry + if (ct.IsCancellationRequested) return; + + var action = poll.OnPollResult(status, body); + if (action == SubmissionPollAction.Subscribe) + { + OnRequestIdKnown(run, poll.RequestId); + return; + } + if (action == SubmissionPollAction.Stop) return; + try { await Task.Delay(SubmissionPoll.Interval, ct); } + catch (OperationCanceledException) { return; } + } + } + + /// Backstop: the response (headers or error body) carried the request id before polling found it. + private void OnResponseRequestId(PlaygroundRun run, string id) + { + if (run.RequestId is not null) return; + OnRequestIdKnown(run, id); + } + + private void OnRequestIdKnown(PlaygroundRun run, string? id) + { + if (string.IsNullOrWhiteSpace(id) || run.RequestId is not null) return; + run.RequestId = id; + StartTrace(run); + Notify(); + } + private static bool IsPreGovernance(InferenceResult r) => (r.HttpStatus == 400 && !string.Equals(r.ErrorCode, "unsupported", StringComparison.Ordinal)) || r.HttpStatus == 401 || r.HttpStatus == 404; diff --git a/src/Covenant.Ui/Services/RequestsViewState.cs b/src/Covenant.Ui/Services/RequestsViewState.cs index 8151851..03627ca 100644 --- a/src/Covenant.Ui/Services/RequestsViewState.cs +++ b/src/Covenant.Ui/Services/RequestsViewState.cs @@ -20,12 +20,16 @@ public RequestsViewState(AppState state) _state.Disconnected += Clear; } + /// Cursor paging of the selected segment (Logic/RequestPaging): requested segment, the Host's segment + /// descriptor, next_cursor and the 410 cursor_expired state. + public RequestPaging Paging { get; } = new(); /// Segment id requested (null = current segment). - public string? SegmentId { get; set; } - public SegmentInfo? Segment { get; set; } + public string? SegmentId => Paging.RequestedSegmentId; + /// The Host's descriptor of the loaded pages (never inferred from a row). + public SegmentInfo? Segment => Paging.Segment; public List Items { get; } = []; - public string? NextCursor { get; set; } - public bool Loaded { get; set; } + public string? NextCursor => Paging.NextCursor; + public bool Loaded => Paging.Loaded; public DateTimeOffset? LoadedUtc { get; set; } public List? Segments { get; set; } @@ -40,15 +44,12 @@ public RequestsViewState(AppState state) /// Starts over for a (possibly different) segment. public void ResetPages(string? segmentId) { - SegmentId = segmentId; - Segment = null; + Paging.Reset(segmentId); Items.Clear(); - NextCursor = null; - Loaded = false; LoadedUtc = null; } - /// Appends a page, de-duplicating by id (a cursor page may overlap after new writes). + /// Appends a page, de-duplicating by id (defensive: stable cursors never overlap). public int AddPage(IEnumerable page) { var seen = new HashSet(Items.Select(i => i.Id), StringComparer.Ordinal); diff --git a/src/Covenant.Ui/Services/RouteHealth.cs b/src/Covenant.Ui/Services/RouteHealth.cs index 661848b..6a1f4ce 100644 --- a/src/Covenant.Ui/Services/RouteHealth.cs +++ b/src/Covenant.Ui/Services/RouteHealth.cs @@ -1,87 +1,64 @@ +using Covenant.Ui.Logic; 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. +/// connections. Built from the server's catalog and status only — never from a client checkbox. public sealed record LocalRouteSummary(LocalRouteState State, string Text, string Tone, DateTimeOffset? LastSuccessUtc, - DateTimeOffset? LastFailureUtc, string? LastError); + DateTimeOffset? LastFailureUtc, string? LastError, string? Target); /// 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) + /// Local route status from (catalog.local.connection_id/health and + /// status.connection_health — the CURRENT runtime connection, review round 2 B11). + public static LocalRouteSummary LocalRoute(CatalogResponse? catalog, StatusReport? status, 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 v = LocalHealth.Derive(catalog, status?.ConnectionHealth); + var target = v.ConnectionId is { Length: > 0 } c ? c + (v.ModelId is { Length: > 0 } m ? "/" + m : "") : null; + var on = target is null ? "" : " (" + target + ")"; + var h = v.Health; + return v.State switch { - 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); + LocalRouteState.Unknown => new(v.State, "Local route: unknown (catalog not loaded)", "hollow", null, null, null, target), + LocalRouteState.NotConfigured => new(v.State, "Local route: not configured", "hollow", null, null, null, target), + LocalRouteState.NotRegistered => new(v.State, "Local route" + on + ": configured but not registered", "bad", null, null, null, target), + LocalRouteState.Degraded => new(v.State, + "Local route" + on + ": degraded (" + (h?.LastSuccessUtc is null ? "never succeeded" : "last success " + Fmt.Ago(h?.LastSuccessUtc, nowUtc)) + ")", + "warn", h?.LastSuccessUtc, h?.LastFailureUtc, h?.LastError, target), + LocalRouteState.Ready => new(v.State, "Local route" + on + ": ready (last success " + Fmt.Ago(h?.LastSuccessUtc, nowUtc) + ")", "ok", + h?.LastSuccessUtc, h?.LastFailureUtc, h?.LastError, target), + _ => new(v.State, "Local route" + on + ": registered, not yet observed", "hollow", null, null, null, target), + }; } - public static bool IsLocalAdapter(string adapter) => string.Equals(adapter, "local", StringComparison.OrdinalIgnoreCase); - - public static IReadOnlyList UnresolvedRoutes(StatusReport? status, CatalogResponse? catalog) + public static IReadOnlyList UnresolvedRoutes(StatusReport? status, CatalogResponse? catalog) { if (status is null || catalog is null) return []; - var registered = new HashSet(StringComparer.OrdinalIgnoreCase); + var registered = new HashSet(StringComparer.Ordinal); foreach (var m in catalog.Models) if (m.Registered) registered.Add(m.Adapter + ":" + m.ModelId); - var unresolved = new List(); + var unresolved = new List(); foreach (var r in status.Routes) if (!registered.Contains(r.Adapter + ":" + r.Model)) unresolved.Add(r); return unresolved; } + /// The catalog's local view is configured but no provider client resolves for it. 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; - } + => status is not null && catalog?.Local is { Configured: true, Registered: false }; - public static bool IsRegistered(RouteView route, CatalogResponse? catalog) + public static bool IsRegistered(Covenant.Ui.Models.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)) + && string.Equals(m.Adapter, route.Adapter, StringComparison.Ordinal) + && string.Equals(m.ModelId, route.Model, StringComparison.Ordinal)) return true; return false; } diff --git a/src/Covenant.Ui/Services/TraceClient.cs b/src/Covenant.Ui/Services/TraceClient.cs index a6f3b51..beaae36 100644 --- a/src/Covenant.Ui/Services/TraceClient.cs +++ b/src/Covenant.Ui/Services/TraceClient.cs @@ -5,8 +5,9 @@ namespace Covenant.Ui.Services; -/// Where a run's trace currently comes from (shown next to the TraceBar). -public enum TraceFeedState { Idle, Connecting, Live, Reconnecting, Snapshot, Complete, Expired, Unavailable } +/// Where a run's trace currently comes from (shown next to the TraceBar). = the run was +/// submitted and the console is asking the Host for its request id (GET /admin/playground/submissions/{id}). +public enum TraceFeedState { Idle, Locating, Connecting, Live, Reconnecting, Snapshot, Complete, Expired, Unavailable } /// Follows one request's real trace (ADR-0013): GET /admin/requests/{id}/trace/stream over the admin /// HttpClient (the token travels in a header; EventSource cannot do that). Replay-then-live; on a dropped diff --git a/src/Covenant.Ui/wwwroot/css/app.css b/src/Covenant.Ui/wwwroot/css/app.css index e77557f..a2cf4fb 100644 --- a/src/Covenant.Ui/wwwroot/css/app.css +++ b/src/Covenant.Ui/wwwroot/css/app.css @@ -400,11 +400,15 @@ details.tech[open] > summary { margin-bottom: 6px; } .ov-top { display: grid; grid-template-columns: minmax(300px, 4fr) minmax(380px, 7fr); gap: 16px; align-items: start; } .ov-top > section { min-width: 0; } .check-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; } -.check { display: grid; grid-template-columns: auto 8.5em minmax(0, 1fr) auto; gap: 8px; align-items: center; padding: 7px 0; border-bottom: 1px solid var(--border); font-size: var(--text-secondary); } +/* Setup checks (review round 2, U5): short status values that never break mid-word; only ids may wrap anywhere. */ +.check { display: grid; grid-template-columns: auto minmax(6.5em, auto) minmax(0, 1fr) auto; gap: 4px 8px; align-items: baseline; padding: 6px 0; border-bottom: 1px solid var(--border); font-size: var(--text-secondary); } .check:last-child { border-bottom: 0; } -.check-name { color: var(--muted); } -.check-value { overflow-wrap: anywhere; } -.check-action { white-space: nowrap; } +.check > .dot { align-self: center; } +.check-name { color: var(--muted); white-space: nowrap; } +.check-value { overflow-wrap: normal; word-break: normal; hyphens: none; min-width: 0; } +.check-status { white-space: nowrap; } +.check-id { display: block; color: var(--muted); font-size: 12px; overflow-wrap: anywhere; word-break: normal; } +.check-action { white-space: nowrap; justify-self: end; } .ov-result { display: flex; flex-direction: column; gap: 8px; border-top: 1px solid var(--border); padding-top: 12px; } .row-main { flex: 1 1 260px; min-width: 0; overflow-wrap: anywhere; } @@ -480,8 +484,9 @@ details.tech[open] > summary { margin-bottom: 6px; } } @media (max-width: 640px) { .composer-grid, .composer-grid.three { grid-template-columns: minmax(0, 1fr); } - .check { grid-template-columns: auto minmax(0, 1fr); } - .check .check-value, .check .check-action { grid-column: 2; } + .check { grid-template-columns: auto minmax(0, 1fr) auto; } + .check .check-value { grid-column: 2 / span 2; } + .check .check-action { grid-column: 3; grid-row: 1; } } @media (max-width: 900px) { @@ -591,3 +596,7 @@ details.panel > summary { cursor: pointer; font-weight: 600; min-height: 32px; d .route-row { grid-template-columns: minmax(0, 1fr); grid-template-areas: "scope" "targets" "meta"; } .route-arrow { display: none; } } + +/* Policies: create-policy form (review round 2, U4). */ +.policy-create { display: flex; flex-direction: column; gap: 10px; border-bottom: 1px solid var(--border); } +.policy-create h3 { margin: 0; font-size: var(--text-body, 14px); } diff --git a/src/Covenant.Ui/wwwroot/js/interop.js b/src/Covenant.Ui/wwwroot/js/interop.js index 3183fbe..3724040 100644 --- a/src/Covenant.Ui/wwwroot/js/interop.js +++ b/src/Covenant.Ui/wwwroot/js/interop.js @@ -20,6 +20,8 @@ try { applyTheme(window.localStorage.getItem(THEME_KEY)); } catch (e) { applyTheme("dark"); } var traps = {}; // containerId -> keydown handler (focus trap for drawers/dialogs) + var escWatchers = {}; // watch id -> document keydown handler (presentation mode Escape) + var escSeq = 0; function focusables(container) { var sel = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'; @@ -88,6 +90,27 @@ delete traps[containerId]; }, + // Presentation mode: Escape anywhere on the page (focus may be on after the Run button disabled itself) + // calls the .NET method. Ignored when a dialog/popover inside the page handles its own Escape. Returns a watch id. + watchEscape: function (dotnetRef, method) { + var id = "esc-" + (++escSeq); + var handler = function (ev) { + if (ev.key !== "Escape" || ev.defaultPrevented) return; + var t = ev.target; + if (t && typeof t.closest === "function" && t.closest('[role="dialog"], .popover')) return; + dotnetRef.invokeMethodAsync(method); + }; + escWatchers[id] = handler; + document.addEventListener("keydown", handler); + return id; + }, + unwatchEscape: function (id) { + var handler = escWatchers[id]; + if (!handler) return; + document.removeEventListener("keydown", handler); + delete escWatchers[id]; + }, + // Copy operator-selected text (a request id or the visible response — never a credential). Resolves true on success. copyText: function (text) { try { diff --git a/tests/Covenant.Tests/ConsoleLogicTests.cs b/tests/Covenant.Tests/ConsoleLogicTests.cs index 38f545b..7eb7ffa 100644 --- a/tests/Covenant.Tests/ConsoleLogicTests.cs +++ b/tests/Covenant.Tests/ConsoleLogicTests.cs @@ -757,8 +757,9 @@ public void Eligible_overrides_follow_policies_profile_baseline_and_mode() config.Mode = "local-only"; Assert.Equal(new[] { "ollama/qwen3:8b" }, ComposerRules.EligibleOverrides(config, "public-tickets", null).Select(o => o.Value)); - config.Mode = "LocalOnly"; // enum-name spelling from an older Host is still understood - Assert.Equal(new[] { "ollama/qwen3:8b" }, ComposerRules.EligibleOverrides(config, "public-tickets", null).Select(o => o.Value)); + // One contract spelling only: an enum-name spelling is not "local-only" (the Host never sends it). + Assert.False(PolicyRoutes.IsLocalOnly("LocalOnly")); + Assert.True(PolicyRoutes.IsLocalOnly("local-only")); } } @@ -964,15 +965,22 @@ public void Unknown_states_and_stages_are_kept_honestly() } [Fact] - public void Audit_summary_fallback_reads_objects_and_compact_strings() + public void Audit_summary_fallback_reads_the_typed_compact_trace() { - var summary = System.Text.Json.JsonDocument.Parse( - "[{\"Stage\":\"auth\",\"State\":\"passed\",\"DurationMs\":1},\"policy:passed:3\",\"provider:failed:900\",\"provider:passed:400\",{\"nonsense\":1}]") - .RootElement.EnumerateArray().Select(e => e.Clone()).ToList(); + // Core AuditTraceStep shape only ({Stage, State, DurationMs, AttemptId?, ReasonCode?}); provider steps are matched + // to Attempts[] by AttemptId. + var summary = new List + { + new() { Stage = "auth", State = "passed", DurationMs = 1 }, + new() { Stage = "policy", State = "passed", DurationMs = 3 }, + new() { Stage = "provider", State = "failed", DurationMs = 900, AttemptId = "a1", ReasonCode = "timeout" }, + new() { Stage = "provider", State = "passed", DurationMs = 400, AttemptId = "a2" }, + new() { Stage = "", State = "passed" }, + }; var attempts = new List { - new() { AttemptId = "a1", ConnectionId = "openai", ModelId = "gpt-x" }, - new() { AttemptId = "a2", ConnectionId = "ollama", ModelId = "qwen" }, + new() { AttemptId = "a1", ConnectionId = "openai", ModelId = "gpt-x", Outcome = "failed" }, + new() { AttemptId = "a2", ConnectionId = "ollama", ModelId = "qwen", Outcome = "served" }, }; var v = TraceModel.FromAuditSummary(summary, attempts, 3)!; Assert.Equal("audit summary", v.Source); @@ -983,6 +991,8 @@ public void Audit_summary_fallback_reads_objects_and_compact_strings() Assert.Equal(2, p.Attempts.Count); Assert.Equal("openai/gpt-x", p.Attempts[0].Target); Assert.Equal(TraceStepState.Failed, p.Attempts[0].State); + Assert.Equal("timeout", p.Attempts[0].ReasonCode); + Assert.Equal("ollama/qwen", p.Attempts[1].Target); Assert.Equal(TraceStepState.Passed, p.State); Assert.Null(TraceModel.FromAuditSummary(null)); Assert.Null(TraceModel.FromAuditSummary([])); @@ -1013,12 +1023,13 @@ public sealed class ShellStatusTests { [Theory] [InlineData("local-only", "Local-only", "local")] - [InlineData("LocalOnly", "Local-only", "local")] [InlineData("hybrid", "Hybrid", "hybrid")] - [InlineData("Hybrid", "Hybrid", "hybrid")] [InlineData("legacy-cloud", "Legacy cloud", "legacy")] - [InlineData("LegacyCloud", "Legacy cloud", "legacy")] - [InlineData("cloud", "Legacy cloud", "legacy")] + // One explicit contract (docs/ui-api-contract.md "Wire spellings"): other spellings are not guessed. + [InlineData("LocalOnly", "Mode not reported", "unknown")] + [InlineData("Hybrid", "Mode not reported", "unknown")] + [InlineData("LegacyCloud", "Mode not reported", "unknown")] + [InlineData("cloud", "Mode not reported", "unknown")] [InlineData(null, "Mode not reported", "unknown")] [InlineData("", "Mode not reported", "unknown")] [InlineData("quantum", "Mode not reported", "unknown")] @@ -1626,34 +1637,40 @@ public void Hybrid_defaults_build_a_restrictive_draft_and_need_a_local_model() public sealed class SegmentScopeTests { [Fact] - public void Current_segment_is_explicit_then_by_id_then_first() + public void Current_segment_is_the_hosts_explicit_flag_only() { - var a = new AuditSegmentDto { Id = "seg-2", Current = true }; - var b = new AuditSegmentDto { Id = "current" }; - var c = new AuditSegmentDto { Id = "2026-10-01" }; - Assert.True(SegmentScope.IsCurrent(a)); - Assert.True(SegmentScope.IsCurrent(b)); - Assert.False(SegmentScope.IsCurrent(new AuditSegmentDto { Id = "x", Current = false })); - var unflagged = new List { new() { Id = "live" }, c }; - Assert.True(SegmentScope.IsCurrent(unflagged[0], unflagged)); - Assert.False(SegmentScope.IsCurrent(c, unflagged)); - Assert.False(SegmentScope.IsCurrent(c, [b, c])); + Assert.True(SegmentScope.IsCurrent(new AuditSegmentDto { Id = "seg-2", Current = true })); + // Never inferred from the id or from the list order. + Assert.False(SegmentScope.IsCurrent(new AuditSegmentDto { Id = "current", Current = false })); + Assert.False(SegmentScope.IsCurrent(new AuditSegmentDto { Id = "a-0123456789abcdef" })); + } + + [Fact] + public void Page_scope_comes_from_the_segment_descriptor() + { + var first = new DateTimeOffset(2026, 10, 16, 9, 0, 0, TimeSpan.Zero); + Assert.Equal("Current segment · since 2026-10-16 09:00:00 UTC", + SegmentScope.Label(new SegmentInfo { Id = "current", Label = "Current segment", IsCurrent = true, FirstUtc = first })); + Assert.Equal("Archived segment Archived 2026-10-01 09:00:00 UTC · read-only", + SegmentScope.Label(new SegmentInfo { Id = "a-0123456789abcdef", Label = "Archived 2026-10-01 09:00:00 UTC", IsCurrent = false })); + // An archived page whose id happens to be "current" is still archived: the flag decides. + Assert.StartsWith("Archived segment", SegmentScope.Label(new SegmentInfo { Id = "current", IsCurrent = false }), StringComparison.Ordinal); } [Fact] public void Labels_say_which_segment_and_that_filters_cover_only_loaded_records() { var first = new DateTimeOffset(2026, 10, 16, 9, 0, 0, TimeSpan.Zero); - Assert.Equal("Current segment · since 2026-10-16 09:00:00 UTC", SegmentScope.Label(new AuditSegmentDto { Id = "current", FirstUtc = first }, true)); - Assert.Equal("Archived segment Oct 1 · read-only", SegmentScope.Label(new AuditSegmentDto { Id = "a1", Label = "Oct 1" }, false)); - Assert.Equal("Archived · a1 (1,200 records)", SegmentScope.Option(new AuditSegmentDto { Id = "a1", Entries = 1200 }, false)); + Assert.Equal("Current segment · since 2026-10-16 09:00:00 UTC", SegmentScope.Label(new AuditSegmentDto { Id = "current", Current = true, FirstUtc = first })); + Assert.Equal("Archived segment Oct 1 · read-only", SegmentScope.Label(new AuditSegmentDto { Id = "a1", Label = "Oct 1" })); + Assert.Equal("Archived · a1 (1,200 records)", SegmentScope.Option(new AuditSegmentDto { Id = "a1", Entries = 1200 })); var cov = SegmentScope.Coverage("Current segment", 200, 1500, moreAvailable: true, filtersActive: true); Assert.Contains("200 of 1,500 records loaded", cov, StringComparison.Ordinal); Assert.Contains("Load older", cov, StringComparison.Ordinal); Assert.Contains("only to these loaded records", cov, StringComparison.Ordinal); Assert.DoesNotContain("all history", cov, StringComparison.OrdinalIgnoreCase); - Assert.Contains("not reachable", SegmentScope.Coverage("Current segment", 200, 1500, moreAvailable: false, filtersActive: false), StringComparison.Ordinal); + Assert.DoesNotContain("Load older", SegmentScope.Coverage("Current segment", 200, 1500, moreAvailable: false, filtersActive: false), StringComparison.Ordinal); } [Theory] @@ -1710,25 +1727,6 @@ public void Local_only_zero_spend_is_detected_for_the_explanatory_empty_state() Assert.False(BudgetText.NoSpendAnywhere([new BudgetStateDto { Id = "g", CapUsd = 10m, ReservedUsd = 0.0001m }])); Assert.False(BudgetText.NoSpendAnywhere(null)); } - - [Fact] - public void Contributing_requests_parse_leniently_and_unknown_shapes_are_null() - { - var arr = BudgetRequests.Parse("[{\"request_id\":\"req_1\",\"attempt_id\":\"a1\",\"amount_usd\":0.000184,\"ts_utc\":\"2026-10-16T09:00:00Z\"},{\"nope\":1}]"); - var one = Assert.Single(arr!); - Assert.Equal("req_1", one.RequestId); - Assert.Equal(0.000184m, one.AmountUsd); - Assert.Equal("a1", one.AttemptId); - Assert.NotNull(one.TimestampUtc); - - var wrapped = BudgetRequests.Parse("{\"items\":[{\"id\":\"req_2\",\"settled_usd\":1.5}]}"); - Assert.Equal("req_2", Assert.Single(wrapped!).RequestId); - Assert.Equal(1.5m, wrapped![0].AmountUsd); - - Assert.Null(BudgetRequests.Parse("{\"something\":true}")); - Assert.Null(BudgetRequests.Parse("not json")); - Assert.Null(BudgetRequests.Parse("")); - } } public sealed class ConnectionFormTests @@ -1919,3 +1917,451 @@ public void Application_filter_matches_v3_application_id_only() Assert.Equal(new[] { "demo-app" }, RequestFilter.Applications([a, legacy])); } } + +// ---- Review round 2 (UI): pure logic behind U2/U4/U6/U7/U8/U9/U10 ---- + +public sealed class SubmissionPollTests +{ + private const string Client = "0123456789abcdef0123456789abcdef"; + private const string Req = "req_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + + private static PlaygroundSubmissionDto Found(string state = "running") => new() { ClientRequestId = Client, RequestId = Req, State = state }; + + [Fact] + public void Not_registered_yet_polls_again_then_subscribes_exactly_once() + { + var p = new SubmissionPoll(Client); + Assert.True(p.ShouldPoll); + Assert.Equal(SubmissionPollAction.PollAgain, p.OnPollResult(404, null)); + Assert.Equal(SubmissionPollAction.PollAgain, p.OnPollResult(null, null)); // transport hiccup: bounded retry + Assert.Equal(SubmissionPollAction.Subscribe, p.OnPollResult(200, Found())); + Assert.Equal(Req, p.RequestId); + Assert.Equal("submission lookup", p.Source); + Assert.False(p.ShouldPoll); + Assert.Equal(3, p.Polls); + + // Later answers and the finished POST never start a second subscription. + Assert.Equal(SubmissionPollAction.Stop, p.OnPollResult(200, Found("completed"))); + Assert.Equal(SubmissionPollAction.Stop, p.OnSendCompleted(Req)); + Assert.True(p.Stopped); + } + + [Fact] + public void A_body_for_another_submission_is_not_accepted() + { + var p = new SubmissionPoll(Client); + var other = new PlaygroundSubmissionDto { ClientRequestId = "ffff", RequestId = "req_x", State = "running" }; + Assert.Equal(SubmissionPollAction.PollAgain, p.OnPollResult(200, other)); + Assert.Null(p.RequestId); + } + + [Fact] + public void Response_id_is_the_backstop_when_polling_found_nothing() + { + var p = new SubmissionPoll(Client); + Assert.Equal(SubmissionPollAction.PollAgain, p.OnPollResult(404, null)); + Assert.Equal(SubmissionPollAction.Subscribe, p.OnSendCompleted(Req)); + Assert.Equal("response", p.Source); + Assert.False(p.ShouldPoll); + + var none = new SubmissionPoll(Client); + Assert.Equal(SubmissionPollAction.Stop, none.OnSendCompleted(null)); // 400 before governance: no id, no trace + Assert.Null(none.RequestId); + } + + [Fact] + public void Unauthorized_and_the_bound_stop_polling() + { + var p = new SubmissionPoll(Client); + Assert.Equal(SubmissionPollAction.Stop, p.OnPollResult(401, null)); + Assert.False(p.ShouldPoll); + + var b = new SubmissionPoll(Client); + for (int i = 1; i < SubmissionPoll.MaxPolls; i++) Assert.Equal(SubmissionPollAction.PollAgain, b.OnPollResult(404, null)); + Assert.Equal(SubmissionPollAction.Stop, b.OnPollResult(404, null)); + Assert.False(b.ShouldPoll); + Assert.Equal(TimeSpan.FromMilliseconds(250), SubmissionPoll.Interval); + } + + [Fact] + public void Client_request_ids_are_guid_n() + { + var id = RequestSnapshot.NewClientRequestId(); + Assert.Matches("^[0-9a-f]{32}$", id); + } +} + +public sealed class LiveTraceStartTests +{ + private static TraceEventDto E(long seq, string stage, string state, string? attempt = null, double? ms = null) + => new() { Seq = seq, Stage = stage, State = state, AttemptId = attempt, DurationMs = ms, RequestId = "req_1" }; + + [Fact] + public void Provider_shows_running_while_waiting_with_its_output_bounds() + { + var acc = new TraceAccumulator(); + acc.AddRange([E(1, "auth", "passed", ms: 0.4), E(2, "budget", "passed", ms: 0.2), + new TraceEventDto { Seq = 3, Stage = "provider", State = "running", AttemptId = "att_1", Target = "ollama/qwen", + RequestedMaxOutputTokens = 256, EffectiveMaxOutputTokens = 64 }]); + var v = acc.View(); + var provider = v.Steps.Single(s => s.Stage == "provider"); + Assert.Equal(TraceStepState.Running, provider.State); + Assert.Null(provider.DurationMs); // no invented timing while it runs + var a = Assert.Single(provider.Attempts); + Assert.Equal(256, a.RequestedMaxOutputTokens); + Assert.Equal(64, a.EffectiveMaxOutputTokens); + Assert.True(v.HasEvents); + Assert.Equal(TraceStepState.Pending, v.Steps.Single(s => s.Stage == "attribution").State); + } + + [Fact] + public void Unknown_state_spellings_are_not_guessed() + => Assert.Equal(TraceStepState.NotReported, TraceModel.ParseState("canceled")); +} + +public sealed class PolicyEditingTests +{ + private static CovenantConfigDto AllClasses() + { + var cfg = Cfg.Hybrid(); + cfg.Mode = "legacy-cloud"; + cfg.Profiles = [new WorkloadProfileDto { Id = "internal", Name = "Internal", Baseline = "Internal" }]; + cfg.Policies = + [ + new PolicyDto + { + Id = "legacy", Name = "Imported", Enabled = true, Classifications = ["Public", "Internal", "Pii", "Phi"], Strategy = "fixed", + Targets = [new PolicyTargetDto { ConnectionId = "openai", ModelId = "gpt-4o-mini" }, new PolicyTargetDto { ConnectionId = "ollama", ModelId = "qwen2.5-coder:7b" }], + Retry = new RetrySettingsDto { MaxAttempts = 2, DeadlineMs = 60_000, On = ["timeout"] }, + }, + ]; + return cfg; + } + + [Fact] + public void Split_makes_public_cloud_with_local_fallback_and_never_cloud_for_sensitive() + { + var cfg = AllClasses(); + Assert.True(PolicyEditing.CanSplit(cfg.Policies[0])); + Assert.Null(PolicyEditing.ApplySplit(cfg, "legacy")); + Assert.Equal(2, cfg.Policies.Count); + + var pub = cfg.Policies[0]; + Assert.Equal(new[] { "Public" }, pub.Classifications); + Assert.Equal(new[] { "openai/gpt-4o-mini", "ollama/qwen2.5-coder:7b" }, pub.Targets.Select(PolicyRoutes.Key)); + Assert.Equal(60_000, pub.Retry!.DeadlineMs); + + var restricted = cfg.Policies[1]; + Assert.Equal(new[] { "Internal", "Pii", "Phi" }, restricted.Classifications); + Assert.Equal(new[] { "ollama/qwen2.5-coder:7b" }, restricted.Targets.Select(PolicyRoutes.Key)); + Assert.DoesNotContain(restricted.Targets, t => t.ConnectionId == "openai"); + Assert.All(PolicyRoutes.Targets(restricted, cfg), t => Assert.Equal("Local", t.Boundary)); + Assert.NotEqual(pub.Id, restricted.Id); + Assert.DoesNotContain(cfg.Policies, p => p.Id == "legacy"); + } + + [Fact] + public void Split_without_a_cloud_target_proposes_a_priced_cloud_model_and_local_only_mode_keeps_public_local() + { + var cfg = AllClasses(); + cfg.Policies[0].Targets = [new PolicyTargetDto { ConnectionId = "ollama", ModelId = "qwen2.5-coder:7b" }]; + var plan = PolicyEditing.PlanSplit(cfg.Policies[0], cfg); + Assert.Null(plan.Problem); + Assert.Equal("openai/gpt-4o-mini", PolicyRoutes.Key(plan.PublicPolicy!.Targets[0])); + Assert.Contains(plan.Notes, n => n.Contains("first enabled, priced cloud model", StringComparison.Ordinal)); + + cfg.Mode = "local-only"; + var local = PolicyEditing.PlanSplit(cfg.Policies[0], cfg); + Assert.Equal(new[] { "ollama/qwen2.5-coder:7b" }, local.PublicPolicy!.Targets.Select(PolicyRoutes.Key)); + Assert.DoesNotContain(local.RestrictedPolicy!.Targets, t => t.ConnectionId == "openai"); + } + + [Fact] + public void Split_needs_a_local_model_and_a_mixed_policy() + { + var cfg = AllClasses(); + cfg.Connections.RemoveAll(c => c.Boundary == "Local"); + var before = ConfigCopy.Canonical(cfg); + Assert.NotNull(PolicyEditing.ApplySplit(cfg, "legacy")); + Assert.Equal(before, ConfigCopy.Canonical(cfg)); // untouched + + Assert.False(PolicyEditing.CanSplit(Cfg.Hybrid().Policies[0])); // Public only + } + + [Fact] + public void Create_policy_never_accepts_a_cloud_target_for_pii_or_phi() + { + var cfg = Cfg.Hybrid(); + var form = new NewPolicyForm { Id = "pii-cloud", Name = "PII", Classifications = ["Pii"], Targets = ["openai/gpt-4o-mini"] }; + var problems = PolicyEditing.Problems(form, cfg); + Assert.Contains(problems, p => p.Contains(PolicyText.SensitiveNeverCloud, StringComparison.Ordinal)); + Assert.Contains(PolicyEditing.TargetOptions(["Pii"], cfg), o => o.Value == "openai/gpt-4o-mini" && o.DisabledReason is not null); + Assert.NotEmpty(PolicyEditing.Add(cfg, form)); + Assert.Equal(3, cfg.Policies.Count); + + var ok = new NewPolicyForm { Id = "public-2", Name = "Public tickets", Classifications = ["Public"], Profiles = [], Targets = ["openai/gpt-4o-mini", "ollama/qwen2.5-coder:7b"] }; + Assert.Empty(PolicyEditing.Add(cfg, ok)); + var added = cfg.Policies[^1]; + Assert.Equal("public-2", added.Id); + Assert.True(added.Enabled); + Assert.Equal("fixed", added.Strategy); + Assert.Equal(new[] { "openai/gpt-4o-mini", "ollama/qwen2.5-coder:7b" }, added.Targets.Select(PolicyRoutes.Key)); + + Assert.Contains(PolicyEditing.Problems(new NewPolicyForm { Id = "public-2", Name = "x", Classifications = ["Public"], Targets = ["ollama/qwen2.5-coder:7b"] }, cfg), + p => p.Contains("already exists", StringComparison.Ordinal)); + Assert.Contains(PolicyEditing.Problems(new NewPolicyForm { Id = "p", Name = "x", Classifications = ["Public"], Profiles = ["nope"], Targets = ["ollama/qwen2.5-coder:7b"] }, cfg), + p => p.Contains("does not exist", StringComparison.Ordinal)); + } + + [Fact] + public void Applicability_edits_refuse_sensitive_classes_behind_a_cloud_target() + { + var cfg = Cfg.Hybrid(); + var pub = cfg.Policies[0]; // openai first + Assert.NotNull(PolicyEditing.SetClassifications(pub, ["Public", "Pii"], cfg)); + Assert.Equal(new[] { "Public" }, pub.Classifications); + Assert.NotNull(PolicyEditing.SetClassifications(pub, [], cfg)); + Assert.Null(PolicyEditing.SetClassifications(cfg.Policies[1], ["Internal", "Public"], cfg)); + Assert.Equal(new[] { "Public", "Internal" }, cfg.Policies[1].Classifications); // contract order + + cfg.Profiles = [new WorkloadProfileDto { Id = "internal", Name = "Internal", Baseline = "Internal" }]; + Assert.Null(PolicyEditing.SetProfiles(cfg.Policies[1], ["internal"], cfg)); + Assert.Equal(new[] { "internal" }, cfg.Policies[1].Profiles); + Assert.NotNull(PolicyEditing.SetProfiles(cfg.Policies[1], ["ghost"], cfg)); + } + + [Fact] + public void Removing_the_only_policy_for_a_class_says_it_will_be_refused() + { + var cfg = Cfg.Hybrid(); + var lines = PolicyEditing.RemovalImpact(cfg.Policies[2], cfg); + Assert.Equal(2, lines.Count); + Assert.All(lines, l => Assert.Contains("REFUSED", l, StringComparison.Ordinal)); + Assert.True(PolicyEditing.Remove(cfg, "sensitive")); + Assert.Equal(new[] { "public", "internal" }, cfg.Policies.Select(p => p.Id)); + Assert.False(PolicyEditing.Remove(cfg, "sensitive")); + } +} + +public sealed class RoundTwoCostAndFactsTests +{ + [Fact] + public void Mixed_cost_basis_is_labelled_as_including_estimates() + { + var r = Rec.V2(costBasis: "mixed", cost: 0.0021m); + Assert.Equal("≈ $0.0021 · Mixed (includes estimates)", CostText.Cost(r)); + Assert.Equal("≈ $0.0021 mixed", CostText.CostShort(r)); + Assert.Contains("includes estimates", CostText.BasisDescription("mixed"), StringComparison.Ordinal); + Assert.Equal("≈ $0.0021 Mixed (includes estimates)", CostText.BasisCost("mixed", 0.0021m)); + Assert.DoesNotContain("reported", CostText.Cost(r), StringComparison.Ordinal); + } + + [Fact] + public void Requested_and_effective_output_bounds_are_labelled_separately() + { + var r = Rec.V2(); + r.RequestedMaxOutputTokens = 256; + r.EffectiveMaxOutputTokens = 64; + r.ServedConnectionId = "ollama"; + Assert.Equal("256", RecordFacts.RequestedMaxOutputTokens(r)); + Assert.Equal("64", RecordFacts.EffectiveMaxOutputTokens(r)); + Assert.Equal("Requested 256 · enforced 64", RecordFacts.BoundsLine(r)); + Assert.Equal("ollama", RecordFacts.ServedConnection(r)); + + var none = Rec.V2(); + none.EffectiveMaxOutputTokens = 1024; + Assert.StartsWith("None requested", RecordFacts.RequestedMaxOutputTokens(none), StringComparison.Ordinal); + + var old = Rec.V2(); // older record: neither field + Assert.Equal("Not recorded", RecordFacts.RequestedMaxOutputTokens(old)); + Assert.Equal("Not recorded", RecordFacts.EffectiveMaxOutputTokens(old)); + Assert.Equal("Not recorded", RecordFacts.ServedConnection(old)); + Assert.Equal("Not recorded", RecordFacts.TruncatedText(old)); + } + + [Fact] + public void Truncation_and_incomplete_streams_are_stated_clearly() + { + var t = Rec.V2(); + t.EffectiveMaxOutputTokens = 64; + t.Attempts = [new AuditAttemptView { AttemptId = "att_1", ConnectionId = "ollama", ModelId = "qwen", Outcome = "served", EffectiveMaxOutputTokens = 64, Truncated = true }]; + Assert.True(RecordFacts.Truncated(t)); + Assert.StartsWith("Yes", RecordFacts.TruncatedText(t), StringComparison.Ordinal); + var line = Assert.Single(AttemptFacts.Lines(t)); + Assert.True(line.Truncated); + Assert.Equal(64, line.EffectiveMaxOutputTokens); + Assert.EndsWith("· bound 64 · truncated (length)", AttemptFacts.Detail(line), StringComparison.Ordinal); + + var inc = Rec.Upstream(); + inc.PartialOutputChars = 120; + inc.Attempts = [new AuditAttemptView { AttemptId = "att_1", ConnectionId = "openai", ModelId = "gpt-x", Outcome = "failed", ErrorClass = "incomplete_stream", EffectiveMaxOutputTokens = 256 }]; + Assert.True(RecordFacts.IsIncompleteStream(inc)); + var text = RecordFacts.IncompleteStreamText(inc)!; + Assert.Contains("NOT served", text, StringComparison.Ordinal); + Assert.Contains("120 characters", text, StringComparison.Ordinal); + Assert.Equal("256 (last attempt — not served)", RecordFacts.EffectiveMaxOutputTokens(inc)); + Assert.Null(RecordFacts.IncompleteStreamText(t)); + } + + [Fact] + public void Attempt_success_is_the_contract_word_served_only() + { + Assert.True(AttemptFacts.IsSuccess(new AuditAttemptView { Outcome = "served" })); + Assert.False(AttemptFacts.IsSuccess(new AuditAttemptView { Outcome = "ok" })); + Assert.False(AttemptFacts.IsSuccess(new AuditAttemptView { Outcome = "succeeded" })); + } + + [Theory] + [InlineData("Ollama")] + [InlineData("OpenAi")] + [InlineData("Anthropic")] + [InlineData("OpenAiCompatible")] + public void New_connections_start_with_a_120_second_timeout(string kind) + { + var f = kind == "Ollama" ? ConnectionForm.NewOllama([]) : ConnectionForm.NewCloud(kind, []); + Assert.Equal(120, f.TimeoutSeconds); + Assert.Equal(ConnectionForm.DefaultTimeoutSeconds, f.TimeoutSeconds); + Assert.Equal(120, f.ToConnection().TimeoutSeconds); + Assert.DoesNotContain(f.Problems([], null), p => p.Contains("Timeout", StringComparison.Ordinal)); + } +} + +public sealed class RequestPagingTests +{ + private static RequestsResponse Page(string id, bool current, string? cursor, int items = 2) + => new() + { + Segment = new SegmentInfo { Id = id, Label = current ? "Current segment" : "Archived 2026-10-01 09:00:00 UTC", IsCurrent = current, Entries = 10, ChainValid = true }, + Items = Enumerable.Range(0, items).Select(i => Rec.V2(id: "req_" + id + i.ToString(System.Globalization.CultureInfo.InvariantCulture))).ToList(), + NextCursor = cursor, + }; + + [Fact] + public void Current_pages_follow_next_cursor_until_the_last_page() + { + var p = new RequestPaging(); + p.Reset(null); + Assert.False(p.CanLoadOlder); + Assert.Equal(PageResult.Accepted, p.ApplyPage(Page("current", true, "c2-a"), older: false)); + Assert.True(p.CanLoadOlder); + Assert.Equal("c2-a", p.NextCursor); + Assert.Equal("Current segment", p.Segment!.Label); + Assert.Equal(PageResult.Accepted, p.ApplyPage(Page("current", true, null), older: true)); + Assert.False(p.CanLoadOlder); + Assert.True(p.Loaded); + } + + [Fact] + public void Scope_is_the_descriptor_never_the_request() + { + var p = new RequestPaging(); + p.Reset(null); + // Asked for the current segment, but the Host says this page is archived: refused, nothing shown. + Assert.Equal(PageResult.SegmentMismatch, p.ApplyPage(Page("a-0123456789abcdef", false, "x"), older: false)); + Assert.False(p.Loaded); + Assert.NotNull(p.Problem); + + var a = new RequestPaging(); + a.Reset("a-0123456789abcdef"); + Assert.Equal(PageResult.SegmentMismatch, a.ApplyPage(Page("current", true, "x"), older: false)); + Assert.Equal(PageResult.Accepted, a.ApplyPage(Page("a-0123456789abcdef", false, "y"), older: false)); + Assert.Equal(PageResult.SegmentMismatch, a.ApplyPage(Page("a-ffffffffffffffff", false, null), older: true)); // older page of another segment + Assert.Null(a.NextCursor); + } + + [Fact] + public void Cursor_expired_410_stops_paging_and_asks_for_a_reload() + { + var p = new RequestPaging(); + p.Reset(null); + p.ApplyPage(Page("current", true, "c2-a"), older: false); + Assert.Equal(PageResult.CursorExpired, p.ApplyError(410, "cursor_expired", "410: the segment was rotated")); + Assert.True(p.Expired); + Assert.False(p.CanLoadOlder); + Assert.Null(p.NextCursor); + Assert.Equal("The audit segment changed (archived) — reload the list.", p.Problem); + + Assert.Equal(PageResult.Failed, p.ApplyError(400, "invalid_cursor", "400: bad")); + Assert.Contains("invalid_cursor", p.Problem, StringComparison.Ordinal); + Assert.Equal(PageResult.Failed, p.ApplyError(410, "expired", "410: other")); // only cursor_expired means "reload" + + p.Reset(null); + Assert.False(p.Expired); + Assert.Null(p.Problem); + Assert.Equal(PageResult.Accepted, p.ApplyPage(Page("current", true, "c2-b"), older: false)); + Assert.True(p.CanLoadOlder); + } + + [Fact] + public void An_empty_page_has_no_older_cursor() + { + var p = new RequestPaging(); + p.Reset(null); + Assert.Equal(PageResult.Accepted, p.ApplyPage(Page("current", true, "c2-a", items: 0), older: false)); + Assert.False(p.CanLoadOlder); + } +} + +public sealed class HeaderLocalHealthTests +{ + private static readonly DateTimeOffset Now = new(2026, 10, 17, 12, 0, 0, TimeSpan.Zero); + + private static CatalogResponse Catalog(ModelHealth? health, ModelHealth? endpoint = null) => new() + { + Mode = "hybrid", + Local = new LocalRouteInfo + { + Configured = true, Registered = true, ConnectionId = "ollama-2", ModelId = "qwen2.5-coder:7b", Endpoint = "http://localhost:11434/v1", + Health = health, EndpointHealth = endpoint ?? new ModelHealth(), + }, + // A stale legacy connection literally named "local" must never be consulted. + Models = [new CatalogModel { Adapter = "local", ModelId = "qwen2.5-coder:7b", Registered = true, Health = new ModelHealth { State = "failed", LastFailureUtc = Now } }], + }; + + private static ConnectionHealthDto Row(string key, ModelHealth h) => new() + { + Key = key, ConnectionId = key.Split(':')[0], ModelId = key[(key.IndexOf(':') + 1)..], Boundary = "Local", Enabled = true, Health = h, + }; + + [Fact] + public void A_successful_governed_local_call_is_ready_from_status_connection_health() + { + var v = LocalHealth.Derive(Catalog(new ModelHealth()), [Row("ollama-2:qwen2.5-coder:7b", new ModelHealth { State = "ok", LastSuccessUtc = Now })]); + Assert.Equal(LocalRouteState.Ready, v.State); + Assert.Equal("status connection_health", v.Source); + Assert.Equal("ollama-2", v.ConnectionId); + } + + [Fact] + public void Catalog_local_health_is_used_when_status_has_no_row_and_the_legacy_local_adapter_is_ignored() + { + var v = LocalHealth.Derive(Catalog(new ModelHealth { State = "ok", LastSuccessUtc = Now }), null); + Assert.Equal(LocalRouteState.Ready, v.State); + Assert.Equal("catalog local.health", v.Source); + + var unobserved = LocalHealth.Derive(Catalog(new ModelHealth()), [Row("local:qwen2.5-coder:7b", new ModelHealth { State = "failed", LastFailureUtc = Now })]); + Assert.Equal(LocalRouteState.NotObserved, unobserved.State); // another connection's row is not this one's health + } + + [Fact] + public void Endpoint_health_only_when_runtime_health_is_unknown_and_newer_failures_degrade() + { + var probe = LocalHealth.Derive(Catalog(new ModelHealth { State = "unknown" }, new ModelHealth { State = "ok", LastSuccessUtc = Now }), []); + Assert.Equal(LocalRouteState.Ready, probe.State); + Assert.Equal("catalog local.endpoint_health", probe.Source); + + var degraded = LocalHealth.Derive(Catalog(new ModelHealth { State = "failed", LastSuccessUtc = Now.AddMinutes(-5), LastFailureUtc = Now, LastError = "timeout" }, + new ModelHealth { State = "ok", LastSuccessUtc = Now }), null); + Assert.Equal(LocalRouteState.Degraded, degraded.State); + Assert.Equal("timeout", degraded.Health!.LastError); + } + + [Fact] + public void Not_configured_not_registered_and_unknown() + { + Assert.Equal(LocalRouteState.Unknown, LocalHealth.Derive(null, null).State); + Assert.Equal(LocalRouteState.NotConfigured, LocalHealth.Derive(new CatalogResponse { Local = new LocalRouteInfo { Configured = false } }, null).State); + Assert.Equal(LocalRouteState.NotRegistered, + LocalHealth.Derive(new CatalogResponse { Local = new LocalRouteInfo { Configured = true, Registered = false, ConnectionId = "ollama" } }, null).State); + } +} diff --git a/tests/Covenant.Tests/ContractRoundTripTests.cs b/tests/Covenant.Tests/ContractRoundTripTests.cs index 81b83c2..69398c8 100644 --- a/tests/Covenant.Tests/ContractRoundTripTests.cs +++ b/tests/Covenant.Tests/ContractRoundTripTests.cs @@ -15,6 +15,12 @@ namespace Covenant.Tests; // → Host reads it (ConfigJsonContext.ConfigPutRequest) // and the configuration that comes out is the one that went in. The UI DTOs are compiled in by link // (Covenant.Tests.csproj), so a field the console drops or misspells fails here, not in production. +// +// Review round 2 (U1): ONE explicit contract. Every admin DTO the console consumes is pinned Host → UI here: the Host +// object is serialized with the SAME context its endpoint uses (CovenantJsonContext: status, catalog, probe, evidence, +// errors, budgets; ConfigJsonContext: config, validate, versions, rollback, applications, simulate; AuditJsonContext: +// requests page, request, segments, export; TraceJsonContext: trace snapshot/event, playground submission) and read with +// UiJsonContext, then asserted field by field. The console has no alternative-shape fallback parser left. public sealed class ContractRoundTripTests { private static readonly DateTimeOffset Created = new(2026, 10, 16, 9, 30, 0, TimeSpan.Zero); @@ -508,7 +514,12 @@ public void Catalog_connections_carry_health_registration_and_allow_listing_to_t { Mode = "hybrid", Models = [new CatalogModel { Adapter = "ollama", ModelId = "qwen3:8b", Classifications = ["Internal"], Registered = true, PriceBasis = "zero", Health = ok, ConnectionId = "ollama", Boundary = "Local", Key = "ollama:qwen3:8b" }], - Local = new LocalConfigView { Configured = true, Endpoint = "http://ollama-host:11434/v1", ModelId = "qwen3:8b", Registered = true, EndpointHealth = new HealthView { State = "failed", LastFailureUtc = Created, LastError = "refused" } }, + Local = new LocalConfigView + { + Configured = true, Endpoint = "http://ollama-host:11434/v1", ModelId = "qwen3:8b", Registered = true, + EndpointHealth = new HealthView { State = "failed", LastFailureUtc = Created, LastError = "refused" }, + ConnectionId = "ollama", Health = new HealthView { State = "ok", LastSuccessUtc = Created.AddMinutes(1) }, + }, ProbeAllowList = ["ollama-host:11434"], ConfigVersion = 7, EgressAllowList = ["api.openai.com:443", "ollama-host:11434"], @@ -529,16 +540,46 @@ public void Catalog_connections_carry_health_registration_and_allow_listing_to_t Assert.Equal("Local", ui.Models[0].Boundary); Assert.Equal("ollama", ui.Models[0].ConnectionId); Assert.Equal("ollama:qwen3:8b", ui.Models[0].Key); - Assert.Equal("refused", ui.Local!.EndpointHealth!.LastError); + Assert.Equal("hybrid", ui.Mode); + Assert.Equal(new[] { "ollama-host:11434" }, ui.ProbeAllowList); + var m0 = Assert.Single(ui.Models); + Assert.Equal("ollama", m0.Adapter); + Assert.Equal("qwen3:8b", m0.ModelId); + Assert.Equal(new[] { "Internal" }, m0.Classifications); + Assert.True(m0.Registered); + Assert.Equal("zero", m0.PriceBasis); + Assert.Equal("ok", m0.Health!.State); + Assert.Equal(Created, m0.Health!.LastSuccessUtc); + var local = ui.Local!; + Assert.True(local.Configured); + Assert.True(local.Registered); + Assert.Equal("http://ollama-host:11434/v1", local.Endpoint); + Assert.Equal("qwen3:8b", local.ModelId); + Assert.Equal("failed", local.EndpointHealth.State); + Assert.Equal("refused", local.EndpointHealth.LastError); + Assert.Equal(Created, local.EndpointHealth.LastFailureUtc); + // Review round 2 (B11): the CURRENT runtime connection and its health. + Assert.Equal("ollama", local.ConnectionId); + Assert.Equal("ok", local.Health!.State); + Assert.Equal(Created.AddMinutes(1), local.Health!.LastSuccessUtc); + Assert.Equal(Covenant.Ui.Logic.LocalRouteState.Ready, Covenant.Ui.Logic.LocalHealth.Derive(ui, null).State); var c = Assert.Single(ui.Connections!); + Assert.Equal("openai", c.Id); + Assert.Equal("OpenAI", c.DisplayName); + Assert.True(c.Enabled); + Assert.Null(c.Endpoint); Assert.Equal("OpenAi", c.Kind); Assert.Equal("Cloud", c.Boundary); Assert.True(c.EndpointAllowListed); Assert.False(c.SecretAvailable); Assert.Equal("Secrets:openai", c.SecretRef); var m = Assert.Single(c.Models); + Assert.Equal("openai:gpt-x-mini", m.Key); + Assert.Equal("gpt-x-mini", m.ModelId); Assert.False(m.Registered); + Assert.Equal("configured", m.PriceBasis); Assert.Equal(0.15m, m.InPer1M); + Assert.Equal(0.60m, m.OutPer1M); Assert.Equal("unknown", m.Health!.State); } @@ -557,6 +598,14 @@ public void Budget_state_and_contributions_reach_the_console() }, }, CovenantJsonContext.Default.ListBudgetStateView); var ui = Assert.Single(JsonSerializer.Deserialize(states, UiModels.UiJsonContext.Default.ListBudgetStateDto)!); + Assert.Equal("global", ui.Id); + Assert.Equal("global", ui.Scope); + Assert.Equal("monthly", ui.Period); + Assert.Equal(25m, ui.CapUsd); + Assert.Equal(24.997716m, ui.RemainingUsd); + Assert.Equal("none", ui.Warning); + Assert.Equal("hard", ui.Enforcement); + Assert.Equal(Created.AddDays(16), ui.PeriodEndUtc); Assert.Equal("2026-10", ui.PeriodId); Assert.Equal(0.000184m, ui.SpentUsd); Assert.Equal(0.0021m, ui.ReservedUsd); @@ -573,13 +622,19 @@ public void Budget_state_and_contributions_reach_the_console() new BudgetContributionView { RequestId = "req_b", AttemptId = "att_1", Kind = "settle-recovered", AmountUsd = 0.0021m, TsUtc = Created }, ], }, CovenantJsonContext.Default.BudgetRequestsView); - var rows = Covenant.Ui.Logic.BudgetRequests.Parse(contributions)!; + var page = JsonSerializer.Deserialize(contributions, UiModels.UiJsonContext.Default.BudgetRequestsDto)!; + Assert.Equal("global", page.BudgetId); + Assert.Equal("global", page.Scope); + Assert.Equal("2026-10", page.PeriodId); + var rows = page.Items; Assert.Equal(new[] { "req_a", "req_b" }, rows.Select(r => r.RequestId)); Assert.Equal(0.000184m, rows[0].AmountUsd); Assert.Equal("att_2", rows[0].AttemptId); + Assert.Equal("settle", rows[0].Kind); Assert.True(rows[0].Overrun); + Assert.False(rows[1].Overrun); Assert.Equal("settle-recovered", rows[1].Kind); - Assert.Equal(Created, rows[0].TimestampUtc); + Assert.Equal(Created, rows[0].TsUtc); } [Fact] @@ -591,22 +646,578 @@ public void Audit_segments_and_cursor_pages_reach_the_console() new() { Id = "a-0123456789abcdef", Label = "Archived 2026-10-01 09:00", Current = false, Entries = 40, Events = 2, ChainValid = true, ArchivedUtc = Created.AddDays(-15) }, }, AuditJsonContext.Default.ListSegmentView); var ui = JsonSerializer.Deserialize(segs, UiModels.UiJsonContext.Default.ListAuditSegmentDto)!; - Assert.True(Covenant.Ui.Logic.SegmentScope.IsCurrent(ui[0], ui)); - Assert.False(Covenant.Ui.Logic.SegmentScope.IsCurrent(ui[1], ui)); + Assert.True(Covenant.Ui.Logic.SegmentScope.IsCurrent(ui[0])); + Assert.False(Covenant.Ui.Logic.SegmentScope.IsCurrent(ui[1])); + Assert.Equal("current", ui[0].Id); + Assert.Equal("Current", ui[0].Label); + Assert.Equal(12, ui[0].Entries); + Assert.Equal(Created, ui[0].FirstUtc); + Assert.True(ui[0].ChainValid); + Assert.Equal("a-0123456789abcdef", ui[1].Id); + Assert.Equal("Archived 2026-10-01 09:00", ui[1].Label); Assert.Equal(40, ui[1].Entries); Assert.Equal(2, ui[1].Events); - Assert.NotNull(ui[1].ArchivedUtc); + Assert.Equal(Created.AddDays(-15), ui[1].ArchivedUtc); + var cursor = AuditSegments.Cursor("a-0123456789abcdef", "0123456789abcdef", 40); var page = JsonSerializer.Serialize(new RequestsPage { - Segment = new SegmentInfo { Path = "/var/covenant/audit.jsonl", Entries = 40, ChainValid = true, Id = "a-0123456789abcdef", Label = "Archived 2026-10-01 09:00" }, + Segment = new SegmentInfo + { + Path = "/var/covenant/audit.jsonl", Entries = 80, Events = 3, ChainValid = true, FirstUtc = Created, LastUtc = Created.AddHours(1), + Id = "a-0123456789abcdef", Label = "Archived 2026-10-01 09:00", IsCurrent = false, + }, Items = [], - NextCursor = "opaque-token", + NextCursor = cursor, }, AuditJsonContext.Default.RequestsPage); var uiPage = JsonSerializer.Deserialize(page, UiModels.UiJsonContext.Default.RequestsResponse)!; - Assert.Equal("a-0123456789abcdef", uiPage.Segment.Id); // the console refuses to label an unconfirmed segment - Assert.Equal("opaque-token", uiPage.NextCursor); - Assert.Equal(40, uiPage.Segment.Entries); + // The segment descriptor — never inferred from a row. + Assert.Equal("a-0123456789abcdef", uiPage.Segment.Id); + Assert.Equal("Archived 2026-10-01 09:00", uiPage.Segment.Label); + Assert.False(uiPage.Segment.IsCurrent); + Assert.Equal("/var/covenant/audit.jsonl", uiPage.Segment.Path); + Assert.Equal(80, uiPage.Segment.Entries); + Assert.Equal(3, uiPage.Segment.Events); + Assert.True(uiPage.Segment.ChainValid); + Assert.Equal(Created, uiPage.Segment.FirstUtc); + Assert.Equal(Created.AddHours(1), uiPage.Segment.LastUtc); + Assert.Equal(cursor, uiPage.NextCursor); // opaque: passed back verbatim + Assert.Equal("Archived segment Archived 2026-10-01 09:00 · read-only", Covenant.Ui.Logic.SegmentScope.Label(uiPage.Segment)); + + var paging = new Covenant.Ui.Logic.RequestPaging(); + paging.Reset("a-0123456789abcdef"); + Assert.Equal(Covenant.Ui.Logic.PageResult.Accepted, paging.ApplyPage(uiPage, older: false)); + + // is_current is ALWAYS on the wire, even when false. + Assert.False(Wire(page).GetProperty("segment").GetProperty("is_current").GetBoolean()); + var last = JsonSerializer.Serialize(new RequestsPage + { + Segment = new SegmentInfo { Path = "/var/covenant/audit.jsonl", Entries = 0, ChainValid = true, Id = "current", Label = "Current segment", IsCurrent = true }, + Items = [], + NextCursor = null, + }, AuditJsonContext.Default.RequestsPage); + var uiLast = JsonSerializer.Deserialize(last, UiModels.UiJsonContext.Default.RequestsResponse)!; + Assert.True(uiLast.Segment.IsCurrent); + Assert.Null(uiLast.NextCursor); + } + + // ---- Review round 2 (U1): the remaining Host → UI contracts, field by field ---- + + private static AuditEntry RoundTwoRecord() => new( + Id: "req_0123456789abcdef0123456789abcdef", + TimestampUtc: Created, + Principal: "console:demo-app", + Tags: new AttributionTags("payments", "console", "playground"), + Classification: DataClassification.Pii, + Effect: PolicyEffect.Allow, + Reason: "allowed", + ServedByModel: "ollama/qwen3:8b", + Usage: new Usage(84, 10, 0.0021m), + DurationMs: 812.5, + PromptChars: 120, + PromptSha256: new string('a', 64), + Signal: "US SSN pattern", + PromptPreview: null, + CacheHit: false, + SchemaVersion: 2, + CorrelationId: "req_0123456789abcdef0123456789abcdef", + ClassificationEvaluated: true, + DenialKind: "None", + StoppedAtStage: null, + SelectedModel: "openai/gpt-x-mini", + AttemptedModel: "ollama/qwen3:8b", + Stream: true, + UsageReported: true, + CostBasis: "mixed", + EventType: "request", + ConfigVersion: 13, + EntryPoint: "console", + OperatorRef: "shared-admin-token", + ApplicationId: "demo-app", + ProfileId: "public-tickets", + BaselineClassification: DataClassification.Public, + Attempts: + [ + new AuditAttempt("att_1", "openai", "gpt-x-mini", "failed", "incomplete_stream", 1500.25, 0.0021m, "estimated_failed_call", + ReservedUsd: 0.0021m, Overrun: false, EffectiveMaxOutputTokens: 256, Truncated: null), + new AuditAttempt("att_2", "ollama", "qwen3:8b", "served", null, 640.5, 0m, "zero_priced", + ReservedUsd: 0m, Overrun: false, EffectiveMaxOutputTokens: 64, Truncated: true), + ], + Trace: + [ + new AuditTraceStep("auth", "passed", 0.4), + new AuditTraceStep("provider", "failed", 1500.25, "att_1", "incomplete_stream"), + new AuditTraceStep("provider", "passed", 640.5, "att_2"), + ], + ReservedUsd: 0.0021m, + SettledUsd: 0.0021m, + RequestedMaxOutputTokens: 256, + EffectiveMaxOutputTokens: 64, + PartialOutputChars: null, + ServedConnectionId: "ollama"); + + private static void AssertRecord(AuditEntry h, UiModels.AuditEntryView u) + { + Assert.Equal(h.Id, u.Id); + Assert.Equal(h.TimestampUtc, u.TimestampUtc); + Assert.Equal(h.Principal, u.Principal); + Assert.Equal(h.Tags.Team, u.Tags.Team); + Assert.Equal(h.Tags.Workflow, u.Tags.Workflow); + Assert.Equal(h.Tags.UseCase, u.Tags.UseCase); + Assert.Equal("Pii", u.Classification); + Assert.Equal("Allow", u.Effect); + Assert.Equal(h.Reason, u.Reason); + Assert.Equal(h.ServedByModel, u.ServedByModel); + Assert.Equal(h.Usage.InputTokens, u.Usage.InputTokens); + Assert.Equal(h.Usage.OutputTokens, u.Usage.OutputTokens); + Assert.Equal(h.Usage.TotalTokens, u.Usage.TotalTokens); + Assert.Equal(h.Usage.CostUsd, u.Usage.CostUsd); + Assert.Equal(h.DurationMs, u.DurationMs); + Assert.Equal(h.PromptChars, u.PromptChars); + Assert.Equal(h.PromptSha256, u.PromptSha256); + Assert.Equal(h.Signal, u.Signal); + Assert.Null(u.PromptPreview); + Assert.Equal(h.CacheHit, u.CacheHit); + Assert.Equal(h.SchemaVersion, u.SchemaVersion); + Assert.Equal(h.CorrelationId, u.CorrelationId); + Assert.Equal(h.ClassificationEvaluated, u.ClassificationEvaluated); + Assert.Equal(h.DenialKind, u.DenialKind); + Assert.Equal(h.StoppedAtStage, u.StoppedAtStage); + Assert.Equal(h.SelectedModel, u.SelectedModel); + Assert.Equal(h.AttemptedModel, u.AttemptedModel); + Assert.Equal(h.Stream, u.Stream); + Assert.Equal(h.UsageReported, u.UsageReported); + Assert.Equal(h.CostBasis, u.CostBasis); + Assert.Equal(h.EventType, u.EventType); + Assert.Equal(h.ConfigVersion, u.ConfigVersion); + Assert.Equal(h.EntryPoint, u.EntryPoint); + Assert.Equal(h.OperatorRef, u.OperatorRef); + Assert.Equal(h.ApplicationId, u.ApplicationId); + Assert.Equal(h.ProfileId, u.ProfileId); + Assert.Equal("Public", u.BaselineClassification); + Assert.Equal(h.ReservedUsd, u.ReservedUsd); + Assert.Equal(h.SettledUsd, u.SettledUsd); + Assert.Equal(h.RequestedMaxOutputTokens, u.RequestedMaxOutputTokens); + Assert.Equal(h.EffectiveMaxOutputTokens, u.EffectiveMaxOutputTokens); + Assert.Equal(h.PartialOutputChars, u.PartialOutputChars); + Assert.Equal(h.ServedConnectionId, u.ServedConnectionId); + + Assert.Equal(h.Attempts!.Count, u.Attempts!.Count); + foreach (var (ha, ua) in h.Attempts!.Zip(u.Attempts!)) + { + Assert.Equal(ha.AttemptId, ua.AttemptId); + Assert.Equal(ha.ConnectionId, ua.ConnectionId); + Assert.Equal(ha.ModelId, ua.ModelId); + Assert.Equal(ha.Outcome, ua.Outcome); + Assert.Equal(ha.ErrorClass, ua.ErrorClass); + Assert.Equal(ha.DurationMs, ua.DurationMs); + Assert.Equal(ha.CostUsd, ua.CostUsd); + Assert.Equal(ha.CostBasis, ua.CostBasis); + Assert.Equal(ha.ReservedUsd, ua.ReservedUsd); + Assert.Equal(ha.Overrun, ua.Overrun); + Assert.Equal(ha.EffectiveMaxOutputTokens, ua.EffectiveMaxOutputTokens); + Assert.Equal(ha.Truncated, ua.Truncated); + } + Assert.Equal(h.Trace!.Count, u.Trace!.Count); + foreach (var (ht, ut) in h.Trace!.Zip(u.Trace!)) + { + Assert.Equal(ht.Stage, ut.Stage); + Assert.Equal(ht.State, ut.State); + Assert.Equal(ht.DurationMs, ut.DurationMs); + Assert.Equal(ht.AttemptId, ut.AttemptId); + Assert.Equal(ht.ReasonCode, ut.ReasonCode); + } + } + + [Fact] + public void Audit_record_v3_round_two_fields_reach_the_console_from_the_requests_page_and_the_by_id_lookup() + { + var record = RoundTwoRecord(); + var page = JsonSerializer.Serialize(new RequestsPage + { + Segment = new SegmentInfo { Path = "/var/covenant/audit.jsonl", Entries = 1, ChainValid = true, Id = "current", Label = "Current segment", IsCurrent = true }, + Items = [record], + NextCursor = null, + }, AuditJsonContext.Default.RequestsPage); + var ui = JsonSerializer.Deserialize(page, UiModels.UiJsonContext.Default.RequestsResponse)!; + AssertRecord(record, Assert.Single(ui.Items)); + + var byId = JsonSerializer.Deserialize(JsonSerializer.Serialize(record, AuditJsonContext.Default.AuditEntry), UiModels.UiJsonContext.Default.AuditEntryView)!; + AssertRecord(record, byId); + + // What the drawer shows from those fields. + Assert.Equal("256", Covenant.Ui.Logic.RecordFacts.RequestedMaxOutputTokens(byId)); + Assert.Equal("64", Covenant.Ui.Logic.RecordFacts.EffectiveMaxOutputTokens(byId)); + Assert.True(Covenant.Ui.Logic.RecordFacts.Truncated(byId)); + Assert.True(Covenant.Ui.Logic.RecordFacts.IsIncompleteStream(byId)); + Assert.Equal("ollama", Covenant.Ui.Logic.RecordFacts.ServedConnection(byId)); + Assert.Contains("Mixed (includes estimates)", Covenant.Ui.Logic.CostText.Cost(byId), StringComparison.Ordinal); + var trace = Covenant.Ui.Logic.TraceModel.FromAuditSummary(byId.Trace, byId.Attempts, byId.ConfigVersion)!; + var provider = trace.Steps.Single(st => st.Stage == "provider"); + Assert.Equal(2, provider.Attempts.Count); + Assert.Equal("openai/gpt-x-mini", provider.Attempts[0].Target); + Assert.Equal("incomplete_stream", provider.Attempts[0].ReasonCode); + } + + [Fact] + public void Status_report_with_connection_health_reaches_the_console() + { + var recent = new RecentRequest + { + Id = "req_1", T = Created, Principal = "console:demo-app", Team = "payments", Workflow = "console", UseCase = "playground", + Classification = "Pii", Effect = "Allow", Model = "ollama/qwen3:8b", Tokens = 94, TokensIn = 84, TokensOut = 10, CostUsd = 0.0021m, + Ms = 812.5, Reason = "allowed", PromptChars = 120, PromptSha256 = "abc", Signal = "US SSN pattern", PromptPreview = null, CacheHit = false, CostBasis = "mixed", + }; + var host = new StatusReport + { + GeneratedUtc = Created, StartedUtc = Created.AddHours(-1), + KillSwitch = new KillSwitchState { Engaged = true, Reason = "demo" }, + Budget = new BudgetStatus { GlobalCapUsd = 25m, GlobalSpendUsd = 0.5m, Teams = [new TeamBudgetStatus { Team = "payments", CapUsd = null, SpendUsd = 0.5m }] }, + Routes = [new RouteView { Classification = "Pii", Adapter = "ollama", Model = "qwen3:8b" }], + FinOps = new FinOpsSummary + { + Requests = 3, Allowed = 2, Denied = 1, TotalCostUsd = 0.0021m, LocalRequests = 1, LocalTokens = 94, + EstimatedSavingsUsd = 0m, SavingsLocalUsd = 0m, SavingsRouterUsd = 0m, SavingsCacheUsd = 0m, CacheHits = 0, + UnknownCostRequests = 1, EstimatedCostRequests = 1, + CostByTeamUsd = new() { ["payments"] = 0.0021m }, DenialsByReason = new() { ["paused"] = 1 }, + Activity = [new ActivityBucket { T = Created, Requests = 3, Denied = 1, CostUsd = 0.0021m, AvgMs = 400.5 }], + RequestsByModel = new() { ["ollama/qwen3:8b"] = 2 }, + Recent = [recent], + Savings = new SavingsSummary { Baseline = "openai/gpt-x", RouteAvoidedUsd = 0.01m, CacheAvoidedUsd = 0.002m, TotalUsd = 0.012m, ExcludedRecords = 1 }, + }, + ChainValid = true, AuditEntries = 3, Auth = new AuthStatus { AllowAnonymous = false, KeyCount = 2 }, OtelEnabled = false, RoutingThresholdTokens = 400, + Environment = "local", Mode = "local-only", AuditPath = "/var/covenant/audit.jsonl", CacheTtlSeconds = 300, PromptPreviewChars = 0, + Anchor = new AnchorStatus { Configured = true, Every = 100, AnchorsWritten = 2, LastAnchorUtc = Created }, + Version = "2.0.0", ConfigVersion = 13, + ConnectionHealth = + [ + new ConnectionHealthView + { + Key = "ollama:qwen3:8b", ConnectionId = "ollama", ModelId = "qwen3:8b", Boundary = "Local", Enabled = true, + Health = new HealthView { State = "ok", LastSuccessUtc = Created, LastFailureUtc = Created.AddMinutes(-5), LastError = "timeout" }, + }, + ], + }; + var ui = JsonSerializer.Deserialize(JsonSerializer.Serialize(host, CovenantJsonContext.Default.StatusReport), UiModels.UiJsonContext.Default.StatusReport)!; + + Assert.Equal(Created, ui.GeneratedUtc); + Assert.Equal(Created.AddHours(-1), ui.StartedUtc); + Assert.True(ui.KillSwitch.Engaged); + Assert.Equal("demo", ui.KillSwitch.Reason); + Assert.Equal(25m, ui.Budget.GlobalCapUsd); + Assert.Equal(0.5m, ui.Budget.GlobalSpendUsd); + Assert.Equal("payments", Assert.Single(ui.Budget.Teams).Team); + Assert.Null(ui.Budget.Teams[0].CapUsd); + Covenant.Ui.Models.RouteView route = Assert.Single(ui.Routes); + Assert.Equal("Pii", route.Classification); + Assert.Equal("ollama", route.Adapter); + Assert.Equal("qwen3:8b", route.Model); + Assert.True(ui.ChainValid); + Assert.Equal(3, ui.AuditEntries); + Assert.False(ui.Auth.AllowAnonymous); + Assert.Equal(2, ui.Auth.KeyCount); + Assert.False(ui.OtelEnabled); + Assert.Equal(400, ui.RoutingThresholdTokens); + Assert.Equal("local", ui.Environment); + Assert.Equal("local-only", ui.Mode); + Assert.Equal("Local-only", Covenant.Ui.Logic.ShellStatus.Mode(ui.Mode).Label); + Assert.Equal("/var/covenant/audit.jsonl", ui.AuditPath); + Assert.Equal(300, ui.CacheTtlSeconds); + Assert.Equal(0, ui.PromptPreviewChars); + Assert.True(ui.Anchor!.Configured); + Assert.Equal(100, ui.Anchor!.Every); + Assert.Equal(2, ui.Anchor!.AnchorsWritten); + Assert.Equal(Created, ui.Anchor!.LastAnchorUtc); + Assert.Equal("2.0.0", ui.Version); + Assert.Equal(13, ui.ConfigVersion); + + var f = ui.FinOps; + Assert.Equal(3, f.Requests); + Assert.Equal(2, f.Allowed); + Assert.Equal(1, f.Denied); + Assert.Equal(0.0021m, f.TotalCostUsd); + Assert.Equal(1, f.LocalRequests); + Assert.Equal(94, f.LocalTokens); + Assert.Equal(1, f.UnknownCostRequests); + Assert.Equal(1, f.EstimatedCostRequests); + Assert.Equal(0.0021m, f.CostByTeamUsd["payments"]); + Assert.Equal(1, f.DenialsByReason["paused"]); + Assert.Equal(2, f.RequestsByModel["ollama/qwen3:8b"]); + var b = Assert.Single(f.Activity); + Assert.Equal(Created, b.T); + Assert.Equal(400.5, b.AvgMs); + Assert.Equal("Estimated provider charge avoided", f.Savings!.Label); + Assert.Equal("openai/gpt-x", f.Savings!.Baseline); + Assert.Equal(0.01m, f.Savings!.RouteAvoidedUsd); + Assert.Equal(0.002m, f.Savings!.CacheAvoidedUsd); + Assert.Equal(0.012m, f.Savings!.TotalUsd); + Assert.Equal(1, f.Savings!.ExcludedRecords); + var r = Assert.Single(f.Recent); + Assert.Equal("req_1", r.Id); + Assert.Equal(Created, r.T); + Assert.Equal("Pii", r.Classification); + Assert.Equal("Allow", r.Effect); + Assert.Equal("ollama/qwen3:8b", r.Model); + Assert.Equal(94, r.Tokens); + Assert.Equal(84, r.TokensIn); + Assert.Equal(10, r.TokensOut); + Assert.Equal(0.0021m, r.CostUsd); + Assert.Equal(812.5, r.Ms); + Assert.Equal(120, r.PromptChars); + Assert.Equal("US SSN pattern", r.Signal); + Assert.False(r.CacheHit); + Assert.Equal("mixed", r.CostBasis); + + // Review round 2 (B11): connection_health — the header's source for the CURRENT runtime connection. + var h = Assert.Single(ui.ConnectionHealth!); + Assert.Equal("ollama:qwen3:8b", h.Key); + Assert.Equal("ollama", h.ConnectionId); + Assert.Equal("qwen3:8b", h.ModelId); + Assert.Equal("Local", h.Boundary); + Assert.True(h.Enabled); + Assert.Equal("ok", h.Health.State); + Assert.Equal(Created, h.Health.LastSuccessUtc); + Assert.Equal(Created.AddMinutes(-5), h.Health.LastFailureUtc); + Assert.Equal("timeout", h.Health.LastError); + + var catalog = new UiModels.CatalogResponse + { + Local = new UiModels.LocalRouteInfo { Configured = true, Registered = true, ConnectionId = "ollama", ModelId = "qwen3:8b" }, + }; + Assert.Equal(Covenant.Ui.Logic.LocalRouteState.Ready, Covenant.Ui.Logic.LocalHealth.Derive(catalog, ui.ConnectionHealth).State); + } + + [Fact] + public void Applications_reach_the_console_without_credentials() + { + var body = JsonSerializer.Serialize(new List + { + new() { Id = "demo-app", Team = "payments", Enabled = true, ConsoleTesting = true, GrantedProfiles = ["public-tickets", "internal"], DefaultProfile = "internal" }, + new() { Id = "prod-app", Team = "risk", Enabled = false, ConsoleTesting = false, GrantedProfiles = [], DefaultProfile = null }, + }, ConfigJsonContext.Default.ListApplicationView); + var ui = JsonSerializer.Deserialize(body, UiModels.UiJsonContext.Default.ListApplicationSummaryDto)!; + Assert.Equal(2, ui.Count); + Assert.Equal("demo-app", ui[0].Id); + Assert.Equal("payments", ui[0].Team); + Assert.True(ui[0].Enabled); + Assert.True(ui[0].ConsoleTesting); + Assert.Equal(new[] { "public-tickets", "internal" }, ui[0].GrantedProfiles); + Assert.Equal("internal", ui[0].DefaultProfile); + Assert.False(ui[1].Enabled); + Assert.False(ui[1].ConsoleTesting); + Assert.Empty(ui[1].GrantedProfiles); + Assert.Null(ui[1].DefaultProfile); + Assert.DoesNotContain("key", body, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void Rollback_answer_and_config_errors_reach_the_console() + { + // POST /admin/config/rollback answers like a PUT: {version, etag} (ConfigJsonContext.ConfigPutResponse). + var ok = JsonSerializer.Deserialize(JsonSerializer.Serialize(new ConfigPutResponse { Version = 14, Etag = "\"v14\"" }, ConfigJsonContext.Default.ConfigPutResponse), + UiModels.UiJsonContext.Default.ConfigPutResponseDto)!; + Assert.Equal(14, ok.Version); + Assert.Equal("\"v14\"", ok.Etag); + + var notFound = JsonSerializer.Deserialize(JsonSerializer.Serialize(new ConfigErrorResponse { Error = "not_found", Reason = "no activated configuration version 99", ActiveVersion = 13 }, + ConfigJsonContext.Default.ConfigErrorResponse), UiModels.UiJsonContext.Default.ConfigErrorResponseDto)!; + Assert.Equal("not_found", notFound.Error); + Assert.Equal("no activated configuration version 99", notFound.Reason); + Assert.Equal(13, notFound.ActiveVersion); + Assert.Null(notFound.Errors); + + var rolledBack = Covenant.Ui.Logic.EditOutcomes.FromResponse(200, + JsonSerializer.Serialize(new ConfigPutResponse { Version = 14, Etag = "\"v14\"" }, ConfigJsonContext.Default.ConfigPutResponse), rollback: true); + Assert.True(rolledBack.Succeeded); + Assert.Equal(14, rolledBack.Version); + + // A historical snapshot (GET /admin/config/versions/{n}) is a plain CovenantConfig. + var snap = JsonSerializer.Deserialize(JsonSerializer.Serialize(Representative(ProviderMode.LocalOnly), ConfigJsonContext.Default.CovenantConfig), + UiModels.UiJsonContext.Default.CovenantConfigDto)!; + Assert.Equal(7, snap.Version); + Assert.Equal("local-only", snap.Mode); + Assert.Equal(4, snap.Connections.Count); + Assert.Equal(90, snap.Connections[0].TimeoutSeconds); + } + + [Fact] + public void Common_admin_error_body_carries_the_error_code_the_console_branches_on() + { + foreach (var (error, reason) in new[] { ("cursor_expired", "the segment was rotated"), ("invalid_cursor", "malformed"), ("not_found", "no record") }) + { + var ui = JsonSerializer.Deserialize(JsonSerializer.Serialize(new ErrorResponse { Error = error, Reason = reason, RequestId = "req_1", Scanned = 3 }, CovenantJsonContext.Default.ErrorResponse), + UiModels.UiJsonContext.Default.ErrorResponse)!; + Assert.Equal(error, ui.Error); + Assert.Equal(reason, ui.Reason); + Assert.Equal("req_1", ui.RequestId); + Assert.Equal(3, ui.Scanned); + } + var p = new Covenant.Ui.Logic.RequestPaging(); + p.Reset(null); + Assert.Equal(Covenant.Ui.Logic.PageResult.CursorExpired, p.ApplyError(410, "cursor_expired", "410")); + } + + [Fact] + public void Request_export_reaches_the_console_without_content() + { + var record = RoundTwoRecord() with { PromptPreview = null }; + var host = new RequestExport + { + ExportedUtc = Created.AddDays(1), + RequestId = record.Id, + Segment = new SegmentView { Id = "a-0123456789abcdef", Label = "Archived 2026-10-01 09:00:00 UTC", Current = false, Entries = 40, Events = 2, FirstUtc = Created, LastUtc = Created.AddHours(2), ChainValid = true, ArchivedUtc = Created.AddDays(1) }, + ConfigVersion = 13, + Record = record, + Attempts = record.Attempts, + Trace = record.Trace, + Integrity = new ExportIntegrity + { + SegmentId = "a-0123456789abcdef", ChainValid = true, ChainFailure = null, Line = 17, PreviousHash = new string('b', 64), EntryHash = new string('c', 64), + AnchorConfigured = true, Status = "verified", + }, + ContentIncluded = false, + }; + var ui = JsonSerializer.Deserialize(JsonSerializer.Serialize(host, AuditJsonContext.Default.RequestExport), UiModels.UiJsonContext.Default.RequestExportDto)!; + Assert.Equal(Created.AddDays(1), ui.ExportedUtc); + Assert.Equal(record.Id, ui.RequestId); + Assert.Equal("a-0123456789abcdef", ui.Segment.Id); + Assert.Equal("Archived 2026-10-01 09:00:00 UTC", ui.Segment.Label); + Assert.False(ui.Segment.Current); + Assert.Equal(40, ui.Segment.Entries); + Assert.Equal(2, ui.Segment.Events); + Assert.Equal(Created, ui.Segment.FirstUtc); + Assert.Equal(Created.AddHours(2), ui.Segment.LastUtc); + Assert.True(ui.Segment.ChainValid); + Assert.Equal(Created.AddDays(1), ui.Segment.ArchivedUtc); + Assert.Equal(13, ui.ConfigVersion); + AssertRecord(record, ui.Record); + Assert.Equal(new[] { "att_1", "att_2" }, ui.Attempts!.Select(a => a.AttemptId)); + Assert.Equal(new[] { "auth", "provider", "provider" }, ui.Trace!.Select(t => t.Stage)); + Assert.Equal("a-0123456789abcdef", ui.Integrity.SegmentId); + Assert.True(ui.Integrity.ChainValid); + Assert.Null(ui.Integrity.ChainFailure); + Assert.Equal(17, ui.Integrity.Line); + Assert.Equal(new string('b', 64), ui.Integrity.PreviousHash); + Assert.Equal(new string('c', 64), ui.Integrity.EntryHash); + Assert.True(ui.Integrity.AnchorConfigured); + Assert.Equal("verified", ui.Integrity.Status); + Assert.False(ui.ContentIncluded); + } + + [Fact] + public void Trace_snapshot_event_and_playground_submission_reach_the_console() + { + var ev = new TraceEventView + { + Seq = 9, RequestId = "req_1", ConfigVersion = 13, Stage = "provider", AttemptId = "att_1", State = "running", TsUtc = Created, + DurationMs = null, ReasonCode = null, Target = "ollama/qwen3:8b", RequestedMaxOutputTokens = 256, EffectiveMaxOutputTokens = 64, + }; + var uiEv = JsonSerializer.Deserialize(JsonSerializer.Serialize(ev, TraceJsonContext.Default.TraceEventView), UiModels.UiJsonContext.Default.TraceEventDto)!; + Assert.Equal(9, uiEv.Seq); + Assert.Equal("req_1", uiEv.RequestId); + Assert.Equal(13, uiEv.ConfigVersion); + Assert.Equal("provider", uiEv.Stage); + Assert.Equal("att_1", uiEv.AttemptId); + Assert.Equal("running", uiEv.State); + Assert.Equal(Created, uiEv.TsUtc); + Assert.Null(uiEv.DurationMs); + Assert.Null(uiEv.ReasonCode); + Assert.Equal("ollama/qwen3:8b", uiEv.Target); + Assert.Equal(256, uiEv.RequestedMaxOutputTokens); + Assert.Equal(64, uiEv.EffectiveMaxOutputTokens); + + var snap = new TraceSnapshotView + { + RequestId = "req_1", ConfigVersion = 13, Complete = true, Truncated = true, + Events = [ev, new TraceEventView { Seq = 10, RequestId = "req_1", ConfigVersion = 13, Stage = "provider", AttemptId = "att_1", State = "passed", TsUtc = Created.AddSeconds(1), DurationMs = 812.25 }], + }; + var uiSnap = JsonSerializer.Deserialize(JsonSerializer.Serialize(snap, TraceJsonContext.Default.TraceSnapshotView), UiModels.UiJsonContext.Default.TraceSnapshotDto)!; + Assert.Equal("req_1", uiSnap.RequestId); + Assert.Equal(13, uiSnap.ConfigVersion); + Assert.True(uiSnap.Complete); + Assert.True(uiSnap.Truncated); + Assert.Equal(new long[] { 9, 10 }, uiSnap.Events.Select(e => e.Seq)); + Assert.Equal(812.25, uiSnap.Events[1].DurationMs); + var acc = new Covenant.Ui.Logic.TraceAccumulator(); + acc.ApplySnapshot(uiSnap); + var attempt = Assert.Single(acc.View().Steps.Single(st => st.Stage == "provider").Attempts); + Assert.Equal(Covenant.Ui.Logic.TraceStepState.Passed, attempt.State); + Assert.Equal(64, attempt.EffectiveMaxOutputTokens); + + foreach (var state in new[] { "running", "completed" }) + { + var sub = new PlaygroundSubmissionView { ClientRequestId = "0123456789abcdef0123456789abcdef", RequestId = "req_1", State = state }; + var uiSub = JsonSerializer.Deserialize(JsonSerializer.Serialize(sub, TraceJsonContext.Default.PlaygroundSubmissionView), UiModels.UiJsonContext.Default.PlaygroundSubmissionDto)!; + Assert.Equal("0123456789abcdef0123456789abcdef", uiSub.ClientRequestId); + Assert.Equal("req_1", uiSub.RequestId); + Assert.Equal(state, uiSub.State); + var poll = new Covenant.Ui.Logic.SubmissionPoll("0123456789abcdef0123456789abcdef"); + Assert.Equal(Covenant.Ui.Logic.SubmissionPollAction.Subscribe, poll.OnPollResult(200, uiSub)); + Assert.Equal("req_1", poll.RequestId); + } + } + + [Fact] + public void Console_inference_body_always_carries_a_client_request_id_the_host_accepts() + { + var snapshot = Covenant.Ui.Logic.RequestSnapshot.Freeze(1, new Covenant.Ui.Logic.PlaygroundForm { ApplicationId = "demo-app", Prompt = "Reply OK." }, Created); + var body = JsonSerializer.Serialize(new UiModels.PlaygroundRequestDto + { + ApplicationId = "demo-app", Messages = [new UiModels.ChatMessageDto { Role = "user", Content = "Reply OK." }], MaxTokens = 256, Stream = true, + ClientRequestId = snapshot.ClientRequestId, + }, UiModels.UiJsonContext.Default.PlaygroundRequestDto); + var host = JsonSerializer.Deserialize(body, CovenantJsonContext.Default.PlaygroundRequest)!; + Assert.Null(PlaygroundApi.Validate(host)); // required since review round 2 (B7) + Assert.Equal(snapshot.ClientRequestId, host.ClientRequestId); + Assert.True(PlaygroundApi.IsValidClientRequestId(host.ClientRequestId)); + Assert.Equal(256, host.MaxTokens); + Assert.True(host.Stream); + } + + [Fact] + public void Probe_evidence_and_kill_switch_reach_the_console() + { + var probe = JsonSerializer.Deserialize(JsonSerializer.Serialize(new ProbeResult + { + Allowed = true, Reachable = true, HttpStatus = 200, Models = ["qwen2.5-coder:7b"], Error = null, DurationMs = 12.5, Endpoint = "http://localhost:11434/v1/", CheckedUtc = Created, + }, CovenantJsonContext.Default.ProbeResult), UiModels.UiJsonContext.Default.ProbeResponse)!; + Assert.True(probe.Allowed); + Assert.True(probe.Reachable); + Assert.Equal(200, probe.HttpStatus); + Assert.Equal(new[] { "qwen2.5-coder:7b" }, probe.Models); + Assert.Equal(12.5, probe.DurationMs); + Assert.Equal("http://localhost:11434/v1/", probe.Endpoint); + Assert.Equal(Created, probe.CheckedUtc); + + var ev = JsonSerializer.Deserialize(JsonSerializer.Serialize(new EvidenceReport + { + GeneratedUtc = Created, AuditLogPath = "/var/covenant/audit.jsonl", ChainValid = false, ChainFailure = "hash mismatch", FirstInvalidLine = 4, + Entries = 10, Events = 2, Allowed = 7, Denied = 3, FirstEntryUtc = Created, LastEntryUtc = Created.AddHours(1), TotalCostUsd = 0.5m, + CostByTeamUsd = new() { ["payments"] = 0.5m }, RequestsByClassification = new() { ["Pii"] = 4 }, AnchorConfigured = true, AnchorCount = 3, LastAnchorUtc = Created, + }, CovenantJsonContext.Default.EvidenceReport), UiModels.UiJsonContext.Default.EvidenceReport)!; + Assert.Equal(Created, ev.GeneratedUtc); + Assert.Equal("/var/covenant/audit.jsonl", ev.AuditLogPath); + Assert.False(ev.ChainValid); + Assert.Equal("hash mismatch", ev.ChainFailure); + Assert.Equal(4, ev.FirstInvalidLine); + Assert.Equal(10, ev.Entries); + Assert.Equal(2, ev.Events); + Assert.Equal(7, ev.Allowed); + Assert.Equal(3, ev.Denied); + Assert.Equal(0.5m, ev.TotalCostUsd); + Assert.Equal(0.5m, ev.CostByTeamUsd["payments"]); + Assert.Equal(4, ev.RequestsByClassification["Pii"]); + Assert.True(ev.AnchorConfigured); + Assert.Equal(3, ev.AnchorCount); + Assert.Equal(Created, ev.LastAnchorUtc); + + var ks = JsonSerializer.Deserialize(JsonSerializer.Serialize(new KillSwitchState { Engaged = true, Reason = "paused from console" }, CovenantJsonContext.Default.KillSwitchState), + UiModels.UiJsonContext.Default.KillSwitchState)!; + Assert.True(ks.Engaged); + Assert.Equal("paused from console", ks.Reason); + var reset = JsonSerializer.Deserialize(JsonSerializer.Serialize(new ResetResponse { ArchivedTo = "/var/covenant/audit.jsonl.20261017-120000.archived" }, CovenantJsonContext.Default.ResetResponse), + UiModels.UiJsonContext.Default.ResetResponse)!; + Assert.Equal("/var/covenant/audit.jsonl.20261017-120000.archived", reset.ArchivedTo); } private static JsonElement Wire(string json) diff --git a/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs b/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs index 569894a..d84e4da 100644 --- a/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs +++ b/tests/Covenant.Tests/CorrelationAndEvidenceTests.cs @@ -733,7 +733,7 @@ await sink.EnqueueAsync(new AuditEntry("req_v2b", DateTimeOffset.Parse("2026-10- Assert.Equal("estimated_failed_call", entries[2].CostBasis); var ledger = new InMemorySpendLedger(); - LedgerReplay.Rebuild(entries, ledger); + Covenant.Host.LedgerReplay.Rebuild(entries, ledger); Assert.Equal(0.002m + 0.01m + 0.0005m, ledger.GlobalSpendUsd); Assert.Equal(0.002m, ledger.TeamSpendUsd("legacy-team")); Assert.Equal(0.0105m, ledger.TeamSpendUsd("v2-team")); // the estimated failed-call charge replays diff --git a/tests/Covenant.Tests/ReviewRound2Tests.cs b/tests/Covenant.Tests/ReviewRound2Tests.cs index 4b3ed89..3ecf11c 100644 --- a/tests/Covenant.Tests/ReviewRound2Tests.cs +++ b/tests/Covenant.Tests/ReviewRound2Tests.cs @@ -2,6 +2,7 @@ using System.Net.Http.Headers; using System.Text; using System.Text.Json; +using Covenant.Adapters; using Covenant.Core; using Covenant.Governance; using Covenant.Host; From 2a7d5e522849c457c0e14e125fb5c384dac998db Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Sat, 17 Oct 2026 10:30:27 -0400 Subject: [PATCH 11/14] feat(ui): applications & workload profiles editor; trace 5x2 at <=1440; final classification facts; 'Evidence recorded' wording; prose to details (UI round 3) --- docs/console-v2-progress.md | 23 ++ .../Components/ProfilesEditor.razor | 348 ++++++++++++++++++ .../Components/RequestComposer.razor | 33 +- src/Covenant.Ui/Components/RunDetails.razor | 4 +- src/Covenant.Ui/Components/RunSummary.razor | 9 +- src/Covenant.Ui/Components/TraceBar.razor | 32 +- src/Covenant.Ui/Logic/ConfigDraft.cs | 6 + src/Covenant.Ui/Logic/ModelFacts.cs | 41 ++- src/Covenant.Ui/Logic/ProfileEditing.cs | 250 +++++++++++++ src/Covenant.Ui/Pages/Playground.razor | 5 +- src/Covenant.Ui/Pages/Policies.razor | 26 +- src/Covenant.Ui/Pages/Settings.razor | 11 + src/Covenant.Ui/Services/PlaygroundState.cs | 9 +- src/Covenant.Ui/Services/RunText.cs | 10 +- src/Covenant.Ui/wwwroot/css/app.css | 44 ++- tests/Covenant.Tests/ConsoleLogicTests.cs | 223 +++++++++++ .../Covenant.Tests/ContractRoundTripTests.cs | 78 ++++ 17 files changed, 1111 insertions(+), 41 deletions(-) create mode 100644 src/Covenant.Ui/Components/ProfilesEditor.razor create mode 100644 src/Covenant.Ui/Logic/ProfileEditing.cs diff --git a/docs/console-v2-progress.md b/docs/console-v2-progress.md index a06e32e..0193d14 100644 --- a/docs/console-v2-progress.md +++ b/docs/console-v2-progress.md @@ -966,3 +966,26 @@ dotnet build Covenant.sln -c Release --disable-build-servers dotnet test tests/Covenant.Tests -c Release --disable-build-servers --filter "FullyQualifiedName~ContractRoundTripTests|FullyQualifiedName~SubmissionPollTests|FullyQualifiedName~LiveTraceStartTests|FullyQualifiedName~PolicyEditingTests|FullyQualifiedName~RoundTwoCostAndFactsTests|FullyQualifiedName~RequestPagingTests|FullyQualifiedName~HeaderLocalHealthTests|FullyQualifiedName~SegmentScopeTests|FullyQualifiedName~ShellStatusTests|FullyQualifiedName~TraceModelTests" dotnet test tests/Covenant.Tests -c Release --disable-build-servers ``` + +## Review fixes round 3 (UI) — 2026-10-17 + +Source: `docs/verification-2026-10-16/v2/CODEX-REVIEW.txt` (round-2 browser items, `round2-presentation-1280-light.png`, +`round2-live-trace.png`). Not compiled here (no SDK in this environment). New pure logic: `Logic/ProfileEditing.cs`; +new component `Components/ProfilesEditor.razor`. + +| # | Finding | Fix | Test(s) | Browser verification step | +|---|---|---|---|---| +| R3-1 | No way to create workload profiles or edit application grants/defaults in the console | Policies → new section **Applications & workload profiles** (`#applications`, linked from Settings). Profiles: list (id, name, baseline, description, granted to / default of / named by policy), Create profile (id, name, baseline Public/Internal/PII/PHI, description), edit name/description/baseline, Remove (impact list first; refused client-side while it is an application's default — "choose another default first" — or a policy's ONLY profile, because dropping it would widen that policy to every profile). Applications (existing only; keys are startup secrets): team, enabled, console testing, granted profiles (checkboxes; the default cannot be unchecked), default profile (granted only, or none → built-in `legacy-internal`/Internal), max output tokens (≥ 1). One line + "About profiles and applications" details: baseline is server-side, detection only escalates, Playground offers only granted profiles, no client-side classification control. Same draft → Preview impact → If-Match Save & apply → new version; Host field errors shown inline (`profiles[i]`, `applications[i]` claimed). | `ProfileEditingTests.*` (create/validate, name/baseline edits, default-profile removal refused, only-profile-of-policy refused, removal impact + cleanup, grant/default consistency, team/output bound, labels); `ContractRoundTripTests.Profile_and_grant_edits_made_by_the_console_pass_host_validation`, `…Console_and_host_agree_that_a_default_profile_must_be_granted` (console draft → PUT body → Host `ConfigValidator`) | Policies → Edit → Create profile `support` (Public) → Add → preview valid → grant it to the test app, make it the default → Preview → Save & apply (new version) → Playground: the profile select now offers `support`; try Remove on the default profile → explanation, no remove button; Settings → "Open under Policies" scrolls to the section. | +| R3-2 | Trace bar with 10 columns at 1280 clipped Attribution and every duration | `.trace` is a CSS container; `.trace-steps` is a 5×2 grid by default; one row of 10 only when the viewport is > 1440 px AND the trace container ≥ 1200 px. State and duration are separate lines (`.trace-meta` / `.trace-dur`); narrow containers (< 640 px, e.g. the normal Playground pane) drop the icon column; the chip `title` carries "Stage · State · duration". | — (CSS/markup) | Presentation 1280×720 light and dark: two rows of five, "Attribution" and each duration fully visible; 1920×1080: one row of ten; normal Playground at 1280: 5×2 with durations visible. | +| R3-3 | Final classification missing from result facts | `ModelFacts.ClassificationFact`: "PII (baseline Public, escalated: US SSN pattern)", "Internal (baseline Internal, not escalated)", "Not evaluated — stopped at …", baseline-not-recorded variants; from the audit record only. Shown as a full-width **Classification** fact in the Playground result and presentation mode (and the details drawer). | `ClassificationFactTests.*` | Run preset B (synthetic SSN) as a Public-baseline profile → result and presentation show "PII (baseline Public, escalated: US SSN pattern)" without opening the drawer. | +| R3-4 | "Evidence verified — record found" conflated existence with integrity | Playground/presentation/drawer now say **Evidence recorded** (drawer adds "chain integrity is verified under Audit & evidence"). "Audit integrity verified" remains only on Audit & evidence, where chain verification runs. (Header "Chain verified" is the Host's status chain check, unchanged.) | — | Run any request → Evidence fact reads "Evidence recorded"; Audit & evidence still shows "Audit integrity verified". | +| R3-5 | Composer spent many lines on identity/retention diagnostics | "Run as" help only shows problems/loading; identity and baseline sentences moved to tooltips and an "About this" `
    ` under the selectors (also holds "response text stays in this tab's memory"); the Playground's separate retention note removed. | — | Playground at 1280×720: prompt area visibly taller; "About this" expands with the four explanations. | +| R3-6 | (Codex 137) Preset warning lingered; presentation showed an old result next to an edited prompt; cache provenance lacked the connection | `PlaygroundState`: preset note cleared on app/profile change and when a manual edit leaves the preset. Presentation shows "Previous result — the prompt has changed since. Run to update." Cache destination/served text uses `ServedConnectionId` + model (`ModelFacts.CacheOrigin`). | `ClassificationFactTests.Cache_provenance_uses_the_served_connection_when_the_model_lacks_it` | Preset B on an app without a Public profile → warning → change profile → warning gone; presentation: edit prompt after a run → marker appears; repeat a cached request → "Cache — no provider call (originally local/stub-slow)". | + +### Verifier commands (not executed here) + +``` +dotnet build Covenant.sln -c Release --disable-build-servers +dotnet test tests/Covenant.Tests -c Release --disable-build-servers --filter "FullyQualifiedName~ProfileEditingTests|FullyQualifiedName~ClassificationFactTests|FullyQualifiedName~ContractRoundTripTests|FullyQualifiedName~PolicyEditingTests|FullyQualifiedName~ModelFacts" +dotnet test tests/Covenant.Tests -c Release --disable-build-servers +``` diff --git a/src/Covenant.Ui/Components/ProfilesEditor.razor b/src/Covenant.Ui/Components/ProfilesEditor.razor new file mode 100644 index 0000000..b9f6b6f --- /dev/null +++ b/src/Covenant.Ui/Components/ProfilesEditor.razor @@ -0,0 +1,348 @@ +@inject ConfigEditor Editor + +@* Review round 3: "Applications & workload profiles" under Policies. Minimal — no enterprise IAM. Profiles: list, create, + edit name/description/baseline, remove (impact first; refused while an application's default or a policy's only + profile). Applications: EXISTING ones only (keys are startup secrets) — team, enabled, console testing, granted profiles, + default profile (must be granted), max output tokens. Every change edits the shared "policies" DRAFT; Preview impact → + Save & apply via ConfigEditor (If-Match). The baseline is server configuration; there is no client-side classification + control anywhere in the console. Pure rules: Logic/ProfileEditing.cs; the Host's validation stays authoritative. *@ + +
    +
    +

    Applications & workload profiles

    + @(Editing ? "Editing the draft" : "Read-only — choose Edit above") +
    +
    + Each profile carries a server-side trusted baseline; detection can only escalate it. The Playground offers only the profiles granted to the chosen application. +
    + About profiles and applications +
      +
    • @ProfileEditing.BaselineExplained
    • +
    • @ProfileEditing.PlaygroundExplained
    • +
    • @ProfileEditing.ApplicationsExplained
    • +
    • A request without a profile uses the application's default profile, or the built-in @ProfileEditing.LegacyInternal (baseline Internal) when none is set.
    • +
    • The console checks grants and defaults before you preview; the Host's validation on Preview impact and Save & apply is authoritative.
    • +
    +
    +
    + + @* ---- Workload profiles ---- *@ +
    +

    Workload profiles

    + @if (Editing && _newProfile is null) + { + + } +
    + @if (Editing && _newProfile is { } np) + { + var npProblems = ProfileEditing.Problems(np, Cfg); +
    +

    New workload profile (draft)

    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + A new profile is granted to no application; grant it below. + @if (npProblems.Count > 0) + { +
      + @foreach (var pp in npProblems) {
    • @pp
    • } +
    + } +
    + + +
    +
    + } + @if (Cfg.Profiles.Count == 0) + { +
    No workload profiles are declared. Requests run with the built-in @ProfileEditing.LegacyInternal profile (baseline Internal).
    + } +
      + @foreach (var p in Cfg.Profiles) + { + var prof = p; + var pi = Cfg.Profiles.IndexOf(prof); + var usage = ProfileEditing.Usage(Cfg, prof.Id); + var key = "p:" + prof.Id; +
    • +
      +
      + @(string.IsNullOrWhiteSpace(prof.Name) ? prof.Id : prof.Name) + @prof.Id · @("baseline " + PolicyText.ClassificationLabel(prof.Baseline) + (string.IsNullOrWhiteSpace(prof.Description) ? "" : " · " + prof.Description)) +
      + @if (Editing) + { + + } +
      + + Granted to: @(usage.GrantedTo.Count == 0 ? "no application" : string.Join(", ", usage.GrantedTo)) + @if (usage.DefaultOf.Count > 0) + { + · default of @string.Join(", ", usage.DefaultOf) + } + @if (usage.ScopedPolicies.Count > 0) + { + · named by policy @string.Join(", ", usage.ScopedPolicies) + } + + @if (Editing && _removeAsk == prof.Id) + { + var blockers = ProfileEditing.RemovalBlockers(Cfg, prof.Id); +
      +
      + @(blockers.Count > 0 ? "Profile " + prof.Id + " cannot be removed yet" : "Remove profile " + prof.Id + " from the draft?") +
        + @foreach (var line in blockers.Count > 0 ? blockers : ProfileEditing.RemovalImpact(Cfg, prof.Id)) {
      • @line
      • } +
      + @if (blockers.Count == 0) + { + The Host's impact preview runs right after; nothing is applied until Save & apply. + } +
      +
      + @if (blockers.Count == 0) + { + + } + +
      +
      + } + @if (Editing) + { +
      +
      + + +
      +
      + + + Server-side; detection can only raise it. +
      +
      + + +
      +
      + } + @if (_errors.TryGetValue(key, out var perr)) + { + @perr + } + +
    • + } +
    + + @* ---- Applications (existing only) ---- *@ +
    +

    Applications

    + Existing applications only — keys are startup secrets (Auth:Keys). +
    + @if (Cfg.Applications.Count == 0) + { +
    No applications are configured. Applications and their keys are defined at startup.
    + } +
      + @foreach (var a in Cfg.Applications) + { + var app = a; + var ai = Cfg.Applications.IndexOf(app); + var key = "a:" + app.Id; + var appProblems = ProfileEditing.ApplicationProblems(app, Cfg); +
    • +
      +
      + @app.Id + team @app.Team · max output @(app.MaxOutputTokens?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "server default") tokens +
      + + +
      + @if (!Editing) + { + Granted: @(app.GrantedProfiles.Count == 0 ? "no profile" : string.Join(", ", app.GrantedProfiles.Select(g => ProfileEditing.Label(Cfg, g)))) + Default: @ProfileEditing.DefaultText(Cfg, app) + } + else + { +
      +
      + + +
      +
      + + +
      +
      + + + Only granted profiles can be the default. +
      +
      +
      + + +
      +
      + Granted profiles + @foreach (var g in ProfileEditing.GrantOptions(Cfg, app)) + { + var gid = g; + var isDefault = string.Equals(app.DefaultProfile, gid, StringComparison.Ordinal); + + } +
      + } + @if (_errors.TryGetValue(key, out var aerr)) + { + @aerr + } + @if (Editing && appProblems.Count > 0) + { +
        + @foreach (var ap in appProblems) {
      • @ap
      • } +
      + } + +
    • + } +
    +
    + +@code { + /// The configuration shown: the draft while editing, else the applied one. + [Parameter, EditorRequired] public CovenantConfigDto Cfg { get; set; } = default!; + /// True while the Policies page owns the draft. + [Parameter] public bool Editing { get; set; } + + private readonly Dictionary _errors = new(StringComparer.Ordinal); + private NewProfileForm? _newProfile; + private string? _removeAsk; + + private void StartCreate() + { + _newProfile = new NewProfileForm { Id = ProfileEditing.UniqueId("profile", Cfg), Baseline = "Internal" }; + _removeAsk = null; + } + + private async Task AddProfileAsync(NewProfileForm f) + { + if (!Editing || Editor.Draft is not { } d) return; + if (ProfileEditing.Add(d, f).Count > 0) return; + _newProfile = null; + Editor.Touch(); + await Editor.ValidateAsync(); + } + + private void AskRemove(string profileId) + { + _removeAsk = profileId; + _newProfile = null; + } + + private async Task RemoveProfileAsync(string profileId) + { + _removeAsk = null; + if (!Editing || Editor.Draft is not { } d) return; + if (ProfileEditing.Remove(d, profileId) is { } problem) + { + _errors["p:" + profileId] = problem; + return; + } + _errors.Remove("p:" + profileId); + Editor.Touch(); + await Editor.ValidateAsync(); + } + + private void SetName(WorkloadProfileDto p, ChangeEventArgs e) => Result("p:" + p.Id, ProfileEditing.SetName(p, e.Value?.ToString())); + + private void SetBaseline(WorkloadProfileDto p, ChangeEventArgs e) => Result("p:" + p.Id, ProfileEditing.SetBaseline(p, e.Value?.ToString())); + + private void SetDescription(WorkloadProfileDto p, ChangeEventArgs e) + { + ProfileEditing.SetDescription(p, e.Value?.ToString()); + Result("p:" + p.Id, null); + } + + private void SetTeam(ApplicationDto a, ChangeEventArgs e) => Result("a:" + a.Id, ProfileEditing.SetTeam(a, e.Value?.ToString())); + + private void SetMax(ApplicationDto a, ChangeEventArgs e) + { + int? value = int.TryParse(e.Value?.ToString(), System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var n) ? n : null; + Result("a:" + a.Id, ProfileEditing.SetMaxOutputTokens(a, value)); + } + + private void SetDefault(ApplicationDto a, ChangeEventArgs e) => Result("a:" + a.Id, ProfileEditing.SetDefault(a, e.Value?.ToString())); + + private void SetGrant(ApplicationDto a, string profileId, ChangeEventArgs e) + => Result("a:" + a.Id, ProfileEditing.SetGrant(a, profileId, e.Value is bool b && b, Cfg)); + + private void SetEnabled(ApplicationDto a, ChangeEventArgs e) + { + a.Enabled = e.Value is bool b && b; + Result("a:" + a.Id, null); + } + + private void SetConsoleTesting(ApplicationDto a, ChangeEventArgs e) + { + a.ConsoleTesting = e.Value is bool b && b; + Result("a:" + a.Id, null); + } + + /// Null = the edit was applied to the draft (preview becomes stale); otherwise the refusal is shown and the + /// draft is untouched. + private void Result(string key, string? error) + { + if (!Editing) return; + if (error is null) + { + _errors.Remove(key); + Editor.Touch(); + } + else _errors[key] = error; + } +} diff --git a/src/Covenant.Ui/Components/RequestComposer.razor b/src/Covenant.Ui/Components/RequestComposer.razor index bb8dc21..7088289 100644 --- a/src/Covenant.Ui/Components/RequestComposer.razor +++ b/src/Covenant.Ui/Components/RequestComposer.razor @@ -13,20 +13,25 @@
    - @AppHelp + @if (AppHelp is { } ah) + { + @ah + }
    @{ var app = ComposerRules.Find(Ws.Applications, Pg.Form.ApplicationId); var granted = ComposerRules.GrantedProfiles(app); } - Trusted baseline set by the server; detection can only escalate it.
    + @if (!Compact) + { + @* Review round 3: identity/retention explanations live here (and in tooltips), not as repeated lines in the flow. *@ +
    + About this +
      +
    • Identity and team come from the selected application; its credential never reaches the browser. The admin token runs the request as that application.
    • +
    • Only profiles granted to the application are offered. Each profile's baseline is a trusted, server-side classification; detection can only escalate it. There is no client-side classification control.
    • +
    • Response text is console-only: kept in this tab's memory, never persisted. The audit record holds a prompt fingerprint, not the response.
    • +
    • Grants, defaults and baselines are edited under Policies → Applications & workload profiles.
    • +
    +
    + }
    Presets @@ -164,15 +181,17 @@ } } - private string AppHelp + /// Only a problem or a loading state is shown under "Run as"; the identity explanation is a tooltip and + /// part of "About this" (review round 3). + private string? AppHelp { get { if (Ws.ApplicationsError is { } e) return e; if (Ws.Applications is null) return Ws.Loading ? "Loading test applications…" : "Test applications not loaded."; if (!Ws.Applications.Any(a => ComposerRules.WhyNotSelectable(a) is null)) - return "No application is enabled for console testing (configure one under Settings / configuration)."; - return "Identity and team come from this application; its credential never reaches the browser."; + return "No application is enabled for console testing (allow it under Policies → Applications & workload profiles)."; + return null; } } diff --git a/src/Covenant.Ui/Components/RunDetails.razor b/src/Covenant.Ui/Components/RunDetails.razor index c5efdda..3a4603e 100644 --- a/src/Covenant.Ui/Components/RunDetails.razor +++ b/src/Covenant.Ui/Components/RunDetails.razor @@ -47,7 +47,7 @@

    Classification

    Trusted baseline
    @Fmt.OrNotRecorded(rec.BaselineClassification) @(rec.ProfileId is { Length: > 0 } rp ? "· profile " + rp : "")
    -
    Final classification
    @ModelFacts.Classification(rec)
    +
    Final classification
    @ModelFacts.ClassificationFact(rec)
    The profile sets a trusted baseline; the detector can only escalate it (ADR-0012). The detector is a narrow demonstration pattern set, not DLP.
    @@ -115,7 +115,7 @@ { case EvidenceState.Found when Run.Evidence.Record is { } er:
    -
    Status
    Verified — audit record found
    +
    Status
    Evidence recorded (chain integrity is verified under Audit & evidence)
    Record id
    diff --git a/src/Covenant.Ui/Components/RunSummary.razor b/src/Covenant.Ui/Components/RunSummary.razor index 5ee9276..94622e9 100644 --- a/src/Covenant.Ui/Components/RunSummary.razor +++ b/src/Covenant.Ui/Components/RunSummary.razor @@ -1,7 +1,8 @@ @inject WorkspaceConfig Ws -@* The compact outcome line under the response: outcome, actual destination (with Local/Cloud tag), duration, - tokens, cost basis and evidence state. The full facts live in the details drawer — not repeated here. *@ +@* The compact outcome line under the response: outcome, final classification (baseline → escalation, review round 3), + actual destination (with Local/Cloud tag), duration, tokens, cost basis and evidence state. The full facts live in the + details drawer — not repeated here. "Evidence recorded" = the audit record exists; integrity is verified on Audit & evidence. *@
    @if (Run.InFlight) @@ -29,6 +30,10 @@ @te }
    +
    +
    Classification
    +
    @RunText.Classification(Run)
    +
    Destination
    diff --git a/src/Covenant.Ui/Components/TraceBar.razor b/src/Covenant.Ui/Components/TraceBar.razor index 722dad1..04edd5b 100644 --- a/src/Covenant.Ui/Components/TraceBar.razor +++ b/src/Covenant.Ui/Components/TraceBar.razor @@ -2,7 +2,9 @@ state and server-measured duration; provider attempts are counted on the provider chip. Nothing is animated from configuration — a chip changes only when an event arrives. Skipped stages are drawn visibly different (dashed, "Skipped"). Clicking a chip opens a small popover with state, reason code, duration and attempts; - Escape closes it (and does not bubble, so presentation mode stays open). *@ + Escape closes it (and does not bubble, so presentation mode stays open). Review round 3: two rows of five stages up to + 1440 px (one row of ten only when wide — CSS container query); state and duration on separate lines so neither clips; + the chip's title carries the full text. *@
      @@ -13,10 +15,14 @@ var open = _open == s.Stage;
    1. } @@ -105,13 +111,17 @@ _ => "pending", }; - private static string Meta(TraceStepView s) - { - var state = TraceModel.StateText(s.State); - return s.DurationMs is { } d && s.State is not (TraceStepState.Pending or TraceStepState.Skipped or TraceStepState.NotReported) - ? state + " · " + Fmt.Ms(d) - : state; - } + private static string Name(TraceStepView s) + => s.Label + (s.Attempts.Count > 1 ? " ×" + s.Attempts.Count.ToString(System.Globalization.CultureInfo.InvariantCulture) : ""); + + /// Server-measured duration, only for a stage that actually ran. + private static string? Duration(TraceStepView s) + => s.DurationMs is { } d && s.State is not (TraceStepState.Pending or TraceStepState.Skipped or TraceStepState.NotReported) + ? Fmt.Ms(d) + : null; + + private static string ChipTitle(TraceStepView s) + => Name(s) + " · " + TraceModel.StateText(s.State) + (Duration(s) is { } d ? " · " + d : ""); private string SourceText { diff --git a/src/Covenant.Ui/Logic/ConfigDraft.cs b/src/Covenant.Ui/Logic/ConfigDraft.cs index b866cc3..b358506 100644 --- a/src/Covenant.Ui/Logic/ConfigDraft.cs +++ b/src/Covenant.Ui/Logic/ConfigDraft.cs @@ -255,6 +255,8 @@ public static bool Under(string? issuePath, string prefix) public static string Policy(int i) => "policies[" + I(i) + "]"; public static string Target(int p, int t) => Policy(p) + ".targets[" + I(t) + "]"; public static string Budget(int i) => "budgets[" + I(i) + "]"; + public static string Profile(int i) => "profiles[" + I(i) + "]"; + public static string Application(int i) => "applications[" + I(i) + "]"; public static string Setting(string name) => "settings." + name; private static string I(int i) => i.ToString(CultureInfo.InvariantCulture); @@ -284,6 +286,10 @@ public static class IssueHelp "Covenant could not build a provider client for this enabled connection (endpoint, secret or allow-list). Disable it or fix the cause above.", "ambiguous_policy_overlap" => "Two enabled policies at the same specificity cover the same classification/profile. Narrow one by profile or disable it — Covenant never picks an arbitrary winner.", + "default_profile_not_granted" => + "An application's default profile must also be granted to it. Grant it, or choose another default.", + "profile_not_found" => + "A grant, default or policy names a workload profile that does not exist. Create the profile, or remove the reference.", "missing_global_budget" => "A global budget is required: nothing is unlimited.", _ => null, diff --git a/src/Covenant.Ui/Logic/ModelFacts.cs b/src/Covenant.Ui/Logic/ModelFacts.cs index 00efaaf..716f5c1 100644 --- a/src/Covenant.Ui/Logic/ModelFacts.cs +++ b/src/Covenant.Ui/Logic/ModelFacts.cs @@ -34,7 +34,7 @@ public static string Attempted(AuditEntryView r) public static string Served(AuditEntryView r) { if (r.CacheHit) - return string.IsNullOrWhiteSpace(r.ServedByModel) ? FromCache : FromCache + " · " + r.ServedByModel; + return CacheOrigin(r) is { } origin ? FromCache + " · " + origin : FromCache; if (!string.IsNullOrWhiteSpace(r.ServedByModel)) return r.ServedByModel; return string.Equals(r.Effect, "Deny", StringComparison.OrdinalIgnoreCase) ? "None — not served" : NotRecorded; } @@ -50,6 +50,27 @@ public static string Classification(AuditEntryView r) return string.IsNullOrWhiteSpace(r.Signal) ? cls + " · no rule matched" : cls + " · " + r.Signal; } + /// The FINAL classification for the result facts (Playground + presentation mode, review round 3), with the + /// trusted baseline and whether detection escalated it — from the audit record only: + /// "PII (baseline Public, escalated: US SSN pattern)", "Internal (baseline Internal, not escalated)", + /// "Not evaluated — stopped at Authentication". Never inferred from the request or the profile alone. + public static string ClassificationFact(AuditEntryView r) + { + if (r.ClassificationEvaluated is null) return NotRecorded; + if (r.ClassificationEvaluated == false) + return "Not evaluated — stopped at " + PipelineStages.Label(r.StoppedAtStage); + if (string.IsNullOrWhiteSpace(r.Classification)) return NotRecorded; + var final = PolicyText.ClassificationLabel(r.Classification); + var signal = string.IsNullOrWhiteSpace(r.Signal) ? null : r.Signal.Trim(); + if (string.IsNullOrWhiteSpace(r.BaselineClassification)) + return final + (signal is null ? " (no detector rule matched; baseline not recorded)" : " (detector: " + signal + "; baseline not recorded)"); + var baseline = PolicyText.ClassificationLabel(r.BaselineClassification); + bool escalated = PolicyText.ClassificationOrder(r.Classification) > PolicyText.ClassificationOrder(r.BaselineClassification); + if (escalated) + return final + " (baseline " + baseline + ", escalated" + (signal is null ? "" : ": " + signal) + ")"; + return final + " (baseline " + baseline + ", not escalated" + (signal is null ? "" : "; detector: " + signal) + ")"; + } + /// The connection's boundary ("Local"/"Cloud") from the configuration, or null when unknown. Pre-v2 /// "local" adapter ids count as Local. public static string? BoundaryOf(string? connectionId, IReadOnlyList? connections) @@ -68,8 +89,11 @@ public static DestinationView Destination(AuditEntryView r, IReadOnlyList 0 } attempts) { @@ -86,6 +110,17 @@ public static DestinationView Destination(AuditEntryView r, IReadOnlyList"connection/model" that produced a cached answer: ServedByModel when it already names the connection, + /// else ServedConnectionId + "/" + ServedByModel; null when neither is recorded. + public static string? CacheOrigin(AuditEntryView r) + { + var model = string.IsNullOrWhiteSpace(r.ServedByModel) ? null : r.ServedByModel.Trim(); + var conn = string.IsNullOrWhiteSpace(r.ServedConnectionId) ? null : r.ServedConnectionId.Trim(); + if (model is null) return conn; + if (conn is null || ConnectionPart(model) is not null) return model; + return conn + "/" + model; + } + /// "conn/model" → "conn"; "local:tag" (pre-v2) → "local"; otherwise null. public static string? ConnectionPart(string? model) { diff --git a/src/Covenant.Ui/Logic/ProfileEditing.cs b/src/Covenant.Ui/Logic/ProfileEditing.cs new file mode 100644 index 0000000..8c5830d --- /dev/null +++ b/src/Covenant.Ui/Logic/ProfileEditing.cs @@ -0,0 +1,250 @@ +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// The "Create workload profile" form (review round 3). Nothing here is applied: +/// puts the profile into the configuration DRAFT; the Host validates it on Preview impact and activates it on Save & apply. +public sealed class NewProfileForm +{ + public string Id { get; set; } = ""; + public string Name { get; set; } = ""; + /// Trusted baseline, wire spelling: Public | Internal | Pii | Phi. + public string Baseline { get; set; } = "Internal"; + public string Description { get; set; } = ""; +} + +/// One profile row of the editor: who is granted it, whose default it is, which policies are scoped to it. +public sealed record ProfileUsage(string ProfileId, IReadOnlyList GrantedTo, IReadOnlyList DefaultOf, IReadOnlyList ScopedPolicies); + +/// Draft-only edits of workload profiles and application grants (review round 3). Mirrors the Host's +/// rules (src/Covenant.Governance/ConfigValidation.cs — profiles/applications) so the draft the console builds passes +/// them; the Host's validation stays authoritative. The baseline is a SERVER-SIDE trusted classification: detection can +/// only escalate it, and the console never offers a client-side classification control. Applications are edited, never +/// created or deleted here: their keys are startup secrets (Auth:Keys). Pure. +public static class ProfileEditing +{ + /// The Host's implicit profile (PolicyEngineV2.LegacyInternalProfile, baseline Internal): always exists, + /// used when an application has no default profile. Not declared in profiles; never created or removed here. + public const string LegacyInternal = "legacy-internal"; + + /// Baselines in display order (contract spellings). + public static IReadOnlyList Baselines => PolicyEditing.AllClassifications; + + public const string BaselineExplained = + "The baseline is a trusted classification held in server configuration. The detector can only escalate it (e.g. a US SSN pattern raises Public to PII), never lower it."; + + public const string PlaygroundExplained = + "The Playground can only run with a profile granted to the chosen application; there is no client-side classification control."; + + public const string ApplicationsExplained = + "Applications are created at startup (their keys are startup secrets, Auth:Keys). Here you edit an existing application's team, state, console testing, profile grants and output bound."; + + public static bool IsDeclared(CovenantConfigDto cfg, string? id) + => id is not null && cfg.Profiles.Any(p => string.Equals(p.Id, id, StringComparison.Ordinal)); + + /// Declared, or the Host's implicit legacy-internal profile. + public static bool Exists(CovenantConfigDto cfg, string? id) + => string.Equals(id, LegacyInternal, StringComparison.Ordinal) || IsDeclared(cfg, id); + + public static WorkloadProfileDto? Find(CovenantConfigDto cfg, string? id) + => id is null ? null : cfg.Profiles.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.Ordinal)); + + public static ApplicationDto? FindApplication(CovenantConfigDto cfg, string? id) + => id is null ? null : cfg.Applications.FirstOrDefault(a => string.Equals(a.Id, id, StringComparison.Ordinal)); + + public static bool IsBaseline(string? b) => b is not null && Baselines.Contains(b, StringComparer.Ordinal); + + /// A free profile id derived from . + public static string UniqueId(string seed, CovenantConfigDto cfg) + => ConnectionRules.UniqueId(seed, cfg.Profiles.Select(p => p.Id).Append(LegacyInternal)); + + /// "Public tickets (baseline Public)"; the implicit profile is labelled as such. + public static string Label(CovenantConfigDto cfg, string id) + { + if (Find(cfg, id) is { } p) + return (string.IsNullOrWhiteSpace(p.Name) ? p.Id : p.Name) + " (baseline " + PolicyText.ClassificationLabel(p.Baseline) + ")"; + return string.Equals(id, LegacyInternal, StringComparison.Ordinal) + ? LegacyInternal + " (built-in, baseline Internal)" + : id + " (not configured)"; + } + + public static ProfileUsage Usage(CovenantConfigDto cfg, string profileId) => new( + profileId, + cfg.Applications.Where(a => a.GrantedProfiles.Contains(profileId, StringComparer.Ordinal)).Select(a => a.Id).ToList(), + cfg.Applications.Where(a => string.Equals(a.DefaultProfile, profileId, StringComparison.Ordinal)).Select(a => a.Id).ToList(), + cfg.Policies.Where(p => p.Profiles.Contains(profileId, StringComparer.Ordinal)).Select(p => p.Id).ToList()); + + // ---- profiles ---- + + /// Every reason the create form cannot be added to the draft (empty = ready). + public static IReadOnlyList Problems(NewProfileForm f, CovenantConfigDto cfg) + { + var p = new List(); + var id = f.Id.Trim(); + if (!ConnectionRules.IsValidId(id)) p.Add("Profile id must be 1–64 characters of letters, digits, '.', '_' or '-'."); + else if (string.Equals(id, LegacyInternal, StringComparison.Ordinal)) p.Add("'" + LegacyInternal + "' is the built-in profile; choose another id."); + else if (IsDeclared(cfg, id)) p.Add("A profile with id '" + id + "' already exists."); + if (string.IsNullOrWhiteSpace(f.Name)) p.Add("Enter a profile name."); + if (!IsBaseline(f.Baseline)) p.Add("Choose a baseline: Public, Internal, PII or PHI."); + return p; + } + + public static WorkloadProfileDto Build(NewProfileForm f) => new() + { + Id = f.Id.Trim(), + Name = f.Name.Trim(), + Baseline = f.Baseline, + Description = string.IsNullOrWhiteSpace(f.Description) ? null : f.Description.Trim(), + }; + + /// Adds the form's profile to . Returns the problems (draft untouched) or an empty list. + /// A new profile is granted to nobody: grant it to an application below. + public static IReadOnlyList Add(CovenantConfigDto draft, NewProfileForm f) + { + var problems = Problems(f, draft); + if (problems.Count == 0) draft.Profiles.Add(Build(f)); + return problems; + } + + /// Renames a profile. Refused (returns why, profile untouched) for a blank name. + public static string? SetName(WorkloadProfileDto profile, string? name) + { + if (string.IsNullOrWhiteSpace(name)) return "A profile needs a name."; + profile.Name = name.Trim(); + return null; + } + + public static void SetDescription(WorkloadProfileDto profile, string? description) + => profile.Description = string.IsNullOrWhiteSpace(description) ? null : description.Trim(); + + /// Changes the trusted baseline. Refused for anything but Public | Internal | Pii | Phi. + public static string? SetBaseline(WorkloadProfileDto profile, string? baseline) + { + if (!IsBaseline(baseline)) return "Choose a baseline: Public, Internal, PII or PHI."; + profile.Baseline = baseline; + return null; + } + + /// Why the profile cannot be removed from the draft (empty = removable). Removal is refused while it is an + /// application's default (choose another default first), and while a policy is scoped to it ALONE — dropping the + /// only profile from a policy would widen it to every profile, so re-scope or remove that policy first. + public static IReadOnlyList RemovalBlockers(CovenantConfigDto cfg, string profileId) + { + var b = new List(); + if (string.Equals(profileId, LegacyInternal, StringComparison.Ordinal)) + { + b.Add("The built-in profile cannot be removed."); + return b; + } + if (!IsDeclared(cfg, profileId)) + { + b.Add("Profile '" + profileId + "' is not in the draft."); + return b; + } + foreach (var app in cfg.Applications.Where(a => string.Equals(a.DefaultProfile, profileId, StringComparison.Ordinal))) + b.Add("It is the default profile of application '" + app.Id + "': choose another default for it first (requests without a profile would otherwise have no trusted baseline)."); + foreach (var pol in cfg.Policies.Where(p => p.Profiles.Count == 1 && string.Equals(p.Profiles[0], profileId, StringComparison.Ordinal))) + b.Add("Policy '" + pol.Id + "' applies only to this profile: removing the profile would widen that policy to every profile. Re-scope or remove the policy first."); + return b; + } + + /// What removing the profile changes in the draft (shown before the Host's impact preview). + public static IReadOnlyList RemovalImpact(CovenantConfigDto cfg, string profileId) + { + var lines = new List(); + var u = Usage(cfg, profileId); + foreach (var app in u.GrantedTo) + lines.Add("Application '" + app + "' loses the grant: it can no longer request this profile (the console Playground no longer offers it)."); + foreach (var pol in cfg.Policies.Where(p => p.Profiles.Count > 1 && p.Profiles.Contains(profileId, StringComparer.Ordinal))) + lines.Add("Policy '" + pol.Id + "' stops listing this profile; it still applies to " + string.Join(", ", pol.Profiles.Where(x => x != profileId)) + "."); + if (lines.Count == 0) lines.Add("No application is granted this profile and no policy names it: removing it changes no route."); + return lines; + } + + /// Removes the profile, its grants and its entries in multi-profile policies from the draft. Returns the + /// first blocker (draft untouched) or null. + public static string? Remove(CovenantConfigDto draft, string profileId) + { + if (RemovalBlockers(draft, profileId) is { Count: > 0 } blockers) return blockers[0]; + draft.Profiles.RemoveAll(p => string.Equals(p.Id, profileId, StringComparison.Ordinal)); + foreach (var app in draft.Applications) app.GrantedProfiles.RemoveAll(g => string.Equals(g, profileId, StringComparison.Ordinal)); + foreach (var pol in draft.Policies) pol.Profiles.RemoveAll(g => string.Equals(g, profileId, StringComparison.Ordinal)); + return null; + } + + // ---- applications (existing only) ---- + + /// Profiles an application's grant list can show: every declared profile, plus any id it is already + /// granted that is not declared (the built-in legacy-internal, or a dangling id the Host will reject). + public static IReadOnlyList GrantOptions(CovenantConfigDto cfg, ApplicationDto app) + => cfg.Profiles.Select(p => p.Id).Concat(app.GrantedProfiles).Distinct(StringComparer.Ordinal).ToList(); + + /// Grants or revokes a profile. Revoking the application's default is refused (choose another default + /// first); granting an unknown profile is refused. + public static string? SetGrant(ApplicationDto app, string profileId, bool granted, CovenantConfigDto cfg) + { + bool has = app.GrantedProfiles.Contains(profileId, StringComparer.Ordinal); + if (granted) + { + if (has) return null; + if (!Exists(cfg, profileId)) return "Profile '" + profileId + "' does not exist."; + app.GrantedProfiles.Add(profileId); + return null; + } + if (!has) return null; + if (string.Equals(app.DefaultProfile, profileId, StringComparison.Ordinal)) + return "'" + profileId + "' is the default profile of '" + app.Id + "': choose another default before revoking it."; + app.GrantedProfiles.RemoveAll(g => string.Equals(g, profileId, StringComparison.Ordinal)); + return null; + } + + /// Sets the default profile (null/empty = none: requests without a profile use the built-in + /// legacy-internal, baseline Internal). The default must already be granted. + public static string? SetDefault(ApplicationDto app, string? profileId) + { + if (string.IsNullOrWhiteSpace(profileId)) + { + app.DefaultProfile = null; + return null; + } + if (!app.GrantedProfiles.Contains(profileId, StringComparer.Ordinal)) + return "Grant '" + profileId + "' to '" + app.Id + "' before making it the default."; + app.DefaultProfile = profileId; + return null; + } + + public static string? SetTeam(ApplicationDto app, string? team) + { + if (string.IsNullOrWhiteSpace(team)) return "Team is required (attribution and team budgets use it)."; + app.Team = team.Trim(); + return null; + } + + /// The enforced output bound (≥ 1; sent to the provider and used for the budget reservation). + public static string? SetMaxOutputTokens(ApplicationDto app, int? value) + { + if (value is not { } v || v < 1) return "Max output tokens must be a whole number ≥ 1."; + app.MaxOutputTokens = v; + return null; + } + + /// Everything the Host would reject about an application's profile settings (empty = consistent). + public static IReadOnlyList ApplicationProblems(ApplicationDto app, CovenantConfigDto cfg) + { + var p = new List(); + if (string.IsNullOrWhiteSpace(app.Team)) p.Add("Team is required."); + foreach (var g in app.GrantedProfiles.Where(g => !Exists(cfg, g))) + p.Add("Granted profile '" + g + "' does not exist."); + if (app.DefaultProfile is { } d) + { + if (!Exists(cfg, d)) p.Add("Default profile '" + d + "' does not exist."); + else if (!app.GrantedProfiles.Contains(d, StringComparer.Ordinal)) p.Add("Default profile '" + d + "' is not granted."); + } + if (app.MaxOutputTokens is < 1) p.Add("Max output tokens must be ≥ 1."); + return p; + } + + /// What a request WITHOUT a profile resolves to for this application (Host ProfileResolution). + public static string DefaultText(CovenantConfigDto cfg, ApplicationDto app) + => app.DefaultProfile is { } d ? Label(cfg, d) : "None — requests without a profile use " + Label(cfg, LegacyInternal); +} diff --git a/src/Covenant.Ui/Pages/Playground.razor b/src/Covenant.Ui/Pages/Playground.razor index a4ae443..23d6fd4 100644 --- a/src/Covenant.Ui/Pages/Playground.razor +++ b/src/Covenant.Ui/Pages/Playground.razor @@ -59,6 +59,10 @@
      @ResponseBody(prun)
      + @if (!prun.InFlight && !prun.Snapshot.MatchesForm(Pg.Form)) + { + Previous result — the prompt has changed since. Run to update. + } } else @@ -135,7 +139,6 @@ else
      @ResponseBody(run)
      - Response text is console-only: kept in this tab's memory, never persisted. } diff --git a/src/Covenant.Ui/Pages/Policies.razor b/src/Covenant.Ui/Pages/Policies.razor index c5d2efc..50f5a2c 100644 --- a/src/Covenant.Ui/Pages/Policies.razor +++ b/src/Covenant.Ui/Pages/Policies.razor @@ -2,6 +2,8 @@ @inject AppState State @inject ConfigEditor Editor @inject WorkspaceConfig Ws +@inject NavigationManager Nav +@inject Interop Interop @implements IDisposable Policies · Covenant @@ -12,6 +14,8 @@ policy, remove one (impact shown first), edit classification/profile applicability, targets, order, pause/resume, retry, and "Split this policy" (Public → cloud + local fallback; Internal/PII/PHI → local). Every change edits the DRAFT only; Preview impact → Save & apply via ConfigEditor. Cloud targets are never offered for PII/PHI. Simulator = dry run. + Review round 3: "Applications & workload profiles" (Components/ProfilesEditor.razor, #applications) edits profiles and + existing applications' grants in the same draft. *@
      @@ -30,7 +34,7 @@
      + ViewHint="Viewing the applied routing. Edit to change targets, order, pauses, mode, profiles or application grants." /> @if (Editor.Current is not { } cfg) { @@ -422,6 +426,8 @@
    + + } @@ -451,7 +457,23 @@ private bool Editing => Editor.Editing && Editor.Owner == "policies"; private bool CanStartEdit => Editor.Applied is not null && !Editor.Saving && (!Editor.IsDirty || Editor.Owner == "policies"); - private IReadOnlyList ClaimedPaths => Editor.Current is { } c ? Enumerable.Range(0, c.Policies.Count).Select(IssueIndex.Policy).ToList() : []; + private IReadOnlyList ClaimedPaths => Editor.Current is { } c + ? Enumerable.Range(0, c.Policies.Count).Select(IssueIndex.Policy) + .Concat(Enumerable.Range(0, c.Profiles.Count).Select(IssueIndex.Profile)) + .Concat(Enumerable.Range(0, c.Applications.Count).Select(IssueIndex.Application)).ToList() + : []; + + // policies#applications (linked from Settings): focus the section once it has rendered (focus scrolls it into view). + private bool _anchorDone; + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (_anchorDone || Editor.Current is null) return; + _anchorDone = true; + if (!new Uri(Nav.Uri).Fragment.Equals("#applications", StringComparison.OrdinalIgnoreCase)) return; + try { await Interop.FocusElementAsync("applications"); } + catch (JSException) { /* best effort */ } + } protected override async Task OnInitializedAsync() { diff --git a/src/Covenant.Ui/Pages/Settings.razor b/src/Covenant.Ui/Pages/Settings.razor index 1b474b4..c64658b 100644 --- a/src/Covenant.Ui/Pages/Settings.razor +++ b/src/Covenant.Ui/Pages/Settings.razor @@ -93,6 +93,17 @@ } +
    +
    + + Server configuration · edited with the routing policies +
    +
    + Workload profiles (trusted baselines) and which existing applications may use them, their default profile, console testing and output bound. + Open under Policies +
    +
    +

    Console preferences

    diff --git a/src/Covenant.Ui/Services/PlaygroundState.cs b/src/Covenant.Ui/Services/PlaygroundState.cs index 6b2b881..caa153b 100644 --- a/src/Covenant.Ui/Services/PlaygroundState.cs +++ b/src/Covenant.Ui/Services/PlaygroundState.cs @@ -137,6 +137,7 @@ public bool SelectApplication(string? id) { if (Running) return false; var ok = ComposerRules.SelectApplication(Form, _workspace.Applications, id); + PresetNote = null; // the note was about the preset's own app/profile pick (review round 3) Notify(); return ok; } @@ -145,11 +146,17 @@ public bool SelectProfile(string? profileId) { if (Running) return false; var ok = ComposerRules.SelectProfile(Form, _workspace.Applications, profileId); + PresetNote = null; Notify(); return ok; } - public void NotifyFormChanged() => Notify(); + /// After a manual edit: a preset-specific note is dropped once the form no longer holds that preset. + public void NotifyFormChanged() + { + if (PresetNote is not null && !(ScenarioPresets.Find(Form.Scenario) is { } p && p.StillMatches(Form))) PresetNote = null; + Notify(); + } /// Runs the preset only if the form still holds it and nothing blocks Run (the explicit /// "Run preset" action on Overview). diff --git a/src/Covenant.Ui/Services/RunText.cs b/src/Covenant.Ui/Services/RunText.cs index 0bfd91e..d172305 100644 --- a/src/Covenant.Ui/Services/RunText.cs +++ b/src/Covenant.Ui/Services/RunText.cs @@ -27,15 +27,19 @@ public static string Tokens(PlaygroundRun run) public static string Cost(PlaygroundRun run) => run.Evidence.Record is { } rec ? CostText.Cost(rec) : AwaitingText(run); - /// Pending → Verified (record found) / Unavailable after the bounded retries. Never "verified" before - /// the record exists. + /// Final classification with baseline/escalation (review round 3) — from the audit record only. + public static string Classification(PlaygroundRun run) + => run.Evidence.Record is { } rec ? ModelFacts.ClassificationFact(rec) : AwaitingText(run); + + /// Pending → Recorded (record found) / Unavailable after the bounded retries. Finding the record is NOT an + /// integrity check: "verified" wording is reserved for Audit & evidence, where chain verification runs. public static (string Text, string Tone) Evidence(PlaygroundRun run) { if (run.InFlight) return ("Evidence after completion", "hollow"); return run.Evidence.State switch { EvidenceState.Pending => ("Evidence pending", "hollow"), - EvidenceState.Found => ("Evidence verified — record found", "ok"), + EvidenceState.Found => ("Evidence recorded", "ok"), EvidenceState.Unavailable => ("Evidence unavailable", "warn"), EvidenceState.Error => ("Evidence lookup failed", "bad"), _ => run.Outcome?.Outcome == DisplayOutcome.RejectedBeforeGovernance diff --git a/src/Covenant.Ui/wwwroot/css/app.css b/src/Covenant.Ui/wwwroot/css/app.css index a2cf4fb..b18ea97 100644 --- a/src/Covenant.Ui/wwwroot/css/app.css +++ b/src/Covenant.Ui/wwwroot/css/app.css @@ -340,19 +340,37 @@ details.tech[open] > summary { margin-bottom: 6px; } .run-facts > div { min-width: 0; display: flex; flex-direction: column; gap: 2px; } .run-facts dt { color: var(--muted); } .run-facts dd { overflow-wrap: anywhere; display: flex; flex-wrap: wrap; gap: 4px 6px; align-items: center; } +.run-facts > div.wide { grid-column: 1 / -1; } /* Trace bar */ -.trace { position: relative; display: flex; flex-direction: column; gap: 6px; min-width: 0; } -.trace-steps { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px; } -.trace-step { flex: 1 1 88px; min-width: 0; } +/* Review round 3: a 5×2 grid (two rows of five stages) by default, so Attribution and every duration stay visible at + 1280; one row of ten only on a wide viewport (> 1440 px) AND a wide trace container. State and duration are separate + lines; narrow containers drop the icon column (the state stays as text and colour). */ +.trace { position: relative; display: flex; flex-direction: column; gap: 6px; min-width: 0; container: trace / inline-size; } +.trace-steps { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 4px; } +.trace-step { min-width: 0; } .trace-chip { - width: 100%; display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto; column-gap: 6px; align-items: center; + width: 100%; height: 100%; display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto auto; column-gap: 6px; align-items: center; text-align: left; padding: 6px 8px; min-height: 44px; border-radius: var(--radius-control); border: 1px solid var(--border); background: var(--surface2); color: var(--text); font: inherit; cursor: pointer; } -.trace-chip .icon { grid-row: 1 / span 2; } +.trace-chip .icon { grid-row: 1 / span 3; } .trace-name { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -.trace-meta { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-family: var(--font-mono); } +.trace-meta, .trace-dur { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-family: var(--font-mono); } +.trace-dur { color: var(--text); } +@media (min-width: 1441px) { + @container trace (min-width: 1200px) { + .trace-steps { grid-template-columns: repeat(10, minmax(0, 1fr)); } + } +} +@container trace (max-width: 639px) { + .trace-chip { grid-template-columns: minmax(0, 1fr); padding: 6px; } + .trace-chip .icon { display: none; } + .trace-name { font-size: 12px; } +} +@container trace (max-width: 379px) { + .trace-steps { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} .trace-step.s-passed .trace-chip { border-color: transparent; background: var(--green-bg); } .trace-step.s-passed .icon, .trace-step.s-passed .trace-meta { color: var(--green); } .trace-step.s-refused .trace-chip { border-color: var(--amber); background: var(--amber-bg); } @@ -376,8 +394,7 @@ details.tech[open] > summary { margin-bottom: 6px; } } .trace-pop-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; } .trace-source { font-size: 12px; color: var(--subtle); } -.trace.compact .trace-step { flex-basis: 70px; } -.trace.compact .trace-meta { display: none; } +.trace.compact .trace-meta, .trace.compact .trace-dur { display: none; } .attempt-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; font-size: var(--text-secondary); } .attempt-list li { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: center; padding: 6px 8px; border: 1px solid var(--border); border-radius: var(--radius-control); } .state-text.s-passed { color: var(--green); } .state-text.s-failed { color: var(--red); } .state-text.s-refused { color: var(--amber); } @@ -416,6 +433,7 @@ details.tech[open] > summary { margin-bottom: 6px; } at most one scroll (the layer itself), plus the response's intentional scroll. ---- */ .present-root { position: fixed; inset: 0; z-index: 60; background: var(--bg); display: grid; grid-template-rows: auto minmax(0, 1fr); overflow: auto; } .present-root:focus { outline: none; } +.panel[tabindex="-1"]:focus { outline: none; } .present-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; padding: 8px 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; } @@ -435,7 +453,7 @@ details.tech[open] > summary { margin-bottom: 6px; } .present-response .outcome { font-size: 30px; } .present-response .run-facts { font-size: 16px; } .present-trace .trace-name { font-size: 15px; } -.present-trace .trace-meta { font-size: 13px; } +.present-trace .trace-meta, .present-trace .trace-dur { font-size: 13px; } /* ---- Requests ---- */ .filters { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; } @@ -600,3 +618,11 @@ details.panel > summary { cursor: pointer; font-weight: 600; min-height: 32px; d /* Policies: create-policy form (review round 2, U4). */ .policy-create { display: flex; flex-direction: column; gap: 10px; border-bottom: 1px solid var(--border); } .policy-create h3 { margin: 0; font-size: var(--text-body, 14px); } + +/* ---- Applications & workload profiles (Policies, review round 3) ---- */ +.sub-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 6px 12px; border-top: 1px solid var(--border); padding-top: 12px; padding-bottom: 4px; } +.sub-head h3 { margin: 0; font-size: var(--text-body, 14px); } +.profile-intro { display: flex; flex-direction: column; gap: 6px; padding-top: 0; } +.composer .about { font-size: var(--text-secondary); } +.composer .about summary { cursor: pointer; color: var(--muted); } +.composer .about ul { margin-top: 6px; } diff --git a/tests/Covenant.Tests/ConsoleLogicTests.cs b/tests/Covenant.Tests/ConsoleLogicTests.cs index 7eb7ffa..64bf31f 100644 --- a/tests/Covenant.Tests/ConsoleLogicTests.cs +++ b/tests/Covenant.Tests/ConsoleLogicTests.cs @@ -2365,3 +2365,226 @@ public void Not_configured_not_registered_and_unknown() LocalHealth.Derive(new CatalogResponse { Local = new LocalRouteInfo { Configured = true, Registered = false, ConnectionId = "ollama" } }, null).State); } } + +// ---- Review round 3 (UI) ---- + +public sealed class ClassificationFactTests +{ + private static AuditEntryView With(string classification, string? baseline, string? signal) + { + var r = Rec.V2(classification: classification, signal: signal); + r.BaselineClassification = baseline; + return r; + } + + [Fact] + public void Escalation_names_baseline_and_detector() + => Assert.Equal("PII (baseline Public, escalated: US SSN pattern)", ModelFacts.ClassificationFact(With("Pii", "Public", "US SSN pattern"))); + + [Fact] + public void Escalation_without_a_recorded_signal_still_says_escalated() + => Assert.Equal("PHI (baseline Internal, escalated)", ModelFacts.ClassificationFact(With("Phi", "Internal", null))); + + [Fact] + public void Same_as_baseline_is_not_escalated() + { + Assert.Equal("Internal (baseline Internal, not escalated)", ModelFacts.ClassificationFact(With("Internal", "Internal", null))); + Assert.Equal("PII (baseline PII, not escalated; detector: US SSN pattern)", ModelFacts.ClassificationFact(With("Pii", "Pii", "US SSN pattern"))); + } + + [Fact] + public void Missing_baseline_is_said_not_guessed() + { + Assert.Equal("PII (detector: US SSN pattern; baseline not recorded)", ModelFacts.ClassificationFact(With("Pii", null, "US SSN pattern"))); + Assert.Equal("Internal (no detector rule matched; baseline not recorded)", ModelFacts.ClassificationFact(With("Internal", null, null))); + } + + [Fact] + public void Not_evaluated_and_legacy_records_never_show_the_restrictive_default_as_a_detection() + { + Assert.StartsWith("Not evaluated — stopped at", ModelFacts.ClassificationFact(Rec.AuthFail()), StringComparison.Ordinal); + Assert.DoesNotContain("PHI", ModelFacts.ClassificationFact(Rec.AuthFail()), StringComparison.Ordinal); + Assert.Equal(ModelFacts.NotRecorded, ModelFacts.ClassificationFact(Rec.Legacy())); + } + + [Fact] + public void Cache_provenance_uses_the_served_connection_when_the_model_lacks_it() + { + var r = Rec.V2(cacheHit: true, attempted: null, served: "stub-slow"); + r.ServedConnectionId = "local"; + Assert.Equal("local/stub-slow", ModelFacts.CacheOrigin(r)); + Assert.Equal("Cache — no provider call (originally local/stub-slow)", ModelFacts.Destination(r).Text); + Assert.Equal("Served from cache (no provider call) · local/stub-slow", ModelFacts.Served(r)); + + var full = Rec.V2(cacheHit: true, attempted: null, served: "ollama/qwen"); + full.ServedConnectionId = "ollama"; + Assert.Equal("ollama/qwen", ModelFacts.CacheOrigin(full)); + Assert.Null(ModelFacts.CacheOrigin(Rec.V2(cacheHit: true, attempted: null, served: null))); + } +} + +public sealed class ProfileEditingTests +{ + /// Hybrid config + two profiles and two existing applications (demo grants both, default internal). + private static CovenantConfigDto WithProfiles() + { + var cfg = Cfg.Hybrid(); + cfg.Profiles = + [ + new WorkloadProfileDto { Id = "public-demo", Name = "Public demo", Baseline = "Public" }, + new WorkloadProfileDto { Id = "internal-default", Name = "Internal", Baseline = "Internal" }, + ]; + cfg.Applications = + [ + new ApplicationDto { Id = "demo", Team = "payments", Enabled = true, ConsoleTesting = true, GrantedProfiles = ["public-demo", "internal-default"], DefaultProfile = "internal-default", MaxOutputTokens = 256 }, + new ApplicationDto { Id = "batch", Team = "risk", Enabled = true, ConsoleTesting = false, GrantedProfiles = ["internal-default"], DefaultProfile = "internal-default" }, + ]; + return cfg; + } + + [Fact] + public void Create_profile_validates_id_name_baseline_and_is_granted_to_nobody() + { + var cfg = WithProfiles(); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = "bad id!", Name = "x", Baseline = "Public" }, cfg), p => p.Contains("Profile id", StringComparison.Ordinal)); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = "public-demo", Name = "x", Baseline = "Public" }, cfg), p => p.Contains("already exists", StringComparison.Ordinal)); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = ProfileEditing.LegacyInternal, Name = "x", Baseline = "Internal" }, cfg), p => p.Contains("built-in", StringComparison.Ordinal)); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = "p", Name = " ", Baseline = "Public" }, cfg), p => p.Contains("name", StringComparison.Ordinal)); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = "p", Name = "x", Baseline = "Secret" }, cfg), p => p.Contains("baseline", StringComparison.Ordinal)); + Assert.Contains(ProfileEditing.Problems(new NewProfileForm { Id = "p", Name = "x", Baseline = "pii" }, cfg), p => p.Contains("baseline", StringComparison.Ordinal)); // contract spelling only + + var before = ConfigCopy.Canonical(cfg); + Assert.NotEmpty(ProfileEditing.Add(cfg, new NewProfileForm { Id = "", Name = "x" })); + Assert.Equal(before, ConfigCopy.Canonical(cfg)); // refused ⇒ draft untouched + + Assert.Empty(ProfileEditing.Add(cfg, new NewProfileForm { Id = " customer-pii ", Name = " Customer PII ", Baseline = "Pii", Description = " " })); + var added = cfg.Profiles[^1]; + Assert.Equal("customer-pii", added.Id); + Assert.Equal("Customer PII", added.Name); + Assert.Equal("Pii", added.Baseline); + Assert.Null(added.Description); + Assert.Empty(ProfileEditing.Usage(cfg, "customer-pii").GrantedTo); + Assert.NotEqual("customer-pii", ProfileEditing.UniqueId("customer-pii", cfg)); + } + + [Fact] + public void Edit_name_and_baseline_refuse_blank_or_unknown_values() + { + var cfg = WithProfiles(); + var p = cfg.Profiles[0]; + Assert.NotNull(ProfileEditing.SetName(p, " ")); + Assert.Equal("Public demo", p.Name); + Assert.Null(ProfileEditing.SetName(p, " Public tickets ")); + Assert.Equal("Public tickets", p.Name); + Assert.NotNull(ProfileEditing.SetBaseline(p, "Confidential")); + Assert.Equal("Public", p.Baseline); + Assert.Null(ProfileEditing.SetBaseline(p, "Internal")); + Assert.Equal("Internal", p.Baseline); + ProfileEditing.SetDescription(p, " "); + Assert.Null(p.Description); + } + + [Fact] + public void Removing_a_default_profile_is_refused_client_side_with_the_reason() + { + var cfg = WithProfiles(); + var blockers = ProfileEditing.RemovalBlockers(cfg, "internal-default"); + Assert.Equal(2, blockers.Count); // default of demo and of batch + Assert.All(blockers, b => Assert.Contains("default profile", b, StringComparison.Ordinal)); + var before = ConfigCopy.Canonical(cfg); + Assert.NotNull(ProfileEditing.Remove(cfg, "internal-default")); + Assert.Equal(before, ConfigCopy.Canonical(cfg)); + Assert.NotEmpty(ProfileEditing.RemovalBlockers(cfg, ProfileEditing.LegacyInternal)); + Assert.NotEmpty(ProfileEditing.RemovalBlockers(cfg, "ghost")); + } + + [Fact] + public void Removing_the_only_profile_of_a_policy_is_refused_because_it_would_widen_the_policy() + { + var cfg = WithProfiles(); + cfg.Policies[0].Profiles = ["public-demo"]; + Assert.Contains(ProfileEditing.RemovalBlockers(cfg, "public-demo"), b => b.Contains("widen", StringComparison.Ordinal)); + Assert.NotNull(ProfileEditing.Remove(cfg, "public-demo")); + Assert.Equal(new[] { "public-demo" }, cfg.Policies[0].Profiles); + } + + [Fact] + public void Removal_impact_lists_grants_and_multi_profile_policies_then_remove_cleans_every_reference() + { + var cfg = WithProfiles(); + cfg.Policies[0].Profiles = ["public-demo", "internal-default"]; + var impact = ProfileEditing.RemovalImpact(cfg, "public-demo"); + Assert.Contains(impact, l => l.Contains("'demo' loses the grant", StringComparison.Ordinal)); + Assert.Contains(impact, l => l.Contains("Policy 'public' stops listing", StringComparison.Ordinal)); + Assert.Empty(ProfileEditing.RemovalBlockers(cfg, "public-demo")); + + Assert.Null(ProfileEditing.Remove(cfg, "public-demo")); + Assert.DoesNotContain(cfg.Profiles, p => p.Id == "public-demo"); + Assert.Equal(new[] { "internal-default" }, cfg.Applications[0].GrantedProfiles); + Assert.Equal(new[] { "internal-default" }, cfg.Policies[0].Profiles); + Assert.All(cfg.Applications, a => Assert.Empty(ProfileEditing.ApplicationProblems(a, cfg))); + + var unused = WithProfiles(); + unused.Profiles.Add(new WorkloadProfileDto { Id = "spare", Name = "Spare", Baseline = "Phi" }); + Assert.Contains(ProfileEditing.RemovalImpact(unused, "spare"), l => l.Contains("changes no route", StringComparison.Ordinal)); + } + + [Fact] + public void Grants_and_default_profile_stay_consistent() + { + var cfg = WithProfiles(); + var demo = cfg.Applications[0]; + + // The default cannot be revoked; another default first. + Assert.NotNull(ProfileEditing.SetGrant(demo, "internal-default", false, cfg)); + Assert.Contains("internal-default", demo.GrantedProfiles); + Assert.NotNull(ProfileEditing.SetDefault(cfg.Applications[1], "public-demo")); // not granted to batch + Assert.Equal("internal-default", cfg.Applications[1].DefaultProfile); + Assert.Null(ProfileEditing.SetDefault(demo, "public-demo")); + Assert.Null(ProfileEditing.SetGrant(demo, "internal-default", false, cfg)); + Assert.Equal(new[] { "public-demo" }, demo.GrantedProfiles); + + // Unknown profiles are never granted; the built-in one may be. + Assert.NotNull(ProfileEditing.SetGrant(demo, "ghost", true, cfg)); + Assert.Null(ProfileEditing.SetGrant(demo, ProfileEditing.LegacyInternal, true, cfg)); + Assert.Contains(ProfileEditing.LegacyInternal, ProfileEditing.GrantOptions(cfg, demo)); + + // No default ⇒ the built-in legacy-internal (baseline Internal) applies. + Assert.Null(ProfileEditing.SetDefault(demo, "")); + Assert.Null(demo.DefaultProfile); + Assert.Contains(ProfileEditing.LegacyInternal, ProfileEditing.DefaultText(cfg, demo), StringComparison.Ordinal); + Assert.Empty(ProfileEditing.ApplicationProblems(demo, cfg)); + + // What the Host rejects is reported. + demo.DefaultProfile = "internal-default"; + Assert.Contains(ProfileEditing.ApplicationProblems(demo, cfg), p => p.Contains("not granted", StringComparison.Ordinal)); + demo.GrantedProfiles.Add("ghost"); + Assert.Contains(ProfileEditing.ApplicationProblems(demo, cfg), p => p.Contains("does not exist", StringComparison.Ordinal)); + } + + [Fact] + public void Team_and_output_bound_are_validated() + { + var app = WithProfiles().Applications[0]; + Assert.NotNull(ProfileEditing.SetTeam(app, " ")); + Assert.Equal("payments", app.Team); + Assert.Null(ProfileEditing.SetTeam(app, " risk ")); + Assert.Equal("risk", app.Team); + Assert.NotNull(ProfileEditing.SetMaxOutputTokens(app, 0)); + Assert.NotNull(ProfileEditing.SetMaxOutputTokens(app, null)); + Assert.Equal(256, app.MaxOutputTokens); + Assert.Null(ProfileEditing.SetMaxOutputTokens(app, 64)); + Assert.Equal(64, app.MaxOutputTokens); + } + + [Fact] + public void Labels_name_the_baseline_and_the_built_in_profile() + { + var cfg = WithProfiles(); + Assert.Equal("Public demo (baseline Public)", ProfileEditing.Label(cfg, "public-demo")); + Assert.Equal("legacy-internal (built-in, baseline Internal)", ProfileEditing.Label(cfg, ProfileEditing.LegacyInternal)); + Assert.Equal("ghost (not configured)", ProfileEditing.Label(cfg, "ghost")); + Assert.True(ProfileEditing.Exists(cfg, ProfileEditing.LegacyInternal)); + Assert.False(ProfileEditing.IsDeclared(cfg, ProfileEditing.LegacyInternal)); + } +} diff --git a/tests/Covenant.Tests/ContractRoundTripTests.cs b/tests/Covenant.Tests/ContractRoundTripTests.cs index 69398c8..56e2855 100644 --- a/tests/Covenant.Tests/ContractRoundTripTests.cs +++ b/tests/Covenant.Tests/ContractRoundTripTests.cs @@ -1225,4 +1225,82 @@ private static JsonElement Wire(string json) using var doc = JsonDocument.Parse(json); return doc.RootElement.Clone(); } + + // ---- Review round 3 (UI): the profile/grant editor builds drafts the Host's validation accepts ---- + + private static Covenant.Governance.ValidationEnvironment PermissiveEnvironment() => new() + { + EgressAllowList = new HashSet(StringComparer.OrdinalIgnoreCase) { "ollama-host:11434", "vllm-host:8000", "api.openai.com:443", "api.anthropic.com:443" }, + SecretAvailable = _ => true, + LocalEndpoints = new HashSet(StringComparer.OrdinalIgnoreCase) { "ollama-host:11434", "vllm-host:8000" }, + }; + + /// Console draft → PUT body (UiJsonContext) → Host ConfigPutRequest → ConfigValidator. + private static (CovenantConfig Host, Covenant.Governance.ConfigValidationResult Result) HostValidates(UiModels.CovenantConfigDto draft) + { + var body = JsonSerializer.Serialize(new UiModels.ConfigPutRequestDto { Config = draft, ChangeSummary = "profiles" }, UiModels.UiJsonContext.Default.ConfigPutRequestDto); + var put = JsonSerializer.Deserialize(body, ConfigJsonContext.Default.ConfigPutRequest); + Assert.NotNull(put?.Config); + var config = put!.Config!; + var result = Covenant.Governance.ConfigValidator.Validate(config, PermissiveEnvironment()); + Assert.True(result.StructurallySound, string.Join("; ", result.Errors.Select(e => e.Path + ": " + e.Code))); + return (config, result); + } + + private static bool ProfileOrGrantPath(string path) + => path.StartsWith("profiles", StringComparison.Ordinal) || path.StartsWith("applications", StringComparison.Ordinal) || path.Contains(".profiles", StringComparison.Ordinal); + + [Fact] + public void Profile_and_grant_edits_made_by_the_console_pass_host_validation() + { + var (_, envelope, _, _) = RoundTrip(Representative(ProviderMode.Hybrid)); + var draft = envelope.Config!; + + Assert.Empty(Covenant.Ui.Logic.ProfileEditing.Add(draft, new Covenant.Ui.Logic.NewProfileForm { Id = "support", Name = "Support tickets", Baseline = "Public", Description = "Synthetic" })); + var demo = Covenant.Ui.Logic.ProfileEditing.FindApplication(draft, "demo-app")!; + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetGrant(demo, "support", true, draft)); + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetDefault(demo, "support")); + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetMaxOutputTokens(demo, 128)); + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetTeam(demo, "payments-ops")); + var prod = Covenant.Ui.Logic.ProfileEditing.FindApplication(draft, "prod-app")!; + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetGrant(prod, "support", true, draft)); + Assert.Null(Covenant.Ui.Logic.ProfileEditing.SetDefault(prod, "internal")); + prod.Enabled = true; + prod.ConsoleTesting = true; + + // "clinical" is only granted (no default, no policy) → removable; "public-tickets" is policy 'public''s only + // profile → refused client-side (removing it would widen that policy). + Assert.Null(Covenant.Ui.Logic.ProfileEditing.Remove(draft, "clinical")); + Assert.NotNull(Covenant.Ui.Logic.ProfileEditing.Remove(draft, "public-tickets")); + Assert.All(draft.Applications, a => Assert.Empty(Covenant.Ui.Logic.ProfileEditing.ApplicationProblems(a, draft))); + + var (host, result) = HostValidates(draft); + Assert.DoesNotContain(result.Errors, e => ProfileOrGrantPath(e.Path)); + var support = host.Profiles.Single(p => p.Id == "support"); + Assert.Equal(DataClassification.Public, support.Baseline); + Assert.Equal("Synthetic", support.Description); + Assert.DoesNotContain(host.Profiles, p => p.Id == "clinical"); + var hostDemo = host.Applications.Single(a => a.Id == "demo-app"); + Assert.Equal("support", hostDemo.DefaultProfile); + Assert.Equal(128, hostDemo.MaxOutputTokens); + Assert.Equal("payments-ops", hostDemo.Team); + Assert.DoesNotContain("clinical", hostDemo.GrantedProfiles); + var hostProd = host.Applications.Single(a => a.Id == "prod-app"); + Assert.True(hostProd.Enabled); + Assert.True(hostProd.ConsoleTesting); + Assert.Equal(new[] { "internal", "support" }, hostProd.GrantedProfiles); + } + + [Fact] + public void Console_and_host_agree_that_a_default_profile_must_be_granted() + { + var (_, envelope, _, _) = RoundTrip(Representative(ProviderMode.Hybrid)); + var draft = envelope.Config!; + var prod = Covenant.Ui.Logic.ProfileEditing.FindApplication(draft, "prod-app")!; + Assert.NotNull(Covenant.Ui.Logic.ProfileEditing.SetDefault(prod, "customer-pii")); // the editor refuses + prod.DefaultProfile = "customer-pii"; // forced, to compare + Assert.NotEmpty(Covenant.Ui.Logic.ProfileEditing.ApplicationProblems(prod, draft)); + var (_, result) = HostValidates(draft); + Assert.Contains(result.Errors, e => e.Code == "default_profile_not_granted"); + } } From 45760e93a77a6b3a3046195944a1a12b974857b1 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Sat, 17 Oct 2026 10:32:19 -0400 Subject: [PATCH 12/14] =?UTF-8?q?feat(demo):=20T09=20=E2=80=94=20v2=20laun?= =?UTF-8?q?cher=20(isolated=20local-only/hybrid=20profiles),=20explicit=20?= =?UTF-8?q?hybrid=20seed=20prices,=20v2=20runbook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - hybrid seed never assumes a cloud price: Pricing::InPer1M/OutPer1M required (basis/date kept); regressions: custom model without prices refused, supplied prices retained, local-only needs none - launcher: own port (5210) and state dir per profile, Config:Seed, no app key in the console flow, FRESH=1 renames old state (never deletes), never touches other instances - runbook: preflight + A/A'/B/B'/C/D/F/G/H/pause/auth walkthrough with expected trace and cost/evidence --- docs/demo-runbook.md | 120 ++++++++++-------- scripts/run-local-demo.sh | 143 ++++++++++++++-------- src/Covenant.Host/ConfigBootstrap.cs | 34 ++++- tests/Covenant.Tests/ConfigV2TestKit.cs | 2 + tests/Covenant.Tests/LegacyImportTests.cs | 45 ++++++- tests/Covenant.Tests/RuntimeV2TestKit.cs | 2 + 6 files changed, 242 insertions(+), 104 deletions(-) diff --git a/docs/demo-runbook.md b/docs/demo-runbook.md index 23d31a4..9a2d544 100644 --- a/docs/demo-runbook.md +++ b/docs/demo-runbook.md @@ -1,23 +1,30 @@ -# Covenant console — demo runbook +# Covenant console v2 — demo runbook -The demo runs entirely in the browser after startup. `demo.sh` stays an optional smoke/diagnostic tool. +Everything after startup is done in the browser. `demo.sh` remains an optional `/v1` smoke tool. Scenario letters +follow `docs/CONSOLE-V2-IMPLEMENTATION-SPEC.md` §8. Expected behaviour below describes the implementation; it is +not a record of a run — see `docs/console-v2-acceptance.md` for what has actually been executed. -## 1. Configuration (names only — values live in user-secrets / env / vault) +## 1. Start an isolated demo profile -Required in every mode: `Admin:Token`, `Budget:GlobalCapUsd`, `Auth:Keys:0:Key`, `Auth:Keys:0:Principal`, -`Auth:Keys:0:Team` (the application key used by Playground is one of these keys — never the admin token). - -| Mode | Settings | -|---|---| -| Cloud + local PII route (default) | `OpenAI:ApiKey`, optional `Local:Endpoint` + `Local:ModelId` | -| Local-only (no cloud credential) | `Providers:Mode=local-only`, `Local:Endpoint`, `Local:ModelId`; **no** `OpenAI:ApiKey` / `Anthropic:ApiKey` | - -Optional: `Covenant:Environment` (header label, e.g. `vslive-demo`), `Providers:ProbeAllowList` -(host:port list the wizard may probe; the applied Local:Endpoint is always allowed), `Cache:TtlSeconds`, -`Audit:PromptPreviewChars` (0 = no prompt text in evidence), `Audit:AnchorPath` + `Audit:AnchorEvery`. - -`Local:Endpoint` is as seen **from the Covenant host** (`http://localhost:11434/v1` only if Ollama runs on the -same machine/container as Covenant). `Local:ModelId` is the exact installed tag (`ollama list`) — nothing guesses it. +``` +scripts/run-local-demo.sh # Local-only: Ollama only, no cloud credential, port 5210 +PROFILE=hybrid OPENAI_API_KEY=… CLOUD_PRICE_IN_1M=… CLOUD_PRICE_OUT_1M=… scripts/run-local-demo.sh +``` +The launcher checks Ollama and the model tag, publishes the self-contained binary, starts it on its own port with +its own state directory (`/tmp/covenant-v2-demo-/`: audit log, configuration repository, budget ledger), +and opens the console already connected (admin token in the URL fragment, read once, never sent to the server). +It never touches another instance (e.g. :5100, :5201). State persists per profile; `FRESH=1` moves it aside +(renamed, not deleted). + +**Seeds** (`Config:Seed`, first start only; afterwards the configuration repository wins — ADR-0011): +- Workload profiles: `public-demo` (trusted baseline **Public**, synthetic public content only) and + `internal-default` (baseline **Internal**). Detection can only escalate a baseline (US-SSN pattern → PII; + MRN/diagnosis/patient-id keywords → PHI). It is a demonstration detector, not DLP. +- Application `demo-app` (team `platform`, console testing allowed, granted both profiles). +- Policies — Local-only: everything → `ollama/`. Hybrid: Public → `openai/` with approved fallback + `ollama/`; Internal → local; PII & PHI → local only (cloud targets are never eligible for PII/PHI). +- Budget: global, monthly, cap `CAP` (default $5). Hybrid cloud prices come only from the operator + (`CLOUD_PRICE_IN_1M`/`OUT_1M`, current provider list price); the seed refuses to start without them. ## 1a. Supported artifact (2026-10-17) @@ -33,45 +40,54 @@ suppressed and the build is not claimed AOT-verified. Unblocking needs an AOT-cl replacing the Anthropic connector with an AOT-clean `IChatClient`, and moving the optional Neo4j projector out of the appliance image), then a clean `PublishAot=true` run. See ADR-0001 "Status update 2026-10-17". -## 2. Startup and preflight (before the audience arrives) - -``` -dotnet run --project src/Covenant.Host -c Release # or the published binary -``` -1. Open `http://localhost:5100/ui/` → Connect with the admin token (held in this tab only). -2. Overview: no red alerts. Header shows the environment, "Console connected", fresh "Updated n s ago". -3. Models & connections: applied local endpoint/model shown, **Registered: yes**. Run *Test connection*, then - the governed test with the application key → Served by `local:`. This also **warms the model** - (first Ollama load can take 10–60 s; do it before the talk). -4. Evidence: chain "Internal consistency verified". If anchoring is configured, anchors written > 0. -5. Settings → note prompt retention (`prompt_preview_chars`). Do **not** use Maintenance → Archive & reset as - a demo step; it archives evidence (budgets are NOT reopened — the ledger is independent of audit segments). - -## 3. The A / B / C / D sequence (Playground, optionally Presentation mode) - -Paste the application key once (memory only). Presets only fill the form; Run sends a real request. - -| Run | Expected outcome | Evidence to show | -|---|---|---| -| **A** normal request | Served (cloud mode: cheapest permitted cloud model; local-only: `local:`) | Selected = attempted = served; cost basis | -| **B** unapproved model | HTTP 403 Policy denied; provider attempted: **None** | Stopped at `policy`; classification evaluated | -| **C** synthetic PII | Served by `local:`; without a local route: 403 at `provider`, attempted None | Signal "US SSN pattern"; never a cloud model | -| **D** pause → run → resume → run | 403 Paused (stopped at `pause`), then Served | Fresh nonce each run, so never a cache hit | - -Auth failure demo: clear the key and Run → 401, classification **Not evaluated — stopped at auth**. -Every result has *View request evidence* → *Open in Requests*: the exact record by request id. +## 2. Preflight (before the audience arrives) + +1. Header shows the environment (`demo-local-only` / `demo-hybrid`), the **mode badge** (Local-only / Hybrid), + **Live**, and "New provider calls: running". No red alerts on Overview. +2. **Models & connections**: the Ollama connection shows the selected tag; Test succeeds. Run one request from + the Playground to **warm the model** (first Ollama load can take 10–60 s) — the header local health turns ok. +3. **Policies**: route view reads e.g. "Public → openai/gpt-4o-mini · fallback: ollama/qwen2.5-coder:7b"; + "Internal → ollama/…"; "PII & PHI → ollama/… (local only)". +4. **Budgets**: global budget, period id, spent/reserved/remaining, warning none. +5. **Audit & evidence**: "Audit integrity verified" (internal consistency of the hash chain; not answer quality). +6. Settings: prompt preview retention 0 (no prompt text in evidence) unless you deliberately change it. + +## 3. Walkthrough (Playground; Presentation mode for the projector) + +"Run as" **demo-app**; pick the profile; presets only fill the form — Run sends a real governed request. Each run +shows the live trace (auth → shape → classify → policy → cache → rate limit → pause → budget → provider (per +attempt) → attribution), the outcome, destination (Local/Cloud tag), final classification, tokens, cost basis, +and **Evidence recorded** → *Open in Requests* for the exact record. + +| | Do | Expected decision / trace | Cost & evidence | +|---|---|---|---| +| **A** Public → cloud (Hybrid) | Preset A, profile Public demo | classify passed (Public, no escalation); policy → openai primary; provider passed | reported usage × configured price ("estimated provider charge"); team `platform`, app `demo-app` | +| **A′** same in Local-only | Preset A | Public → ollama | $0 configured provider charge — infrastructure excluded | +| **B** Sensitive → local | Preset B (synthetic SSN 078-05-1120), profile Public demo | classify: **PII (baseline Public, escalated: US SSN pattern)**; policy → ollama only | zero-priced local; evidence shows the signal, never the prompt | +| **B′** cloud override refused | B with Advanced → model `openai/` | policy refused: target not eligible for PII; provider **skipped** | no provider call, $0, audited refusal | +| **C** missing local | Models & connections → disable the Ollama connection → Preview → Save (new version) → run B | policy refused: no eligible destination; provider skipped; **no cloud call** | re-enable afterwards (another new version) | +| **D** approved fallback | (fixture) Policies → pause the primary route **or** stop the primary provider → run A | provider attempt 1 failed/paused-skipped → attempt 2 on the approved fallback | both attempts in the drawer; failed attempt charged its estimate, never $0 | +| **F** budget | Budgets → lower the cap below spend → Preview → Save → run A | budget refused ("would exceed cap") | spend preserved across the edit; raise the cap again (audited new version) | +| **G** exact cache | Settings → cache TTL 60 → Save; run the same request twice | 2nd run: cache passed, rate limit/pause/budget/provider **skipped (cache_hit)** | $0 no provider call; drawer names the original served connection/model; any config change invalidates | +| **H** policy editing | Policies → pause the primary route → Save; run A; pause the whole policy → Save; run A; resume → Save | route paused → fallback serves; policy paused → refused; resumed → primary again | each change is a new version (history + rollback available) | +| **Pause** | Header → Pause new provider calls → run D (fresh nonce) → Resume → run D | pause stage refused → then served | cache hits are not stopped by the pause (documented) | +| **Auth** | Applications & workload profiles → disable console testing for demo-app → Save → Run | auth refused (governed 403, audited) | re-enable afterwards | + +Stage timings are measured by the server; skipped stages are shown as skipped, never animated as if they ran. ## 4. Recovery | Symptom | Action | |---|---| -| Header "Stale" / "Connection lost — retrying" | Covenant process down or network: check terminal; console reconnects by itself | -| Local route **degraded** (last success kept) | Ollama stopped/unreachable: restart Ollama, re-run the governed test; protected requests are refused meanwhile (no cloud fallback) | -| C refused at `provider` | Local route not registered: Models & connections shows why (not configured / wrong tag) | -| Everything 403 Paused | Header Resume (pause is global and persists across pages) | -| Budget exhausted | Raise `Budget:GlobalCapUsd` and restart — not Archive & reset | -| Token rejected | Re-enter the admin token (sessionStorage is per tab) | +| Header **Stale** / connection lost | Covenant stopped? Check the launcher terminal / `$STATE/server.log`; the console reconnects by itself | +| Local health **degraded** | Ollama down/unreachable: restart Ollama; protected requests are refused meanwhile (no cloud fallback for Internal/PII/PHI) | +| Save shows "Configuration changed since you started editing" | Another tab/operator applied a version: Reload, re-apply your change | +| Save refused with field errors | Fix the highlighted fields; the active version is unchanged | +| Everything refused at **pause** | Header → Resume | +| Budget exhausted | Raise the cap (Budgets → Save). Archive/reset does **not** reopen budgets (ADR-0014) | +| Startup refused | The launcher prints Covenant's reason (e.g. missing hybrid prices, corrupt journal — never auto-repaired silently) | ## 5. Optional: Open WebUI as a client -Base URL `http://:5100/v1`, API key = a Covenant **application** key. Text chat only; streaming -supported. Pointing Open WebUI at Ollama directly bypasses Covenant. +Base URL `http://localhost:/v1`, API key = the launcher's **/v1 app key** (never the admin token); optional +header `X-Covenant-Profile` selects a granted profile. Text chat only; streaming supported. Pointing Open WebUI at +Ollama directly bypasses Covenant. diff --git a/scripts/run-local-demo.sh b/scripts/run-local-demo.sh index 70dde9e..a0fef77 100755 --- a/scripts/run-local-demo.sh +++ b/scripts/run-local-demo.sh @@ -1,94 +1,137 @@ #!/usr/bin/env bash -# Run the Covenant appliance + console locally in local-only mode against an existing Ollama. -# Isolated: Production environment (your user-secrets are NOT loaded), its own port and audit file, -# throwaway credentials generated per run. Your service on :5100 and your Ollama are not touched. +# Covenant v2 demo launcher — isolated, reproducible, no terminal needed after it opens the console. # -# scripts/run-local-demo.sh # defaults below -# MODEL=qwen3.8:27b-mlx PORT=5202 scripts/run-local-demo.sh -# SKIP_PUBLISH=1 scripts/run-local-demo.sh # reuse the last publish +# scripts/run-local-demo.sh # Local-only profile (Ollama only, no cloud credential) +# PROFILE=hybrid scripts/run-local-demo.sh # Hybrid: Public → cloud (+ local fallback), everything else local +# MODEL=qwen3.8:27b-mlx PORT=5212 scripts/run-local-demo.sh +# SKIP_PUBLISH=1 scripts/run-local-demo.sh # reuse the last publish +# FRESH=1 scripts/run-local-demo.sh # start this profile's isolated state from scratch +# +# Isolation: Production environment (user-secrets NOT loaded), its own port and its own state directory +# (/tmp/covenant-v2-demo-/: audit log, configuration repository, budget ledger). It never touches +# another running instance (e.g. :5100 or :5201) or its files. State persists across runs of the same profile +# so configuration versions, spend and evidence survive restarts; FRESH=1 moves the old state aside (renamed, +# never deleted) and starts again from the seed. +# +# Hybrid needs, in the ENVIRONMENT (never printed, never written to disk by this script): +# OPENAI_API_KEY the cloud credential (server-side only; the console only sees "available") +# CLOUD_PRICE_IN_1M USD per 1M input tokens for CLOUD_MODEL, from the provider's CURRENT price list +# CLOUD_PRICE_OUT_1M USD per 1M output tokens +# CLOUD_MODEL default gpt-4o-mini; CLOUD_PRICE_DATE (yyyy-MM-dd) optional +# Covenant refuses to start the hybrid seed without explicit prices — no default price is ever assumed. set -euo pipefail -PORT="${PORT:-5201}" +PROFILE="${PROFILE:-local-only}" +PORT="${PORT:-5210}" OLLAMA="${OLLAMA:-http://localhost:11434/v1}" MODEL="${MODEL:-qwen2.5-coder:7b}" -OUT="${OUT:-/tmp/covenant-pub}" -AUDIT="${AUDIT:-/tmp/covenant-demo-audit.log}" -LOG="${LOG:-/tmp/covenant-demo.log}" +CAP="${CAP:-5}" +OUT="${OUT:-/tmp/covenant-v2-pub}" +STATE="${STATE:-/tmp/covenant-v2-demo-$PROFILE}" ROOT="$(cd "$(dirname "$0")/.." && pwd)" +case "$PROFILE" in local-only) SEED=demo-local-only ;; hybrid) SEED=demo-hybrid ;; + *) echo "PROFILE must be local-only or hybrid"; exit 1 ;; esac case "$(uname -s)-$(uname -m)" in Darwin-arm64) RID=osx-arm64 ;; Darwin-x86_64) RID=osx-x64 ;; Linux-x86_64) RID=linux-x64 ;; Linux-aarch64) RID=linux-arm64 ;; *) echo "unsupported platform $(uname -sm)"; exit 1 ;; esac - say() { printf '\n\033[1m%s\033[0m\n' "$*"; } -say "1/4 Checking Ollama at $OLLAMA" -if ! models="$(curl -sS --max-time 5 "$OLLAMA/models")"; then - echo "Ollama is not reachable at $OLLAMA — start it (ollama serve) or set OLLAMA=..."; exit 1 -fi +say "1/5 Checking Ollama at $OLLAMA" +models="$(curl -sS --max-time 5 "$OLLAMA/models")" || { echo "Ollama is not reachable at $OLLAMA (ollama serve, or set OLLAMA=...)"; exit 1; } if ! grep -q "\"id\":\"$MODEL\"" <<<"$models"; then - echo "Model '$MODEL' is not installed. Installed tags:" - grep -o '"id":"[^"]*"' <<<"$models" | cut -d'"' -f4 | sed 's/^/ /' + echo "Model '$MODEL' is not installed. Installed tags:"; grep -o '"id":"[^"]*"' <<<"$models" | cut -d'"' -f4 | sed 's/^/ /' echo "Re-run with MODEL=."; exit 1 fi -echo "ok — $MODEL is installed" +echo "ok — $MODEL" + +if [[ "$PROFILE" == hybrid ]]; then + : "${OPENAI_API_KEY:?Hybrid needs OPENAI_API_KEY in the environment}" + : "${CLOUD_PRICE_IN_1M:?Hybrid needs CLOUD_PRICE_IN_1M (USD per 1M input tokens, current provider list price)}" + : "${CLOUD_PRICE_OUT_1M:?Hybrid needs CLOUD_PRICE_OUT_1M (USD per 1M output tokens)}" +fi +CLOUD_MODEL="${CLOUD_MODEL:-gpt-4o-mini}" if lsof -nP -iTCP:"$PORT" -sTCP:LISTEN >/dev/null 2>&1; then - echo "Port $PORT is already in use:"; lsof -nP -iTCP:"$PORT" -sTCP:LISTEN; echo "Stop it or set PORT=..."; exit 1 + echo "Port $PORT is in use — pick another with PORT=..."; lsof -nP -iTCP:"$PORT" -sTCP:LISTEN; exit 1 +fi + +if [[ "${FRESH:-}" == "1" && -d "$STATE" ]]; then + mv "$STATE" "$STATE.$(date -u +%Y%m%dT%H%M%SZ).previous" + echo "previous state kept at $STATE.*.previous (not deleted)" fi +mkdir -p "$STATE" if [[ "${SKIP_PUBLISH:-}" != "1" ]]; then - say "2/4 Publishing ($RID, Release) → $OUT (first run takes a few minutes)" + say "2/5 Publishing ($RID, Release, self-contained single file) → $OUT" dotnet publish "$ROOT/src/Covenant.Host" -c Release -r "$RID" --self-contained true \ -p:PublishSingleFile=true --disable-build-servers -o "$OUT" -v:minimal -nologo else - say "2/4 Skipping publish (SKIP_PUBLISH=1)" + say "2/5 Skipping publish (SKIP_PUBLISH=1)" fi [[ -x "$OUT/Covenant.Host" ]] || { echo "No binary at $OUT/Covenant.Host — the publish step failed above."; exit 1; } +# Credentials for THIS run only: the admin token (console) and one application key for /v1 clients +# (Open WebUI, curl). The console never needs the application key — it runs requests as authorized test +# applications (ADR-0012). ADMIN="$(openssl rand -hex 16)"; APPKEY="$(openssl rand -hex 16)" +LOCAL_AUTHORITY="$(sed -E 's#^https?://([^/]+).*#\1#' <<<"$OLLAMA")" -say "3/4 Starting Covenant on http://localhost:$PORT (log: $LOG)" -ASPNETCORE_ENVIRONMENT=Production \ -ASPNETCORE_URLS="http://localhost:$PORT" \ -Covenant__Environment=local-demo \ -Providers__Mode=local-only \ -Local__Endpoint="$OLLAMA" \ -Local__ModelId="$MODEL" \ -Admin__Token="$ADMIN" \ -Budget__GlobalCapUsd=5 \ -Auth__Keys__0__Key="$APPKEY" \ -Auth__Keys__0__Principal=demo-user \ -Auth__Keys__0__Team=platform \ -Audit__Path="$AUDIT" \ - "$OUT/Covenant.Host" >"$LOG" 2>&1 & +say "3/5 Starting Covenant ($PROFILE) on http://localhost:$PORT (state: $STATE)" +env_args=( + ASPNETCORE_ENVIRONMENT=Production + ASPNETCORE_URLS="http://localhost:$PORT" + Covenant__Environment="demo-$PROFILE" + Config__Seed="$SEED" + Local__Endpoint="$OLLAMA" + Local__ModelId="$MODEL" + Providers__LocalEndpoints="$LOCAL_AUTHORITY" + Admin__Token="$ADMIN" + Budget__GlobalCapUsd="$CAP" + Auth__Keys__0__Key="$APPKEY" + Auth__Keys__0__Principal=demo-service + Auth__Keys__0__Team=platform + Auth__Keys__0__Application=demo-app + Audit__Path="$STATE/audit.log" +) +if [[ "$PROFILE" == hybrid ]]; then + env_args+=( + OpenAI__ApiKey="$OPENAI_API_KEY" + OpenAI__ModelId="$CLOUD_MODEL" + "Pricing__${CLOUD_MODEL}__InPer1M=$CLOUD_PRICE_IN_1M" + "Pricing__${CLOUD_MODEL}__OutPer1M=$CLOUD_PRICE_OUT_1M" + "Pricing__${CLOUD_MODEL}__Basis=provider list price (operator-supplied)" + ) + [[ -n "${CLOUD_PRICE_DATE:-}" ]] && env_args+=("Pricing__${CLOUD_MODEL}__EffectiveDate=$CLOUD_PRICE_DATE") +fi +LOG="$STATE/server.log" +env "${env_args[@]}" "$OUT/Covenant.Host" >"$LOG" 2>&1 & PID=$! trap 'kill $PID 2>/dev/null || true' INT TERM -for _ in $(seq 1 40); do - if ! kill -0 "$PID" 2>/dev/null; then - echo "Covenant exited during startup. Its output:"; echo "------"; cat "$LOG"; echo "------"; exit 1 - fi +say "4/5 Waiting for the console" +code="" +for _ in $(seq 1 60); do + kill -0 "$PID" 2>/dev/null || { echo "Covenant exited during startup:"; echo "------"; cat "$LOG"; echo "------"; exit 1; } code="$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:$PORT/ui/" || true)" [[ "$code" == "200" ]] && break sleep 0.5 done -[[ "${code:-}" == "200" ]] || { echo "Covenant did not answer on /ui/ (last HTTP '$code'). Log:"; cat "$LOG"; kill $PID; exit 1; } +[[ "$code" == "200" ]] || { echo "No answer on /ui/ (last HTTP '$code'). Log:"; cat "$LOG"; kill $PID; exit 1; } -LAUNCH="http://localhost:$PORT/ui/connect#token=$ADMIN&appkey=$APPKEY" -say "4/4 Running — opening the console, already connected" +LAUNCH="http://localhost:$PORT/ui/connect#token=$ADMIN" +say "5/5 Running — opening the console (already connected)" command -v open >/dev/null && open "$LAUNCH" || true cat < seed is LocalOnly or Hybrid; + /// Explicit model-bound price for the hybrid seed's cloud model: Pricing:<model>:InPer1M and :OutPer1M + /// (USD per million tokens, required), :Basis (default "operator-supplied") and :EffectiveDate (yyyy-MM-dd, optional). + /// Missing or invalid ⇒ a startup error; never a default. + internal static PriceConfig? SeedCloudPrice(IConfiguration config, string model, string seed, List errors) + { + var section = config.GetSection($"Pricing:{model}"); + bool okIn = decimal.TryParse(section["InPer1M"], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out var inPer1M) && inPer1M >= 0m; + bool okOut = decimal.TryParse(section["OutPer1M"], System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out var outPer1M) && outPer1M >= 0m; + if (!okIn || !okOut) + { + errors.Add($"Pricing:{model}:InPer1M / OutPer1M — required by Config:Seed={seed} for the cloud model '{model}' " + + "(USD per 1M tokens from the provider's current price list; no default price is assumed)"); + return null; + } + DateOnly? effective = null; + if (section["EffectiveDate"] is { Length: > 0 } d) + { + if (DateOnly.TryParseExact(d, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var parsed)) effective = parsed; + else errors.Add($"Pricing:{model}:EffectiveDate — expected yyyy-MM-dd, got '{d}'"); + } + return new PriceConfig + { + InputPer1M = inPer1M, OutputPer1M = outPer1M, + Basis = section["Basis"] is { Length: > 0 } b ? b.Trim() : "operator-supplied", + EffectiveDate = effective, + }; + } + public static CovenantConfig Build(string seed, IConfiguration config, DateTimeOffset now, List errors) { bool hybrid = seed == Hybrid; @@ -309,6 +337,10 @@ public static CovenantConfig Build(string seed, IConfiguration config, DateTimeO if (localModel is not { Length: > 0 }) errors.Add($"Local:ModelId — required by Config:Seed={seed} (the exact installed model tag)"); localModel ??= "local-model"; string cloudModel = config["OpenAI:ModelId"] ?? "gpt-4o-mini"; + // Hybrid seeds never assume a cloud price (prices change and differ per model): the operator supplies the + // model-bound rates explicitly, with their basis/date, or the seed refuses to start. No default-model price + // is ever inherited by another model, so demo budget claims rest on stated numbers only. + PriceConfig? cloudPrice = hybrid ? SeedCloudPrice(config, cloudModel, seed, errors) : null; var connections = new List { @@ -328,7 +360,7 @@ public static CovenantConfig Build(string seed, IConfiguration config, DateTimeO { Id = "openai", DisplayName = "OpenAI", Kind = ProviderKind.OpenAi, Boundary = Boundary.Cloud, Endpoint = StartupValidation.Trimmed(config["OpenAI:Endpoint"]), Enabled = true, SecretRef = "OpenAI:ApiKey", - Models = [new ModelConfig { ModelId = cloudModel, Price = new PriceConfig { InputPer1M = 0.15m, OutputPer1M = 0.60m, Basis = "provider-list" } }], + Models = [new ModelConfig { ModelId = cloudModel, Price = cloudPrice }], }); publicTargets.Add(new PolicyTarget { ConnectionId = "openai", ModelId = cloudModel }); } diff --git a/tests/Covenant.Tests/ConfigV2TestKit.cs b/tests/Covenant.Tests/ConfigV2TestKit.cs index 88e055c..c89c858 100644 --- a/tests/Covenant.Tests/ConfigV2TestKit.cs +++ b/tests/Covenant.Tests/ConfigV2TestKit.cs @@ -167,6 +167,8 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseEnvironment("Production"); builder.UseSetting("Config:Seed", "demo-hybrid"); + builder.UseSetting($"Pricing:{V2.CloudModel}:InPer1M", "0.15"); // explicit, model-bound (seed never assumes) + builder.UseSetting($"Pricing:{V2.CloudModel}:OutPer1M", "0.60"); builder.UseSetting("OpenAI:ApiKey", Secret); builder.UseSetting("Anthropic:ApiKey", ""); builder.UseSetting("Local:Endpoint", "http://127.0.0.1:11434/v1"); diff --git a/tests/Covenant.Tests/LegacyImportTests.cs b/tests/Covenant.Tests/LegacyImportTests.cs index ca95e3d..060587a 100644 --- a/tests/Covenant.Tests/LegacyImportTests.cs +++ b/tests/Covenant.Tests/LegacyImportTests.cs @@ -229,7 +229,8 @@ public void Invalid_legacy_values_are_reported_not_ignored() [Fact] public void Demo_seeds_use_the_restrictive_defaults() { - var cfg = Config(("OpenAI:ApiKey", "sk"), ("Local:Endpoint", "http://localhost:11434/v1"), ("Local:ModelId", "qwen3:8b"), ("Budget:GlobalCapUsd", "3")); + var cfg = Config(("OpenAI:ApiKey", "sk"), ("Local:Endpoint", "http://localhost:11434/v1"), ("Local:ModelId", "qwen3:8b"), ("Budget:GlobalCapUsd", "3"), + ("Pricing:gpt-4o-mini:InPer1M", "0.15"), ("Pricing:gpt-4o-mini:OutPer1M", "0.60")); var errors = new List(); var hybrid = DemoSeeds.Build(DemoSeeds.Hybrid, cfg, DateTimeOffset.UtcNow, errors); var local = DemoSeeds.Build(DemoSeeds.LocalOnly, cfg, DateTimeOffset.UtcNow, errors); @@ -250,4 +251,46 @@ public void Demo_seeds_use_the_restrictive_defaults() Assert.Equal(BudgetPeriod.Monthly, hybrid.Budgets.Single().Period); Assert.Equal(3m, hybrid.Budgets.Single().CapUsd); } + + // Reviewer finding (T09): the hybrid seed accepted any OpenAI:ModelId but always seeded gpt-4o-mini's 0.15/0.60 + // "provider-list" rates — a custom model silently inherited another model's price, corrupting budget claims. + [Fact] + public void Hybrid_seed_refuses_a_cloud_model_without_explicit_model_bound_prices() + { + var cfg = Config(("OpenAI:ApiKey", "sk"), ("OpenAI:ModelId", "my-custom-model"), ("Local:Endpoint", "http://localhost:11434/v1"), + ("Local:ModelId", "qwen3:8b"), ("Budget:GlobalCapUsd", "3")); + var errors = new List(); + var seeded = DemoSeeds.Build(DemoSeeds.Hybrid, cfg, DateTimeOffset.UtcNow, errors); + + Assert.Contains(errors, e => e.StartsWith("Pricing:my-custom-model:InPer1M", StringComparison.Ordinal)); + var model = seeded.Connections.Single(c => c.Id == "openai").Models.Single(); + Assert.Null(model.Price); // never 0.15/0.60 inherited + } + + [Fact] + public void Hybrid_seed_retains_supplied_prices_basis_and_date_for_a_custom_model() + { + var cfg = Config(("OpenAI:ApiKey", "sk"), ("OpenAI:ModelId", "my-custom-model"), ("Local:Endpoint", "http://localhost:11434/v1"), + ("Local:ModelId", "qwen3:8b"), ("Budget:GlobalCapUsd", "3"), + ("Pricing:my-custom-model:InPer1M", "1.25"), ("Pricing:my-custom-model:OutPer1M", "5.5"), + ("Pricing:my-custom-model:Basis", "provider list price"), ("Pricing:my-custom-model:EffectiveDate", "2026-10-01")); + var errors = new List(); + var seeded = DemoSeeds.Build(DemoSeeds.Hybrid, cfg, DateTimeOffset.UtcNow, errors); + + Assert.Empty(errors); + var price = seeded.Connections.Single(c => c.Id == "openai").Models.Single().Price!; + Assert.Equal(1.25m, price.InputPer1M); + Assert.Equal(5.5m, price.OutputPer1M); + Assert.Equal("provider list price", price.Basis); + Assert.Equal(new DateOnly(2026, 10, 1), price.EffectiveDate); + } + + [Fact] + public void Local_only_seed_needs_no_cloud_price() + { + var cfg = Config(("Local:Endpoint", "http://localhost:11434/v1"), ("Local:ModelId", "qwen3:8b"), ("Budget:GlobalCapUsd", "3")); + var errors = new List(); + DemoSeeds.Build(DemoSeeds.LocalOnly, cfg, DateTimeOffset.UtcNow, errors); + Assert.Empty(errors); + } } diff --git a/tests/Covenant.Tests/RuntimeV2TestKit.cs b/tests/Covenant.Tests/RuntimeV2TestKit.cs index 38c1c67..18c1bf3 100644 --- a/tests/Covenant.Tests/RuntimeV2TestKit.cs +++ b/tests/Covenant.Tests/RuntimeV2TestKit.cs @@ -257,6 +257,8 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseEnvironment("Production"); builder.UseSetting("Config:Seed", "demo-hybrid"); + builder.UseSetting($"Pricing:{V2.CloudModel}:InPer1M", "0.15"); // explicit, model-bound (seed never assumes) + builder.UseSetting($"Pricing:{V2.CloudModel}:OutPer1M", "0.60"); builder.UseSetting("OpenAI:ApiKey", HybridSeedFactory.Secret); builder.UseSetting("Anthropic:ApiKey", ""); builder.UseSetting("Local:Endpoint", "http://127.0.0.1:11434/v1"); From 9e71d66fc48d709384798ef7d91ed2731018dc53 Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Sat, 17 Oct 2026 10:32:54 -0400 Subject: [PATCH 13/14] =?UTF-8?q?docs:=20console=20v2=20handoff=20and=20ac?= =?UTF-8?q?ceptance=20record=20(spec=20=C2=A79)=20=E2=80=94=20observations?= =?UTF-8?q?=20vs=20claims,=20limitations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/console-v2-acceptance.md | 75 +++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 docs/console-v2-acceptance.md diff --git a/docs/console-v2-acceptance.md b/docs/console-v2-acceptance.md new file mode 100644 index 0000000..28af603 --- /dev/null +++ b/docs/console-v2-acceptance.md @@ -0,0 +1,75 @@ +# Console v2 — handoff and acceptance record (spec §9) + +Branch `feat/console-v2` from `main` 9371dbe. Not merged. **The author's environment cannot run `dotnet`.** Every +"Observed" entry below was executed by the independent verifier (Codex) on macOS arm64 against the commit named, +with logs/screenshots in the git-excluded `docs/verification-2026-10-16/v2/` folder. "Claimed" = implemented, not +yet independently observed at the latest commit. + +## 1. Commits by task + +| Task | Commits | +|---|---| +| T01 architecture | f1ebd12 (ADR-0011..0014, v2 contract, migration notes, config model), 79ec4b0 (review corrections) | +| T10 CI | 2f2a28a (single `test` check; docs-only vs code decided in one job) | +| T02/T03 config, profiles, policies | a929d84, 8bb8923 (review round 1 incl. torn journal) | +| T04/T05/T06 budgets, console inference + trace, fallback/cache | a16bed8, 1ad07c4 (review round 2) | +| T07/T08 UI | 3d579fe, 96deed5, 959ce13 (UI round 2), 2a7d5e5 (UI round 3) | +| T09 demo | 45760e9 (launcher, explicit hybrid seed prices, runbook) | + +Docs: ADR-0011..0014 (+ ADR-0001 status update), `docs/ui-api-contract.md` (v2), `docs/migration-v2.md`, +`docs/demo-runbook.md`, `docs/console-v2-progress.md` (per-round defect → fix → test), this file. + +## 2. Executed verification (observed by the verifier) + +| Commit | Observation | +|---|---| +| 2f2a28a | Release build 0 warnings/errors; 310 tests pass (baseline) | +| 8bb8923 | Release build + 491 tests pass incl. torn-journal regression; osx-arm64 self-contained single-file publish; `/ui`→302 `/ui/`; `/ui/`, nested route, Blazor JS → 200 | +| 1ad07c4 (+2 test-only name fixes, applied in 959ce13) | Release build + 723 tests pass; HTTP stream suite: partial-then-error ⇒ Deny/no fallback; length finish relayed + Truncated; post-content stall ⇒ timeout, partial kept, no fallback; empty completion ⇒ 200/Allow. Cache collision probes (delimiter, output-bound) ⇒ calls=2, no false hit. 503/429/timeout fallback with two charged attempts. Ledger migration crash window ⇒ refuses start; clean import preserves spend. Stable pagination; early trace (provider Running before first token) | +| 959ce13 | Release build + **761 tests pass**, no verifier patches; osx-arm64 single-file publish pass; coverage measured at an earlier checkpoint: line 95.14 % / branch 81.94 % | +| browser (959ce13 era) | connect once; budget edit → preview → apply (v10) with spend preserved; policy split/save (v31); pause primary + approved slow fixture (v32); cache TTL edit (v33) + repeated request = cache hit, no provider call, $0, skipped stages; live provider Running before first token; Ollama discovery → select `qwen2.5-coder:7b` → save → real synthetic sensitive request: Pii (US SSN pattern), served by local Qwen, zero configured provider charge, evidence found; presentation fits 1280×720; Escape restores focus; header local health correct. Screenshots: `qwen-real-{1280,1920}-{dark,light}.png`, `dashboard-1280-dark.png`, `presentation-1280-dark.png`, `round2-*.png`, `budget-applied-v10.png` | +| security probes | invalid enums / null settings ⇒ validation errors (no 500); removed application's key ⇒ 403; app key cannot read admin APIs; admin token cannot authorize inference; browser disconnect ⇒ Cancelled, one estimated charged attempt, no fallback, reservation released | +| NativeAOT | **Fails**: IL2104/IL3053 from Anthropic 12.8.0 and Neo4j.Driver 6.2.1 — documented, not suppressed (ADR-0001 status update, runbook §1a). Supported artifact: self-contained single file | + +## 3. Status by task (claims vs observations) + +| Task | Implemented (claimed) | Executed verification | Remaining gap | +|---|---|---|---| +| T01 | ADRs 0011–0014, contract, migration | reviewed by verifier | — | +| T02 | repository, journal, validation, impact, rollback, legacy import | tests + HTTP | — | +| T03 | profiles, baseline escalation, policy engine v2, simulator, modes | tests + browser split/save | — | +| T04 | ledger, reservations, periods, settle/release, migration | tests + HTTP (concurrency 1×200/5×403, archive preserves spend) | — | +| T05 | console endpoint, submissions, trace hub/stream | tests + browser live trace | — | +| T06 | fallback, attempt evidence, cache identity, savings, archive/export | tests + HTTP fixture | real cloud fallback not exercised (see §5) | +| T07 | shell, composer, Playground, presentation | browser (both themes, 1280/1920) | round-3 UI (2a7d5e5) **not yet re-observed** | +| T08 | editors, requests archive, evidence export | browser (budget/policy/settings/connections) | profile/grant editor (2a7d5e5) **not yet observed** | +| T09 | launcher, seeds, runbook | seed price regressions written | 45760e9 **not yet built/run**; launcher not yet executed | +| T10 | single CI check; this record | — | final full rerun at HEAD; Linux publish on a supported runner | + +## 4. Verifier commands for HEAD + +``` +dotnet build Covenant.sln -c Release --disable-build-servers +dotnet test tests/Covenant.Tests -c Release --disable-build-servers --collect:"XPlat Code Coverage" --settings tests/coverlet.runsettings +dotnet test tests/Covenant.Tests -c Release -p:SkipConsolePublish=true --artifacts-path +dotnet publish src/Covenant.Host -c Release -r osx-arm64 --self-contained -p:PublishSingleFile=true -o +scripts/run-local-demo.sh # isolated port 5210, own state; then runbook §2–§3 in the browser +``` +Route checks with GET (not HEAD): `curl -sS -D - -o /dev/null http://localhost:5210/ui` → 302 `/ui/`; `/ui/` and +`/ui/requests/x` → 200 text/html. + +## 5. Known limitations (stated, not hidden) + +- **Detector coverage:** `RegexDataClassifier` recognises a US-SSN pattern and MRN/diagnosis/patient-id keywords only. + It is a demonstration detector, not DLP; Public is reachable only through a trusted, granted Public profile, and + detection can only escalate. It cannot prove content is non-sensitive. +- **Price and usage uncertainty:** costs are configured-price × provider-reported usage. Unreported usage and + failed attempts are charged a conservative estimate (UTF-8 byte bound); a hard budget is an *estimated* + enforcement bound, not an invoice ceiling. Local "$0" is zero configured provider charge, infrastructure excluded. + Savings are shown only with a configured priced baseline and are not evidence of equal answer quality. +- **Answer quality:** Covenant governs routing, cost and evidence; it does not evaluate answers. "Audit integrity + verified" means the hash chain is internally consistent, nothing about correctness. +- **Identity:** console actions are attributed to the shared admin credential (`OperatorRef = shared-admin-token`); + no individual operator attribution until real IAM. +- **Real cloud smoke:** BLOCKED / NOT RUN — needs owner-supplied credentials, synthetic prompts and a small cap. +- **NativeAOT:** blocked by dependencies (above). **Linux-x64 publish:** not yet run on a supported runner. From 3a57cab87ec734253bbc482343216173b7623a2a Mon Sep 17 00:00:00 2001 From: Alex Kaziuka Date: Sat, 17 Oct 2026 10:42:57 -0400 Subject: [PATCH 14/14] fix(demo): protect launch credentials and record verified console v2 acceptance --- docs/console-v2-acceptance.md | 28 ++++++++++++++++------ docs/demo-runbook.md | 16 +++++++++---- scripts/run-local-demo.sh | 44 +++++++++++++++++++++++++++-------- 3 files changed, 66 insertions(+), 22 deletions(-) diff --git a/docs/console-v2-acceptance.md b/docs/console-v2-acceptance.md index 28af603..b812dd4 100644 --- a/docs/console-v2-acceptance.md +++ b/docs/console-v2-acceptance.md @@ -3,7 +3,9 @@ Branch `feat/console-v2` from `main` 9371dbe. Not merged. **The author's environment cannot run `dotnet`.** Every "Observed" entry below was executed by the independent verifier (Codex) on macOS arm64 against the commit named, with logs/screenshots in the git-excluded `docs/verification-2026-10-16/v2/` folder. "Claimed" = implemented, not -yet independently observed at the latest commit. +yet independently observed. Final source checkpoint: `9e71d66`; subsequent verifier changes affect only the +launcher and documentation and have their own executed checks below. No source patches were required for the +780-test run. ## 1. Commits by task @@ -26,8 +28,10 @@ Docs: ADR-0011..0014 (+ ADR-0001 status update), `docs/ui-api-contract.md` (v2), | 2f2a28a | Release build 0 warnings/errors; 310 tests pass (baseline) | | 8bb8923 | Release build + 491 tests pass incl. torn-journal regression; osx-arm64 self-contained single-file publish; `/ui`→302 `/ui/`; `/ui/`, nested route, Blazor JS → 200 | | 1ad07c4 (+2 test-only name fixes, applied in 959ce13) | Release build + 723 tests pass; HTTP stream suite: partial-then-error ⇒ Deny/no fallback; length finish relayed + Truncated; post-content stall ⇒ timeout, partial kept, no fallback; empty completion ⇒ 200/Allow. Cache collision probes (delimiter, output-bound) ⇒ calls=2, no false hit. 503/429/timeout fallback with two charged attempts. Ledger migration crash window ⇒ refuses start; clean import preserves spend. Stable pagination; early trace (provider Running before first token) | -| 959ce13 | Release build + **761 tests pass**, no verifier patches; osx-arm64 single-file publish pass; coverage measured at an earlier checkpoint: line 95.14 % / branch 81.94 % | +| 959ce13 | Release build + **761 tests pass**, no verifier patches; osx-arm64 single-file publish pass; coverage measured at an earlier checkpoint: line 95.57 % / branch 83.24 % | | browser (959ce13 era) | connect once; budget edit → preview → apply (v10) with spend preserved; policy split/save (v31); pause primary + approved slow fixture (v32); cache TTL edit (v33) + repeated request = cache hit, no provider call, $0, skipped stages; live provider Running before first token; Ollama discovery → select `qwen2.5-coder:7b` → save → real synthetic sensitive request: Pii (US SSN pattern), served by local Qwen, zero configured provider charge, evidence found; presentation fits 1280×720; Escape restores focus; header local health correct. Screenshots: `qwen-real-{1280,1920}-{dark,light}.png`, `dashboard-1280-dark.png`, `presentation-1280-dark.png`, `round2-*.png`, `budget-applied-v10.png` | +| 9e71d66 + verifier launcher corrections | Full solution Release build: **0 warnings, 0 errors**. Embedded-console test run: **780 passed, 0 failed/skipped**; coverage **95.59% line / 83.65% branch**. Fresh-output `SkipConsolePublish=true`: **780 passed**. Self-contained single-file publishes: **osx-arm64 and linux-x64 passed** (Linux cross-publish only, not executed). Published Mac routes: `/ui/`, nested route and Blazor JS all 200. Launcher Local-only starts, real Qwen synthetic request returns 200, restart retains audit/config; no credentials in normal stdout, private files 0600. Spaced JSON catalog, exact model matching, occupied-port and missing hybrid key/price guards pass. | +| UI round 3 (2a7d5e5, included in 9e71d66) | Created Public profile, granted existing application, previewed and saved v34; real Public and PII Qwen requests succeed. Final classification/escalation visible; previous-result marker and cache original-model provenance verified. Presentation screenshots at 1280×720 and 1920×1080 in light/dark; all trace stages and timings visible. At 900×700 no horizontal page overflow. Evidence: `round3-presentation-*.png`, `final-cache-presentation.png`. | | security probes | invalid enums / null settings ⇒ validation errors (no 500); removed application's key ⇒ 403; app key cannot read admin APIs; admin token cannot authorize inference; browser disconnect ⇒ Cancelled, one estimated charged attempt, no fallback, reservation released | | NativeAOT | **Fails**: IL2104/IL3053 from Anthropic 12.8.0 and Neo4j.Driver 6.2.1 — documented, not suppressed (ADR-0001 status update, runbook §1a). Supported artifact: self-contained single file | @@ -41,10 +45,10 @@ Docs: ADR-0011..0014 (+ ADR-0001 status update), `docs/ui-api-contract.md` (v2), | T04 | ledger, reservations, periods, settle/release, migration | tests + HTTP (concurrency 1×200/5×403, archive preserves spend) | — | | T05 | console endpoint, submissions, trace hub/stream | tests + browser live trace | — | | T06 | fallback, attempt evidence, cache identity, savings, archive/export | tests + HTTP fixture | real cloud fallback not exercised (see §5) | -| T07 | shell, composer, Playground, presentation | browser (both themes, 1280/1920) | round-3 UI (2a7d5e5) **not yet re-observed** | -| T08 | editors, requests archive, evidence export | browser (budget/policy/settings/connections) | profile/grant editor (2a7d5e5) **not yet observed** | -| T09 | launcher, seeds, runbook | seed price regressions written | 45760e9 **not yet built/run**; launcher not yet executed | -| T10 | single CI check; this record | — | final full rerun at HEAD; Linux publish on a supported runner | +| T07 | shell, composer, Playground, presentation | browser (both themes, 1280/1920) | round 3 independently verified (see above) | +| T08 | editors, requests archive, evidence export | browser (budget/policy/settings/connections) | profile/grant editor independently verified | +| T09 | launcher, seeds, runbook | seed tests pass; actual Local-only launcher/restart + Qwen request; credential/model/port guards verified | real cloud smoke remains opt-in and not run | +| T10 | single CI check; this record | final full build/test/coverage, clean skip-console tests, Mac publish/run, Linux cross-publish | GitHub CI and Linux runtime execution not run (branch not pushed) | ## 4. Verifier commands for HEAD @@ -72,4 +76,14 @@ Route checks with GET (not HEAD): `curl -sS -D - -o /dev/null http://localhost:5 - **Identity:** console actions are attributed to the shared admin credential (`OperatorRef = shared-admin-token`); no individual operator attribution until real IAM. - **Real cloud smoke:** BLOCKED / NOT RUN — needs owner-supplied credentials, synthetic prompts and a small cap. -- **NativeAOT:** blocked by dependencies (above). **Linux-x64 publish:** not yet run on a supported runner. +- **NativeAOT:** blocked by dependencies (above). **Linux-x64:** cross-publish passed on macOS; the artifact has not been executed on Linux. + +## 6. Final verifier handoff + +Claude completed through `9e71d66`. While the Mac was locked and Claude was idle, Codex corrected the launcher +and runbook directly, then exercised those changes. Launch with `scripts/run-local-demo.sh` (port 5210); +`OPEN_BROWSER=0` keeps it headless. The existing instance on port 5201 was not changed. + +Local implementation and verification are complete within the stated limits. This is a reviewable feature branch, +not a production certification: no merge/push, real paid cloud call, Linux runtime run or NativeAOT success is claimed. +The scope does not include semantic caching, prompt rewriting, answer-quality evaluation or individual-admin IAM. diff --git a/docs/demo-runbook.md b/docs/demo-runbook.md index 9a2d544..b045cab 100644 --- a/docs/demo-runbook.md +++ b/docs/demo-runbook.md @@ -12,7 +12,12 @@ PROFILE=hybrid OPENAI_API_KEY=… CLOUD_PRICE_IN_1M=… CLOUD_PRICE_OUT_1M=… s ``` The launcher checks Ollama and the model tag, publishes the self-contained binary, starts it on its own port with its own state directory (`/tmp/covenant-v2-demo-/`: audit log, configuration repository, budget ledger), -and opens the console already connected (admin token in the URL fragment, read once, never sent to the server). +and opens the console already connected. The token is read from the URL fragment and removed; it is not sent +in the request URL or access logs, but is subsequently sent in the admin authentication header. +Prerequisites: .NET 10 SDK (unless reusing a publish), Python 3, curl, OpenSSL and lsof. +`OPEN_BROWSER=0` keeps startup headless. Normal output contains no credentials. Owner-only files under +`$STATE/.launch-credentials/` hold the connected console URL and application key. Open the URL privately when +needed; do not copy it into chat, logs or screenshots. Credentials rotate on every launcher run. It never touches another instance (e.g. :5100, :5201). State persists per profile; `FRESH=1` moves it aside (renamed, not deleted). @@ -66,12 +71,13 @@ and **Evidence recorded** → *Open in Requests* for the exact record. | **B** Sensitive → local | Preset B (synthetic SSN 078-05-1120), profile Public demo | classify: **PII (baseline Public, escalated: US SSN pattern)**; policy → ollama only | zero-priced local; evidence shows the signal, never the prompt | | **B′** cloud override refused | B with Advanced → model `openai/` | policy refused: target not eligible for PII; provider **skipped** | no provider call, $0, audited refusal | | **C** missing local | Models & connections → disable the Ollama connection → Preview → Save (new version) → run B | policy refused: no eligible destination; provider skipped; **no cloud call** | re-enable afterwards (another new version) | -| **D** approved fallback | (fixture) Policies → pause the primary route **or** stop the primary provider → run A | provider attempt 1 failed/paused-skipped → attempt 2 on the approved fallback | both attempts in the drawer; failed attempt charged its estimate, never $0 | -| **F** budget | Budgets → lower the cap below spend → Preview → Save → run A | budget refused ("would exceed cap") | spend preserved across the edit; raise the cap again (audited new version) | +| **D** transient-failure fallback | Use an isolated approved failing provider fixture plus a healthy fallback; run A | first attempted provider fails transiently, then the approved fallback serves | two actual attempts in the drawer; failed attempt charged an estimate, plus the fallback charge | +| **D′** skip a paused route | Hybrid: Policies → pause the primary route → Save → run A | primary is skipped without being called; local fallback serves | one actual provider attempt; no charge for the skipped route | +| **F** budget | Requires a nonzero-priced route: real cloud (opt-in) or an isolated fixture with explicitly synthetic prices. First incur spend, then lower cap below spend → Preview → Save → run a fresh uncached request | budget refused ("would exceed cap") | spend preserved; restore cap afterwards. Default zero-priced Local-only cannot demonstrate this spending scenario | | **G** exact cache | Settings → cache TTL 60 → Save; run the same request twice | 2nd run: cache passed, rate limit/pause/budget/provider **skipped (cache_hit)** | $0 no provider call; drawer names the original served connection/model; any config change invalidates | | **H** policy editing | Policies → pause the primary route → Save; run A; pause the whole policy → Save; run A; resume → Save | route paused → fallback serves; policy paused → refused; resumed → primary again | each change is a new version (history + rollback available) | | **Pause** | Header → Pause new provider calls → run D (fresh nonce) → Resume → run D | pause stage refused → then served | cache hits are not stopped by the pause (documented) | -| **Auth** | Applications & workload profiles → disable console testing for demo-app → Save → Run | auth refused (governed 403, audited) | re-enable afterwards | +| **Auth** | Applications & workload profiles → disable console testing for demo-app → Save → Playground | application is unavailable for console selection; Run cannot submit as it | re-enable afterwards. A separate direct API negative test verifies 403 for an unauthorized submission | Stage timings are measured by the server; skipped stages are shown as skipped, never animated as if they ran. @@ -88,6 +94,6 @@ Stage timings are measured by the server; skipped stages are shown as skipped, n | Startup refused | The launcher prints Covenant's reason (e.g. missing hybrid prices, corrupt journal — never auto-repaired silently) | ## 5. Optional: Open WebUI as a client -Base URL `http://localhost:/v1`, API key = the launcher's **/v1 app key** (never the admin token); optional +Base URL `http://localhost:/v1`, API key = the owner-only `$STATE/.launch-credentials/application-key` file (never the admin token); optional header `X-Covenant-Profile` selects a granted profile. Text chat only; streaming supported. Pointing Open WebUI at Ollama directly bypasses Covenant. diff --git a/scripts/run-local-demo.sh b/scripts/run-local-demo.sh index a0fef77..64b9458 100755 --- a/scripts/run-local-demo.sh +++ b/scripts/run-local-demo.sh @@ -6,6 +6,7 @@ # MODEL=qwen3.8:27b-mlx PORT=5212 scripts/run-local-demo.sh # SKIP_PUBLISH=1 scripts/run-local-demo.sh # reuse the last publish # FRESH=1 scripts/run-local-demo.sh # start this profile's isolated state from scratch +# OPEN_BROWSER=0 scripts/run-local-demo.sh # headless; private connection files are listed below # # Isolation: Production environment (user-secrets NOT loaded), its own port and its own state directory # (/tmp/covenant-v2-demo-/: audit log, configuration repository, budget ledger). It never touches @@ -20,6 +21,7 @@ # CLOUD_MODEL default gpt-4o-mini; CLOUD_PRICE_DATE (yyyy-MM-dd) optional # Covenant refuses to start the hybrid seed without explicit prices — no default price is ever assumed. set -euo pipefail +umask 077 PROFILE="${PROFILE:-local-only}" PORT="${PORT:-5210}" @@ -40,11 +42,20 @@ esac say() { printf '\n\033[1m%s\033[0m\n' "$*"; } say "1/5 Checking Ollama at $OLLAMA" -models="$(curl -sS --max-time 5 "$OLLAMA/models")" || { echo "Ollama is not reachable at $OLLAMA (ollama serve, or set OLLAMA=...)"; exit 1; } -if ! grep -q "\"id\":\"$MODEL\"" <<<"$models"; then - echo "Model '$MODEL' is not installed. Installed tags:"; grep -o '"id":"[^"]*"' <<<"$models" | cut -d'"' -f4 | sed 's/^/ /' - echo "Re-run with MODEL=."; exit 1 -fi +command -v python3 >/dev/null || { echo "Python 3 is required to parse the model catalog."; exit 1; } +models="$(curl -fsS --max-time 5 "$OLLAMA/models")" || { echo "Ollama is not reachable at $OLLAMA (ollama serve, or set OLLAMA=...)"; exit 1; } +printf '%s' "$models" | python3 -c ' +import json, sys +try: + models = json.load(sys.stdin)["data"] + ids = [m["id"] for m in models if isinstance(m, dict) and isinstance(m.get("id"), str)] +except (ValueError, KeyError, TypeError): + sys.exit("Invalid model catalog: expected an OpenAI-compatible JSON data array.") +if sys.argv[1] not in ids: + print("Requested model is not installed. Installed tags:") + print("\n".join(" " + model for model in ids)) + sys.exit("Re-run with MODEL=.") +' "$MODEL" echo "ok — $MODEL" if [[ "$PROFILE" == hybrid ]]; then @@ -109,7 +120,9 @@ fi LOG="$STATE/server.log" env "${env_args[@]}" "$OUT/Covenant.Host" >"$LOG" 2>&1 & PID=$! -trap 'kill $PID 2>/dev/null || true' INT TERM +trap 'kill "$PID" 2>/dev/null || true' EXIT +trap 'exit 130' INT +trap 'exit 143' TERM say "4/5 Waiting for the console" code="" @@ -122,14 +135,25 @@ done [[ "$code" == "200" ]] || { echo "No answer on /ui/ (last HTTP '$code'). Log:"; cat "$LOG"; kill $PID; exit 1; } LAUNCH="http://localhost:$PORT/ui/connect#token=$ADMIN" -say "5/5 Running — opening the console (already connected)" -command -v open >/dev/null && open "$LAUNCH" || true +CREDENTIALS="$STATE/.launch-credentials" +mkdir -p "$CREDENTIALS" +chmod 700 "$CREDENTIALS" +printf '%s\n' "$LAUNCH" > "$CREDENTIALS/console-url" +printf '%s\n' "$APPKEY" > "$CREDENTIALS/application-key" +chmod 600 "$CREDENTIALS/console-url" "$CREDENTIALS/application-key" +say "5/5 Running" +if [[ "${OPEN_BROWSER:-1}" == "1" ]]; then + if command -v open >/dev/null; then open "$LAUNCH" || true + elif command -v xdg-open >/dev/null; then xdg-open "$LAUNCH" >/dev/null 2>&1 || true + fi +fi cat <
    OrderTargetStateActions