Metadata-Version: 2.4
Name: compass-kb-validation
Version: 4.13.0
Summary: Knowledge-base readiness validation for RAG & AI agents — config-driven, deterministic pipeline integrity checks.
Author: COMPASS
License: MIT
Project-URL: Homepage, https://github.com/TestAutomationArchitect/compass
Project-URL: Repository, https://github.com/TestAutomationArchitect/compass
Project-URL: Issues, https://github.com/TestAutomationArchitect/compass/issues
Keywords: rag,knowledge-base,vector-database,data-validation,pipeline-testing,llm-infrastructure
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.31.0
Requires-Dist: boto3>=1.34.0
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: redis>=5.0.0
Provides-Extra: dashboard
Requires-Dist: fastapi>=0.104.0; extra == "dashboard"
Requires-Dist: uvicorn>=0.24.0; extra == "dashboard"
Provides-Extra: pdf
Requires-Dist: PyPDF2>=3.0.0; extra == "pdf"
Provides-Extra: pdf-layout
Requires-Dist: pymupdf>=1.24; extra == "pdf-layout"
Provides-Extra: content
Requires-Dist: beautifulsoup4>=4.9.0; extra == "content"
Provides-Extra: perf
Requires-Dist: numpy>=1.24; extra == "perf"
Provides-Extra: qdrant
Requires-Dist: qdrant-client>=1.7.0; extra == "qdrant"
Provides-Extra: pgvector
Requires-Dist: psycopg[binary]>=3.1; extra == "pgvector"
Provides-Extra: pinecone
Requires-Dist: pinecone>=5.0.0; extra == "pinecone"
Provides-Extra: weaviate
Requires-Dist: weaviate-client>=4.5.0; extra == "weaviate"
Provides-Extra: chroma
Requires-Dist: chromadb>=0.5.0; extra == "chroma"
Provides-Extra: azure
Requires-Dist: azure-storage-blob>=12.0.0; extra == "azure"
Requires-Dist: azure-identity>=1.15.0; extra == "azure"
Provides-Extra: gcs
Requires-Dist: google-cloud-storage>=2.10.0; extra == "gcs"
Provides-Extra: offline
Requires-Dist: rdflib<8,>=7.0; extra == "offline"
Provides-Extra: all
Requires-Dist: fastapi>=0.104.0; extra == "all"
Requires-Dist: uvicorn>=0.24.0; extra == "all"
Requires-Dist: PyPDF2>=3.0.0; extra == "all"
Requires-Dist: beautifulsoup4>=4.9.0; extra == "all"
Requires-Dist: qdrant-client>=1.7.0; extra == "all"
Requires-Dist: psycopg[binary]>=3.1; extra == "all"
Requires-Dist: pinecone>=5.0.0; extra == "all"
Requires-Dist: weaviate-client>=4.5.0; extra == "all"
Requires-Dist: chromadb>=0.5.0; extra == "all"
Requires-Dist: numpy>=1.24; extra == "all"
Requires-Dist: azure-storage-blob>=12.0.0; extra == "all"
Requires-Dist: azure-identity>=1.15.0; extra == "all"
Requires-Dist: google-cloud-storage>=2.10.0; extra == "all"
Requires-Dist: rdflib<8,>=7.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: pyflakes>=3.0.0; extra == "dev"
Requires-Dist: pyright==1.1.409; extra == "dev"
Requires-Dist: bandit>=1.7.5; extra == "dev"
Requires-Dist: pip-audit>=2.6.0; extra == "dev"
Requires-Dist: numpy>=1.24; extra == "dev"
Requires-Dist: rdflib<8,>=7.0; extra == "dev"
Dynamic: license-file

# COMPASS — the quality gate for your RAG knowledge base

