Metadata-Version: 2.4
Name: receiptdb
Version: 1.0.0rc1
Summary: Provenance-native storage for AI-derived data: receipts, label inheritance, cascading retraction and policy-filtered retrieval on PostgreSQL.
Author: Counterfoil Labs
License-Expression: FSL-1.1-ALv2
Project-URL: Homepage, https://counterfoillabs.com
Project-URL: Documentation, https://github.com/counterfoillabs/receiptdb/tree/main/docs
Project-URL: Source, https://github.com/counterfoillabs/receiptdb
Project-URL: Issues, https://github.com/counterfoillabs/receiptdb/issues
Project-URL: Changelog, https://github.com/counterfoillabs/receiptdb/blob/main/CHANGELOG.md
Keywords: provenance,data-lineage,rag,ai-agents,langchain,llamaindex,haystack,semantic-kernel,agent-memory,vector-search,data-governance,postgresql,pgvector
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Database
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: psycopg[binary]>=3.2
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-timeout>=2.3; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Requires-Dist: hypothesis>=6.100; extra == "dev"
Requires-Dist: schemathesis>=4.0; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: standardwebhooks>=1.0; extra == "dev"
Requires-Dist: jsonschema>=4.18; extra == "dev"
Requires-Dist: pypdf>=6.21.4; extra == "dev"
Requires-Dist: pyyaml>=6; extra == "dev"
Requires-Dist: markdown-it-py>=3; extra == "dev"
Provides-Extra: live
Requires-Dist: anthropic>=1.8; extra == "live"
Requires-Dist: sentence-transformers>=6; extra == "live"
Provides-Extra: anthropic
Requires-Dist: anthropic>=1.8; extra == "anthropic"
Provides-Extra: langchain
Requires-Dist: langchain-core>=1.0; extra == "langchain"
Provides-Extra: demo
Requires-Dist: langchain-core>=1.0; extra == "demo"
Requires-Dist: numpy>=2; extra == "demo"
Provides-Extra: langgraph
Requires-Dist: langgraph-checkpoint>=4; extra == "langgraph"
Provides-Extra: llamaindex
Requires-Dist: llama-index-core>=0.14; extra == "llamaindex"
Provides-Extra: haystack
Requires-Dist: haystack-ai>=3.3; extra == "haystack"
Provides-Extra: semantic-kernel
Requires-Dist: semantic-kernel>=1.45; extra == "semantic-kernel"
Provides-Extra: mcp
Requires-Dist: mcp>=2.2; extra == "mcp"
Requires-Dist: sentence-transformers>=6; extra == "mcp"
Provides-Extra: bedrock
Requires-Dist: boto3>=1.34; extra == "bedrock"
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.25; extra == "otel"
Requires-Dist: opentelemetry-sdk>=1.25; extra == "otel"
Requires-Dist: opentelemetry-exporter-otlp>=1.25; extra == "otel"
Provides-Extra: client
Requires-Dist: httpx>=0.27; extra == "client"
Provides-Extra: importers
Requires-Dist: httpx>=0.27; extra == "importers"
Provides-Extra: promptguard
Requires-Dist: transformers>=4.46; extra == "promptguard"
Requires-Dist: torch>=2.3; extra == "promptguard"
Provides-Extra: pii
Requires-Dist: presidio-analyzer>=2.2; extra == "pii"
Provides-Extra: pdf
Requires-Dist: pypdf>=6.21.4; extra == "pdf"
Provides-Extra: office
Requires-Dist: python-docx>=1.1; extra == "office"
Requires-Dist: python-pptx>=1.0; extra == "office"
Provides-Extra: server
Requires-Dist: fastapi>=0.118; extra == "server"
Requires-Dist: uvicorn[standard]>=0.30; extra == "server"
Requires-Dist: psycopg-pool>=3.3; extra == "server"
Requires-Dist: prometheus-client>=0.20; extra == "server"
Requires-Dist: httpx>=0.27; extra == "server"
Requires-Dist: mcp>=2.2; extra == "server"
Requires-Dist: pyjwt[crypto]>=2.8; extra == "server"
Provides-Extra: bench
Requires-Dist: numpy>=2; extra == "bench"
Requires-Dist: pyarrow>=15; extra == "bench"
Requires-Dist: receiptdb[live]; extra == "bench"
Requires-Dist: py-spy>=0.4; extra == "bench"
Provides-Extra: examples
Requires-Dist: receiptdb[langchain,live,llamaindex]; extra == "examples"
Requires-Dist: langchain-text-splitters>=1.0; extra == "examples"
Requires-Dist: langchain-huggingface>=1.0; extra == "examples"
Requires-Dist: llama-index-embeddings-huggingface>=0.6; extra == "examples"
Dynamic: license-file

# ReceiptDB

