Metadata-Version: 2.4
Name: ucde
Version: 0.2.1
Summary: Version-controlled research evidence: search what was known at any past date, with citations, verifiable history and a read-only MCP server
Author: Muhammad Q Farooqi
License-Expression: Apache-2.0
Project-URL: Homepage, https://ucde-evidence.closedtiger256.chatgpt.site/
Project-URL: Documentation, https://github.com/mqfarooqi1/ucde#guide
Project-URL: Repository, https://github.com/mqfarooqi1/ucde
Project-URL: Issues, https://github.com/mqfarooqi1/ucde/issues
Project-URL: Changelog, https://github.com/mqfarooqi1/ucde/blob/main/CHANGELOG.md
Keywords: research data,provenance,evidence retrieval,reproducibility,audit trail,bitemporal,time travel,hash chain,ro-crate,w3c-prov,plant breeding,phenotyping,sqlite,fts5,bm25,mcp,model context protocol,ai agents,agent memory
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Database
Classifier: Topic :: Database :: Database Engines/Servers
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: mcp
Requires-Dist: mcp==2.3.0; extra == "mcp"
Dynamic: license-file

<!-- mcp-name: io.github.mqfarooqi1/ucde -->
<p align="center"><a href="https://ucde-evidence.closedtiger256.chatgpt.site/"><img src="https://raw.githubusercontent.com/mqfarooqi1/ucde/main/docs/assets/ucde-logo.png" alt="UCDE logo" width="96" height="96"></a></p>

<h1 align="center">UCDE: Universal Cognitive Data Engine</h1>

<p align="center"><strong>Version control for research evidence.</strong> Search what was known at any past date, see where every answer came from, and give AI agents the same cited, read-only view.</p>

<p align="center">
<a href="https://pypi.org/project/ucde/"><img src="https://img.shields.io/pypi/v/ucde" alt="PyPI version"></a>
<a href="https://pypi.org/project/ucde/"><img src="https://img.shields.io/pypi/pyversions/ucde" alt="Supported Python versions"></a>
<a href="https://github.com/mqfarooqi1/ucde/actions/workflows/ci.yml"><img src="https://github.com/mqfarooqi1/ucde/actions/workflows/ci.yml/badge.svg" alt="CI status"></a>
<a href="https://github.com/mqfarooqi1/ucde/blob/main/LICENSE"><img src="https://img.shields.io/badge/licence-Apache--2.0-blue" alt="Apache-2.0 licence"></a>
<a href="#connect-an-ai-agent-mcp"><img src="https://img.shields.io/badge/MCP-read--only%20server-6E56CF" alt="Read-only MCP server"></a>
</p>

<p align="center"><a href="https://ucde-evidence.closedtiger256.chatgpt.site/">Website</a> · <a href="#quick-start">Quick start</a> · <a href="#connect-an-ai-agent-mcp">AI agents</a> · <a href="#guide">Guide</a> · <a href="https://github.com/mqfarooqi1/ucde/blob/main/CHANGELOG.md">Changelog</a></p>

UCDE is a local, append-only evidence ledger for experimental and computational research. Each observation keeps its source, locator, measurement context and complete revision history in one SQLite file. Corrections and retractions add revisions instead of overwriting, so a past search can be rerun exactly, cited and checked by someone else.

The first workflow uses plant breeding and phenotyping records. The examples also cover an assay-method record, a published wheat sensing dataset and two releases of the public JARVIS materials-simulation database. UCDE preserves independent observations even when they disagree.

## Why UCDE

Spreadsheets overwrite. Databases keep the latest value. Vector stores lose track of where an answer came from. UCDE is built for the questions those tools cannot answer.

