Metadata-Version: 2.4
Name: ucde
Version: 0.2.0
Summary: Local experimental evidence memory with repeatable historical search
Author: Muhammad Q Farooqi
License-Expression: Apache-2.0
Project-URL: Repository, https://github.com/mqfarooqi1/ucde
Project-URL: Changelog, https://github.com/mqfarooqi1/ucde/blob/main/CHANGELOG.md
Keywords: research data,provenance,evidence retrieval,plant breeding,sqlite,mcp
Classifier: Development Status :: 3 - Alpha
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 :: Scientific/Engineering
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

# Universal Cognitive Data Engine

UCDE is a local evidence ledger and search engine for experimental research. It helps a researcher recover the observation behind a result, see which version was available at a past cutoff, and filter to the genotype or sample, variable, method, scale and conditions that make the observation relevant.

The first workflow uses plant breeding records. The same schema supports assay-method records, as demonstrated with a fictional nonpatient example. UCDE preserves independent observations even when they disagree, keeps corrections and retractions in history, and returns source references and ranking components. Python and SQLite store and search evidence without model inference or network calls.

## Run locally

Use Python 3.11+ with SQLite built with FTS5 and JSON functions. From this folder, `python -m pip install .` installs the core library and `ucde` command. It 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==0.2.0`. The wheel has no runtime dependencies.

```powershell
ucde --db evidence.db init
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
```

From a source checkout without an install, set `$env:PYTHONPATH = 'python'` in PowerShell or `export PYTHONPATH=python` in a POSIX shell. Use `python -m ucde` as the CLI command in that case. 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).

## Store and retrieve an observation

```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.

## 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](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.

```powershell
$cutoff = (Get-Date).ToUniversalTime().ToString("o")
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](examples/README.md#portable-packets-from-published-datasets).

### Compare two packets

```powershell
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

```powershell
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

```powershell
$checkpoint = ucde --db evidence.db checkpoint | ConvertFrom-Json
ucde --db evidence.db checkpoint --known-at $checkpoint.known_at --expected-sha256 $checkpoint.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

```powershell
ucde --db evidence.db enable-chain --output evidence-v3.db
ucde --db evidence-v3.db chain-head | Set-Content -Encoding utf8 trusted-head.json
ucde --db evidence-v3.db verify --head-file trusted-head.json
```

`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](specifications/ledger-chaining-v3.md).

### Export a portable history archive

```powershell
$receipt = ucde --db evidence.db archive --output evidence-history.jsonl | ConvertFrom-Json
ucde verify-archive evidence-history.jsonl --expected-sha256 $receipt.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

```powershell
ucde crate evidence-history.jsonl --expected-sha256 $receipt.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 $receipt.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/).

## Optional interoperability

- Install `python -m pip install ".[mcp]"` and register `ucde-mcp --db <absolute-path-to-existing-db>` as a local stdio MCP server. The two evidence tools have read-only access to that file. 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). Its instructions tell clients to cite source and locator and to treat evidence text as data. Use `python -m ucde.mcp_server --db …` in a source environment with the MCP SDK installed.
- `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

Start with the [Phase 0 assessment](research/phase-0-assessment.md), [algorithm specification](specifications/evidence-memory-v1.md), and [benchmark](benchmarks/README.md). The [development status](DEVELOPMENT_STATUS.md) records verified results, current limits and the next research milestone. The [threat model](security/THREAT_MODEL.md) explains the local trust boundary. Use separate files and OS permissions for different principals. The prototype is intended for research evidence and has no clinical workflow or enterprise service.

## Licence

Apache-2.0. See [LICENSE](LICENSE). To cite UCDE, use [CITATION.cff](CITATION.cff).

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