Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions NOTICE.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,11 @@ the upstream license, source revisions and attribution. New Python contracts,
local generations and evaluation tooling implement this adaptation's narrower
scope; no Rust kernel, broker or enterprise infrastructure is ported. Existing
Writ and JolliAI credits above remain applicable.

## Canonical-memory follow-up

The opt-in native projection and grounded-context workflow applies Writ V2
retrieval/memory design inputs at `a0e0e413e3b20082a85e7d75c58b45b0ba09b903`.
New public source passages retain exact MIT Writ citations and the existing
Lucio Saldivar / JolliAI attribution. OpenAI Codex assisted with implementation,
provisional labels and evaluation; independent human review remains pending.
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ bounded graph enrichment, weighted ranking, filtering, abstention and context
budget selection. Decision and memory recall is a separate path. No Neo4j server,
Bolt driver, agent host or Writ V2 kernel is required.

## Opt-in canonical memory indexes

A follow-up adds persistent native Relate projections from the canonical memory
ledger, full-text context cards and explicit source/evidence requirements. The
existing retrieval paths remain controls. See [commands](experiments/reliable_memory/COMMANDS.md),
[contracts](experiments/reliable_memory/CONTRACTS.md) and [measured findings](experiments/reliable_memory/FINDINGS.md).
On the provisional held-out natural-language subset, grounded flat/native deliver
20/24 labeled passages versus legacy hybrid’s 19/24; development regresses
15/24 versus 17/24. Native is slightly slower at the median. This does not establish a graph advantage or better agent outcomes.
Human review and actual generative trials remain pending.

## Reliable versioned context (Phase 3)

