Metadata-Version: 2.4
Name: chronomemory
Version: 0.1.7
Summary: Epistemic State Database — tamper-evident WAL-based persistence for agentic AI workflows.
Author: Layer1Labs Silicon, Inc.
License-Expression: LicenseRef-Proprietary
Project-URL: Homepage, https://github.com/layer1labs/chronomemory
Project-URL: Documentation, https://specsmith.readthedocs.io/en/stable/esdb/
Project-URL: Repository, https://github.com/layer1labs/chronomemory
Project-URL: Issues, https://github.com/layer1labs/chronomemory/issues
Project-URL: Changelog, https://github.com/layer1labs/chronomemory/blob/main/CHANGELOG.md
Project-URL: Licensing, https://layer1labs.com/esdb-licensing
Keywords: esdb,epistemic-ai,agent-memory,wal,agentic-ai,chronomemory,anti-hallucination,oea,epistemic-state-database,layer1labs
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: COMMERCIAL-LICENSE.md
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: pre-commit>=3.0; extra == "dev"
Provides-Extra: rust
Requires-Dist: maturin>=1.4; extra == "rust"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.6; extra == "docs"
Requires-Dist: mkdocs-material>=9.5; extra == "docs"
Requires-Dist: pymdown-extensions>=10.0; extra == "docs"
Dynamic: license-file

# chronomemory

**Epistemic State Database (ESDB) for agentic AI workflows.**