| Question | How UCDE answers it |
|---|---|
| What did we know on 1 March? | `--known-at` reruns a search against the ledger as it stood at that instant. Recording time and observation time are separate, so a search can also bound when the measurement was taken. |
| Where did this number come from? | Every hit returns its source, locator, optional source SHA-256, revision number and ranking components. |
| What changed since the analysis? | Corrections, retractions and restorations are new revisions with their own provenance. Each write states the revision it expects, so one edit cannot silently replace another. Save a search as a packet, then compare or replay it later. |
| Can a reviewer check it without trusting us? | `ucde verify` audits the file. Checkpoints, an opt-in SHA-256 hash chain, portable archives and evidence packets produce receipts that anyone can check offline. |
| Can we share it in a standard format? | `ucde crate` packages history as an RO-Crate 1.2 with a W3C PROV-O provenance graph. |
| Can an AI agent use it safely? | A read-only MCP server exposes search and history. Its instructions tell agents to cite the source and to treat evidence text as data, never as instructions. |

The core is Python 3.11+ and SQLite: FTS5 for BM25 text search, plus optional dense vectors that you supply. It has no runtime dependencies and makes no network or model calls. The optional Ollama commands run only when you invoke them.

## Install

```shell
pip install ucde            # Python library and ucde CLI, no dependencies
pip install "ucde[mcp]"     # adds the MCP server for AI agents
```