[![CI](https://github.com/TestAutomationArchitect/compass/actions/workflows/ci.yml/badge.svg)](https://github.com/TestAutomationArchitect/compass/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/compass-kb-validation)](https://pypi.org/project/compass-kb-validation/)
[![Python](https://img.shields.io/pypi/pyversions/compass-kb-validation)](https://pypi.org/project/compass-kb-validation/)

**Point COMPASS at your RAG knowledge base. It runs 73 deterministic checks across storage,
knowledge graph, vectors and retrieval, and fails your CI build when the KB is broken.**
No LLM, no test-writing — the checks ship with it.

Think of it as a **linter for your RAG data plane**: a catalogue of built-in checks with
HARD/WARN severity tiers, tuned in YAML, gating CI by exit code. It answers *"is the
knowledge base itself sound?"* — not *"are the answers good?"* (that's the eval layer's
job; COMPASS is the gate that runs first).

### Your KB is broken and you don't know yet

Chunks that never got embedded. An embedding model swapped without a re-index. A document
deleted at the source but still answering questions. Citations pointing at the wrong file.
Storage, graph and vector store quietly disagreeing about what exists. **All of it is
invisible from the outside** — retrieval still returns *something*, answers still look
plausible, and your eval scores drift for reasons nobody can trace.

COMPASS finds these deterministically, before your agents serve them.

### 30 seconds to see it work

```bash
pip install compass-kb-validation
compass demo                                   # sample report, no backend needed
compass check redis://localhost:6379/my_index  # your real index: profile -> validate -> report
```

`compass check` needs no config: it profiles the index, fills in the shape it detects, runs
the checks, and opens an HTML report. See **[QUICKSTART.md](QUICKSTART.md)** for the
five-step path to a gating CI check.

### Does it actually catch things?

Yes — and you can verify that claim yourself in one command, no services required:

```bash
python benchmark/broken_kb_benchmark.py
#   Detection rate:      16/16  (100%)
#   False-positive rate: 0/6    (0%)
```

The [broken-KB benchmark](benchmark/) injects 16 realistic faults (zero chunks, wrong
embedding dimension, degenerate vectors, cross-document contamination, orphaned sources,
retrieval drift, …) into fixtures, runs the **real** validators against them, and scores
detection vs false positives. It also runs 6 healthy fixtures to prove COMPASS doesn't cry
wolf. It's part of the test suite, so the number can't rot.

## What COMPASS Does

COMPASS validates a document's journey through your ingestion pipeline and verifies the resulting knowledge base is agent-ready. The pipeline is **declarative** — you choose which steps run, in what order, in YAML — and ships with these built-in steps:

```
API Upload → Object Storage → Knowledge Graph → Vector Store → Retrieval → Cross-Stage Consistency
```

Enable only the steps your setup has (no object store? no graph? drop them), reorder them, or register your own. For each enabled step it deterministically checks, for example:

- **Ingestion** — the document was accepted and assigned an id (**GraphQL or REST** ingestion APIs, config-driven)
- **Object storage** — it persisted with the right content type, size, and integrity, and (opt-in) the *source document* is healthy across PDF/DOCX/PPTX/HTML (S3, MinIO, R2, Azure Blob, GCS…)
- **Knowledge graph** — metadata is present, correct, and *agrees with the other stores*: required predicates, identity uniqueness, storage-reference integrity, RDF typing, ontology-namespace consistency, dangling links, orphan nodes, version supersession (GraphDB, Neptune, Neo4j, Stardog, Blazegraph…) — **19 checks**, HARD / WARN tiered, every predicate and query config-driven so they fit any ontology
- **Vector store** — chunks exist with valid embeddings, correct dimensions/metric, sane ordering/overlap, structure coherence, retrievable via KNN, no cross-document contamination, no near-duplicate bloat (Redis, Qdrant, pgvector, Chroma, Pinecone, Weaviate) — **30 toggleable checks**, each on a **HARD / WARN** severity tier (only HARD gates the run)
- **Retrieval** — the document's own content is actually retrievable (recall@K, MRR); opt-in embedding-drift, provenance, filtered-recall, negative-retrieval, keyword-completeness
- **Cross-stage consistency** — do object storage, the graph, and the vector index *agree* about each document (eTag, metadata, ACL propagation)?

Two modes: **live** validation as documents are ingested, and **post-hoc discovery** of a corpus that's already loaded.

> Scope note: COMPASS validates *pipeline & data integrity*. It does **not** judge answer quality — that's the evaluation layer's job. COMPASS is the gate that runs first.

## What's new in 4.13

4.13 comes from a whole-codebase review: it removes the remaining ways a check could pass over
data it never examined, corrects the eval oracle's numbers, and makes large documents compare
faster. Discover's findings match 4.11 on the partner-shaped mocks.

| Situation | 4.12.1 | 4.13 |
|---|---|---|
| A document with 99 garbled pages and one clean one | CONTENT_OK | partly verified (`eval.fidelity.min_pages_examined`) |
| A store that answers the ping, then times out on the chunk query | "No chunks found", FAILED | did not answer, not checked |
| `doc-1` looked up in master metadata when only `doc-10` exists | passed | missing |
| A judge scoring 1-5 in `calibrate-judges` / `quality-gate` | read as 0-1 (4/5 = 4.0) | read on its own scale |
| A 1,600-chunk document in fidelity | about 58 s | about 44 s, same result |

**What reads differently**

- **Coverage.** The vector step reads up to 5,000 chunks a document (was 1,000), so long documents
  are checked whole; one past the cap is partly verified, not passed.
- **Commands.** A shell variable wins over `.env` files; commands that measured nothing exit 3;
  `run_validation.py` exits 3 when documents were not checked; discovery looks the graph up once.
- **Eval oracle.** Groundedness no longer penalises fabrication twice; cited page ranges are whole;
  one case-id rule; `benchmark` names no winner over unequal query sets.
- **Privacy.** Fixture bundles carry no hosts or profiles; more text fields are redacted.

See the [CHANGELOG](CHANGELOG.md) for the upgrade table.

## What's new in 4.12

4.12 answers a field review of 4.11 that ran every command: a step that could not run read as a
failure, commands that did not load the environment file, acceptance that failed documents it
never compared, and eval-oracle counts that missed recorded chunks. Checked on synthetic cases 96
to 119; cases 36 to 95 still pass, and `discover` scores the same as 4.11 on the partner-shaped
mocks.

| Situation | 4.11.0 | 4.12 |
|---|---|---|
| Storage step could not run (TLS dropped) | Integrity FAILED, reason "storage step could run" | INCOMPLETE, reason `S3 Storage could not run: <error>` |
| A cited value in the second recorded chunk of a page | retrieval gap | grounded; in another chunk of the document, `citation_error` |
| `acceptance` with expected documents the run did not compare | missed (FAIL) | not compared (INCOMPLETE); unasked criteria SKIPPED |
| `fixture check` with no baseline | REGRESSED | NO BASELINE (exit 3) |
| Repeat `fidelity` / `discover` on unchanged snapshots | every snapshot read again | read from the ETag-keyed snapshot cache |

**What reads differently**

- **Commands.** Every command loads `.env` and `.env.<env>`; a missing credential is not retried;
  `policy --set` refuses an unknown key; MCP checks arguments against each tool's schema.
- **Eval oracle.** Groundedness confidence follows how many citations could be checked;
  `calibrate-judges` and `quality-gate` report truth coverage; `diff` takes two `enrich` outputs;
  `simulate --truth-index` names no winner when the truth favours one index.
- **Run time.** The cost line breaks comparing down by stage and element type; the Redis pool
  follows `--workers`; `Step times` says when the steps mostly wait.
- **Opt-in.** `eval.fidelity.line_found_share` holds long lines found only in part to a share.

See the [CHANGELOG](CHANGELOG.md) for the upgrade table.

## What's new in 4.11

4.11 answers a field review of 4.10: a verdict that changed with a transient snapshot error, an
advisory check that could take a document's verdict, and repeat work across runs. Checked on
synthetic cases 85 to 95; cases 36 to 84 still pass.

| Situation | 4.10.0 | 4.11 |
|---|---|---|
| Snapshot read fails (dropped connection on the version listing) | reported `missing`, compared with the source PDF; verdict changed run to run | `unreadable` with its error, document UNVERIFIABLE, readiness NOT VERIFIED |
| CC-14b on a table every chunk repeats | `max() iterable argument is empty`, comparison discarded | table not judged; any check that raises is "could not run" for that check only |
| `fidelity` after `discover` on unchanged sources | every source downloaded and extracted again | read from the ETag-keyed source cache |
| `[Chart]` marker plus its description in a chunk | description counted as ALTERED | generated text (`eval.chunks.generated_block_patterns`) |

**What reads differently**

- **Content.** An image label's numbers belong to the label; `re- pairing` and `re-pairing` find
  the source's `repairing`; a footnote after a table's grid is a `table_note`.
- **Wording.** The console Integrity word matches the HTML card; no legacy verdict beside NOT
  VERIFIED; cross-stage names only the stores it compared; the cross-check counts passages; a check
  turned off reads `disabled by config`.
- **Run time.** The cost line splits snapshots from sources and shows cache hits; `Step times`
  split working from waiting.
- **Config.** `lint` knows every key the code reads, and a test keeps it that way.

See the [CHANGELOG](CHANGELOG.md) for the upgrade table.

## What's new in 4.10

4.10 answers a field review of 4.9: what a dropped connection did to the verdict, and what still
read as lost when it was not. Measured on the 502-document offline mock and on synthetic cases:

| Measure | 4.9.0 | 4.10 |
|---|---|---|
| 502-document mock: documents, fidelity verdicts, lost passages, findings | as 4.9 | identical, except the one document missing from storage, whose other checks now run |
| Storage step, 502 documents with stale stored keys (summed) | 13,875 s | 28 s |
| Document checks, same run, 3 fidelity processes | 20 min | 8 min |
| Largest mock document (3.0M characters): fidelity peak memory, time | 1,166 MB, 62.7 s | 814 MB, 52.9 s |
| A dropped object-store connection | document FAILED, later steps skipped, minutes of retries; readiness counted it OK | partly verified, other steps run, readiness NOT VERIFIED, retries capped at 60 s |

**What reads differently**

- **Could not run is not failed.** A step in ERROR leaves the document partly verified; `discover`
  runs each store's checks on its own; the report lists every step with its status.
- **Content.** A range (`2.5-2.8%`) keeps both ends; a wrapped table title is one title; a wordmark
  next to Markdown logos is an image label; `eval.chunks.generated_line_patterns` counts a
  pipeline's generated lines apart from altered chunks.
- **One vocabulary.** The console, HTML and JSON count `passed`, `partial`, `failed` alike; coverage
  says partly verified, could not run, not run, disabled by config or not applicable.
- **Run time.** `Step times` and a fidelity cost split in the summary; fidelity uses every core but
  one as memory allows, budgets from measured peaks, and starts the slowest documents first.

See the [CHANGELOG](CHANGELOG.md) for the upgrade table.

## What's new in 4.9

4.9 fixes what a field run of 4.8 still got wrong and gives every run one verdict. Measured on the
offline mock knowledge bases (`compass mock-kb`) and on synthetic documents:

| Measure | 4.8.0 | 4.9 |
|---|---|---|
| Mock scorecards (custom, provider, Large): real losses found, false gates | as listed for 4.8 | identical; the new shapes (approximate values, hyphenated titles, cropped footnotes) read as intended |
| One 50-page document, 10% of lines lost: peak memory, time | 728 MB, 161 s | 257 MB, 26 s |
| One 400-page document, 10% of lines lost: peak memory, time | not measured | 763 MB, 148 s (`scripts/fidelity_memory_check.py`) |
| 502-document mock, full discover with fidelity, 8 workers (one 16 GB host, same session) | 59.1 min; 1 document failed on a memory error, 2 comparisons failed | 48.9 min; none |
| Qdrant (157-document KB, real embedded engine): documents validated | 150 | 157 |

**What reads differently**

- **One verdict per run.** With a readiness preset, the HTML badge, the readiness page, the JSON
  `verdict`, the console and the exit code all give the preset's badge, with the numbers that
  decided it ("READY WITH CONDITIONS: 0 blocked, 7 need review (4.5% of 157) ...") and what blocks.
  The legacy verdict is shown once, for comparison. Opt-in `readiness.policy.retrieval_relief`.
- **Content verdicts.** An approximate value (`~20.6`) no longer takes a table row's `0.6`; a title
  the sentence above writes hyphenated stays `table_title`; a cropped footnote and a logo wordmark
  (in any annotation form, or misread by OCR) never gate.
- **A failed storage read is an error, never "not found".** A stale stored key finds its source by
  ETag under the prefix, and the source checks run.
- **The summary names one weakest area**, the one the verdict rests on; hygiene is labelled
  "advisory checks only".
- **Every hover uses the report's own tooltip**, charts included.

See the [CHANGELOG](CHANGELOG.md) for the upgrade table: under a preset discover's exit code follows
the badge, and the console's integrity line is now `Integrity:`.

## What's new in 4.8

4.8 fixes what a field run of 4.7 still got wrong, keeping every finding. Measured on the
offline mock knowledge bases (`compass mock-kb`) with the 4.8 planters, against 4.7.0 on the same
mocks:

| Mock KB | Real losses found (4.7.0 -> 4.8) | Documents gated without a loss | False gating lines | Unchanged values flagged (per value) |
|---|---|---|---|---|
| Reference, custom index | 32 -> 32 | 2 -> **0** | 2 -> **0** | 2 -> **0** (changed values found 1 -> **3 of 3**) |
| Reference, provider index | 10 of 10 -> 10 of 10 | 0 -> 0 | 0 -> 0 | 0 -> 0 |
| Large KB (50 documents) | 34 -> 34 | 0 -> 0 | 10 -> **0** (form questions in table rows) | 0 -> 0 |

Fidelity uses about 40% less CPU than 4.7.0 on the Large mock (paired runs, identical results),
for about 90 MB more peak memory per fidelity process (capped on the largest documents).

**What reads differently**

- **Table rows are judged cell by cell.** A line whose words sit in the cells of one stored row
  is stored, layout differs; a table title whose words are in the sentence above stays lost.
- **The cross-check confirms `lost` only when a word of the line is missing from its page.**
  Every word on the page, in another order, is `unresolved`: still gating under the legacy
  verdict, NEEDS REVIEW under a preset.
- **A chart read as a table** (an evenly spaced scale in a cell) is a figure, tier low.
- **`overall` says `PARTLY_VERIFIED`** where the headline does; readiness findings are counted as
  KB-level.

### Upgrading from 4.7.0: what changes by default

| Change | Why | To keep 4.7.0 |
|---|---|---|
| JSON `overall` is `PARTLY_VERIFIED` for a document where a check could not run while others did; schemas `compass-run/2`, `compass-discovery/2` | The headline said partly verified, the JSON `NOT_CHECKED` | match both values where you matched `NOT_CHECKED` |
| Cross-check `lost` needs a word missing from the page +-1; else `unresolved` | Lines with every word on the page were confirmed lost | none; both gate under the legacy verdict |
| A stored Markdown row is judged cell by cell | Form questions in a row's cells gated as lost | none needed |
| An axis scale in a table cell is kind `figure`, tier low | Chart labels gated as table text | raise `figure` in `eval.fidelity.tiers` |
| Readiness findings line: "N readiness finding(s) (KB-level)" | Stage names were counted as documents | none; finding ids are unchanged |

Exit codes are unchanged.

## What's new in 4.7

4.7 keeps what 4.6 finds and fixes what a field run of 4.6 got wrong: false content-loss
findings, counts that did not add up, and runs where one stage could not answer. Measured on the
offline mock knowledge bases (`compass mock-kb`) with the 4.7 planters, against 4.6.0 on the same
mocks:

| Mock KB | Real losses found (4.6.0 -> 4.7) | Documents gated without a loss | False gating lines | Unchanged values flagged |
|---|---|---|---|---|
| Reference, custom index | 32 of 32 -> 32 of 32 | 2 -> **0** | 3 -> **0** | 6 -> **0** |
| Reference, provider index | 7 of 10 -> **10 of 10** | 0 -> 0 | 0 -> 0 | 0 -> 0 |
| Large KB (50 documents) | 34 -> 34 | 0 -> 0 | 1 -> **0** | 0 -> 0 |

On the reference mock the independent cross-check confirms every planted loss as lost, with none
left unresolved. On the Large mock, overlap is measured in chunk order, so a chunker with
variable overlap passes (49 documents; 4.6.0 failed 46).

**What reads differently**

- **Partly verified.** A document where a stage could not run but nothing failed is *partly
  verified*, not *not checked*. The console headline, JSON summary, corpus line and report all
  count the same four outcomes: passed, failed, partly verified, not checked.
- **A store that did not answer is never cited.** Cross-store checks compare only the stores
  that answered. A source replaced after ingestion is still found while the graph is down.
- **Counts name their unit.** Fidelity passages and values are counted apart, and each breakdown
  sums to its total. Tracked findings say "N failed check(s) on D document(s)". Chunk integrity
  gives its denominator and every chunk it left out, with the reason.
- **`remediation.json`** separates `review` (confirmed lost) from `review_suspected` (the
  cross-check could not settle it), and adds `ingest` for a source with no chunks.
- **`compass readiness`** names each artifact's Compass version and time. A stale artifact does
  not decide the verdict unless `--allow-stale`. Under a preset there is one verdict: the badge.
- **Faster on large corpora.** Under `--parallel`, fidelity runs alongside the document checks.
  A 502-document, 208,467-chunk mock took 51 minutes instead of 75. The console prints a "Stage
  times" line.

### Upgrading from 4.6.0: what changes by default

| Change | Why | To keep 4.6.0 |
|---|---|---|
| A check that did not run or does not apply writes `passed: null` in JSON (was `false`); `outcome` is authoritative | A reader counting `passed: false` counted checks that never ran as failures | none; read `outcome` |
| JSON summary gains `partly_verified`; `not_checked` now means no check could run | Partly checked documents read "not checked" | none; `not_checked + partly_verified` is the 4.6.0 `not_checked` |
| Value drift is advisory under every preset | Unchanged values read as rewritten | `document.block_on: [value_drift]` |
| A lost line is decided on 5-token runs on its page +-1 and elsewhere | Real losses of common words were never "lost" | none needed |
| Cropped columns and image wordmarks are kinds `fragment` and `image_label`, tier low | They gated as content loss | raise them in `eval.fidelity.tiers` |
| Under a preset, readiness prints the badge as the verdict and the legacy verdict "for comparison" | Two verdicts on one screen | none; the exit code already followed the badge |
| Readiness leaves out artifacts from another version or older than the discover report | A stale artifact decided the verdict | `compass readiness --allow-stale` |
| Overlap is measured in stored chunk order; a non-fixed strategy passes if any pair overlaps | Variable overlap read as "0%" | `redis.chunking_strategy: fixed` keeps `overlap_min_ratio` |

Exit codes are unchanged.

## What's new in 4.6

4.6 keeps what 4.5.1 finds and removes what it found wrongly. Measured on offline mock knowledge
bases built from measured production shapes (`compass mock-kb`), against 4.5.1 with the
same configuration:

| Mock KB | Real losses found (4.5.1 -> 4.6) | Documents gated without a loss | False gating lines |
|---|---|---|---|
| Reference, custom index | 32 of 32 -> 32 of 32 | 10 -> **0** | 18 -> **0** |
| Reference, provider index | 10 of 10 -> 10 of 10 | 3 -> **0** | 5 -> **0** |
| Large KB (50 documents) | 34 -> 34 | 18 -> **0** | 4,669 -> **0** |

On the Large KB, retrieval misses read correctly 10 of 10 (4.5.1: 0 of 10), and a source replaced
after ingestion gives 1 finding instead of 6.

**New commands**

| Command | What it does |
|---|---|
| `compass run --project P` | The whole run: `doctor`, discover with fidelity, readiness, acceptance. Stops early if `doctor` finds a stage that cannot run |
| `compass doctor` | Now runs your graph query for sample documents and names the graphs that hold them; shows each stage's identity and tests its permissions |
| `compass profile --snapshots N` | Suggests `chunking_strategy`, `chunk_overlap`, `max_chunks_per_document`, consistency fields; groups unmatched snapshot lines by shape with a pattern to copy |
| `compass policy show / diff` | The effective readiness policy and where each value came from |
| `compass readiness --report saved.json --policy strict --compare lenient` | Re-judge a saved run under another policy, no re-run |
| `compass check-document --id D` / `compass.gate_document()` | A per-document gate for your ingestion pipeline (exit 0 pass, 1 fail, 3 not checked) |
| `compass questions generate` | A deterministic question set for a KB that has none (review it before gating on it) |
| `compass fixture export` / `fixture check` | A pseudonymised offline copy of chosen documents, with an equivalence check; run it as a release test |
| `compass show-finding` | Under `privacy.redact`, read a lost line from the store on your machine; nothing is written |

**Readiness policy (opt-in).** `readiness.policy.preset: strict | standard | lenient |
report_only` gives every document a status (BLOCKED, NEEDS REVIEW, OK WITH NOTES, OK, NOT
VERIFIED, QUARANTINED) and the KB a badge (NOT READY exit 1, NOT VERIFIED exit 3, READY WITH
CONDITIONS, READY). Presets are strictness levels, not domains; every value can be overridden in
YAML or with `--set`. Your content rules are yours: `eval.fidelity.value_patterns` (a dropped
"not", a changed unit), `kinds` (footnotes, steps), `section_roles`, `order`,
`boilerplate_min_documents`. `privacy.redact` keeps the words of your documents out of every report.

### Upgrading from 4.5.1: what changes by default

Without a `readiness.policy.preset`, readiness gives the 4.5.1 verdict. What detection reports
changes as follows, each with the setting that keeps the 4.5.1 behaviour:

| Change | Why | To keep 4.5.1 |
|---|---|---|
| Undeclared `chunking_strategy`: chunk size and overlap checks are not applicable (they were scored as fixed-size) | 325 and 410 false failures on a layout-chunked KB | `redis.chunking_strategy: fixed` |
| Overlap is measured for any declared strategy (advisory unless fixed) | A separator-aligned splitter overlaps by less than the setting | none needed |
| Every gating fidelity line is cross-checked by an independent method; lines it shows stored do not gate | False content-loss findings | `eval.fidelity.cross_check: report` (classes only) or `off` |
| A line stored in another layout (cells reordered, rewrapped) is "layout differs", advisory | Same | `eval.fidelity.layout_rules: []` |
| An unconfigured metadata check is not applicable, not "not checked" | Documents read "not checked" for an option nobody set | none needed |
| A probe that retrieves nothing is an advisory retrieval miss; only a store that cannot be queried is "not run" | An outage and a miss read the same | none needed |
| A source replaced after ingestion is one finding; the checks that follow from it are linked as consequences | One stale id gave 6 hard failures | none needed |
| A backend that refuses access is reported once, with the identity and missing permission, and not asked again | 502 tracebacks and an hour of fidelity | none needed |
| Text like `<500K` or `< >` is text, not an HTML tag (normalisation `norm-v2`) | Literal text was deleted | none; fidelity finding ids from 4.5.1 can be re-keyed with `compass triage migrate` |
| A document whose only checks could not run is NOT_CHECKED, not EMPTY | It was neither passed nor failed | none needed |

All JSON reports gain fields (`schema`, `outcome` per check, `coverage`, `cross_check`,
`remediation`, `policy_layer`); none is removed or renamed.

## Key Features

✅ **Declarative pipeline** — choose/reorder/extend steps in YAML; no fixed shape  
✅ **Config-Driven** — zero code changes per project; all customization in YAML  
✅ **Pluggable backends** — storage / vector store / knowledge graph via a provider registry (one file to add a vendor). Redis, Qdrant, pgvector, Chroma, Pinecone and Weaviate all support **metadata pre-filters**, so a probe reproduces production's *filtered* retrieval on any of them ([SUPPORT.md](SUPPORT.md))  
✅ **Pluggable steps** — register custom validators in a step registry; the report adapts automatically  
✅ **Deterministic & cheap** — structural/byte/schema checks, no LLM, CI-gateable  
✅ **Query & analyze the KB** — ask it questions, expose it to agents over MCP, and preview embedding-model migrations / map retrieval coverage — all deterministic, read-only (see *Beyond validation*)  
✅ **Eval oracle** — enrich any eval with deterministic KB-grounding signals, then measure how accurate its LLM judges are against that ground truth (`compass enrich` / `compass calibrate-judges`) — the eval framework guesses, COMPASS checks the KB  
✅ **Interactive reporting** — self-contained HTML dashboard + JSON + JUnit XML  
✅ **Trend Tracking** — SQLite historical performance analysis  
✅ **Notifications** — Slack/Teams webhooks for alerts  
✅ **Parallel Execution** — process many documents concurrently  
✅ **Graceful Degradation** — non-critical failures don't crash the pipeline  

## Install

Core deps only; add extras per backend (Redis is built in):

```bash
pip install compass-kb-validation
pip install "compass-kb-validation[qdrant,pgvector,chroma]"
#   vector stores: qdrant | pgvector | chroma | pinecone | weaviate
#   also: pdf (PDF source checks) | content (HTML extraction) | azure | gcs | dashboard
```

### Project path (saved config)

Then use the unified **`compass`** CLI - one verb, subcommands:

```bash
compass init my-kb          # scaffold config/projects/my-kb.yaml + .env.example + a .compass marker
cp .env.example .env        # fill in your backend connection
#   edit config/projects/my-kb.yaml  (search_index, document_id_field)
compass doctor --project my-kb     # verify connectivity + config (per stage)
compass discover --project my-kb   # validate the already-populated KB, emit a report
```

`compass init` drops a `.compass` marker, so the CLI works from any subdirectory of the
project (no env var to set). Other subcommands:

```bash
compass validate --project my-kb --output-format all   # live ingestion validation
compass profile  --project my-kb                        # read a store's shape, suggest config
compass list-checks                                     # check catalogue + severity tiers (no project needed)
compass <cmd> --help                                    # per-command options
```

The standalone `compass-discover` / `compass-validate` / `compass-profile` commands keep
working. Live validation also reads a `test_data/<name>.yaml` (scaffold it with
`compass-validate --project my-kb --init-test-data`).

### Beyond validation — inspect, migrate, map coverage

These read-only, deterministic (no-LLM) tools help you **verify, diagnose, and safely change**
a knowledge base — they don't turn COMPASS into a retrieval app or an agent-serving platform.
`compass ask` is a **retrieval probe** (see *what the KB returns* for a query, no generated
answer); `compass mcp` is an **inspection surface** (read-only KB tools an agent can call, not
a serving layer). Everything here stays on COMPASS's side of the line and never affects a
validation pass/fail. They read an `embedding:` block in the project YAML (provider `openai` /
`azure_openai` / `bedrock` / `openai_compatible` for a self-hosted server such as vLLM, Ollama or
TEI, `model_id`, `dimensions`) so a query is embedded the way ingestion was.

```bash
# Ask the KB a question - returns the ranked chunks it would retrieve (no generated answer)
compass ask --project my-kb "what is the refund policy?"

# Match production retrieval with metadata pre-filters (hybrid search; commas AND, | ORs a field)
compass ask --project my-kb --filter "category=report,region=US|EU" "summarize the latest report"

# Expose the KB to agents (Copilot/Claude) as MCP tools over stdio
compass mcp --project my-kb --print-config   # prints a .vscode/mcp.json snippet
compass mcp --project my-kb                   # run the server (query_kb, list_documents, ...)

# Preview an embedding-model switch BEFORE you cut over (self-bootstraps, no questions needed)
compass migrate --project my-kb --to openai/text-embedding-3-large

# Map retrieval coverage / find dead zones a question set never reaches (feed real query logs)
compass coverage --project my-kb --questions query_logs.jsonl

# Prove retrieval matches production: compare vs a ground-truth file (precision/recall/Jaccard)
compass compare --project my-kb --ground-truth production_ground_truth.json
# Mixed ground-truth file? Non-retrieval cases (no chunks) are auto-skipped; filter by variant:
compass compare --project my-kb --ground-truth gt.json --variant answerable

# Hand retrieval to any eval framework: emit generic RAG eval test cases
compass ask --project my-kb --batch questions.jsonl --format eval --output eval_input.jsonl

# Corpus health (deterministic, no LLM): score chunk quality / find stale + orphan sources
compass quality   --project my-kb
compass freshness --project my-kb --stale-after 30

# Validate an EXTERNAL eval's output against the KB COMPASS already has access to. Not an eval,
# not a tracer: the eval (an LLM judge, or the bot's captured trace) claims "grounded",
# "cited MIS p.1", "28%" - COMPASS deterministically checks those claims against ground truth
# in the KB and attributes any failure to a layer (retrieval vs the model), never scoring answer
# quality. Verifies each CITED claim at its cited location: a fabricated number, a wrong page, a
# fact present in the KB but not retrieved, or a source not in the KB. Uses the eval's retrieved
# chunks when present (Level 1) and the live KB (Level 2); the answer text + a reachable KB alone
# still catches fabricated figures and phantom citations.
compass grounding-audit --project my-kb --eval-result case.json --fail-on-fabrication

# Level 3 (opt-in): when the KB cannot confirm a cited value, read the ORIGINAL source object and
# check the cited page of the real document. This separates the two cases the KB alone cannot tell
# apart - the fact IS in the source but never reached the KB (an INGESTION defect: re-ingest, no
# amount of retrieval tuning fixes it), versus the fact is nowhere in the source (a PROVEN
# generation hallucination). Needs eval.citation_source_key_fields + object-store access.
compass grounding-audit --project my-kb --eval-results cases.jsonl --verify-source

# Eval oracle (deterministic, no LLM): enrich an eval with KB-grounded signals, then measure how
# accurate the eval's OWN LLM judges are against that deterministic truth. LLM judges GUESS whether
# a response is grounded; COMPASS CHECKS it against the KB - so it can tell you which judge is right.
compass enrich --project my-kb --input eval.json --output enriched.json
compass calibrate-judges --input enriched.json --metric groundedness

# Close the loop: re-decide the eval's PASS/FAIL using deterministic truth instead of judge
# noise, and report every verdict that changed - cases the eval FAILED that are actually
# grounded (rescued), and cases it PASSED that contain a fabrication (demoted). Pure
# arithmetic over the enriched file: no KB, no LLM, no credentials. CI-ready exit codes.
compass quality-gate --input enriched.json --weights weights.json --threshold 0.80

# Before spending judge money: does each ground-truth answer make the key points declared for
# it? A point the reference itself does not make grades every real answer against a bar the
# reference cannot clear - and those failures look like model defects. Checks the GROUND TRUTH
# against itself, never the system's answers. Deterministic, no KB, no LLM.
compass gt-lint --input ground_truth.json --answer-field answer --points-field key_points

# Pre-flight: which cited document names actually resolve to a KB document? An unresolvable
# name makes every claim citing it unverifiable, so finding out from a finished report means
# paying for the run twice. Exits 1 if any name does not resolve.
compass grounding-audit --project my-kb --eval-results eval.json --check-aliases

# Is retrieval the problem, or is the KB? Compare retrieval configurations over the SAME
# validated KB using the eval's own ground-truth chunks - recall / precision / MRR / NDCG /
# hit rate. No LLM: a chunk is relevant because the ground truth says so.
compass benchmark --project my-kb --input eval.json

# Did the source content reach the store? Compares each document with its chunks: body text
# coverage, per-page coverage and numbers, with the passages behind every finding. See
# "Source fidelity" below. Report-only unless --fail-on-findings.
compass fidelity --project my-kb --sample 25 --format html --output reports/fidelity.html

# Is the re-ingested index better? Scores one eval against two ALREADY-BUILT indices and says
# which won on NDCG and on recall. Nothing is re-embedded. Warns when the indices were chunked
# differently, because document + page matching is then invalid (use --match content).
compass simulate --project my-kb --input eval.json --index-a kb_v1 --index-b kb_v2

# Is my chunker the right choice, before paying to re-embed? Rebuilds sampled documents from
# their chunks, re-chunks the same text, and reports mid-thought cuts, table/list splits, sizes,
# fragmentation and "worse on N of M documents". No embedder, no LLM, never a gate. Text rebuilt
# from chunks is lossy and understates what a fixed splitter does to raw tables.
compass chunk-eval --project my-kb --sample 50 --strategy fixed:3000/200 --strategy recursive:3000

# One verdict for the whole KB, composed from artifacts the commands above already wrote. See
# "KB readiness" below. No live connections. Exit 0 READY, 1 otherwise, 2 bad input.
compass readiness --project my-kb      # finds reports/my-kb-<stage>.json; or name each with a flag
# Do two environments hold the same KB? Documents missing either way, schema, e_tags that
# differ, pollution patterns, stale versions. Exits 0 no drift, 1 drift, 2 config error or could
# not compare: an environment that cannot be read is never reported as "no drift".
compass drift --project my-kb --env-a dev --env-b qa

# Audit traceability: does each sampled document still trace to its source? Classifies orphan /
# stale / broken-ref / no-version; a stage that cannot run says why. CSV for the auditor.
compass lineage --project my-kb --sample 200 --format csv --output lineage.csv

# Grounding dropped between runs - what changed? Attributes the regression to the documents
# responsible, ranked by share ("doc X REMOVED -> 40.0 pp across 8 cases"). A drop that no
# changed document explains is reported as unexplained, never spread to make totals reconcile.
compass diff --project my-kb            # or: --baseline run-a.json --current run-b.json

# Incremental discovery: re-validate only what changed (by content, not clock), plus a
# spot-check of the rest. Unchanged documents are reported as NOT re-validated, never as passed.
compass discover --project my-kb --since last-run
```

## Source fidelity

`compass fidelity` compares two extractions of a document, so it has to tell extraction noise from
loss. Both sides are normalised (Unicode, ligatures, hyphenation, markup, and spacing, including
gaps inside words), tables are judged by their numbers, and every exclusion is counted. Install a
better text layer with `pip install "compass-kb-validation[pdf-layout]"`, or `[pdf]` for the
lower-bound default.

Start report-only, and list what your pipeline drops on purpose until only real findings remain:

```yaml
eval:
  citation_source_key_fields: ["s3_key"]   # chunk field holding the source object key
  source_extractor: auto                   # auto | pymupdf | pdfplumber | pypdf | pdf_text
  fidelity:
    text_field: text                       # index field holding chunk text (not the eval file's)
    normalization: aggressive              # minimal | standard | aggressive
    match: shingle                         # shingle | exact
    coverage_min: {default: 0.90, quarterly: 0.97}   # keyed by document_type
    prefer_snapshot: true
    figure_regions: snapshot               # snapshot | off: numbers inside figures reported apart
    figure_types: [figure, chart, image]   # snapshot element types that are figures
    lost_passages_allowed: 0               # named lost passages tolerated (snapshot baseline)
    figure_words: gate                     # gate | report: lost words inside figures gate or not
    figure_match: words                    # words | run: a figure's label line is matched word by word
    locate_sample: false                   # true: faster chunk integrity and structure checks by a
                                           # sampled locate; their advisory counts can move slightly
    presence:                              # how a line is judged present (one test for everything)
      unit: line                           # each line on its own; lines are never joined
      match: tokens                        # tokens (default for a snapshot) | chars (for a text layer)
      run_tokens: 5                        # tokens: runs of this many words
      run_tolerance: 1                     # words of a run that may differ (a corrected typo)
      line_present: 0.5                    # share of a line's runs that makes it present
      min_line_chars: 12                   # shorter lines are not judged either way
      max_line_chars: 300                  # longer lines are judged sentence by sentence (0 = off)
    verify_scope: document                 # document | page: page also reports lines stored only
                                           # in another page's chunks (structure, not loss)
    partial_drop_floor: 0                  # e.g. 0.8: an element stored below this share is reported whole
    caption_max_chunk_gap: 1               # chunks a caption may sit from its figure
    tiers: {table: high, table_title: medium, number: high, source_note: high, heading: medium,
            figure: low, body: high, body_short: medium}
    tier_body_chars: 75                    # body text at or over this is "body", under it "body_short"
    gate_tiers: [high, medium, low]        # tiers whose pipeline drops gate
    source_figure_labels: figure           # figure | unknown: short source labels on a chart page
    show_nongating: collapsed              # collapsed | inline: non-gating evidence in the report
    probe_retrieval: off                   # off | lexical | vector: can retrieval surface the element
    probe_max: 200
    probe_k: 10                            # results read per probe
    probe_min_share: 1.0                   # share of the element's stored lines the top k must hold
    number_format: "1,234.5"               # or "1.234,5" | "1 234,5" | "1'234.5"
  source_exclusions:                       # nothing is excluded that is not listed here
    repeated_on_pages: 5                   # headers and footers
    min_chars: 75                          # small fragments (every element type)
    figure_min_chars: 75                   # figure text this short (an element or a lost piece of one)
    repeated_on_all_pages: false           # true: a line on every page of a short document is a header
    patterns: ["(?i)^past performance"]    # by-design notices
    line_patterns:                         # annotation lines an extractor writes into element text,
      image-note: "^\\[Image:"             # removed before comparison and counted per pattern;
      axis-years: "^(?:(?:19|20)\\d\\d\\s+){3,}(?:19|20)\\d\\d$"   # none ship built in
    page_roles: {disclaimer: "(?i)^important disclosures"}
    roles: [marginalia, logo, attestation] # read from a snapshot, so they need one
    must_retain: ["material change"]       # overrides every exclusion; missing is a loss
```

`fidelity` also runs the other way, chunk by chunk, and each chunk that does not trace is reported
by id: `WRONG_PAGE`, `ALTERED`, `TRUNCATED`, `OUT_OF_ORDER`, `UNTRACEABLE`, or `UNVERIFIABLE` where
the source has pages with no text layer. A consistent page shift is reported once. Tune it with
`eval.fidelity.page_tolerance` (default 1), `page_field`, `page_end_field` and `position_field`, or
turn it off with `chunk_integrity: false`.

Two outcomes are setup faults, never losses. A document whose chunks have no text in
`eval.fidelity.text_field` is not comparable, and the reason names the fields that do hold text.
A document where not one chunk traces to its source is `SOURCE_MISMATCH`: either the field or the
source key is wrong, or the store holds another document's text under that id. Neither is averaged
into coverage as a 0%. A snapshot that cannot be found is reported with the key it was looked for at.

**One presence test, line by line.** Whether text is stored is answered by one function
(`compass.presence`) for the gate, the finding, the retrieval probe, cross-index drift and the
report, with its settings under `eval.fidelity.presence` and its method carried in every result. Each
line is judged on its own; two lines never have to sit next to each other in the store, so a heading,
a sub-heading and a label stored in different chunks are stored. An element's share is the share of
its judged lines present, weighted by size. A line whose words are stored with a different number is
not missing text (the number check reports the change), and a typo the store corrected is tolerated
(`run_tolerance`).

What gates is what can be named. Against a snapshot, every element with lines the store lacks is a
finding that lists **its missing lines** and the element's line share, with its element type, page and
box, and one is enough for `CONTENT_LOSS` (`lost_passages_allowed` raises that). A number in body text that is not stored is
listed with its page and sentence. Numbers inside a figure region, and runs of evenly spaced numbers
such as an axis (`20.0% 22.0% 24.0%`), are reported apart as `figure_numbers` and never gate; words
inside a figure are still compared. Page coverage is shown as context, not as a gate. The JSON keeps
every finding, body text first; the console shows the first few. A caption or a `Source:` note
stored more than one chunk away from its figure is `CAPTION_DETACHED`, with both chunk ids. A
source that cannot be read (encrypted, image-only) is compared through its snapshot.

Each finding carries the kind of what is missing and a tier from `tiers`. A missing line takes its
own kind: in a table element a row is `table` and a line outside the rows (a title, subtitle or note)
is `table_title`, so a table whose cells are all stored but whose title is not is never reported as a
lost table; whether that gates is your `tiers` and `gate_tiers`. A table row held in a text element is
`table`, a heading element `heading`, a figure label `figure`, a line with a figure `number`, else
body text (`body` over `tier_body_chars`, `body_short` under). With `partial_drop_floor` set, an
element stored below that share is reported whole, as the first of those kinds its missing lines have.
Against a snapshot the coverage threshold does not gate (every missing line is already a named
finding); against a source text layer it does. A caption is located among the chunks of its own page,
never in a chunk of another page that repeats the same `Source:` line. Each gating finding names the
stored chunk of its page nearest its text. `--probe-retrieval lexical` asks whether retrieval can
surface the element: it queries with the element's **stored** lines (never the missing ones), scoped
to the document in the search itself, and counts a hit when the top `probe_k` chunks together hold
them, so an element split over chunks is still found.

The gate counts what the report shows. A document clears when the findings its verdict rests on
(the gating passages, or the numbers) are triaged `by_design` or `false`; extractor misses and
chunk-integrity rows around them need no triage. `readiness`, the fidelity page and the discover
report read the same post-triage counts, with figure-only drops stated apart.

Findings say what is missing, not who lost it, until you declare the extractor's own output. Any
extractor that writes JSON works: map its fields once, and each finding becomes `PIPELINE_DROP`,
`PIPELINE_ALTER` or `EXTRACTOR_MISS`.

```yaml
eval:
  snapshot:
    provider: storage_json
    location: "snapshots/{project}/{id}/{e_tag}/document.json"   # also {source_key}
    fallback_locations: ["backup/{e_tag}/document.json"]         # tried in order after it
    version: latest_with_elements          # current (default) | latest_with_elements
    format: my_extractor
    formats:
      my_extractor:                        # paths into the extractor's JSON
        elements: "metadata.element_list"
        type: "chunk_type"
        text: "text"
        order: "chunk_index"
        page: "grounding[0].page"          # [n] picks one item
        boxes: "grounding[*].box"          # [*] takes all: an element may have several boxes
        box_keys: [left, top, right, bottom]   # for boxes written as objects
        page_base: 0                       # the extractor counts pages from 0
        cells: "table.cells"
```

`version: latest_with_elements` reads older object versions when a later write replaced the element
list with a text-only file, or the key was deleted under bucket versioning. Each document's snapshot
is `present`, `superseded` (read from an older version or a fallback), `missing`, `wrong_shape` or
`unreadable`; the counts are in `snapshot_health`, and `readiness.min_snapshot_coverage` (0 to 1)
fails readiness when too few were read. `compass doctor` reads the snapshots of a few documents,
says which location and version holds the element list, and prints a `formats` entry to paste when
the mapping is wrong.

A passage the extractor produced and the store lacks is a pipeline drop, and it fails `readiness`
by default (`fidelity_pipeline_drop`); text missing from the extractor too stays advisory. Table
elements are compared like any passage, image links (`![name](url)`) and URLs are ignored on every
side, and a `Source:` line inside a text element is judged as a caption.

Structure is checked against the snapshot too, under `eval.structure` (every check reports "not
checked" when its input is missing): a heading stored with its section, a table in one chunk,
reading order, every page with text covered by a chunk, the page a chunk states, every source image
represented by a figure element, and pages whose text layer has no Unicode map. The chunk box and
chunk type checks run when the index carries those fields (`chunk_box_field`, `chunk_type_field`).
An extractor that writes headings as lines inside text elements (Markdown `# Title`, for example)
emits no heading element; set `eval.structure.heading_line_pattern` (a regex, e.g. `"^#{1,6} "`) and
the heading check judges each such line with the text after it.

Each gating finding opens one evidence view: the source page (the document's own text layer), the
extractor element, the nearest stored chunk and the retrieval probe side by side, with the missing
lines marked where they appear.

Index settings that change what every check reads:

```yaml
redis:
  text_field: content          # the field holding chunk text
  page_base: 0                 # the index counts pages from 0; every page is read 1-based
  production_index: kb_merged  # the index production queries; reports say when they read another
  near_duplicate_sample: 40    # vectors compared for near-duplicate embeddings
coverage: full                 # every sampled check reads every item, near-duplicates too (default: sampled)
triage_file: config/triage.yaml   # decisions kept between runs (see below)
```

**Triage.** `triage_file` lists decisions on findings: `{key, decision: defect | by_design | false,
reason, owner, expires}`. Every finding carries a stable id and a key (`check|index|document|chunk`,
globs allowed); `by_design` and `false` never gate, expired entries are ignored with a warning, and
`compass triage stats` reports each check's precision over the labelled entries. Findings are marked
new, still open or resolved against the previous run, and `--export-findings DIR` writes one file
per owner with index, chunk id, chunk index, page and a snippet. Ids are built from inputs only (the
document; for a lost passage its page, snapshot element and kind, or its first source line), never
from what the matcher reported, so a decision survives a change of matching. Entries for a command
that match none of its findings are listed as stale, and `compass triage migrate --file T
--old-report OLD.json --new-report NEW.json --output T2.yaml` re-keys entries written against an
earlier release's ids.

**Accept a release on your own KB.** `compass acceptance --report fidelity.json --expected
reference-kb.json` (or `acceptance.expected_file`) scores a run against a file listing, per index,
every element whose text is not stored (document, page, and optionally element type, kind, line
share and missing lines). It checks six criteria: gating findings name exactly the expected
(document, page), none missed or extra; each lists its missing lines and line share; expected kinds
match (a missing title is `table_title`); one document count across surfaces; ids stable against
`--previous`; and the retrieval probe finds every probed element. A criterion that could not be
judged is NOT RUN, never a pass, and the exit code is 0 only on PASS. `--write-expected FILE` builds a
starter file from a run, to check row by row in the store. The repository's own CI runs a synthetic
reference KB this way (`tests/acceptance_kb.py`).

**Run history and what it says.** Every `discover` and `validate` run is recorded in a SQLite file
(`trends.db_path`, default `validation_trends.db`; one file holds many projects): the run's document
outcomes (passed, failed, not checked), step and check totals, wall clock and summed time,
concurrency, config hash and coverage, COMPASS version, fidelity and tracked-finding counts; each
document's outcome, step statuses and times, failed and unrun checks, first failure message and
fidelity verdict; and per check how many documents passed, failed or could not run it. Older
databases are migrated in place. The report's Historical Trends section, the console and the JSON
output then say what the history shows: documents newly failing, fixed, still failing, added or
removed since the previous run; **flaky** documents (outcome flipped between passed and failed at
least `flaky_min_flips` times across comparable runs; a flip across a config or coverage change is
never counted); **chronic** documents (failed in every one of at least `chronic_min_runs` runs);
checks that are new, worse, better or cleared; steps whose time per document is `slower_ratio` times
their median and `slower_min_seconds` more; and a falling pass rate. Each document to watch has a
history strip, one cell per run. `compass trends [--project P] [--last N] [--json] [--export
[FILE]]` prints the same analysis and writes the runs and analysis as JSON (`compass-trends/1`,
default `.trends/trends.json`, e.g. for a CI cache); `trends.export_path` writes it after every run
and `trends.keep_runs` prunes old runs. Every threshold is `trends:` YAML; nothing is inferred by a
model.

```yaml
trends:
  db_path: validation_trends.db
  window: 20            # runs the analysis reads
  flaky_min_flips: 2
  chronic_min_runs: 3
  slower_ratio: 1.5
  slower_min_seconds: 1.0
  keep_runs: 0          # 0 keeps every run
  export_path: ""       # e.g. .trends/{project}.json
```

**Several indexes.** `discover` lists other indexes in the same store holding the same sources, and
`compass drift --project P --index-a A --index-b B` reports, per source document, content present
in one index and missing from the other, judged line by line with the same presence test
(`drift.cross_index.min_share`, default 0.5; findings list the missing lines). Markup (links, images,
HTML and table tags, entities) is removed before matching, and with `drift.cross_index.type_field` set, chunks of `generated_types` (chart and figure
descriptions each pipeline words its own way) are compared apart (`generated: separate`, default)
or skipped (`skip`), never reported missing. Chunk integrity reads the same chunk type from
`eval.structure.chunk_type_field`: a chunk of a `chunk_figure_types` type is generated text, left
out of "traced N of M", and the share of generated text in mixed chunks is reported apart.

**Document metadata.** The opt-in `metadata_checks` step (name it in `pipeline.steps`) checks that
date fields agree with each other and with the file name, that each document type carries its
period fields, that a type sits in its folder, and that chunks were ingested after the source last
changed. Every field, pattern and map is set under `metadata_checks:`. With `version_field` naming the
chunk field that holds the source version (`e_tag`), a source re-uploaded with the same bytes after
ingestion is not flagged.

### KB readiness

`compass readiness --discover D.json [--grounding G.json] [--benchmark B.json] [--drift X.json]
[--project P] [--format console|json|html] [--output F]` reads JSON the other commands wrote and
returns READY, AT RISK or NOT READY, with a stage and an owner (ingestion, retrieval config,
generator) for every finding. A stage whose artifact is absent, or which measured nothing, is
**not examined** and caps the verdict at AT RISK: never READY by omission. With `--project`, a stage
no flag names is read from `readiness.artifacts` (`{stage: path}`), then from
`reports/<project>-discovery-report.json` and `reports/<project>-<stage>.json` for `benchmark`,
`grounding`, `drift` and `fidelity`. A stage still missing names the command that writes it. `gate` means NOT READY,
`risk` means AT RISK, `advisory` is reported and changes nothing.

Every stage line says what set its status (`AT RISK: <finding id> - <detail>; <what was
measured>`) and the JSON stage carries `basis` (the finding ids). Retrieval with no
`readiness.min_recall` reads **NOT GATED**: the recall is shown, nothing is concluded from it, and
it is neither green nor a failure (it neither caps the verdict nor changes the exit code).

A document where no check failed but a check that should have run could not (`status: not_run`
on the check row) is **not checked**, not passed: discover reports `passed`, `failed` and
`not_checked` separately, the ingestion stage reads `156 of 157 document(s) passed, 1 not checked`,
and the corpus verdict is capped at AT RISK. A check that does not fit the store
(`status: not_applicable`) is neutral and is not counted against anything.

Every verdict carries `verified` / `unverifiable` / `not-checked` counts, and `discover` prints and
exports the same block (`coverage` in the JSON). `unverifiable` means it was attempted and could not
be compared, with the reason; `not-checked` means nobody tried. A fidelity comparison that never ran
reads `content-fidelity: not-checked`, under a READY too when the stage is waived. This is reporting:
it changes no verdict.

| Finding | Default | Owner |
|---------|---------|-------|
| `corpus_not_ready` | gate | ingestion |
| `documents_failed` (report has no corpus verdict) | gate | ingestion |
| `grounding_ingestion_loss` (proven at Level 3) | gate | ingestion |
| `grounding_generation_proven` (proven at Level 3) | gate | generator |
| `retrieval_below_floor` (only with `min_recall` set) | gate | retrieval config |
| `grounding_below_floor` (only with `min_kb_confirmed_pct` set) | gate | generator |
| `corpus_at_risk` | risk | ingestion |
| `corpus_verdict_missing` * | risk | ingestion |
| `documents_unexamined` * (skipped, pending or empty checks) | risk | ingestion |
| `checks_not_run` * (a backend such as the PDF reader failed to load) | risk | ingestion |
| `partial_run` * (`discover --since`) | risk | ingestion |
| `retrieval_query_errors` * | risk | retrieval config |
| `retrieval_found_nothing` | risk | retrieval config |
| `grounding_retrieval_gap` | risk | retrieval config |
| `grounding_generation` (unproven) | risk | generator |
| `grounding_wrong_count` | risk | generator |
| `grounding_fabricated_source` | risk | generator |
| `drift_detected` | risk | ingestion |
| `fidelity_content_loss` | advisory | ingestion |
| `fidelity_numbers_missing` | advisory | ingestion |
| `fidelity_value_drift` | advisory | ingestion |
| `fidelity_source_mismatch` | risk | ingestion |
| `fidelity_caption_detached` | risk | ingestion |
| `fidelity_extractor_gap` (source text the extractor did not produce) | advisory | ingestion |
| `fidelity_pipeline_drop` (passages the extractor produced, missing from the store) | gate | ingestion |
| `fidelity_triage_stale` | advisory | ingestion |
| `fidelity_lines_elsewhere` | advisory | ingestion |
| `structure_findings` | advisory | ingestion |
| `fidelity_documents_unverifiable` * (could not be compared) | risk | ingestion |
| `fidelity_snapshot_coverage` * (below `readiness.min_snapshot_coverage`) | gate | ingestion |
| `chunk_integrity_findings` | advisory | ingestion |
| `stale_versions`, `stale_versions_unchecked` | advisory | ingestion |
| `documents_within_threshold` | advisory | ingestion |
| `grounding_direction_mismatch` (word-adjacency heuristic) | advisory | generator |
| `grounding_citation_error`, `grounding_mostly_unverifiable` | advisory | generator |
| `retrieval_no_floor`, `retrieval_unfiltered`, `retrieval_cases_excluded`, `retrieval_unreviewed_set` | advisory | retrieval config |
| `retrieval_empty_under_filter` | advisory | ingestion |

\* A "could not check" finding: it can be raised to `gate`, never lowered to `advisory`.

Change the table per project. An unknown key exits 2, because a typo here would turn a gate off:

```yaml
readiness:
  severity: {stale_versions: risk, grounding_direction_mismatch: gate}
  waived_stages: [drift]     # stages this project does not run, so absence stops capping
  min_recall: 0.6            # 0 = no floor: recall is reported, not gated
  min_kb_confirmed_pct: 80
```

`enrich` adds a `compass` block per case (a **citation grounding rate** over the verifiable
citation+numeric subset, citation fidelity, chunk quality, context utilization, `COMPASS_*` signal
codes). Each citation also carries a **graduated support tier** — `SOUND` / `LIKELY_SOUND` (≥70% of
its values found) / `PARTIAL` / `UNSUPPORTED` — reported alongside the strict rate, so a near-miss
is not filed next to a fabrication. Short cited tokens ("WIU", "Q3 QIP") resolve automatically
against the index's own document names; a token owned by two documents resolves to nothing rather
than guessing. It is **schema-agnostic** — every field resolves through your `eval.gt_*` config, so it
works whatever shape your eval JSON takes. `calibrate-judges` then reports each judge's error,
bias, accuracy, and an evidence-based **recommended weight** — something no eval framework can
compute, because it needs KB access.

`migrate` and `coverage` also render a **self-contained HTML report** (same look as the
validation dashboard) with `--html [path] --open` — a coverage heatmap, a migration
stability distribution, verdicts, and the most-changed / dead-zone tables.

> Same boundary as the gate: these never *judge answer quality* (that's the eval layer) and
> never put an LLM in a pass/fail decision. `migrate` and `coverage` share one deterministic
> retrieval-analysis engine (sample → in-memory KNN → neighbor/reachability analysis).

### Catch regressions over time (baselines + drift)

Snapshot a known-good run, then diff later runs against it — so a scheduled check is a
gate, not just a report:

```bash
compass discover --project my-kb --save-baseline          # freeze a green run -> baselines/my-kb.json
# ...later (cron / CI)...
compass discover --project my-kb --against baselines/my-kb.json --fail-on-regression
```

Drift flags what a single run can't: **dropped documents**, docs that **passed before and
fail now** (and which checks newly fail), **index drift** (embedding dimension / distance
metric changed under you), and **readiness / pass-rate decline**. `--fail-on-regression`
makes the run exit non-zero, so cron or CI alerts on degradation. (`compass check` takes
the same `--save-baseline` / `--against` flags.)
```

> From source instead of PyPI: `git clone … && cd compass && pip install -e ".[all]"`.

### Running scenarios without editing YAML

`compass-discover` takes overrides that win over config + profiling, so you can try
different shapes and policies from the command line:

```bash
# Point at a different index/identity, faster, and relax the readiness bar
compass-discover --project my-kb --parallel --workers 8 \
  --id-field agent_id --expected-dim 1024 \
  --readiness-threshold 0.99 \
  --disable-check chunk_count near_duplicate_embeddings \
  --severity duplicate_detection=hard \
  --unreachable-as skipped
```

Severity model: every vector check is **HARD** (gates the run) or **WARN** (advisory).
`--severity name=hard|warn` (or `redis.check_severity` in YAML) promotes/demotes any
check; `--list-checks` shows the defaults.
> Releases are published via [PUBLISHING.md](PUBLISHING.md).

Reports are written to `reports/` (HTML dashboard + JSON + JUnit XML). Add
`--live` to open a real-time progress dashboard, `--no-trends` to skip recording run history,
`--parallel` for concurrency.

### Try it locally (no cloud needed)

A self-contained Docker stack runs the full pipeline against MinIO + Redis Stack +
a mock ingestion API — see **[integration/README.md](integration/README.md)**.

## Project Structure

```
compass/
├── run_validation.py              # Entry point — live ingestion validation
├── discover_and_validate.py       # Entry point — post-hoc discovery
├── compass/          # Main package
│   ├── models/                    # StepResult / PipelineResult (stdlib dataclasses)
│   ├── config/                    # Layered YAML config + typed Settings
│   ├── utils/                     # Run-id, logging, polling w/ backoff
│   ├── providers/                 # Pluggable backends via a registry:
│   │   ├── storage.py             #   object storage (S3-family…)
│   │   ├── vectorstore.py         #   vector store (Redis, Qdrant, pgvector, Chroma…)
│   │   ├── graph.py               #   knowledge graph (SPARQL, Neptune…)
│   │   ├── embedding.py           #   text→vector for query (OpenAI/Azure/Bedrock)
│   │   └── source.py              #   document discovery (storage|index|manifest)
│   ├── validators/                # BaseValidator + step registry + the steps
│   │   └── registry.py            #   declarative pipeline (StepSpec registry)
│   ├── pipeline/                  # Orchestrator (context propagation, halting)
│   ├── report/                    # Self-contained HTML dashboard + JSON/JUnit
│   ├── cli.py                     # Unified `compass` CLI (all subcommands)
│   ├── ask.py                     # `compass ask` — deterministic NL retrieval
│   ├── mcp_server.py              # `compass mcp` — agent-callable KB tools (stdio)
│   ├── retrieval_analysis.py      # engine for `migrate`/`coverage`/`compare` (read-only)
│   ├── eval_interop.py            # vendor-neutral eval export + ground-truth reader
│   ├── corpus.py                  # Corpus-level KB readiness analysis
│   ├── live_dashboard.py          # FastAPI + SSE real-time dashboard
│   ├── notifications.py           # Slack / Teams webhooks
│   ├── trend_tracker.py           # SQLite historical trends
│   └── trend_analysis.py          # what the run history says (compass trends)
├── config/{base.yaml, projects/_template.yaml}
├── test_data/_template.yaml       # Documents to validate (live mode)
├── integration/                   # Local Docker integration stack
├── tests/                         # Unit tests (backends faked — no live services)
└── reports/                       # Generated reports (gitignored)
```

## Documentation

- **[QUICKSTART.md](QUICKSTART.md)** — pip install → a gating CI check in five steps
- **[ARCHITECTURE.md](ARCHITECTURE.md)** — how COMPASS is built: layers, data flow, the registries, the two run modes, extension points
- **[CONTRACT.md](CONTRACT.md)** — the Knowledge-Base Contract: express your KB's guarantees as one declarative artifact, with each clause mapped to the command/flag that enforces it in CI
- **[CASE_STUDIES.md](CASE_STUDIES.md)** — the reproducible benchmark story in full, plus templates for real-outcome case studies (missing docs, filter regressions, migration drift, orphan chunks)
- **[benchmark/](benchmark/)** — the broken-KB benchmark: injects realistic faults and scores detection rate (currently **16/16**) vs false-positive rate (**0/6**)
- **[SUPPORT.md](SUPPORT.md)** — backend support matrix (which backends are *verified* vs *adapter-available*)
- **[COMPATIBILITY.md](COMPATIBILITY.md)** — stability & versioning policy: what's stable, what's evolving, deprecation & pinning
- **[EXTENDING-BACKENDS.md](EXTENDING-BACKENDS.md)** — add a new backend (storage/vector/graph/source) or a new pipeline step
- **[integration/README.md](integration/README.md)** — run the full pipeline locally on Docker
- [CONTRIBUTING.md](CONTRIBUTING.md) · [SECURITY.md](SECURITY.md)

## Configuration

All behaviour lives in YAML; credentials are referenced by **environment-variable
name** and resolved at runtime (never stored in config). `config/base.yaml` holds
shared defaults; each `config/projects/<name>.yaml` overlays only what differs and
selects a `dev`/`staging`/`prod` environment block.

```yaml
# config/projects/my-kb.yaml
display_name: "My Knowledge Base"

# Declarative pipeline — choose which steps run, in what order (registry keys).
# Omit to use the full default pipeline.
pipeline:
  steps: [api_upload, s3_storage, redis_chunks, retrieval_quality]
  critical_steps: ["API Upload", "S3 Storage"]   # failure here halts the run

# Where post-hoc discovery finds documents: storage | vectorstore | manifest
discovery:
  provider: vectorstore           # enumerate the KB straight from the index

environments:
  dev:
    api:
      base_url_env: API_BASE_URL          # env-var NAME, not the value
      graphql_mutation: |
        mutation ($file: Upload!, $metadata: JSON) { uploadDocument(file:$file, metadata:$metadata){ status document_id } }
    s3:
      provider: s3                        # s3 | minio | r2 | azure_blob | gcs | local …
      bucket_name: my-documents
      prefix: knowledge-base/
    redis:
      provider: redis                     # redis | qdrant | pinecone | pgvector …
      search_index: my_embeddings
      text_field: text                    # the field holding chunk text (content, page_content, ...)
      expected_embedding_dim: 1536
      expected_distance_metric: COSINE
```

`redis.chunking_strategy` selects the chunk checks. Under anything but `fixed`, size-derived checks
stop applying and advisory checks take over: fragmentation, summary presence, `element_integrity`
(a chunk holding part of a table, list or code block), `boundary_on_structure` (a boundary inside
one, which needs a positional field) and `cap_truncation` (a chunk at `max_chunk_size` that ends
inside one). A structure continuing onto the next page, a mid-sentence end and a heading left at a
chunk's tail are how layout chunkers work, and are not counted. The strategy comes from the chunks
when `redis.chunker_field` and `chunker_strategy_map` are set, else from `chunking_strategy`. A
project that declares neither is scored exactly as before: where the chunks are clearly not
fixed-size and carry a summary or markdown structure, the structural rows appear marked `inferred`,
with their evidence, and are never scored.

`embedding.input_fields`, `input_joiner` and `input_truncation` declare what the pipeline embeds, so
the embedding probes re-embed that and nothing else. `embedding.sync_check` (off by default) has
`discover` re-embed a sample and name chunks whose vector does not match; a chunk missing a declared
field is unverifiable, not out of sync, and `tokens:N` truncation is reported, never estimated.

`discover --since` re-validates a document when its ETag, its chunk count, or (where the store can
list them in one aggregation: Redis today) its chunk ids or `redis.chunker_version_field` value
changed. The id hash is over sorted ids, so it sees a changed set rather than a reordering, and ids
built from document + position do not change under a same-count re-chunk: point
`redis.chunk_id_field` at a content hash if the pipeline stores one.

## Advanced Usage

### Add a custom pipeline step

Steps are declarative — register a validator and reference it in `pipeline.steps`:

```python
from compass.validators.base import BaseValidator
from compass.validators.registry import register_step, StepSpec
from compass.models import StepResult, StepStatus

class PiiRedactionValidator(BaseValidator):
    step_name = "PII Redaction"
    def __init__(self, config): self.config = config
    def validate(self, context: dict) -> StepResult:
        return StepResult(self.step_name, StepStatus.PASSED, "no PII leaked")

register_step(StepSpec(
    key="pii_redaction", name="PII Redaction",
    factory=lambda settings, shared: PiiRedactionValidator(settings.s3),
    abbr="PII", order=25,
))
# then:  pipeline.steps: [api_upload, pii_redaction, redis_chunks]
```

The orchestrator, live dashboard, and HTML report adapt automatically. See
**[EXTENDING-BACKENDS.md](EXTENDING-BACKENDS.md)** for adding backends too.

### CI/CD integration — the readiness gate

COMPASS is built to run **before** your agents or eval consume the knowledge
base: wire it into the pipeline that publishes the KB and fail the build when
the KB is not retrieval-ready. Every entry point returns a CI-friendly exit
code — **0 = gate passed, 1 = gate failed, 2 = config error** — and emits JUnit
XML for any CI system.

> **Reliable exit codes:** invoke the gate via `python -m compass discover …`
> or the `compass-discover` console script — both `sys.exit()` the code directly. Avoid
> piping (`… | tee`) which returns the pipe's exit code, and note that the `compass` shim in
> Git-Bash on Windows can drop the code. To verify in a shell: `… ; echo $?` (bash) or
> `…; echo $LASTEXITCODE` (PowerShell).

**Gate strictness** (discovery mode) is yours to choose:

```bash
# Strictest: any failed document fails the build (default)
compass-discover --project my-kb

# Tolerate a few failures: require >= 95% of documents to pass
compass-discover --project my-kb --fail-under 95

# Also require the corpus to be READY (completeness/coverage/dedup verdict)
compass-discover --project my-kb --require-ready
```

**GitHub Actions** — drop the reusable action into your KB pipeline:

```yaml
# .github/workflows/kb-readiness.yml
jobs:
  kb-readiness:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4              # your repo holds config/projects/<name>.yaml
      - uses: TestAutomationArchitect/compass@v1
        with:
          project: my-kb
          require-ready: "true"                # block promotion unless READY
          # fail-under: "95"                   # ...or tolerate a bounded failure rate
        env:
          REDIS_HOST: ${{ secrets.REDIS_HOST }}   # config references env-var names; supply them here
```

A full example you can copy is in **[examples/kb-readiness.yml](examples/kb-readiness.yml)**.

**Container** — no Python setup needed; works in any CI or a self-hosted runner:

```bash
docker build -t compass:latest .
docker run --rm -v "$PWD:/work" --env-file .env \
  compass:latest compass-discover --project my-kb --require-ready
```

## Applicable Domains

Enterprise document management · legal/compliance · healthcare · financial
research · customer-support KBs · internal wikis · e-commerce catalogs · academic
repositories — any RAG/agent knowledge base built from a document pipeline.

## License

MIT License — see [LICENSE](LICENSE).