[![CI](https://github.com/counterfoillabs/receiptdb/actions/workflows/ci.yml/badge.svg)](https://github.com/counterfoillabs/receiptdb/actions/workflows/ci.yml)
[![Licence: FSL-1.1-ALv2](https://img.shields.io/badge/licence-FSL--1.1--ALv2-blue)](https://github.com/counterfoillabs/receiptdb/blob/main/LICENSE)
[![Python 3.12+](https://img.shields.io/badge/python-3.12%2B-blue)](https://github.com/counterfoillabs/receiptdb/blob/main/pyproject.toml)

**Provenance-native storage for AI-derived data. Accountability for whatever your AI produces.**

Every chunk, embedding, agent memory, summary and answer stored in ReceiptDB carries a *receipt*. The receipt records what the record was derived from, which model or transform produced it, and the trust, license and privacy labels it inherited. ReceiptDB enforces receipts on both writes and reads. If a source is retracted, everything derived from it is retracted too. If a model changes, stale data is flagged, not silently served.

> **Status: release candidate.** This is a release candidate of 1.0.0, the first supported release; it is for evaluation. This README and `docs/` describe `main`.

```bash
pip install "receiptdb[live]==1.0.0rc1"       # then: docs/getting-started.md
```

---

## Five minutes: see a receipt, then erase someone

You need Docker, Python 3.12+, [uv](https://docs.astral.sh/uv/), git and make. No model or API key:

```bash
git clone https://github.com/counterfoillabs/receiptdb.git receiptdb && cd receiptdb
make install   # .venv with ReceiptDB at the versions in uv.lock
make demo      # starts PostgreSQL in Docker and runs six short steps, offline
```

The demo ingests a few labelled documents, answers a question with its **receipt** (the exact sources, their versions
and who may read them), gives an employee and a contractor different answers from the same assistant, supersedes a
policy and flags the answers built on it, **erases** a customer from every copy with a certificate, and checks that
erasure with `receipt verify-erasure`, a separate process ([what to look at in each step](https://github.com/counterfoillabs/receiptdb/blob/main/docs/demo.md)).

Then on your own documents, with your own model (Claude, a local Ollama, OpenAI or Bedrock:
[getting started](https://github.com/counterfoillabs/receiptdb/blob/main/docs/getting-started.md)):

```bash
make install-live && . .venv/bin/activate   # the live extra; the embedding model (about 130 MB) downloads on first use
export ANTHROPIC_API_KEY=...                 # for `ask`, or RECEIPTDB_MODEL=ollama:llama3.3 (or openai:, bedrock:)
receipt ingest ./my-docs --subjects person:jane --readers group:hr
receipt ask "When is Jane's salary review?" --as group:hr      # prints the answer and its receipt ID
receipt explain <receipt id>                                     # the receipt: sources, versions, labels
receipt erase --subject person:jane --reason "DSR-1" --certificate jane.json
receipt verify-erasure jane.json --subject person:jane          # checked independently
```

How it compares with a plain vector store: [ReceiptDB vs a plain vector store](https://github.com/counterfoillabs/receiptdb/blob/main/docs/vs-vector-store.md). Where it fits:
[RAG under GDPR](https://github.com/counterfoillabs/receiptdb/blob/main/docs/use-cases/rag-under-gdpr.md), [agent memory with erasure](https://github.com/counterfoillabs/receiptdb/blob/main/docs/use-cases/agent-memory.md),
[oversharing](https://github.com/counterfoillabs/receiptdb/blob/main/docs/use-cases/oversharing.md).

## Why ReceiptDB

AI systems turn source data into large amounts of derived data: chunks, vectors, extracted facts, agent memories, cached summaries and answers. Once that happens, today's stacks lose track of where the derived data came from.

- **A bad source can't be fully removed.** If a document turns out to be wrong, poisoned, or withdrawn for consent reasons, its copies live on in vector indexes, memory stores and caches. No system of record knows where all of them are.
- **Governance stops at the table boundary.** Catalogs enforce policy on tables, but the policy is lost when content is embedded, chunked or summarized. A non-commercial license or a PII tag doesn't follow the data into a retrieval index.
- **Model upgrades fail silently.** Querying an index built with one embedding model using another model's vectors returns plausible-looking but meaningless results.
- **Answers can't be audited.** "Why did the agent say that?" usually has no traceable answer.

ReceiptDB treats **provenance as a storage primitive**, not as an after-the-fact catalog entry.

## Capabilities

| | |
|---|---|
| **Receipts on every record** | Records are identified by content hash. Each one links to its inputs and names the versioned transform (chunker, extractor, embedding model, agent) that produced it. |
| **Label inheritance** | Trust, license, PII and AI-generated labels flow from sources to everything derived from them under conservative, well-defined rules. |
| **Cascading retraction** | Retract a source and every downstream chunk, memory, embedding, summary and answer is retracted in one transaction. A dry run shows the impact first. |
| **Versioned re-ingestion** | Re-index on every run. Unchanged sources are no-ops. A changed source, or with page-level versioning just the changed page, supersedes its previous version and everything derived from it, answers already given included. Only text that actually changed is re-embedded. |
| **Import from another vector store** | `receipt import` brings a Qdrant, Weaviate, Pinecone or Chroma collection, an Elasticsearch or OpenSearch index, or a pgvector table, across with its vectors, each point a versioned source labelled unknown provenance until you say where it came from. Re-run it on a schedule: only what changed is written. |
| **Validity windows** | Sources can carry `valid_from` and `valid_to`. Derivatives are valid only where all their inputs are, so a digest expires with its earliest-expiring input. Search skips expired content, `Policy(as_of=...)` shows what retrieval would have returned on any date (with `point_in_time=True`, also with each record's status then: before a retraction, a new version or a quarantine), and `expiring(before=...)` reports what's about to expire. |
| **Right to erasure** | Tag sources with the people they're about (`subjects`). `erase(subject=...)` removes that person's data from every chunk, embedding, summary, memory and answer derived from it, in any status. Vectors and text are deleted, tombstones stay for audit, a certificate lists the answers that had used the data, and `receipt verify-erasure` checks the result independently. |
| **Legal holds** | `place_hold(matter, uri=... \| subject=..., reason=...)` keeps a document (every version) or everything about a person, and everything derived from them, through erasure and retention: held records leave search and answers but keep their content, and releasing the hold completes the erasure. Certificates list what was held back and for which matter. A *retention requirement* (`place_retention_requirement(kind, keep_days, authority=..., reason=...)`) does the same by rule: records of a kind are kept at least so many days (FINRA 4511, SEC 17a-4), certificates name the obligation and the date, and `receipt retention` completes the erasure when it next runs after the period ends (the Helm chart schedules it daily). |
| **Re-derivation** | When one input of a summary, digest or memory is retracted or superseded, the derivative is queued. `rederive({...handlers})` rebuilds it from its remaining inputs *plus the current version of each superseded one* (a new version records what it replaced), with a link to the version it replaces. `followups()` lists the answers that need revisiting, with who asked and the current versions of their sources. The HTTP worker endpoints let a service in any language do the rebuilding. |
| **Quarantine for suspicious content** | Ingestion scanners (`ledger.scanners`) hold flagged sources and everything derived from them out of retrieval until someone reviews them; the pipeline keeps running. `release(uri)` restores them, and `retract(uri)` rejects them. Ships with a cheap heuristic, Meta's Prompt Guard 2 run locally, a Lakera Guard adapter, a model-based classifier (any configured model) and a small HTTP contract for your own; each verdict is kept on the quarantined record. |
| **Personal data, found** | `RECEIPTDB_SCAN=pii` flags personal data a writer never declared and proposes the people it names for a reviewer to confirm; once confirmed, erasing them reaches those records too. The built-in engine (`RECEIPTDB_PII_ENGINE=patterns`) finds email addresses, phone numbers, card numbers, IBANs and the US and UK national identifiers you name, with no model and no extra service; Microsoft Presidio adds names. It records entity types and scores, never the text it matched, and only tightens labels ([content safety](https://github.com/counterfoillabs/receiptdb/blob/main/docs/guides/content-safety.md#personal-data-detection)). |
| **Tainted-input protection** | Nothing can be derived from retracted or stale data, and a retracted source cannot be re-ingested. |
| **Permission-aware retrieval** | Sources carry `readers`, for example `["group:finance"]`. Derived records (summaries, memories, answers) inherit access from **every** input, and revoking access to a source revokes it on everything built from it. Searches that don't say who is asking see only unrestricted data. |
| **Re-answer and diff** | When a source changes, `reanswer_followups()` asks each affected question again against the current sources, links the old answer to the new one, and reports which answers actually changed (with a word-level diff), so you tell only the people whose answer is different. |
| **Grounding checks** | By default, every answer the API or the CLI records says in its receipt whether its claims are supported by the passages it cites: a score, the unsupported sentences, and the checker (offline, or the configured model). `ungrounded_answers()` lists the ones that go beyond their sources. |
| **Data-egress control** | Label where content may be sent (`egress: ["local", "anthropic:eu"]`). Derived records inherit the strictest limits, searches for a given model return only what may go to it, and every answer records where its sources were sent, flagged if they shouldn't have been. |
| **Policy-filtered retrieval** | Queries such as "verified sources only" or "no non-commercial content" are enforced on inherited labels, so they hold even inside the vector index. |
| **Safe model migration** | Cross-model queries are refused. A shadow index is backfilled while the current one keeps serving, then cutover happens atomically and the old embeddings are marked stale. |
| **Agent memory with provenance** | A Mem0-style memory API (`add`, `search`, `get_all`, `history`, `update`, `delete`, batch deletes, an expiry per memory). Updates supersede old memories instead of piling up contradictions; two edits at once can't fork one; and untrusted sources can't overwrite trusted memories (their claims are kept for review, out of search). |
| **Safe answer cache** | `AnswerCache` serves a cached answer to a similar question only while every source behind it is valid and readable by the caller, so it's never stale and never leaks across permissions or tenants, with no invalidation code. Each hit is recorded as an answer of its own. |
| **Approved answers** | A reviewer approves an answer (`approve_answer`), and `AnswerCache.lookup(approved_only=True)` serves only approved answers, with who approved them. An approval lapses for good when any source changes, its labels make the answer stricter, or its validity ends; `approvals(lapsed=True)` lists those to review again, with why and when. |
| **Change feed and webhooks** | `GET /v1/events` and signed webhooks (`RECEIPTDB_WEBHOOK_URL`) report every retraction, supersession, erasure and quarantine, with the answers it affected, so apps can tell the people who were given them. Deliveries are [Standard Webhooks](https://www.standardwebhooks.com), at least once and in order, one round at a time across replicas; an event the receiver refuses is set aside as a dead letter while the rest go on, and an outage dead-letters nothing. Enterprise gives each tenant its own endpoint and secret, rotated with a window in which both sign. |
| **Hybrid search** | `mode="hybrid"` combines meaning (vectors) with exact terms (IDF-weighted full-text): 0.727 vs 0.635 hit@1 on real SQuAD questions ([benchmarks](https://github.com/counterfoillabs/receiptdb/blob/main/docs/benchmarks.md)). Every mode applies the same policy. |
| **Fast, filter-safe search** | Optional HNSW indexes per embedding model. On real `bge-small` embeddings, tuned Postgres on its own 8-vCPU server: about 3.3 ms p50 with trust and license filters at 0.975 recall@10 (0.99 unfiltered). Filtered results are always complete: a caller who can read only a little is searched exactly through an index on who can read what. See [benchmarks](https://github.com/counterfoillabs/receiptdb/blob/main/docs/benchmarks.md). |
| **Built to stay correct under load** | Property-based tests over random derivation graphs, concurrency tests (relabels, rebuild workers and commits racing each other), fault injection (database restarts mid-cascade, an exhausted pool, a hanging webhook receiver), fuzzing of every HTTP endpoint, and upgrade tests from the previous release. Every retraction, supersession, quarantine, release, relabel and erasure, with its connection cut before and after the commit, behind PgBouncer in session and transaction mode, applies whole or not at all, checked on every change to the code. After a database outage or failover, each API replica serves again within about a second of the database accepting connections. A source with 2,000,000 derived records retracts in one transaction in under two minutes on an 8-vCPU database server ([benchmarks](https://github.com/counterfoillabs/receiptdb/blob/main/docs/benchmarks.md#one-million-chunks-access-data-shapes-and-the-provenance-tax)). |
| **Explainability and audit** | `explain(record)` returns the full derivation tree behind any answer. `audit_answers()` and `receipt audit` export one receipt per answer as JSON Lines: question, answer, asker, model, status history and lineage to every source. It filters by time window, asker, or "every answer that used source X". `receipt verify-receipt` re-hashes a saved receipt against the database, down to every source it names, and names the reason when a record was erased or sealed, the answer isn't in the ledger, or a source moved to another URI. `apply_retention()` enforces storage limits. |

## How it works

*The diagram is in [the README on GitHub](https://github.com/counterfoillabs/receiptdb#how-it-works).*

ReceiptDB is a thin layer on top of PostgreSQL and pgvector, not a new database engine. The derivation graph is an ordinary table. Transactions make cascades and cutovers atomic, and the whole system runs on infrastructure your team already operates.

Run by your platform team: behind PgBouncer in session or transaction mode, with timeouts on every request, a separate
ceiling for retractions and erasures, per-caller rate limits and a throttle on failed authentication. API keys rotate
with zero downtime (the outgoing key keeps working beside the new one for a window you set, up to a week). Structured
JSON logs, Prometheus metrics and OpenTelemetry traces; sixteen [runbooks](https://github.com/counterfoillabs/receiptdb/blob/main/docs/runbooks/README.md), one per failure,
each drilled against the real failure it describes, linked from the alerts that raise them; and `receipt
support-bundle` for a support ticket, with no record content or secrets in it ([deployment](https://github.com/counterfoillabs/receiptdb/blob/main/docs/ops/deploy.md)).

### Label inheritance rules

| Label | When a record is derived | Unlabelled source |
|---|---|---|
| `trust`: `untrusted < low < medium < verified` | Lowest trust among the inputs. A derived record can lower it but never raise it. | `untrusted` |
| `license`: `public < internal < cc-by-nc < restricted` | Most restrictive license among the inputs | `restricted` |
| `ai_generated`, `pii` | Set if set on any input | `false` |
| `unknown_provenance` | Set if set on any input | `true`: nothing vouches for where it came from; `false` asserts the origin is known |
| `origins` | Union of root source URIs, used for citations | the source URI |
| `readers` | One clause per input; a caller must match every clause | readable by everyone |
| `subjects` | Union over inputs (for erasure requests) | none |
| `valid_from`, `valid_to` | Latest start and earliest end among inputs | unbounded |

Every rule fails closed: a derived record is never more trusted, or less restricted, than its least favourable input.

## Quickstart

Requirements: Docker, Python 3.12+, [uv](https://docs.astral.sh/uv/) (`brew install uv` or `pipx install uv`), git and make.

```bash
git clone https://github.com/counterfoillabs/receiptdb.git receiptdb && cd receiptdb
make install   # create .venv and install ReceiptDB at the versions in uv.lock
make demo      # start PostgreSQL alone (make up-postgres) and run the demo (make demo-assistant: offline, no API keys)
make test      # start the whole development stack (make up: about 20 containers) and run the test suite
```

To have a real model write the demo's answers (Claude by default, or any model `RECEIPTDB_MODEL` names, such as a local
`ollama:llama3.3`):

```bash
make install-live
echo "ANTHROPIC_API_KEY=..." > .env   # git-ignored
make demo ARGS=--live
```

The other live demos and the examples need an Anthropic API key (in `.env` or the environment), and the first run downloads the
embedding model from Hugging Face (about 130 MB; the engineering demo's live mode, two models, about 220 MB). Each one
checks first and says in one line what's missing.

### Docker (API only)

```bash
echo "RECEIPTDB_API_KEY=$(openssl rand -hex 16)" >> .env
docker compose --profile api up -d        # Postgres + the ReceiptDB API on :8321   (or: make docker)
curl -H "Authorization: Bearer $(grep RECEIPTDB_API_KEY .env | cut -d= -f2)" localhost:8321/v1/status
```

The image is `python:3.12-slim` running as a non-root user, with a health check. The quick-start kit and the Helm chart set `RECEIPTDB_SCAN=heuristics`, so new sources are screened for prompt injection; the setting is off when unset.

## Usage

```python
from receiptdb import Ledger, Policy
from receiptdb.embedders import SentenceTransformerEmbedder

led = Ledger.connect()            # uses $RECEIPTDB_DSN
led.init_schema()
emb = SentenceTransformerEmbedder("BAAI/bge-small-en-v1.5")

# Write path: every derived record gets a receipt.
src   = led.put_source(text, uri="https://example.com/page", labels={"trust": "low", "license": "public"})
chunk = led.derive("chunk", paragraph, [src], transform="chunker:paragraph@1")
fact  = led.derive("memory", statement, [chunk], transform="extract:claude-opus-5-5@p1",
                   labels={"ai_generated": True})
led.embed(chunk, emb)
led.embed(fact, emb)

# Read path: policy is enforced on inherited labels.
hits = led.search("How do I reset my password?", emb, Policy(min_trust="medium", commercial_use=True))

# Access: derived records inherit readers from every input; changes propagate.
led.relabel("https://example.com/page", {"readers": ["group:support"]}, reason="restricted")
led.search("reset password", emb, Policy(principals=("user:alice", "group:support")))

# Lifecycle.
print(led.retract("https://example.com/page", reason="source withdrawn", dry_run=True).summary())
cert = led.erase(subject="person:alice@example.com", reason="GDPR Art. 17 request #42", compact=True)
print(cert.to_dict()["counts"], cert.answers)   # what was removed, and which answers had used it
print(led.explain(fact))
```

An embedder is any object with a `.model` name and an `.embed(text)` method (plus an optional `.embed_many(texts)` for batching), so hosted and self-hosted models plug in the same way.

For bulk loads, `led.derive_many([...])` and `led.embed_many(ids, emb)` write whole batches in one transaction with the same rules. That's about 4,100–4,400 chunks/s with Postgres on its own 8-vCPU server, 15–20× the one-at-a-time path ([benchmarks](https://github.com/counterfoillabs/receiptdb/blob/main/docs/benchmarks.md)). The framework adapters use them automatically.

### Answers: grounding, egress and follow-ups

```python
from receiptdb.grounding import LexicalGrounding          # or integrations.anthropic.ClaudeGrounding

# Label where content may be sent; search for the model that will read the results.
led.put_source(text, uri="hr://salaries", labels={"readers": ["group:hr"], "egress": ["local"]})
hits = led.search(question, emb, Policy(principals=("group:hr",), destination="anthropic"))  # no salaries

# Record the answer with where it went, and check it against its sources.
answer_id = led.record_answer(question, answer, [h.record_id for h in hits], "agent:claude-opus-5-5@p1",
                              asked_by="dana", destination="anthropic", grounding=LexicalGrounding())
led.get(answer_id)["meta"]["grounding"]    # {"score": 1.0, "unsupported": [], "grounded": true, ...}
led.ungrounded_answers()                   # answers with claims their sources don't support

# A source changed: ask each affected question again, and tell only the people whose answer changed.
report = led.reanswer_followups(lambda q, passages: my_model(q, passages), "agent:claude-opus-5-5@p1")
for r in report["changed"]:
    notify(r["asked_by"], r["question"], r["new_answer"])    # r["diff"] is a word-level diff
```

For anything beyond development, build the search index for the embedding model
(`led.create_ann_index(emb.model)`, or `receipt index build`; [ops/scaling.md](https://github.com/counterfoillabs/receiptdb/blob/main/docs/ops/scaling.md#the-search-index)).

### Agent memory

`ReceiptMemory` has the same shape as Mem0's API, with provenance underneath:

```python
from receiptdb.memory import ReceiptMemory
from receiptdb.integrations.anthropic import ClaudeMemoryModel

memory = ReceiptMemory(led, emb, ClaudeMemoryModel())
memory.add([{"role": "user", "content": "I'm vegetarian and I live in Berlin."}], user_id="Alice")
memory.add(email_text, user_id="Alice", source="https://mail.example/8841", labels={"trust": "low", "license": "internal"})

memory.search("Where is Alice based?", user_id="Alice", policy=Policy(min_trust="medium"))
memory.history(memory_id)                     # every version, with why it changed
led.retract("https://mail.example/8841", "phishing")   # removes every memory learned from it
```

- **Every memory is derived from a source** (a conversation turn, an email, a tool result) and inherits its trust and license.
- **Updates supersede.** When a new fact replaces an old one, the old memory is kept in `history` but never retrieved. Answers built on it are flagged.
- **Untrusted content can't overwrite trusted memory.** When a lower-trust source tries to update or delete a more trusted memory, its claim is stored as a *contesting* memory instead, which a trust policy filters out.
- **Users can be forgotten.** Every memory is tagged with its user, so `memory.forget("Alice")` erases her conversations, memories and anything derived from them, and returns a certificate. Other users are untouched.
- **The model is pluggable.** `ClaudeMemoryModel` uses Claude for fact extraction and for the ADD/UPDATE/DELETE/NONE decision. Any object with `extract` and `decide` methods works. The HTTP API's `/v1/memory` endpoints use the model `RECEIPTDB_MEMORY_MODEL` names (any provider), and stay off until it's set.

Run `make demo-memory` to see a phishing email try to relocate a user, an update from vegetarian to pescatarian that flags an answer built on the old fact, and a retraction. It's live: it needs `make install-live`, an Anthropic API key, and downloads about 130 MB of embedding model on the first run.

### Frameworks and agents

`ReceiptVectorStore` is a drop-in LangChain `VectorStore`. Moving an existing RAG app from `InMemoryVectorStore` changes four lines, and the rest of the app is untouched:

```diff
-from langchain_core.vectorstores import InMemoryVectorStore
+from receiptdb.integrations.langchain import ReceiptVectorStore

-store = InMemoryVectorStore(embeddings)
+store = ReceiptVectorStore(embeddings, source_labels=source_labels())

     answer = next(b.text for b in response.content if b.type == "text")
+    store.record_answer(question, answer, docs, transform=f"agent:{response.model}@p1", asked_by=user)
     return answer
```

Every adapter, its store and its extra; [the frameworks guide](https://github.com/counterfoillabs/receiptdb/blob/main/docs/guides/frameworks.md) has each in full:

| Framework | ReceiptDB's store | Install |
|---|---|---|
| [LangChain](https://github.com/counterfoillabs/receiptdb/blob/main/docs/guides/frameworks.md#langchain) | `receiptdb.integrations.langchain.ReceiptVectorStore`, a `VectorStore` | `receiptdb[langchain]` |
| [LlamaIndex](https://github.com/counterfoillabs/receiptdb/blob/main/docs/guides/frameworks.md#llamaindex) | `receiptdb.integrations.llamaindex.ReceiptVectorStore`, for any `VectorStoreIndex` | `receiptdb[llamaindex]` |
| [LangGraph](https://github.com/counterfoillabs/receiptdb/blob/main/docs/guides/frameworks.md#langgraph) | `receiptdb.integrations.langgraph.ReceiptStore`, a `BaseStore` | `receiptdb[langgraph]` |
| [Haystack](https://github.com/counterfoillabs/receiptdb/blob/main/docs/guides/frameworks.md#haystack) | `receiptdb.integrations.haystack.ReceiptDocumentStore`, a `DocumentStore`, with `ReceiptEmbeddingRetriever` and `ReceiptHybridRetriever` | `receiptdb[haystack]` |
| [Semantic Kernel](https://github.com/counterfoillabs/receiptdb/blob/main/docs/guides/frameworks.md#semantic-kernel) | `receiptdb.integrations.semantic_kernel.ReceiptStore` and `ReceiptCollection`, a vector store and its collections | `receiptdb[semantic-kernel]`, in an environment of its own |
| [MCP (agents)](https://github.com/counterfoillabs/receiptdb/blob/main/docs/guides/frameworks.md#mcp-agents) | the API's MCP server at `/mcp`; `receipt mcp` over stdio | `receiptdb[server]`; `receiptdb[mcp]` for stdio |

The complete before-and-after example is in [`examples/langchain_rag`](https://github.com/counterfoillabs/receiptdb/tree/main/examples/langchain_rag). Run it with `make install-examples && make example-langchain`: it runs the before app, then the after one, with Claude answering, so it needs an Anthropic API key and downloads about 130 MB of embedding model on the first run ([`examples/README.md`](https://github.com/counterfoillabs/receiptdb/blob/main/examples/README.md)).

### HTTP API and TypeScript

Run the service, which needs `pip install 'receiptdb[server]'`:

```bash
RECEIPTDB_API_KEY=... receipt serve --port 8321    # or: make serve
```

It exposes the ledger over JSON: sources, derived records (single and batch), vectors, policy-filtered search, retract, supersede, answers, explain and ANN indexes. Clients send their own vectors, so the service works with any embedding model. When `RECEIPTDB_API_KEY` is set, every `/v1` request needs `Authorization: Bearer <key>`. Interactive docs are at `/docs`; every route, its scope and its request body: [docs/http-api.md](https://github.com/counterfoillabs/receiptdb/blob/main/docs/http-api.md).

For Python services calling a shared deployment, `receiptdb.client.ReceiptClient` (`pip install 'receiptdb[client]'`) has the same methods over HTTP, e.g. `put_source`, `put_sources`, `derive_many`, `search`, `retract`, `erase` and `audit_answers`.

The TypeScript client ([`clients/typescript`](https://github.com/counterfoillabs/receiptdb/tree/main/clients/typescript), its [README](https://github.com/counterfoillabs/receiptdb/blob/main/clients/typescript/README.md)) is dependency-free and typed. Install it with `npm install @receiptdb/client@next` (the release candidate; from 1.0.0, `npm install @receiptdb/client`), or from the tarball each GitHub release carries:

```ts
import { ReceiptClient } from "@receiptdb/client";

const rdb = new ReceiptClient({ baseUrl: "http://127.0.0.1:8321", apiKey: process.env.RECEIPTDB_API_KEY });
const src = await rdb.putSource({ uri: "https://wiki/policy", text, labels: { trust: "verified", license: "internal" } });
const [chunk] = await rdb.deriveMany([{ kind: "chunk", payload: text, inputs: [src], transform: "split@1" }]);
await rdb.putEmbeddings("my-model@1", [{ recordId: chunk, vector }]);
const hits = await rdb.search({ vector: q, model: "my-model@1", policy: { commercialUse: true } });
const impact = await rdb.retract({ uri: "https://wiki/policy", reason: "superseded", dryRun: true });
```

It calls every route a client uses, Enterprise's included (`setTenantWebhook`, `tenantReady`, `usage`, …), and a test fails when a route has no method. Every failure throws `ReceiptError` with the HTTP status and the server's error type, for example `TaintedInputError`. A body that isn't the API's JSON (a proxy's error page) is `HTTP<status>` with the start of the body in `error.body`. No answer within `timeoutMs` (default 30 s) throws `ReceiptTimeoutError`, and an unreachable server throws `ReceiptConnectionError`. `make test-ts` runs the client's tests against a live server.

### Command line

Every command and flag: [docs/cli.md](https://github.com/counterfoillabs/receiptdb/blob/main/docs/cli.md).

```bash
receipt ingest ./docs --readers group:legal --license restricted   # files → labelled, versioned sources
receipt search "notice period" --as group:legal                     # passages with their receipts
receipt ask "What is the notice period?" --as group:legal           # the configured model answers (RECEIPTDB_MODEL); the receipt is recorded, with grounding
receipt ingest ./privileged --egress local                           # never sent to a hosted model
receipt import qdrant http://qdrant:6333 --collection docs --model BAAI/bge-small-en-v1.5   # an existing vector store, vectors kept
receipt follow-up                                                    # answers a change made stale, and who was given them
receipt follow-up --reanswer                                         # ask them again; show only what changed
receipt follow-up --include-resolved                                 # also those already re-answered
receipt erase --subject person:jane --reason "DSR-17" --certificate cert.json
receipt hold place --matter "Doe v. Acme" --uri hr://dana --reason "litigation hold"   # kept through erasure
receipt hold list                                                    # active holds and what each covers
receipt retention require --kind answer --keep-days 2190 --authority "FINRA 4511" --reason "communications"
receipt retention --kind answer --older-than-days 365                # completes what's due, then the age limit
receipt retention --complete-only --all-tenants                      # only what's due, in every tenant: schedule it (the chart does, daily)
receipt approve <answer-id> --note "FAQ 12"                          # the cache can serve only approved answers
receipt approvals --lapsed                                           # approvals a source change or expiry ended
receipt search "notice period" --as-of 2026-03-01                    # replay: what search returned then
receipt status                 # record counts by status and kind, active embedding model
receipt index build            # the HNSW search index for the active model (also: index status)
receipt events --follow        # the change feed
receipt mcp                    # the MCP server over stdio (the API serves it at /mcp too)
receipt serve --port 8321      # run the HTTP API
receipt audit --since 2026-09-01 --out audit.jsonl          # answer receipts for compliance
receipt audit --source wiki://policy-2024                   # every answer that used this source
receipt explain <id-prefix>    # derivation tree for a record
receipt impact <source-uri>    # dry-run a retraction
receipt retract <source-uri> --reason "..."
receipt verify-receipt receipt.json   # re-hash a saved receipt against the database, down to every source
receipt config check           # validate every setting, secrets redacted, and check the database
receipt migrate                # upgrade the schema now (the server's start does it too)
receipt support-bundle         # diagnostics for a support ticket, with no record content or secrets
```

## Demo

`make demo-assistant` (or `make demo`) runs a fictional company's internal AI assistant in six steps on the Community
edition, offline and with no API key: every answer with its receipt (the sources, their versions, who could see them),
an employee and a contractor told different things by the same assistant, a changed policy taking its answers and a
summary with it, a customer erased from every copy with a certificate an independent check confirms, a receipt
verified later, and the whole LangChain integration as a diff. `ARGS=--pause` to present it, `ARGS=--live` for a real
model. What to look at in each step: [docs/demo.md](https://github.com/counterfoillabs/receiptdb/blob/main/docs/demo.md).

`make demo-web` runs the same story as a web page on your machine (127.0.0.1, offline by default), in seven steps:
Quillmere's assistant on the left; on the right, the live lineage graph with the step's receipt or certificate beneath
it. Every record, status and count on the right is read live from `receipt serve` and its checks, and the words around
them are the app's. You cause each change: ask (and let the stand-in add a sentence its sources don't
support, which the receipt's grounding check marks), retype HR's policy, receive a supplier's note with a planted
instruction (held at the door) and quarantine an earlier one with everything built on it, approve an erasure and
confirm a record the detector found that nobody had labelled, edit a saved receipt. An evidence pack of the session
(the receipts, the quarantine, both erasure certificates and the checks, a summary and each file's SHA-256) downloads
at any step. It needs the `server`
and `demo` extras: [docs/demo.md](https://github.com/counterfoillabs/receiptdb/blob/main/docs/demo.md#the-web-page).

`make demo-enterprise` is the longer walk-through, Acme's legal and HR assistant in six scenes: destination
policy, grounding checks and the audit export (all Community), plus the Enterprise provenance explorer with `make demo-ui` (it needs ReceiptDB Enterprise and a licence with `ui`, and makes a
throwaway master key in `.demo-master-key` unless `RECEIPTDB_MASTER_KEY` is set). `make demo-enterprise-live` has
Claude write the answers.

`make demo-engineering` is the original help-desk demo, including an embedding-model migration
and read-time licence policy (offline; `make demo-engineering-live` with Claude and two local models).

`make demo-memory` is agent memory: a phishing email tries to relocate a user, an updated fact flags an answer built
on the old one, and a retraction removes what the email taught (live only: `make install-live` and an Anthropic API key).

Every demo starts PostgreSQL alone (`make up-postgres`), not the whole development stack.

## Roadmap

[Why ReceiptDB](https://github.com/counterfoillabs/receiptdb/blob/main/docs/roadmap.md) sets out each problem ReceiptDB solves, with the public evidence for it, and what
comes next as themes: production evidence (failover, backup and restore, scale), a security review, integrations
proven against live services, a stable 1.0, memory for agents, and more uses of the receipts. What each release
ships is in the [changelog](https://github.com/counterfoillabs/receiptdb/blob/main/CHANGELOG.md).

## Current limitations

The full list is in [docs/limitations.md](https://github.com/counterfoillabs/receiptdb/blob/main/docs/limitations.md). The main ones:

- Retraction is conservative: a derived record with any retracted input is retracted in full. Rebuilding it from the remaining inputs is opt-in, through `rederive()` and a handler per transform.
- Benchmarks run on one and two 8-vCPU servers and on 32-vCPU servers (the database and the API each on its own, the load from a third machine), up to 1M chunks (synthetic) and about 19k real passages, with API throughput for 1–8 server processes on 8 vCPUs and 8–40 on 32 vCPUs, and a 60-minute soak ([details](https://github.com/counterfoillabs/receiptdb/blob/main/docs/benchmarks.md)); larger deployments and replicas aren't measured yet, and managed Postgres is validated for correctness ([validation](https://github.com/counterfoillabs/receiptdb/blob/main/docs/validation/README.md)), not yet measured for performance. Build the HNSW index before production traffic (`receipt index build`, or the Helm chart's job): without it, search is exact and slows as the corpus grows, and `/v1/status` says so.
- Provenance guarantees apply only to data written through ReceiptDB.
- Erasure removes data from the database, and `compact=True` rewrites table and index files. Copies in WAL archives and backups need their own retention policy, except for text protected by Enterprise crypto-shredding with a separate key store, which stays unreadable after a restore.

## Enterprise

Organisation-wide features ship separately as ReceiptDB Enterprise, under a commercial licence ([docs/enterprise/README.md](https://github.com/counterfoillabs/receiptdb/blob/main/docs/enterprise/README.md), [counterfoillabs.com](https://counterfoillabs.com)): identity sync from Okta or Entra ID over SCIM, with retrieval policies that search *as a user*; permission-syncing connectors; crypto-shredding with keys in your KMS and, optionally, a separate key store so erased text stays unreadable after a backup restore, and sealed vectors so base backups and WAL archives hold embeddings only encrypted; signed compliance evidence and a tamper-evident audit log with signed anchors; scoped API keys, which can be bound to fixed groups and a trust ceiling, multi-tenancy and quotas; a provenance explorer UI. The core ledger, including access inheritance, retraction and erasure, is not held back.

## Documentation

- [The documentation index](https://github.com/counterfoillabs/receiptdb/blob/main/docs/README.md): every page, grouped by what you're here to do
- [Getting started](https://github.com/counterfoillabs/receiptdb/blob/main/docs/getting-started.md) and [a tour](https://github.com/counterfoillabs/receiptdb/blob/main/docs/tour.md) (start here)
- [Worked example](https://github.com/counterfoillabs/receiptdb/blob/main/docs/worked-example.md): withdraw a source, erase a person, every step checked; no model or key
- [Configuration reference](https://github.com/counterfoillabs/receiptdb/blob/main/docs/configuration.md), [command-line reference](https://github.com/counterfoillabs/receiptdb/blob/main/docs/cli.md) and [HTTP API reference](https://github.com/counterfoillabs/receiptdb/blob/main/docs/http-api.md)
- [Frameworks and agents](https://github.com/counterfoillabs/receiptdb/blob/main/docs/guides/frameworks.md): the LangChain, LlamaIndex, LangGraph, Haystack and Semantic Kernel stores, and MCP
- [Building on the API](https://github.com/counterfoillabs/receiptdb/blob/main/docs/building-on-the-api.md): the key, cross-origin access, the clients, the events cursor
- [Stability tiers](https://github.com/counterfoillabs/receiptdb/blob/main/docs/stability.md): what is stable, beta or experimental, and the frozen stable OpenAPI document
- [Versioning and deprecation](https://github.com/counterfoillabs/receiptdb/blob/main/docs/versioning.md): what a release may change, and how a stable thing is deprecated
- [Releases and support](https://github.com/counterfoillabs/receiptdb/blob/main/docs/releases.md): release candidates, how often releases come, and how long each gets fixes
- [Upgrading](https://github.com/counterfoillabs/receiptdb/blob/main/docs/ops/upgrading.md) and [changelog](https://github.com/counterfoillabs/receiptdb/blob/main/CHANGELOG.md)
- [Known limitations](https://github.com/counterfoillabs/receiptdb/blob/main/docs/limitations.md)
- [Security policy](https://github.com/counterfoillabs/receiptdb/blob/main/SECURITY.md): how to report a vulnerability, response times, supported versions
- [Why ReceiptDB and the roadmap](https://github.com/counterfoillabs/receiptdb/blob/main/docs/roadmap.md)
- [Benchmarks](https://github.com/counterfoillabs/receiptdb/blob/main/docs/benchmarks.md)
- [Enterprise](https://github.com/counterfoillabs/receiptdb/blob/main/docs/enterprise/README.md)
- [Deployment](https://github.com/counterfoillabs/receiptdb/blob/main/docs/ops/deploy.md)
- [Security: the threat model](https://github.com/counterfoillabs/receiptdb/blob/main/docs/security.md)
- [Verifying a release](https://github.com/counterfoillabs/receiptdb/blob/main/docs/verifying-releases.md): check a release image's signature with `cosign verify`
- [Compliance](https://github.com/counterfoillabs/receiptdb/blob/main/docs/compliance/README.md): GDPR, the EU AI Act and FINRA 24-09 mapped to what ReceiptDB does, and what stays yours
- [Runbooks](https://github.com/counterfoillabs/receiptdb/blob/main/docs/runbooks/README.md): one page per failure an operator can meet

## License

ReceiptDB is licensed under the [Functional Source License, FSL-1.1-ALv2](https://github.com/counterfoillabs/receiptdb/blob/main/LICENSE): free to use, copy, modify and redistribute for any purpose except offering a competing product or service, and each release becomes Apache-2.0 two years after it ships. Copyright © 2026 Counterfoil Labs. ReceiptDB Enterprise is a separate commercial product.

Contributions are welcome: see [CONTRIBUTING.md](https://github.com/counterfoillabs/receiptdb/blob/main/CONTRIBUTING.md). To report a security problem, see [SECURITY.md](https://github.com/counterfoillabs/receiptdb/blob/main/SECURITY.md).
