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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,7 @@ appsettings.Development.json
appsettings.Local.json
secrets.json
.env
.covenant-local/
__pycache__/
*.pfx
*.key
58 changes: 43 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,54 @@
# Covenant

An in-perimeter **AI inference governance and FinOps control plane** for regulated environments (BFSI first). Every LLM request passes through one governed pipeline: classified, policy-routed, budget-checked, cost-attributed, and audited — including the requests that get refused.
An in-perimeter **AI inference governance and FinOps control plane** for organizations that must show who used which model, with what data, where it ran and what it cost. Every LLM request passes through one governed pipeline: identified, classified, policy-routed, budget-checked, cost-attributed and audited — including the requests that get refused.

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)

## Architecture

![Covenant architecture — ingress, governance pipeline, providers, and the evidence plane](docs/diagrams/covenant-architecture.svg)

**Color key:** 🔵 caller surface · 🟠 governance decisions · 🟢 model call · 🟣 evidence (attribution & audit) · 🔴 refusal

Editable sources: [`docs/diagrams/*.drawio`](docs/diagrams/) (open in [diagrams.net](https://app.diagrams.net); the SVGs open there too). Both are generated by `docs/diagrams/gen_diagram.py` — edit the node lists there, not the outputs.
**Start here:** [User guide](docs/user-guide.md) · [7-minute demo](docs/demo-7-minute.md) · [Console usage guide](docs/console-quickstart.md) · [Tavily setup](docs/web-search.md)

## Deployment and trust boundaries

```mermaid
flowchart LR
subgraph Org["Customer perimeter"]
direction LR
Apps["Calling applications<br/>(app key → team)"] --> C["Covenant appliance<br/>canonical proxy + policy middleware"]
Console["Admin console<br/>(admin token)"] --> C
C --> Ollama["Local models<br/>(Ollama, in perimeter)"]
C -.-> Audit[("Hash-chained audit<br/>+ budget ledger")]
Vault["Server-side secrets<br/>(env / vault)"] -.-> C
end
C == "approved egress allow-list only" ==> Providers["Approved model providers<br/>(Anthropic, OpenAI)"]
C == "Public only, opt-in" ==> Search["Tavily web search"]
Browser["Direct SaaS use in a browser"] -. "outside Covenant's scope" .-> Providers
```

Credentials stay on the server; the console never holds an application key or a provider key. Egress is limited to the
startup allow-list. Traffic that does not pass through Covenant (for example a browser talking to a SaaS chatbot) is not
governed by it; that needs network or endpoint controls.

## Request journey

```mermaid
flowchart LR
A["Identify caller<br/>application → team"] --> B["Classify<br/>workload baseline,<br/>detection may raise"]
B --> P["Policy<br/>one match → approved<br/>primary + fallback"]
P --> R["Sanitize<br/>only for an opted-in<br/>structured-record route"]
R --> K["Exact cache"] --> G["Rate · pause · budget<br/>reserve before spend"]
G --> W["Web search<br/>(Public, opt-in)"] --> M["Model call<br/>Local or External"]
M --> F["Finalize cost"] --> E[("Audit record<br/>every request, refused too")]
P -. "no match / not eligible" .-> X["Refuse (fail-closed)"] -.-> E
```

The patterns are a canonical proxy with policy middleware, approved model routing with bounded fallback,
retrieval-augmented answers from one governed web search, an exact-match cache, and per-request attribution and
tamper-evident audit. Covenant does **not** rewrite prompts, does not judge answer quality, and has no learned quality
router. The optional length-based strategy is a deterministic size threshold (characters / 4), not a quality signal.
Sanitization (ADR-0016) applies only to a bounded structured record on a dedicated route. It is not anonymisation.

## Working principles

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.
1. **Fail-closed.** No policy match → deny. Unclassified defaults to the most restrictive class. Misconfiguration → the appliance refuses to start. Raw PII/PHI never reaches a public provider. The one opt-in exception (ADR-0016) sends only a Covenant-built, sanitized payload of a bounded structured record for a dedicated PII workload; PHI and free text never qualify.
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 approved model endpoints and explicitly enabled Public web search (ADR-0015); no phone-home.
Expand Down
48 changes: 48 additions & 0 deletions docs/CONSOLE-DEMO-JOURNEY-SPEC.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Covenant: request journey and conference demo iteration

User approved implementation on November 1, 2026. Continue the current dirty checkout; preserve all existing edits. Codex supervises, runs builds/tests/browser/live provider verification. Claude owns implementation. No commits, pushes, subagents, credential access, runtime configuration edits or server restarts by Claude.

## Outcome

A newcomer can explain who requested work, what data may leave, where it ran, why, and who pays. Deliver actual working UI and backend, not simulated outcomes. Keep existing presentation/replay, versioned configuration, audit compatibility, strict policy/budget checks and focus/dirty-dialog behavior.

## 1. Vocabulary and request journey

Rename composer caller selector to “Send a request as”. Application = authenticated consuming system, owned by a team; Playground exercises an authorized test identity. Explain once through an accessible info/popover, not paragraphs. Keep owner/team visible in compact chips.
Separate data classification (Public/Internal/Sensitive), workload/task (coding/research/writing) and actual destination (Local/External). Public permits external processing, does not require it. Show short route preview before Run and actual route/reason after. External uses consistent amber/purple distinct from local teal; red means sensitive detected/blocked. Icons/text required, not color alone. Examples must not silently change caller or bypass permissions; filter by grants. Mixed internal/public workloads on same application supported, with one visible selection and clear defaults.

## 2. Focused policy and provider configuration

Retain separate Routes / Applications / Workloads tabs and focused dialogs. Make primary route + fallback plain language. Team ownership prominent on application cards/list. Hide advanced conditions in disclosure. Preserve concurrency/validation protections.
Cloud model catalog discovery for existing Anthropic and OpenAI adapters, server-side credentials only, fixed/allow-listed provider endpoint, bounded timeout/pagination, safe errors; no arbitrary URL proxy/SSRF. Provider-specific parsing stays in adapters where feasible. Model discovery is NOT approval or pricing. Catalog selection populates model ID; operator explicitly adds permitted model and configured price. Retain manual entry on discovery failure. Never invent prices or model IDs. Tests fake HTTP endpoints/handlers.

## 3. Usage and evidence

Add Usage navigation/page, backed by authenticated server aggregation of recorded evidence/accounting, with team/application/workload grouping and period/time-window filter. Clearly identify included time window/segments and limitations; avoid unbounded rescanning hot paths. Requests, estimated inference/search/total charge, cache hits, external calls, sensitive detections, redactions and refusals. Refused/zero-cost requests count. Unknown costs are unknown, not zero. Do not call local compute free. Do not double-count retries/search/ledger/audit. No raw prompts/PII in aggregation. Team trend is a signal, not employee misconduct proof.
Result/request detail hierarchy: outcome + destination/reason + owner/team + cost split + expandable evidence. Colored semantic chips, concise labels, long technical text in details. Audit integrity explicitly not correctness/compliance.

## 4. Explicit redaction policy (new ADR BEFORE code)

Default behavior stays fail closed. Add opt-in restricted structured-data redaction demonstration using synthetic data, not generic guaranteed anonymization. Original classification is never rewritten as Public to bypass policy. Dedicated approved policy authorizes only a transformed payload; retain original classification plus redaction decision/counts/types, policy version and transformed classification/egress decision separately in audit. Configure via focused UI, with preview of transformed request before external execution for demo. Original sensitive values must never appear in routine logs/audit preview/cache or tool query. No reverse mapping stored; no reinsertion into response. Sanitize entire canonical message set, not last user message only. Re-check transformed payload. Unsupported/unresolved sensitive fields, conflicting instructions, PHI/free-text cases not safely covered, missing policy => refuse external. Search must not receive original payload; initially disable search for redacted requests if needed. All external attempts/fallbacks use transformed payload. Cache partition includes policy/version/transformation identity; no unsafe cross-context reuse. Cost/attribution/refusal/cancellation audited. Explicit opt-in does not silently change all PII/PHI routing. Document detector limits and that de-identification cannot be guaranteed. Synthetic examples use known structured fields (e.g. email/phone/SSN) with no real person data. Tests prove raw values never reach external adapter, web search, audit previews or cache; prove unsupported and PHI cases fail closed.
The user's explicit request supersedes older blanket 'PII never public' prose only for a dedicated sanitized-payload policy. Update affected invariant docs precisely; never weaken the default or silently lower classification.

## 5. Coding escalation and public local search

Implement explicit approved coding escalation via a workload/route policy and visible user action after a local result (not fabricated automatic difficulty/quality detection). Public synthetic coding can compare or escalate to the configured stronger external model; Internal must not gain external permission because it is difficult. Require explicit reclassification/confirmation before external submission of previously internal content and re-run detection/policy; do not silently change caller grants. State what is measured vs operator choice. If existing routing strategy supports deterministic complexity, document heuristic honestly, never present as quality guarantee.
Public research can use local inference + approved Tavily web search independently of model boundary; show external retrieval badge/query destination and separate search charge. Do not grant all teams search automatically. Existing cache demonstration remains, policy-scoped, fresh/time-sensitive web results bypass cached stale answers as existing rules require.

## 6. Docs and three-demo plan

Update README with two compact, aligned inline Mermaid diagrams: deployment trust boundaries (callers -> Covenant -> approved providers + Ollama; credentials/network controls; direct SaaS browser bypass outside Covenant scope) and request journey. Name actual patterns: canonical proxy, policy middleware, approved model routing/fallback, retrieval augmentation, exact cache, attribution/audit. Do not imply prompt rewriting or learned quality routing exists.
7-minute demo: (1) public research local inference + Tavily, (2) synthetic public coding local then permitted stronger external escalation, (3) sensitive structured input denied then explicit redaction policy preview/approved external sanitized call. Repeat safe request for cache in ~30s. Synthetic prompts only. Missing setup must have actionable setup links, not misleading runnable examples.
Simple user guide begins 4-5 sentences; deep details separate. Scope excludes automatic prompt rewriting/quality-preservation claims and endpoint/device-management implementation.

## Acceptance and handoff

Provide meaningful tests for governance, catalog security, scoped usage accounting, redaction and UI state transitions; no live providers in automated tests. Keep source-generated JSON/AOT compatibility. Report exact files/remaining checks honestly. Implement in stages and report when ready for Codex compile review; continue through full scope. Screens must work at1280x720 and1920x1080, both themes, keyboard dialog navigation. Response may scroll; caller/destination/cost/evidence/trace remain visible in presentation mode. No secrets in logs/screenshots.

### Reviewer notes

Redaction must apply in the shared canonical pipeline for authenticated `/v1` consumers as well as console requests. Preview is never authorization; execution independently validates the bound configuration and transformed request. Review all provider attempts/fallbacks, web queries, prompt previews, request fingerprints and cache keys for original-value leakage. Existing `/v1` search support is limited; document capabilities honestly.

Live discovery verified by Codex: saved Anthropic credential lists `claude-opus-5-5`, `claude-sonnet-5-5`, and other model IDs. Do not hardcode this list as discovery. Opus standard global list-price estimate verified on November 1: $4 input / $20 output per 1M tokens, https://platform.claude.com/docs/en/models/opus-5-5/overview . Codex will configure the demo and verify actual calls after implementation; do not mutate runtime state yourself.
23 changes: 23 additions & 0 deletions docs/CONSOLE-USABILITY-NOVEMBER.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# November usability correction

Preserve existing uncommitted October work. Preserve Playground responses, presentation mode and replay. Codex owns launcher/state recovery, live configuration and verification. Claude owns the UI implementation. No commits, subagents, runtime changes or secret reads.

## Verified defects

Running port 5210 is local-only configuration v1, with only Ollama, both Public/Internal routed locally and search disabled. Previous v7 hybrid state was under /tmp and is gone. The API contains all three user requests, although Requests showed only one. This is not simply operator misunderstanding.

## Required changes

1. Distinguish workload/data classification from destination. Public means cloud-eligible only under policy, not cloud execution. Show actual approved Local/Cloud destination and model beside workload selection, refreshed on form/config changes. Configuration-needed states must link to the relevant setup. Do not weaken classification or policy. Clear example labels/expectations when profile or relevant form values change; an Internal coding example cannot remain labelled as such after switching Public.
2. Disabled web search needs a precise visible reason and direct action even when Off: Local-only mode, profile restriction, missing key, price or disabled service. Internal workloads remain local. Correctly configured Public workloads must support Auto/Required. Hide irrelevant location controls. Never bypass controls.
3. Fix Requests refresh on navigation and successive completion. Inspect stale filters/pagination/snapshot bugs. Show active filters and Clear filters, count, loading and errors. All allowed, denied, cached and streamed requests stay discoverable. Add meaningful regressions.
4. Redesign Policies into Routes, Applications and Workloads views. Routes show match -> primary -> optional fallback -> state -> per-item Edit/Pause. Edit opens a focused accessible dialog/side panel titled with the entity, NOT an appended wall of fields. Configure primary/fallback with eligible model selectors; advanced retries/threshold collapsed. Applications/workloads get entity-specific editing. Preserve existing versioned ConfigEditor validation, conflict handling and deliberate Save/Cancel. Never save unrelated draft changes.
5. Budgets: per-scope Edit dialog; separate Add dialog. Settings: concise section summaries and section-specific dialogs. Shared dialog needs focus trap, Escape, focus return, safe dirty cancellation and visible action footer. No new dependencies. Test save/cancel isolation.
6. Models: clearly distinguish configured connections, available credentials and tested usability; explicit Add/Configure cloud flow. Repair alignment of model IDs, route arrows, badges, labels and Overview local route. Check 1280x720 and 1920x1080 in light/dark. No awkward narrow columns beside empty space.
7. Trace: preserve success/failure status colors, add a distinct accent and proportional duration indicator for the longest measured stage. Describe share of measured processing, not necessarily total wall time. Do not fabricate timings or mark slow as failed. Keep replay and <1ms/skipped semantics.
8. Audit: rename Verify to Check audit integrity. Explain exactly which hash links/checkpoints are checked (inspect actual implementation); it does NOT validate answer accuracy or compliance. Show checked count/time/result and actionable errors. Button must run fresh verification.
9. Usage guide starts with 3-5 practical sentences, technical reference later. Avoid explanatory walls in product flows.

## Acceptance

Build/tests plus actual browser verification: Internal local coding; switch Public and clearly see configured cloud route; search works when allowed and has explicit reason when blocked; every run appears in Requests; modal editing save/cancel/conflict behavior; integrity check reruns; no alignment/overflow at tested sizes. Test values and configuration must survive a normal launcher restart. Deliver a compilable checkpoint and pause for Codex review. Do not claim unexecuted tests passed.
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,6 @@ hits** — the UI says so), costs $0 provider charge with `CostBasis = no_call`,
- (+) Fallback is bounded, explainable, evidenced, and cannot route sensitive data to cloud by accident.
- (+) The console shows real stage execution, not a configured-order animation.
- (−) Every config activation cold-starts the cache.

## Amendment (2026-11-01): ADR-0016
The "PII/PHI ⇒ cloud targets are never eligible" rule has exactly one exception: a profile-scoped, PII-only policy carrying an ADR-0016 redaction contract makes its cloud targets eligible **only** for the payload the redact stage builds from a valid `covenant.record.v1` record (re-verified per attempt). PHI, prose and every other PII policy are unchanged. The classification is never lowered.
Loading
Loading