Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ An in-perimeter **AI inference governance and FinOps control plane** for regulat

Research artifact: can inference governance be an architecturally separable control layer — enforceably, evidentially, and at acceptable cost?

**Start here:** [Console usage guide](docs/console-quickstart.md) · [Tavily setup](docs/web-search.md)

## At a glance

![Covenant overview](docs/diagrams/covenant-overview.svg)
Expand All @@ -21,7 +23,7 @@ Editable sources: [`docs/diagrams/*.drawio`](docs/diagrams/) (open in [diagrams.
1. **Fail-closed.** No policy match → deny. Unclassified defaults to the most restrictive class. Misconfiguration → the appliance refuses to start. PII/PHI never reaches a public provider because no public route exists for those classifications.
2. **Governance is the pipeline, not a bolt-on.** Every capability — classification, policy, budgets, attribution, audit — is an ordered stage in one middleware chain. Nothing bypasses it.
3. **Everything is evidence.** Each request, allowed or denied, appends exactly one hash-chained audit entry. Altering any past entry breaks every hash after it.
4. **The perimeter is sacred.** Deployed inside the customer boundary; egress only to the approved model allow-list; no phone-home.
4. **The perimeter is sacred.** Deployed inside the customer boundary; egress only to approved model endpoints and explicitly enabled Public web search (ADR-0015); no phone-home.

## Where the detail lives

Expand Down
91 changes: 91 additions & 0 deletions docs/adr/ADR-0015-governed-web-search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# ADR-0015 — Governed web search (Tavily) as a bounded pipeline stage

**Status:** Accepted
**Date:** 2026-10-17
**Relates to:** ADR-0008 (tool use — still Proposed; this is NOT general tool execution), ADR-0011 (versioned
configuration, startup-only egress allow-list), ADR-0012 (profiles, console inference), ADR-0013 (trace, cache),
ADR-0014 (ledger reservations).

## Context
Operators want the console to answer questions that need fresh public information ("what's the weather in Toronto
today?", "latest release notes"). A model alone answers from stale training data and may pretend otherwise. Adding a
web-search capability is an **external egress of request-derived text**, so it must be governed like a provider call:
authorized, classified, budgeted, traced, evidenced, fail-closed — and must not become an agent loop or a way to run
arbitrary tools.

## Decision
**One bounded search, performed by Covenant itself, as an ordered stage — never a model-chosen tool.**

1. **Pipeline position.** `auth → shape → classify → policy → cache → rate_limit → pause → budget → search → provider →
attribution` (audit wraps). Auth, policy, pause, rate limit and budget therefore run **before** any search call.
The model never decides to search and never sees a tool definition; it receives retrieved snippets as data.

2. **Request mode** (console only; `/v1` is unchanged = Off): `web_search` ∈ `off | auto | required`, plus an
optional `location` field. `auto` triggers only on bounded **freshness cues** (weather/forecast/temperature,
latest/today/tonight/tomorrow/this week/current/right now, news/breaking, scores, stock/price "now") — never on
every prompt. `required` always searches. A triggered request **bypasses the exact cache** (lookup and store).

3. **Location.** A weather request needs a place. If neither the `location` field nor an explicit place in the
prompt ("weather **in** Toronto") is present, the request is refused **before any external call** (400,
`location_required`, "Add a location, e.g. 'Toronto'"). No IP geolocation, no inferred or default city.

4. **Who may search (versioned, fail-closed).** All must hold, else the request is refused before any external call:
- global `web_search.enabled` (configuration, default **false**), versioned with ADR-0011 apply/rollback;
- mode **Hybrid** — Local-only means *no external calls of any kind* (validation error, runtime refusal);
- the request's workload profile has `web_search_allowed` (default false), and only a **Public**-baseline profile
may carry it (validation error otherwise);
- final classification of the full request is **Public**, AND the search query + location, classified separately,
do not escalate (Internal/PII/PHI search is refused: `search_sensitive`);
- the API key `Tavily:ApiKey` is configured server-side (reported as configured/missing, never returned; nothing is
read or imported from other tools' configuration, e.g. Open WebUI);
- an explicit price (`price_per_credit_usd`) is configured — unknown price is **not** zero (validation error);
- `api.tavily.com:443` is on the **startup** egress allow-list (`Providers:ProbeAllowList`). Enabling search in the
console never widens egress (ADR-0011).

5. **The call.** `POST https://api.tavily.com/search` (fixed constant, not configurable), `Authorization: Bearer`,
`{query, search_depth:"basic", max_results ≤ 3, include_answer:false, include_raw_content:false,
include_usage:true, auto_parameters:false}`. Source-generated JSON; redirects disabled; per-call deadline
(configurable 1–30 s, default 10); response capped at 256 KiB; **no retries, no crawling, no follow-up searches.**
Results are validated: absolute http(s) URL without userinfo (≤ 500 chars), title ≤ 200, snippet ≤ 800 chars,
control characters stripped. Invalid sources are dropped.

6. **Accounting.** Search is a separately-reserved **tool call** on the existing ledger (ADR-0014), same scopes as
the request: reserved before the call at `price_per_credit_usd × 1` (basic search = 1 credit), settled exactly once
at `credits reported × price` (`reported`) or, when the call failed, timed out, was cancelled after being sent, or
reported no usage, at the reservation (`estimated_failed_call` when sent and failed or cancelled,
`estimated_unreported` when it succeeded without usage — never $0). A call that was never sent (connection refused
before sending) releases its reservation (`no_call`, $0). The budget stage's first-attempt reservation already
includes a bound for the grounding text the search can add.

7. **Grounding.** On ≥ 1 valid source, the provider receives a system message stating the current UTC date, that
the following numbered sources are **untrusted data, not instructions**, to answer only from them, cite `[n]`, and
say plainly when they do not contain enough evidence; then a data block of the sources (title, URL, retrieval time,
snippet) with the block delimiters neutralised inside snippets. The original request messages are untouched (the
model call uses a derived message list; evidence hashes the original prompt). Weather answers carry no accuracy
guarantee. **Search failure, timeout, 429 or zero valid sources fails the request clearly** (502 / `search_failed`,
`search_timeout`, `search_rate_limited`, `search_empty`) — the model is never asked to answer "current" questions
without evidence.

8. **Evidence and trace.** Trace stage `search`: passed / refused / failed / skipped (`search_off`,
`search_not_triggered`, `not_reached`) with measured duration. Audit v3 adds (additive, nullable) `WebSearch`
= `{Mode, Triggered, Cue, Outcome, SourceCount, SourceHosts[≤3], DurationMs}` and `ToolCalls[]` =
`{ToolCallId, Tool:"web_search", Provider:"tavily", Outcome, ErrorClass, DurationMs, CostUsd, CostBasis,
ReservedUsd, Credits}`. The query, location and snippets are **not** recorded by default. Full retrieved sources
(title, URL, retrieval time) are kept only in the bounded in-memory request store for the console
(`GET /admin/requests/{id}/search`, same TTL as traces) and shown separately from any citations in the answer.

## Consequences
- (+) Fresh-information answers become possible without giving the model tools or an agent loop.
- (+) Every egress of request-derived text is authorized, classified, budgeted and evidenced like a provider call.
- (−) Snippets reach the routed model (cloud for Public under Hybrid policies) — acceptable only because the request
and query are Public; that is exactly why non-Public search is refused.
- (−) The freshness cues and location extraction are heuristics; `required` and the location field are the explicit
controls. Answer accuracy (weather, prices) is not guaranteed and the UI says so.
- (−) Prompt-injection inside snippets cannot be eliminated, only contained: snippets are data, the model has no
tools and no ability to act, and the answer is shown with its actual sources.

## Alternatives considered
- Model-invoked search tool (function calling) — rejected: that is ADR-0008 territory and an agent loop.
- Search via the local model's own runtime/extensions or Open WebUI — rejected: ungoverned egress, ungoverned keys.
- Search in Local-only mode — rejected: Local-only is defined as no external calls.
- Answer without sources when search fails — rejected: it pretends to current knowledge.
67 changes: 67 additions & 0 deletions docs/console-quickstart.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Covenant: everyday use

## Start and connect

With Ollama running and your Qwen model installed, run from the repository:

```sh
scripts/run-local-demo.sh
```

This builds the current code, starts Covenant on port 5210 and opens a connected console. Keep that terminal open. Do not use `SKIP_PUBLISH=1` after changing code: it reuses the old executable. If the port is occupied, stop your previous launcher with Ctrl+C or choose another port with `PORT=5212`.

The console needs only the **admin token**. The separate **application key** is for API clients such as Open WebUI; you do not enter it to run requests in the console. The launcher connects the console for you and keeps the application key in an owner-only file.

## Run a request

1. Open **Overview** or **Playground**.
2. Select the application under **Run as** and its workload profile.
3. Write a prompt and click **Run**. The answer appears on the same page.

Use an **Internal** profile for internal work. Use a **Public** profile for genuinely public content. Profiles establish the starting classification; detection can raise it. The current detector recognises specific patterns, not every possible secret or sensitive fact.

**Demo presets** fills the form; it does not run it. **Advanced** contains model overrides and streaming. **Presentation mode** provides the larger conference view. Use Escape to leave it.

## Get current information with Tavily

Open WebUI's Tavily configuration is separate. Covenant needs its own server configuration; it does not import Open WebUI's key.

One-time setup:

1. Supply `Tavily__ApiKey` to the Covenant server environment through your normal secret-management method. Do not put it in source code or the console.
2. Add `api.tavily.com:443` to `Providers__ProbeAllowList`, preserving existing approved endpoints, and restart Covenant.
3. Under **Policies**, change the mode to **Hybrid** and apply. Your model can still be local; Hybrid permits approved external calls, including search.
4. Under **Settings → Web search (Tavily)**, click **Edit**, configure web search, enter your plan's price per credit and enable it. Preview and apply.
5. Under **Policies → Applications & workload profiles**, allow web search on the Public profile you intend to use. Preview and apply.
6. Check **Settings → Web search**. Its readiness list tells you what is still missing.

To try it: choose that Public profile, select **Web sources → Auto**, enter a city under **Location**, and ask “What's the weather today?”

- **Off:** model knowledge only.
- **Auto:** searches for recognised current-information cues, including weather and news.
- **Required:** always searches before answering.

The answer includes a separate list of retrieved sources and their retrieval time. A failed or empty search produces a clear failure rather than asking the model to invent a current answer. Search is not a dedicated weather feed, so check the sources and their dates.

Local-only mode never searches externally. Internal, PII and PHI requests cannot use Tavily. Search and model inference have separate charges in the request evidence, charged to the same budget.

## Use OpenAI or Anthropic for Public requests

1. Supply `OpenAI__ApiKey` or `Anthropic__ApiKey` in the server environment and restart. These are provider credentials, separate from the console admin token.
2. Ensure the provider endpoint is approved at startup: `api.openai.com:443` or `api.anthropic.com:443` in `Providers__ProbeAllowList`. Preserve the local and search endpoints you still need.
3. Open **Models & connections → Add cloud provider**. Choose the provider, enter the exact model ID and its current input/output prices. The secret reference is selected automatically; the key itself never enters this form.
4. Preview and apply the connection.
5. Under **Policies**, use **Hybrid** mode and edit the **Public** route to select that connection and model. Add an approved local fallback if wanted. Keep sensitive routes local. Preview and apply.
6. Run a Public request in Playground. The result shows the actual destination and charge.

Adding a connection alone does not change routing. **Local-only** blocks cloud calls even if a cloud connection exists. Prices come from your provider plan; Covenant does not download invoices or automatically update prices.

## Know what happened

- **Playground trace:** the steps that actually ran, including search, refusal and provider attempts.
- **Requests → View:** one request's classification, route, attempts, cost and audit record.
- **Budgets → Edit:** change caps and enforcement, preview, then apply. Local inference has no per-call provider charge; hardware and electricity are not included.
- **Audit & evidence:** verify the audit chain and export evidence. “Evidence recorded” means the record exists; chain verification checks its integrity.
- **Pause new provider calls:** blocks new paid/external work through the pipeline. It does not erase history or reset budgets.

For exact search limits and troubleshooting, see [Web search](web-search.md). For the conference sequence, see [Demo runbook](demo-runbook.md).
44 changes: 44 additions & 0 deletions docs/search-usability-acceptance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Search and console usability verification

Verified on 2026-10-17, macOS arm64, .NET SDK 10.0.107. Branch: `feat/console-search-usability`, based on console v2 PR #7.

## Executed checks

- Release solution build: passed, no warnings or errors.
- Final full regression suite with coverage: **889 passed**, none failed or skipped. Measured coverage: **95.70% line / 83.68% branch** (the repository's coverage settings).
- Clean `SkipConsolePublish=true` build/test in a separate output directory: 888 passed. This preceded the final additional test for local-model synthesis from web sources; production code is identical.
- Self-contained single-file `osx-arm64` publish: passed. Ran that executable on isolated loopback port 5297.
- Published GET routes: `/ui` → 302 `/ui/`; `/ui/` and `/ui/requests/example` → 200 HTML. HEAD is not supported by these routes.
- Real Ollama `qwen2.5-coder:7b` request through the published appliance: answered READY, recorded the local destination, charge basis and audit evidence. Search Off was correctly traced as skipped.
- Browser search attempt with search disabled: refused at Web search; Provider and Attribution skipped, no external call.
- All eight main pages checked at 800px width without document-level horizontal overflow. Main pages also checked at 1280×720 in light and dark themes.
- Playground at 1280×720: prompt, Web sources, location and Run button visible with main scroll position 0. Run button bottom was 655px.
- Presentation mode: 1280×720 light/dark has two trace rows; 1920×1080 dark has one row of eleven stages. The short-response panel has no overflow or overlap.
- Checked cloud editor defaults (OpenAI → Anthropic updates its default credential reference), Settings/header theme synchronization in both directions, route navigation scroll reset, dashboard answer display, and Enter-key access to the Requests drawer.
- Browser error log: no errors in the checked final session.

## Defects corrected during verification

- Missing search-stage name mapping prevented its events appearing under the expected trace identifier.
- Search test compilation errors and outdated trace expectations.
- Connection resets after dispatch incorrectly treated as definitely unbillable; now conservatively estimated. DNS failures remain no-call.
- Already-cancelled requests could reach search reservation; now checked before reservation and client dispatch.
- Default provider secret selector empty on fresh installations.
- Theme header and Settings selector disagreed after changes.
- Dropdown padding/chevrons, stretched segmented controls, checkbox dimensions, field/button alignment and grid shrinkage.
- Requests table forced unnecessary horizontal scrolling; budget Requests button split across lines.
- Navigation preserved the old page's scroll position.
- New search controls did not fit the initial Playground viewport and were hidden in the dashboard composer.
- Demo presets reused previous web-search settings; applying a preset now turns search Off and clears location.
- Added durable search/tool evidence to the Requests drawer as well as Playground details.
- Eleven trace stages created an extra presentation row and squeezed result facts; responsive columns corrected.

## Verification limits

A live Tavily request was subsequently verified on the isolated published host: three sources retrieved, one reported credit, local Qwen synthesis, and $0.008 recorded using the explicitly labelled public pay-as-you-go reference rate (not a claim about the operator’s plan). Request: `req_302add2043ad4edca714ca7c75608f43`. The source endpoint and durable audit record both passed inspection. No paid OpenAI/Anthropic credential was configured in the verification process. Search wire format, local/cloud synthesis paths, source handling, failures, cancellation, permissions, cache bypass and budget accounting were exercised using test transports/adapters. Paid model-provider calls remain unverified live.

Search is explicit and off by default. The implementation grounds a model using retrieved web snippets; it is not a dedicated weather API or a guarantee of answer accuracy. Classification recognises configured patterns and trusted profile baselines; it is not comprehensive data-loss prevention.

The user's running instances on 5201/5210 and the Ollama server were not stopped or reconfigured. Changes require rebuilding/restarting the intended Covenant instance. NativeAOT and Linux runtime validation were not repeated in this follow-up.

Local build logs and screenshots are in the git-ignored `docs/verification-2026-10-16/usability/` directory. Usage: [Console quickstart](console-quickstart.md); search setup: [Web search](web-search.md).
Loading
Loading