Skip to main content
Glama
README.md
# open-pcv

Deterministic checking of model-written proof certificates, monotonic repair of drafts, and an MCP server so open and local LLM agents can show their evidence.

A language model that cites sources can misquote them, drop a qualifier, or stretch a finding to a population the source never studied. open-pcv makes the model emit a structured certificate for each claim (`pcv-cert-v1`). Plain code then checks that certificate with no model calls: every quoted passage must exist verbatim in a hashed source snapshot, the claim's spans must reproduce the claim word for word, the five scope checks must be present, and the verdict must follow from them. A certificate that fails any check is downgraded to `NOT_ENOUGH_EVIDENCE`. Nothing is ever upgraded.

This repository is version 0.1.0. It is the prototype checker extracted into a standalone package, plus the data and scripts behind my preliminary results.

## What it checks, and what it does not

It checks structure, provenance and explicit scope assessments:

- Every evidence passage is selected by ID from numbered passages of the cited source, or quoted exactly (whitespace aside), and lies within one contiguous segment of the source text.
- The claim is split into 1 to 12 ordered spans that reproduce it exactly. A dropped qualifier, an added word or a changed number fails.
- `subject` and `authority` are always assessed. `time`, `population` and `conditions` are assessed or explicitly marked not applicable.
- `SUPPORTED` requires every span to be entailed by applicable evidence with no mismatched or unknown dimension. Missing measurements and examples cannot establish a real-world outcome.
- `REFUTED` requires an exact counter-quote from the selected evidence. A counter-quote that only says a value is unknown, unresolved or not measured is not a refutation.
- A certificate bound to a snapshot digest is rejected against any other snapshot, and a snapshot whose text no longer matches its hashes is rejected outright.

It does not establish semantic truth. A model can still label a real but irrelevant passage as entailing a claim, and the structural check will pass it. The full pipeline adds an independent Stage-2 relation review for that, and high-stakes use still needs human audit. It is also not a formal proof system: there is no Lean or Coq here, only deterministic validation code inspired by proof-carrying code.

## Quickstart

Requires Node.js 20 or newer. There are no runtime dependencies and no build step.

```sh
git clone https://github.com/ahrufcodes/open-pcv.git
cd open-pcv
npm test                         # checker invariants, repair, MCP server, reproduction, data audit
npm run reproduce                # recompute every published table from raw results, offline
node examples/verify-demo.mjs    # accept a valid certificate, reject a tampered one, repair a draft
```

Run the diagnostic suite against a local model (Ollama by default):

```sh
ollama pull qwen2.5:7b-instruct
npm run eval:local -- --model qwen2.5:7b-instruct --limit 20
npm run eval:local -- --base-url http://localhost:8080/v1 --model local   # llama.cpp server
npm run eval:local -- --help
```

Use it from goose: see [examples/goose-extension.md](examples/goose-extension.md).

```sh
goose session --with-extension "node /path/to/open-pcv/bin/pcv-mcp.mjs"
```

## Library

Until the package is on npm, install it from git (`npm install github:ahrufcodes/open-pcv`) or import `src/index.mjs` directly.

```js
import { snapshotSources, verifyCertificate, applyMonotonicRepair } from "open-pcv";

const snapshot = snapshotSources([
  { text: pageText, url: "https://example.org/study", tool: "web_fetch" },
]);
// snapshot.sha256 is the digest; snapshot.sources[0].passages are [{ id: "1:0", quote }, ...]

const result = verifyCertificate(certificateFromModel, snapshot);
// { verdict: "SUPPORTED" | "REFUTED" | "NOT_ENOUGH_EVIDENCE", accepted, downgraded, failure? }
```

Public API (types in [types/index.d.ts](types/index.d.ts)):