A separate local path binds guidance, memory, evidence and rendering to one
Expand All @@ -20,7 +31,7 @@ See [runnable Phase 3 commands](docs/PHASE3.md), the [V2 scope map](docs/phase3/
The real-history experiment is deliberately reported without a graph-advantage
claim: connected covers 3/10 target source versions versus flat hybrid's 4/10.
Labels remain unreviewed; no generative-agent outcome experiment was run.
Current validation is **117 pytest checks**, five original demo checks and nine
Historical Phase 3 validation is **117 pytest checks**, five original demo checks and nine
scripted restart/retraction checks. Original
weighted retrieval and all Phase 1/2 fixtures/evidence remain available below.

Expand Down
10 changes: 10 additions & 0 deletions docs/VALIDATION.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Validation

## Canonical memory / native projection follow-up

The isolated follow-up passes **149 pytest checks** and all five original unittest demo checks. It preserves prior evidence and adds actual persistent native
index refresh/restart/corruption checks, complete-passage context, explicit
requirements and a 17-process CLI workflow. See [findings](../experiments/reliable_memory/FINDINGS.md),
[commands](../experiments/reliable_memory/COMMANDS.md), and machine-readable
[held-out results](../experiments/reliable_memory/evidence/heldout/summary.json).
The 72-task benchmark remains provisional and unreviewed; actual generative-agent
trials are NOT RUN. Prior evidence remains historical and byte-preserved.

## Phase 3 evidence

**117 pytest checks pass**, including real Relate regressions; the original five
Expand Down
74 changes: 74 additions & 0 deletions experiments/reliable_memory/COMMANDS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Run the opt-in workflow

Use Python 3.12 on Linux x86_64. From the repository root:

```bash
python -m pip install -c requirements-validated.txt -e '.[dev]'
python scripts/prepare_model.py --output data/model
git clone --single-branch --branch v2/architecture-rebuild https://github.com/infinri/Writ ../Writ-public
python scripts/offline_run.py -m pytest -q
python scripts/offline_run.py -m unittest discover -s tests -v
python scripts/offline_run.py -m experiments.reliable_memory.audit \
--repo ../Writ-public --out data/passage-provenance.json
```

Clone/model preparation is online and explicit. Everything below is local; ingestion reads exact objects and never checks out or executes upstream code. Keep the upstream checkout read-only. Use fresh work and result directories for each run.

```bash
python scripts/offline_run.py -m experiments.reliable_memory.run \
--model-dir data/model --work-dir data/reliable-dev \
--out data/reliable-dev-results --split development
python scripts/offline_run.py -m experiments.reliable_memory.run \
--model-dir data/model --work-dir data/reliable-heldout \
--out data/reliable-heldout-results --split heldout
python scripts/offline_run.py -m experiments.reliable_memory.analyze \
--results data/reliable-heldout-results/queries.jsonl.gz \
--out data/reliable-heldout-results/comparison.json
python scripts/offline_run.py -m experiments.reliable_memory.demo \
--repo ../Writ-public --model-dir data/model \
--work-dir data/reliable-demo --out data/reliable-demo-results
```

The frozen held-out set has now been opened. It is a regression set for future work. Do not tune against it and then claim unseen evaluation; freeze a new set first. `freeze.py --repo PATH` reproduces input preparation, not a way to overwrite gold while retaining its old evidence claims.

## Supported owner capture, offline context and inspection

```bash
python -m writ_retrieval.reliable.cli --store data/local-memory passage-ingest \
--repo ../Writ-public --revision a0e0e413e3b20082a85e7d75c58b45b0ba09b903 \
--path docs/architecture/retrieval-and-memory.md --project writ-public --create
python -m writ_retrieval.reliable.grounded_cli \
--store data/local-memory --model-dir data/model --cache-dir data/local-indexes \
--project writ-public --backend relate --arm hybrid \
'What distinguishes retrieved guidance from execution permission?'
```

`grounded_cli` installs the same network deny as the legacy read-only agent before loading third-party runtimes. Default backend is `flat`; native `relate` is opt-in. Use `--request request.json` for exact source/binding, history and evidence requirements described in CONTRACTS.md. Use `--require KEY_TOKEN` for hard required records and `--max-bytes/--max-chars` for the entire payload. `--inspect` returns owner diagnostics; give a model only the wrapper's `payload`.

Capture/feedback/claim/retraction/lifecycle commands remain `reliable.cli`, using the Phase 3 contracts and actual local-owner terminal for confirmation/review. Those commands are absent from the grounded agent. Existing `reliable.agent context/inspect`, weighted `writ-retrieval query`, and Phase 2 connected/recall commands remain unchanged controls.

Read exact versions with the legacy read-only inspector, using a grounded cache directory and returned generation:

```bash
python -m writ_retrieval.reliable.agent --store data/local-memory inspect \
'{"project":"writ-public","label":"Claim","id":"EXACT_ID_FROM_CONTEXT"}' \
--project writ-public --generation sha256:EXACT_GENERATION --cache-dir data/local-indexes
```

For a corrupt derived index: stop the context process, take the exact projection identity from diagnostics/pointer, quarantine it through the owner CLI, then rerun context. Keep canonical data intact.

```bash
python -m writ_retrieval.reliable.cli --store data/local-memory projection-quarantine \
--cache-dir data/local-indexes --identity sha256:EXACT_PROJECTION_ID
```

## Review and actual generative trials

```bash
python scripts/offline_run.py -m experiments.reliable_memory.prepare_review \
--results data/reliable-heldout-results/queries.jsonl.gz --out data/new-review
python scripts/offline_run.py -m experiments.reliable_memory.agent \
--packets data/new-review/agent-packets.json.gz --out data/agent-status
```

The last command records NOT RUN without a generative host. Once explicitly authorized, run the **separate experimental** harness outside the offline agent with `--endpoint http://127.0.0.1:PORT/v1 --model EXACT_MODEL --model-revision IMMUTABLE_REVISION`. It only accepts localhost; existing offline controls are unchanged. Four profiles (no history, legacy hybrid, grounded flat, grounded Relate), identical prompts/tools/one-packet allowance/budgets, three paired repetitions and fixed seeds. It records actual model responses, usage if supplied, errors and traces; costs remain unknown if the host does not report billing. It is fixed-context QA, not query rewriting or repository-editing task execution. Human review of responses is still required.
45 changes: 45 additions & 0 deletions experiments/reliable_memory/CONTRACTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Opt-in reliable-memory contracts

This implements selected retrieval/memory parts of Writ V2 at `a0e0e413e3b20082a85e7d75c58b45b0ba09b903`. The Phase 3 contracts remain the canonical ledger contracts. No kernel, broker, authentication service or execution permission is added.

| Responsibility | Existing guarantee retained | New opt-in behavior |
| --- | --- | --- |
| Canonical capture / feedback | ReliableStore transaction/revision, exact Rule/Decision/Outcome bindings, durable receipts, separate owner confirmation | All native search rows derive from one exported transaction; native indexes never own these semantics |
| Source identity | Qualified Key, immutable source revision and text/subject digests; source statements unverified | Bounded read-only Markdown paragraph ingestion; optional complete comparison against local Git objects |
| Index freshness | Content-addressed source snapshot, complete replacement, failed refresh unavailable | Separate native persistent Relate index per permitted/request-filtered partition; complete database-file manifest, exact text/vector/payload bindings, read-only reopen |
| Publication | Source generation remains inspectable | `writ-grounded-pointer/1` publishes source generation + revision + projection identity/manifest together, with previous distinct source generation |
| Lifecycle | Retraction and supersession preserve historical ledger records | Current records only by default; stale-subject Evidence excluded. Explicit history can include clearly marked historical/retracted/obsolete evidence |
| Graph | Typed, source-bound relations, two hops / 64 visits; invisible/retracted bridges excluded; non-seed Rules excluded | Ranked candidates precede optional enrichment. Required/mandatory/conflict bundles still take priority. Old unbound extra edges remain intentionally excluded |
| Evidence request | Integrity, source verification and approval remain separate | `writ-context-request/1` supports a source URI+revision OR current exact record binding, optional owner-confirmed evidence, explicit history flag |
| Output | One complete UTF-8 / character budget; explicit required-content errors | Full joined record text; no 640-character truncation; rendered-text digest; deterministic indivisible conflict bundles and omission metadata |
| Approval | Actual local terminal judgment, distinct from correlated observations | No approval/confirmation command in the grounded agent CLI; no imported text can grant verification |

## Context requests

```json
{"contract_version":"writ-context-request/1","source":{"uri":"https://github.com/infinri/Writ/blob/EXACT40HEX/docs/architecture/retrieval-and-memory.md#L5","revision":"EXACT40HEX"},"verification":"owner_confirmed","include_history":false}
```

Replace placeholders with real values. `source` accepts only URI and revision selectors (Source's other optional fields are rejected). Alternatively supply `binding` as the exact `{ref, revision, content_digest}` returned by inspection. A binding must match the node in this snapshot, including its current lifecycle revision. An old pre-supersession binding cannot silently rebind to a later record. Use a historical source selector or inspect the exact old snapshot for historical material.

`evidence_assessment.status` is `requirements_satisfied`, `insufficient` or `unassessed`. The first means that at least one permitted **complete** record meets the explicit mechanical request and is delivered. It says nothing about general semantic sufficiency or truth. A generic question without requirements is unassessed even when records are retrieved. Owner-confirmed requirements do not treat Git object identity, a content hash, repository text, a tool assertion, or review eligibility as human confirmation. An unavailable/unfittable required record is an error. An absent requested source or verification class yields `insufficient`; mandatory guidance may still be delivered. `abstained` describes empty delivered context; `ranked_abstained` describes candidate selection. Neither is a generated-agent outcome.

## Generations, indexes and recovery

`GroundedSession` reuses the source snapshot/cache implementation with a separate frozen `writ-grounded-policy/1`; the default `ReliableSession` policy bytes remain unchanged. Generation identity covers the full canonical export, revision, encoder identity, policy and lifecycle classification. Counts are recomputed from that export using the retained active-confidence algorithm. Wording restoration under a new revision does not reactivate old observations.

Relate 1.0.1 native `CREATE VECTOR INDEX`, `CREATE FULLTEXT INDEX`, `db.index.vector.queryNodes` and `db.index.fulltext.queryNodes` are tested on actual persistent stores. Vector search scans the whole bounded permitted partition before deterministic ties; `(native_score*2)-1` is compared with the raw cosine gate. Exact-vector mechanics are checked against an application dot-product oracle. Fulltext analyzers are not assumed numerically equivalent: candidate-order differences are published. RRF, typed graph traversal, conflict closure and output assembly remain application-owned.

The native directory contains a read-only Relate database and manifest binding the complete database files, rows, source generation, project and engine profile. Build into a temporary sibling, close/checkpoint the engine, fsync completed files and rename before opening read-only. Validate index text, vectors and citation payload against the canonical rows. Every query also checks file digests, so an open reader cannot conceal offline corruption. Partition before top-k prevents hidden-project candidate starvation and hidden-document IDF influence. Local permitted partitions are application logic, not database authorization. Historical doctrine visibility, including global doctrine types and explicitly supported `_shared` records, is unchanged; caller project selection is a local-owner convention, not authenticated tenancy.

Only after search, contract checks, complete rendering, canonical revision and expiry checks succeed does `GROUNDED-CURRENT.json` publish the source/projection receipt. A failed build, query, render or publication returns no fresh payload. Prior generations are retained for inspection, never served as current after an update failure. `CURRENT.json` remains the legacy pointer. Concurrent threads/writers, protected clocks, hostile same-account modification and power-loss durability have not been established. Process restart is tested.

A corrupt derived index is not silently healed or used. Close the reader, run the owner-only `projection-quarantine` command with its exact identity, then start a fresh context process. Damaged bytes and a recovery receipt are retained; the next context rebuilds and validates from canonical data before publication. No source record or observation is deleted. Quarantine is derived-cache recovery, not evidence retraction.

Caches retain old source/index generations on disk; compaction is not implemented. In-memory native/keyword partition handles are bounded to two per session. A canonical revision currently causes a complete source generation build/embedding pass even if text is unchanged; incremental vector reuse and large-corpus refresh costs remain work.

## Budget and source semantics

The default limits are 8,000 UTF-8 bytes and 6,000 Unicode codepoints for the **entire canonical JSON payload**, including trust, request, snapshot, projection, citations and omissions. Records/conflict bundles are indivisible: skip a whole optional bundle or return `BudgetError` for required content. All delivered text is complete; omitted records are listed in diagnostics. `ceil(chars/4)` remains a heuristic. The pinned MiniLM tokenizer is an embedding tokenizer with 128-token inputs, not a target generative-model tokenizer; no exact output-token claim is made.

The paragraph importer reads Git objects without checkout, hooks, fetch or repository execution. It accepts normalized `.md` paths, at most 32 files / 8 MB / 1,000 selected paragraphs, exact forty-hex revisions, and preserves line/character intervals and source digests in the import receipt. It selects paragraphs 70–1,600 characters long under level-two headings; code/table blocks and other material are not an exhaustive repository export. Identity includes exact Git revision and a path/offset/text digest. Reimport is idempotent, changed immutable meaning is rejected and batch failures roll back. Different snapshots can coexist; importing a newer paragraph export does **not** infer supersession of older paragraphs or identify renamed sections. Explicit lifecycle operations or separate as-of stores are required. Verification against a local object database establishes byte/object identity only; it does not authenticate remote publication or verify assertions in prose.
Loading
Loading