UCDE needs SQLite with FTS5 and JSON functions, which the python.org, Homebrew and common Linux builds include. To try it without installing, run `uvx ucde --help` with [uv](https://docs.astral.sh/uv/).

## Quick start

Save a measurement as `plot-18.json`:

```json
{"id": "plot-18", "subject": "W-017", "variable": "plant height", "method": "ruler-v1", "scale": "cm",
 "observed_at": "2025-09-05T05:30:00Z", "text": "W-017 measured 81 cm in plot 18.",
 "source": "fieldbook-2025.csv", "locator": "row 18"}
```

Save its later correction as `plot-18-fixed.json`:

```json
{"id": "plot-18", "subject": "W-017", "variable": "plant height", "method": "ruler-v1", "scale": "cm",
 "observed_at": "2025-09-05T05:30:00Z", "text": "W-017 measured 86 cm in plot 18 after re-measurement.",
 "source": "fieldbook-2025-v2.csv", "locator": "row 18"}
```

Record both, then search the present and the past:

```shell
ucde --db evidence.db init
ucde --db evidence.db put plot-18.json                              # revision 1: note the recorded_at it prints
ucde --db evidence.db put plot-18-fixed.json --expected-revision 1  # revision 2: the correction
ucde --db evidence.db search "plant height" --subject W-017         # returns the 86 cm correction
ucde --db evidence.db search "plant height" --subject W-017 --known-at <recorded_at of revision 1>
ucde --db evidence.db history plot-18                               # both revisions with their sources
ucde --db evidence.db verify                                        # audit the file; exit 1 on any problem
```

The search with `--known-at` returns the original 81 cm revision and its source, `fieldbook-2025.csv`, because the correction was recorded later. Every command prints JSON, so the output works with `jq`, scripts and notebooks.

## Use it from Python

```python
from ucde import Evidence, MemoryStore

store = MemoryStore("breeding-evidence.db")
observation = Evidence(
    id="north-2025-plot-18", subject="W-017", variable="plant height",
    method="ruler-v1", scale="cm", observed_at="2025-09-05T05:30:00Z",
    text="W-017 measured 81 cm in plot 18.",
    source="north-2025-fieldbook.csv", locator="csv-row:18",
    context={"site": "north", "treatment": "rainfed", "trial": "2025"},
)
store.put(observation)
result = store.search("plant height", subject="W-017", method="ruler-v1",
                      scale="cm", context={"site": "north", "treatment": "rainfed"})
for hit in result.hits:
    print(hit.revision.evidence.source, hit.revision.evidence.locator, hit.score)
```

The write above expects a new observation ID. Keep the returned revision and pass its `revision` to `store.put(corrected, expected_revision=...)` when correcting the observation. Use `known_at` to reconstruct which revision was available at a cutoff, and `observed_after` and `observed_before` to constrain when the measurement happened. Both observation endpoints are inclusive. `target_at` adds a soft date preference under adaptive ranking. Use `strategy="nearest"` with `target_at` when closeness in observation time should take priority over lexical relevance. See `ucde search --help` for the corresponding CLI options.

```python
store.search(
    "plant height", subject="W-017", method="ruler-v1", scale="cm",
    observed_after="2025-09-01T00:00:00Z", observed_before="2025-09-08T00:00:00Z",
    target_at="2025-09-05T00:00:00Z", strategy="nearest",
)
```

Source locators and optional checksums are provided by the caller. The engine does not resolve source content.

## Connect an AI agent (MCP)

`ucde[mcp]` adds a [Model Context Protocol](https://modelcontextprotocol.io) server with two read-only tools.

| Tool | Returns |
|---|---|
| `search_evidence` | Ranked hits with exact selectors, `known_at` time travel, observation-date bounds and full citations |
| `evidence_history` | Every retained revision of one observation, including corrections, retractions and restorations, in pages |

Point the server at an existing ledger by its absolute path. On Windows, write the path with forward slashes, such as `C:/research/evidence.db`. With [uv](https://docs.astral.sh/uv/) installed, the configurations below fetch everything else.

Claude Code:

```shell
claude mcp add ucde -- uvx --from "ucde[mcp]" ucde-mcp --db /absolute/path/evidence.db
```

Claude Desktop, Cursor, Windsurf and other clients that read an `mcpServers` file:

```json
{
  "mcpServers": {
    "ucde": {
      "command": "uvx",
      "args": ["--from", "ucde[mcp]", "ucde-mcp", "--db", "/absolute/path/evidence.db"]
    }
  }
}
```

VS Code, in `.vscode/mcp.json`:

```json
{
  "servers": {
    "ucde": {
      "type": "stdio",
      "command": "uvx",
      "args": ["--from", "ucde[mcp]", "ucde-mcp", "--db", "/absolute/path/evidence.db"]
    }
  }
}
```

Without uv, run `pip install "ucde[mcp]"` and use `ucde-mcp --db /absolute/path/evidence.db` as the command. From 0.2.1, `ucde --db /absolute/path/evidence.db mcp` starts the same server.

The server opens the file read-only and refuses a file whose schema UCDE did not create. Tool errors do not echo paths or database details. The server uses the MCP Python SDK 2.3 and accepts both the initialize handshake (protocol 2025-11-25) and the per-request protocol (2026-07-28). Read the [threat model](https://github.com/mqfarooqi1/ucde/blob/main/security/THREAT_MODEL.md) before you open a store to an agent.

## Guide

### Load and replay dataset releases

Use `store.apply_batch(...)` to commit a complete set of changes as one event. Pass `EvidenceWrite` for new or corrected records and `EvidenceRetraction` for records that should cease to be active. Each change carries the current expected revision, with `0` for a new identifier. All revisions in a batch share one `recorded_at`. `store.get(id, known_at=cutoff)` returns the active revision by ID using the recording cutoff alone. Earlier revisions remain available through `store.history(id)`.

The [JARVIS release replay](https://github.com/mqfarooqi1/ucde/blob/main/benchmarks/real_data/README.md#replay-two-published-jarvis-releases) applies these operations to two checksummed public archives. Its recording clock uses each publisher release instant to reconstruct historical availability.

### Export a historical evidence packet

Use `ucde export` to save a scoped text search, its recording cutoff, and the exact results with citations and revision numbers. A collaborator can read the JSON and verify the packet offline. The cutoff is any ISO 8601 time with a UTC offset, such as the `recorded_at` of your latest write.

```shell
ucde --db breeding-evidence.db export "plant height" --subject W-017 --known-at <cutoff> --output height-packet.json
ucde verify-packet height-packet.json
```

The export prints a SHA-256 receipt. To compare a copy against a digest received separately, pass that digest to `ucde verify-packet` with `--expected-sha256`. The Python SDK also provides `export_packet` and `verify_packet`. [Public examples and attribution](https://github.com/mqfarooqi1/ucde/blob/main/examples/README.md#portable-packets-from-published-datasets).

#### Compare two packets

```shell
ucde compare earlier-packet.json later-packet.json
```

The report matches records by evidence ID and shows changes to the evidence, citation, revision, and ranking. It also shows differences in search settings and the effective observation cutoff for each packet. A record present in just one result can reflect the query, the result limit, or the ledger state. Supply `--before-sha256` and `--after-sha256` to check the files against digests received separately. The SDK equivalent is `compare_packets`.

#### Replay a packet against a ledger

```shell
ucde --db breeding-evidence.db replay height-packet.json
```

Replay runs the saved query and selectors at the packet's recording cutoff. It opens the ledger read-only and reports whether the new result has the same digest. A difference report includes changes to returned records, citations, ranking, and search candidate counts. The command exits 0 for a match and 1 for a difference or invalid packet. To supply a separately obtained digest, use `--expected-sha256`. The SDK equivalent is `replay_packet`.

### Check a ledger

`ucde --db evidence.db verify` audits a file without changing it. It runs SQLite's integrity check, then confirms each ledger invariant against the stored payloads, for example that an observation's revisions are consecutive, that recording times stay in order, and that every search entry matches the payload it indexes. It prints a JSON report and exits 1 when it finds a problem, so it can gate a backup, a restore or a scheduled job. `MemoryStore.verify()` returns the same report in Python. Every open also refuses a file whose schema UCDE did not create, such as one that defines a trigger or view.

#### Save and check a ledger checkpoint

```shell
ucde --db evidence.db checkpoint     # prints known_at and sha256
ucde --db evidence.db checkpoint --known-at <known_at> --expected-sha256 <sha256>
```

Save the reported cutoff and SHA-256 separately from the ledger, for example in a lab notebook. Rechecking compares every retained revision through that cutoff, including retractions. Commits recorded after the cutoff preserve the checkpoint. A purge of covered history or a change to a covered citation produces a mismatch and exit code 1. The CLI opens the ledger read-only and returns the digest and counts. The Python SDK provides the same check through `MemoryStore.checkpoint()`.

#### Enable and verify a persistent ledger chain

```shell
ucde --db evidence.db enable-chain --output evidence-v3.db
ucde --db evidence-v3.db chain-head > trusted-head.json
ucde --db evidence-v3.db verify --head-file trusted-head.json
```

In Windows PowerShell 5.1, save the head with `| Set-Content -Encoding utf8 trusted-head.json` instead, because `>` in that shell writes UTF-16.

`enable-chain` audits and upgrades a new SQLite copy. The source remains the schema 2 backup when upgrading from schema 2. Save the chain head separately from the database. Verification checks the saved prefix and every commit that follows it, so later valid writes preserve the check and an older backup fails it. A purge retains opaque commitments and commit coordinates while removing the payload and nonce from the ledger. The SDK provides `MemoryStore.enable_chain()`, `chain_head()`, and `verify(expected_head=...)`. [Schema 3 format and migration](https://github.com/mqfarooqi1/ucde/blob/main/specifications/ledger-chaining-v3.md).

#### Export a portable history archive

```shell
ucde --db evidence.db archive --output evidence-history.jsonl     # prints a receipt with its sha256
ucde verify-archive evidence-history.jsonl --expected-sha256 <sha256>
```

The archive contains the full stored payload for every retained revision through its recording cutoff, including earlier versions, retractions, and stored vectors. Use `--known-at` to select a specific cutoff. The archive bytes hash to the same SHA-256 as a checkpoint at that cutoff. A recipient can verify the file offline using the digest you saved separately. The verifier returns exit 1 if the digest differs or the archive is malformed. Python applications can use `MemoryStore.export_archive()` and `verify_archive()`.

#### Package an archive for research exchange

```shell
ucde crate evidence-history.jsonl --expected-sha256 <sha256> --output research-crate --name "Study evidence" --description "Retained measurement revisions" --date-published 2026-12-05 --license "Internal research use"
ucde verify-archive research-crate/history.jsonl --expected-sha256 <sha256>
```

`ucde crate` validates the archive before packaging it with its checkpoint receipt, RO-Crate metadata, and a JSON-LD provenance graph. The graph records source locators and digests, revision links, and recording and observation times. Supply the title, description, publication date, and licence or terms that apply to your package. The Python equivalent is `create_crate()`. [RO-Crate 1.2](https://www.researchobject.org/ro-crate/specification/1.2/) · [W3C PROV-O](https://www.w3.org/TR/prov-o/).

### Run from a source checkout

```shell
python -m pip install .
python examples/evidence_walkthrough.py
python examples/agicam_wheat.py --wheat spring --variety 9 --sensor AG13 --vi NDVI --through 2022-06-10
python -m unittest discover -s tests -v
python -m benchmarks.run_memory --output my-memory-benchmark.json
```

`python -m pip install .` can fetch the pinned build dependency when needed. If `build` and setuptools 81.0.0 are already available, build and install entirely offline with `python -m build --no-isolation --wheel` followed by `python -m pip install --no-index --no-deps --find-links dist ucde`. To run without installing, set `PYTHONPATH` to `python` and use `python -m ucde` as the CLI command. The walkthroughs use temporary databases. The AGIcam example returns the original CSV line and measurement context from a small published dataset excerpt. [Dataset and licence](https://zenodo.org/records/17970104).

### Optional integrations

- `ucde models` and `ucde generate --model <installed-model> --prompt "Example"` connect to an already running Ollama daemon on numeric loopback. `ucde.ollama.OllamaClient.embed` computes an embedding explicitly. Use one pinned embedding space for compatible vectors. The ledger and MCP server never send retrieved evidence to Ollama. Disable cloud features and block outbound connectivity in offline deployments. [Ollama FAQ](https://docs.ollama.com/faq).
- With Docker Compose, `docker compose run --rm ucde` initializes a named volume in an isolated container. Pass CLI arguments after `ucde` for subsequent runs. The image contains the core CLI only and builds using the Docker base image and the pinned build backend. CI builds it and round-trips evidence with no network and a read-only root file system.

## Project status

UCDE is alpha software for research evidence. It has no clinical workflow or enterprise service. Start with the [Phase 0 assessment](https://github.com/mqfarooqi1/ucde/blob/main/research/phase-0-assessment.md), [algorithm specification](https://github.com/mqfarooqi1/ucde/blob/main/specifications/evidence-memory-v1.md), and [benchmark](https://github.com/mqfarooqi1/ucde/blob/main/benchmarks/README.md). The [development status](https://github.com/mqfarooqi1/ucde/blob/main/DEVELOPMENT_STATUS.md) records verified results, current limits and the next research milestone, and the [roadmap](https://github.com/mqfarooqi1/ucde/blob/main/ROADMAP.md) lists what comes next. The [threat model](https://github.com/mqfarooqi1/ucde/blob/main/security/THREAT_MODEL.md) explains the local trust boundary. Use separate files and OS permissions for different principals.

## Contributing

Bug reports, research use cases and pull requests are welcome. Read the [contributing guide](https://github.com/mqfarooqi1/ucde/blob/main/CONTRIBUTING.md) and the [code of conduct](https://github.com/mqfarooqi1/ucde/blob/main/CODE_OF_CONDUCT.md). Report security problems privately as described in the [security policy](https://github.com/mqfarooqi1/ucde/blob/main/SECURITY.md). If UCDE is useful to you, a star on [GitHub](https://github.com/mqfarooqi1/ucde) helps other researchers find it.

## Citation and licence

To cite UCDE, use [CITATION.cff](https://github.com/mqfarooqi1/ucde/blob/main/CITATION.cff) or the "Cite this repository" button on GitHub. UCDE is licensed under Apache-2.0. See [LICENSE](https://github.com/mqfarooqi1/ucde/blob/main/LICENSE).

Created and maintained by [Muhammad Q Farooqi](https://github.com/mqfarooqi1).
