From 66ebe0c3b060b32bc91d58c06b915af8615d46ef Mon Sep 17 00:00:00 2001 From: gosha70 Date: Tue, 24 Nov 2026 08:47:36 -0500 Subject: [PATCH 1/2] Add the context diff over a run's receipts (#119 H3) eval/context-diff/diff.py --store ...[,root=...] --run [--json ...] reads the run's receipts from the recall log (MCP recalls and hook blocks carrying its run_id) and reports, per memory the run received, its statuses against the store now: missing (deleted or expired, alone), superseded (and by what), withdrawn, changed, rehashed (another hashing scheme, hashes not compared), flagged (against the receipt's state), source changed (the source file is gone or hashes differently, through compute_content_hash), unknown (only cut-down receipts; combines with superseded and withdrawn) or unchanged. Each memory is judged by the last receipt in the run with its hash; a code chunk by its file record (parent_ref, the id's prefix once the chunk is gone, or a pre-0.4 owner's chunk_refs, as revalidation recognises it). Source checks need root=; without it they are skipped and each memory says "no source check (no root given)"; a given root is named in the report. Unreadable log files are skipped and counted, and a run with no records says the log was incomplete when any were. A note counts records whose ref_ids were cut short. No memory content; every scope read. Exit 0 report, 1 no record carries the run id, 2 usage or store error. CI's strict type check covers it. Spec: specs/memkernel-0-15-harness-foundations, amendment H3 (C1-C9). --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 8 + eval/context-diff/diff.py | 334 ++++++++++++++++++ ...igin-alignment-2026-11-24-0845-build-h3.md | 25 ++ .../tasks.md | 2 +- tests/unit/test_context_diff.py | 316 +++++++++++++++++ 6 files changed, 685 insertions(+), 2 deletions(-) create mode 100644 eval/context-diff/diff.py create mode 100644 specs/memkernel-0-15-harness-foundations/origin-alignment-2026-11-24-0845-build-h3.md create mode 100644 tests/unit/test_context_diff.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 72b43e5..11216b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,7 +58,7 @@ jobs: run: poetry run mypy src/ - name: Mypy (maintained eval tools) # Listed explicitly: only maintained tools, not the eval fixture and task trees. - run: poetry run mypy --strict eval/repeat-mistakes/count.py eval/repeat-mistakes/transcripts.py + run: poetry run mypy --strict eval/repeat-mistakes/count.py eval/repeat-mistakes/transcripts.py eval/context-diff/diff.py test: name: Tests diff --git a/CHANGELOG.md b/CHANGELOG.md index be0888a..99e26fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,14 @@ All notable changes to this project are documented here. The format follows ### Added +- **The context diff** (#119 H3; specs/memkernel-0-15-harness-foundations, amendment H3). + `eval/context-diff/diff.py --store … --run ` reads a run's receipts from the recall log and reports, per + memory the run received, what changed in the store since: `missing`, `superseded` (and by what), `withdrawn`, + `changed`, `rehashed` (another hashing scheme, never reported as changed content), `flagged`, `source changed` + (the source file is gone or hashes differently), `unknown` (only cut-down receipts) or `unchanged`. A code chunk is + judged by its file record. The report holds ids, hashes and sources, never memory content. Needs the recall log + and a `run_id` (H1). + - **Scope: private memory per agent and per task** (#119 H2; specs/memkernel-0-15-harness-foundations, amendment H2). A memory is `project` (the default, shared) or private to the caller's agent or task: `retain(scope="agent" | "task")`, with `agent_id`/`task_id` as tool arguments or `MEMKERNEL_AGENT_ID`/`MEMKERNEL_TASK_ID`. A caller sees diff --git a/eval/context-diff/diff.py b/eval/context-diff/diff.py new file mode 100644 index 0000000..43b1089 --- /dev/null +++ b/eval/context-diff/diff.py @@ -0,0 +1,334 @@ +# Copyright (c) 2026 EGOGE +# SPDX-License-Identifier: Apache-2.0 +"""Compare the context a run received with the store now (memkernel-0-15-harness-foundations H3: FR-004, SC-2). + +Reads a run's receipts from the recall log (MCP recalls and hook blocks whose ``run_id`` is the run's; H1) and gives +each memory the run received the statuses that apply against the store now (amendment H3, C1–C9): + +- ``missing``: no record, or expired. It stands alone. +- ``superseded`` (with what replaced it) or ``withdrawn`` (with the reason): read from the store. +- ``changed``: another ``content_hash`` under the same hashing scheme, for a record that still exists (a deleted + chunk is judged through its file record). ``rehashed``: the receipt's hash was made with another scheme than this + memkernel's, so it is not compared (C2); for code, the source check then only notices a file that is gone. +- ``flagged``: needs review now, and ``live`` in its receipt (the run did not see a flag). +- ``source changed``: the memory's ``source`` file under the project root no longer hashes to the receipt's + ``source_hash`` (a decision) or ``content_hash`` (code), through memkernel's own ``compute_content_hash``; a file + that is gone counts too. It says nothing about whether the memory is wrong, or about other files its text cites. +- ``unknown``: no receipt in the run has the memory's hash (every record that returned it was cut down). It combines + only with ``superseded`` and ``withdrawn``. +- ``unchanged``: nothing else applies. + +Each memory is judged by the last receipt in the run that has its hash (C1). A code chunk is judged by the file record +it belongs to: its ``parent_ref``, the id's prefix (``-chunk-``) once the chunk record is gone, or, for a +chunk from before 0.4, the code record whose ``chunk_refs`` lists it (as revalidation recognises it). Source checks +need ``root=``, the project the sources resolve under; without it they are skipped and each memory with a source +says so. Unreadable log files are skipped and counted. The report holds ids, hashes, sources and statuses, never +memory content; it reads every scope. Exit codes: 0 report printed, 1 no record carries the run id, 2 usage error or a +store it cannot open. + +Usage: + poetry run python eval/context-diff/diff.py \\ + --store name=main,chroma=.memkernel/chroma,state=.memkernel/state,project=default[,root=/path/to/project] \\ + --run [--json report.json] +""" + +from __future__ import annotations + +import argparse +import json +import sys +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[1] / "src")) + +from memkernel import recall_log # noqa: E402 +from memkernel.config import MemKernelSettings # noqa: E402 +from memkernel.core.models import MemoryType # noqa: E402 +from memkernel.memory.dedup import CONTENT_HASH_SCHEME, compute_content_hash # noqa: E402 +from memkernel.memory.lifecycle import memory_is_expired # noqa: E402 +from memkernel.storage.chroma import ChromaVectorStore # noqa: E402 + +if TYPE_CHECKING: + from memkernel.core.models import Memory + from memkernel.core.ports import VectorStorePort + +MISSING = "missing" +SUPERSEDED = "superseded" +WITHDRAWN = "withdrawn" +CHANGED = "changed" +REHASHED = "rehashed" +FLAGGED = "flagged" +SOURCE_CHANGED = "source changed" +UNKNOWN = "unknown" +UNCHANGED = "unchanged" +STATUSES = (MISSING, SUPERSEDED, WITHDRAWN, CHANGED, REHASHED, FLAGGED, SOURCE_CHANGED, UNKNOWN, UNCHANGED) +CHUNK_INFIX = "-chunk-" # a code chunk's id: -chunk- +NOTE_NO_ROOT = "no source check (no root given)" +NOTE_OUTSIDE_ROOT = "no source check (outside the project root)" +NOTE_UNREADABLE = "no source check (the file cannot be read as text)" +EXIT_REPORT, EXIT_NO_RECORDS, EXIT_USAGE = 0, 1, 2 + + +@dataclass +class Judged: + """One memory the run received, with its statuses (C3) and what explains them.""" + + ref_id: str + statuses: list[str] + source: str = "" + scope: str = "" + superseded_by: str = "" + withdrawn_reason: str = "" + owner: str = "" # a code chunk's file record + notes: list[str] = field(default_factory=list) + + +def parse_store(spec: str) -> tuple[MemKernelSettings, Path | None]: + """``name=…,chroma=…,state=…,project=…[,root=…]``: the count's store format, plus ``root``, the project that + sources resolve under (None when not given: no source checks). A bad spec or a missing store exits 2 (C5).""" + parts = dict(item.split("=", 1) for item in spec.split(",") if "=" in item) + missing = {"chroma", "state", "project"} - parts.keys() + if missing: + print(f"--store {spec!r}: missing {', '.join(sorted(missing))}", file=sys.stderr) + raise SystemExit(EXIT_USAGE) + if not Path(parts["chroma"]).is_dir(): + print(f"--store {spec!r}: no store at {parts['chroma']}", file=sys.stderr) # reading must not create one + raise SystemExit(EXIT_USAGE) + root = Path(parts["root"]).resolve() if parts.get("root") else None + settings = MemKernelSettings( + chroma_persist_path=parts["chroma"], state_dir=parts["state"], project_id=parts["project"] + ) + return settings, root + + +def run_records(settings: MemKernelSettings, run_id: str) -> tuple[list[dict[str, Any]], int]: + """Every recall-log record of the store whose ``run_id`` is ``run_id``, rotated files included, oldest first, and + how many log files could not be read (one being rotated, or damaged) and were skipped. Lines that are not JSON + objects are skipped.""" + current = Path(settings.state_dir) / recall_log.RECALL_LOG_DIR / settings.project_id / recall_log.RECALL_LOG_FILE + records: list[dict[str, Any]] = [] + unreadable = 0 + for path in [current, *current.parent.glob(f"{current.name}.[0-9]*")]: + if not path.is_file(): + continue + try: + text = path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + unreadable += 1 + continue + for line in text.splitlines(): + try: + record = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(record, dict) and record.get("run_id") == run_id: + records.append(record) + return sorted(records, key=lambda r: str(r.get("time", ""))), unreadable + + +def received(records: list[dict[str, Any]]) -> tuple[list[str], dict[str, dict[str, Any]]]: + """The memories the run received, in first-seen order, and for each the last receipt entry with its hash (C1).""" + order: list[str] = [] + entries: dict[str, dict[str, Any]] = {} + for record in records: + details = { + e["ref_id"]: e + for e in record.get("memories", []) + if isinstance(e, dict) and isinstance(e.get("ref_id"), str) and isinstance(e.get("content_hash"), str) + } + for ref_id in record.get("ref_ids", []): + if not isinstance(ref_id, str): + continue + if ref_id not in order: + order.append(ref_id) + if ref_id in details: + entries[ref_id] = details[ref_id] + return order, entries + + +def legacy_owners(store: VectorStorePort) -> dict[str, str]: + """Chunks from before 0.4, which carry no ``parent_ref``: each id a code record's ``chunk_refs`` lists, mapped to + that record, a live one preferred where an old shared chunk has several (revalidation's ``referenced``).""" + owners: dict[str, str] = {} + records = store.list_all({"type": MemoryType.CODE.value}, include_content=False) + for record in sorted(records, key=lambda m: m.retired()): # live records first, so they win + for chunk in record.chunk_refs: + owners.setdefault(chunk, record.ref_id) + return owners + + +def _owner_id(ref_id: str, memory: Memory | None, legacy: dict[str, str]) -> str | None: + """A code chunk's file record: its ``parent_ref``; else a pre-0.4 owner whose ``chunk_refs`` lists it; else, + when the chunk record is gone, the id's prefix.""" + if memory is not None and memory.parent_ref: + return memory.parent_ref + if ref_id in legacy and legacy[ref_id] != ref_id: + return legacy[ref_id] + if memory is None and CHUNK_INFIX in ref_id: + return ref_id.rsplit(CHUNK_INFIX, 1)[0] + return None + + +def _resolve(root: Path, source: str) -> Path | None: + """``source`` inside the project root, as revalidation resolves it; None when it escapes the root.""" + root = root.resolve() + candidate = Path(source) if Path(source).is_absolute() else root / source + try: + resolved = candidate.resolve() + except OSError: + return None + return resolved if resolved.is_relative_to(root) else None + + +def _source_check(root: Path | None, source: str, expected: str, judged: Judged) -> None: + """Add ``source changed`` when the file is gone or hashes differently from ``expected`` (no hash: gone only); + without a root, only a note.""" + if root is None: + judged.notes.append(NOTE_NO_ROOT) + return + path = _resolve(root, source) + if path is None: + judged.notes.append(NOTE_OUTSIDE_ROOT) + return + if not path.exists(): + judged.statuses.append(SOURCE_CHANGED) + return + if not expected: + return # a decision saved before source_hash existed, whose file is still there: nothing to compare + try: + text = path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + judged.notes.append(NOTE_UNREADABLE) + return + if compute_content_hash(text) != expected: + judged.statuses.append(SOURCE_CHANGED) + + +def judge( + store: VectorStorePort, + settings: MemKernelSettings, + ref_id: str, + entry: dict[str, Any] | None, + root: Path | None = None, + legacy: dict[str, str] | None = None, +) -> Judged: + """The statuses of one memory the run received (C3, C6), against the store now; every scope is read.""" + memory = store.get_by_id(ref_id) + owner_id = _owner_id(ref_id, memory, legacy or {}) + subject = store.get_by_id(owner_id) if owner_id else memory # a chunk is judged by its file record + judged = Judged(ref_id, [], owner=owner_id or "") + if subject is None or memory_is_expired(subject, settings): + judged.statuses = [MISSING] + return judged + judged.source, judged.scope = subject.source, subject.scope + if subject.superseded_by: + judged.statuses.append(SUPERSEDED) + judged.superseded_by = subject.superseded_by + if subject.withdrawn_reason: + judged.statuses.append(WITHDRAWN) + judged.withdrawn_reason = subject.withdrawn_reason + if entry is None: + judged.statuses.append(UNKNOWN) + return judged + same_scheme = entry.get("content_hash_scheme", CONTENT_HASH_SCHEME) == CONTENT_HASH_SCHEME + if not same_scheme: + judged.statuses.append(REHASHED) + elif memory is not None and memory.content_hash != entry["content_hash"]: + judged.statuses.append(CHANGED) + if entry.get("state") == recall_log.STATE_LIVE and subject.needs_review: + judged.statuses.append(FLAGGED) + source = subject.source if owner_id else str(entry.get("source") or subject.source) + if source: + if owner_id: + expected = subject.content_hash # made now, with the current scheme: C2 does not apply + elif subject.type == MemoryType.CODE: + expected = str(entry["content_hash"]) if same_scheme else "" + else: + expected = str(entry.get("source_hash") or "") + _source_check(root, source, expected, judged) + if not judged.statuses: + judged.statuses = [UNCHANGED] + return judged + + +def diff( + settings: MemKernelSettings, run_id: str, store: VectorStorePort | None = None, root: Path | None = None +) -> dict[str, Any]: + """The report for ``run_id``; ``records`` is 0 when no record carries it. ``root`` enables source checks.""" + records, unreadable = run_records(settings, run_id) + notes = ( + [f"{unreadable} log file(s) could not be read and were skipped: the log is incomplete"] if unreadable else [] + ) + report: dict[str, Any] = { + "run_id": run_id, + "root": str(root) if root is not None else None, + "records": len(records), + "unreadable_log_files": unreadable, + "memories": [], + "counts": dict.fromkeys(STATUSES, 0), + "notes": notes, + } + if not records: + return report + vector_store = store if store is not None else ChromaVectorStore(settings) + legacy = legacy_owners(vector_store) + order, entries = received(records) + judged = [judge(vector_store, settings, ref_id, entries.get(ref_id), root, legacy) for ref_id in order] + cut = sum(1 for r in records if r.get("ref_ids_truncated") is True) + if cut: + notes.append( + f"{cut} record(s) of this run had their ref_ids cut short: the run may have received memories not listed" + ) + report["memories"] = [asdict(j) for j in judged] + report["counts"] = {status: sum(status in j.statuses for j in judged) for status in STATUSES} + return report + + +def render(report: dict[str, Any]) -> str: + counts = ", ".join(f"{n} {status}" for status, n in report["counts"].items() if n) + root = report["root"] + lines = [ + f"Run {report['run_id']}: {len(report['memories'])} memory(ies) in {report['records']} record(s)" + + (f": {counts}." if counts else "."), + f"Root: {root}" if root else "Root: none given, so no source checks (pass root= in --store).", + ] + for m in report["memories"]: + extra = [f"by {m['superseded_by']}" if m["superseded_by"] else "", m["withdrawn_reason"], *m["notes"]] + detail = "; ".join(e for e in extra if e) + where = f" ({m['source']})" if m["source"] else "" + lines.append(f"- {m['ref_id']}{where}: {', '.join(m['statuses'])}" + (f" [{detail}]" if detail else "")) + lines.extend(f"Note: {note}" for note in report["notes"]) + return "\n".join(lines) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=(__doc__ or "").split("\n\n")[0]) + parser.add_argument( + "--store", + required=True, + help="name=…,chroma=…,state=…,project=…[,root=…]; root, the project that sources resolve under, enables " + "the source checks", + ) + parser.add_argument("--run", required=True, help="the run_id the harness passed to memkernel") + parser.add_argument("--json", type=Path, help="also write the report as JSON") + args = parser.parse_args(argv) + settings, root = parse_store(args.store) + report = diff(settings, args.run, root=root) + if not report["records"]: + incomplete = report["unreadable_log_files"] + print( + f"No recall-log record carries run_id {args.run!r} (a wrong id, or the log was off or rotated away)." + + (f" {incomplete} log file(s) could not be read, so the log is incomplete." if incomplete else "") + ) + return EXIT_NO_RECORDS + print(render(report)) + if args.json: + args.json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + return EXIT_REPORT + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/specs/memkernel-0-15-harness-foundations/origin-alignment-2026-11-24-0845-build-h3.md b/specs/memkernel-0-15-harness-foundations/origin-alignment-2026-11-24-0845-build-h3.md new file mode 100644 index 0000000..d423c11 --- /dev/null +++ b/specs/memkernel-0-15-harness-foundations/origin-alignment-2026-11-24-0845-build-h3.md @@ -0,0 +1,25 @@ +# Origin alignment check — memkernel-0-15-harness-foundations, the H3 build + +Origin: #119 Part 2 (Reproducible Knowledge Context), the reviews the owner passed on, and the owner's decisions: D1–D6 +(2026-11-19), amendments H1 and H2 (2026-11-23), amendment H3 with C1 refined and C2–C4 confirmed, then the owner's +fixes (2026-11-24, PR #157). + +Origin claim: as in plan.md. Part 2: versioned, inspectable knowledge selections; traceability to sources and source +revisions; awareness of changed, stale, missing or superseded knowledge; an explainable record of why knowledge was +selected. Success scenario: after source code or architectural decisions change, the system can identify differences +from the context used by an earlier harness run. + +Working claim: +> Built as amendment H3 says: eval/context-diff/diff.py reads a run's receipts (H1) and reports, per memory, missing, +> superseded, withdrawn, changed, rehashed, flagged (against the receipt's state), source changed (a gone file +> included), unknown or unchanged, with C3's combination rules; each memory judged by the last receipt with its hash; +> code chunks judged by their file record; a note for cut-short ref_ids; exit codes 0, 1, 2; no memory content; in +> CI's strict type check. Tested, starting with SC-2. + +Mismatches: + - none for H3. Noted, unchanged by H3: Part 2's "explainable record of why particular knowledge was selected" is + served by what the receipt records (the query, its filters, the exclusion counts), as the approved spec decided + (FR-003, D3); no per-memory reason is recorded. + +Verdict: aligned +Confidence: high diff --git a/specs/memkernel-0-15-harness-foundations/tasks.md b/specs/memkernel-0-15-harness-foundations/tasks.md index 302697f..75ed31e 100644 --- a/specs/memkernel-0-15-harness-foundations/tasks.md +++ b/specs/memkernel-0-15-harness-foundations/tasks.md @@ -8,7 +8,7 @@ - [x] `scope` on records, `agent`/`task` on every read path, promotion keeping scope (FR-001, SC-1); the empty-result reason in the receipt (FR-005, SC-6) ## US3 (H3): context diff -- [ ] `eval/context-diff/diff.py` over a run's receipts (FR-004) +- [x] `eval/context-diff/diff.py` over a run's receipts (FR-004) ## US4: docs and checks - [ ] README "Using memkernel from a harness" (FR-007); SC-1–SC-5 diff --git a/tests/unit/test_context_diff.py b/tests/unit/test_context_diff.py new file mode 100644 index 0000000..71f04ee --- /dev/null +++ b/tests/unit/test_context_diff.py @@ -0,0 +1,316 @@ +# Copyright (c) 2026 EGOGE +# SPDX-License-Identifier: Apache-2.0 +"""The context diff (memkernel-0-15-harness-foundations H3: FR-004, SC-2; amendment C1–C9).""" + +from __future__ import annotations + +import importlib.util +import json +import sys +import uuid +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any + +import chromadb +import pytest + +from memkernel import recall_log +from memkernel.config import MemKernelSettings +from memkernel.core.models import EVERYONE, NEEDS_REVIEW_KEY, REVIEW_REASON_KEY, Caller, MemoryType +from memkernel.factory import build_service +from tests.conftest import MockEmbedding + +pytestmark = pytest.mark.unit + +DIFF = Path(__file__).resolve().parents[2] / "eval" / "context-diff" / "diff.py" +RUN = "run-7" + + +def _load() -> Any: + spec = importlib.util.spec_from_file_location("context_diff", DIFF) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +diff_module = _load() + + +@pytest.fixture +def env(tmp_path: Path) -> tuple[Any, MemKernelSettings, Path]: + root = tmp_path / "project" + root.mkdir() + settings = MemKernelSettings( + project_id=f"h3-{uuid.uuid4().hex[:8]}", + chroma_persist_path=str(tmp_path / "chroma"), + state_dir=str(tmp_path / "state"), + project_root=str(root), + recall_log=True, + observation_ttl_days=7, + ) + svc = build_service(settings, embedding=MockEmbedding(), chroma_client=chromadb.EphemeralClient()) + return svc, settings, root + + +def _receive(svc: Any, settings: MemKernelSettings, refs: list[str], **overrides: Any) -> None: + """One recall-log record of the run, as an MCP recall writes it, with ``overrides`` per memory entry.""" + memories = [svc.get(ref, touch=False, caller=EVERYONE) for ref in refs] + recall_log.append(settings, recall_log.ORIGIN_TOOL, refs, query="q", ids=recall_log.Correlation(RUN)) + if overrides: + path = recall_log.log_path(settings) + assert path is not None + lines = path.read_text(encoding="utf-8").splitlines() + record = json.loads(lines[-1]) + record["memories"] = [{**recall_log.receipt_entry(m), **overrides.get(m.ref_id, {})} for m in memories] + lines[-1] = json.dumps(record) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + else: + _rewrite_last(settings, lambda r: {**r, "memories": [recall_log.receipt_entry(m) for m in memories]}) + + +def _rewrite_last(settings: MemKernelSettings, change: Any) -> None: + path = recall_log.log_path(settings) + assert path is not None + lines = path.read_text(encoding="utf-8").splitlines() + lines[-1] = json.dumps(change(json.loads(lines[-1]))) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def _report(svc: Any, settings: MemKernelSettings) -> dict[str, Any]: + """The report with source checks on: the fixture's project folder as the root.""" + return diff_module.diff(settings, RUN, store=svc._vector_store, root=Path(settings.project_root)) + + +def _statuses(svc: Any, settings: MemKernelSettings) -> dict[str, list[str]]: + report = _report(svc, settings) + assert report is not None + return {m["ref_id"]: m["statuses"] for m in report["memories"]} + + +def test_sc2_a_superseded_decision_and_a_changed_code_file(env: Any) -> None: + svc, settings, root = env + (root / "app.py").write_text("def handler():\n return 1\n", encoding="utf-8") + decision = svc.retain("Use Postgres for the user store.", MemoryType.DECISION) + code = svc.retain((root / "app.py").read_text(encoding="utf-8"), MemoryType.CODE, source="app.py") + _receive(svc, settings, [decision, code]) + svc.retain("Use MySQL for the user store.", MemoryType.DECISION, supersedes=decision) + (root / "app.py").write_text("def handler():\n return 2\n", encoding="utf-8") + statuses = _statuses(svc, settings) + assert statuses == {decision: ["superseded"], code: ["source changed"]} + + +def test_an_untouched_memory_is_unchanged_and_the_report_holds_no_content(env: Any) -> None: + svc, settings, _ = env + fact = svc.retain("Secret-free fact: the API listens on 8080.", MemoryType.FACT) + _receive(svc, settings, [fact]) + report = _report(svc, settings) + assert report["memories"][0]["statuses"] == ["unchanged"] and "8080" not in json.dumps(report) + assert report["counts"]["unchanged"] == 1 and report["records"] == 1 + + +def test_a_deleted_or_expired_memory_is_missing_and_nothing_else(env: Any) -> None: + svc, settings, _ = env + gone = svc.retain("A fact to delete.", MemoryType.FACT) + stale = svc.retain("A slow query on Monday.", MemoryType.OBSERVATION) + _receive(svc, settings, [gone, stale]) + svc.forget(gone) + svc._vector_store.update_metadata(stale, {"timestamp": (datetime.now(UTC) - timedelta(days=60)).isoformat()}) + assert _statuses(svc, settings) == {gone: ["missing"], stale: ["missing"]} + + +def test_withdrawn_changed_and_rehashed(env: Any) -> None: + svc, settings, _ = env + page = svc.retain("A wiki fact.", MemoryType.FACT) + edited = svc.retain("A fact whose text the run saw differently.", MemoryType.FACT) + rehashed = svc.retain("A fact hashed under a later scheme.", MemoryType.FACT) + _receive( + svc, + settings, + [page, edited, rehashed], + **{edited: {"content_hash": "0" * 64}, rehashed: {"content_hash": "1" * 64, "content_hash_scheme": "canon"}}, + ) + svc.withdraw(page, "deprecated") + statuses = _statuses(svc, settings) + assert statuses == {page: ["withdrawn"], edited: ["changed"], rehashed: ["rehashed"]} + + +def test_flagged_is_judged_against_the_receipts_state(env: Any) -> None: + svc, settings, _ = env + newly = svc.retain("A fact flagged after the run.", MemoryType.FACT) + already = svc.retain("A fact the run saw flagged.", MemoryType.FACT) + svc._vector_store.update_metadata(already, {NEEDS_REVIEW_KEY: True, REVIEW_REASON_KEY: "changed"}) + _receive(svc, settings, [newly, already]) + svc._vector_store.update_metadata(newly, {NEEDS_REVIEW_KEY: True, REVIEW_REASON_KEY: "changed"}) + assert _statuses(svc, settings) == {newly: ["flagged"], already: ["unchanged"]} + + +def test_two_statuses_on_one_memory(env: Any) -> None: + svc, settings, root = env + (root / "notes.md").write_text("Postgres.\n", encoding="utf-8") + decision = svc.retain("Use Postgres.", MemoryType.DECISION, source="notes.md") + _receive(svc, settings, [decision]) + svc.retain("Use MySQL.", MemoryType.DECISION, supersedes=decision) + (root / "notes.md").write_text("MySQL.\n", encoding="utf-8") + assert _statuses(svc, settings) == {decision: ["superseded", "source changed"]} + + +def test_a_gone_file_counts_with_or_without_a_source_hash(env: Any) -> None: + svc, settings, root = env + for name in ("with.md", "without.md", "kept.md"): + (root / name).write_text(f"{name}\n", encoding="utf-8") + hashed = svc.retain("Decision citing with.md.", MemoryType.DECISION, source="with.md") + unhashed = svc.retain("Decision citing without.md.", MemoryType.DECISION, source="without.md") + present = svc.retain("Decision citing kept.md.", MemoryType.DECISION, source="kept.md") + _receive( + svc, settings, [hashed, unhashed, present], **{unhashed: {"source_hash": ""}, present: {"source_hash": ""}} + ) + (root / "with.md").unlink() + (root / "without.md").unlink() + assert _statuses(svc, settings) == { + hashed: ["source changed"], + unhashed: ["source changed"], + present: ["unchanged"], + } + + +def test_a_source_outside_the_root_gets_no_check_and_says_so(env: Any) -> None: + svc, settings, _ = env + decision = svc.retain("Decision citing a file elsewhere.", MemoryType.DECISION, source="/etc/hosts") + _receive(svc, settings, [decision]) + report = _report(svc, settings) + (judged,) = report["memories"] + assert judged["statuses"] == ["unchanged"] and judged["notes"] == [diff_module.NOTE_OUTSIDE_ROOT] + + +def test_a_chunk_is_judged_by_its_file_record_after_its_chunks_were_deleted(env: Any) -> None: + svc, settings, root = env + v1 = "def first():\n return 1\n\n\ndef second():\n return 2\n" + (root / "lib.py").write_text(v1, encoding="utf-8") + owner = svc.retain(v1, MemoryType.CODE, source="lib.py") + chunks = [m for m in svc._vector_store.list_all({"parent_ref": owner}, include_content=False)] + assert chunks, "the code chunker gives the snapshot chunk records" + chunk = chunks[0].ref_id + _receive(svc, settings, [chunk]) + v2 = v1.replace("return 2", "return 3") + (root / "lib.py").write_text(v2, encoding="utf-8") + svc.retain(v2, MemoryType.CODE, source="lib.py") + assert svc._vector_store.get_by_id(chunk) is None # the superseded snapshot's chunks are gone + report = _report(svc, settings) + (judged,) = report["memories"] + assert judged["owner"] == owner and judged["statuses"] == ["superseded", "source changed"] + + +def test_unknown_combines_with_superseded_and_an_earlier_full_receipt_counts(env: Any) -> None: + svc, settings, _ = env + cut = svc.retain("Decision only in cut-down records.", MemoryType.DECISION) + earlier = svc.retain("Decision with an earlier full receipt.", MemoryType.DECISION) + _receive(svc, settings, [earlier]) + _receive(svc, settings, [cut, earlier]) + _rewrite_last(settings, lambda r: {**r, "memories": [], "memories_truncated": True, "truncated": True}) + svc.retain("A newer decision.", MemoryType.DECISION, supersedes=cut) + assert _statuses(svc, settings) == {earlier: ["unchanged"], cut: ["superseded", "unknown"]} + + +def test_a_private_memory_is_judged_across_scopes(env: Any) -> None: + svc, settings, _ = env + private = svc.retain("Agent a's note.", MemoryType.FACT, scope="agent", caller=Caller(agent_id="a")) + _receive(svc, settings, [private]) + report = _report(svc, settings) + assert report["memories"][0]["statuses"] == ["unchanged"] and report["memories"][0]["scope"] == "agent:a" + + +def test_cut_short_ref_ids_add_a_note(env: Any) -> None: + svc, settings, _ = env + fact = svc.retain("A fact.", MemoryType.FACT) + _receive(svc, settings, [fact]) + _rewrite_last(settings, lambda r: {**r, "ref_ids_truncated": True, "truncated": True}) + report = _report(svc, settings) + assert report["notes"] == [ + "1 record(s) of this run had their ref_ids cut short: the run may have received memories not listed" + ] + assert "Note: 1 record(s)" in diff_module.render(report) + + +def test_exit_codes(env: Any, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + svc, settings, _ = env + fact = svc.retain("A fact.", MemoryType.FACT) + _receive(svc, settings, [fact]) + spec = f"chroma={settings.chroma_persist_path},state={settings.state_dir},project={settings.project_id}" + Path(settings.chroma_persist_path).mkdir(parents=True, exist_ok=True) # a store folder the command line opens + out = tmp_path / "report.json" + assert diff_module.main(["--store", spec, "--run", RUN, "--json", str(out)]) == 0 + assert json.loads(out.read_text(encoding="utf-8"))["run_id"] == RUN + assert diff_module.main(["--store", spec, "--run", "no-such-run"]) == 1 + assert "No recall-log record carries run_id" in capsys.readouterr().out + with pytest.raises(SystemExit) as missing_store: + diff_module.main(["--store", "chroma=/nonexistent,state=/x,project=p", "--run", RUN]) + assert missing_store.value.code == 2 + with pytest.raises(SystemExit) as bad_spec: + diff_module.main(["--store", "chroma=/x", "--run", RUN]) + assert bad_spec.value.code == 2 + + +def test_without_a_root_source_checks_are_skipped_and_said_so(env: Any) -> None: + svc, settings, root = env + (root / "notes.md").write_text("v1\n", encoding="utf-8") + decision = svc.retain("Decision citing notes.md.", MemoryType.DECISION, source="notes.md") + _receive(svc, settings, [decision]) + (root / "notes.md").unlink() + report = diff_module.diff(settings, RUN, store=svc._vector_store) + (judged,) = report["memories"] + assert judged["statuses"] == ["unchanged"] and judged["notes"] == ["no source check (no root given)"] + assert report["root"] is None and "Root: none given, so no source checks" in diff_module.render(report) + with_root = _report(svc, settings) + assert with_root["memories"][0]["statuses"] == ["source changed"] + assert with_root["root"] == str(root) and f"Root: {root}" in diff_module.render(with_root) + + +def test_unreadable_log_files_are_counted_and_make_the_log_incomplete( + env: Any, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + svc, settings, _ = env + fact = svc.retain("A fact.", MemoryType.FACT) + _receive(svc, settings, [fact]) + path = recall_log.log_path(settings) + assert path is not None + path.with_name(f"{path.name}.1").write_bytes(b"\xff\xfe not utf-8 \xff") + report = _report(svc, settings) + assert report["unreadable_log_files"] == 1 + assert "1 log file(s) could not be read and were skipped: the log is incomplete" in report["notes"] + Path(settings.chroma_persist_path).mkdir(parents=True, exist_ok=True) + spec = f"chroma={settings.chroma_persist_path},state={settings.state_dir},project={settings.project_id}" + assert diff_module.main(["--store", spec, "--run", "no-such-run"]) == 1 + assert "1 log file(s) could not be read, so the log is incomplete" in capsys.readouterr().out + + +def test_a_chunk_from_before_0_4_is_judged_by_the_record_that_lists_it(env: Any) -> None: + """Revalidation's rule: a record a code record's chunk_refs lists is a chunk of it, though it has no parent_ref.""" + svc, settings, root = env + source = "def legacy():\n return 1\n" + (root / "old.py").write_text(source, encoding="utf-8") + owner = svc.retain(source, MemoryType.CODE, source="old.py") + legacy = "legacy-0-3-chunk" # an id from before 0.4: no -chunk- form + svc._vector_store.upsert( + ref_id=legacy, + content="return 1", + embedding=MockEmbedding().embed(["return 1"])[0], + metadata={ + "project_id": settings.project_id, + "session_id": "default", + "timestamp": datetime.now(UTC).isoformat(), + "type": "code", + "source": "old.py", + "hash": "c" * 64, + "token_count": 1, + "code_chunk": True, + }, + ) + svc._vector_store.update_metadata(owner, {"chunk_refs": legacy}) + _receive(svc, settings, [legacy]) + (root / "old.py").write_text("def legacy():\n return 2\n", encoding="utf-8") + report = _report(svc, settings) + (judged,) = report["memories"] + assert judged["owner"] == owner and judged["statuses"] == ["source changed"] From 23aed0bd1c3049fb169eac6fdb088181fbe770db Mon Sep 17 00:00:00 2001 From: gosha70 Date: Tue, 24 Nov 2026 11:57:20 -0500 Subject: [PATCH 2/2] Context diff: check sources only for decisions and code; open the store read-only (#119 H3) As revalidation, only decisions and code have their source checked; another record's source is a label (a captured record's "capture" named a missing file and read as "source changed"). The store is opened without creating a collection: a store without the project's collection exits 2, and the run creates nothing. Opening or reading the store failing exits 2, not 1. Tests: a captured memory stays unchanged with a root; a missing collection exits 2 and creates none; a failing read exits 2. --- eval/context-diff/diff.py | 49 +++++++++++++++++++++++++------ tests/unit/test_context_diff.py | 51 +++++++++++++++++++++++++++++++-- 2 files changed, 89 insertions(+), 11 deletions(-) diff --git a/eval/context-diff/diff.py b/eval/context-diff/diff.py index 43b1089..ab8d154 100644 --- a/eval/context-diff/diff.py +++ b/eval/context-diff/diff.py @@ -11,7 +11,8 @@ chunk is judged through its file record). ``rehashed``: the receipt's hash was made with another scheme than this memkernel's, so it is not compared (C2); for code, the source check then only notices a file that is gone. - ``flagged``: needs review now, and ``live`` in its receipt (the run did not see a flag). -- ``source changed``: the memory's ``source`` file under the project root no longer hashes to the receipt's +- ``source changed`` (decisions and code only, as revalidation: another record's ``source`` is a label, such as + ``capture``): the memory's ``source`` file under the project root no longer hashes to the receipt's ``source_hash`` (a decision) or ``content_hash`` (code), through memkernel's own ``compute_content_hash``; a file that is gone counts too. It says nothing about whether the memory is wrong, or about other files its text cites. - ``unknown``: no receipt in the run has the memory's hash (every record that returned it was cut down). It combines @@ -23,8 +24,9 @@ chunk from before 0.4, the code record whose ``chunk_refs`` lists it (as revalidation recognises it). Source checks need ``root=``, the project the sources resolve under; without it they are skipped and each memory with a source says so. Unreadable log files are skipped and counted. The report holds ids, hashes, sources and statuses, never -memory content; it reads every scope. Exit codes: 0 report printed, 1 no record carries the run id, 2 usage error or a -store it cannot open. +memory content; it reads every scope, and opens the store without creating anything. Exit codes: 0 report printed, +1 no record carries the run id, 2 usage error, or a store it cannot open or read (no collection for the project +included). Usage: poetry run python eval/context-diff/diff.py \\ @@ -44,6 +46,9 @@ HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE.parents[1] / "src")) +import chromadb # noqa: E402 +from chromadb.errors import ChromaError # noqa: E402 + from memkernel import recall_log # noqa: E402 from memkernel.config import MemKernelSettings # noqa: E402 from memkernel.core.models import MemoryType # noqa: E402 @@ -70,6 +75,12 @@ NOTE_OUTSIDE_ROOT = "no source check (outside the project root)" NOTE_UNREADABLE = "no source check (the file cannot be read as text)" EXIT_REPORT, EXIT_NO_RECORDS, EXIT_USAGE = 0, 1, 2 +SOURCE_CHECKED_TYPES = (MemoryType.DECISION, MemoryType.CODE) # as revalidation: other records' sources are labels +STORE_ERRORS = (ChromaError, OSError, ValueError, RuntimeError) + + +class StoreUnavailableError(Exception): + """The store cannot be opened or read (exit 2): no collection for the project, or chromadb failed.""" @dataclass @@ -104,6 +115,19 @@ def parse_store(spec: str) -> tuple[MemKernelSettings, Path | None]: return settings, root +def open_store(settings: MemKernelSettings) -> VectorStorePort: + """The project's store, opened without creating a collection; ``StoreUnavailableError`` when it has none or chromadb + fails (the adapter itself would create a missing collection, so its existence is checked first).""" + name = f"{settings.chroma_collection_prefix}_{settings.project_id}" + try: + client = chromadb.PersistentClient(path=settings.chroma_persist_path) + client.get_collection(name) # raises NotFoundError for a missing collection; creates nothing + return ChromaVectorStore(settings, client=client) + except STORE_ERRORS as exc: + where = settings.chroma_persist_path + raise StoreUnavailableError(f"no readable collection {name!r} at {where} ({exc})") from exc + + def run_records(settings: MemKernelSettings, run_id: str) -> tuple[list[dict[str, Any]], int]: """Every recall-log record of the store whose ``run_id`` is ``run_id``, rotated files included, oldest first, and how many log files could not be read (one being rotated, or damaged) and were skipped. Lines that are not JSON @@ -241,7 +265,7 @@ def judge( if entry.get("state") == recall_log.STATE_LIVE and subject.needs_review: judged.statuses.append(FLAGGED) source = subject.source if owner_id else str(entry.get("source") or subject.source) - if source: + if source and subject.type in SOURCE_CHECKED_TYPES: if owner_id: expected = subject.content_hash # made now, with the current scheme: C2 does not apply elif subject.type == MemoryType.CODE: @@ -273,10 +297,13 @@ def diff( } if not records: return report - vector_store = store if store is not None else ChromaVectorStore(settings) - legacy = legacy_owners(vector_store) - order, entries = received(records) - judged = [judge(vector_store, settings, ref_id, entries.get(ref_id), root, legacy) for ref_id in order] + vector_store = store if store is not None else open_store(settings) + try: + legacy = legacy_owners(vector_store) + order, entries = received(records) + judged = [judge(vector_store, settings, ref_id, entries.get(ref_id), root, legacy) for ref_id in order] + except STORE_ERRORS as exc: + raise StoreUnavailableError(f"reading the store failed ({exc})") from exc cut = sum(1 for r in records if r.get("ref_ids_truncated") is True) if cut: notes.append( @@ -316,7 +343,11 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("--json", type=Path, help="also write the report as JSON") args = parser.parse_args(argv) settings, root = parse_store(args.store) - report = diff(settings, args.run, root=root) + try: + report = diff(settings, args.run, store=open_store(settings), root=root) + except StoreUnavailableError as exc: + print(f"--store: {exc}", file=sys.stderr) + return EXIT_USAGE if not report["records"]: incomplete = report["unreadable_log_files"] print( diff --git a/tests/unit/test_context_diff.py b/tests/unit/test_context_diff.py index 71f04ee..6be5cd3 100644 --- a/tests/unit/test_context_diff.py +++ b/tests/unit/test_context_diff.py @@ -79,6 +79,12 @@ def _rewrite_last(settings: MemKernelSettings, change: Any) -> None: path.write_text("\n".join(lines) + "\n", encoding="utf-8") +def _persist_collection(settings: MemKernelSettings) -> None: + """The project's collection in a persistent store at the settings' path, as a memkernel server leaves it.""" + client = chromadb.PersistentClient(path=settings.chroma_persist_path) + client.get_or_create_collection(f"{settings.chroma_collection_prefix}_{settings.project_id}") + + def _report(svc: Any, settings: MemKernelSettings) -> dict[str, Any]: """The report with source checks on: the fixture's project folder as the root.""" return diff_module.diff(settings, RUN, store=svc._vector_store, root=Path(settings.project_root)) @@ -239,7 +245,7 @@ def test_exit_codes(env: Any, tmp_path: Path, capsys: pytest.CaptureFixture[str] fact = svc.retain("A fact.", MemoryType.FACT) _receive(svc, settings, [fact]) spec = f"chroma={settings.chroma_persist_path},state={settings.state_dir},project={settings.project_id}" - Path(settings.chroma_persist_path).mkdir(parents=True, exist_ok=True) # a store folder the command line opens + _persist_collection(settings) # a store with the project's collection, for the command line to open out = tmp_path / "report.json" assert diff_module.main(["--store", spec, "--run", RUN, "--json", str(out)]) == 0 assert json.loads(out.read_text(encoding="utf-8"))["run_id"] == RUN @@ -280,7 +286,7 @@ def test_unreadable_log_files_are_counted_and_make_the_log_incomplete( report = _report(svc, settings) assert report["unreadable_log_files"] == 1 assert "1 log file(s) could not be read and were skipped: the log is incomplete" in report["notes"] - Path(settings.chroma_persist_path).mkdir(parents=True, exist_ok=True) + _persist_collection(settings) spec = f"chroma={settings.chroma_persist_path},state={settings.state_dir},project={settings.project_id}" assert diff_module.main(["--store", spec, "--run", "no-such-run"]) == 1 assert "1 log file(s) could not be read, so the log is incomplete" in capsys.readouterr().out @@ -314,3 +320,44 @@ def test_a_chunk_from_before_0_4_is_judged_by_the_record_that_lists_it(env: Any) report = _report(svc, settings) (judged,) = report["memories"] assert judged["owner"] == owner and judged["statuses"] == ["source changed"] + + +def test_a_captured_memorys_source_is_a_label_not_a_file(env: Any) -> None: + """As revalidation: only decisions and code have their source checked; "capture" names no file.""" + svc, settings, _ = env + captured = svc.retain("Command `make` failed, then passed.", MemoryType.OBSERVATION, source="capture") + _receive(svc, settings, [captured]) + (judged,) = _report(svc, settings)["memories"] + assert judged["statuses"] == ["unchanged"] and judged["notes"] == [] + + +def test_a_store_without_the_projects_collection_exits_2_and_creates_nothing( + env: Any, capsys: pytest.CaptureFixture[str] +) -> None: + svc, settings, _ = env + fact = svc.retain("A fact.", MemoryType.FACT) + _receive(svc, settings, [fact]) + client = chromadb.PersistentClient(path=settings.chroma_persist_path) + client.get_or_create_collection("memkernel_another_project") + spec = f"chroma={settings.chroma_persist_path},state={settings.state_dir},project={settings.project_id}" + assert diff_module.main(["--store", spec, "--run", RUN]) == 2 + assert "no readable collection" in capsys.readouterr().err + names = {c if isinstance(c, str) else c.name for c in client.list_collections()} + assert names == {"memkernel_another_project"} # the diff created no collection + + +def test_a_failing_store_read_exits_2(env: Any, monkeypatch: pytest.MonkeyPatch, capsys: Any) -> None: + from chromadb.errors import InternalError + + svc, settings, _ = env + fact = svc.retain("A fact.", MemoryType.FACT) + _receive(svc, settings, [fact]) + _persist_collection(settings) + + def broken(self: Any, ref_id: str) -> Any: + raise InternalError("disk I/O error") + + monkeypatch.setattr(diff_module.ChromaVectorStore, "get_by_id", broken) + spec = f"chroma={settings.chroma_persist_path},state={settings.state_dir},project={settings.project_id}" + assert diff_module.main(["--store", spec, "--run", RUN]) == 2 + assert "reading the store failed" in capsys.readouterr().err