| Export | Purpose |
| --- | --- |
| `validateEvidenceMatch(proof, verdict, sources, claim?, expectedAssertions?)` | The core checker. Returns the verdict, or `NOT_ENOUGH_EVIDENCE` with a failure reason. |
| `verifyCertificate(cert, snapshotOrSources)` / `verifyReport(...)` | Check `pcv-cert-v1` certificates, including the snapshot binding. |
| `snapshotSources(sources)` / `verifySnapshot(snapshot)` | Freeze documents or tool outputs into numbered passages with SHA-256 hashes. |
| `applyMonotonicRepair({ draft, verifiedSpans, patches, sources })` | Per-span monotonic repair (below). |
| `claimAssertionSpans` (alias `extractClaimSpans`) | Check that spans reproduce a claim exactly. |
| `sourcePassages` (alias `extractSourcePassages`) | Number the passages of one source. |
| `sameAssertionText` | Compare two spans, ignoring presentation only. |
| `validateRelationshipReview` | Provenance checks for an independent Stage-2 relation review. |
| `STAGE1_SYSTEM_PROMPT` | The prover prompt used by `eval:local`. |

## The certificate

[`schemas/pcv-cert-v1.schema.json`](schemas/pcv-cert-v1.schema.json) (JSON Schema Draft 2020-12) defines the format. In short:

```json
{
  "schema": "pcv-cert-v1",
  "claim": "Fertilizer F raised tomato yield by 12% in a randomized greenhouse trial [1].",
  "verdict": "SUPPORTED",
  "sourceSnapshotSha256": "8fa7...",
  "checks": {
    "subject":    { "status": "matched", "claimScope": "...", "sourceScope": "..." },
    "authority":  { "status": "matched", "claimScope": "...", "sourceScope": "..." },
    "time":       { "status": "not_applicable" },
    "population": { "status": "matched", "claimScope": "...", "sourceScope": "..." },
    "conditions": { "status": "matched", "claimScope": "...", "sourceScope": "..." }
  },
  "passages": [{ "citationNumber": 1, "passageId": "1:0" }],
  "assertions": [{
    "text": "Fertilizer F raised tomato yield by 12% in a randomized greenhouse trial [1].",
    "relation": "entailed", "claimType": "world_fact", "basis": "measurement",
    "explanation": "The trial reports a 12% yield gain.",
    "passages": [{ "citationNumber": 1, "passageId": "1:0" }]
  }]
}
```

Passing the schema only means the certificate is well formed. The checker decides whether it is accepted.

## Monotonic repair

`applyMonotonicRepair` fixes a draft without damaging the parts that were already right:

1. Spans already verified are copied to the output byte for byte. That is a property of the code, so the 100% preservation figure for MPR below is a guarantee, not an empirical finding.
2. A patch replaces an unverified span only if it carries a `pcv-cert-v1` certificate for exactly the patch text and that certificate checks out as `SUPPORTED`.
3. Every other unverified span is withheld, and the result says which spans were withheld and why.

I have not yet measured how withholding affects fluency and coreference.

## MCP server and goose

`bin/pcv-mcp.mjs` is an MCP server over stdio (JSON-RPC 2.0, newline-delimited or `Content-Length` framed). It exposes `pcv_snapshot_sources`, `pcv_verify_certificate`, `pcv_verify_report`, `pcv_check_spans`, `pcv_apply_monotonic_repair` and the alias `pcv_repair_monotonic`. Snapshots are cached for the session, so an agent can refer to one by its digest. Setup for goose is in [examples/goose-extension.md](examples/goose-extension.md).

## Local models and untrusted provers

`scripts/eval-local.mjs` sends Stage-1 proof generation to any OpenAI-compatible endpoint (Ollama, llama.cpp server, vLLM, a mesh-llm node or a hosted API) and checks each certificate in the local process. The endpoint is treated as untrusted. A dishonest or broken prover can waste compute or force abstention, but it cannot make fabricated evidence pass. The test suite demonstrates this with a mock endpoint that fabricates quotes.

This runner uses a simple one-claim-per-call prompt. It is not the batched harness behind the published numbers, so expect different results. I have not yet run local 7B to 70B models; that is planned work.

## Preliminary results

`npm run reproduce` recomputes these from the raw per-claim records in [`data/results/`](data/results/) and checks 90 published numbers. The runs used cloud endpoints. DeepSeek V4 Pro and Kimi K3.1 Pro are open-weight-lineage models; GPT-6 Sol and Claude Opus 5.5 are closed.

The diagnostic suite is 110 cases I built from failure modes I logged in my own work (50 `SUPPORTED`, 16 `REFUTED`, 44 `NOT_ENOUGH_EVIDENCE`), run on four models for 440 paired runs. It is an internal suite, not an independent benchmark. See [benchmarks/diagnostic-110](benchmarks/diagnostic-110/).

