diff --git a/CHANGELOG.md b/CHANGELOG.md index c9461c9..598487e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ All notable changes to this project are documented here. The format follows ### Added +- **Decisions that cite a file are revalidated** (#123; specs/memkernel-0-10-decision-revalidation). A new decision + records the hash of its `source` file (a readable file under the project root) as `source_hash`; revalidation + flags it `changed` or `missing`, and a decision from before this release, without a hash, only `missing`. A + flagged decision is **not hidden**: `recall` returns it, and every `recall` result now carries `needs_review` and + `review_reason` (additive). Flagged `code` memories stay hidden as before. The session-start `### Needs review` + list names each item's type, with a hint for both. `revalidate()`'s flagged items gain a `type` key. - **A recall log and a repeated-mistake count** (#120; specs/memkernel-0-10-recall-log). With `MEMKERNEL_RECALL_LOG=1`, each MCP `recall`, and each hook block that shows memories, appends one line (time, query, filters, returned `ref_id`s, and the session id for hooks) to diff --git a/README.md b/README.md index f372353..cbd3c7a 100644 --- a/README.md +++ b/README.md @@ -167,11 +167,11 @@ Kiro (and the Kiro CLI, formerly Amazon Q Developer CLI) connects to MemKernel a | Tool | What it does | |------|-------------| | `retain(content, type, session_id?, checkpoint?, source?, importance?, tags?, supersedes?)` | Store a memory. Returns `ref_id`. Idempotent — identical content + type returns the same `ref_id`. `supersedes` hides the memory it replaces. | -| `recall(query, type?, tier?, session_id?, checkpoint_only?, top_k?, include_needs_review?, order?)` | Search by natural language or identifier. Returns lightweight `ArtifactRef` list ranked by relevance + recency + importance. Records an access (reinforces retention). Code memories flagged `needs_review` are hidden unless `include_needs_review=true`. | +| `recall(query, type?, tier?, session_id?, checkpoint_only?, top_k?, include_needs_review?, order?)` | Search by natural language or identifier. Returns lightweight `ArtifactRef` list ranked by relevance + recency + importance. Records an access (reinforces retention). Each result carries `needs_review` and `review_reason`. Code memories flagged `needs_review` are hidden unless `include_needs_review=true`; flagged decisions are returned, marked. | | `get(ref_id)` | Fetch full content of a specific memory. Records an access. | | `forget(ref_id)` | Delete a memory from all indexes. | | `promote(ref_id, type, content?, importance?, tags?)` | Turn a short-term/working memory into a long-term one (you supply the distilled text). Keeps provenance via `promoted_from`. | -| `consolidate(session_id?, limit?, synthesize?, revalidate?)` | Purge expired short-term memories and list the ones most worth promoting (ranked by importance × how often they were recalled). `synthesize=true` also asks an external reasoner to draft long-term statements (`suggested`); `revalidate=true` first checks every code memory against its source file (`revalidated`). The report always carries a `health` summary. | +| `consolidate(session_id?, limit?, synthesize?, revalidate?)` | Purge expired short-term memories and list the ones most worth promoting (ranked by importance × how often they were recalled). `synthesize=true` also asks an external reasoner to draft long-term statements (`suggested`); `revalidate=true` first checks every code memory, and every decision with a `source`, against its file (`revalidated`). The report always carries a `health` summary. | | `ask(ref_id, question, mode?)` | Answer a question about one memory without loading it — for a `document` the full body is consulted. `mode`: `direct` \| `rag` \| `rlm` \| `auto`, passed to the reasoner unchanged; the built-in reasoner answers in `rag` mode with the best-matching chunks. Returns `answer`, `mode`, `citations`, `usage`. | | `wiki_export(wiki_dir?)` | Compile long-term memories without a wiki page into draft markdown pages (`index.md`, `log.md` updated). | | `wiki_import(wiki_dir?, adopt_legacy?, adopt_pages?, adopt_manifest?)` | Index wiki pages as long-term memories, each wiki keeping to its own: approved revisions only with wiki-studio ≥ 0.7.0, every page without it (idempotent; changed pages supersede; `corrects` supersedes the memories a page corrects). | @@ -448,6 +448,8 @@ Rationale: [`docs/adr/ADR-008-llm-wiki-as-semantic-layer.md`](docs/adr/ADR-008-l A `code` memory is a snapshot of a file. `MemoryService.revalidate()` hashes each live snapshot's whole source file and compares it with the stored content hash: a changed file flags the memory `needs_review` (`changed`), a vanished file flags it `missing`, a matching file clears the flag. Flagged memories leave default `recall` until the file is retained again (which supersedes the stale snapshot) or they are asked for with `include_needs_review=true`. Revalidation runs from `consolidate(revalidate=true)`, at every session start through `MemoryLifecycle.on_session_start()` (a `### Needs review` section lists what to re-retain), and from `POST /revalidate`. Sources resolve under `MEMKERNEL_PROJECT_ROOT` (default: the current directory); set it whenever the server or a hook is not started from the project directory. Nothing outside that root is ever read. 0.4 hashes whole files; per-chunk invalidation is a follow-up. +A `decision` that cites a file in `source` is revalidated too. When a decision is created, memkernel records the hash of that file (if it is a readable file under the project root) as `source_hash`; a retain that matches an existing decision returns it unchanged, with its own source and hash. Revalidation flags the decision `changed` when the file's hash differs and `missing` when the file is gone; a decision saved before 0.10, without a hash, is flagged only when its file is missing, and a present file clears only that flag. **A flagged decision is not hidden:** `recall` returns it with `needs_review: true` and its `review_reason`, so the agent re-checks the evidence instead of losing the decision (a file edit unrelated to the decision flags it too). It is listed under `### Needs review` at session start, marked `[decision]`; the list shows every memory still flagged, including one whose file could not be read this time. Only `source` is checked, not other paths the decision cites. + `MemoryService.health()` audits the store without changing it: orphaned chunk and document records, dangling `supersedes` / `superseded_by` / `promoted_from` / `parent_ref` links, supersessions from 0.2/0.3 that lack the durable marker, `code` memories whose source file is gone, memories flagged for review, expired short-term memories not yet purged and, in full mode only, near-duplicate pairs among the most recent long-term memories (cosine ≥ `MEMKERNEL_HEALTH_DUPLICATE_THRESHOLD`). The quick report (counts only, no embeddings, no content loads) is part of every `consolidate()` report and of the `memory://status` resource; the full report is `GET /health/store`. The pass never fixes anything: a fix mode is a later feature. ## Admin API @@ -464,7 +466,7 @@ uvicorn memkernel.api.app:app --host 127.0.0.1 --port 8766 | `GET /stats` | Total memory count, per-type and per-tier breakdown, growth rate, last recall latency | | `GET /collections` | List ChromaDB collections | | `GET /health/store` | Full store health report (orphans, dangling links, stale sources, near-duplicates, …) | -| `POST /revalidate` | Check every code memory against its source file; flag changed or missing ones | +| `POST /revalidate` | Check every code memory, and every decision with a `source`, against its file; flag changed or missing ones | --- diff --git a/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-14-2300-review.md b/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-14-2300-review.md new file mode 100644 index 0000000..f204187 --- /dev/null +++ b/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-14-2300-review.md @@ -0,0 +1,15 @@ +# Origin alignment check — memkernel-0-10-decision-revalidation, review of #126 + +Origin: gosha70/memkernel#123 (origin/2026-11-13-issue-123.md). + +Origin claim: as in plan.md. + +Working claim: +> As approved, with the review's corrections: FR-003 covers the order="newest" path (checkpoints_newest_first) and +> FR-004 both result builders, with an acceptance test (SC-3c); plan and tasks cite the replay as SC-3b. + +Mismatches: + - none. #123 asks that recall return flagged decisions; the newest path is part of recall. + +Verdict: aligned +Confidence: high diff --git a/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-14-2310-review-b.md b/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-14-2310-review-b.md new file mode 100644 index 0000000..cfaa258 --- /dev/null +++ b/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-14-2310-review-b.md @@ -0,0 +1,16 @@ +# Origin alignment check — memkernel-0-10-decision-revalidation, review of #126, after DeepSeek + +Origin: gosha70/memkernel#123 (origin/2026-11-13-issue-123.md). + +Origin claim: as in plan.md. + +Working claim: +> As approved, with the review's corrections: FR-003 covers the order="newest" path (checkpoints_newest_first) and +> FR-004 both result builders, with an acceptance test (SC-3c, both fields); the newest path ignores +> include_needs_review, as today; plan and tasks cite the replay as SC-3b. + +Mismatches: + - none. #123 asks that recall return flagged decisions; the newest path is part of recall. + +Verdict: aligned +Confidence: high diff --git a/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-15-0900-review-c.md b/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-15-0900-review-c.md new file mode 100644 index 0000000..d723e19 --- /dev/null +++ b/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-15-0900-review-c.md @@ -0,0 +1,16 @@ +# Origin alignment check — memkernel-0-10-decision-revalidation, review of #126 (shared layer) + +Origin: gosha70/memkernel#123 (origin/2026-11-13-issue-123.md). + +Origin claim: as in plan.md. + +Working claim: +> As approved, with: flagged decisions returned on recall's relevance and order="newest" paths; on the newest path +> through a keyword on checkpoints_newest_first() that only _newest_checkpoints() sets, so the lifecycle's +> checkpoint selection is unchanged (SC-3c checks both); both result builders fill the new fields. + +Mismatches: + - none. #123 is about what recall returns; the lifecycle's choice of the latest checkpoint stays as it is. + +Verdict: aligned +Confidence: high diff --git a/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-15-1200-build-a1.md b/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-15-1200-build-a1.md new file mode 100644 index 0000000..32e37ad --- /dev/null +++ b/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-15-1200-build-a1.md @@ -0,0 +1,15 @@ +# Origin alignment check — memkernel-0-10-decision-revalidation, build amendment A1 + +Origin: gosha70/memkernel#123 (origin/2026-11-13-issue-123.md). + +Origin claim: as in plan.md. + +Working claim: +> As approved and amended, with A1: the hook blocks' context lines label a flagged memory with its review reason, +> so a flagged decision shown at session start or after compaction is marked as recall marks it. + +Mismatches: + - none. #123 asks that flagged decisions be returned marked; the hook blocks show memories too. + +Verdict: aligned +Confidence: high diff --git a/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-15-1500-review-d.md b/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-15-1500-review-d.md new file mode 100644 index 0000000..3f2161c --- /dev/null +++ b/specs/memkernel-0-10-decision-revalidation/origin-alignment-2026-11-15-1500-review-d.md @@ -0,0 +1,15 @@ +# Origin alignment check — memkernel-0-10-decision-revalidation, second review of #127 + +Origin: gosha70/memkernel#123 (origin/2026-11-13-issue-123.md). + +Origin claim: as in plan.md. + +Working claim: +> As amended, with: a hashless decision's present file clears only a missing flag (FR-002); the startup list shows +> durable flags, not only this pass's (FR-005); SC-4 tested on a record without the source_hash key. + +Mismatches: + - none. Each keeps a flag until evidence disproves it, which is #123's "flag them, don't hide them". + +Verdict: aligned +Confidence: high diff --git a/specs/memkernel-0-10-decision-revalidation/plan.md b/specs/memkernel-0-10-decision-revalidation/plan.md index 96df394..ef21c17 100644 --- a/specs/memkernel-0-10-decision-revalidation/plan.md +++ b/specs/memkernel-0-10-decision-revalidation/plan.md @@ -27,10 +27,11 @@ origin: `storage/chroma.py`). 2. **Revalidate**: extend `revalidate()` to live `decision` memories with a `source` (FR-002); `flagged` items gain the memory's type, so the startup list can name them (D1). -3. **Recall**: `_filter_live` lets flagged decisions through (FR-003); `build_artifact_refs` fills `needs_review` - and `review_reason` (FR-004). +3. **Recall**: `_filter_live`, and `_newest_checkpoints()` through `checkpoints_newest_first(include_flagged_decisions=True)`, + let flagged decisions through; the default stays unchanged for the lifecycle (FR-003); + `build_artifact_refs()` and `_artifact_ref()` fill `needs_review` and `review_reason` (FR-004). 4. **Lifecycle**: the "Needs review" list per D1. -5. **Tests**: the #57 probe as a unit test (SC-1), the legacy and clearing cases (SC-2), the replay re-run (SC-3), +5. **Tests**: the #57 probe as a unit test (SC-1), the legacy and clearing cases (SC-2), the dedup cases (SC-3), the replay re-run (SC-3b), the newest-checkpoint path (SC-3c), a 0.9.x store fixture (SC-4). 6. **Docs**: README and CHANGELOG. diff --git a/specs/memkernel-0-10-decision-revalidation/spec.md b/specs/memkernel-0-10-decision-revalidation/spec.md index b3c370a..40ab5e9 100644 --- a/specs/memkernel-0-10-decision-revalidation/spec.md +++ b/specs/memkernel-0-10-decision-revalidation/spec.md @@ -11,7 +11,11 @@ Status: approved by the owner, 2026-11-14 (D1–D4 with the dedup and hint clari - **That comparison works for `code` only because its content is the file.** A `decision`'s content is its record text, so it has no stored hash of the file it cites; one has to be recorded at retain. - **`recall` hides every flagged memory, whatever its type,** unless `include_needs_review=True` - (`_filter_live`, the owner check for document parts too). + (`_filter_live`, the owner check for document parts too). The `order="newest"` path (with `checkpoint_only=True`) + bypasses `_filter_live`: `_newest_checkpoints()` takes `checkpoints_newest_first()`, which drops every flagged + record unconditionally, and builds its results with `_artifact_ref()`, not `build_artifact_refs()`. + `checkpoints_newest_first()` is shared: the lifecycle uses it to choose the latest checkpoint and in compaction + recovery (`lifecycle.py`, `_latest_checkpoint_memory`, `_compact_recovery`). - **`recall` results do not carry the flag:** `ArtifactRef` has `ref_id`, `preview`, `score`, `token_count`, `type`, `timestamp`, `tier`, `importance` (`core/models.py`; built in `retrieval/search.py`, `build_artifact_refs`). `get` returns the full `Memory`, which has `needs_review` and `review_reason`. @@ -43,15 +47,23 @@ Status: approved by the owner, 2026-11-14 (D1–D4 with the dedup and hint clari - **FR-002 Revalidate decisions.** `revalidate()` branches on type: `code` is unchanged; live `decision` memories with a `source` are checked against `source_hash`: missing file → `missing`; a different hash → `changed`; a match clears the flag. A decision without a `source_hash` (retained before this change, or whose file was unreadable - then) is flagged only when the file is missing, and a present file clears a `missing` flag. Paths outside the + then) is flagged only when the file is missing; a present file clears only a `missing` flag, and any other flag + is kept and counted `unknown`, since nothing can disprove it. Paths outside the project root or unreadable files count as `unknown`, as for `code`. A superseded or withdrawn decision is not checked: `recall` already hides it. Each `flagged` item gains a `type` key (an additive change to the report). - **FR-003 Flagged decisions are returned.** `recall` returns flagged `decision` memories, with the flag in the - result (FR-004); it keeps hiding other flagged memories unless `include_needs_review=True`. + result (FR-004), on both paths: relevance (`_filter_live`) and `order="newest"`. For the newest path, + `checkpoints_newest_first()` gains a keyword, `include_flagged_decisions: bool = False`, which only + `_newest_checkpoints()` sets; every other caller, the lifecycle's latest-checkpoint and compaction-recovery + choices included, keeps today's behaviour and never sees a flagged record. `recall` keeps hiding other flagged + memories on both paths. `include_needs_review=True` shows them on the relevance path; + the newest path ignores it, as it does today (`_newest_checkpoints` does not receive it). - **FR-004 The mark is additive.** `ArtifactRef` gains `needs_review: bool = False` and `review_reason: str = ""`, - filled for every result; the preview and existing fields do not change. + filled for every result by both builders (`build_artifact_refs()` and `_artifact_ref()`); the preview and existing + fields do not change. - **FR-005 Startup list (D1).** Flagged decisions appear in the session-start "Needs review" list, each line naming - its type; the hint becomes type-aware: re-check a flagged decision's evidence and retain a corrected one with + its type; the list shows this pass's flags and every other memory still flagged in the store (one whose file + could not be read this time keeps its flag); the hint becomes type-aware: re-check a flagged decision's evidence and retain a corrected one with `supersedes`, or retain a flagged code file again to refresh it. - **FR-006 Docs.** README (revalidation section, `recall` description), the `recall` tool's docstring (the new fields, and `include_needs_review` no longer needed for decisions), CHANGELOG under `[Unreleased]`. @@ -79,6 +91,10 @@ Status: approved by the owner, 2026-11-14 (D1–D4 with the dedup and hint clari record with its original `source` and `source_hash`; retained again from the same `source`, the record is unchanged; a dedup hit on a record retained before this change leaves it without a `source_hash`. - **SC-3b** #57's replay still finds every seed record. +- **SC-3c** `recall(order="newest", checkpoint_only=True)` returns a flagged decision checkpoint with + `needs_review: true` and its `review_reason`, and still leaves out a flagged non-decision checkpoint; and the + lifecycle's checkpoint selection (`checkpoints_newest_first()` with its default, the latest checkpoint at session + start and in compaction recovery) still excludes every flagged record, the decision included. - **SC-4** A store written by 0.9.x, holding a decision with a `source` and no `source_hash`, opens, and that decision revalidates per FR-002 (flagged only when its file is missing). Fast suite, ruff, mypy strict, coverage ≥ 80%; MCP tool set unchanged. @@ -87,6 +103,8 @@ Status: approved by the owner, 2026-11-14 (D1–D4 with the dedup and hint clari - **D1 Startup list.** Flagged decisions appear in the session-start "Needs review" list, each line naming it a decision, with a type-aware hint (FR-005). The list keeps its 10-line cap. +- **A1 (the owner's, 2026-11-15, review of #127).** The hook blocks' context lines (session start, compaction + recovery, `on_post_compact`) mark a flagged memory in its label, e.g. `[decision, needs review: changed]`. - **D2 The new result fields.** `needs_review` and `review_reason` on every `recall` result, for all types (a flagged `code` memory shows them when `include_needs_review=True`). - **D3 Which files get a hash.** Only a `source` under the project root that can be read, as `code` diff --git a/specs/memkernel-0-10-decision-revalidation/tasks.md b/specs/memkernel-0-10-decision-revalidation/tasks.md index 0887f53..a3d552e 100644 --- a/specs/memkernel-0-10-decision-revalidation/tasks.md +++ b/specs/memkernel-0-10-decision-revalidation/tasks.md @@ -1,16 +1,17 @@ # Tasks: memkernel-0-10-decision-revalidation ## US1: hash and revalidate -- [ ] `source_hash` key, recorded at retain for decisions (FR-001, D3); loads empty for old records -- [ ] `revalidate()` checks decisions (FR-002); flagged items carry the type -- [ ] Unit tests for SC-1 (probe), SC-2 (legacy, clearing, unknown) and SC-3 (cross-source dedup, same-source dedup, +- [x] `source_hash` key, recorded at retain for decisions (FR-001, D3); loads empty for old records +- [x] `revalidate()` checks decisions (FR-002); flagged items carry the type +- [x] Unit tests for SC-1 (probe), SC-2 (legacy, clearing, unknown) and SC-3 (cross-source dedup, same-source dedup, a legacy hashless dedup hit) ## US2: recall and startup -- [ ] `_filter_live` returns flagged decisions (FR-003); `ArtifactRef` fields (FR-004, D2) -- [ ] Startup "Needs review" list per D1, with a type-aware hint (FR-005) -- [ ] Tests: recall marks, code still hidden, the startup list; a 0.9.x store fixture (SC-4) +- [x] `_filter_live` and `_newest_checkpoints()` (via `include_flagged_decisions`, default off) return flagged decisions (FR-003); `ArtifactRef` fields from both + builders (FR-004, D2); a test for the newest-checkpoint path (SC-3c) +- [x] Startup "Needs review" list per D1, with a type-aware hint (FR-005) +- [x] Tests: recall marks, code still hidden, the startup list; a 0.9.x store fixture (SC-4) ## US3: docs and checks -- [ ] README, CHANGELOG (FR-006) -- [ ] #57 replay re-run (SC-3); fast suite, ruff, mypy strict, coverage +- [x] README, CHANGELOG (FR-006) +- [x] #57 replay re-run (SC-3b); fast suite, ruff, mypy strict, coverage diff --git a/src/memkernel/api/routes/admin.py b/src/memkernel/api/routes/admin.py index f110137..207e063 100644 --- a/src/memkernel/api/routes/admin.py +++ b/src/memkernel/api/routes/admin.py @@ -54,6 +54,6 @@ async def collections(request: Request) -> list[dict[str, Any]]: @router.post("/revalidate") async def revalidate(request: Request) -> dict[str, Any]: - """Check every code memory against its source file; flag changed or missing ones (needs_review).""" + """Check every code memory and every decision with a source against its file; flag changed or missing ones.""" svc = _svc(request) return svc.revalidate() diff --git a/src/memkernel/core/models.py b/src/memkernel/core/models.py index 0959b30..96258a0 100644 --- a/src/memkernel/core/models.py +++ b/src/memkernel/core/models.py @@ -115,6 +115,9 @@ class MemoryType(StrEnum): REVIEW_REASON_KEY = "review_reason" REVIEW_REASON_CHANGED = "changed" REVIEW_REASON_MISSING = "missing" +# The content hash of a decision's ``source`` file when the decision was created (memkernel-0-10-decision-revalidation +# FR-001); absent, so empty, on older records and on decisions whose source was not a readable project file. +SOURCE_HASH_KEY = "source_hash" # Wiki-import tags (memkernel-0-6, memkernel-0-7-wiki-scope): what the wiki import writes on a memory. The two # identity tags name the wiki a memory belongs to; only the import sets them (S8). WIKI_TAG = "wiki" @@ -192,6 +195,7 @@ class Memory(BaseModel): parent_ref: str | None = None needs_review: bool = False review_reason: str = "" + source_hash: str = "" # decisions only (memkernel-0-10-decision-revalidation FR-001) # 0.7: withdrawn without a replacement (memkernel-0-7 FR-001); absent, so live, in older stores. withdrawn_reason: str | None = None withdrawn_at: datetime | None = None @@ -279,6 +283,9 @@ class ArtifactRef(BaseModel): timestamp: datetime tier: MemoryTier = MemoryTier.LONG_TERM importance: float = 0.5 + # memkernel-0-10-decision-revalidation FR-004: a flagged decision is returned with its flag and reason. + needs_review: bool = False + review_reason: str = "" class SearchResult(BaseModel): diff --git a/src/memkernel/core/services.py b/src/memkernel/core/services.py index 8c5de9c..3c23e2a 100644 --- a/src/memkernel/core/services.py +++ b/src/memkernel/core/services.py @@ -36,6 +36,7 @@ REVIEW_REASON_CHANGED, REVIEW_REASON_KEY, REVIEW_REASON_MISSING, + SOURCE_HASH_KEY, SUPERSEDED_BY_KEY, WIKI_ID_TAG, WIKI_IDENTITY_TAGS, @@ -203,9 +204,16 @@ def _artifact_ref(memory: Memory, score: float, preview_length: int) -> Artifact timestamp=memory.timestamp, tier=memory.tier, importance=memory.importance, + needs_review=memory.needs_review, + review_reason=memory.review_reason, ) +def _exempt_from_review_hiding(memory: Memory) -> bool: + """A flagged decision is still returned, marked, so its evidence is re-checked (decision-revalidation FR-003).""" + return memory.type == MemoryType.DECISION + + class MemoryService: """Orchestrates retain, recall, get, and forget operations. @@ -753,8 +761,22 @@ def _new_metadata( if extra.document_id: metadata["document_id"] = extra.document_id metadata[DOCUMENT_PART_KEY] = False # a summary record, not a body/chunk part + if type == MemoryType.DECISION and source: + source_hash = self._source_file_hash(source) + if source_hash is not None: + metadata[SOURCE_HASH_KEY] = source_hash # new records only: a dedup hit keeps its own (FR-001) return metadata + def _source_file_hash(self, source: str) -> str | None: + """The content hash of ``source`` if it is a readable file under the project root, else None.""" + path = self._resolve_source(source) + if path is None or not path.is_file(): + return None + try: + return compute_content_hash(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError): + return None + def _write_record(self, ref_id: str, content: str, embedding: list[float], metadata: dict[str, Any]) -> None: """Authoritative store first; BM25 is a derived index whose failure is non-fatal.""" self._vector_store.upsert(ref_id=ref_id, content=content, embedding=embedding, metadata=metadata) @@ -883,7 +905,7 @@ def _filter_live( memory = memories.get(ref.ref_id) if memory is None or memory.retired(): continue - if memory.needs_review and not include_needs_review: + if memory.needs_review and not include_needs_review and not _exempt_from_review_hiding(memory): continue if memory.parent_ref: # A code chunk lives and dies with its owner: dropped when the @@ -977,7 +999,7 @@ def _newest_checkpoints( """``recall(order="newest", checkpoint_only=True)``: the newest live checkpoints, filtered like recall.""" limit = top_k if top_k is not None else self._settings.search_top_k picked: list[ArtifactRef] = [] - for candidate in self.checkpoints_newest_first(): + for candidate in self.checkpoints_newest_first(include_flagged_decisions=True): if len(picked) >= limit: break if (memory_type is not None and candidate.type != memory_type) or ( @@ -991,19 +1013,20 @@ def _newest_checkpoints( picked.append(_artifact_ref(memory, 1.0, self._settings.preview_length)) return picked - def checkpoints_newest_first(self) -> list[Memory]: + def checkpoints_newest_first(self, include_flagged_decisions: bool = False) -> list[Memory]: """Every live checkpoint record, newest first (ties by ``ref_id``), without content and without touching. Selected by metadata, so the newest is found however many older checkpoints a query would rank higher. Live as for :meth:`recall`, judged with this service's settings: not superseded, not flagged for review, not expired. Code-chunk and document-part records are left out: they are parts of a checkpoint, not one. - Read the chosen record with :meth:`get`. + Read the chosen record with :meth:`get`. ``include_flagged_decisions`` keeps flagged decisions; only + ``recall(order="newest")`` sets it, so the lifecycle's choice of the latest checkpoint is unchanged. """ live = [ m for m in self._vector_store.list_all({"checkpoint": True}, include_content=False) if not m.retired() - and not m.needs_review + and (not m.needs_review or (include_flagged_decisions and _exempt_from_review_hiding(m))) and m.parent_ref is None and not _is_document_part(m) and not memory_is_expired(m, self._settings) @@ -1358,14 +1381,16 @@ def _resolve_source(self, source: str) -> Path | None: return resolved if resolved.is_relative_to(root) else None def revalidate(self) -> dict[str, Any]: - """Compare every live canonical `code` memory with its source file; flag or clear ``needs_review``. + """Compare every live canonical `code` memory, and every live `decision` with a ``source``, with its file. Whole-file hashing: the file's content hash (the same one retain uses) against the stored ``content_hash``. A missing file flags ``missing``, a different hash flags ``changed``, a matching file clears a flag; owned chunk records follow their canonical. Paths outside the project root or unreadable count as ``unknown`` and are left untouched. Nothing else - is written. + is written. A decision compares against the ``source_hash`` recorded when it + was created; one without it is flagged only when the file is missing + (memkernel-0-10-decision-revalidation FR-002). Each flagged item names its type. """ report: dict[str, Any] = {"checked": 0, "changed": 0, "missing": 0, "cleared": 0, "unknown": 0, "flagged": []} records = self._vector_store.list_all({"type": MemoryType.CODE.value}, include_content=False) @@ -1387,16 +1412,45 @@ def revalidate(self) -> dict[str, Any]: report["unknown"] += 1 continue reason = REVIEW_REASON_CHANGED if compute_content_hash(text) != memory.content_hash else "" - if reason: - report[reason] += 1 - report["flagged"].append({"ref_id": memory.ref_id, "source": memory.source, "reason": reason}) - if not (memory.needs_review and memory.review_reason == reason): - self._set_review(memory.ref_id, True, reason) - elif memory.needs_review: - report["cleared"] += 1 - self._set_review(memory.ref_id, False, "") + self._record_review(report, memory, reason) + for memory in self._vector_store.list_all({"type": MemoryType.DECISION.value}, include_content=False): + if memory.retired() or not memory.source: + continue + report["checked"] += 1 + path = self._resolve_source(memory.source) + if path is None: + report["unknown"] += 1 + continue + if not path.is_file(): + reason = REVIEW_REASON_MISSING + elif memory.source_hash: + try: + text = path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + report["unknown"] += 1 + continue + reason = REVIEW_REASON_CHANGED if compute_content_hash(text) != memory.source_hash else "" + elif memory.needs_review and memory.review_reason != REVIEW_REASON_MISSING: + report["unknown"] += 1 # no hash: a present file disproves only a missing flag, not this one + continue + else: + reason = "" # no hash from before: only a missing file can be told + self._record_review(report, memory, reason) return report + def _record_review(self, report: dict[str, Any], memory: Memory, reason: str) -> None: + """Flag ``memory`` for ``reason`` (or clear its flag when ``reason`` is empty) and count it in ``report``.""" + if reason: + report[reason] += 1 + report["flagged"].append( + {"ref_id": memory.ref_id, "source": memory.source, "reason": reason, "type": memory.type.value} + ) + if not (memory.needs_review and memory.review_reason == reason): + self._set_review(memory.ref_id, True, reason) + elif memory.needs_review: + report["cleared"] += 1 + self._set_review(memory.ref_id, False, "") + def _set_review(self, ref_id: str, flag: bool, reason: str) -> None: """Write the review flag on a canonical and on its owned chunk records.""" update = {NEEDS_REVIEW_KEY: flag, REVIEW_REASON_KEY: reason} diff --git a/src/memkernel/lifecycle.py b/src/memkernel/lifecycle.py index 6fe6442..18cdc96 100644 --- a/src/memkernel/lifecycle.py +++ b/src/memkernel/lifecycle.py @@ -104,7 +104,10 @@ _CHECKPOINT_PREFIX = "SESSION CHECKPOINT — " _PROMOTE_HINT = "Call promote(ref_id, type, content) for anything that should outlive this session." -_REVIEW_HINT = "These code memories no longer match their source; retain the file again as code to refresh them." +_REVIEW_HINT = ( + "These memories no longer match their source file. A decision: re-check its evidence before relying on it, and " + "retain a corrected one with supersedes. Code: retain the file again as code to refresh it." +) class MemoryLifecycle: @@ -147,7 +150,7 @@ def on_session_start(self, source: str | None = None, session_id: str | None = N *(self._memory_lines(context, CONTEXT_BUDGET - len("\n".join(debt))) or ["No prior memories found."]), ] lines.extend(_candidates_block(report["candidates"])) - lines.extend(_needs_review_block(report.get("revalidated", {}).get("flagged", []))) + lines.extend(_needs_review_block(self._flagged(report.get("revalidated", {}).get("flagged", [])))) lines.extend(_store_health_block(report.get("health", {}))) wiki_index = Path(self._settings.wiki_dir) / "index.md" if self._settings.wiki_dir else None if wiki_index is not None and wiki_index.is_file(): @@ -300,6 +303,17 @@ def checkpointed(window: SessionWindow) -> bool: return session_spool.drain(self._settings, session_id, checkpointed) + def _flagged(self, found: list[dict[str, Any]]) -> list[dict[str, Any]]: + """This pass's flagged items, then every other memory still flagged in the store (one whose file could not be + read this time keeps its flag): the review list shows durable flags, not only those found again (FR-005).""" + listed = {item["ref_id"] for item in found} + durable = [ + {"ref_id": m.ref_id, "source": m.source, "reason": m.review_reason, "type": m.type.value} + for m in self._service.list_memories(tier=MemoryTier.LONG_TERM) + if m.needs_review and m.parent_ref is None and m.ref_id not in listed + ] + return [*found, *sorted(durable, key=lambda item: item["ref_id"])] + def _startup_context(self) -> list[Memory]: """Live long-term memories without a query: by type (CONTEXT_TYPE_ORDER), importance, recency (H1).""" rank = {t: i for i, t in enumerate(CONTEXT_TYPE_ORDER)} @@ -326,7 +340,8 @@ def _checkpoint_lines(self, checkpoint: Memory) -> list[str]: def _memory_lines(self, memories: list[Memory], budget: int = CONTEXT_BUDGET) -> list[str]: preview = self._service.settings.preview_length lines = [ - f"- [{m.type}] {stored(' '.join(m.content.split())[:preview], STORED_KIND_CONTEXT)} ({m.ref_id})" + f"- [{_label(m.type, m.needs_review, m.review_reason)}] " + f"{stored(' '.join(m.content.split())[:preview], STORED_KIND_CONTEXT)} ({m.ref_id})" for m in memories ] return _fit(lines, budget) @@ -344,8 +359,18 @@ def _age(delta: timedelta) -> str: return f"{value} {unit}{'' if value == 1 else 's'}" +def _label(memory_type: MemoryType, needs_review: bool, reason: str) -> str: + """A context line's type label; a flagged memory says so (decision-revalidation A1), e.g. + ``decision, needs review: changed``.""" + return f"{memory_type}, needs review: {reason or 'flagged'}" if needs_review else f"{memory_type}" + + def _context_lines(refs: list[ArtifactRef]) -> list[str]: - return _fit([f"- [{r.type}] {stored(r.preview, STORED_KIND_CONTEXT)} ({r.ref_id})" for r in refs], CONTEXT_BUDGET) + lines = [ + f"- [{_label(r.type, r.needs_review, r.review_reason)}] {stored(r.preview, STORED_KIND_CONTEXT)} ({r.ref_id})" + for r in refs + ] + return _fit(lines, CONTEXT_BUDGET) def _previous_sessions_block(drained: DrainResult) -> list[str]: @@ -459,7 +484,10 @@ def _needs_review_block(flagged: list[dict[str, Any]]) -> list[str]: if not flagged: return [] shown = flagged[:NEEDS_REVIEW_MAX_LINES] - lines = [f"- {stored(f['source'], STORED_KIND_REVIEW)} — {f['reason']} — {f['ref_id']}" for f in shown] + lines = [ + f"- [{f.get('type', 'code')}] {stored(f['source'], STORED_KIND_REVIEW)} — {f['reason']} — {f['ref_id']}" + for f in shown + ] if len(flagged) > len(shown): lines.append(f"… and {len(flagged) - len(shown)} more (consolidate(revalidate=true) lists all)") return ["", HEADING_NEEDS_REVIEW, *_fit(lines, NEEDS_REVIEW_BUDGET), _REVIEW_HINT] diff --git a/src/memkernel/mcp/tools/memory.py b/src/memkernel/mcp/tools/memory.py index 494620d..d58259e 100644 --- a/src/memkernel/mcp/tools/memory.py +++ b/src/memkernel/mcp/tools/memory.py @@ -81,6 +81,8 @@ async def recall( tier: working | short_term | long_term to restrict the search to one tier. include_needs_review: also return code memories whose source file changed or vanished since they were retained (flagged by revalidation; hidden by default). + Flagged decisions are always returned. Each result has needs_review and review_reason; + re-check a flagged decision's evidence before relying on it. """ svc = _service(ctx) results = svc.recall( @@ -174,8 +176,8 @@ async def consolidate( often they were recalled). Call promote(ref_id, type, content) for the keepers. synthesize=true also asks the configured external reasoner to draft long-term statements under "suggested" (empty with the built-in local reasoner). - revalidate=true first checks every code memory against its source file and - flags changed or missing ones (report under "revalidated"). + revalidate=true first checks every code memory, and every decision with a source, + against its file and flags changed or missing ones (report under "revalidated"). """ svc = _service(ctx) return json.dumps( diff --git a/src/memkernel/retrieval/search.py b/src/memkernel/retrieval/search.py index 32be8ea..a4c3a30 100644 --- a/src/memkernel/retrieval/search.py +++ b/src/memkernel/retrieval/search.py @@ -259,6 +259,8 @@ def build_artifact_refs( timestamp=memory.timestamp, tier=memory.tier, importance=memory.importance, + needs_review=memory.needs_review, + review_reason=memory.review_reason, ) ) return refs diff --git a/src/memkernel/storage/chroma.py b/src/memkernel/storage/chroma.py index 3e270f6..821f135 100644 --- a/src/memkernel/storage/chroma.py +++ b/src/memkernel/storage/chroma.py @@ -23,6 +23,7 @@ NEEDS_REVIEW_KEY, PARENT_REF_KEY, REVIEW_REASON_KEY, + SOURCE_HASH_KEY, STORE_LOCK_NAMES, STORE_LOCK_TAGS, SUPERSEDED_BY_KEY, @@ -197,6 +198,7 @@ def _memory_from_chroma( parent_ref=str(meta[PARENT_REF_KEY]) if meta.get(PARENT_REF_KEY) else None, needs_review=bool(meta.get(NEEDS_REVIEW_KEY, False)), review_reason=str(meta.get(REVIEW_REASON_KEY) or ""), + source_hash=str(meta.get(SOURCE_HASH_KEY) or ""), withdrawn_reason=str(meta[WITHDRAWN_REASON_KEY]) if meta.get(WITHDRAWN_REASON_KEY) else None, withdrawn_at=datetime.fromisoformat(str(meta[WITHDRAWN_AT_KEY])) if meta.get(WITHDRAWN_AT_KEY) else None, ) diff --git a/tests/unit/test_decision_revalidation.py b/tests/unit/test_decision_revalidation.py new file mode 100644 index 0000000..3336418 --- /dev/null +++ b/tests/unit/test_decision_revalidation.py @@ -0,0 +1,268 @@ +# Copyright (c) 2026 EGOGE +# SPDX-License-Identifier: Apache-2.0 +"""Decisions that cite files are revalidated and returned flagged (memkernel-0-10-decision-revalidation, #123).""" + +from __future__ import annotations + +import uuid +from typing import TYPE_CHECKING, Any + +import chromadb +import pytest + +from memkernel.config import MemKernelSettings +from memkernel.core.models import SOURCE_HASH_KEY, MemoryType +from memkernel.factory import build_service +from memkernel.lifecycle import HEADING_NEEDS_REVIEW, MemoryLifecycle +from memkernel.memory.dedup import compute_content_hash +from tests.conftest import MockEmbedding + +if TYPE_CHECKING: + from pathlib import Path + +pytestmark = pytest.mark.unit + +V1 = "def redact_text(s):\n return s.replace('secret', '***')\n" +V2 = "def redact_text(s):\n return s\n" +DECISION = "decision: In the context of redaction, we chose redact_text over a new redactor, because one contract." + + +def _service(root: Path) -> tuple[Any, MemKernelSettings]: + settings = MemKernelSettings( + project_id=f"dr-{uuid.uuid4().hex[:8]}", chroma_persist_path="", project_root=str(root) + ) + return build_service(settings, embedding=MockEmbedding(), chroma_client=chromadb.EphemeralClient()), settings + + +def _write(root: Path, rel: str, text: str) -> Path: + path = root / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path + + +def _recalled(svc: Any, ref: str, **kwargs: Any) -> Any: + return next((r for r in svc.recall("redaction redact_text contract", top_k=20, **kwargs) if r.ref_id == ref), None) + + +# ── SC-1 ───────────────────────────────────────────────────────────────────── + + +def test_the_57_probe_flags_the_decision_and_recall_still_returns_it(tmp_path: Path) -> None: + svc, _ = _service(tmp_path) + path = _write(tmp_path, "src/redact.py", V1) + decision = svc.retain(DECISION, MemoryType.DECISION, source="src/redact.py") + code = svc.retain(V1, MemoryType.CODE, source="src/redact.py") + assert svc.get(decision).source_hash == compute_content_hash(V1) + unflagged = _recalled(svc, decision) + assert unflagged is not None and unflagged.needs_review is False and unflagged.review_reason == "" + + path.write_text(V2, encoding="utf-8") + report = svc.revalidate() + assert {(f["ref_id"], f["reason"], f["type"]) for f in report["flagged"]} == { + (decision, "changed", "decision"), + (code, "changed", "code"), + } + hit = _recalled(svc, decision) + assert hit is not None and hit.needs_review is True and hit.review_reason == "changed" + assert all(r.ref_id != code for r in svc.recall("redact_text secret", top_k=20)) # code stays hidden + + path.unlink() + svc.revalidate() + hit = _recalled(svc, decision) + assert hit is not None and hit.review_reason == "missing" + + +# ── SC-2 ───────────────────────────────────────────────────────────────────── + + +def test_restoring_the_file_clears_the_flag(tmp_path: Path) -> None: + svc, _ = _service(tmp_path) + path = _write(tmp_path, "src/redact.py", V1) + decision = svc.retain(DECISION, MemoryType.DECISION, source="src/redact.py") + path.write_text(V2, encoding="utf-8") + svc.revalidate() + path.write_text(V1, encoding="utf-8") + report = svc.revalidate() + assert report["cleared"] == 1 and svc.get(decision).needs_review is False + + +def _raw_metadata(svc: Any, ref: str) -> dict[str, Any]: + raw = svc._vector_store._collection.get(ids=[ref], include=["metadatas"]) + return dict(raw["metadatas"][0]) + + +def test_a_pre_0_10_decision_without_the_key_is_flagged_only_when_its_file_is_missing(tmp_path: Path) -> None: + """SC-4: a decision whose metadata has no source_hash key at all, as a 0.9.x store holds it.""" + svc, _ = _service(tmp_path) + decision = svc.retain(DECISION, MemoryType.DECISION, source="src/redact.py") # no file yet: no key written + assert SOURCE_HASH_KEY not in _raw_metadata(svc, decision) and svc.get(decision).source_hash == "" + path = _write(tmp_path, "src/redact.py", V1) + assert svc.revalidate()["flagged"] == [] + path.write_text(V2, encoding="utf-8") + assert svc.revalidate()["flagged"] == [] # a change cannot be told without a hash + path.unlink() + assert [f["reason"] for f in svc.revalidate()["flagged"]] == ["missing"] + _write(tmp_path, "src/redact.py", V2) + assert svc.revalidate()["cleared"] == 1 + assert SOURCE_HASH_KEY not in _raw_metadata(svc, decision) # never hashed later + + +def test_an_empty_source_hash_reads_as_hashless(tmp_path: Path) -> None: + svc, _ = _service(tmp_path) + path = _write(tmp_path, "src/redact.py", V1) + decision = svc.retain(DECISION, MemoryType.DECISION, source="src/redact.py") + svc._vector_store.update_metadata(decision, {SOURCE_HASH_KEY: ""}) + path.write_text(V2, encoding="utf-8") + assert svc.get(decision).source_hash == "" and svc.revalidate()["flagged"] == [] + + +def test_a_hashless_decision_keeps_a_flag_its_present_file_cannot_disprove(tmp_path: Path) -> None: + svc, _ = _service(tmp_path) + decision = svc.retain(DECISION, MemoryType.DECISION, source="src/redact.py") # hashless + _write(tmp_path, "src/redact.py", V1) + svc._set_review(decision, True, "changed") # a flag from an earlier check + report = svc.revalidate() + assert report["cleared"] == 0 and report["unknown"] == 1 + assert svc.get(decision).needs_review is True and svc.get(decision).review_reason == "changed" + + +@pytest.mark.parametrize("source", ["../outside.py", "src/missing-at-retain.py"], ids=["outside-root", "no-file"]) +def test_a_source_that_cannot_be_hashed_gets_no_hash(tmp_path: Path, source: str) -> None: + root = tmp_path / "project" + root.mkdir() + (tmp_path / "outside.py").write_text(V1, encoding="utf-8") + svc, _ = _service(root) + decision = svc.retain(DECISION, MemoryType.DECISION, source=source) + assert svc.get(decision).source_hash == "" + report = svc.revalidate() + if source.startswith(".."): + assert report["unknown"] == 1 and report["flagged"] == [] + else: + assert [f["reason"] for f in report["flagged"]] == ["missing"] + + +def test_a_decision_without_a_source_is_not_checked(tmp_path: Path) -> None: + svc, _ = _service(tmp_path) + svc.retain(DECISION, MemoryType.DECISION) + assert svc.revalidate()["checked"] == 0 + + +# ── SC-3 ───────────────────────────────────────────────────────────────────── + + +def test_a_dedup_hit_from_another_source_keeps_the_original_source_and_hash(tmp_path: Path) -> None: + svc, _ = _service(tmp_path) + _write(tmp_path, "src/a.py", V1) + _write(tmp_path, "src/b.py", V2) + first = svc.retain(DECISION, MemoryType.DECISION, source="src/a.py") + again = svc.retain(DECISION, MemoryType.DECISION, source="src/b.py") + memory = svc.get(again) + assert again == first and memory.source == "src/a.py" and memory.source_hash == compute_content_hash(V1) + + +def test_a_dedup_hit_from_the_same_source_leaves_the_record_unchanged(tmp_path: Path) -> None: + svc, _ = _service(tmp_path) + path = _write(tmp_path, "src/a.py", V1) + first = svc.retain(DECISION, MemoryType.DECISION, source="src/a.py") + path.write_text(V2, encoding="utf-8") # the file changed since; a dedup hit must not re-hash it + again = svc.retain(DECISION, MemoryType.DECISION, source="src/a.py") + assert again == first and svc.get(first).source_hash == compute_content_hash(V1) + + +def test_a_dedup_hit_on_a_hashless_record_leaves_it_hashless(tmp_path: Path) -> None: + svc, _ = _service(tmp_path) + _write(tmp_path, "src/a.py", V1) + first = svc.retain(DECISION, MemoryType.DECISION, source="src/a.py") + svc._vector_store.update_metadata(first, {SOURCE_HASH_KEY: ""}) + again = svc.retain(DECISION, MemoryType.DECISION, source="src/a.py") + assert again == first and svc.get(first).source_hash == "" + + +# ── SC-3c ──────────────────────────────────────────────────────────────────── + + +def test_newest_recall_returns_a_flagged_decision_checkpoint_and_the_lifecycle_still_skips_it(tmp_path: Path) -> None: + svc, settings = _service(tmp_path) + path = _write(tmp_path, "src/redact.py", V1) + decision = svc.retain(DECISION, MemoryType.DECISION, source="src/redact.py", checkpoint=True) + code = svc.retain(V1, MemoryType.CODE, source="src/redact.py", checkpoint=True) + path.write_text(V2, encoding="utf-8") + svc.revalidate() + + newest = svc.recall("session checkpoint", checkpoint_only=True, order="newest", top_k=5) + assert [r.ref_id for r in newest] == [decision] + assert newest[0].needs_review is True and newest[0].review_reason == "changed" + assert code not in {r.ref_id for r in newest} + + assert svc.checkpoints_newest_first() == [] # the default the lifecycle uses: no flagged record + assert MemoryLifecycle(svc, settings)._latest_checkpoint_memory() is None + + +# ── D1: the session-start list ─────────────────────────────────────────────── + + +def test_session_start_lists_a_flagged_decision_with_its_type(tmp_path: Path) -> None: + svc, settings = _service(tmp_path) + path = _write(tmp_path, "src/redact.py", V1) + decision = svc.retain(DECISION, MemoryType.DECISION, source="src/redact.py") + path.write_text(V2, encoding="utf-8") + text = MemoryLifecycle(svc, settings).on_session_start("startup") + assert f'{HEADING_NEEDS_REVIEW}\n- [decision] src/redact.py' in text + assert f"— changed — {decision}" in text and "A decision: re-check its evidence" in text + + +# ── A1: the hook blocks' context lines mark flagged items ──────────────────── + + +FLAGGED_LABEL = "[decision, needs review: changed]" + + +def _flagged_decision(tmp_path: Path) -> tuple[Any, MemKernelSettings, str]: + svc, settings = _service(tmp_path) + path = _write(tmp_path, "src/redact.py", V1) + decision = svc.retain(DECISION, MemoryType.DECISION, source="src/redact.py") + path.write_text(V2, encoding="utf-8") + svc.revalidate() + return svc, settings, decision + + +def _context_line(text: str, ref: str) -> str: + return next(line for line in text.splitlines() if line.startswith("- [") and line.endswith(f"({ref})")) + + +def test_the_startup_block_marks_a_flagged_decision(tmp_path: Path) -> None: + svc, settings, decision = _flagged_decision(tmp_path) + text = MemoryLifecycle(svc, settings).on_session_start("startup") + assert _context_line(text, decision).startswith(f"- {FLAGGED_LABEL} ") + + +def test_the_compaction_blocks_mark_a_flagged_decision(tmp_path: Path) -> None: + svc, settings, decision = _flagged_decision(tmp_path) + svc.retain("SESSION CHECKPOINT\nCurrent: redaction redact_text contract.", MemoryType.EPISODE, checkpoint=True) + lifecycle = MemoryLifecycle(svc, settings) + recovery = lifecycle.on_session_start("compact") + assert _context_line(recovery, decision).startswith(f"- {FLAGGED_LABEL} ") + post = lifecycle.on_post_compact() + assert _context_line(post, decision).startswith(f"- {FLAGGED_LABEL} ") + + +def test_an_unflagged_decision_keeps_the_plain_label(tmp_path: Path) -> None: + svc, settings = _service(tmp_path) + _write(tmp_path, "src/redact.py", V1) + decision = svc.retain(DECISION, MemoryType.DECISION, source="src/redact.py") + text = MemoryLifecycle(svc, settings).on_session_start("startup") + assert _context_line(text, decision).startswith("- [decision] ") + + +def test_session_start_lists_a_flag_whose_file_could_not_be_read_this_time(tmp_path: Path) -> None: + svc, settings, decision = _flagged_decision(tmp_path) + path = tmp_path / "src" / "redact.py" + path.chmod(0) # unreadable now: this pass reports unknown and keeps the flag + try: + report = svc.revalidate() + assert report["unknown"] == 1 and report["flagged"] == [] + text = MemoryLifecycle(svc, settings).on_session_start("startup") + finally: + path.chmod(0o644) + assert HEADING_NEEDS_REVIEW in text and f"— changed — {decision}" in text diff --git a/tests/unit/test_revalidation.py b/tests/unit/test_revalidation.py index 10ea6a8..be29ba7 100644 --- a/tests/unit/test_revalidation.py +++ b/tests/unit/test_revalidation.py @@ -84,7 +84,7 @@ def test_changed_file_flags_canonical_and_owned_chunks(tmp_path: Path) -> None: path.write_text(V2, encoding="utf-8") report = svc.revalidate() assert (report["checked"], report["changed"]) == (1, 1) - assert report["flagged"] == [{"ref_id": ref, "source": "src/app.py", "reason": "changed"}] + assert report["flagged"] == [{"ref_id": ref, "source": "src/app.py", "reason": "changed", "type": "code"}] memory = svc.get(ref, touch=False) assert memory is not None and memory.needs_review and memory.review_reason == "changed" chunks = store.list_all({"parent_ref": ref}) @@ -149,7 +149,7 @@ def test_absolute_source_inside_the_root_is_allowed(tmp_path: Path) -> None: path = _write(tmp_path, "src/app.py", V1) ref = svc.retain(V1, MemoryType.CODE, source=str(path)) path.write_text(V2, encoding="utf-8") - assert svc.revalidate()["flagged"] == [{"ref_id": ref, "source": str(path), "reason": "changed"}] + assert svc.revalidate()["flagged"] == [{"ref_id": ref, "source": str(path), "reason": "changed", "type": "code"}] def test_unreadable_source_is_unknown(tmp_path: Path) -> None: @@ -202,7 +202,9 @@ def test_consolidate_revalidate_flag(tmp_path: Path) -> None: path.write_text(V2, encoding="utf-8") assert "revalidated" not in svc.consolidate() report = svc.consolidate(revalidate=True) - assert report["revalidated"]["flagged"] == [{"ref_id": ref, "source": "src/app.py", "reason": "changed"}] + assert report["revalidated"]["flagged"] == [ + {"ref_id": ref, "source": "src/app.py", "reason": "changed", "type": "code"} + ] assert report["purged"] == 0 and report["candidates"] == [] @@ -217,7 +219,8 @@ def test_session_start_lists_needs_review_only_when_flagged(tmp_path: Path) -> N path.write_text(V2, encoding="utf-8") text = lifecycle.on_session_start() assert ( - f'{HEADING_NEEDS_REVIEW}\n- src/app.py — changed — {ref}\n' in text + f'{HEADING_NEEDS_REVIEW}\n- [code] src/app.py — changed — {ref}\n' + in text ) assert "retain the file again as code" in text # the 0.3 headings are untouched