[![GitHub](https://img.shields.io/badge/github-layer1labs%2Fchronomemory-8b5cf6?logo=github)](https://github.com/layer1labs/chronomemory)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org)
[![License: MIT](https://img.shields.io/badge/license-MIT%20%28SQLite%29-green)](https://opensource.org/licenses/MIT)
[![License: Commercial](https://img.shields.io/badge/license-Commercial%20%28ESDB%29-red)](COMMERCIAL-LICENSE.md)
[![PyPI](https://img.shields.io/pypi/v/chronomemory?label=PyPI&color=blueviolet)](https://pypi.org/project/chronomemory/)
[![Dependencies](https://img.shields.io/badge/runtime%20deps-none-brightgreen)](pyproject.toml)
[![Tests](https://img.shields.io/badge/tests-197%20passing-brightgreen)](tests/)
[![specsmith ESDB](https://img.shields.io/badge/specsmith-ESDB%20docs-8b5cf6)](https://specsmith.readthedocs.io/en/stable/esdb/)

---

## Why chronomemory?

Traditional databases store **facts**. Agentic AI systems produce **beliefs** — and beliefs have properties that facts do not:

- **Provenance** — was this observed by a sensor, inferred by logic, or hallucinated by an LLM?
- **Confidence** — how strongly is this held? Is it safe to inject into RAG context?
- **Recursion depth** — was this produced by an agent acting on another agent's output?
- **Tamper-evidence** — if someone edits a past belief to hide a mistake, will you know?

chronomemory makes these properties **mandatory on every record** and uses a SHA-256 hash chain to make every past write tamper-evident.

---

## 30-second example

```python
from chronomemory import ChronoStore, ChronoRecord

with ChronoStore("/path/to/project") as store:

    # Write a benchmark result with full epistemic provenance
    store.upsert(ChronoRecord(
        id="bench-A-seed42",
        kind="fact",
        label="Model achieves 0% invalid rollout rate on benchmark",
        source_type="observed",   # H19 — was this measured or inferred?
        confidence=1.0,            # H17 — degree of belief (0.0–1.0)
        evidence=["seed=42", "epoch=50", "model=AgentModel"],  # H20
        epistemic_boundary=["model:AgentModel-v1", "dataset:benchmark-A"],  # H15
        data={"invalid_rate": 0.0, "nll_bits": 0.312},
    ))

    # Confidence-filtered RAG query — H18 enforced
    context = store.query(rag_filter=True)   # confidence >= 0.6 only

    # Tamper detection
    assert store.chain_valid()   # False if any past event was modified
```

---

## Licensing

chronomemory has **two tiers**. Choose based on your needs:

| | 🆓 SQLite backend | 💼 ESDB backend |
|---|---|---|
| **How to get it** | `pip install specsmith` (bundled, default) | `pip install chronomemory` |
| **License** | **MIT** — free, no key required | **Commercial** — license key required |
| **Storage engine** | SQLite WAL | NDJSON SHA-256 hash chain |
| **Tamper-evidence** | ❌ | ✅ |
| **OEA anti-hallucination fields** | ❌ | ✅ |
| **Zero runtime deps** | ❌ (sqlite3 stdlib) | ✅ (pure Python stdlib) |
| **Default for specsmith** | ✅ yes | opt-in via `[esdb]` extra |

> **TL;DR — start free.** `pip install specsmith` gives you the SQLite backend at no cost under MIT.
> Upgrade to the ESDB engine when you need tamper-evidence and OEA fields by obtaining a
> commercial license from [licensing@layer1labs.com](mailto:licensing@layer1labs.com).

---

## Installation

### Free tier — SQLite backend (MIT, default)

The SQLite backend is bundled in **specsmith** and requires no license:

```bash
pip install specsmith
```

No additional setup. specsmith uses SQLite storage automatically.

### Commercial tier — ESDB engine (license required)

The full ESDB engine with SHA-256 hash chain, tamper-evidence, and OEA fields:

```bash
# Step 1 — obtain a license key
# Email licensing@layer1labs.com with your organisation name and intended use.
# You will receive a signed .esdb.key file.

# Step 2 — install
pip install chronomemory                     # standalone
# or via specsmith:
pip install "specsmith[esdb]"

# Step 3 — activate your license
specsmith esdb enable --key-file /path/to/your.esdb.key
specsmith esdb status                        # confirms ChronoStore is active
```

Or install standalone (without specsmith):

```bash
pip install chronomemory
```

Add to `pyproject.toml`:
```toml
dependencies = [
    "chronomemory>=0.1.6",
]
```

**Zero runtime dependencies** — pure Python stdlib (`hashlib`, `json`, `os`, `shutil`, `pathlib`).

Full walkthrough: [specsmith ESDB documentation](https://specsmith.readthedocs.io/en/stable/esdb/)

---

## OEA anti-hallucination fields

Every `ChronoRecord` carries 7 mandatory OEA (Ontological Epistemic Anchoring) fields. Safe defaults apply when omitted.

| Field | Rule | Default | Description |
|-------|------|---------|-------------|
| `source_type` | H19 | `"observed"` | `observed` \| `inferred` \| `hypothesis` \| `synthetic` |
| `confidence` | H17 | `0.7` | Float 0.0–1.0. RAG threshold: `>= 0.6` |
| `evidence` | H20 | `[]` | Source references (doc IDs, URLs, experiment IDs) |
| `epistemic_boundary` | H15 | `[]` | Scope constraints on validity |
| `is_hypothesis` | H20 | `False` | True = tentative, untested belief |
| `model_assumptions` | H21 | `{}` | `{provider, model, temperature, context_window}` |
| `recursion_depth` | H16 | `0` | 0 = human; N = agent chain depth |

`query(rag_filter=True)` returns only records with `confidence >= 0.6` AND `status == "active"` (H18).

---

## Core API

### ChronoStore

```python
from chronomemory import ChronoStore, ChronoRecord

# Context manager (recommended)
with ChronoStore("/path/to/project", recursion_depth=0) as store:
    ...

# Manual lifecycle
store = ChronoStore(project)
store.open()
store.upsert(record)          # write to WAL
records = store.query()       # read from memory
store.delete("FACT-001")      # tombstone (never physical deletion)
assert store.chain_valid()    # verify SHA-256 chain
store.compact()               # truncate WAL → snapshot + 1 sentinel
store.close()
```

**All query parameters:**

```python
store.query(
    kind="fact",           # filter by kind (None = all)
    status="active",       # "active" | "deprecated" | "tombstone" | "" (all)
    rag_filter=True,       # H18: confidence >= 0.6 only
    min_confidence=0.9,    # custom threshold (takes max with rag_filter)
)
```

### ChronoRecord kinds

`fact` · `hypothesis` · `requirement` · `testcase` · `decision` · `risk`

### EsdbBridge

Unified adapter: delegates to `ChronoStore` when `.chronomemory/events.wal` exists; falls back to `.specsmith/*.json` for uninitialized projects.

```python
from chronomemory import EsdbBridge

bridge = EsdbBridge(project_dir=".")
print(bridge.status().to_dict())   # backend, record_count, chain_valid, wal_seq
reqs  = bridge.requirements()      # list[EsdbRecord]
tests = bridge.testcases()          # list[EsdbRecord]
```

---

## Where data lives

```
<project_root>/
  .chronomemory/
    events.wal        ← append-only NDJSON, SHA-256 chained
    snapshot.json     ← materialized state (every 50 events)
    backup/
      20260518T170000/  ← timestamped backup
```

The WAL is NDJSON — human-readable, grep-able, diff-able, no special tooling needed:

```bash
cat .chronomemory/events.wal | python -m json.tool
grep '"op": "upsert"' .chronomemory/events.wal | wc -l
```

---

## Migration from .specsmith/ JSON

Projects using specsmith store requirements and test cases as flat JSON. Migrate to ESDB to gain OEA fields and tamper-evidence:

```python
from chronomemory import ChronoStore
from pathlib import Path

with ChronoStore("." ) as store:
    counts = store.migrate_from_json(Path(".specsmith"))
    print(counts)  # {'requirements': 12, 'testcases': 10, 'skipped': 0}
```

Or: `specsmith esdb migrate` (requires specsmith ≥ 0.13.0)

**Import map:**
```
# Before (specsmith vendored)
from specsmith.esdb.store import ChronoStore, ChronoRecord
from specsmith.esdb.bridge import EsdbBridge

# After (standalone)
from chronomemory import ChronoStore, ChronoRecord, EsdbBridge
```

WAL format is identical — existing `.chronomemory/events.wal` files are fully compatible.

---

## Integration

### chronoagent — memory write gate + RAG source

```python
# chronoagent/memory/store.py
from chronomemory import ChronoStore, ChronoRecord

class AgentMemoryStore:
    def __init__(self, project_root: str, agent_depth: int = 1):
        self._store = ChronoStore(project_root, recursion_depth=agent_depth)
        self._store.open()

    def write_belief(self, content: str, confidence: float = 0.7, evidence=None) -> str:
        """Called by memory_write_gate after gate passes."""
        import uuid
        rid = str(uuid.uuid4())
        self._store.upsert(ChronoRecord(
            id=rid, kind="fact", label=content,
            source_type="inferred", confidence=confidence,
            evidence=evidence or [],
        ))
        return rid

    def rag_context(self) -> list[dict]:
        """Confidence-filtered beliefs for RAG retrieval."""
        return [
            {"chunk_id": r.id, "content": r.label,
             "authority_score": r.confidence, "source_type": r.source_type}
            for r in self._store.query(rag_filter=True)
        ]
```

### specsmith — governance store

```python
# specsmith reads requirements/testcases via EsdbBridge
from chronomemory import EsdbBridge

bridge = EsdbBridge(project_dir=".")
reqs = bridge.requirements()   # ESDB WAL or .specsmith/ JSON fallback
```

---

## Python vs Rust

| | Python (`src/chronomemory/`) | Rust (`crates/chronomemory/`) |
|---|---|---|
| **Status** | ✅ Production-ready | 🔧 Phase 2 (bindings pending) |
| **WAL format** | NDJSON (canonical) | Binary bincode (needs migration) |
| **Deps** | stdlib only | serde, sha2, uuid, chrono |
| **Dep graph** | ✅ (`DepGraph`) | ✅ typed edges |
| **Rollback cascade** | ✅ (`invalidate`) | ✅ transitive invalidation |
| **Context pack** | ✅ (`ContextPackCompiler`) | ✅ token-budget assembly |
| **PyO3 bindings** | — | Phase 2 |

**Phase 2**: migrate Rust WAL to NDJSON → add PyO3 bindings → `from chronomemory import ChronoStore` transparently uses Rust with Python fallback.

---

## Test suite

197 tests, all passing on Python 3.10–3.13 (Linux + Windows):

```bash
pip install -e ".[dev]"
pytest tests/ -v
```

Test categories:
- **test_store.py** — snapshot replay, tombstone, migration, zero-deps
- **test_wal_chain.py** — hash chain integrity, NDJSON format, atomic writes, cross-project compat
- **test_oea.py** — all 7 OEA fields, WAL round-trip, recursion depth stamping
- **test_query.py** — confidence filtering, RAG threshold, kind/status filters
- **test_robustness.py** — 60+ tests: WAL corruption at multiple offsets, hash tampering, binary garbage, snapshot gaps, write failure simulation, crash recovery, CRLF, Unicode, Arabic RTL, 100KB payloads, compact/backup/lifecycle
- **test_bridge.py** — EsdbBridge delegation, JSON fallback, write operations

---

## Docs

Full documentation is available via the **[specsmith ESDB docs](https://specsmith.readthedocs.io/en/stable/esdb/)**.

---

## Spec

Implements **ESDB-Specification.md v1.0** (Layer1Labs, proprietary).

---

© 2026 Layer1Labs Silicon, Inc. All rights reserved.
SQLite backend: [MIT License](https://opensource.org/licenses/MIT).
ESDB engine: proprietary — see [LICENSE](LICENSE) and [COMMERCIAL-LICENSE.md](COMMERCIAL-LICENSE.md).