| Condition (4-lab pooled, n = 440) | Acc | Decisive errors | FCR | Tokens/claim |
| --- | ---: | ---: | ---: | ---: |
| `vanilla` LLM judge | 86.6% | 56 (12.7%) | 5.4% | 361 |
| `cot_quote@1` (quote + reasoning) | 87.7% | 52 (11.8%) | 4.6% | 515 |
| `cot_quote@5` (5x majority vote), see note | 80.7% | 79 (18.0%) | 5.8% | 2,255 |
| `pcv_no_gate` (PCV prompts, no code check) | 92.0% | 33 (7.5%) | 3.3% | 3,677 |
| `pcv_no_rel` (+ deterministic proof gate) | 96.6% | 10 (2.3%) | 2.1% | 3,677 |
| Full PCV v2 (gate + Stage-2 relation review) | 96.6% | 3 (0.7%) | 0.0% (0/240) | 3,609 |
| Cross-Batch Pooled Adaptive PCV | 96.4% | 7 (1.6%) | 1.7% (4/240) | 1,699 |

FCR is the false certification rate: the share of claims whose gold label is not `SUPPORTED` that were certified `SUPPORTED`.

Caveats I want to be explicit about:

- `cot_quote@5` is indicative only. It used a simpler two-sentence prompt instead of the four-step rubric, and the requested temperature of 0.4 was unsupported on 3 of 4 endpoints.
- Under Full PCV v2 the two open-lineage models reached 95.5% accuracy with 0/120 false certifications, against 92.7% for the closed models without PCV. The closed models with PCV score higher still (97.3% to 98.2%). The point is that verification closes the gap, not that open models win outright.
- DeepSeek V4 Pro drops to 90.9% accuracy and 5.0% FCR under pooled cross-fixture batching, so the cheaper mode is not yet safe for every model.
- When a certificate still fails after its one retry, the pipeline falls back to `NOT_ENOUGH_EVIDENCE`. That happened on 5/110 DeepSeek cases under Full PCV v2; if those fallbacks earn no credit, its 95.5% becomes 93.6%.

Ecological repair on 16 real briefs (360 raw claims, 4 domains), graded by a cross-family PCV LLM audit rather than human labels:

| | Self-Refine | Per-span MPR |
| --- | ---: | ---: |
| Verified sentences kept verbatim | 15/163 (9.2%) | 163/163 (100%, by construction) |
| Residual unsupported claims | 29.8% (141/473) | 6.3% (20/320) |
| Verified claims delivered | 332 | 300 |
| Uncited sentences added | 35 | 0 |

Self-Refine delivered more verified claims, mostly by growing drafts from 360 to 473 claims. MPR withheld 48 spans it could not fix.

A 300-claim blind dual-human evaluation is collecting ratings. No human gold labels are finalized yet.

## Repository layout

```
src/                   checker, snapshots, certificates, monotonic repair, prompts (plain ESM)
types/index.d.ts       TypeScript declarations
schemas/               pcv-cert-v1 JSON Schema
bin/pcv-mcp.mjs        MCP stdio server
examples/              goose setup, runnable demo
benchmarks/diagnostic-110/   the 110-case diagnostic suite
data/results/          raw results behind the published tables
scripts/               reproduce, eval-local, data audit
test/                  node:test suite
```

## Roadmap

Planned, not done: a Python package held to the same conformance tests, schema-constrained and span-constrained decoding on llama.cpp and vLLM, a mesh-llm untrusted-peer mode, a small open verifier model, optional Ed25519 signing of certificates, and OpenPCV-Bench with blind dual-human labels on a neutral host. Schema changes will go through public issues.

## Disclosure

I also run BINTEX, a commercial research tool where I first ran into these failure modes, and the checker here is a standalone port of code I wrote and own there. open-pcv contains no BINTEX application code, is released irrevocably under Apache-2.0, and BINTEX uses it on the same terms as anyone else.

## License

Code and schemas: [Apache-2.0](LICENSE). Benchmark fixtures and results: CC-BY-4.0, with third-party excerpts credited to their sources (see [NOTICE](NOTICE)).

Security issues: see [SECURITY.md](SECURITY.md). Contributions: see [CONTRIBUTING.md](CONTRIBUTING.md).