diff --git a/docs/CONSOLE-DEMO-CLARITY-TASKS.md b/docs/CONSOLE-DEMO-CLARITY-TASKS.md new file mode 100644 index 0000000..8385047 --- /dev/null +++ b/docs/CONSOLE-DEMO-CLARITY-TASKS.md @@ -0,0 +1,55 @@ +# Console usability and real hybrid demonstration — implementation brief + +Owner: Claude implements heavy changes; Codex builds, exercises actual models, configures the user's selected instance on port 5210, and visually verifies. Current base 353faac (PR8 on PR7); branch feat/console-demo-clarity. Preserve prior fixes. Do not merge or touch running servers, secrets, or Ollama. No subagents. Work directly in this checkout. Do not commit until Codex confirms a checkpoint. Read CLAUDE.md scope instructions. + +## Outcome +A conference attendee must understand who requested work, why it went to a given model, who pays, and what was enforced, without reading implementation notes. Real providers only in the live demo. No fake durations, invented health or inferred model competence. User chose Anthropic for Public cloud work and port 5210 as the handoff target. + +## Must implement +1. Shell and responsive layout: remove misleading seed/profile name demo-local-only from primary header (environment is deployment identity, not routing mode). Show active mode and meaningful environment, with details available. Header and body share horizontal gutters/width; remove arbitrary max-width dead space. Programmatically focusing a page title must not produce the huge blue box shown on navigation, while keyboard navigation retains accessible focus. Standardize icon-button dimensions/baselines. Fix Settings form field alignment by proper rows/grid, not blanket label heights that fail on multiline help text. Verify light/dark at 1280x720, 1920x1080, and wide desktop. No content clipping to make a viewport test pass. +2. Applications: explain in plain language that an application is the calling system with an owning team, budget and allowed workloads; console runs on its behalf. Show friendly name/team, not only demo-app. Make add/manage application discoverable from composer. Single application should be identified as the only configured choice with a management link, not a misleading unexplained dropdown. Existing profile/application editor should permit creation, grants, team and console testing with validation. Do not bypass authorization. If adding display-name schema fields use backward-compatible defaults and round-trip tests. +3. Workloads and demo examples: replace cryptic A/B/C presets with named, meaningful examples including (a) public research with web sources, (b) public writing through Anthropic, (c) internal coding through qwen2.5-coder:7b, (d) internal research through stronger local Qwen, (e) synthetic sensitive-data refusal for a cloud-only route, (f) cache hit repeat, and (g) budget refusal. Each card explains expected route, payer/team, and observation; fill all relevant fields coherently (application, profile, workflow/use-case, search, prompt). Do not run automatically. Resolve available configuration, show exact missing prerequisites and a link when unavailable, never silently downgrade. Avoid claiming cache behavior if cache is disabled. Do not replace existing operator config with seeds automatically. Supply an explicit preview/apply demo setup action or documented versioned setup, retaining prior entries. +4. Task routing is policy-driven: current installed IDs on localhost11434 are qwen2.5-coder:7b, qwen3.8:27b-mlx, qwen38-64k:latest. Codex will configure selected real routes. Use granted workload/profile selectors for coding/research; do not pretend keyword routing/quality scoring exists. Public writing -> approved Anthropic model, internal coding -> coder7b, internal research -> qwen3.8:27b-mlx. Ensure matching is unambiguous (classification + profile), with no broad earlier rule shadowing explicit workload rules. Detect/report ambiguous rules if required; no unreviewed cloud fallback for Internal/sensitive. Expose chosen policy, eligible target/fallback and why, before/after run. Preserve user prompt. +5. Search usability: composer readiness tied to current server config/app/profile. Off/Auto/Required must not offer a seemingly working setup when impossible. Give ONE specific actionable cause (disabled -> Settings anchor; no credential -> exact server setup; profile denied -> switch allowed profile only by explicit user action; Local-only -> policy mode). Display the specific runtime reason instead of generic laundry list. Don't auto-upgrade classification or silently turn off Required. Refresh on config apply/reconnect/navigation, preventing stale UI drafts overwriting search settings. Deep links target relevant settings section. Distinguish setup problem, missing city, policy refusal, provider failure. Runtime remains authoritative and fail-closed. +6. Explain trace honestly: millisecond rounding currently produces 0 ms. Use <1 ms for positive sub-ms values; unknown stays unknown, actual zero must not be fabricated. Distinguish identity/cost-owner assignment BEFORE provider invocation from final usage accounting/settlement AFTER execution. Refused requests still have app/team/workload and audit evidence, even if no charge. Rename existing Attribution stage to descriptive 'Record usage' or 'Finalize cost' if it only records post-provider usage. Ensure failure/search charges are finalized through outer audit/settlement as actual backend does. Never show 'attribution skipped' implying anonymous/unaccounted refusals. Include app, team, workload, policy, config version and cost basis in results and requests. Show cache outcome (miss/bypass/hit), not a bare Passed. +7. Animation: meaningful live running stage pulse and transitions from real trace events, reduced-motion support. For instantly completed stages, explicit 'Replay trace' / presentation replay with adjustable pedagogical pacing, clearly labelled replay; keep real recorded durations and final outcome, no synthetic timer delays in actual request execution. Replay never invokes provider, changes records or reruns requests. Cancellation/new run/navigation must cancel old replay and not mix traces. Animation is required, not just CSS on an unseen transient state. +8. Cloud/model setup: existing provider editing must clearly support Anthropic with server credential availability, exact configured models/prices, connection test, and applying a Public route. Add stronger local model from catalog without replacing coder model. No fake health from catalog availability. No invented pricing; unavailable key/price blocks execution with concrete instructions. +9. Demo guide: concise walkthrough that teaches app -> workload/classification -> route -> evidence/cost. Show local coding, stronger local research, real Anthropic Public writing, Tavily search, and one predictable refusal plus its resolution. Distinguish configured capability from tested behavior. + +## Checkpoints and verification +First inspect code and implement a coherent UI/configuration checkpoint, then report files and any architectural questions. Continue remaining scope unless Codex asks to pause. Write focused tests for readiness reasons, form/config round-trip, workload routing, preset prerequisites and attribution on refusal/failed search/cache, trace duration/replay logic. No new dependencies unless necessary. Do not claim runs; Codex runs .NET and browser. Do not weaken assertions to pass. If you cannot run tool calls, continue code and report precise blockers. + +Acceptance: One actual 5210 instance after deliberate restart; matching build/config version visible. Real Anthropic call requires user credential (Codex handles privately). All screenshot defects rechecked visually, not just zero horizontal overflow. No generic product-readiness claim from unit test count alone. + +## Verification discoveries (Codex) +- Port 5210 is currently not listening; persisted state exists at /tmp/covenant-v2-demo-local-only (active config v2). Codex will relaunch THIS state after final publish, not hand off a different port. +- Actual qwen3.8:27b-mlx responds, but consumes output budget on reasoning first: max_tokens=180 left a truncated visible answer. Research example needs a practical limit (e.g. 1024–2048), clear finish_reason=length handling, and no invented claim that the token limit covers only visible text. Do not expose internal reasoning as explanation/evidence. Codex tests full larger-model pipeline. + + +## Executed checkpoint review (Codex, while native Claude window locked) +Release snapshot built with 0 warnings/errors. Full suite: 914 pass, one failure in AddApplication roundtrip: applications[3].max_output_tokens must be >=1. Codex fixed AddApplication to explicitly set MaxOutputTokens=1024, matching Host default. Preserve this fix. Evidence_names_the_policy test passed. +Remaining review: WorkspaceConfig concurrently fetches config and search status; mismatched versions must not retain stale Ready indefinitely. Error status must not present old Ready. Refresh budget facts after completed requests as well. Runtime5210 is v4 with engineering-assistant/internal-coding -> coder7b and research-assistant/internal-research -> Qwen27B, actual requests passed with correct team/workflow tags. public-research route/profile and communications-assistant/public-writing also registered; actual Anthropic credential still pending. Preserve runtime entries. + +## Browser review of checkpoint (17:21 UTC) + +- BLOCKER: Examples defaults open and renders seven full documentation cards inside the narrow composer. At 1280×720 the first card alone fills the visible request pane; the prompt is buried several screens down. Replace with a compact example selector/list of titles + readiness; expand ONLY the selected example's explanation, preferably a short summary with optional details. Choosing an example should bring the populated prompt into view. Default composer must show its prompt immediately. Keep Run visible. This is the exact excessive scrolling complaint we must solve, not add to. +- Application/profile values truncate at 1280×720 (communications-ass... / Public writing baseline...). Use friendly display names and put baseline/team in the helper text instead of stuffing the select. Ensure selected value remains understandable. +- Missing whitespace before Profile permissions link in search readiness note. +- docs/demo-guide.md section2 says same application/team as coding, but actual configured apps are engineering-assistant/team engineering and research-assistant/team research. Derive words from the selected example or explain these different owners accurately. +- Settings inputs are horizontally aligned in the tested checkpoint at 1920 and 1280. Preserve that fix. +- Codex has already fixed ProfileEditing.AddApplication MaxOutputTokens=1024; checkpoint full suite passes915. Evidence_names_the_policy passed. Pending latest changes need another build. +- WorkspaceConfig.LoadAllAsync currently preserves stale WebSearch on error and can combine configuration vN with readiness vN-1. Clear readiness on failure/version mismatch; composer must not show stale Ready. Refresh budget states after requests. Guard disconnect/reconnect against completion of an old session's load. + +### Real Tavily run on 5210/v4 +The UI public-research example completed: 3 retrieved sources, 10.30s, 1156 input/299 output tokens, $0.008 tool charge, team research. But the .NET release query returned two irrelevant sources and a weak third-party release page; the answer asserted dubious release/support facts. Search integration works; answer quality is NOT validated. Improve the demonstration query to a bounded authoritative-source task (e.g. site:learn.microsoft.com or official dotnet release notes), and make clear sources are retrieved rather than independently verified. Don't present this particular run as proof of accurate current knowledge. Current overall Cost says 'estimated provider charge' although the only charge is Tavily; ensure summary distinguishes tool cost from inference cost. + +### Executed checkpoint3 validation fix +The new Routing_a_workload_is_additive_unambiguous_and_passes_host_validation test failed: new PolicyDto serialized retry:null, overriding the Host default and failing required-value validation. Codex added explicit RetrySettingsDto (1 attempt,120000ms,empty retry list) in WorkloadRouteSetup. All21 DemoTraceAndSetupTests pass with this correction in the isolated build. Preserve the fix. Full updated suite still requires rerun. + +## Runtime acceptance, October17, configuration v5/v6 +- Anthropic Models API accepted saved key; Claude Sonnet5.5 was listed. Public writing real request req_764cfb82ecd849b3a8a8456f4de48634:39input/101output, $0.001088, communications-assistant/team communications. Prices2/10USD per million from official model overview. Secret remains outside Git. +- Sensitive explicit cloud pin req_5c0ac36b25b7466b8f5258e12f147849:403 at policy, no attempts, no charge, owner retained. Synthetic invalid marker only. +- Exact-cache pair req_e635a1a90ad04c16b699300cfc69cf04 / req_c8743ab02eff4089b0708429dcb468a1:first1providerattempt,$0.000462; second0attempts,$0,owner retained. +- Isolated budget-demo app under v6,cap$0.0001: req_5b5c1d82dac6477a84ea22c211e0cfff refused atbudget with0attempts,$0,team demo-controls retained. Normal application caps unchanged. +- Browser request drawer verified real Anthropic model, input/output usage, reserved/settled costs and policy. Trace replay visibly advances recorded steps under Replay banner. +- Checkpoint4 suite:942passing. Default-application follow-up still under implementation; final build/visual review pending. diff --git a/docs/demo-guide.md b/docs/demo-guide.md new file mode 100644 index 0000000..21daacb --- /dev/null +++ b/docs/demo-guide.md @@ -0,0 +1,113 @@ +# Covenant demo guide: who asked, where it went, who pays, what was enforced + +A 10-minute walkthrough for a live audience. Every step uses real providers. The console shows only recorded facts: +measured durations, observed health and settled charges. A step marked **configured** depends on your setup; a step +marked **tested** was exercised on the demo machine. See "What has been tested" at the end; don't present a configured +capability as tested behaviour. + +## The idea in one line + +**Application → workload → classification → policy → route → evidence and cost.** + +| Concept | Meaning | +|---|---| +| Application | The calling system, e.g. a support portal. It belongs to a team, and that team and its budgets pay. | +| Workload profile | The declared kind of work, e.g. *Internal coding*. It carries a trusted baseline classification. | +| Detection | Can only **raise** the classification (an SSN pattern turns Public into PII). It never lowers it. | +| Policy | Exactly one policy matches (workload profile + classification). It names the model and any approved fallback. Covenant does not route on prompt keywords or guess model quality. | +| Evidence | Every request is recorded, including refused ones: application, team, workload, policy, configuration version, cache outcome and cost basis. | + +## 0. Before the audience arrives (once, versioned, nothing replaced) + +### Server (restart required; the console cannot do these) + +- **Anthropic:** `Anthropic__ApiKey` in the server environment, plus `api.anthropic.com:443` on `Providers__ProbeAllowList`. +- **Tavily:** `Tavily__ApiKey`, plus `api.tavily.com:443` on `Providers__ProbeAllowList`. +- **Local models:** installed in Ollama, e.g. `qwen2.5-coder:7b` and `qwen3.8:27b-mlx`. `GET /v1/models` listing a model is availability, not health. + +### Console (each step is one Preview impact → Save & apply, i.e. a new configuration version) + +1. **Connections → Anthropic:** + - Add or verify the connection, the exact model id, and its input/output prices from the provider's current price list. Covenant never assumes a price. + - **Test** it (connections with an explicit endpoint), or run the Public writing example below. +2. **Connections → Ollama:** add the stronger research model next to the coder model, from the connection's model list. Existing models stay. +3. **Route each workload with "Route a workload here…"** on the model's row: + - `qwen2.5-coder:7b` → **Internal coding** + - `qwen3.8:27b-mlx` → **Internal research** + - the Anthropic model → **Public writing** (cloud models serve Public workloads only) + + Each action only **adds**: the workload profile if missing, a policy scoped to that profile, and a grant to the console-testable applications. Existing policies are untouched. A second rule for the same workload is refused, because it would be ambiguous. + + The preview lists every grant it adds. If a workload belongs to one caller only (e.g. research to `research-assistant`), remove the other grants in the draft before Save & apply. +4. **Settings → Web search:** enable it, enter the price per credit, then allow it on a Public profile (Policies → Applications & workload profiles). +5. **Optional:** + - Settings → Operational → cache TTL > 0, for the cache example. + - A tiny application-scoped budget on a separate demo application, for the budget example. +6. **Research output bound:** set the research application's max output tokens to at least 2048. The research model reasons before it answers; a low bound truncates it, and the result says *Truncated*. + +**Playground → Examples** shows, for each example, whether it is ready. It lists exactly what is missing, with a link to the fix. + +## 1. Internal coding on the local coder model + +1. Use the **Internal coding on the local coder model** example and press **Preview route**. It shows the policy, `ollama/qwen2.5-coder:7b`, local, and no fallback. **Run.** +2. Point at: + - The trace (*Identify caller* assigns the application and team before anything else). + - The route: local, configured $0, infrastructure excluded. + - The evidence row: application, team, workload, policy, configuration version. + +## 2. Stronger local research (a different caller and payer) + +1. Use **Internal research on the stronger local model**. Its *Details* name who runs it. Read the owner from the card; don't assume it is the coding caller. + - On the demo machine (configuration v5) coding runs as `engineering-assistant` (team engineering) and research as `research-assistant` (team research). + - Different calling application, different team paying, different workload profile, so a different policy and model (`qwen3.8:27b-mlx`). +2. The provider stage shows the real measured time. +3. If the output bound is below what the example requests, the card says so before you run. + +## 3. Public writing through Anthropic (real cloud call) + +1. Use **Public writing through Anthropic**. The preview shows the Anthropic model. +2. **Run.** The charge is **reported usage × configured price** and is settled against the team's budgets. + +## 4. Fresh facts with governed web search + +1. Use **Public research with web sources** (Required). The query is bounded to Microsoft's official .NET release notes. +2. The trace shows **Web search** passed; then **Web sources** lists what was actually retrieved, separately from the model's `[n]` citations. +3. The search is charged as its own tool call. +4. Readiness is checked first: if the server cannot search, the composer names the one cause (key, egress, mode, disabled, price or profile) and links to the fix. +5. Say it plainly: the sources are **retrieved, not independently verified**. Covenant proves which pages it fetched and what it cost, not that the answer is correct — check the answer against the cited page. + +## 5. One predictable refusal, and its resolution + +1. Use **Sensitive data never goes to the cloud**. The prompt holds the synthetic marker `000-12-3456`. It is explicitly invalid (area 000 is never assigned), but it matches the detector. +2. The example pins the Anthropic model explicitly. +3. **Run:** **Refused at Policy**. PII is never routed to a cloud destination, and nothing is sent. +4. Point at the evidence: the request is still attributed to its application, team and workload, with no charge. +5. **Resolution:** switch Model back to **Let policy choose** and run again. PII routes to the local model and is served. + +## 6. Optional: cache and budget + +- **Cache** (only when the TTL > 0): run the cache example twice. The second run is a **Cache hit** at $0, still governed and audited. With the TTL at 0 the card says the cache is off and makes no claim. +- **Budget:** the budget example runs as the low-budget demo application. It shows **Refused at Budget** before any spend, and the reservation is released. Other examples never pick an application whose budget is exhausted. + +## Presenting the trace + +- Live requests animate from real events only: a running stage pulses, and a finished one settles into its state. +- Stages that finished in under a millisecond show **<1 ms**, never a rounded 0. +- For a step-by-step explanation use **Replay trace** (Slow / Normal / Fast). It re-reveals the **recorded** events with their recorded durations and outcome. It never calls a model or changes a record, and a new run cancels it. +- *Finalize cost* runs after the provider answered. A refused request shows **No usage** there and is still recorded with its owner. + +## What has been tested vs configured + +Executed on October 17, 2026 at localhost:5210, using saved configuration versions v4–v6. Records remain in Requests. Rehearse again after changing models, policies or prices. + +| Step | Status on the demo machine | +|---|---| +| Local coder route | Passed: engineering-assistant → Qwen coder 7B; team engineering recorded. | +| Stronger local research route | Passed: research-assistant → Qwen 27B, complete concurrency comparison with output cap 2048; team research recorded. | +| Anthropic Public writing | Passed on v5: Claude Sonnet 5.5, 39 input / 101 output tokens, $0.001088; team communications. | +| Tavily search | tested: 3 sources retrieved and charged ($0.008, team research) on v4; answer accuracy NOT validated (that run used an unbounded query) | +| Sensitive refusal | Passed: synthetic PII pinned to Claude refused at policy; no provider attempt, $0, owner retained. | +| Cache hit | Passed: first Claude call $0.000462; identical repeat $0 with no provider attempt. | +| Budget refusal | Passed on v6: isolated budget-demo application with $0.0001 cap refused before provider call, owner retained. | + +Unit-test counts are not product readiness. Only the recorded runs above are. diff --git a/docs/demo-runbook.md b/docs/demo-runbook.md index b045cab..2c84240 100644 --- a/docs/demo-runbook.md +++ b/docs/demo-runbook.md @@ -68,7 +68,7 @@ and **Evidence recorded** → *Open in Requests* for the exact record. |---|---|---|---| | **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** Sensitive → local | Preset B (synthetic SSN 000-12-3456), 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** 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 | diff --git a/docs/ui-api-contract.md b/docs/ui-api-contract.md index e565181..49bd1ed 100644 --- a/docs/ui-api-contract.md +++ b/docs/ui-api-contract.md @@ -359,3 +359,19 @@ model-invoked tool. `/v1` is unchanged (always `web_search` off). reservation), `estimated_unreported` (succeeded without usage: the reservation), `no_call` (never sent: $0, released). `Usage.CostUsd`/`SettledUsd` include tool charges; the request-level `CostBasis` aggregates attempts and tool calls (`mixed` when they differ). + +# Console demo clarity (2026-10-17, additive) + +- `config.applications[].display_name` (≤ 100) and `description` (≤ 300): optional, display only, null by default. They + are never used for authorization or routing. `GET /admin/applications` rows add `display_name`, `description` and + `budgets` (the ids of the budgets that apply: global, `team:`, `application:`). +- Audit record (nullable, absent on older records ⇒ Not recorded): + - `PolicyId`: the policy that decided the route; null when no policy matched or the request stopped earlier. + - `CacheOutcome`: one of `hit`, `miss`, `bypass_web_search`, `disabled`, `not_reached`. +- Trace `cache` stage: + - `passed` with `reason_code` `cache_miss` (looked up, no entry) or `cache_hit`; + - `skipped` with `cache_disabled` (TTL 0, no lookup) or `web_search_bypass`. + - A disabled cache no longer reports `passed`. +- Console wording only (wire names unchanged): stage `auth` is shown as "Identify caller" (assigns application, team + and workload before anything runs); stage `attribution` is shown as "Finalize cost" (prices usage after the provider + answered; a refused request shows "No usage" and is still attributed). diff --git a/scripts/run-local-demo.sh b/scripts/run-local-demo.sh index b6d8d2b..154533d 100755 --- a/scripts/run-local-demo.sh +++ b/scripts/run-local-demo.sh @@ -94,7 +94,7 @@ 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" + Covenant__Environment="${ENV_NAME:-local-demo-$PORT}" Config__Seed="$SEED" Local__Endpoint="$OLLAMA" Local__ModelId="$MODEL" diff --git a/src/Covenant.Core/Configuration.cs b/src/Covenant.Core/Configuration.cs index 25e09b9..6a8e78e 100644 --- a/src/Covenant.Core/Configuration.cs +++ b/src/Covenant.Core/Configuration.cs @@ -117,6 +117,11 @@ public sealed record ApplicationConfig public string? DefaultProfile { get; init; } /// Enforced output bound used for reservation and sent to the provider (ADR-0014). public int MaxOutputTokens { get; init; } = 1024; + /// Human name of the calling system ("Support portal"). Optional; null ⇒ the console shows the id. Display only — + /// never used for authorization or routing. + public string? DisplayName { get; init; } + /// Plain-language purpose of the calling system. Optional, display only. + public string? Description { get; init; } } public sealed record WorkloadProfileConfig diff --git a/src/Covenant.Core/Decisions.cs b/src/Covenant.Core/Decisions.cs index 40bdbc4..4f1368c 100644 --- a/src/Covenant.Core/Decisions.cs +++ b/src/Covenant.Core/Decisions.cs @@ -88,7 +88,11 @@ public sealed record AuditEntry( // ---- v3 continued (ADR-0015, additive, nullable): governed web search metadata (no query/snippets) and // non-inference tool calls with their own charges, separate from provider Attempts. AuditWebSearch? WebSearch = null, - IReadOnlyList? ToolCalls = null); + IReadOnlyList? ToolCalls = null, + // ---- v3 continued (console demo clarity, additive, nullable): WHICH policy decided the route, and what the exact + // cache did (hit | miss | bypass_web_search | disabled | not_reached). Absent on older records ⇒ "Not recorded". + string? PolicyId = null, + string? CacheOutcome = 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. diff --git a/src/Covenant.Core/Execution.cs b/src/Covenant.Core/Execution.cs index ccf513c..10f87d6 100644 --- a/src/Covenant.Core/Execution.cs +++ b/src/Covenant.Core/Execution.cs @@ -57,6 +57,10 @@ public static class TraceReasons public const string SearchEmpty = "search_empty"; /// Cache stage: a triggered web-search request never reads or writes the exact cache. public const string WebSearchBypass = "web_search_bypass"; + /// Cache stage: exact cache disabled in configuration (TTL 0). + public const string CacheDisabled = "cache_disabled"; + /// Cache stage passed: looked up, no entry (the request continued to the provider). + public const string CacheMiss = "cache_miss"; /// Default code of a denial when the denying stage did not name a finer one. public static string ForDenial(DenialKind kind) => kind switch @@ -198,3 +202,13 @@ public static long InputTokenBound(IReadOnlyList messages) return Math.Max(1, bound); } } + +/// What the exact cache did for one request (audit CacheOutcome, console wording). +public static class CacheOutcomes +{ + public const string Hit = "hit"; + public const string Miss = "miss"; + public const string BypassWebSearch = "bypass_web_search"; + public const string Disabled = "disabled"; + public const string NotReached = "not_reached"; +} diff --git a/src/Covenant.Core/InferenceContext.cs b/src/Covenant.Core/InferenceContext.cs index 18d73e6..711b668 100644 --- a/src/Covenant.Core/InferenceContext.cs +++ b/src/Covenant.Core/InferenceContext.cs @@ -82,6 +82,8 @@ public void BindConsoleIdentity(PreAuthenticatedIdentity identity, string operat /// Set by the cache stage on a hit: served without any provider call, cost $0. public bool ServedFromCache { get; set; } + /// What the exact cache did for this request (); null = cache stage not reached. + public string? CacheOutcome { get; set; } public bool IsDenied => DenialReason is not null; @@ -186,6 +188,19 @@ public void Deny(string reason, DenialKind kind = DenialKind.Governance, string? /// "skipped" instead of "passed" when it hands over or returns. public void MarkCurrentStageSkipped(string reasonCode) => _pendingStageSkip = reasonCode; + /// The current stage passed with a specific outcome worth showing (e.g. cache "cache_miss"); emitted as the + /// reason code of its "passed" event instead of a bare Passed. + public void MarkCurrentStagePassed(string reasonCode) => _pendingStagePass = reasonCode; + + private string? _pendingStagePass; + + internal string? TakeStagePass() + { + var s = _pendingStagePass; + _pendingStagePass = null; + return s; + } + internal string? TakeStageSkip() { var s = _pendingStageSkip; diff --git a/src/Covenant.Core/Pipeline.cs b/src/Covenant.Core/Pipeline.cs index cb2c20c..9fefec9 100644 --- a/src/Covenant.Core/Pipeline.cs +++ b/src/Covenant.Core/Pipeline.cs @@ -98,7 +98,8 @@ private static async Task RunStageAsync( // A stage that had nothing to do (e.g. web search Off / not triggered) reports "skipped" with its reason, // never a misleading "passed". var skip = c.TakeStageSkip(); - c.Trace(stageName, skip is null ? TraceStates.Passed : TraceStates.Skipped, watch.Elapsed.TotalMilliseconds, skip); + var pass = c.TakeStagePass(); + c.Trace(stageName, skip is null ? TraceStates.Passed : TraceStates.Skipped, watch.Elapsed.TotalMilliseconds, skip ?? pass); } return next(c, t); }; @@ -132,8 +133,9 @@ private static async Task RunStageAsync( else { var skip = ctx.TakeStageSkip(); + var pass = ctx.TakeStagePass(); ctx.Trace(stageName, skip is null ? TraceStates.Passed : TraceStates.Skipped, watch.Elapsed.TotalMilliseconds, - skip ?? (ctx.ServedFromCache && stageName == "cache" ? TraceReasons.CacheHit : null)); + skip ?? pass ?? (ctx.ServedFromCache && stageName == "cache" ? TraceReasons.CacheHit : null)); } } diff --git a/src/Covenant.Governance/Audit.cs b/src/Covenant.Governance/Audit.cs index 9a5c394..6092720 100644 --- a/src/Covenant.Governance/Audit.cs +++ b/src/Covenant.Governance/Audit.cs @@ -93,7 +93,9 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance ServedConnectionId: v3 && served ? ctx.ServedTarget?.AdapterKey : null, // ADR-0015: bounded search metadata (no query, location or snippets) and the separate tool-call charges. WebSearch: v3 ? ctx.WebSearch?.ToAudit() : null, - ToolCalls: v3 && ctx.ToolCalls.Count > 0 ? ctx.ToolCalls.Select(t => t.ToAudit()).ToList() : null); + ToolCalls: v3 && ctx.ToolCalls.Count > 0 ? ctx.ToolCalls.Select(t => t.ToAudit()).ToList() : null, + PolicyId: v3 ? ctx.Policy?.PolicyId : null, + CacheOutcome: v3 ? ctx.CacheOutcome ?? CacheOutcomes.NotReached : null); // CancellationToken.None: a cancelled request must still produce its audit record. await sink.EnqueueAsync(entry, CancellationToken.None); diff --git a/src/Covenant.Governance/Cache.cs b/src/Covenant.Governance/Cache.cs index 0c19ed9..d055826 100644 --- a/src/Covenant.Governance/Cache.cs +++ b/src/Covenant.Governance/Cache.cs @@ -120,6 +120,8 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance int maxEntries = ctx.Configuration?.Config.Settings.CacheMaxEntries ?? config.MaxEntries; if (ttl <= 0 || ctx.Policy?.Route is not { } route) { + ctx.CacheOutcome = CacheOutcomes.Disabled; + if (ttl <= 0) ctx.MarkCurrentStageSkipped(TraceReasons.CacheDisabled); await next(ctx, ct); return; } @@ -129,6 +131,7 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance if (WebSearchPlanner.Evaluate(ctx.Request).Triggered) { ctx.MarkCurrentStageSkipped(TraceReasons.WebSearchBypass); + ctx.CacheOutcome = CacheOutcomes.BypassWebSearch; await next(ctx, ct); return; } @@ -137,6 +140,7 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance if (cache.TryGet(key, out var hit, out var servedTarget)) { ctx.ServedFromCache = true; + ctx.CacheOutcome = CacheOutcomes.Hit; 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 } }; @@ -145,6 +149,8 @@ public async Task InvokeAsync(InferenceContext ctx, PipelineDelegate next, Cance return; // budget, provider, attribution all skipped — nothing spent, nothing to price } + ctx.CacheOutcome = CacheOutcomes.Miss; + ctx.MarkCurrentStagePassed(TraceReasons.CacheMiss); await next(ctx, ct); if (!ctx.IsDenied && ctx.Response is { } fresh && !ctx.ServedFromCache) diff --git a/src/Covenant.Governance/ConfigValidation.cs b/src/Covenant.Governance/ConfigValidation.cs index 7b2589f..8145bd6 100644 --- a/src/Covenant.Governance/ConfigValidation.cs +++ b/src/Covenant.Governance/ConfigValidation.cs @@ -293,6 +293,8 @@ public static ConfigValidationResult Validate(CovenantConfig c, ValidationEnviro Err($"{p}.default_profile", "default_profile_not_granted", $"default profile '{def}' is not granted to '{app.Id}'"); } if (app.MaxOutputTokens < 1) Err($"{p}.max_output_tokens", "invalid_setting", "max output tokens must be ≥ 1"); + if (app.DisplayName is { Length: > 100 }) Err($"{p}.display_name", "invalid_setting", "display name must be at most 100 characters"); + if (app.Description is { Length: > 300 }) Err($"{p}.description", "invalid_setting", "description must be at most 300 characters"); } // ---- budgets ---- diff --git a/src/Covenant.Host/ConfigAdminApi.cs b/src/Covenant.Host/ConfigAdminApi.cs index fc45055..abe789f 100644 --- a/src/Covenant.Host/ConfigAdminApi.cs +++ b/src/Covenant.Host/ConfigAdminApi.cs @@ -209,6 +209,11 @@ public static void MapConfigAdmin(this WebApplication app, ConfigAdminServices s ConsoleTesting = a.ConsoleTesting, GrantedProfiles = a.GrantedProfiles.ToList(), DefaultProfile = a.DefaultProfile, + DisplayName = a.DisplayName, + Description = a.Description, + Budgets = s.Runtime.Current.Config.Budgets + .Where(b => b.Scope == "global" || b.Scope == "team:" + a.Team || b.Scope == "application:" + a.Id) + .Select(b => b.Id).ToList(), }).ToList(); return Json(list, ConfigJsonContext.Default.ListApplicationView); }); diff --git a/src/Covenant.Host/ConfigContracts.cs b/src/Covenant.Host/ConfigContracts.cs index c23d504..4f1c928 100644 --- a/src/Covenant.Host/ConfigContracts.cs +++ b/src/Covenant.Host/ConfigContracts.cs @@ -141,6 +141,10 @@ public sealed class ApplicationView public required bool ConsoleTesting { get; init; } public required List GrantedProfiles { get; init; } public string? DefaultProfile { get; init; } + public string? DisplayName { get; init; } + public string? Description { get; init; } + /// Budgets that apply to this application's requests (global, its team, the application) — ids only. + public List Budgets { get; init; } = []; } public sealed class SimulateRequest diff --git a/src/Covenant.Ui/Components/ExamplePicker.razor b/src/Covenant.Ui/Components/ExamplePicker.razor new file mode 100644 index 0000000..b72950e --- /dev/null +++ b/src/Covenant.Ui/Components/ExamplePicker.razor @@ -0,0 +1,93 @@ +@inject PlaygroundState Pg +@inject WorkspaceConfig Ws +@inject Interop Interop + +@* Demo examples as a COMPACT selector (browser review: seven open cards buried the prompt at 1280×720). One row: pick an + example by title (readiness in the option text), then "Use example" fills the composer and moves focus to the filled + prompt. Only the selected example shows a one-line expectation; its full explanation, route, payer and any missing + prerequisites (with links) are behind "Details". Nothing runs and nothing changes configuration. *@ + +
+
+ + + @if (Selected is { } sel) + { + + } +
+ @if (Selected is { } s) + { +
+ @(s.Ready ? "Expect: " + s.Example.Expected : "Needs setup: " + (s.Missing.FirstOrDefault()?.Text ?? "prerequisites missing.")) +
+ Details + @s.Example.Teaches + @if (s.Ready) + { +
+
Runs as
@AppName(s.ApplicationId) · workload @ProfileName(s.ProfileId)
+
Route now
@s.ConfiguredRoute
+
Pays
@s.Payer
+
Observe
@s.Example.Observe
+
+ @if (s.OutputNote is { } on) + { + @on + } + } + else + { +
    + @foreach (var m in s.Missing) + { +
  • @m.Text@(m.Href is null ? "" : " ")@if (m.Href is { } href) { @(m.HrefLabel ?? "Fix") }
  • + } +
+ } +
+
+ } +
+ +@code { + /// Element-id prefix of the composer (the prompt is "<prefix>-prompt"). + [Parameter] public string IdPrefix { get; set; } = "cmp"; + + private string? _selected; + + private ExampleResolution? Selected + => (_selected ?? Pg.Form.ExampleId) is { Length: > 0 } id ? Pg.Examples.FirstOrDefault(e => e.Example.Id == id) : null; + + private bool IsActive(ExampleResolution r) + => string.Equals(Pg.Form.ExampleId, r.Example.Id, StringComparison.Ordinal) && DemoExamples.StillMatches(r.Example, Pg.Form); + + private void OnSelect(ChangeEventArgs e) + { + var v = e.Value?.ToString(); + _selected = string.IsNullOrEmpty(v) ? null : v; + } + + private async Task UseAsync(ExampleResolution r) + { + if (!r.Ready || Pg.Running) return; + _selected = r.Example.Id; + var preview = Pg.ApplyExampleAsync(r); // fills synchronously, then previews the route + try { await Interop.FocusElementAsync(IdPrefix + "-prompt"); } catch (JSException) { /* focus is a convenience */ } + await preview; + } + + private string AppName(string? id) + => ComposerRules.Find(Ws.Applications, id) is { } app ? ComposerRules.ApplicationName(app) + " (team " + app.Team + ")" : id ?? "—"; + + private string ProfileName(string? id) + => ComposerRules.Profile(Ws.Profiles, id) is { } p ? (p.Name ?? p.Id) + " (" + p.Baseline + ")" : id ?? "—"; +} diff --git a/src/Covenant.Ui/Components/ProfilesEditor.razor b/src/Covenant.Ui/Components/ProfilesEditor.razor index 43b4f66..3210fd1 100644 --- a/src/Covenant.Ui/Components/ProfilesEditor.razor +++ b/src/Covenant.Ui/Components/ProfilesEditor.razor @@ -181,10 +181,65 @@ @* ---- Applications (existing only) ---- *@ -
+

Applications

- Existing applications only — keys are startup secrets (Auth:Keys). + The calling systems. Each belongs to a team that pays for its requests. + + @if (Editing && _newApp is null) + { + + }
+
@ProfileEditing.ApplicationKeysExplained
+ @if (Editing && _newApp is { } na) + { + var naProblems = ProfileEditing.Problems(na, Cfg); +
+

New application (draft)

+
+
+ + +
+
+ + + Used in evidence and by its startup key. +
+
+ + + Team budgets and attribution use this. +
+
+ + +
+
+
+ Allowed workloads (granted profiles) + @foreach (var pid in Cfg.Profiles.Select(x => x.Id)) + { + var gid = pid; + + } +
+ + @if (naProblems.Count > 0) + { +
    + @foreach (var pp in naProblems) {
  • @pp
  • } +
+ } +
+ + +
+
+ } @if (Cfg.Applications.Count == 0) {
No applications are configured. Applications and their keys are defined at startup.
@@ -199,8 +254,12 @@
  • - @app.Id - team @app.Team · max output @(app.MaxOutputTokens?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "server default") tokens + @ProfileEditing.ApplicationName(app.Id, app.DisplayName) + @if (!string.IsNullOrWhiteSpace(app.Description)) + { + @app.Description + } + @app.Id · team @app.Team · max output @(app.MaxOutputTokens?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "server default") tokens
    @@ -214,7 +273,15 @@ {
    - + + +
    +
    + + +
    +
    +
    @@ -276,6 +343,36 @@ private NewProfileForm? _newProfile; private string? _removeAsk; + private NewApplicationForm? _newApp; + + private void StartCreateApp() + { + _newApp = new NewApplicationForm { Id = ConnectionRules.UniqueId("app", Cfg.Applications.Select(a => a.Id)) }; + _newProfile = null; + } + + private static void ToggleNewGrant(NewApplicationForm f, string profileId, ChangeEventArgs e) + { + bool on = e.Value is bool b && b; + f.GrantedProfiles.Remove(profileId); + if (on) f.GrantedProfiles.Add(profileId); + if (f.DefaultProfile is { } d && !f.GrantedProfiles.Contains(d)) f.DefaultProfile = null; + f.DefaultProfile ??= f.GrantedProfiles.FirstOrDefault(); + } + + private async Task AddAppAsync(NewApplicationForm f) + { + if (!Editing || Editor.Draft is not { } d) return; + if (ProfileEditing.AddApplication(d, f).Count > 0) return; + _newApp = null; + Editor.Touch(); + await Editor.ValidateAsync(); + } + + private void SetAppName(ApplicationDto a, ChangeEventArgs e) => Result("a:" + a.Id, ProfileEditing.SetDisplayName(a, e.Value?.ToString())); + + private void SetAppDescription(ApplicationDto a, ChangeEventArgs e) => Result("a:" + a.Id, ProfileEditing.SetApplicationDescription(a, e.Value?.ToString())); + private void StartCreate() { _newProfile = new NewProfileForm { Id = ProfileEditing.UniqueId("profile", Cfg), Baseline = "Internal" }; diff --git a/src/Covenant.Ui/Components/RequestComposer.razor b/src/Covenant.Ui/Components/RequestComposer.razor index dbcf340..abfc0d5 100644 --- a/src/Covenant.Ui/Components/RequestComposer.razor +++ b/src/Covenant.Ui/Components/RequestComposer.razor @@ -6,32 +6,45 @@ @* The shared request composer (Playground and the Overview compact composer bind the SAME PlaygroundState form). "Run as" lists GET /admin/applications: only enabled + console-testing applications are selectable; the others stay visible, disabled, with the reason. The profile select offers ONLY the application's granted profiles. - Presets populate; Run is always explicit; nothing here submits on render, on preset click or on reload. *@ + Examples populate; Run is always explicit; nothing here submits on render, on example click or on reload. *@
    - - - @if (AppHelp is { } ah) + @{ var only = ComposerRules.OnlySelectable(Ws.Applications); var current = ComposerRules.Find(Ws.Applications, Pg.Form.ApplicationId); } + @if (only is not null && string.Equals(only.Id, Pg.Form.ApplicationId, StringComparison.Ordinal)) { - @ah + Run as (calling application) +
    + @ComposerRules.ApplicationName(only) + @if (!string.IsNullOrWhiteSpace(only.DisplayName)) {  @only.Id } +
    + The only application allowed to run console requests. Add or manage applications + } + else + { + + + @(AppHelp ?? "The system this request comes from.") Add or manage applications + } + @if (current is not null) + { + @current.Id · @ComposerRules.PayerText(current)@(string.IsNullOrWhiteSpace(current.Description) ? "" : " · " + current.Description) }
    - - @{ var app = ComposerRules.Find(Ws.Applications, Pg.Form.ApplicationId); var granted = ComposerRules.GrantedProfiles(app); } + + @{ var app = current; var granted = ComposerRules.GrantedProfiles(app); } + @{ var selectedProfile = ComposerRules.Profile(Ws.Profiles, Pg.Form.ProfileId); } + + @if (selectedProfile is not null) + { + Baseline @PolicyText.ClassificationLabel(selectedProfile.Baseline)@(string.IsNullOrWhiteSpace(selectedProfile.Description) ? "" : " · " + selectedProfile.Description). + } + Policy routes by this workload; detection can only raise the classification. +
    -
    - Demo presets -
    - Presets - @foreach (var p in ScenarioPresets.All) - { - var preset = p; - - } -
    -
    - @if (CurrentPreset is { } cur) + + @if (!Compact) { - Expected: @cur.Expectation + } @if (Pg.PresetNote is { } pn) { @@ -77,32 +85,53 @@ }
    - @* Search options stay visible in both composers; never silently reuse a hidden egress setting. *@ - @* ADR-0015: governed web sources. The Host decides (cue, permissions, budget) and reports what actually happened. *@ -
    -
    - Web sources -
    - @foreach (var m in new[] { WebSourcesMode.Off, WebSourcesMode.Auto, WebSourcesMode.Required }) - { - var mode = m; - - } -
    - @WebSourcesText.Help(Pg.Form.WebSources) + @* ADR-0015: governed web sources. The Host decides (cue, permissions, budget) and reports what actually happened; the + console only refuses to OFFER a mode the current server setup cannot run, with ONE cause and its fix. The form is never + changed behind the operator's back: a blocked Required stays Required (Run is blocked with the cause). *@ + @{ var ready = Pg.SearchReadiness; } +
    +
    + Web sources +
    + @foreach (var m in new[] { WebSourcesMode.Off, WebSourcesMode.Auto, WebSourcesMode.Required }) + { + var mode = m; + var blocked = mode != WebSourcesMode.Off && ready is { Known: true, Possible: false } && Pg.Form.WebSources != mode; + + }
    - @if (Pg.Form.WebSources != WebSourcesMode.Off) + @if (ready is { Known: true, Possible: false }) { -
    - - - @WebSourcesText.LocationHelp -
    + + @(ready.Cause + " " + ready.Fix + (ready.Href is null ? "" : " "))@if (ready.Href is { } href) { @ready.HrefLabel } + + @if (ready.SwitchToProfile is { } alt) + { + + } + } + else + { + @WebSourcesText.Help(Pg.Form.WebSources)@(ready.Known ? "" : " (" + ready.Cause + ")") }
    + @if (Pg.Form.WebSources != WebSourcesMode.Off) + { +
    + + + @WebSourcesText.LocationHelp +
    + } +
    + + @if (!Compact) + { + + } @if (!Compact) { @@ -112,6 +141,7 @@
    About this
      +
    • An application is the calling system (for example a support portal). It belongs to a team, which pays for its requests through the team's and the application's budgets, and it may only use the workload profiles granted to it.
    • 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.
    • @@ -194,6 +224,8 @@ private ScenarioPreset? CurrentPreset => ScenarioPresets.Find(Pg.Form.Scenario) is { } p && p.StillMatches(Pg.Form) ? p : null; + private DemoExample? CurrentExample => DemoExamples.Find(Pg.Form.ExampleId) is { } e && DemoExamples.StillMatches(e, Pg.Form) ? e : null; + private IReadOnlyList Overrides => ComposerRules.EligibleOverrides(Ws.Config?.Config, Pg.Form.ProfileId, State.Catalog); private string RunLabel @@ -201,6 +233,7 @@ get { if (Pg.Running) return "Running…"; + if (CurrentExample is not null) return "Run example"; return CurrentPreset is { } p && ScenarioPresets.IsReady(p, Pg.Form, Ws.Applications) ? "Run preset " + p.Letter : "Run"; diff --git a/src/Covenant.Ui/Components/RoutePreviewPanel.razor b/src/Covenant.Ui/Components/RoutePreviewPanel.razor new file mode 100644 index 0000000..53ad7f2 --- /dev/null +++ b/src/Covenant.Ui/Components/RoutePreviewPanel.razor @@ -0,0 +1,47 @@ +@inject PlaygroundState Pg + +@* BEFORE the run: the Host's dry-run route (POST /admin/policies/simulate) — which policy matches the application's + workload profile and final classification, the primary target, approved fallbacks, and excluded targets with the + reason. Real engine, no provider call, no record, no spend. AFTER the run, the run summary shows what actually + happened from evidence. The user's prompt is sent exactly as typed. *@ + +
      +
      + + Asks the policy engine where this request would go — no model is called. +
      + @if (Pg.Preview is { } pv) + { + if (pv.Loading) + { + Checking the route… + } + else if (pv.Error is { } err) + { + @err + } + else if (pv.Result is { } r) + { +
      + @RoutePreview.Summary(r) + @RoutePreview.Classification(r) + @if (r.Eligible.Count > 0) + { +
        + @foreach (var e in r.Eligible) + { +
      • @e.Target @(e.Boundary is { Length: > 0 } b ? "· " + b : "") @(e.ExcludedReason is { Length: > 0 } why ? "— excluded: " + why : "— eligible")
      • + } +
      + } + @if (!string.IsNullOrWhiteSpace(r.Explanation)) { @r.Explanation } + @if (!pv.IsCurrent(Pg.Form)) + { + This preview is for a previous form — preview again after changing application, profile, model or prompt. + } + Dry run on configuration v@(r.ConfigVersion?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "?") — runtime checks (pause, rate limit, budget, provider health) still apply when you Run. +
      + } + } +
      diff --git a/src/Covenant.Ui/Components/RunDetails.razor b/src/Covenant.Ui/Components/RunDetails.razor index cf4f908..4456776 100644 --- a/src/Covenant.Ui/Components/RunDetails.razor +++ b/src/Covenant.Ui/Components/RunDetails.razor @@ -97,6 +97,16 @@ +
      +

      Who requested and who pays

      +
      +
      Assigned before the call
      @Ownership.Assigned(rec)
      +
      Finalized after execution
      @Ownership.Finalized(rec)
      +
      Cache
      @Ownership.Cache(rec)
      +
      + The application, team and workload are attached when the request arrives, so refused requests are attributed too. The charge is settled once the provider (and any web search) finished, then the audit record is written. +
      +

      Usage and cost

      diff --git a/src/Covenant.Ui/Components/RunSummary.razor b/src/Covenant.Ui/Components/RunSummary.razor index 94622e9..abef248 100644 --- a/src/Covenant.Ui/Components/RunSummary.razor +++ b/src/Covenant.Ui/Components/RunSummary.razor @@ -21,7 +21,7 @@ }
    - @if (!Run.InFlight && Run.Outcome is { } ox) + @if (!Large && !Run.InFlight && Run.Outcome is { } ox) { @ox.Explanation } @@ -29,6 +29,19 @@ { @te } + @if (Large) + { +
    +
    Caller · owning team
    @(Run.Evidence.Record is { } owner ? (ComposerRules.Find(Ws.Applications, owner.ApplicationId) is { } app ? ComposerRules.ApplicationName(app) : owner.ApplicationId ?? "Not recorded") + " · " + owner.Tags.Team : RunText.AwaitingText(Run))
    +
    Destination
    @if (Run.Evidence.Record is { } record) { var destination = ModelFacts.Destination(record, Ws.Connections); @destination.Text } else { @RunText.AwaitingText(Run) }
    +
    Classification
    @RunText.Classification(Run)
    +
    Charged after execution
    @RunText.Cost(Run)
    +
    Duration
    @RunText.Duration(Run)
    +
    Evidence
    @{ var evidence = RunText.Evidence(Run); } @evidence.Text
    +
    + } + else + {
    Classification
    @@ -52,6 +65,18 @@ }
    + @if (Run.Evidence.Record is { } own) + { +
    +
    Requested by · pays (assigned before the call)
    +
    @Ownership.Assigned(own)
    +
    +
    +
    Charged (finalized after execution)
    +
    @Ownership.Finalized(own)
    +
    +
    Cache
    @Ownership.Cache(own)
    + }
    Duration
    @RunText.Duration(Run)
    @if (!Large) { @@ -64,6 +89,7 @@
    @ev.Text
    + }
    @code { diff --git a/src/Covenant.Ui/Components/TraceBar.razor b/src/Covenant.Ui/Components/TraceBar.razor index 04edd5b..8a5e8f5 100644 --- a/src/Covenant.Ui/Components/TraceBar.razor +++ b/src/Covenant.Ui/Components/TraceBar.razor @@ -4,9 +4,10 @@ (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). 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. *@ + the chip's title carries the full text. Animation (§7): each state has its own keyframes, so a REAL state change (a new + event) swaps the animation and plays it once; a running stage pulses. prefers-reduced-motion disables all of it. *@ -
    +
      @foreach (var step in Trace.Steps) { @@ -18,7 +19,7 @@ title="@ChipTitle(s)" @onclick="() => Toggle(s.Stage)"> @Name(s) - @TraceModel.StateText(s.State) + @TraceModel.OutcomeText(s) @if (Duration(s) is { } dur) { @dur @@ -35,8 +36,10 @@ @sel.Label
    + @TraceModel.Explain(sel.Stage) + @if (TraceModel.OutcomeNote(sel) is { } note) { @note }
    -
    State
    @TraceModel.StateText(sel.State)
    +
    State
    @TraceModel.OutcomeText(sel)
    Reason code
    @(sel.ReasonCode ?? "None reported")
    Duration
    @(sel.DurationMs is { } d ? Fmt.Ms(d) + " (server-measured)" : "Not reported")
    @if (sel.Target is { Length: > 0 } t && sel.Attempts.Count == 0) @@ -77,6 +80,8 @@ [Parameter] public TraceFeedState FeedState { get; set; } [Parameter] public string? Message { get; set; } [Parameter] public bool Compact { get; set; } + /// The view is a labelled replay of recorded events (TraceWithReplay), not a live request. + [Parameter] public bool Replaying { get; set; } private readonly string _id = "trace-" + Guid.NewGuid().ToString("n")[..8]; private string? _open; @@ -116,12 +121,12 @@ /// 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) + => s.State is not (TraceStepState.Pending or TraceStepState.Skipped or TraceStepState.NotReported) + ? TraceModel.DurationText(s.DurationMs) : null; private static string ChipTitle(TraceStepView s) - => Name(s) + " · " + TraceModel.StateText(s.State) + (Duration(s) is { } d ? " · " + d : ""); + => Name(s) + " · " + TraceModel.OutcomeText(s) + (Duration(s) is { } d ? " · " + d : ""); private string SourceText { diff --git a/src/Covenant.Ui/Components/TraceWithReplay.razor b/src/Covenant.Ui/Components/TraceWithReplay.razor new file mode 100644 index 0000000..b12c3b1 --- /dev/null +++ b/src/Covenant.Ui/Components/TraceWithReplay.razor @@ -0,0 +1,113 @@ +@implements IDisposable + +@* The real trace (live or recorded) plus an explicit, clearly labelled "Replay trace" for presenting a request whose stages + completed too fast to watch. Replay re-reveals the RECORDED events at a chosen pace: it never calls a provider, never + changes a record and never re-runs the request; durations and the final outcome are the recorded ones. A new run, a + different request, navigation or Stop cancels it, so traces never mix. Live requests animate from real events only. *@ + +
    + @if (_playing && _frame is { } frame) + { +
    + + Replay + step @_revealed / @_script.Count · pacing is for explanation; the durations shown are the recorded ones + + +
    + + } + else + { + + } + @if (CanReplay) + { +
    + + + @foreach (var sp in TraceReplay.Speeds) + { + var speed = sp; + + } + +
    + } +
    + +@code { + /// The live/recorded view shown when not replaying. + [Parameter] public TraceView Trace { get; set; } = TraceView.Empty; + [Parameter] public TraceFeedState FeedState { get; set; } + [Parameter] public string? Message { get; set; } + [Parameter] public bool Compact { get; set; } + /// The recorded events of THIS request (live accumulator or audit summary). Read only when replay starts. + [Parameter] public Func>? Events { get; set; } + /// Identity of the request shown; a change cancels any replay of the previous one. + [Parameter] public string? RequestKey { get; set; } + /// A request is in flight: replay is not offered and any replay stops (no mixing with live events). + [Parameter] public bool Busy { get; set; } + + private CancellationTokenSource? _cts; + private IReadOnlyList _script = []; + private TraceView? _frame; + private int _revealed; + private bool _playing; + private double _speed = 1.0; + private string? _key; + + private bool CanReplay => !Busy && Events is not null && Trace.Complete && Trace.HasEvents; + + protected override void OnParametersSet() + { + if (!string.Equals(_key, RequestKey, StringComparison.Ordinal) || Busy) + { + _key = RequestKey; + Stop(); + } + } + + private async Task StartAsync() + { + if (Events is null || Busy) return; + Stop(); + _script = TraceReplay.Script(Events()); + if (_script.Count == 0) return; + var cts = new CancellationTokenSource(); + _cts = cts; + _playing = true; + try + { + for (_revealed = 0; _revealed <= _script.Count; _revealed++) + { + _frame = TraceReplay.Frame(_script, _revealed, Trace.ConfigVersion); + StateHasChanged(); + if (_revealed == _script.Count) break; + await Task.Delay(TraceReplay.DelayMs(_speed), cts.Token); + } + // Hold the final (recorded) frame briefly, then return to the live/recorded view. + await Task.Delay(TraceReplay.DelayMs(_speed) * 3, cts.Token); + } + catch (OperationCanceledException) { return; } + finally + { + if (ReferenceEquals(_cts, cts)) { _playing = false; _frame = null; _cts = null; } + cts.Dispose(); + } + StateHasChanged(); + } + + private void Stop() + { + var cts = _cts; + _cts = null; + _playing = false; + _frame = null; + if (cts is not null) { try { cts.Cancel(); } catch (ObjectDisposedException) { } } + } + + public void Dispose() => Stop(); +} diff --git a/src/Covenant.Ui/Components/WebSourcesPanel.razor b/src/Covenant.Ui/Components/WebSourcesPanel.razor index a2c2629..dbcf711 100644 --- a/src/Covenant.Ui/Components/WebSourcesPanel.razor +++ b/src/Covenant.Ui/Components/WebSourcesPanel.razor @@ -6,7 +6,16 @@ @if (Run.Snapshot.WebSources != WebSourcesMode.Off) {
    - @Run.WebSourcesStatus + @{ var kind = WebSourcesText.Kind(Run.Search?.ReasonCode); } + + @if (kind != SearchProblemKind.None) { @WebSourcesText.KindLabel(kind): } + @Run.WebSourcesStatus + + @if (kind != SearchProblemKind.None && Run.Result?.ErrorReason is { Length: > 0 } serverReason) + { + @* The Host's specific reason for THIS request (e.g. "web search is disabled in configuration v3"), not a generic list. *@ + Server: @serverReason + } @if (Run.Search is { Outcome: "passed", Sources.Count: > 0 } s) {
      diff --git a/src/Covenant.Ui/Components/WorkloadRouteAction.razor b/src/Covenant.Ui/Components/WorkloadRouteAction.razor new file mode 100644 index 0000000..2d94791 --- /dev/null +++ b/src/Covenant.Ui/Components/WorkloadRouteAction.razor @@ -0,0 +1,87 @@ +@inject ConfigEditor Editor + +@* "Route a workload here…" for one configured model (Connections). Explicit and additive: shows exactly what would be + added (profile, profile-scoped policy, grants) or why it is refused, then puts it into the configuration DRAFT for the + normal Preview impact → Save & apply. Never edits existing rules, never invents a price, never sends Internal work to + a cloud model. *@ + +@if (!_open) +{ + +} +else +{ + var current = Editor.Current; + var preset = WorkloadRouteSetup.Presets.FirstOrDefault(p => p.ProfileId == _profile); + var plan = current is null || preset is null ? null : WorkloadRouteSetup.Plan(current, preset, Connection.Id, ModelId); +
      +
      + + + @if (ComposerRules.BoundaryLabel(Connection.Boundary) == "Cloud") + { + Cloud models serve Public workloads only. + } +
      + @if (plan is { Ok: false }) + { + @plan.Problem + } + else if (plan is { } ok) + { +
        + @foreach (var c in ok.Changes) {
      • @c
      • } +
      + } + @if (_error is { } err) { @err } +
      + + +
      +
      +} + +@code { + [Parameter, EditorRequired] public ConnectionDto Connection { get; set; } = default!; + [Parameter, EditorRequired] public string ModelId { get; set; } = ""; + + private readonly string _id = "wr-" + Guid.NewGuid().ToString("n")[..8]; + private bool _open; + private string? _profile; + private string? _error; + + private bool CanEdit => Editor.Applied is not null && !Editor.Saving && (!Editor.Editing || Editor.Owner == "connections" || !Editor.IsDirty); + + private void Close() + { + _open = false; + _profile = null; + _error = null; + } + + private async Task ApplyAsync(WorkloadPreset preset) + { + _error = null; + if (!Editor.BeginEdit("connections") || Editor.Draft is not { } draft) + { + _error = "Another page is editing the configuration — finish or discard that draft first."; + return; + } + var result = WorkloadRouteSetup.ApplyTo(draft, preset, Connection.Id, ModelId); + if (!result.Ok) + { + _error = result.Problem; + return; + } + Editor.Touch(); + Close(); + await Editor.ValidateAsync(); + } +} diff --git a/src/Covenant.Ui/Layout/StatusHeader.razor b/src/Covenant.Ui/Layout/StatusHeader.razor index 91593d6..7e8e15e 100644 --- a/src/Covenant.Ui/Layout/StatusHeader.razor +++ b/src/Covenant.Ui/Layout/StatusHeader.razor @@ -9,16 +9,21 @@ with its scope, and the theme switch. The ticking element is NOT a live region; one visually hidden polite region announces state changes only (connected / paused / stale). *@
      - @(State.Connected ? State.EnvironmentLabel : "—") - @if (State.Connected) { - var mode = ShellStatus.Mode(State.LastStatus?.Mode); - + var st = State.LastStatus; + var mode = ShellStatus.Mode(st?.Mode); + @if (mode.Tone == "local") { } else if (mode.Tone is "hybrid" or "legacy") { } - @mode.Label + @ShellStatus.ModeWithVersion(st?.Mode, st?.ConfigVersion) + var env = ShellStatus.Environment(st?.Environment, st?.ConfigVersion, st?.Version, st?.StartedUtc); + Environment @env.Label + } + else + { + Not connected } @{ var fresh = ShellStatus.Freshness(State.Connected, State.IsStale, State.LastUpdatedUtc, DateTimeOffset.UtcNow, State.FeedError); } diff --git a/src/Covenant.Ui/Logic/ConnectionLogic.cs b/src/Covenant.Ui/Logic/ConnectionLogic.cs index 07d4e94..2116f5d 100644 --- a/src/Covenant.Ui/Logic/ConnectionLogic.cs +++ b/src/Covenant.Ui/Logic/ConnectionLogic.cs @@ -5,11 +5,11 @@ namespace Covenant.Ui.Logic; /// 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 + /// Synthetic prompt for the governed test. It contains a synthetic, explicitly invalid SSN-shaped marker (000-12-3456) so that in cloud /// mode the PII rule routes it to the local model (PII/PHI → local); in local-only mode every class routes /// there anyway. public const string GovernedTestPromptBase = - "Synthetic connection test record: SSN 078-05-1120 (the published sample number). Reply with the single word OK."; + "Synthetic connection test record: SSN 000-12-3456 (synthetic, invalid area number). Reply with the single word OK."; /// Fresh per run (nonce) so a governed test can never be answered from the response cache — /// a cached reply would prove nothing about the provider being reachable now. diff --git a/src/Covenant.Ui/Logic/CostText.cs b/src/Covenant.Ui/Logic/CostText.cs index 2608a0b..c5498ca 100644 --- a/src/Covenant.Ui/Logic/CostText.cs +++ b/src/Covenant.Ui/Logic/CostText.cs @@ -18,7 +18,7 @@ public static class CostText public const string MixedLabel = "Mixed (includes estimates)"; - public static string Cost(AuditEntryView r) => ToolOnly(r) ? "≈ " + Usd(r.Usage.CostUsd) + " web-search charge (no provider call)" : r.CostBasis switch + public static string Cost(AuditEntryView r) => ToolOnly(r) ? "≈ " + Usd(r.Usage.CostUsd) + " web-search charge (no provider call)" : Split(r) ?? r.CostBasis switch { "estimated_unreported" => "≈ " + Usd(r.Usage.CostUsd) + " (includes an estimated web-search charge)", "reported" => Usd(r.Usage.CostUsd) + " (estimated provider charge)", @@ -54,12 +54,33 @@ public static class CostText _ => NotReported, }; + /// When a request has BOTH a tool charge (web search) and inference, the total split into its parts with each + /// part's own basis — never one "provider charge" label for a total that is mostly (or only) the search. + public static string? Split(AuditEntryView r) + { + if (r.ToolCalls is not { Count: > 0 } tools || ToolOnly(r)) return null; + decimal tool = tools.Sum(t => t.CostUsd ?? 0m); + decimal inference = Math.Max(0m, r.Usage.CostUsd - tool); + var attempts = r.Attempts ?? new List(); + string inferenceBasis = + attempts.Count == 0 ? "no provider call" + : attempts.All(a => a.CostBasis == "zero_priced") ? "configured $0 local model, infrastructure excluded" + : attempts.Any(a => a.CostBasis is "estimated_from_text" or "estimated_failed_call") ? "includes estimates" + : attempts.Any(a => a.CostBasis is "unpriced" or "unknown_failed_call") ? "partly unknown" + : "reported usage × configured price"; + string toolBasis = tools.All(t => t.CostBasis == "reported") ? "credits × configured price" + : tools.All(t => t.CostBasis == "no_call") ? "not sent" + : "reserved charge"; + return Usd(r.Usage.CostUsd) + " total · web search " + Usd(tool) + " (" + toolBasis + ") · inference " + + Usd(inference) + " (" + inferenceBasis + ")"; + } + /// True when the request's only charge is a tool call (e.g. a failed search before any provider call). public static bool ToolOnly(AuditEntryView r) => r.ToolCalls is { Count: > 0 } && (r.Attempts is null || r.Attempts.Count == 0) && r.CostBasis is not "no_call"; /// Short form for table cells (same rules, fewer words). - public static string CostShort(AuditEntryView r) => ToolOnly(r) ? "≈ " + Usd(r.Usage.CostUsd) + " search" : r.CostBasis switch + public static string CostShort(AuditEntryView r) => ToolOnly(r) ? "≈ " + Usd(r.Usage.CostUsd) + " search" : Split(r) is not null ? Usd(r.Usage.CostUsd) + " incl. search" : r.CostBasis switch { "estimated_unreported" => "≈ " + Usd(r.Usage.CostUsd), "reported" => Usd(r.Usage.CostUsd), diff --git a/src/Covenant.Ui/Logic/DemoExamples.cs b/src/Covenant.Ui/Logic/DemoExamples.cs new file mode 100644 index 0000000..a7223ab --- /dev/null +++ b/src/Covenant.Ui/Logic/DemoExamples.cs @@ -0,0 +1,388 @@ +using System.Globalization; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// What an example needs from the configuration to show what it claims. Routing is ALWAYS policy-driven +/// (classification + workload profile); an example never relies on keyword routing or model "quality". +public enum ExampleNeed +{ + /// A Public profile allowed to use web search, and search ready on the server. + PublicWebResearch, + /// A Public profile whose policy primary is an Anthropic connection. + PublicAnthropic, + /// An Internal profile whose policy primary is the coder model. + InternalCoder, + /// An Internal profile whose policy primary is the stronger local research model. + InternalResearch, + /// A Public profile with an eligible cloud target, used with an explicit cloud model pin and a synthetic SSN. + SensitiveCloudPinRefusal, + /// The exact cache enabled (TTL > 0) and a Public route. + CacheRepeat, + /// A hard budget applying to the application that cannot cover one more request. + BudgetRefusal, +} + +/// A named, meaningful demo example. It only FILLS the composer; Run stays explicit. is +/// what the scenario is designed to show; the card also shows the Host's dry-run route for the current configuration, +/// and the run's own evidence is the result. +public sealed record DemoExample( + string Id, + string Title, + string Teaches, + string Expected, + string Observe, + ExampleNeed Need, + string Prompt, + WebSourcesMode WebSources, + string Workflow, + string UseCase, + bool FreshNonce, + int? MaxTokens = null, + /// Words that name the intended workload/team ("research", "writing", "coding"): when several profiles + /// fit, a profile or application whose id/name contains one is preferred. Never used for routing. + string[]? Prefer = null); + +/// A missing prerequisite: exactly what is missing and where to fix it. Never silently downgraded. +public sealed record ExamplePrerequisite(string Text, string? Href, string? HrefLabel); + +/// An example resolved against the CURRENT applied configuration. When , the application and +/// profile it will use are named; otherwise says why (the Apply button is not offered). +public sealed record ExampleResolution( + DemoExample Example, + bool Ready, + string? ApplicationId, + string? ProfileId, + string? ModelPin, + string? ConfiguredRoute, + string? Payer, + IReadOnlyList Missing, + /// Output bound actually enforced = min(request, application cap, model cap), and whether it is below what + /// the example asks for (the answer may then be cut — shown, never hidden). + string? OutputNote = null); + +/// The policy (and its first eligible target) that would decide a (classification, profile) pair, mirroring +/// PolicyEngineV2.Match/Ineligibility. Used to FIND a fitting profile for an example — the Host's dry run is the preview. +public sealed record ResolvedRoute(PolicyDto? Policy, PolicyTargetDto? Primary, ConnectionDto? PrimaryConnection, IReadOnlyList Eligible, string? Refusal); + +public static class DemoExamples +{ + /// Installed model ids on the demo machine (docs/CONSOLE-DEMO-CLARITY-TASKS.md). Examples look for policies + /// routing to these; nothing is assumed to exist — a missing route is reported with a link. + public const string CoderModel = "qwen2.5-coder:7b"; + public const string ResearchModel = "qwen3.8:27b-mlx"; + + /// Synthetic SSN-shaped marker. Area number 000 is never assigned, so it is explicitly invalid and identifies + /// no one; it still matches the demo detector's US SSN pattern (\d{3}-\d{2}-\d{4}). + public const string SyntheticSsn = "000-12-3456"; + + public static readonly IReadOnlyList All = + [ + new("public-research", "Public research with web sources", + "Fresh public facts come from one governed Tavily search, charged as a separate tool call.", + "Search runs once (Required) against an official source, then the Public route answers only from what was retrieved.", + "Web sources lists what was retrieved — retrieved, not independently verified; check the answer against the cited page. The search charge is shown separately from inference.", + ExampleNeed.PublicWebResearch, + "site:learn.microsoft.com What is the newest .NET version listed in Microsoft's official .NET release notes, and its release date? Answer in one sentence citing the page; if the retrieved pages do not say, reply \"not stated in the sources\".", + WebSourcesMode.Required, "research", "public-research", false, Prefer: ["research"]), + new("public-writing", "Public writing through Anthropic", + "Public content may use an approved cloud model; the team pays the configured price.", + "Routed by the Public writing profile's policy to the approved Anthropic model.", + "Route shows the Anthropic model and policy; cost basis is reported provider usage × configured price.", + ExampleNeed.PublicAnthropic, + "Rewrite this public announcement as three short newsletter bullets: \"Covenant now records who requested each AI call, which policy routed it, and what it cost.\"", + WebSourcesMode.Off, "writing", "public-newsletter", false, Prefer: ["writing"]), + new("internal-coding", "Internal coding on the local coder model", + "Internal work never leaves the perimeter; a coding workload profile routes to the coder model.", + "Routed by the coding profile's policy to " + CoderModel + " (local, $0 configured).", + "Route shows the local coder model; no cloud attempt; cost is $0 configured, infrastructure excluded.", + ExampleNeed.InternalCoder, + "Write a C# extension method Chunk(this IEnumerable source, int size) that yields arrays of at most size items, with XML doc comments and argument validation.", + WebSourcesMode.Off, "coding", "internal-code-assist", false, Prefer: ["coding", "code"]), + new("internal-research", "Internal research on the stronger local model", + "A different workload profile selects a stronger local model — routing by declared workload, not by guessing from the prompt.", + "Routed by the research profile's policy to " + ResearchModel + " (local).", + "Route shows the stronger local model; the provider stage duration is the real measured time. A reasoning model spends part of the output bound thinking — if it is cut, the result says Truncated.", + ExampleNeed.InternalResearch, + "For an internal ledger service, compare optimistic and pessimistic concurrency control: when to use each, and two failure modes of each. Keep it under 200 words.", + WebSourcesMode.Off, "research", "internal-analysis", false, MaxTokens: 2048, Prefer: ["research"]), + new("sensitive-refusal", "Sensitive data never goes to the cloud", + "Detection escalates a Public request containing an SSN pattern to PII; pinning a cloud model is then refused.", + "Refused at policy: PII is never routed to a cloud destination. Nothing is sent to the provider.", + "Outcome Refused at Policy with the reason; evidence still names the application, team and profile; no charge. Resolution: remove the marker, or let policy choose (PII → local).", + ExampleNeed.SensitiveCloudPinRefusal, + "Summarize this public support ticket in one sentence: \"Printer on floor 3 jammed again. Reporter SSN " + SyntheticSsn + " (synthetic test marker).\"", + WebSourcesMode.Off, "writing", "sensitive-check", false, Prefer: ["writing"]), + new("cache-repeat", "Repeat a request: exact cache hit", + "An identical request within the cache TTL is answered from the exact cache at $0, still governed and audited.", + "First run: cache miss, provider call. Second identical run: cache hit, no provider call.", + "Run twice. The second trace shows Cache hit and skipped downstream stages; cost $0 — no provider call.", + ExampleNeed.CacheRepeat, + "In one sentence, what does an exact-match response cache do?", + WebSourcesMode.Off, "demo", "cache-repeat", false), + new("budget-refusal", "Budget refusal before any spend", + "A request that cannot fit the remaining budget is refused before the provider call; nothing is charged.", + "Refused at Budget: the reservation exceeds what remains in an applicable hard budget.", + "Outcome Refused at Budget naming the budget; no provider attempt; reservations released.", + ExampleNeed.BudgetRefusal, + "Write a short paragraph about governed AI spending.", + WebSourcesMode.Off, "demo", "budget-check", true, Prefer: ["budget"]), + ]; + + public static DemoExample? Find(string? id) + => string.IsNullOrWhiteSpace(id) ? null : All.FirstOrDefault(e => string.Equals(e.Id, id, StringComparison.Ordinal)); + + // ---------------------------------------------------------------- route mirror + + /// Mirror of PolicyEngineV2.Match + Ineligibility (UI copy; the Host decides at run time). + public static ResolvedRoute Route(CovenantConfigDto cfg, string classification, string? profileId) + { + var matching = cfg.Policies.Where(p => p.Enabled + && p.Classifications.Contains(classification, StringComparer.OrdinalIgnoreCase) + && (p.Profiles.Count == 0 || (profileId is not null && p.Profiles.Contains(profileId, StringComparer.Ordinal)))) + .ToList(); + var specific = matching.Where(p => p.Profiles.Count > 0).ToList(); + var tier = specific.Count > 0 ? specific : matching; + if (tier.Count == 0) return new(null, null, null, [], "no policy covers " + classification + " for this profile"); + if (tier.Count > 1) return new(null, null, null, [], "ambiguous: policies " + string.Join(", ", tier.Select(p => p.Id)) + " match at the same specificity"); + var policy = tier[0]; + if (policy.Paused) return new(policy, null, null, [], "policy " + policy.Id + " is paused"); + var eligible = policy.Targets.Where(t => Ineligible(cfg, t, classification) is null).ToList(); + if (eligible.Count == 0) return new(policy, null, null, [], "no eligible destination under policy " + policy.Id); + var conn = FindConnection(cfg, eligible[0].ConnectionId); + return new(policy, eligible[0], conn, eligible, null); + } + + public static string? Ineligible(CovenantConfigDto cfg, PolicyTargetDto t, string classification) + { + if (t.Paused) return "route paused"; + var conn = FindConnection(cfg, t.ConnectionId); + if (conn is null) return "unknown connection"; + if (!conn.Enabled) return "connection disabled"; + var model = conn.Models.FirstOrDefault(m => string.Equals(m.ModelId, t.ModelId, StringComparison.Ordinal)); + if (model is null) return "model not on connection"; + if (ComposerRules.BoundaryLabel(conn.Boundary) == "Cloud") + { + if (PolicyRoutes.IsLocalOnly(cfg.Mode)) return "cloud excluded in local-only mode"; + if (PolicyText.IsSensitive(classification)) return "sensitive data never routed to cloud"; + if (model.Price is null && cfg.Budgets.Any(b => string.Equals(b.Enforcement, "hard", StringComparison.Ordinal) || b.Enforcement is null)) + return "unpriced cloud model under a hard budget"; + } + return null; + } + + public static ConnectionDto? FindConnection(CovenantConfigDto cfg, string? id) + => cfg.Connections.FirstOrDefault(c => string.Equals(c.Id, id, StringComparison.Ordinal)); + + public static string RouteText(ResolvedRoute r) + { + if (r.Refusal is { } why) return "Refused: " + why; + var main = r.Primary!.ConnectionId + "/" + r.Primary.ModelId; + var fb = r.Eligible.Skip(1).Select(t => t.ConnectionId + "/" + t.ModelId).ToList(); + return main + (fb.Count > 0 ? " (approved fallback: " + string.Join(", ", fb) + ")" : "") + " · policy " + r.Policy!.Id; + } + + // ---------------------------------------------------------------- resolution + + /// Resolves one example against the applied configuration. Picks the application and profile that satisfy + /// the example's need (preferring ); otherwise lists exactly what is missing. + /// Never edits configuration and never substitutes a different route than the example claims. + public static ExampleResolution Resolve(DemoExample ex, CovenantConfigDto? cfg, IReadOnlyList? apps, + IReadOnlyList? budgets, WebSearchStatusDto? search, string? preferredApplication = null) + { + var missing = new List(); + if (cfg is null || apps is null) + return new(ex, false, null, null, null, null, null, [new("The configuration and applications are not loaded yet.", null, null)]); + var selectable = apps.Where(a => ComposerRules.WhyNotSelectable(a) is null) + .OrderBy(a => string.Equals(a.Id, preferredApplication, StringComparison.Ordinal) ? 0 : 1) + .ThenBy(a => a.Id, StringComparer.Ordinal).ToList(); + if (selectable.Count == 0) + return new(ex, false, null, null, null, null, null, + [new("No application is enabled for console testing.", "policies#applications-list", "Applications")]); + + string baseline = ex.Need is ExampleNeed.InternalCoder or ExampleNeed.InternalResearch ? "Internal" : "Public"; + var candidates = new List<(ApplicationSummaryDto App, WorkloadProfileDto Profile, ResolvedRoute Route, string Pin, int Score)>(); + foreach (var app in selectable) + { + // An application whose applicable hard budget is exhausted would refuse ANY charged request (a priced route or + // a web-search tool charge): only the budget-refusal example may pick it, so the others never fail by accident. + bool exhausted = ExhaustedBudget(app, budgets) is not null; + foreach (var pid in ComposerRules.GrantedProfiles(app)) + { + var profile = cfg.Profiles.FirstOrDefault(p => p.Id == pid); + if (profile is null || !string.Equals(profile.Baseline, baseline, StringComparison.Ordinal)) continue; + var route = Route(cfg, baseline, pid); + if (Fits(ex, cfg, app, profile, route, budgets, search) is not { } pin) continue; + if (exhausted && ex.Need != ExampleNeed.BudgetRefusal && (PrimaryPriced(route) || ex.WebSources != WebSourcesMode.Off)) continue; + candidates.Add((app, profile, route, pin, Score(ex, app, profile, preferredApplication))); + } + } + if (candidates.Count > 0) + { + var best = candidates.OrderByDescending(c => c.Score).ThenBy(c => c.App.Id, StringComparer.Ordinal) + .ThenBy(c => c.Profile.Id, StringComparer.Ordinal).First(); + var routeText = ex.Need == ExampleNeed.SensitiveCloudPinRefusal + ? RouteText(Route(cfg, "Pii", best.Profile.Id)) + " — the explicit cloud pin is refused" + : RouteText(best.Route); + return new(ex, true, best.App.Id, best.Profile.Id, best.Pin.Length == 0 ? null : best.Pin, routeText, + ComposerRules.PayerText(best.App), [], OutputNote(ex, cfg, best.App.Id, best.Route)); + } + missing.AddRange(WhatIsMissing(ex, cfg, selectable, budgets, search, baseline)); + return new(ex, false, null, null, null, null, null, missing); + } + + /// Preference among fitting candidates: a profile/application named for the example's workload, then the + /// application currently selected. Display ranking only — the policy engine still routes. + private static int Score(DemoExample ex, ApplicationSummaryDto app, WorkloadProfileDto profile, string? preferredApplication) + { + int score = 0; + foreach (var word in ex.Prefer ?? Array.Empty()) + { + if (Contains(profile.Id, word) || Contains(profile.Name, word)) score += 4; + if (Contains(app.Id, word) || Contains(app.DisplayName, word) || Contains(app.Team, word)) score += 2; + } + if (string.Equals(app.Id, preferredApplication, StringComparison.Ordinal)) score += 1; + return score; + } + + private static bool Contains(string? text, string word) => text is not null && text.Contains(word, StringComparison.OrdinalIgnoreCase); + + /// "Output bound 2048 requested · application cap 1024 → 1024 enforced: the answer may be cut." Null when the + /// example sets no bound. Effective = min(request, application cap, model cap) — the Host's rule. + public static string? OutputNote(DemoExample ex, CovenantConfigDto cfg, string appId, ResolvedRoute route) + { + if (ex.MaxTokens is not { } want) return null; + int appCap = cfg.Applications.FirstOrDefault(a => a.Id == appId)?.MaxOutputTokens ?? 1024; + int? modelCap = route.Primary is { } p ? route.PrimaryConnection?.Models.FirstOrDefault(m => m.ModelId == p.ModelId)?.MaxOutputTokens : null; + int effective = Math.Min(want, Math.Min(appCap, modelCap ?? int.MaxValue)); + var text = "Output bound: " + want.ToString(CultureInfo.InvariantCulture) + " requested · application cap " + appCap.ToString(CultureInfo.InvariantCulture) + + (modelCap is { } mc ? " · model cap " + mc.ToString(CultureInfo.InvariantCulture) : "") + + " → " + effective.ToString(CultureInfo.InvariantCulture) + " enforced"; + return effective < want + ? text + ". The answer may be cut short (the result will say Truncated); raise the application's max output tokens under Policies → Applications to allow more." + : text + "."; + } + + /// Non-null when (app, profile, route) satisfies the example: "" or the model pin to use. + private static string? Fits(DemoExample ex, CovenantConfigDto cfg, ApplicationSummaryDto app, WorkloadProfileDto profile, + ResolvedRoute route, IReadOnlyList? budgets, WebSearchStatusDto? search) + { + switch (ex.Need) + { + case ExampleNeed.PublicWebResearch: + if (route.Primary is null || !profile.WebSearchAllowed) return null; + return search is { Ready: true } ? "" : null; + case ExampleNeed.PublicAnthropic: + return route.PrimaryConnection is { Kind: "Anthropic" } ? "" : null; + case ExampleNeed.InternalCoder: + return route.Primary is { } c && c.ModelId == CoderModel && IsLocal(route) ? "" : null; + case ExampleNeed.InternalResearch: + return route.Primary is { } r && r.ModelId == ResearchModel && IsLocal(route) ? "" : null; + case ExampleNeed.SensitiveCloudPinRefusal: + var cloud = route.Eligible.FirstOrDefault(t => ComposerRules.BoundaryLabel(FindConnection(cfg, t.ConnectionId)?.Boundary) == "Cloud"); + return cloud is null ? null : cloud.ConnectionId + "/" + cloud.ModelId; + case ExampleNeed.CacheRepeat: + return route.Primary is not null && (cfg.Settings?.CacheTtlSeconds ?? 0) > 0 ? "" : null; + case ExampleNeed.BudgetRefusal: + // A $0-priced (local) route reserves nothing, so only a PRICED primary can show a budget refusal. + return PrimaryPriced(route) && ExhaustedBudget(app, budgets) is not null ? "" : null; + } + return null; + } + + private static bool PrimaryPriced(ResolvedRoute r) + => r.Primary is { } p && r.PrimaryConnection?.Models.FirstOrDefault(m => m.ModelId == p.ModelId)?.Price is { } price + && ((price.InputPer1M ?? 0m) > 0m || (price.OutputPer1M ?? 0m) > 0m); + + private static bool IsLocal(ResolvedRoute r) => ComposerRules.BoundaryLabel(r.PrimaryConnection?.Boundary) == "Local"; + + /// A hard budget that applies to the application (global, its team, itself) with essentially nothing left. + public static BudgetStateDto? ExhaustedBudget(ApplicationSummaryDto app, IReadOnlyList? budgets) + => budgets?.FirstOrDefault(b => (b.Scope == "global" || b.Scope == "team:" + app.Team || b.Scope == "application:" + app.Id) + && !string.Equals(b.Enforcement, "warn-only", StringComparison.Ordinal) + && b.RemainingUsd <= 0.0001m); + + private static IEnumerable WhatIsMissing(DemoExample ex, CovenantConfigDto cfg, IReadOnlyList apps, + IReadOnlyList? budgets, WebSearchStatusDto? search, string baseline) + { + bool anyBaselineProfile = apps.Any(a => ComposerRules.GrantedProfiles(a) + .Any(g => cfg.Profiles.Any(p => p.Id == g && string.Equals(p.Baseline, baseline, StringComparison.Ordinal)))); + if (!anyBaselineProfile) + yield return new("No console-testable application is granted a " + baseline + "-baseline workload profile.", "policies#applications", "Grant a profile"); + switch (ex.Need) + { + case ExampleNeed.PublicWebResearch: + if (search is not { Ready: true }) + yield return new("Web search is not ready on the server" + (search is null ? " (status not loaded)." : ": " + (search.Setup.FirstOrDefault() ?? "see Settings → Web search.")), + "settings#ws-h", "Web search settings"); + if (!cfg.Profiles.Any(p => p.WebSearchAllowed)) + yield return new("No Public profile is allowed to use web search.", "policies#applications", "Allow web search on a profile"); + break; + case ExampleNeed.PublicAnthropic: + if (!cfg.Connections.Any(c => c.Kind == "Anthropic" && c.Enabled)) + yield return new("No enabled Anthropic connection. Add one (server key Anthropic:ApiKey, model and its price) under Connections.", "connections", "Connections"); + else + yield return new("No Public workload profile's policy routes to the Anthropic model first. Add a profile-scoped Public policy with the Anthropic target (e.g. a 'public-writing' profile).", "policies", "Policies"); + break; + case ExampleNeed.InternalCoder: + case ExampleNeed.InternalResearch: + var model = ex.Need == ExampleNeed.InternalCoder ? CoderModel : ResearchModel; + if (!cfg.Connections.Any(c => c.Enabled && c.Models.Any(m => m.ModelId == model))) + yield return new("Local model " + model + " is not registered on an enabled local connection. Add it from the connection's model catalog under Connections.", "connections", "Connections"); + yield return new("No Internal workload profile's policy routes to " + model + " first. Add a profile-scoped Internal policy (e.g. profile '" + (ex.Need == ExampleNeed.InternalCoder ? "internal-coding" : "internal-research") + "' → " + model + ").", "policies", "Policies"); + break; + case ExampleNeed.SensitiveCloudPinRefusal: + yield return new("No Public profile has an eligible cloud target to pin. This example needs a Public cloud route (Hybrid mode).", "policies", "Policies"); + break; + case ExampleNeed.CacheRepeat: + if ((cfg.Settings?.CacheTtlSeconds ?? 0) <= 0) + yield return new("The exact cache is disabled (TTL 0), so a repeat would NOT be a cache hit. Set a cache TTL under Settings → Operational.", "settings#op-h", "Cache settings"); + break; + case ExampleNeed.BudgetRefusal: + yield return new("No hard budget that applies to a console-testable application on a PRICED Public route is exhausted" + (budgets is null ? " (budgets not loaded)" : "") + + ". To show a refusal, add an application-scoped budget with a tiny cap (e.g. $0.0001) under Budgets for an application whose Public route is a priced model — a $0 local route reserves nothing.", "budgets", "Budgets"); + break; + } + } + + // ---------------------------------------------------------------- apply + + /// Fills the composer from a READY resolution: application, profile, prompt, web sources, labels, routing + /// mode (a cloud pin only for the refusal example), output bound. Never runs, never changes configuration. + public static bool ApplyTo(ExampleResolution r, PlaygroundForm form) + { + if (!r.Ready || r.ApplicationId is null) return false; + var ex = r.Example; + form.Scenario = null; + form.ExampleId = ex.Id; + form.ApplicationId = r.ApplicationId; + form.ProfileId = r.ProfileId; + form.Prompt = ex.Prompt; + form.WebSources = ex.WebSources; + form.Location = ""; + form.Workflow = ex.Workflow; + form.UseCase = ex.UseCase; + form.FreshNonce = ex.FreshNonce; + if (ex.MaxTokens is { } mt) form.MaxTokens = mt; + if (r.ModelPin is { } pin) + { + form.Mode = RouteMode.Catalog; + form.CatalogModel = pin; + } + else + { + form.Mode = RouteMode.Policy; + form.CatalogModel = null; + } + return true; + } + + /// True while the form still holds exactly what the example filled in (labels the run with the example). + public static bool StillMatches(DemoExample ex, PlaygroundForm form) + => string.Equals(form.ExampleId, ex.Id, StringComparison.Ordinal) + && string.Equals(form.Prompt, ex.Prompt, StringComparison.Ordinal) + && form.WebSources == ex.WebSources + && form.FreshNonce == ex.FreshNonce; + + public static string Money(decimal v) => v.ToString("0.####", CultureInfo.InvariantCulture); +} diff --git a/src/Covenant.Ui/Logic/Ownership.cs b/src/Covenant.Ui/Logic/Ownership.cs new file mode 100644 index 0000000..2faa680 --- /dev/null +++ b/src/Covenant.Ui/Logic/Ownership.cs @@ -0,0 +1,54 @@ +using System.Globalization; +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// Who requested, who pays and what was finally charged — from the audit record, in two honest phases: +/// identity and cost owner are ASSIGNED before any provider call (auth/profile/policy), and the charge is FINALIZED +/// after execution (usage priced, budgets settled, record written). A refused request still has its application, +/// team and workload; it just has no charge. +public static class Ownership +{ + public const string NotRecorded = "Not recorded"; + + /// "demo-app · team platform · workload public-writing · policy public · config v3". + public static string Assigned(AuditEntryView r) + { + var parts = new List + { + "application " + (r.ApplicationId ?? NotRecorded), + "team " + (string.IsNullOrWhiteSpace(r.Tags.Team) ? NotRecorded : r.Tags.Team), + "workload " + (r.ProfileId ?? NotRecorded), + }; + parts.Add(r.PolicyId is { Length: > 0 } p ? "policy " + p : r.Effect == "Deny" && r.StoppedAtStage is "auth" or "shape" or "classify" or "policy" ? "no policy decided (refused at " + r.StoppedAtStage + ")" : "policy " + NotRecorded); + if (r.ConfigVersion is { } v) parts.Add("config v" + v.ToString(CultureInfo.InvariantCulture)); + return string.Join(" · ", parts); + } + + /// The finalized charge with its basis, or why there is none. + public static string Finalized(AuditEntryView r) + { + bool anyCall = (r.Attempts?.Count ?? 0) > 0 || (r.ToolCalls?.Count ?? 0) > 0; + if (r.CacheHit) return "$0.00 — answered from the exact cache (no provider call)"; + if (!anyCall && ModelFacts.IsV2(r)) + return "No charge — " + (r.StoppedAtStage is { Length: > 0 } st ? "refused at " + TraceModel.Label(st) + " before any provider call" : "no provider call") + "; recorded with its application, team and workload"; + var cost = CostText.Cost(r); + var parts = new List { cost }; + if (r.ToolCalls is { Count: > 0 } tools) + parts.Add("includes " + tools.Count.ToString(CultureInfo.InvariantCulture) + (tools.Count == 1 ? " tool call" : " tool calls") + " (" + string.Join(", ", tools.Select(t => t.Tool)) + ")"); + if (r.ReservedUsd is { } res) parts.Add("reserved " + CostText.Usd(res) + ", settled " + (r.SettledUsd is { } s ? CostText.Usd(s) : NotRecorded)); + return string.Join(" · ", parts); + } + + /// Plain words for the recorded cache outcome. + public static string Cache(AuditEntryView r) => r.CacheOutcome switch + { + "hit" => "Hit — served from the exact cache", + "miss" => "Miss — looked up, then called the provider", + "bypass_web_search" => "Bypassed — web-search requests never use the cache", + "disabled" => "Off — the exact cache is disabled", + "not_reached" => "Not reached — refused before the cache stage", + null => r.CacheHit ? "Hit" : NotRecorded, + _ => r.CacheOutcome, + }; +} diff --git a/src/Covenant.Ui/Logic/ProfileEditing.cs b/src/Covenant.Ui/Logic/ProfileEditing.cs index d401cab..e2cb22e 100644 --- a/src/Covenant.Ui/Logic/ProfileEditing.cs +++ b/src/Covenant.Ui/Logic/ProfileEditing.cs @@ -13,6 +13,20 @@ public sealed class NewProfileForm public string Description { get; set; } = ""; } +/// The "Add application" form. An application is the CALLING SYSTEM: it owns a team (who pays), its budgets apply, +/// and it is granted the workload profiles it may use. The console runs requests on its behalf (ADR-0012). Creating it +/// here adds it to the configuration DRAFT only; a /v1 client additionally needs a startup key (Auth:Keys) bound to it. +public sealed class NewApplicationForm +{ + public string Id { get; set; } = ""; + public string DisplayName { get; set; } = ""; + public string Team { get; set; } = ""; + public string Description { get; set; } = ""; + public bool ConsoleTesting { get; set; } = true; + public List GrantedProfiles { get; set; } = []; + public string? DefaultProfile { 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); @@ -37,7 +51,68 @@ public static class ProfileEditing "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."; + "An application is the calling system (for example a support portal or a coding assistant). It belongs to a team — that team and its budgets pay for its requests — and it is granted the workload profiles it may use. The console runs requests on its behalf; nothing here bypasses its grants."; + + public const string ApplicationKeysExplained = + "Adding an application here lets the console run as it. A real client calling /v1 also needs an application key, which is a startup secret (Auth:Keys with Application set to this id) — keys are never created or shown in the console."; + + public const int MaxDisplayNameChars = 100; + public const int MaxDescriptionChars = 300; + + /// "Support portal" — or the id when no display name is configured. + public static string ApplicationName(string id, string? displayName) => string.IsNullOrWhiteSpace(displayName) ? id : displayName.Trim(); + + public static IReadOnlyList Problems(NewApplicationForm f, CovenantConfigDto cfg) + { + var p = new List(); + var id = f.Id.Trim(); + if (!ConnectionRules.IsValidId(id)) p.Add("Application id must be 1–64 characters of letters, digits, '.', '_' or '-'."); + else if (FindApplication(cfg, id) is not null) p.Add("An application with id '" + id + "' already exists."); + if (string.IsNullOrWhiteSpace(f.Team)) p.Add("Enter the owning team (it pays for the application's requests)."); + else if (!ConnectionRules.IsValidId(f.Team.Trim())) p.Add("Team must be 1–64 characters of letters, digits, '.', '_' or '-'."); + if (f.DisplayName.Trim().Length > MaxDisplayNameChars) p.Add("Display name must be at most 100 characters."); + if (f.Description.Trim().Length > MaxDescriptionChars) p.Add("Description must be at most 300 characters."); + foreach (var g in f.GrantedProfiles.Where(g => !Exists(cfg, g))) p.Add("Profile '" + g + "' does not exist."); + if (f.DefaultProfile is { Length: > 0 } d && !f.GrantedProfiles.Contains(d, StringComparer.Ordinal)) + p.Add("The default profile must also be granted."); + return p; + } + + /// Adds the application to (enabled). Returns the problems (draft untouched) or empty. + public static IReadOnlyList AddApplication(CovenantConfigDto draft, NewApplicationForm f) + { + var problems = Problems(f, draft); + if (problems.Count > 0) return problems; + draft.Applications.Add(new ApplicationDto + { + Id = f.Id.Trim(), + Team = f.Team.Trim(), + Enabled = true, + ConsoleTesting = f.ConsoleTesting, + MaxOutputTokens = 1024, // Match the Host default; serializing an unset nullable DTO otherwise yields an invalid zero bound. + GrantedProfiles = f.GrantedProfiles.Distinct(StringComparer.Ordinal).ToList(), + DefaultProfile = string.IsNullOrWhiteSpace(f.DefaultProfile) ? null : f.DefaultProfile, + DisplayName = string.IsNullOrWhiteSpace(f.DisplayName) ? null : f.DisplayName.Trim(), + Description = string.IsNullOrWhiteSpace(f.Description) ? null : f.Description.Trim(), + }); + return problems; + } + + public static string? SetDisplayName(ApplicationDto app, string? name) + { + var v = (name ?? "").Trim(); + if (v.Length > MaxDisplayNameChars) return "Display name must be at most 100 characters."; + app.DisplayName = v.Length == 0 ? null : v; + return null; + } + + public static string? SetApplicationDescription(ApplicationDto app, string? description) + { + var v = (description ?? "").Trim(); + if (v.Length > MaxDescriptionChars) return "Description must be at most 300 characters."; + app.Description = v.Length == 0 ? null : v; + return null; + } public static bool IsDeclared(CovenantConfigDto cfg, string? id) => id is not null && cfg.Profiles.Any(p => string.Equals(p.Id, id, StringComparison.Ordinal)); diff --git a/src/Covenant.Ui/Logic/RequestSnapshot.cs b/src/Covenant.Ui/Logic/RequestSnapshot.cs index 8569e03..17f2edf 100644 --- a/src/Covenant.Ui/Logic/RequestSnapshot.cs +++ b/src/Covenant.Ui/Logic/RequestSnapshot.cs @@ -17,6 +17,8 @@ public sealed class PlaygroundForm /// Preset letter the form was last filled from (A–D), or null for a custom request. public char? Scenario { get; set; } + /// Demo example the form was last filled from (), or null. + public string? ExampleId { get; set; } /// "Run as" application (GET /admin/applications id). The console never holds its credential. public string? ApplicationId { get; set; } /// Workload profile; only profiles granted to the application are selectable. Null = the server uses @@ -67,6 +69,7 @@ public string? Problem public void Clear() { Scenario = null; + ExampleId = null; ApplicationId = null; ProfileId = null; Prompt = ""; @@ -127,9 +130,11 @@ public static RequestSnapshot Freeze(int sequence, PlaygroundForm form, DateTime var prompt = form.FreshNonce ? basePrompt + (nonce ?? ScenarioPresets.NewNonce()) : basePrompt; var preset = ScenarioPresets.Find(form.Scenario); var matches = preset is not null && preset.StillMatches(form); + var example = DemoExamples.Find(form.ExampleId); + var exampleMatches = example is not null && DemoExamples.StillMatches(example, form); return new RequestSnapshot( Sequence: sequence, - ScenarioLabel: matches ? "Scenario " + preset!.Letter + " · " + preset.Title : "Custom", + ScenarioLabel: exampleMatches ? "Example · " + example!.Title : matches ? "Scenario " + preset!.Letter + " · " + preset.Title : "Custom", Scenario: matches ? preset!.Letter : null, ApplicationId: PlaygroundForm.Blank(form.ApplicationId), ProfileId: PlaygroundForm.Blank(form.ProfileId), @@ -167,7 +172,9 @@ public bool MatchesForm(PlaygroundForm form) /// An application as the "Run as" select shows it: disabled ones stay visible with the reason. public sealed record ApplicationChoice(ApplicationSummaryDto App, bool Selectable, string? Reason) { - public string Label => App.Id + (string.IsNullOrWhiteSpace(App.Team) ? "" : " · team " + App.Team) + (Reason is null ? "" : " — " + Reason); + /// Short option text: the friendly name (id when none), plus why it cannot be chosen. Team and id are shown in + /// the helper text under the select, so the selected value stays readable in a narrow pane. + public string Label => ComposerRules.ApplicationName(App) + (Reason is null ? "" : " — " + Reason); } /// A model-override option. is "Local", "Cloud" or null (not reported). @@ -194,6 +201,32 @@ public static IReadOnlyList Applications(IReadOnlyList"Support portal", or the id when no display name is configured. + public static string ApplicationName(ApplicationSummaryDto app) => string.IsNullOrWhiteSpace(app.DisplayName) ? app.Id : app.DisplayName.Trim(); + + /// Who pays for a run as this application: its team and the budgets that apply (ids). + public static string PayerText(ApplicationSummaryDto app) + => "Team " + (string.IsNullOrWhiteSpace(app.Team) ? "not set" : app.Team) + + (app.Budgets.Count > 0 ? " pays · budgets " + string.Join(", ", app.Budgets) : " pays"); + + /// The application the composer starts with: the first selectable one whose applicable hard budget is NOT + /// exhausted (so an isolated budget-demo application that sorts first is not the default), else the first selectable + /// one. Every application stays in the dropdown and can still be chosen explicitly; the budget example picks its own. + public static ApplicationSummaryDto? DefaultApplication(IReadOnlyList? apps, IReadOnlyList? budgets) + { + var selectable = Applications(apps).Where(c => c.Selectable).Select(c => c.App).ToList(); + return selectable.FirstOrDefault(a => DemoExamples.ExhaustedBudget(a, budgets) is null) ?? selectable.FirstOrDefault(); + } + + /// True when exactly one application can run console requests — the composer then states it instead of + /// showing an unexplained one-item dropdown. + public static ApplicationSummaryDto? OnlySelectable(IReadOnlyList? apps) + { + if (apps is null) return null; + var selectable = apps.Where(a => WhyNotSelectable(a) is null).ToList(); + return selectable.Count == 1 ? selectable[0] : null; + } + public static ApplicationSummaryDto? Find(IReadOnlyList? apps, string? id) { if (apps is null || string.IsNullOrWhiteSpace(id)) return null; diff --git a/src/Covenant.Ui/Logic/RoutePreview.cs b/src/Covenant.Ui/Logic/RoutePreview.cs new file mode 100644 index 0000000..adab34f --- /dev/null +++ b/src/Covenant.Ui/Logic/RoutePreview.cs @@ -0,0 +1,27 @@ +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// A Host dry-run route for the composer inputs captured in . Stale once the form changes +/// (application, profile, prompt or model) — shown as "Preview is for a previous form; preview again". +public sealed record RoutePreview(string Key, SimulateResponseDto? Result, string? Error, bool Loading) +{ + public static string KeyOf(PlaygroundForm f) + => string.Join("\u001f", f.ApplicationId ?? "", f.ProfileId ?? "", f.RequestedModel ?? "", f.Prompt); + + public bool IsCurrent(PlaygroundForm f) => string.Equals(Key, KeyOf(f), StringComparison.Ordinal); + + /// "Policy public-writing → anthropic/claude… (approved fallback: …)", or "Refused: …". + public static string Summary(SimulateResponseDto r) + { + if (!string.Equals(r.Decision, "route", StringComparison.Ordinal)) + return "Would be refused" + (r.PolicyId is { Length: > 0 } p ? " by policy " + p : "") + ": " + (r.Reason ?? "no reason reported"); + var head = (r.PolicyId is { Length: > 0 } pid ? "Policy " + pid + " → " : "→ ") + (r.Primary ?? "primary not reported"); + return r.Fallbacks.Count > 0 ? head + " (approved fallback: " + string.Join(", ", r.Fallbacks) + ")" : head; + } + + /// "Profile public-demo sets Public; detection found US SSN pattern → Pii." + public static string Classification(SimulateResponseDto r) + => "Profile " + (r.Profile ?? "default") + " sets " + (r.Baseline ?? "?") + + (r.DetectedSignal is { Length: > 0 } sig ? "; detection found " + sig + " → " + r.Classification : " → " + r.Classification) + "."; +} diff --git a/src/Covenant.Ui/Logic/ScenarioPresets.cs b/src/Covenant.Ui/Logic/ScenarioPresets.cs index d69df2b..a798377 100644 --- a/src/Covenant.Ui/Logic/ScenarioPresets.cs +++ b/src/Covenant.Ui/Logic/ScenarioPresets.cs @@ -35,12 +35,13 @@ public static class ScenarioPresets "Extract the priority from this ticket and answer only JSON {\"priority\":\"low|medium|high\"}: " + "'Printer on floor 3 is jammed again, not urgent.'"; - /// The same ticket with a synthetic sensitive marker. 078-05-1120 is the published sample SSN (never - /// issued to a person); it matches RegexDataClassifier's US SSN rule, so detection escalates the Public - /// baseline to Pii — the request must then stay local, or be refused when no local destination is eligible. + /// The same ticket with a synthetic sensitive marker. 000-12-3456 is structurally invalid as an SSN (area + /// number 000 is never assigned), so it identifies no one; it still matches RegexDataClassifier's US SSN pattern, so + /// detection escalates the Public baseline to Pii — the request must then stay local, or be refused when no local + /// destination is eligible. public const string SensitiveTicketPrompt = "Extract the priority from this ticket and answer only JSON {\"priority\":\"low|medium|high\"}: " + - "'Printer on floor 3 is jammed again, not urgent. Reporter SSN 078-05-1120 (synthetic test marker).'"; + "'Printer on floor 3 is jammed again, not urgent. Reporter SSN 000-12-3456 (synthetic test marker).'"; public const string ExpectedLow = "{\"priority\":\"low\"}"; diff --git a/src/Covenant.Ui/Logic/ShellStatus.cs b/src/Covenant.Ui/Logic/ShellStatus.cs index 5930bcb..baa2d98 100644 --- a/src/Covenant.Ui/Logic/ShellStatus.cs +++ b/src/Covenant.Ui/Logic/ShellStatus.cs @@ -7,6 +7,8 @@ public sealed record ModeBadge(string Label, string Tone, string Description); /// Header freshness: "Live" while fresh; "Stale · 12 s" only when stale. carries the /// exact last-update time for the tooltip/details. : ok | warn | bad. +public sealed record EnvironmentView(string Label, string? Raw, string Details); + public sealed record FreshnessView(string Label, string Tone, string Title, bool Stale); /// Pure header logic (mode badge, live/stale label, the one polite announcement). @@ -32,6 +34,35 @@ public static class ShellStatus _ => new(ModeNotReported, "unknown", "The Host did not report a provider mode."), }; + /// Header environment chip (deployment identity — NOT the routing mode). Launch profile names that look like + /// a routing mode ("demo-local-only", "demo-hybrid") are shown as "Demo instance" so the header never contradicts the + /// ACTIVE configuration's mode; the raw value stays in the tooltip/details. + public static EnvironmentView Environment(string? environment, int? configVersion, string? version, DateTimeOffset? startedUtc) + { + var raw = string.IsNullOrWhiteSpace(environment) ? null : environment.Trim(); + var label = raw is null ? "Environment not reported" + : LooksLikeRoutingMode(raw) ? "Demo instance" + : raw; + var details = new List { "Environment (Covenant:Environment): " + (raw ?? "not reported") }; + if (raw is not null && LooksLikeRoutingMode(raw)) + details.Add("This is the launch profile name, not the routing mode — the mode badge shows the active configuration."); + if (configVersion is { } v) details.Add("Active configuration: v" + v.ToString(CultureInfo.InvariantCulture)); + if (!string.IsNullOrWhiteSpace(version)) details.Add("Build: " + version); + if (startedUtc is { } st) details.Add("Started: " + st.UtcDateTime.ToString("yyyy-MM-dd HH:mm 'UTC'", CultureInfo.InvariantCulture)); + return new EnvironmentView(label, raw, string.Join("\n", details)); + } + + private static bool LooksLikeRoutingMode(string env) + { + var e = env.ToLowerInvariant(); + return e.EndsWith("local-only", StringComparison.Ordinal) || e.EndsWith("-hybrid", StringComparison.Ordinal) + || e is "hybrid" or "local" or "legacy-cloud"; + } + + /// "Hybrid · v7" — the ACTIVE configuration's mode and version. + public static string ModeWithVersion(string? mode, int? configVersion) + => Mode(mode).Label + (configVersion is { } v ? " · v" + v.ToString(CultureInfo.InvariantCulture) : ""); + /// 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/TraceModel.cs b/src/Covenant.Ui/Logic/TraceModel.cs index 9e84d11..915d276 100644 --- a/src/Covenant.Ui/Logic/TraceModel.cs +++ b/src/Covenant.Ui/Logic/TraceModel.cs @@ -49,7 +49,7 @@ public static class TraceModel public static string Label(string stage) => stage switch { - "auth" => "Auth", + "auth" => "Identify caller", "shape" => "Shape", "classify" => "Classify", "policy" => "Policy", @@ -59,10 +59,64 @@ public static class TraceModel "budget" => "Budget", "search" => "Web search", "provider" => "Provider", - "attribution" => "Attribution", + "attribution" => "Finalize cost", _ => stage, }; + /// What each stage does, in plain words (popover). Wire names stay stable; only the wording is descriptive. + public static string Explain(string stage) => stage switch + { + "auth" => "Resolves the calling application, its team (who pays) and the workload profile — BEFORE anything else runs, so even a refused request is attributed.", + "shape" => "Checks the request is well-formed and within bounds.", + "classify" => "Starts from the profile's trusted baseline; the detector can only raise it (e.g. an SSN pattern → PII).", + "policy" => "Finds the one policy for this workload profile and classification, and its eligible targets in order.", + "cache" => "Exact-match cache: a hit answers at $0 with no provider call; web-search requests bypass it.", + "rate_limit" => "Per-minute limits for all traffic and per team.", + "pause" => "Refuses new provider calls while an operator has paused them.", + "budget" => "Reserves the worst-case cost against every applicable budget before the call; refuses if it does not fit.", + "search" => "Optional governed web search: one bounded Tavily call, charged as a separate tool call.", + "provider" => "Calls the routed model; an approved fallback is a second attempt, never a hidden retry.", + "attribution" => "AFTER the provider answered: prices the reported (or estimated) usage. Budget settlement and the audit record happen for every request, refused ones included.", + _ => "", + }; + + /// Server-measured duration text. Positive sub-millisecond values are "<1 ms" (never a fabricated 0 ms); + /// unknown stays null; a measured 0 is "0 ms". + public static string? DurationText(double? ms) + { + if (ms is not { } d || double.IsNaN(d) || d < 0) return null; + if (d > 0 && d < 1) return "<1 ms"; + return d < 1000 ? d.ToString("F0", System.Globalization.CultureInfo.InvariantCulture) + " ms" + : (d / 1000).ToString("F2", System.Globalization.CultureInfo.InvariantCulture) + " s"; + } + + /// Chip state text that says the OUTCOME where "Passed/Skipped" would hide it (cache hit/miss/off, search + /// off/not needed, cost not needed because nothing was called). + public static string OutcomeText(TraceStepView s) => (s.Stage, s.State, s.ReasonCode) switch + { + ("cache", TraceStepState.Passed, "cache_hit") => "Hit", + ("cache", TraceStepState.Passed, "cache_miss") => "Miss", + ("cache", TraceStepState.Skipped, "cache_disabled") => "Off", + ("cache", TraceStepState.Skipped, "web_search_bypass") => "Bypassed", + ("search", TraceStepState.Skipped, "search_off") => "Off", + ("search", TraceStepState.Skipped, "search_not_triggered") => "Not needed", + ("attribution", TraceStepState.Skipped, _) => "No usage", + (_, TraceStepState.Skipped, "cache_hit") => "Not needed", + _ => StateText(s.State), + }; + + /// A sentence for the popover when the step's state alone would mislead. + public static string? OutcomeNote(TraceStepView s) => (s.Stage, s.State, s.ReasonCode) switch + { + ("attribution", TraceStepState.Skipped, _) => "No provider answer to price. The request is still recorded with its application, team and workload; any reservation was released or settled by the budget stage.", + ("cache", TraceStepState.Skipped, "cache_disabled") => "The exact cache is disabled (TTL 0): no lookup was made.", + ("cache", TraceStepState.Passed, "cache_miss") => "Looked up; no identical recent request — continued to the provider.", + ("cache", TraceStepState.Passed, "cache_hit") => "Answered from the exact cache at $0; no provider call.", + (_, TraceStepState.Skipped, "cache_hit") => "Not needed: the cache answered.", + (_, TraceStepState.Skipped, "not_reached") => "Not reached: an earlier stage ended the request.", + _ => null, + }; + public static TraceStepState ParseState(string? state) => state switch { "pending" => TraceStepState.Pending, @@ -214,7 +268,14 @@ private static TraceStepView ReduceProvider(List evs) /// 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 = EventsFromAuditSummary(summary, attempts); + return events.Count == 0 ? null : Reduce(events, complete: true, configVersion, source: "audit summary"); + } + + /// The compact persisted trace as terminal events in recorded order (for display and replay). + public static IReadOnlyList EventsFromAuditSummary(IReadOnlyList? summary, IReadOnlyList? attempts = null) + { + if (summary is null || summary.Count == 0) return []; var events = new List(summary.Count); long seq = 0; foreach (var step in summary) @@ -229,7 +290,7 @@ private static TraceStepView ReduceProvider(List evs) AttemptId = step.AttemptId, ReasonCode = step.ReasonCode, Target = target, }); } - return events.Count == 0 ? null : Reduce(events, complete: true, configVersion, source: "audit summary"); + return events; } /// "connection/model" for an attempt, or whichever half is recorded. @@ -251,6 +312,9 @@ public sealed class TraceAccumulator public bool Complete { get; private set; } public bool Expired { get; private set; } + + /// Every recorded event in seq order (replay input; never mutated by a replay). + public IReadOnlyList Events => _events.Values.OrderBy(e => e.Seq).ToList(); public int? ConfigVersion { get; private set; } public long LastSeq { get; private set; } public int Count => _events.Count; @@ -324,3 +388,46 @@ public sealed class SseParser return null; } } + +/// Replay of a RECORDED trace (§7): reveals the real events one at a time at a pedagogical pace. It never calls a +/// provider, never changes a record and never re-runs a request; durations and the final outcome shown are exactly the +/// recorded ones — only the pacing between reveals is chosen by the presenter, and the view says so. +public static class TraceReplay +{ + public const int BaseStepMs = 650; + + public static readonly IReadOnlyList<(string Label, double Speed)> Speeds = [("Slow", 0.5), ("Normal", 1.0), ("Fast", 2.0)]; + + /// Delay between reveals for a speed factor (clamped 0.25–4). + public static int DelayMs(double speed) => (int)Math.Round(BaseStepMs / Math.Clamp(speed, 0.25, 4.0)); + + /// Events in seq order, duplicates dropped. A trace that only has terminal events (the compact audit summary) + /// gets a "running" reveal before each terminal event, so every stage visibly enters and finishes; that inserted step + /// carries no duration and is pacing only. + public static IReadOnlyList Script(IEnumerable events) + { + var ordered = events.Where(e => e is not null && !string.IsNullOrWhiteSpace(e.Stage)) + .GroupBy(e => e.Seq).Select(g => g.First()).OrderBy(e => e.Seq).ToList(); + if (ordered.Any(e => e.State == "running")) return ordered; + var script = new List(ordered.Count * 2); + long seq = 0; + foreach (var e in ordered) + { + script.Add(new TraceEventDto { Seq = ++seq, Stage = e.Stage, State = "running", AttemptId = e.AttemptId, Target = e.Target }); + script.Add(new TraceEventDto + { + Seq = ++seq, Stage = e.Stage, State = e.State, DurationMs = e.DurationMs, ReasonCode = e.ReasonCode, + AttemptId = e.AttemptId, Target = e.Target, TsUtc = e.TsUtc, + RequestedMaxOutputTokens = e.RequestedMaxOutputTokens, EffectiveMaxOutputTokens = e.EffectiveMaxOutputTokens, + }); + } + return script; + } + + /// The view after the first script events. The last frame equals the recorded trace. + public static TraceView Frame(IReadOnlyList script, int revealed, int? configVersion) + { + var n = Math.Clamp(revealed, 0, script.Count); + return TraceModel.Reduce(script.Take(n), complete: n >= script.Count, configVersion, source: "replay"); + } +} diff --git a/src/Covenant.Ui/Logic/WebSourcesText.cs b/src/Covenant.Ui/Logic/WebSourcesText.cs index 361d62f..f14521e 100644 --- a/src/Covenant.Ui/Logic/WebSourcesText.cs +++ b/src/Covenant.Ui/Logic/WebSourcesText.cs @@ -69,7 +69,7 @@ public static class WebSourcesText "search_off" => "Web sources were off.", "search_not_triggered" => "Auto: the prompt did not ask for current information, so no search was made.", "location_required" => "A weather question needs a location. Add one in the Location field (or name the place in the prompt) and run again. Nothing was sent externally.", - "search_not_permitted" => "Web search is not permitted for this request (disabled, not Hybrid, profile not allowed, no price or key). Nothing was sent externally.", + "search_not_permitted" => "Web search is not set up for this request; the server's reason is below. Nothing was sent externally.", "search_sensitive" => "Refused: only Public requests may be searched, and the query or location must not contain sensitive data. Nothing was sent externally.", "search_failed" => "The search failed. No answer was given without sources.", "search_timeout" => "The search timed out. No answer was given without sources.", @@ -102,6 +102,84 @@ public static string Status(WebSourcesMode requested, RequestSearchDto? search, }; } + /// Which kind of problem a search reason code is — so the console never presents a setup gap as a provider + /// failure, or a missing city as a policy refusal. + public static SearchProblemKind Kind(string? code) => code switch + { + "location_required" => SearchProblemKind.MissingLocation, + "search_not_permitted" => SearchProblemKind.Setup, + "search_sensitive" or "budget_exceeded" => SearchProblemKind.PolicyRefusal, + "search_failed" or "search_timeout" or "search_rate_limited" or "search_empty" => SearchProblemKind.ProviderFailure, + _ => SearchProblemKind.None, + }; + + public static string KindLabel(SearchProblemKind kind) => kind switch + { + SearchProblemKind.Setup => "Setup", + SearchProblemKind.MissingLocation => "Needs a location", + SearchProblemKind.PolicyRefusal => "Refused by policy", + SearchProblemKind.ProviderFailure => "Search provider failed", + _ => "", + }; + + /// Can the CURRENT composer selection search, according to the applied configuration and the Host's + /// readiness report? Returns ONE cause — the most fundamental one — with one fix. Never changes the form: a profile + /// switch is only offered (), never applied. The Host's runtime check stays + /// authoritative and fail-closed; this only avoids offering a control that is guaranteed to be refused. + public static SearchReadiness Readiness(WebSearchStatusDto? status, string? statusError, CovenantConfigDto? config, + ApplicationSummaryDto? app, string? profileId) + { + if (status is null) + return SearchReadiness.Unknown(statusError ?? "Web search status has not been loaded yet."); + if (!status.KeyConfigured) + return SearchReadiness.Blocked("The server has no Tavily API key.", + "Set Tavily__ApiKey (or Tavily:ApiKey in the server's secret store) and restart Covenant. The key is never entered in the console.", + "settings#ws-h", "Web search settings"); + if (!status.EgressApproved) + return SearchReadiness.Blocked("api.tavily.com:443 is not on the startup egress allow-list.", + "Add api.tavily.com:443 to Providers:ProbeAllowList and restart Covenant. The console cannot widen egress.", + "settings#ws-h", "Web search settings"); + if (!status.ModeAllowsSearch) + return SearchReadiness.Blocked("The configuration is Local-only, which makes no external calls.", + "Switch the mode to Hybrid on the Policies page to allow approved external calls.", "policies", "Policies → mode"); + if (!status.Enabled) + return SearchReadiness.Blocked("Web search is disabled in the active configuration.", + "Enable it under Settings → Web search, then Save & apply.", "settings#ws-h", "Enable web search"); + if (!status.PriceConfigured) + return SearchReadiness.Blocked("No price per Tavily credit is configured (an unknown price is never $0).", + "Enter the price from your Tavily plan under Settings → Web search.", "settings#ws-h", "Set the price"); + var profile = config is null || profileId is null ? null : config.Profiles.FirstOrDefault(p => p.Id == profileId); + bool allowed = profileId is not null && (profile?.WebSearchAllowed ?? status.ProfilesAllowed.Contains(profileId, StringComparer.Ordinal)); + if (!allowed) + { + var alternative = app is null ? null + : ComposerRules.GrantedProfiles(app).FirstOrDefault(g => status.ProfilesAllowed.Contains(g, StringComparer.Ordinal)); + var name = profile?.Name ?? profileId ?? "the selected profile"; + return alternative is not null + ? SearchReadiness.Blocked("Workload profile '" + name + "' is not allowed to use web search.", + "Switch to an allowed Public profile, or allow this one under Policies → Applications & workload profiles.", + "policies#applications", "Profile permissions", alternative) + : SearchReadiness.Blocked("No workload profile granted to this application may use web search.", + "Allow web search on a Public-baseline profile and grant it to this application.", + "policies#applications", "Profile permissions"); + } + if (profile is not null && !string.Equals(profile.Baseline, "Public", StringComparison.Ordinal)) + return SearchReadiness.Blocked("Only Public requests may be searched; this profile's baseline is " + profile.Baseline + ".", + "Use a Public-baseline profile for research with web sources.", "policies#applications", "Profile permissions"); + return SearchReadiness.Ok; + } + + /// The readiness to SHOW for the configuration shown. A failed fetch shows no readiness (never an old Ready); + /// readiness computed for a different configuration version than the one shown is discarded (Mismatch ⇒ refetch). + public static (WebSearchStatusDto? Status, string? Error, bool Mismatch) Reconcile(int? shownConfigVersion, WebSearchStatusDto? fetched, string? fetchError) + { + if (fetched is null) return (null, fetchError ?? "Web search status is not available.", false); + if (shownConfigVersion is { } cv && fetched.ConfigVersion is { } rv && rv != cv) + return (null, "Web search readiness was reported for configuration v" + rv.ToString(CultureInfo.InvariantCulture) + + " while v" + cv.ToString(CultureInfo.InvariantCulture) + " is shown — refreshing.", true); + return (fetched, fetchError, false); + } + public static string Count(int n) => n.ToString(CultureInfo.InvariantCulture) + (n == 1 ? " source" : " sources"); /// Readiness checklist of GET /admin/web-search, in the order an operator fixes it. @@ -115,3 +193,16 @@ public static string Status(WebSourcesMode requested, RequestSearchDto? search, ("At least one Public profile allowed to search", s.ProfilesAllowed.Count > 0), ]; } + +public enum SearchProblemKind { None, Setup, MissingLocation, PolicyRefusal, ProviderFailure } + +/// One readiness verdict for the composer. false ⇒ Auto/Required are not offered as if +/// they would work; the cause and its single fix are shown instead. false ⇒ the status could not be +/// read; the controls stay usable and the Host decides. +public sealed record SearchReadiness(bool Possible, bool Known, string? Cause, string? Fix, string? Href, string? HrefLabel, string? SwitchToProfile) +{ + public static readonly SearchReadiness Ok = new(true, true, null, null, null, null, null); + public static SearchReadiness Unknown(string why) => new(true, false, why, "The Host still checks every search request.", null, null, null); + public static SearchReadiness Blocked(string cause, string fix, string href, string hrefLabel, string? switchTo = null) + => new(false, true, cause, fix, href, hrefLabel, switchTo); +} diff --git a/src/Covenant.Ui/Logic/WorkloadRouteSetup.cs b/src/Covenant.Ui/Logic/WorkloadRouteSetup.cs new file mode 100644 index 0000000..da38480 --- /dev/null +++ b/src/Covenant.Ui/Logic/WorkloadRouteSetup.cs @@ -0,0 +1,92 @@ +using Covenant.Ui.Models; + +namespace Covenant.Ui.Logic; + +/// A named workload the demo uses. Routing is by this profile (+ classification), never by prompt keywords. +public sealed record WorkloadPreset(string ProfileId, string Name, string Baseline, string Purpose); + +/// What "route this workload to this model" would change in the DRAFT — or why it is refused (draft untouched). +public sealed record WorkloadRoutePlan(string? Problem, IReadOnlyList Changes) +{ + public bool Ok => Problem is null; +} + +/// Explicit, ADDITIVE demo setup (docs/CONSOLE-DEMO-CLARITY-TASKS.md §3/§4/§8): routes one named workload profile +/// to one configured model by adding (1) the profile if missing, (2) a policy scoped to exactly that profile and its +/// baseline, and (3) a grant of that profile to the console-testable applications. Existing policies, profiles, +/// connections and prices are never modified or removed; the operator previews the impact and saves a new version. +/// Refused: a cloud model for a non-Public workload (no unreviewed cloud fallback for Internal/sensitive work), an +/// unpriced cloud model (no invented pricing), a disabled connection, or a workload already routed by its own policy. +public static class WorkloadRouteSetup +{ + public static readonly IReadOnlyList Presets = + [ + new("public-writing", "Public writing", "Public", "Public content drafted with an approved model."), + new("public-research", "Public research", "Public", "Public research; may use governed web search where allowed."), + new("internal-coding", "Internal coding", "Internal", "Internal code assistance on a local model."), + new("internal-research", "Internal research", "Internal", "Internal analysis on a stronger local model."), + ]; + + /// The presets a model may serve: a cloud model only Public workloads. + public static IReadOnlyList PresetsFor(ConnectionDto connection) + => ComposerRules.BoundaryLabel(connection.Boundary) == "Cloud" ? Presets.Where(p => p.Baseline == "Public").ToList() : Presets; + + public static WorkloadRoutePlan Plan(CovenantConfigDto cfg, WorkloadPreset preset, string connectionId, string modelId) + => Build(cfg, preset, connectionId, modelId, apply: false); + + /// Applies the plan to when it is allowed; returns the same plan either way. + public static WorkloadRoutePlan ApplyTo(CovenantConfigDto draft, WorkloadPreset preset, string connectionId, string modelId) + => Build(draft, preset, connectionId, modelId, apply: true); + + private static WorkloadRoutePlan Build(CovenantConfigDto cfg, WorkloadPreset preset, string connectionId, string modelId, bool apply) + { + var conn = cfg.Connections.FirstOrDefault(c => c.Id == connectionId); + if (conn is null) return Refuse("Connection '" + connectionId + "' is not configured."); + if (!conn.Enabled) return Refuse("Connection '" + connectionId + "' is disabled — enable it first."); + var model = conn.Models.FirstOrDefault(m => m.ModelId == modelId); + if (model is null) return Refuse("Model '" + modelId + "' is not permitted on '" + connectionId + "' — add it to the connection first."); + bool cloud = ComposerRules.BoundaryLabel(conn.Boundary) == "Cloud"; + if (cloud && preset.Baseline != "Public") + return Refuse(preset.Name + " is " + preset.Baseline + " work: it never routes to a cloud model."); + if (cloud && PolicyRoutes.IsLocalOnly(cfg.Mode)) + return Refuse("The configuration is Local-only: cloud models cannot run. Switch to Hybrid on the Policies page first."); + if (cloud && (model.Price?.InputPer1M is null || model.Price?.OutputPer1M is null)) + return Refuse("Model '" + modelId + "' has no input/output price. Enter the provider's current prices on the connection first — an unknown price is never $0."); + + var profile = cfg.Profiles.FirstOrDefault(p => p.Id == preset.ProfileId); + if (profile is not null && !string.Equals(profile.Baseline, preset.Baseline, StringComparison.Ordinal)) + return Refuse("Profile '" + preset.ProfileId + "' exists with baseline " + profile.Baseline + ", not " + preset.Baseline + ". Use another profile or edit it under Policies."); + var existing = cfg.Policies.FirstOrDefault(p => p.Enabled && p.Profiles.Contains(preset.ProfileId, StringComparer.Ordinal) + && p.Classifications.Contains(preset.Baseline, StringComparer.OrdinalIgnoreCase)); + if (existing is not null) + return Refuse("'" + preset.Name + "' is already routed by policy '" + existing.Id + "'. Edit that policy under Policies instead of adding a second rule (two rules would be ambiguous and refused)."); + + var changes = new List(); + if (profile is null) changes.Add("Add workload profile '" + preset.ProfileId + "' (" + preset.Name + ", baseline " + preset.Baseline + ")."); + var policyId = PolicyEditing.UniqueId(preset.ProfileId, cfg); + changes.Add("Add policy '" + policyId + "': " + preset.Baseline + " requests of profile '" + preset.ProfileId + "' → " + connectionId + "/" + modelId + + (cloud ? " (cloud, priced)" : " (local)") + ". No fallback; other profiles and PII/PHI keep their existing rules."); + var grantTo = cfg.Applications.Where(a => a.Enabled && a.ConsoleTesting && !a.GrantedProfiles.Contains(preset.ProfileId, StringComparer.Ordinal)).ToList(); + foreach (var a in grantTo) changes.Add("Grant '" + preset.ProfileId + "' to application '" + a.Id + "' (its other grants and default are unchanged)."); + if (preset.ProfileId == "public-research") + changes.Add("Web search stays as configured — allow it on this profile under Policies → Applications & workload profiles if wanted."); + + if (apply) + { + if (profile is null) + cfg.Profiles.Add(new WorkloadProfileDto { Id = preset.ProfileId, Name = preset.Name, Baseline = preset.Baseline, Description = preset.Purpose }); + cfg.Policies.Add(new PolicyDto + { + Id = policyId, Name = preset.Name + " → " + modelId, Enabled = true, + Classifications = [preset.Baseline], Profiles = [preset.ProfileId], Strategy = "fixed", + Retry = new RetrySettingsDto { MaxAttempts = 1, DeadlineMs = 120_000, On = [] }, + Targets = [new PolicyTargetDto { ConnectionId = connectionId, ModelId = modelId }], + Explanation = preset.Purpose + " Routed by workload profile, not by the prompt's content.", + }); + foreach (var a in grantTo) a.GrantedProfiles.Add(preset.ProfileId); + } + return new WorkloadRoutePlan(null, changes); + } + + private static WorkloadRoutePlan Refuse(string why) => new(why, []); +} diff --git a/src/Covenant.Ui/Models/ConfigContracts.cs b/src/Covenant.Ui/Models/ConfigContracts.cs index d7f7430..37d2308 100644 --- a/src/Covenant.Ui/Models/ConfigContracts.cs +++ b/src/Covenant.Ui/Models/ConfigContracts.cs @@ -113,6 +113,9 @@ public sealed class ApplicationDto [JsonPropertyName("granted_profiles")] public List GrantedProfiles { get; set; } = []; [JsonPropertyName("default_profile")] public string? DefaultProfile { get; set; } [JsonPropertyName("max_output_tokens")] public int? MaxOutputTokens { get; set; } + /// Human name of the calling system (optional, display only; null ⇒ show the id). + [JsonPropertyName("display_name")] public string? DisplayName { get; set; } + [JsonPropertyName("description")] public string? Description { get; set; } } public sealed class WorkloadProfileDto @@ -270,6 +273,10 @@ public sealed class ApplicationSummaryDto [JsonPropertyName("console_testing")] public bool ConsoleTesting { get; set; } [JsonPropertyName("granted_profiles")] public List GrantedProfiles { get; set; } = []; [JsonPropertyName("default_profile")] public string? DefaultProfile { get; set; } + [JsonPropertyName("display_name")] public string? DisplayName { get; set; } + [JsonPropertyName("description")] public string? Description { get; set; } + /// Budget ids that apply to this application's requests (global, team, application). + [JsonPropertyName("budgets")] public List Budgets { get; set; } = []; } /// POST /admin/playground/requests body (admin token; same response contract as /v1/chat/completions). diff --git a/src/Covenant.Ui/Models/Contracts.cs b/src/Covenant.Ui/Models/Contracts.cs index b1f902d..2b61a4c 100644 --- a/src/Covenant.Ui/Models/Contracts.cs +++ b/src/Covenant.Ui/Models/Contracts.cs @@ -283,6 +283,10 @@ public sealed class AuditEntryView [JsonPropertyName("WebSearch")] public AuditWebSearchView? WebSearch { get; set; } /// ADR-0015: non-inference tool calls with their own charges, separate from provider Attempts. [JsonPropertyName("ToolCalls")] public List? ToolCalls { get; set; } + /// The policy that decided the route (null on older records, or when no policy matched). + [JsonPropertyName("PolicyId")] public string? PolicyId { get; set; } + /// hit | miss | bypass_web_search | disabled | not_reached (null on older records). + [JsonPropertyName("CacheOutcome")] public string? CacheOutcome { get; set; } } /// Core AuditWebSearch. diff --git a/src/Covenant.Ui/Pages/Connections.razor b/src/Covenant.Ui/Pages/Connections.razor index a453b01..cbcbdaa 100644 --- a/src/Covenant.Ui/Pages/Connections.razor +++ b/src/Covenant.Ui/Pages/Connections.razor @@ -120,7 +120,8 @@
        @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)
      • +
      • @m.ModelId · @Money.Price(m.Price?.InputPer1M, m.Price?.OutputPer1M)@(m.Price?.Basis is { Length: > 0 } b ? " (" + b + ")" : "")@RegisteredNote(cat, m.ModelId) +
      • }
      } diff --git a/src/Covenant.Ui/Pages/Playground.razor b/src/Covenant.Ui/Pages/Playground.razor index 534f970..bbb97df 100644 --- a/src/Covenant.Ui/Pages/Playground.razor +++ b/src/Covenant.Ui/Pages/Playground.razor @@ -25,9 +25,9 @@
      Covenant - @State.EnvironmentLabel - @{ var mode = ShellStatus.Mode(State.LastStatus?.Mode); } - @mode.Label + @{ var mode = ShellStatus.Mode(State.LastStatus?.Mode); var penv = ShellStatus.Environment(State.LastStatus?.Environment, State.LastStatus?.ConfigVersion, State.LastStatus?.Version, State.LastStatus?.StartedUtc); } + @ShellStatus.ModeWithVersion(State.LastStatus?.Mode, State.LastStatus?.ConfigVersion) + @penv.Label @if (State.Paused) { New provider calls paused @@ -75,7 +75,8 @@
      @if (Pg.Selected is { } trun) { - + } else { @@ -142,7 +143,8 @@ else
      - + }
    @@ -298,7 +300,11 @@ else // applications endpoint still gets the prompt filled. if (Ws.Applications is null && (Ws.Loading || State.Restoring || (State.Connected && Ws.LoadedUtc is null))) return; _appliedScenario = Scenario; - if (!Pg.Running && ScenarioPresets.Find(Scenario) is { } preset) Pg.ApplyPreset(preset); + if (Pg.Running) return; + // /playground/ fills a ready example (never runs); legacy /playground/A–D fill the old presets. + if (Pg.Examples.FirstOrDefault(e => string.Equals(e.Example.Id, Scenario, StringComparison.Ordinal)) is { Ready: true } example) + _ = Pg.ApplyExampleAsync(example); + else if (ScenarioPresets.Find(Scenario) is { } preset) Pg.ApplyPreset(preset); } private Task RunAsync() diff --git a/src/Covenant.Ui/Pages/Requests.razor b/src/Covenant.Ui/Pages/Requests.razor index 66e27ad..77fe4da 100644 --- a/src/Covenant.Ui/Pages/Requests.razor +++ b/src/Covenant.Ui/Pages/Requests.razor @@ -162,7 +162,7 @@ Time (UTC) - Application / team + Application / team / workload Outcome Selected → served Duration @@ -178,7 +178,7 @@ var model = ModelFacts.SelectedToServed(r); @(r.TimestampUtc.UtcDateTime.ToString("HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture))@(r.TimestampUtc.UtcDateTime.ToString("MM-dd", System.Globalization.CultureInfo.InvariantCulture)) - @(r.ApplicationId ?? r.Principal)@r.Tags.Team + @(r.ApplicationId ?? r.Principal)@r.Tags.Team@(r.ProfileId ?? "")@(r.PolicyId is { } pol2 ? " · " + pol2 : "") @model@(r.Attempts is { Count: > 1 } at ? " (" + at.Count.ToString(System.Globalization.CultureInfo.InvariantCulture) + " attempts)" : "") @Fmt.Ms(r.DurationMs) @@ -284,6 +284,7 @@
    Operator
    @(rec.EntryPoint == "console" ? Fmt.OrNotRecorded(rec.OperatorRef) + " (shared console operator)" : rec.OperatorRef ?? "— (application key)")
    Workload profile
    @Fmt.OrNotRecorded(rec.ProfileId)
    Config version
    @(rec.ConfigVersion is { } cv ? "v" + cv.ToString(System.Globalization.CultureInfo.InvariantCulture) : ModelFacts.NotRecorded)
    +
    Policy
    @(rec.PolicyId ?? (ModelFacts.IsV2(rec) && rec.ConfigVersion is not null ? "None decided" : ModelFacts.NotRecorded))
    Workflow / use case
    @Fmt.OrNotRecorded(rec.Tags.Workflow) · @Fmt.OrNotRecorded(rec.Tags.UseCase)
    Stopped at
    @StoppedText(rec)
    Recorded reason
    @Fmt.OrNotRecorded(rec.Reason)
    @@ -354,7 +355,8 @@

    Trace summary

    @if (trace is not null) { - + } else { @@ -374,7 +376,8 @@ {
    Reserved / settled
    @Money.Usd(res) / @Money.Usd(rec.SettledUsd)
    } -
    Cache
    @(rec.CacheHit ? "Hit — response reused, no provider call" : "Not served from cache")
    +
    Cache
    @Ownership.Cache(rec)
    +
    Charged (after execution)
    @Ownership.Finalized(rec)
    Duration
    @Fmt.Ms(rec.DurationMs) (recorded by Covenant)
    diff --git a/src/Covenant.Ui/Services/Fmt.cs b/src/Covenant.Ui/Services/Fmt.cs index 8939a24..1b8bbb9 100644 --- a/src/Covenant.Ui/Services/Fmt.cs +++ b/src/Covenant.Ui/Services/Fmt.cs @@ -30,7 +30,8 @@ public static string Utc(DateTimeOffset? t) public static string UtcShort(DateTimeOffset t) => t.UtcDateTime.ToString("HH:mm:ss", Inv); - public static string Ms(double ms) => ms < 1000 ? ms.ToString("F0", Inv) + " ms" : (ms / 1000).ToString("F2", Inv) + " s"; + /// Positive sub-millisecond values render as "<1 ms", never a rounded "0 ms" (Logic/TraceModel.DurationText). + public static string Ms(double ms) => Covenant.Ui.Logic.TraceModel.DurationText(ms) ?? "Not reported"; public static string Ago(DateTimeOffset? t, DateTimeOffset now) { diff --git a/src/Covenant.Ui/Services/PlaygroundState.cs b/src/Covenant.Ui/Services/PlaygroundState.cs index 89ae75e..31b26b4 100644 --- a/src/Covenant.Ui/Services/PlaygroundState.cs +++ b/src/Covenant.Ui/Services/PlaygroundState.cs @@ -35,6 +35,10 @@ public sealed class PlaygroundRun(RequestSnapshot snapshot) /// HTTP status of the search lookup (null = not looked up yet). public int? SearchLookupStatus { get; internal set; } + /// The recorded events of this run for a replay: the live/snapshot events, else the audit summary. + public IReadOnlyList RecordedEvents() + => Trace.Count > 0 ? Trace.Events : TraceModel.EventsFromAuditSummary(Evidence.Record?.Trace, Evidence.Record?.Attempts); + public string WebSourcesStatus => WebSourcesText.Status(Snapshot.WebSources, Search, SearchLookupStatus); public string Text => Result is { Text.Length: > 0 } r && !InFlight ? r.Text : _text.ToString(); @@ -113,7 +117,54 @@ public void SetStreamingDefault(bool streaming) Notify(); } - public string? Problem => ComposerRules.Problem(Form, _workspace.Applications); + public string? Problem => ComposerRules.Problem(Form, _workspace.Applications) + ?? (Form.WebSources != WebSourcesMode.Off && SearchReadiness is { Known: true, Possible: false } r + ? "Web sources " + WebSourcesText.Label(Form.WebSources) + " cannot run: " + r.Cause + " Choose Off, or fix it first." + : null); + + /// Can the current selection search (ONE cause when not)? From the applied configuration and the Host's + /// readiness report; the runtime check stays authoritative. + public SearchReadiness SearchReadiness => WebSourcesText.Readiness(_workspace.WebSearch, _workspace.WebSearchError, + _workspace.Config?.Config, ComposerRules.Find(_workspace.Applications, Form.ApplicationId), Form.ProfileId); + + /// Examples resolved against the CURRENT applied configuration. + public IReadOnlyList Examples => DemoExamples.All + .Select(e => DemoExamples.Resolve(e, _workspace.Config?.Config, _workspace.Applications, _workspace.Budgets, _workspace.WebSearch, Form.ApplicationId)) + .ToList(); + + /// Host dry run (POST /admin/policies/simulate) for the form as it was when previewed: chosen policy, primary, + /// approved fallbacks, excluded targets and why. No provider call, no record, no spend. + public RoutePreview? Preview { get; private set; } + + /// Fills the composer from a ready example (never runs) and previews its route. + public async Task ApplyExampleAsync(ExampleResolution resolution) + { + if (Running || !DemoExamples.ApplyTo(resolution, Form)) return; + PresetNote = null; + Notify(); + await PreviewRouteAsync(); + } + + public async Task PreviewRouteAsync() + { + if (Running || string.IsNullOrWhiteSpace(Form.ApplicationId) || string.IsNullOrWhiteSpace(Form.Prompt)) return; + var key = RoutePreview.KeyOf(Form); + Preview = new RoutePreview(key, null, null, Loading: true); + Notify(); + try + { + var result = await _admin.SimulateAsync(new SimulateRequestDto + { + ApplicationId = Form.ApplicationId!, ProfileId = Form.ProfileId, Prompt = Form.Prompt, Model = Form.RequestedModel, + }); + Preview = new RoutePreview(key, result, null, Loading: false); + } + catch (Exception ex) + { + Preview = new RoutePreview(key, null, "Route preview unavailable: " + ex.Message, Loading: false); + } + Notify(); + } public bool CanRun => !Running && Problem is null; /// Shows a stored run. Never resubmits. @@ -137,8 +188,8 @@ public void EnsureDefaultApplication() { if (Running || _workspace.Applications is not { } apps) return; if (ComposerRules.Find(apps, Form.ApplicationId) is { } cur && ComposerRules.WhyNotSelectable(cur) is null) return; - var first = ComposerRules.Applications(apps).FirstOrDefault(c => c.Selectable); - if (first is not null && ComposerRules.SelectApplication(Form, apps, first.App.Id)) Notify(); + var first = ComposerRules.DefaultApplication(apps, _workspace.Budgets); + if (first is not null && ComposerRules.SelectApplication(Form, apps, first.Id)) Notify(); } public bool SelectApplication(string? id) @@ -234,6 +285,8 @@ public async Task RunAsync() // The backend records success/failure from real calls: re-read shared health after any provider attempt. _ = _catalog.RefreshAsync(); + // Spend and reservations changed: refresh budget facts (Budgets page, budget example readiness). + if (result.HttpStatus is not null) _ = _workspace.RefreshBudgetsAsync(); } /// Stops waiting for the in-flight run. Not a rollback. @@ -393,6 +446,7 @@ private void Clear() Form.Clear(); Form.Streaming = StreamingDefault; PresetNote = null; + Preview = null; _sequence = 0; Notify(); } diff --git a/src/Covenant.Ui/Services/WorkspaceConfig.cs b/src/Covenant.Ui/Services/WorkspaceConfig.cs index add5088..c027fa0 100644 --- a/src/Covenant.Ui/Services/WorkspaceConfig.cs +++ b/src/Covenant.Ui/Services/WorkspaceConfig.cs @@ -13,6 +13,9 @@ public sealed class WorkspaceConfig : IDisposable private readonly AppState _state; private readonly AdminApi _api; private Task? _inflight; + /// Incremented on disconnect: a load that started in an older session never applies its results. + private int _generation; + private int _mismatchRetries; public WorkspaceConfig(AppState state, AdminApi api) { @@ -33,6 +36,11 @@ public WorkspaceConfig(AppState state, AdminApi api) public List? Budgets { get; private set; } public string? BudgetsError { get; private set; } + /// GET /admin/web-search (ADR-0015): readiness of the APPLIED configuration. Refreshed with everything else + /// (config apply, reconnect, an active-version change reported by the status feed). + public WebSearchStatusDto? WebSearch { get; private set; } + public string? WebSearchError { get; private set; } + public DateTimeOffset? LoadedUtc { get; private set; } public bool Loading => _inflight is { IsCompleted: false }; @@ -53,26 +61,41 @@ public Task EnsureLoadedAsync(bool force = false) /// Loads on connect (also after a session restore) so every page sees the same facts. private void OnStateChanged() { - if (_state.Connected && LoadedUtc is null && _inflight is null) _ = EnsureLoadedAsync(); + if (!_state.Connected) return; + if (LoadedUtc is null && _inflight is null) { _ = EnsureLoadedAsync(); return; } + // Another tab, a rollback or a CLI change activated a different version: never keep composing against a stale one. + if (_state.LastStatus?.ConfigVersion is { } active && !Loading + && ((Config is { } loaded && loaded.Version != active) || (WebSearch is { } ws && ws.ConfigVersion is { } wv && wv != active))) + _ = EnsureLoadedAsync(force: true); } private async Task LoadAllAsync() { + int generation = _generation; try { var apps = LoadAsync(() => _api.GetApplicationsAsync(), "Test applications"); var config = LoadAsync(() => _api.GetConfigAsync(), "Configuration"); var budgets = LoadAsync(() => _api.GetBudgetsAsync(), "Budgets"); + var search = LoadAsync(() => _api.GetWebSearchStatusAsync(), "Web search status"); var (a, ae) = await apps; var (c, ce) = await config; var (b, be) = await budgets; - if (!_state.Connected) return; + var (w, we) = await search; + if (!_state.Connected || generation != _generation) return; // disconnected (or reconnected) meanwhile Applications = a ?? Applications; ApplicationsError = ae; Config = c ?? Config; ConfigError = ce; Budgets = b ?? Budgets; BudgetsError = be; + // Readiness must describe the configuration shown: never keep an old Ready after a failed refresh, and never + // pair configuration vN with readiness computed for another version (both are fetched concurrently). + var (shown, shownError, mismatch) = Covenant.Ui.Logic.WebSourcesText.Reconcile(Config?.Version, w, we); + WebSearch = shown; + WebSearchError = shownError; + if (!mismatch) _mismatchRetries = 0; + else if (_mismatchRetries++ < 3) _ = RetryAfterMismatchAsync(generation); LoadedUtc = DateTimeOffset.UtcNow; } finally @@ -83,6 +106,26 @@ private async Task LoadAllAsync() public Task RefreshAsync() => EnsureLoadedAsync(force: true); + private async Task RetryAfterMismatchAsync(int generation) + { + await Task.Delay(500); + if (generation == _generation) await EnsureLoadedAsync(force: true); + } + + /// Budget states only — after a completed request (spend and reservations changed), so readiness of the + /// budget example and the Budgets facts are current. Guarded like a full load; failures keep the last known values + /// with the error reported. + public async Task RefreshBudgetsAsync() + { + if (!_state.Connected) return; + int generation = _generation; + var (b, be) = await LoadAsync(() => _api.GetBudgetsAsync(), "Budgets"); + if (!_state.Connected || generation != _generation) return; + Budgets = b ?? Budgets; + BudgetsError = be; + Notify(); + } + private static async Task<(T? Value, string? Error)> LoadAsync(Func> call, string what) where T : class { try @@ -105,12 +148,16 @@ private async Task LoadAllAsync() private void Clear() { + _generation++; + _mismatchRetries = 0; Applications = null; ApplicationsError = null; Config = null; ConfigError = null; Budgets = null; BudgetsError = null; + WebSearch = null; + WebSearchError = null; LoadedUtc = null; _inflight = null; Notify(); diff --git a/src/Covenant.Ui/wwwroot/css/app.css b/src/Covenant.Ui/wwwroot/css/app.css index c4051ea..f39d80f 100644 --- a/src/Covenant.Ui/wwwroot/css/app.css +++ b/src/Covenant.Ui/wwwroot/css/app.css @@ -32,6 +32,11 @@ code, .mono { font-family: var(--font-mono); font-variant-numeric: tabular-nums; /* Focus: one visible ring everywhere, in the accent colour. */ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: var(--radius-control); } button:focus:not(:focus-visible), a:focus:not(:focus-visible) { outline: none; } +/* Route change focuses the page

    (FocusOnNavigate sets tabindex=-1) so screen readers announce the new page. That + heading is not an interactive control, so it never shows a focus outline — on mouse OR keyboard navigation. Tab moves + on to real controls, which keep the :focus-visible ring above. */ +h1[tabindex="-1"]:focus, h1[tabindex="-1"]:focus-visible { outline: none; box-shadow: none; } +.page-head h1, .titles > h1 { align-self: flex-start; max-width: 100%; } /* ---- Boot placeholder (replaced when the runtime mounts) ---- */ .boot { min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; color: var(--muted); } @@ -74,13 +79,15 @@ button:focus:not(:focus-visible), a:focus:not(:focus-visible) { outline: none; } } .nav-disconnect { align-self: flex-start; } -.shell-main { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; } +/* One horizontal gutter for header, banners and page body so their content edges line up at every width. */ +.shell-main { --gutter: 28px; flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; } .status-header { - display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; padding: 8px 24px; min-height: 56px; + display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; padding: 8px var(--gutter); min-height: 56px; border-bottom: 1px solid var(--border); background: var(--surface); font-size: var(--text-secondary); position: relative; z-index: 20; } -.status-header .env { font-family: var(--font-mono); padding: 2px 8px; border: 1px solid var(--border); border-radius: 4px; overflow-wrap: anywhere; } +.status-header .env { display: inline-flex; align-items: baseline; gap: 6px; padding: 2px 8px; border: 1px solid var(--border); border-radius: 4px; overflow-wrap: anywhere; color: var(--text); text-decoration: none; } +.status-header a.env:hover { border-color: var(--accent); } .status-header .grow, .present-head .grow, .panel-head .grow { flex-grow: 1; } .indicator { display: inline-flex; align-items: center; gap: 6px; } .dot { width: 8px; height: 8px; border-radius: 4px; background: var(--subtle); flex: 0 0 auto; display: inline-block; } @@ -96,7 +103,10 @@ button:focus:not(:focus-visible), a:focus:not(:focus-visible) { outline: none; } .mode-badge.hybrid { background: var(--cloud-bg); color: var(--cloud); border-color: transparent; } .mode-badge.legacy { background: var(--amber-bg); color: var(--amber); border-color: transparent; } .mode-badge.unknown { color: var(--muted); } -.icon-btn { padding: 0 8px; min-width: 32px; } +/* Icon-only buttons: fixed square, icon centred on the same baseline as neighbouring buttons. */ +.btn.icon-btn { padding: 0; width: var(--target-min); min-width: var(--target-min); height: var(--target-min); min-height: var(--target-min); flex: 0 0 auto; } +.btn.sm.icon-btn { width: 32px; min-width: 32px; height: 32px; min-height: 32px; } +.btn .icon { display: block; } .pause-control { position: relative; display: inline-flex; align-items: center; gap: 4px; } .popover { position: absolute; top: calc(100% + 6px); right: 0; z-index: 40; width: min(360px, 90vw); @@ -107,12 +117,12 @@ button:focus:not(:focus-visible), a:focus:not(:focus-visible) { outline: none; } .icon { flex: 0 0 auto; vertical-align: middle; } .pause-banner { - display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; padding: 10px 28px; + display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; padding: 10px var(--gutter); background: var(--amber-bg); border-bottom: 1px solid var(--amber); font-size: var(--text-secondary); } .pause-banner strong { color: var(--amber); } -.page { padding: 22px 28px 48px; display: flex; flex-direction: column; gap: 18px; max-width: 1400px; width: 100%; } +.page { padding: 22px var(--gutter) 48px; display: flex; flex-direction: column; gap: 18px; width: 100%; } .page-head { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 16px; } .page-head .titles { display: flex; flex-direction: column; flex: 1 1 320px; min-width: 0; } .page-head .lede { font-size: var(--text-secondary); color: var(--muted); } @@ -363,7 +373,7 @@ details.tech[open] > summary { margin-bottom: 6px; } border: 1px solid var(--border); background: var(--surface2); color: var(--text); font: inherit; cursor: pointer; } .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-name { font-size: 13px; font-weight: 600; white-space: normal; overflow-wrap: anywhere; } .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) { @@ -392,10 +402,28 @@ details.tech[open] > summary { margin-bottom: 6px; } .trace-step.s-skipped .trace-name { font-weight: 500; text-decoration: line-through; text-decoration-color: var(--border); } .trace-step.s-pending .trace-chip, .trace-step.s-notreported .trace-chip { background: transparent; color: var(--subtle); } .trace-step.open .trace-chip { outline: 2px solid var(--accent); outline-offset: 1px; } +/* §7: real-event animation. A state change swaps the class → a different animation-name → it plays once. Running pulses. + Replay (.trace.replaying) uses the same states, revealed from recorded events at a presenter-chosen pace. */ +.trace-chip { transition: background-color .3s ease, border-color .3s ease, box-shadow .3s ease, color .3s ease; } @media (prefers-reduced-motion: no-preference) { .trace-step.s-running .icon { animation: trace-spin 1.6s linear infinite; } + .trace-step.s-running .trace-chip { animation: trace-pulse 1.1s ease-in-out infinite; } + .trace-step.s-passed .trace-chip { animation: trace-arrive-ok .55s ease-out 1; } + .trace-step.s-refused .trace-chip { animation: trace-arrive-stop .6s ease-out 1; } + .trace-step.s-failed .trace-chip { animation: trace-arrive-fail .6s ease-out 1; } + .trace-step.s-skipped .trace-chip { animation: trace-arrive-skip .45s ease-out 1; } @keyframes trace-spin { to { transform: rotate(360deg); } } + @keyframes trace-pulse { 0%, 100% { box-shadow: 0 0 0 0 var(--accent); } 50% { box-shadow: 0 0 0 4px transparent; transform: translateY(-1px); } } + @keyframes trace-arrive-ok { from { transform: scale(.96); box-shadow: 0 0 0 3px var(--green); } to { transform: none; box-shadow: none; } } + @keyframes trace-arrive-stop { 0% { transform: translateX(0); box-shadow: 0 0 0 3px var(--amber); } 30% { transform: translateX(-3px); } 60% { transform: translateX(3px); } 100% { transform: none; box-shadow: none; } } + @keyframes trace-arrive-fail { 0% { transform: translateX(0); box-shadow: 0 0 0 3px var(--red); } 30% { transform: translateX(-3px); } 60% { transform: translateX(3px); } 100% { transform: none; box-shadow: none; } } + @keyframes trace-arrive-skip { from { opacity: .3; } to { opacity: 1; } } } +.trace.replaying { outline: 1px dashed var(--accent); outline-offset: 4px; border-radius: var(--radius-control); } +.trace-replay-wrap { display: flex; flex-direction: column; gap: 8px; min-width: 0; } +.replay-banner { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; padding: 6px 10px; border-radius: var(--radius-control); background: var(--blue-bg); font-size: var(--text-secondary); } +.replay-banner .grow { flex-grow: 1; } +.replay-controls { font-size: var(--text-secondary); } .trace-pop { display: flex; flex-direction: column; gap: 8px; padding: 12px 14px; font-size: var(--text-secondary); background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-inner); box-shadow: var(--shadow); @@ -459,7 +487,9 @@ details.tech[open] > summary { margin-bottom: 6px; } .present-prompt .btn { font-size: 18px; min-height: 48px; } .present-response .response { flex: 1 1 auto; max-height: none; min-height: 100px; font-size: 19px; } .present-response .outcome { font-size: 30px; } -.present-response .run-facts { font-size: 16px; } +.present-response .run-facts { font-size: 14px; } +.present-response .presentation-facts { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 7px 16px; } +.present-response .run-summary { flex: 0 0 auto; } .present-trace .trace-name { font-size: 15px; } .present-trace .trace-meta, .present-trace .trace-dur { font-size: 13px; } @@ -520,7 +550,7 @@ details.tech[open] > summary { margin-bottom: 6px; } @media (max-width: 900px) { .shell { flex-direction: column; } .shell-nav { flex: none; border-right: 0; border-bottom: 1px solid var(--border); } - .page, .status-header, .pause-banner { padding-left: 16px; padding-right: 16px; } + .shell-main { --gutter: 16px; } .shell-nav { flex-direction: row; flex-wrap: wrap; padding: 8px; gap: 2px; } .shell-brand { padding: 0 8px 4px; flex-basis: 100%; } .nav-link.active::before { display: none; } @@ -559,7 +589,13 @@ details.tech[open] > summary { margin-bottom: 6px; } .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 220px), 1fr)); gap: 12px 16px; align-items: start; } .form-grid > *, .price-grid > * { min-width: 0; } -.form-grid > .field > label, .form-grid > .field > .field-label { min-height: 2.8em; display: flex; align-items: flex-end; } +/* Rows, not label heights: each field spans five shared rows (label · control · help · issues · extra) via subgrid, so the + controls of one visual row line up even when one label or help text wraps to several lines. */ +@supports (grid-template-rows: subgrid) { + .form-grid { row-gap: 6px; } + .form-grid > .field { display: grid; grid-template-rows: subgrid; grid-row: span 5; row-gap: 6px; margin-bottom: 10px; align-content: start; } + .form-grid > .field > label:first-child, .form-grid > .field > .field-label:first-child { align-self: end; } +} .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; } @@ -664,3 +700,21 @@ details[open] > summary::before { transform: rotate(45deg); } .present-trace .trace-steps { grid-template-columns: repeat(6, minmax(0, 1fr)); } } .present-response { overflow-y: auto; } + +/* ---- Demo examples (named, meaningful; fill only) ---- */ +.examples { display: flex; flex-direction: column; gap: 6px; min-width: 0; } +.example-bar { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 8px; } +.example-bar .field-label { white-space: nowrap; } +.example-summary { display: flex; flex-direction: column; gap: 4px; padding: 6px 10px; border-left: 3px solid var(--accent); background: var(--surface2); border-radius: 0 var(--radius-control) var(--radius-control) 0; } +.example-summary .facts { grid-template-columns: minmax(0, max-content) minmax(0, 1fr); margin-top: 6px; } +@media (max-width: 640px) { .example-bar { grid-template-columns: minmax(0, 1fr); } } +.missing-list li { color: var(--muted); overflow-wrap: anywhere; } +.sub-head .grow { flex-grow: 1; } + +/* ---- Route preview (Host dry run, before Run) ---- */ +.route-preview { display: flex; flex-direction: column; gap: 8px; } +.route-result { display: flex; flex-direction: column; gap: 4px; padding: 10px 12px; border: 1px solid var(--border); border-left: 4px solid var(--accent); border-radius: var(--radius-inner); background: var(--surface2); overflow-wrap: anywhere; } +.route-result.refused { border-left-color: var(--amber); } +.route-result.stale { opacity: .7; border-style: dashed; } +.workload-route { display: flex; flex-direction: column; gap: 8px; margin: 6px 0 4px; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--radius-inner); background: var(--bg); } +.inline-list > li { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; } diff --git a/tests/Covenant.Tests/ConsoleLogicTests.cs b/tests/Covenant.Tests/ConsoleLogicTests.cs index 8a019f8..2d7dff7 100644 --- a/tests/Covenant.Tests/ConsoleLogicTests.cs +++ b/tests/Covenant.Tests/ConsoleLogicTests.cs @@ -600,9 +600,9 @@ 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 + // The synthetic marker is the explicitly invalid SSN-shaped 000-12-3456, 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.Contains("000-12-3456", 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); diff --git a/tests/Covenant.Tests/DemoCheckpoint3Tests.cs b/tests/Covenant.Tests/DemoCheckpoint3Tests.cs new file mode 100644 index 0000000..922d563 --- /dev/null +++ b/tests/Covenant.Tests/DemoCheckpoint3Tests.cs @@ -0,0 +1,122 @@ +using Xunit; +using UiModels = Covenant.Ui.Models; +using UiLogic = Covenant.Ui.Logic; + +namespace Covenant.Tests; + +/// Browser-review corrections (docs/CONSOLE-DEMO-CLARITY-TASKS.md, checkpoint 3): no stale or mismatched search +/// readiness, tool cost shown apart from inference, short readable select labels, bounded authoritative search example. +public sealed class DemoCheckpoint3Tests +{ + private static UiModels.WebSearchStatusDto Ready(int version) => new() + { + KeyConfigured = true, EgressApproved = true, ModeAllowsSearch = true, Enabled = true, PriceConfigured = true, + ProfilesAllowed = ["public-research"], Ready = true, ConfigVersion = version, + }; + + [Fact] + public void Readiness_for_another_configuration_version_is_never_shown() + { + var (status, error, mismatch) = UiLogic.WebSourcesText.Reconcile(5, Ready(4), null); + Assert.Null(status); + Assert.True(mismatch); + Assert.Contains("v4", error, StringComparison.Ordinal); + Assert.Contains("v5", error, StringComparison.Ordinal); + + var same = UiLogic.WebSourcesText.Reconcile(5, Ready(5), null); + Assert.NotNull(same.Status); + Assert.False(same.Mismatch); + } + + [Fact] + public void A_failed_status_refresh_never_presents_an_old_ready() + { + var (status, error, mismatch) = UiLogic.WebSourcesText.Reconcile(5, null, "Web search status could not be loaded: timeout"); + Assert.Null(status); + Assert.False(mismatch); + Assert.Contains("timeout", error, StringComparison.Ordinal); + + // With no status the composer does not claim Ready; the runtime stays authoritative. + var readiness = UiLogic.WebSourcesText.Readiness(status, error, null, null, "public-research"); + Assert.False(readiness.Known); + Assert.Null(UiLogic.WebSourcesText.Reconcile(5, null, null).Status); + } + + private static UiModels.AuditEntryView SearchedLocalAnswer() + { + var r = new UiModels.AuditEntryView + { + SchemaVersion = 2, CostBasis = "reported", Effect = "Allow", + Attempts = [new() { AttemptId = "att_1", Outcome = "served", CostUsd = 0m, CostBasis = "zero_priced" }], + ToolCalls = [new() { ToolCallId = "tool_1", Tool = "web_search", Provider = "tavily", Outcome = "succeeded", CostUsd = 0.008m, CostBasis = "reported", Credits = 1 }], + }; + r.Usage.CostUsd = 0.008m; + return r; + } + + [Fact] + public void A_search_plus_local_answer_is_not_called_a_provider_charge() + { + var r = SearchedLocalAnswer(); + var text = UiLogic.CostText.Cost(r); + Assert.DoesNotContain("estimated provider charge", text, StringComparison.Ordinal); + Assert.Contains("web search $0.008 (credits × configured price)", text, StringComparison.Ordinal); + Assert.Contains("inference $0", text, StringComparison.Ordinal); + Assert.Contains("configured $0 local model", text, StringComparison.Ordinal); + Assert.Contains("incl. search", UiLogic.CostText.CostShort(r), StringComparison.Ordinal); + } + + [Fact] + public void A_record_without_tool_calls_keeps_its_existing_wording() + { + var r = SearchedLocalAnswer(); + r.ToolCalls = null; + r.Attempts![0].CostBasis = "reported"; + Assert.Null(UiLogic.CostText.Split(r)); + Assert.Contains("estimated provider charge", UiLogic.CostText.Cost(r), StringComparison.Ordinal); + } + + [Fact] + public void Application_options_are_short_names_with_the_reason_only() + { + var app = new UiModels.ApplicationSummaryDto { Id = "communications-assistant", DisplayName = "Communications", Team = "comms", Enabled = true, ConsoleTesting = true }; + Assert.Equal("Communications", new UiLogic.ApplicationChoice(app, true, null).Label); + var off = new UiModels.ApplicationSummaryDto { Id = "batch", Team = "data", Enabled = false }; + Assert.Equal("batch — disabled", new UiLogic.ApplicationChoice(off, false, "disabled").Label); + } + + [Fact] + public void The_composer_default_skips_an_exhausted_budget_demo_app_but_keeps_it_selectable() + { + UiModels.ApplicationSummaryDto App(string id, string team) => new() { Id = id, Team = team, Enabled = true, ConsoleTesting = true, GrantedProfiles = ["public-writing"] }; + var apps = new List { App("budget-demo", "budget-demo"), App("communications-assistant", "communications") }; + var budgets = new List + { + new() { Id = "global", Scope = "global", CapUsd = 25m, RemainingUsd = 24m, Enforcement = "hard" }, + new() { Id = "budget-demo", Scope = "application:budget-demo", CapUsd = 0.0001m, RemainingUsd = 0.0001m, Enforcement = "hard" }, + }; + + Assert.Equal("communications-assistant", UiLogic.ComposerRules.DefaultApplication(apps, budgets)!.Id); + Assert.Equal("budget-demo", UiLogic.ComposerRules.Applications(apps)[0].App.Id); // still listed, first + var form = new UiLogic.PlaygroundForm(); + Assert.True(UiLogic.ComposerRules.SelectApplication(form, apps, "budget-demo")); // explicit choice works + Assert.Equal("budget-demo", form.ApplicationId); + + // When it is the only usable application it is still the default; without budget facts, plain order applies. + Assert.Equal("budget-demo", UiLogic.ComposerRules.DefaultApplication([apps[0]], budgets)!.Id); + Assert.Equal("budget-demo", UiLogic.ComposerRules.DefaultApplication(apps, null)!.Id); + // A warn-only budget does not refuse, so it does not disqualify the default. + budgets[1].Enforcement = "warn-only"; + Assert.Equal("budget-demo", UiLogic.ComposerRules.DefaultApplication(apps, budgets)!.Id); + } + + [Fact] + public void Research_example_is_bounded_to_an_official_source_and_honest_about_verification() + { + var ex = UiLogic.DemoExamples.Find("public-research")!; + Assert.Contains("site:learn.microsoft.com", ex.Prompt, StringComparison.Ordinal); + Assert.Contains("not stated in the sources", ex.Prompt, StringComparison.Ordinal); + Assert.Contains("not independently verified", ex.Observe, StringComparison.Ordinal); + Assert.True(ex.Prompt.Length <= 300); // the Host bounds the search query to 300 characters + } +} diff --git a/tests/Covenant.Tests/DemoClarityTests.cs b/tests/Covenant.Tests/DemoClarityTests.cs new file mode 100644 index 0000000..36c073e --- /dev/null +++ b/tests/Covenant.Tests/DemoClarityTests.cs @@ -0,0 +1,364 @@ +using System.Text.Json; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; +using MEAI = Microsoft.Extensions.AI; +using UiModels = Covenant.Ui.Models; +using UiLogic = Covenant.Ui.Logic; + +namespace Covenant.Tests; + +/// Console demo clarity (docs/CONSOLE-DEMO-CLARITY-TASKS.md): examples resolved from the CURRENT configuration +/// (never silently downgraded, never tripped by another application's exhausted budget), one actionable search-readiness +/// cause, application identity, honest header environment, and evidence of the chosen policy and cache outcome. +public sealed class DemoClarityTests +{ + // ---------------------------------------------------------------- fixtures (console DTO shapes) + + private static UiModels.ConnectionDto Ollama() => new() + { + Id = "ollama", Kind = "Ollama", Boundary = "Local", Enabled = true, Endpoint = "http://127.0.0.1:11434/v1", + Models = + [ + new() { ModelId = UiLogic.DemoExamples.CoderModel, Price = new() { InputPer1M = 0m, OutputPer1M = 0m, Basis = "zero-marginal-local" } }, + new() { ModelId = UiLogic.DemoExamples.ResearchModel, MaxOutputTokens = 4096, Price = new() { InputPer1M = 0m, OutputPer1M = 0m, Basis = "zero-marginal-local" } }, + ], + }; + + private static UiModels.ConnectionDto Anthropic(bool enabled = true) => new() + { + Id = "anthropic", Kind = "Anthropic", Boundary = "Cloud", Enabled = enabled, SecretRef = "Anthropic:ApiKey", + Models = [new() { ModelId = "claude-test", Price = new() { InputPer1M = 1m, OutputPer1M = 5m, Basis = "provider-list" } }], + }; + + private static UiModels.PolicyDto P(string id, string[] classes, string[] profiles, params (string C, string M)[] targets) => new() + { + Id = id, Name = id, Enabled = true, Classifications = classes.ToList(), Profiles = profiles.ToList(), Strategy = "fixed", + Targets = targets.Select(t => new UiModels.PolicyTargetDto { ConnectionId = t.C, ModelId = t.M }).ToList(), + }; + + private static UiModels.CovenantConfigDto Demo(int cacheTtl = 0, bool anthropic = true) => new() + { + Version = 3, Mode = "hybrid", + Connections = [Ollama(), Anthropic(anthropic)], + Profiles = + [ + new() { Id = "public-research", Name = "Public research", Baseline = "Public", WebSearchAllowed = true }, + new() { Id = "public-writing", Name = "Public writing", Baseline = "Public" }, + new() { Id = "internal-coding", Name = "Internal coding", Baseline = "Internal" }, + new() { Id = "internal-research", Name = "Internal research", Baseline = "Internal" }, + ], + Applications = + [ + new() { Id = "demo-app", Team = "platform", Enabled = true, ConsoleTesting = true, MaxOutputTokens = 2048, + GrantedProfiles = ["public-research", "public-writing", "internal-coding", "internal-research"], DefaultProfile = "public-writing" }, + new() { Id = "aaa-budget-demo", Team = "budget-demo", Enabled = true, ConsoleTesting = true, + GrantedProfiles = ["public-research", "public-writing"], DefaultProfile = "public-writing" }, + ], + Policies = + [ + P("public", ["Public"], [], ("anthropic", "claude-test"), ("ollama", UiLogic.DemoExamples.CoderModel)), + P("internal-coding", ["Internal"], ["internal-coding"], ("ollama", UiLogic.DemoExamples.CoderModel)), + P("internal-research", ["Internal"], ["internal-research"], ("ollama", UiLogic.DemoExamples.ResearchModel)), + P("internal", ["Internal"], [], ("ollama", UiLogic.DemoExamples.CoderModel)), + P("sensitive", ["Pii", "Phi"], [], ("ollama", UiLogic.DemoExamples.CoderModel)), + ], + Budgets = [new() { Id = "global", Scope = "global", CapUsd = 100m, Enforcement = "hard" }], + Settings = new() { CacheTtlSeconds = cacheTtl }, + }; + + private static List Apps(UiModels.CovenantConfigDto cfg) => cfg.Applications.Select(a => new UiModels.ApplicationSummaryDto + { + Id = a.Id, Team = a.Team, Enabled = a.Enabled, ConsoleTesting = a.ConsoleTesting, GrantedProfiles = a.GrantedProfiles.ToList(), + DefaultProfile = a.DefaultProfile, DisplayName = a.DisplayName, + Budgets = cfg.Budgets.Where(b => b.Scope == "global" || b.Scope == "team:" + a.Team || b.Scope == "application:" + a.Id).Select(b => b.Id).ToList(), + }).ToList(); + + private static List Budgets(bool budgetDemoExhausted) => + [ + new() { Id = "global", Scope = "global", CapUsd = 100m, RemainingUsd = 99m, Enforcement = "hard" }, + new() { Id = "budget-demo", Scope = "application:aaa-budget-demo", CapUsd = 0.0001m, RemainingUsd = budgetDemoExhausted ? 0m : 0.0001m, Enforcement = "hard" }, + ]; + + private static UiModels.WebSearchStatusDto SearchReady() => new() + { + KeyConfigured = true, EgressApproved = true, ModeAllowsSearch = true, Enabled = true, PriceConfigured = true, + PricePerCreditUsd = 0.008m, ProfilesAllowed = ["public-research"], Ready = true, + }; + + private static UiLogic.ExampleResolution Resolve(string id, UiModels.CovenantConfigDto cfg, bool exhausted = true, UiModels.WebSearchStatusDto? search = null) + => UiLogic.DemoExamples.Resolve(UiLogic.DemoExamples.Find(id)!, cfg, Apps(cfg), Budgets(exhausted), search ?? SearchReady()); + + // ---------------------------------------------------------------- examples + + [Fact] + public void Each_example_resolves_to_the_workload_and_route_it_claims() + { + var cfg = Demo(cacheTtl: 60); + var research = Resolve("public-research", cfg); + Assert.True(research.Ready); + Assert.Equal("public-research", research.ProfileId); + + var writing = Resolve("public-writing", cfg); + Assert.True(writing.Ready); + Assert.Equal("public-writing", writing.ProfileId); + Assert.StartsWith("anthropic/claude-test", writing.ConfiguredRoute, StringComparison.Ordinal); + + var coding = Resolve("internal-coding", cfg); + Assert.Equal("internal-coding", coding.ProfileId); + Assert.StartsWith("ollama/" + UiLogic.DemoExamples.CoderModel, coding.ConfiguredRoute, StringComparison.Ordinal); + Assert.Contains("policy internal-coding", coding.ConfiguredRoute, StringComparison.Ordinal); // scoped rule, not the broad one + + var deep = Resolve("internal-research", cfg); + Assert.Equal("internal-research", deep.ProfileId); + Assert.StartsWith("ollama/" + UiLogic.DemoExamples.ResearchModel, deep.ConfiguredRoute, StringComparison.Ordinal); + + var refusal = Resolve("sensitive-refusal", cfg); + Assert.True(refusal.Ready); + Assert.Equal("anthropic/claude-test", refusal.ModelPin); + Assert.Contains("refused", refusal.ConfiguredRoute, StringComparison.Ordinal); + + Assert.True(Resolve("cache-repeat", cfg).Ready); + } + + [Fact] + public void An_exhausted_low_budget_demo_application_never_captures_ordinary_examples() + { + // "aaa-budget-demo" sorts first and is granted the Public profiles; its own budget is exhausted. + var cfg = Demo(cacheTtl: 60); + foreach (var ex in UiLogic.DemoExamples.All.Where(e => e.Need != UiLogic.ExampleNeed.BudgetRefusal)) + { + var r = UiLogic.DemoExamples.Resolve(ex, cfg, Apps(cfg), Budgets(budgetDemoExhausted: true), SearchReady()); + if (r.Ready) Assert.True(r.ApplicationId == "demo-app", $"{ex.Id} picked {r.ApplicationId}"); + } + var budget = Resolve("budget-refusal", cfg); + Assert.True(budget.Ready); + Assert.Equal("aaa-budget-demo", budget.ApplicationId); + } + + [Fact] + public void Missing_prerequisites_are_named_with_a_link_and_never_downgraded() + { + var cfg = Demo(cacheTtl: 0, anthropic: false); + var cache = Resolve("cache-repeat", cfg); + Assert.False(cache.Ready); + Assert.Contains(cache.Missing, m => m.Text.Contains("cache is disabled", StringComparison.Ordinal) && m.Href == "settings#op-h"); + + var writing = Resolve("public-writing", cfg); + Assert.False(writing.Ready); // never falls back to a local "writing" route + Assert.Contains(writing.Missing, m => m.Href == "connections"); + + var notReady = UiLogic.DemoExamples.Resolve(UiLogic.DemoExamples.Find("public-research")!, cfg, Apps(cfg), Budgets(true), + new UiModels.WebSearchStatusDto { KeyConfigured = false, Setup = ["Set Tavily:ApiKey"] }); + Assert.False(notReady.Ready); + Assert.Contains(notReady.Missing, m => m.Href == "settings#ws-h"); + + var budget = Resolve("budget-refusal", cfg, exhausted: false); + Assert.False(budget.Ready); + Assert.Contains(budget.Missing, m => m.Href == "budgets"); + } + + [Fact] + public void Research_example_states_the_enforced_output_bound_honestly() + { + var cfg = Demo(); + var r = Resolve("internal-research", cfg); + Assert.Contains("2048 requested", r.OutputNote, StringComparison.Ordinal); + Assert.Contains("→ 2048 enforced", r.OutputNote, StringComparison.Ordinal); + + cfg.Applications[0].MaxOutputTokens = 1024; + var capped = Resolve("internal-research", cfg); + Assert.Contains("→ 1024 enforced", capped.OutputNote, StringComparison.Ordinal); + Assert.Contains("cut short", capped.OutputNote, StringComparison.Ordinal); + Assert.DoesNotContain("Slower", UiLogic.DemoExamples.Find("internal-research")!.Expected, StringComparison.Ordinal); + } + + [Fact] + public void Applying_an_example_fills_the_form_without_running_and_labels_the_snapshot() + { + var cfg = Demo(); + var r = Resolve("sensitive-refusal", cfg); + var form = new UiLogic.PlaygroundForm(); + Assert.True(UiLogic.DemoExamples.ApplyTo(r, form)); + Assert.Equal("demo-app", form.ApplicationId); + Assert.Equal(UiLogic.RouteMode.Catalog, form.Mode); + Assert.Equal("anthropic/claude-test", form.RequestedModel); + Assert.Contains("000-12-3456", form.Prompt, StringComparison.Ordinal); + Assert.Equal("Example · " + r.Example.Title, UiLogic.RequestSnapshot.Freeze(1, form, DateTimeOffset.UnixEpoch).ScenarioLabel); + form.Prompt += " edited"; + Assert.Equal("Custom", UiLogic.RequestSnapshot.Freeze(2, form, DateTimeOffset.UnixEpoch).ScenarioLabel); + + var notReady = UiLogic.DemoExamples.Resolve(UiLogic.DemoExamples.Find("cache-repeat")!, Demo(cacheTtl: 0), Apps(Demo()), null, null); + Assert.False(UiLogic.DemoExamples.ApplyTo(notReady, new UiLogic.PlaygroundForm())); + } + + [Fact] + public void The_synthetic_marker_is_explicitly_invalid_and_still_escalates_to_pii() + { + var prompt = UiLogic.DemoExamples.Find("sensitive-refusal")!.Prompt; + Assert.Contains("000-12-3456", prompt, StringComparison.Ordinal); + Assert.DoesNotContain("078-05-1120", prompt, StringComparison.Ordinal); + var result = new RegexDataClassifier().Classify(new InferenceRequest("t", [new ChatMessage(ChatRole.User, prompt)], null, AttributionTags.Unattributed)); + Assert.Equal(DataClassification.Pii, result.Classification); + } + + [Fact] + public void Ui_route_mirror_prefers_the_profile_scoped_rule_and_reports_ambiguity() + { + var cfg = Demo(); + Assert.Equal("internal-coding", UiLogic.DemoExamples.Route(cfg, "Internal", "internal-coding").Policy!.Id); + Assert.Equal("internal", UiLogic.DemoExamples.Route(cfg, "Internal", "some-other").Policy!.Id); + cfg.Policies.Add(P("dup", ["Internal"], ["internal-coding"], ("ollama", UiLogic.DemoExamples.CoderModel))); + Assert.Contains("ambiguous", UiLogic.DemoExamples.Route(cfg, "Internal", "internal-coding").Refusal, StringComparison.Ordinal); + Assert.Contains("never routed to cloud", UiLogic.DemoExamples.Ineligible(cfg, new() { ConnectionId = "anthropic", ModelId = "claude-test" }, "Pii"), StringComparison.Ordinal); + } + + // ---------------------------------------------------------------- search readiness + + [Theory] + [InlineData("key", "Tavily API key", "settings#ws-h")] + [InlineData("egress", "egress allow-list", "settings#ws-h")] + [InlineData("local", "Local-only", "policies")] + [InlineData("disabled", "disabled", "settings#ws-h")] + [InlineData("price", "price", "settings#ws-h")] + public void Search_readiness_gives_one_specific_cause_with_its_fix(string gap, string fragment, string href) + { + var s = SearchReady(); + s.Ready = false; + switch (gap) + { + case "key": s.KeyConfigured = false; s.Enabled = false; break; // several gaps: the most fundamental one only + case "egress": s.EgressApproved = false; break; + case "local": s.ModeAllowsSearch = false; break; + case "disabled": s.Enabled = false; break; + case "price": s.PriceConfigured = false; break; + } + var cfg = Demo(); + var r = UiLogic.WebSourcesText.Readiness(s, null, cfg, Apps(cfg)[0], "public-research"); + Assert.False(r.Possible); + Assert.True(r.Known); + Assert.Contains(fragment, r.Cause, StringComparison.Ordinal); + Assert.Equal(href, r.Href); + } + + [Fact] + public void A_denied_profile_offers_an_explicit_switch_never_an_automatic_one() + { + var cfg = Demo(); + var app = Apps(cfg)[0]; + var r = UiLogic.WebSourcesText.Readiness(SearchReady(), null, cfg, app, "public-writing"); + Assert.False(r.Possible); + Assert.Equal("public-research", r.SwitchToProfile); + + var ok = UiLogic.WebSourcesText.Readiness(SearchReady(), null, cfg, app, "public-research"); + Assert.True(ok.Possible); + + var unknown = UiLogic.WebSourcesText.Readiness(null, "status endpoint missing", cfg, app, "public-research"); + Assert.True(unknown.Possible); // runtime stays authoritative + Assert.False(unknown.Known); + } + + [Theory] + [InlineData("location_required", UiLogic.SearchProblemKind.MissingLocation)] + [InlineData("search_not_permitted", UiLogic.SearchProblemKind.Setup)] + [InlineData("search_sensitive", UiLogic.SearchProblemKind.PolicyRefusal)] + [InlineData("search_timeout", UiLogic.SearchProblemKind.ProviderFailure)] + [InlineData("search_empty", UiLogic.SearchProblemKind.ProviderFailure)] + [InlineData(null, UiLogic.SearchProblemKind.None)] + public void Search_outcomes_are_classified_by_kind(string? code, UiLogic.SearchProblemKind kind) + => Assert.Equal(kind, UiLogic.WebSourcesText.Kind(code)); + + // ---------------------------------------------------------------- applications + + [Fact] + public void A_new_application_is_validated_and_round_trips_with_display_name_through_the_host() + { + // Start from a real Host configuration as the console reads it. + var cfg = JsonSerializer.Deserialize(JsonSerializer.Serialize(V2.Hybrid(), ConfigJsonContext.Default.CovenantConfig), UiModels.UiJsonContext.Default.CovenantConfigDto)!; + var bad = new UiLogic.NewApplicationForm { Id = "demo-app", Team = "" }; + Assert.Equal(2, UiLogic.ProfileEditing.Problems(bad, cfg).Count); // duplicate id + missing team + + var form = new UiLogic.NewApplicationForm + { + Id = "support-portal", DisplayName = "Support portal", Team = "support", Description = "Answers customer questions", + GrantedProfiles = ["public-demo"], DefaultProfile = "public-demo", + }; + Assert.Empty(UiLogic.ProfileEditing.AddApplication(cfg, form)); + var added = cfg.Applications.Single(a => a.Id == "support-portal"); + Assert.True(added.Enabled); + Assert.Equal("Support portal", UiLogic.ProfileEditing.ApplicationName(added.Id, added.DisplayName)); + + var json = JsonSerializer.Serialize(cfg, UiModels.UiJsonContext.Default.CovenantConfigDto); + var host = JsonSerializer.Deserialize(json, ConfigJsonContext.Default.CovenantConfig)!; + var app = host.Applications.Single(a => a.Id == "support-portal"); + Assert.Equal("Support portal", app.DisplayName); + Assert.True(ConfigValidator.Validate(host, V2.Env()).IsValid); // the console's new application passes Host validation + Assert.Equal("Answers customer questions", app.Description); + var back = JsonSerializer.Deserialize(JsonSerializer.Serialize(host, ConfigJsonContext.Default.CovenantConfig), UiModels.UiJsonContext.Default.CovenantConfigDto)!; + Assert.Equal("Support portal", back.Applications.Single(a => a.Id == "support-portal").DisplayName); + + // A configuration written before display names existed still loads (null = show the id). + var legacy = JsonSerializer.Deserialize(JsonSerializer.Serialize(V2.Hybrid(), ConfigJsonContext.Default.CovenantConfig), ConfigJsonContext.Default.CovenantConfig)!; + Assert.All(legacy.Applications, a => Assert.Null(a.DisplayName)); + Assert.True(ConfigValidator.Validate(legacy, V2.Env()).IsValid); + var tooLong = V2.Hybrid(tweak: c => c with { Applications = c.Applications.Select(a => a with { DisplayName = new string('x', 101) }).ToList() }); + Assert.Contains(ConfigValidator.Validate(tooLong, V2.Env()).Errors, e => e.Path.EndsWith(".display_name", StringComparison.Ordinal)); + } + + [Fact] + public void Single_selectable_application_is_identified_as_the_only_choice() + { + var cfg = Demo(); + var apps = Apps(cfg); + apps[1].ConsoleTesting = false; + Assert.Equal("demo-app", UiLogic.ComposerRules.OnlySelectable(apps)!.Id); + apps[1].ConsoleTesting = true; + Assert.Null(UiLogic.ComposerRules.OnlySelectable(apps)); + Assert.Equal("Team platform pays · budgets global", UiLogic.ComposerRules.PayerText(apps[0])); + } + + [Theory] + [InlineData("demo-local-only", "Demo instance")] + [InlineData("demo-hybrid", "Demo instance")] + [InlineData("local-demo-5210", "local-demo-5210")] + [InlineData(null, "Environment not reported")] + public void Header_environment_never_poses_as_the_routing_mode(string? env, string label) + { + var v = UiLogic.ShellStatus.Environment(env, 3, "1.2.3", null); + Assert.Equal(label, v.Label); + Assert.Contains("Active configuration: v3", v.Details, StringComparison.Ordinal); + Assert.Equal("Hybrid · v3", UiLogic.ShellStatus.ModeWithVersion("hybrid", 3)); + } + + // ---------------------------------------------------------------- evidence: policy + cache outcome + + private static readonly IReadOnlyDictionary Clients = new Dictionary + { + [$"openai:{V2.CloudModel}"] = new StubChatClient("cloud"), + [$"ollama:{V2.LocalTag}"] = new StubChatClient("local"), + }; + + [Fact] + public async Task Evidence_names_the_policy_and_the_exact_cache_outcome() + { + var off = V2Rig.Build(V2.Hybrid(), Clients); + var (ctx, e) = await off.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal("public", e.PolicyId); + Assert.Equal(CacheOutcomes.Disabled, e.CacheOutcome); + Assert.Contains(ctx.TraceEvents, t => t.Stage == "cache" && t.State == TraceStates.Skipped && t.ReasonCode == TraceReasons.CacheDisabled); + + var on = V2Rig.Build(V2.Hybrid(tweak: c => c with { Settings = c.Settings with { CacheTtlSeconds = 60 } }), Clients, cache: new ResponseCache()); + var (miss, me) = await on.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal(CacheOutcomes.Miss, me.CacheOutcome); + Assert.Contains(miss.TraceEvents, t => t.Stage == "cache" && t.State == TraceStates.Passed && t.ReasonCode == TraceReasons.CacheMiss); + var (_, he) = await on.RunAsync(V2Rig.PublicPrompt, profile: "public-demo"); + Assert.Equal(CacheOutcomes.Hit, he.CacheOutcome); + Assert.True(he.CacheHit); + + // A refusal before the cache stage still records who asked; the cache was never reached. + var (_, refused) = await off.RunAsync(V2Rig.PublicPrompt, profile: "no-such-profile"); + Assert.Equal(CacheOutcomes.NotReached, refused.CacheOutcome); + Assert.Equal("demo-app", refused.ApplicationId); + } +} diff --git a/tests/Covenant.Tests/DemoTraceAndSetupTests.cs b/tests/Covenant.Tests/DemoTraceAndSetupTests.cs new file mode 100644 index 0000000..17becd5 --- /dev/null +++ b/tests/Covenant.Tests/DemoTraceAndSetupTests.cs @@ -0,0 +1,230 @@ +using System.Text.Json; +using Covenant.Core; +using Covenant.Governance; +using Covenant.Host; +using Xunit; +using UiModels = Covenant.Ui.Models; +using UiLogic = Covenant.Ui.Logic; + +namespace Covenant.Tests; + +/// Demo clarity §6–§8: honest durations and stage wording, cost ownership before/after execution, recorded-trace +/// replay that never invents data, and the additive workload-route setup. +public sealed class DemoTraceAndSetupTests +{ + // ---------------------------------------------------------------- §6 durations and wording + + [Theory] + [InlineData(0.04, "<1 ms")] + [InlineData(0.999, "<1 ms")] + [InlineData(0.0, "0 ms")] + [InlineData(1.4, "1 ms")] + [InlineData(812.0, "812 ms")] + [InlineData(1534.0, "1.53 s")] + public void Durations_never_round_a_positive_value_to_zero(double ms, string text) + => Assert.Equal(text, UiLogic.TraceModel.DurationText(ms)); + + [Fact] + public void Unknown_duration_stays_unknown() + { + Assert.Null(UiLogic.TraceModel.DurationText(null)); + Assert.Null(UiLogic.TraceModel.DurationText(-1)); + Assert.Null(UiLogic.TraceModel.DurationText(double.NaN)); + } + + private static UiLogic.TraceStepView Step(string stage, UiLogic.TraceStepState state, string? reason = null) + => new(stage, UiLogic.TraceModel.Label(stage), state, 0.3, reason, null, null, []); + + [Fact] + public void Stage_labels_describe_what_happens_before_and_after_the_call() + { + Assert.Equal("Identify caller", UiLogic.TraceModel.Label("auth")); + Assert.Equal("Finalize cost", UiLogic.TraceModel.Label("attribution")); + Assert.Contains("BEFORE", UiLogic.TraceModel.Explain("auth"), StringComparison.Ordinal); + Assert.Contains("AFTER", UiLogic.TraceModel.Explain("attribution"), StringComparison.Ordinal); + + var skippedCost = Step("attribution", UiLogic.TraceStepState.Skipped, "not_reached"); + Assert.Equal("No usage", UiLogic.TraceModel.OutcomeText(skippedCost)); + Assert.DoesNotContain("Skipped", UiLogic.TraceModel.OutcomeText(skippedCost), StringComparison.Ordinal); + Assert.Contains("still recorded with its application, team and workload", UiLogic.TraceModel.OutcomeNote(skippedCost), StringComparison.Ordinal); + } + + [Theory] + [InlineData(UiLogic.TraceStepState.Passed, "cache_hit", "Hit")] + [InlineData(UiLogic.TraceStepState.Passed, "cache_miss", "Miss")] + [InlineData(UiLogic.TraceStepState.Skipped, "cache_disabled", "Off")] + [InlineData(UiLogic.TraceStepState.Skipped, "web_search_bypass", "Bypassed")] + public void Cache_chip_states_the_outcome_not_a_bare_passed(UiLogic.TraceStepState state, string reason, string text) + => Assert.Equal(text, UiLogic.TraceModel.OutcomeText(Step("cache", state, reason))); + + // ---------------------------------------------------------------- §6 ownership + + private static UiModels.AuditEntryView Record(Action? tweak = null) + { + var r = new UiModels.AuditEntryView + { + Id = "req_1", SchemaVersion = 2, ApplicationId = "demo-app", ProfileId = "public-writing", PolicyId = "public-writing", + ConfigVersion = 3, Effect = "Allow", CostBasis = "reported", Attempts = [new() { AttemptId = "att_1", Outcome = "served", CostUsd = 0.0004m, CostBasis = "reported" }], + ReservedUsd = 0.002m, SettledUsd = 0.0004m, CacheOutcome = "miss", + }; + r.Tags.Team = "platform"; + r.Usage.CostUsd = 0.0004m; + tweak?.Invoke(r); + return r; + } + + [Fact] + public void Ownership_is_assigned_before_and_finalized_after() + { + var r = Record(); + Assert.Equal("application demo-app · team platform · workload public-writing · policy public-writing · config v3", UiLogic.Ownership.Assigned(r)); + Assert.Contains("reserved", UiLogic.Ownership.Finalized(r), StringComparison.Ordinal); + Assert.StartsWith("Miss", UiLogic.Ownership.Cache(r), StringComparison.Ordinal); + } + + [Fact] + public void A_refusal_is_attributed_but_not_charged() + { + var r = Record(x => + { + x.Effect = "Deny"; x.StoppedAtStage = "budget"; x.Attempts = []; x.CostBasis = "no_call"; x.ReservedUsd = null; x.SettledUsd = null; + x.Usage.CostUsd = 0m; x.CacheOutcome = "disabled"; + }); + Assert.Contains("team platform", UiLogic.Ownership.Assigned(r), StringComparison.Ordinal); + var charged = UiLogic.Ownership.Finalized(r); + Assert.Contains("No charge", charged, StringComparison.Ordinal); + Assert.Contains("refused at Budget", charged, StringComparison.Ordinal); + Assert.Contains("recorded with its application, team and workload", charged, StringComparison.Ordinal); + } + + [Fact] + public void A_failed_search_charge_is_shown_as_the_tool_charge_it_is() + { + var r = Record(x => + { + x.Effect = "Deny"; x.StoppedAtStage = "search"; x.Attempts = []; x.CostBasis = "estimated_failed_call"; x.Usage.CostUsd = 0.008m; + x.ToolCalls = [new() { ToolCallId = "tool_1", Tool = "web_search", Provider = "tavily", Outcome = "failed", CostUsd = 0.008m, CostBasis = "estimated_failed_call" }]; + x.ReservedUsd = 0.012m; x.SettledUsd = 0.008m; x.CacheOutcome = "bypass_web_search"; + }); + var charged = UiLogic.Ownership.Finalized(r); + Assert.Contains("web-search charge", charged, StringComparison.Ordinal); + Assert.Contains("1 tool call (web_search)", charged, StringComparison.Ordinal); + Assert.StartsWith("Bypassed", UiLogic.Ownership.Cache(r), StringComparison.Ordinal); + } + + [Fact] + public void A_cache_hit_costs_nothing_and_says_why() + => Assert.Contains("exact cache", UiLogic.Ownership.Finalized(Record(x => { x.CacheHit = true; x.CacheOutcome = "hit"; x.Attempts = []; })), StringComparison.Ordinal); + + // ---------------------------------------------------------------- §7 replay + + private static UiModels.TraceEventDto E(long seq, string stage, string state, double? ms = null, string? reason = null) + => new() { Seq = seq, Stage = stage, State = state, DurationMs = ms, ReasonCode = reason }; + + [Fact] + public void Replay_reveals_the_recorded_events_and_ends_on_the_recorded_trace() + { + var live = new List + { + E(1, "auth", "running"), E(2, "auth", "passed", 0.2), E(3, "policy", "running"), E(4, "policy", "refused", 0.5, "governance_denied"), + }; + var script = UiLogic.TraceReplay.Script(live.AsEnumerable().Reverse().Append(live[0])); // any order, duplicates + Assert.Equal(live.Select(e => e.Seq), script.Select(e => e.Seq)); // live events unchanged + + var first = UiLogic.TraceReplay.Frame(script, 1, 3); + Assert.Equal(UiLogic.TraceStepState.Running, first.Steps.Single(s => s.Stage == "auth").State); + Assert.Equal(UiLogic.TraceStepState.Pending, first.Steps.Single(s => s.Stage == "policy").State); + Assert.False(first.Complete); + + var last = UiLogic.TraceReplay.Frame(script, script.Count, 3); + var recorded = UiLogic.TraceModel.Reduce(live, complete: true, 3); + Assert.True(last.Complete); + foreach (var stage in UiLogic.TraceModel.Stages) + { + var a = last.Steps.Single(s => s.Stage == stage); + var b = recorded.Steps.Single(s => s.Stage == stage); + Assert.Equal(b.State, a.State); + Assert.Equal(b.DurationMs, a.DurationMs); // recorded durations, never synthetic + Assert.Equal(b.ReasonCode, a.ReasonCode); + } + } + + [Fact] + public void Replay_of_an_audit_summary_adds_running_reveals_without_durations() + { + var summary = new List + { + new() { Stage = "auth", State = "passed", DurationMs = 0.3 }, + new() { Stage = "cache", State = "passed", DurationMs = 0.1, ReasonCode = "cache_hit" }, + }; + var script = UiLogic.TraceReplay.Script(UiLogic.TraceModel.EventsFromAuditSummary(summary)); + Assert.Equal(["running", "passed", "running", "passed"], script.Select(e => e.State).ToArray()); + Assert.All(script.Where(e => e.State == "running"), e => Assert.Null(e.DurationMs)); + var final = UiLogic.TraceReplay.Frame(script, script.Count, null); + Assert.Equal(0.1, final.Steps.Single(s => s.Stage == "cache").DurationMs); + Assert.Equal("cache_hit", final.Steps.Single(s => s.Stage == "cache").ReasonCode); + } + + [Fact] + public void Replay_pacing_is_bounded() + { + Assert.Equal(1300, UiLogic.TraceReplay.DelayMs(0.5)); + Assert.Equal(650, UiLogic.TraceReplay.DelayMs(1)); + Assert.Equal(UiLogic.TraceReplay.DelayMs(4), UiLogic.TraceReplay.DelayMs(100)); + Assert.Equal(UiLogic.TraceReplay.DelayMs(0.25), UiLogic.TraceReplay.DelayMs(0)); + } + + // ---------------------------------------------------------------- §8 workload route setup (additive) + + private static UiModels.CovenantConfigDto UiConfig(Func? tweak = null) + => JsonSerializer.Deserialize(JsonSerializer.Serialize(V2.Hybrid(tweak: tweak), ConfigJsonContext.Default.CovenantConfig), UiModels.UiJsonContext.Default.CovenantConfigDto)!; + + private static UiLogic.WorkloadPreset Preset(string id) => UiLogic.WorkloadRouteSetup.Presets.Single(p => p.ProfileId == id); + + [Fact] + public void Routing_a_workload_is_additive_unambiguous_and_passes_host_validation() + { + var draft = UiConfig(); + var before = UiLogic.ConfigCopy.Deep(draft); + var plan = UiLogic.WorkloadRouteSetup.ApplyTo(draft, Preset("internal-coding"), "ollama", V2.LocalTag); + Assert.True(plan.Ok, plan.Problem); + + // Nothing that existed was modified or removed. + foreach (var p in before.Policies) + Assert.Equal(UiLogic.ConfigCopy.Canonical(p), UiLogic.ConfigCopy.Canonical(draft.Policies.Single(x => x.Id == p.Id))); + Assert.All(before.Applications, a => Assert.All(a.GrantedProfiles, g => Assert.Contains(g, draft.Applications.Single(x => x.Id == a.Id).GrantedProfiles))); + Assert.Equal(before.Connections.Count, draft.Connections.Count); + + var host = JsonSerializer.Deserialize(JsonSerializer.Serialize(draft, UiModels.UiJsonContext.Default.CovenantConfigDto), ConfigJsonContext.Default.CovenantConfig)!; + Assert.True(ConfigValidator.Validate(host, V2.Env()).IsValid, string.Join("; ", ConfigValidator.Validate(host, V2.Env()).Errors.Select(e => e.Code + " " + e.Message))); + var snap = new RuntimeSnapshot(host); + var coding = PolicyEngineV2.Evaluate(snap, DataClassification.Internal, "internal-coding", null, []); + Assert.Equal(PolicyEffect.Allow, coding.Effect); + Assert.Equal("internal-coding", coding.PolicyId); + Assert.Equal("internal", PolicyEngineV2.Evaluate(snap, DataClassification.Internal, "internal-default", null, []).PolicyId); // others unchanged + Assert.Equal("sensitive", PolicyEngineV2.Evaluate(snap, DataClassification.Pii, "internal-coding", null, []).PolicyId); // PII keeps its local rule + + var again = UiLogic.WorkloadRouteSetup.Plan(draft, Preset("internal-coding"), "ollama", V2.LocalTag); + Assert.False(again.Ok); // never a second, ambiguous rule + Assert.Contains("already routed by policy", again.Problem, StringComparison.Ordinal); + } + + [Fact] + public void Cloud_routes_are_public_only_priced_only_and_hybrid_only() + { + var cfg = UiConfig(); + var internalOnCloud = UiLogic.WorkloadRouteSetup.Plan(cfg, Preset("internal-research"), "openai", V2.CloudModel); + Assert.Contains("never routes to a cloud model", internalOnCloud.Problem, StringComparison.Ordinal); + Assert.DoesNotContain(UiLogic.WorkloadRouteSetup.PresetsFor(cfg.Connections.Single(c => c.Id == "openai")), p => p.Baseline != "Public"); + + var unpriced = UiConfig(c => c with { Connections = [V2.Ollama(), V2.OpenAi(priced: false)] }); + Assert.Contains("never $0", UiLogic.WorkloadRouteSetup.Plan(unpriced, Preset("public-writing"), "openai", V2.CloudModel).Problem, StringComparison.Ordinal); + + cfg.Mode = "local-only"; + Assert.Contains("Local-only", UiLogic.WorkloadRouteSetup.Plan(cfg, Preset("public-writing"), "openai", V2.CloudModel).Problem, StringComparison.Ordinal); + + var ok = UiLogic.WorkloadRouteSetup.Plan(UiConfig(), Preset("public-writing"), "openai", V2.CloudModel); + Assert.True(ok.Ok); + Assert.Contains(ok.Changes, c => c.Contains("(cloud, priced)", StringComparison.Ordinal)); + } +} diff --git a/tests/Covenant.Tests/FallbackTests.cs b/tests/Covenant.Tests/FallbackTests.cs index c4f3e70..512de4f 100644 --- a/tests/Covenant.Tests/FallbackTests.cs +++ b/tests/Covenant.Tests/FallbackTests.cs @@ -258,7 +258,7 @@ public async Task Sensitive_request_whose_local_primary_fails_never_reaches_a_cl 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"); + var (ctx, e) = await rig.RunAsync("Customer SSN 000-12-3456 needs a summary.", profile: "public-demo"); Assert.Equal(DataClassification.Pii, e.Classification); Assert.Equal(DenialKind.UpstreamFailure, ctx.DenialKind); diff --git a/tests/Covenant.Tests/TraceTests.cs b/tests/Covenant.Tests/TraceTests.cs index 2f96d39..de0d325 100644 --- a/tests/Covenant.Tests/TraceTests.cs +++ b/tests/Covenant.Tests/TraceTests.cs @@ -71,7 +71,9 @@ public async Task Subscribing_after_completion_replays_every_event_then_ends() { 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(stage == "search" ? "skipped" : "passed", terminal.Data.GetProperty("state").GetString()); + // The demo seed disables the exact cache (TTL 0): the cache stage reports "skipped · cache_disabled", never a + // Passed that would imply a lookup happened. Web search is off on this request. + Assert.Equal(stage is "search" or "cache" ? "skipped" : "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 _)); @@ -90,7 +92,9 @@ public async Task Subscribing_after_completion_replays_every_event_then_ends() // Durable compact summary in the audit record. var audit = await CorrelationTestKit.LookupAsync(_client, id); Assert.NotNull(audit.Trace); - Assert.All(Stages.Where(s => s is not ("provider" or "search")), s => Assert.Contains(audit.Trace!, t => t.Stage == s && t.State == "passed")); + Assert.All(Stages.Where(s => s is not ("provider" or "search" or "cache")), s => Assert.Contains(audit.Trace!, t => t.Stage == s && t.State == "passed")); + Assert.Contains(audit.Trace!, t => t.Stage == "cache" && t.State == "skipped" && t.ReasonCode == "cache_disabled"); + Assert.Equal("disabled", audit.CacheOutcome); Assert.Contains(audit.Trace!, t => t.Stage == "provider" && t.AttemptId == "att_1" && t.State == "passed"); Assert.Contains(audit.Trace!, t => t.Stage == "search" && t.State == "skipped" && t.ReasonCode == "search_off"); } diff --git a/tests/Covenant.Tests/WebSearchTests.cs b/tests/Covenant.Tests/WebSearchTests.cs index 052e324..b1b20b1 100644 --- a/tests/Covenant.Tests/WebSearchTests.cs +++ b/tests/Covenant.Tests/WebSearchTests.cs @@ -282,8 +282,8 @@ public async Task An_explicit_location_field_satisfies_the_weather_rule() { "disabled", Weather, null, TraceReasons.SearchNotPermitted }, { "local-only", Weather, null, TraceReasons.SearchNotPermitted }, { "internal-profile", Weather, null, TraceReasons.SearchNotPermitted }, - { "pii-in-request", "What's the weather in Toronto today for 078-05-1120?", null, TraceReasons.SearchSensitive }, - { "pii-in-location", "What's the weather today?", "078-05-1120", TraceReasons.SearchSensitive }, + { "pii-in-request", "What's the weather in Toronto today for 000-12-3456?", null, TraceReasons.SearchSensitive }, + { "pii-in-location", "What's the weather today?", "000-12-3456", TraceReasons.SearchSensitive }, { "unknown-price", Weather, null, TraceReasons.SearchNotPermitted }, { "missing-key", Weather, null, TraceReasons.SearchNotPermitted }, };